@agentxjs/runtime 1.0.2 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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.js
CHANGED
|
@@ -1,176 +1,6 @@
|
|
|
1
1
|
// src/internal/SystemBusImpl.ts
|
|
2
2
|
import { Subject } from "rxjs";
|
|
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
|
|
3
|
+
import { createLogger } from "@agentxjs/common";
|
|
174
4
|
var logger = createLogger("runtime/SystemBusImpl");
|
|
175
5
|
var SystemBusImpl = class {
|
|
176
6
|
subject = new Subject();
|
|
@@ -329,7 +159,8 @@ var SystemBusImpl = class {
|
|
|
329
159
|
};
|
|
330
160
|
|
|
331
161
|
// src/internal/BusDriver.ts
|
|
332
|
-
|
|
162
|
+
import { createLogger as createLogger2 } from "@agentxjs/common";
|
|
163
|
+
var logger2 = createLogger2("runtime/BusDriver");
|
|
333
164
|
var BusDriver = class {
|
|
334
165
|
name = "BusDriver";
|
|
335
166
|
description = "Driver that listens to SystemBus for DriveableEvents";
|
|
@@ -514,7 +345,8 @@ var BusDriver = class {
|
|
|
514
345
|
};
|
|
515
346
|
|
|
516
347
|
// src/internal/AgentInteractor.ts
|
|
517
|
-
|
|
348
|
+
import { createLogger as createLogger3 } from "@agentxjs/common";
|
|
349
|
+
var logger3 = createLogger3("runtime/AgentInteractor");
|
|
518
350
|
var AgentInteractor = class {
|
|
519
351
|
producer;
|
|
520
352
|
session;
|
|
@@ -605,1006 +437,13 @@ var AgentInteractor = class {
|
|
|
605
437
|
}
|
|
606
438
|
};
|
|
607
439
|
|
|
608
|
-
//
|
|
609
|
-
|
|
610
|
-
|
|
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
|
-
}
|
|
440
|
+
// src/internal/RuntimeAgent.ts
|
|
441
|
+
import { createAgent } from "@agentxjs/agent";
|
|
442
|
+
import { createLogger as createLogger7 } from "@agentxjs/common";
|
|
1605
443
|
|
|
1606
444
|
// src/environment/ClaudeReceptor.ts
|
|
1607
|
-
|
|
445
|
+
import { createLogger as createLogger4 } from "@agentxjs/common";
|
|
446
|
+
var logger4 = createLogger4("ecosystem/ClaudeReceptor");
|
|
1608
447
|
var ClaudeReceptor = class {
|
|
1609
448
|
producer = null;
|
|
1610
449
|
currentMeta = null;
|
|
@@ -1622,7 +461,7 @@ var ClaudeReceptor = class {
|
|
|
1622
461
|
*/
|
|
1623
462
|
connect(producer) {
|
|
1624
463
|
this.producer = producer;
|
|
1625
|
-
|
|
464
|
+
logger4.debug("ClaudeReceptor connected to SystemBusProducer");
|
|
1626
465
|
}
|
|
1627
466
|
/**
|
|
1628
467
|
* Feed SDK message to receptor with correlation metadata
|
|
@@ -1740,7 +579,7 @@ var ClaudeReceptor = class {
|
|
|
1740
579
|
case "content_block_start": {
|
|
1741
580
|
const contentBlock = event.content_block;
|
|
1742
581
|
this.blockContext.currentBlockIndex = event.index;
|
|
1743
|
-
|
|
582
|
+
logger4.debug("content_block_start received", { contentBlock, index: event.index });
|
|
1744
583
|
if (contentBlock.type === "text") {
|
|
1745
584
|
this.blockContext.currentBlockType = "text";
|
|
1746
585
|
this.emitToBus({
|
|
@@ -1877,9 +716,11 @@ var ClaudeReceptor = class {
|
|
|
1877
716
|
// src/environment/ClaudeEffector.ts
|
|
1878
717
|
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
1879
718
|
import { Subject as Subject2 } from "rxjs";
|
|
719
|
+
import { createLogger as createLogger6 } from "@agentxjs/common";
|
|
1880
720
|
|
|
1881
721
|
// src/environment/buildOptions.ts
|
|
1882
|
-
|
|
722
|
+
import { createLogger as createLogger5 } from "@agentxjs/common";
|
|
723
|
+
var logger5 = createLogger5("environment/buildOptions");
|
|
1883
724
|
function buildOptions(context, abortController) {
|
|
1884
725
|
const options = {
|
|
1885
726
|
abortController,
|
|
@@ -1904,7 +745,7 @@ function buildOptions(context, abortController) {
|
|
|
1904
745
|
env.ANTHROPIC_API_KEY = context.apiKey;
|
|
1905
746
|
}
|
|
1906
747
|
options.env = env;
|
|
1907
|
-
|
|
748
|
+
logger5.info("buildOptions called", {
|
|
1908
749
|
hasPath: !!env.PATH,
|
|
1909
750
|
pathLength: env.PATH?.length,
|
|
1910
751
|
hasApiKey: !!env.ANTHROPIC_API_KEY,
|
|
@@ -1915,7 +756,7 @@ function buildOptions(context, abortController) {
|
|
|
1915
756
|
cwd: context.cwd
|
|
1916
757
|
});
|
|
1917
758
|
options.stderr = (data) => {
|
|
1918
|
-
|
|
759
|
+
logger5.info("SDK stderr", { data: data.trim() });
|
|
1919
760
|
};
|
|
1920
761
|
if (context.model) options.model = context.model;
|
|
1921
762
|
if (context.systemPrompt) options.systemPrompt = context.systemPrompt;
|
|
@@ -2018,7 +859,7 @@ async function* observableToAsyncIterable(observable) {
|
|
|
2018
859
|
}
|
|
2019
860
|
|
|
2020
861
|
// src/environment/ClaudeEffector.ts
|
|
2021
|
-
var
|
|
862
|
+
var logger6 = createLogger6("ecosystem/ClaudeEffector");
|
|
2022
863
|
var DEFAULT_TIMEOUT = 3e4;
|
|
2023
864
|
var ClaudeEffector = class {
|
|
2024
865
|
config;
|
|
@@ -2037,12 +878,12 @@ var ClaudeEffector = class {
|
|
|
2037
878
|
* Connect to SystemBus consumer to subscribe to events
|
|
2038
879
|
*/
|
|
2039
880
|
connect(consumer) {
|
|
2040
|
-
|
|
881
|
+
logger6.debug("ClaudeEffector connected to SystemBusConsumer", {
|
|
2041
882
|
agentId: this.config.agentId
|
|
2042
883
|
});
|
|
2043
884
|
consumer.on("user_message", async (event) => {
|
|
2044
885
|
const typedEvent = event;
|
|
2045
|
-
|
|
886
|
+
logger6.debug("user_message event received", {
|
|
2046
887
|
eventAgentId: typedEvent.context?.agentId,
|
|
2047
888
|
myAgentId: this.config.agentId,
|
|
2048
889
|
matches: typedEvent.context?.agentId === this.config.agentId
|
|
@@ -2078,14 +919,14 @@ var ClaudeEffector = class {
|
|
|
2078
919
|
this.currentMeta = meta;
|
|
2079
920
|
const timeout = this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
2080
921
|
const timeoutId = setTimeout(() => {
|
|
2081
|
-
|
|
922
|
+
logger6.warn("Request timeout", { timeout });
|
|
2082
923
|
this.currentAbortController?.abort(new Error(`Request timeout after ${timeout}ms`));
|
|
2083
924
|
}, timeout);
|
|
2084
925
|
try {
|
|
2085
926
|
await this.initialize(this.currentAbortController);
|
|
2086
927
|
const sessionId = this.config.sessionId || "default";
|
|
2087
928
|
const sdkUserMessage = buildSDKUserMessage(message, sessionId);
|
|
2088
|
-
|
|
929
|
+
logger6.debug("Sending message to Claude", {
|
|
2089
930
|
content: typeof message.content === "string" ? message.content.substring(0, 80) : "[structured]",
|
|
2090
931
|
timeout,
|
|
2091
932
|
requestId: meta.requestId
|
|
@@ -2102,13 +943,13 @@ var ClaudeEffector = class {
|
|
|
2102
943
|
*/
|
|
2103
944
|
interrupt(meta) {
|
|
2104
945
|
if (this.claudeQuery) {
|
|
2105
|
-
|
|
946
|
+
logger6.debug("Interrupting Claude query", { requestId: meta?.requestId });
|
|
2106
947
|
this.wasInterrupted = true;
|
|
2107
948
|
if (meta) {
|
|
2108
949
|
this.currentMeta = meta;
|
|
2109
950
|
}
|
|
2110
951
|
this.claudeQuery.interrupt().catch((err) => {
|
|
2111
|
-
|
|
952
|
+
logger6.debug("SDK interrupt() error (may be expected)", { error: err });
|
|
2112
953
|
});
|
|
2113
954
|
}
|
|
2114
955
|
}
|
|
@@ -2117,7 +958,7 @@ var ClaudeEffector = class {
|
|
|
2117
958
|
*/
|
|
2118
959
|
async initialize(abortController) {
|
|
2119
960
|
if (this.isInitialized) return;
|
|
2120
|
-
|
|
961
|
+
logger6.info("Initializing ClaudeEffector");
|
|
2121
962
|
const context = {
|
|
2122
963
|
apiKey: this.config.apiKey,
|
|
2123
964
|
baseUrl: this.config.baseUrl,
|
|
@@ -2134,7 +975,7 @@ var ClaudeEffector = class {
|
|
|
2134
975
|
});
|
|
2135
976
|
this.isInitialized = true;
|
|
2136
977
|
this.startBackgroundListener();
|
|
2137
|
-
|
|
978
|
+
logger6.info("ClaudeEffector initialized");
|
|
2138
979
|
}
|
|
2139
980
|
/**
|
|
2140
981
|
* Start background listener for SDK responses
|
|
@@ -2143,7 +984,7 @@ var ClaudeEffector = class {
|
|
|
2143
984
|
(async () => {
|
|
2144
985
|
try {
|
|
2145
986
|
for await (const sdkMsg of this.claudeQuery) {
|
|
2146
|
-
|
|
987
|
+
logger6.debug("SDK message received", {
|
|
2147
988
|
type: sdkMsg.type,
|
|
2148
989
|
subtype: sdkMsg.subtype,
|
|
2149
990
|
sessionId: sdkMsg.session_id,
|
|
@@ -2160,10 +1001,10 @@ var ClaudeEffector = class {
|
|
|
2160
1001
|
}
|
|
2161
1002
|
if (sdkMsg.type === "result") {
|
|
2162
1003
|
const resultMsg = sdkMsg;
|
|
2163
|
-
|
|
1004
|
+
logger6.info("SDK result received (full)", {
|
|
2164
1005
|
fullResult: JSON.stringify(sdkMsg, null, 2)
|
|
2165
1006
|
});
|
|
2166
|
-
|
|
1007
|
+
logger6.info("SDK result received", {
|
|
2167
1008
|
subtype: resultMsg.subtype,
|
|
2168
1009
|
isError: resultMsg.is_error,
|
|
2169
1010
|
errors: resultMsg.errors,
|
|
@@ -2181,10 +1022,10 @@ var ClaudeEffector = class {
|
|
|
2181
1022
|
}
|
|
2182
1023
|
} catch (error) {
|
|
2183
1024
|
if (this.isAbortError(error)) {
|
|
2184
|
-
|
|
1025
|
+
logger6.debug("Background listener aborted (expected during interrupt)");
|
|
2185
1026
|
this.resetState();
|
|
2186
1027
|
} else {
|
|
2187
|
-
|
|
1028
|
+
logger6.error("Background listener error", { error });
|
|
2188
1029
|
if (this.currentMeta) {
|
|
2189
1030
|
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
2190
1031
|
this.receptor.emitError(errorMessage, "runtime_error", this.currentMeta);
|
|
@@ -2216,7 +1057,7 @@ var ClaudeEffector = class {
|
|
|
2216
1057
|
* Dispose and cleanup resources
|
|
2217
1058
|
*/
|
|
2218
1059
|
dispose() {
|
|
2219
|
-
|
|
1060
|
+
logger6.debug("Disposing ClaudeEffector");
|
|
2220
1061
|
if (this.currentAbortController) {
|
|
2221
1062
|
this.currentAbortController.abort();
|
|
2222
1063
|
}
|
|
@@ -2247,7 +1088,7 @@ var ClaudeEnvironment = class {
|
|
|
2247
1088
|
};
|
|
2248
1089
|
|
|
2249
1090
|
// src/internal/RuntimeAgent.ts
|
|
2250
|
-
var
|
|
1091
|
+
var logger7 = createLogger7("runtime/RuntimeAgent");
|
|
2251
1092
|
var BusPresenter = class {
|
|
2252
1093
|
constructor(producer, session, agentId, imageId, containerId) {
|
|
2253
1094
|
this.producer = producer;
|
|
@@ -2284,67 +1125,18 @@ var BusPresenter = class {
|
|
|
2284
1125
|
this.producer.emit(systemEvent);
|
|
2285
1126
|
if (category === "message") {
|
|
2286
1127
|
this.session.addMessage(data).catch((err) => {
|
|
2287
|
-
|
|
1128
|
+
logger7.error("Failed to persist message", { error: err, messageType: output.type });
|
|
2288
1129
|
});
|
|
2289
1130
|
}
|
|
2290
1131
|
}
|
|
2291
1132
|
/**
|
|
2292
1133
|
* Convert AgentOutput to proper Message type for persistence
|
|
1134
|
+
*
|
|
1135
|
+
* Since messageAssemblerProcessor now emits complete Message objects,
|
|
1136
|
+
* we can directly use the data field without transformation.
|
|
2293
1137
|
*/
|
|
2294
1138
|
convertToMessage(output) {
|
|
2295
|
-
|
|
2296
|
-
const messageId = eventData.messageId ?? eventData.id;
|
|
2297
|
-
const timestamp = eventData.timestamp || output.timestamp;
|
|
2298
|
-
switch (output.type) {
|
|
2299
|
-
case "assistant_message": {
|
|
2300
|
-
const content = eventData.content;
|
|
2301
|
-
return {
|
|
2302
|
-
id: messageId,
|
|
2303
|
-
role: "assistant",
|
|
2304
|
-
subtype: "assistant",
|
|
2305
|
-
content,
|
|
2306
|
-
timestamp
|
|
2307
|
-
};
|
|
2308
|
-
}
|
|
2309
|
-
case "tool_call_message": {
|
|
2310
|
-
const toolCalls = eventData.toolCalls;
|
|
2311
|
-
const toolCall = toolCalls[0];
|
|
2312
|
-
return {
|
|
2313
|
-
id: messageId,
|
|
2314
|
-
role: "assistant",
|
|
2315
|
-
subtype: "tool-call",
|
|
2316
|
-
toolCall,
|
|
2317
|
-
timestamp
|
|
2318
|
-
};
|
|
2319
|
-
}
|
|
2320
|
-
case "tool_result_message": {
|
|
2321
|
-
const results = eventData.results;
|
|
2322
|
-
const toolResult = results[0];
|
|
2323
|
-
return {
|
|
2324
|
-
id: messageId,
|
|
2325
|
-
role: "tool",
|
|
2326
|
-
subtype: "tool-result",
|
|
2327
|
-
toolCallId: toolResult.id,
|
|
2328
|
-
toolResult,
|
|
2329
|
-
timestamp
|
|
2330
|
-
};
|
|
2331
|
-
}
|
|
2332
|
-
case "error_message": {
|
|
2333
|
-
const content = eventData.content;
|
|
2334
|
-
const errorCode = eventData.errorCode;
|
|
2335
|
-
return {
|
|
2336
|
-
id: messageId,
|
|
2337
|
-
role: "error",
|
|
2338
|
-
subtype: "error",
|
|
2339
|
-
content,
|
|
2340
|
-
errorCode,
|
|
2341
|
-
timestamp
|
|
2342
|
-
};
|
|
2343
|
-
}
|
|
2344
|
-
default:
|
|
2345
|
-
logger9.warn("Unknown message type, passing through", { type: output.type });
|
|
2346
|
-
return eventData;
|
|
2347
|
-
}
|
|
1139
|
+
return output.data;
|
|
2348
1140
|
}
|
|
2349
1141
|
/**
|
|
2350
1142
|
* Determine event category from output type
|
|
@@ -2403,7 +1195,7 @@ var RuntimeAgent = class {
|
|
|
2403
1195
|
});
|
|
2404
1196
|
this.environment.receptor.connect(config.bus.asProducer());
|
|
2405
1197
|
this.environment.effector.connect(config.bus.asConsumer());
|
|
2406
|
-
|
|
1198
|
+
logger7.info("ClaudeEnvironment created for agent", {
|
|
2407
1199
|
agentId: this.agentId,
|
|
2408
1200
|
imageId: this.imageId,
|
|
2409
1201
|
cwd: config.sandbox.workdir.path,
|
|
@@ -2438,14 +1230,14 @@ var RuntimeAgent = class {
|
|
|
2438
1230
|
this.driver = new BusDriver(config.bus.asConsumer(), {
|
|
2439
1231
|
agentId: this.agentId,
|
|
2440
1232
|
onStreamEvent: (event) => {
|
|
2441
|
-
|
|
1233
|
+
logger7.debug("BusDriver \u2192 Engine.handleStreamEvent", { type: event.type });
|
|
2442
1234
|
this.engine.handleStreamEvent(event);
|
|
2443
1235
|
},
|
|
2444
1236
|
onStreamComplete: (reason) => {
|
|
2445
|
-
|
|
1237
|
+
logger7.debug("Stream completed", { reason, agentId: this.agentId });
|
|
2446
1238
|
}
|
|
2447
1239
|
});
|
|
2448
|
-
|
|
1240
|
+
logger7.debug("RuntimeAgent created", {
|
|
2449
1241
|
agentId: this.agentId,
|
|
2450
1242
|
imageId: this.imageId
|
|
2451
1243
|
});
|
|
@@ -2454,13 +1246,13 @@ var RuntimeAgent = class {
|
|
|
2454
1246
|
* Save SDK session ID to image metadata for future resume
|
|
2455
1247
|
*/
|
|
2456
1248
|
saveSessionId(sdkSessionId) {
|
|
2457
|
-
|
|
1249
|
+
logger7.info("Saving SDK session ID to image metadata", {
|
|
2458
1250
|
agentId: this.agentId,
|
|
2459
1251
|
imageId: this.imageId,
|
|
2460
1252
|
sdkSessionId
|
|
2461
1253
|
});
|
|
2462
1254
|
this.imageRepository.updateMetadata(this.imageId, { claudeSdkSessionId: sdkSessionId }).catch((err) => {
|
|
2463
|
-
|
|
1255
|
+
logger7.error("Failed to save SDK session ID", { error: err, imageId: this.imageId });
|
|
2464
1256
|
});
|
|
2465
1257
|
}
|
|
2466
1258
|
get lifecycle() {
|
|
@@ -2473,7 +1265,7 @@ var RuntimeAgent = class {
|
|
|
2473
1265
|
* @param requestId - Request ID for correlation
|
|
2474
1266
|
*/
|
|
2475
1267
|
async receive(content, requestId) {
|
|
2476
|
-
|
|
1268
|
+
logger7.debug("RuntimeAgent.receive called", {
|
|
2477
1269
|
agentId: this.agentId,
|
|
2478
1270
|
contentPreview: content.substring(0, 50),
|
|
2479
1271
|
requestId
|
|
@@ -2482,13 +1274,13 @@ var RuntimeAgent = class {
|
|
|
2482
1274
|
throw new Error(`Cannot send message to ${this._lifecycle} agent`);
|
|
2483
1275
|
}
|
|
2484
1276
|
await this.interactor.receive(content, requestId || `req_${Date.now()}`);
|
|
2485
|
-
|
|
1277
|
+
logger7.debug("RuntimeAgent.receive completed", { agentId: this.agentId });
|
|
2486
1278
|
}
|
|
2487
1279
|
/**
|
|
2488
1280
|
* Interrupt current operation
|
|
2489
1281
|
*/
|
|
2490
1282
|
interrupt(requestId) {
|
|
2491
|
-
|
|
1283
|
+
logger7.debug("RuntimeAgent.interrupt called", { agentId: this.agentId, requestId });
|
|
2492
1284
|
this.interactor.interrupt(requestId);
|
|
2493
1285
|
this.producer.emit({
|
|
2494
1286
|
type: "interrupted",
|
|
@@ -2663,7 +1455,7 @@ var RuntimeSandbox = class {
|
|
|
2663
1455
|
"containers",
|
|
2664
1456
|
config.containerId,
|
|
2665
1457
|
"workdirs",
|
|
2666
|
-
config.
|
|
1458
|
+
config.imageId
|
|
2667
1459
|
);
|
|
2668
1460
|
this.workdir = new RuntimeWorkdir(config.agentId, workdirPath);
|
|
2669
1461
|
}
|
|
@@ -2683,7 +1475,8 @@ var RuntimeSandbox = class {
|
|
|
2683
1475
|
};
|
|
2684
1476
|
|
|
2685
1477
|
// src/internal/RuntimeImage.ts
|
|
2686
|
-
|
|
1478
|
+
import { createLogger as createLogger8 } from "@agentxjs/common";
|
|
1479
|
+
var logger8 = createLogger8("runtime/RuntimeImage");
|
|
2687
1480
|
var RuntimeImage = class _RuntimeImage {
|
|
2688
1481
|
constructor(record, context) {
|
|
2689
1482
|
this.record = record;
|
|
@@ -2740,7 +1533,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2740
1533
|
createdAt: now,
|
|
2741
1534
|
updatedAt: now
|
|
2742
1535
|
});
|
|
2743
|
-
|
|
1536
|
+
logger8.info("Image created", {
|
|
2744
1537
|
imageId,
|
|
2745
1538
|
sessionId,
|
|
2746
1539
|
containerId: config.containerId,
|
|
@@ -2754,10 +1547,10 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2754
1547
|
static async load(imageId, context) {
|
|
2755
1548
|
const record = await context.imageRepository.findImageById(imageId);
|
|
2756
1549
|
if (!record) {
|
|
2757
|
-
|
|
1550
|
+
logger8.debug("Image not found", { imageId });
|
|
2758
1551
|
return null;
|
|
2759
1552
|
}
|
|
2760
|
-
|
|
1553
|
+
logger8.debug("Image loaded", { imageId, name: record.name });
|
|
2761
1554
|
return new _RuntimeImage(record, context);
|
|
2762
1555
|
}
|
|
2763
1556
|
/**
|
|
@@ -2791,7 +1584,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2791
1584
|
updatedAt: now
|
|
2792
1585
|
};
|
|
2793
1586
|
await this.context.imageRepository.saveImage(updatedRecord);
|
|
2794
|
-
|
|
1587
|
+
logger8.info("Image updated", { imageId: this.imageId, updates });
|
|
2795
1588
|
return new _RuntimeImage(updatedRecord, this.context);
|
|
2796
1589
|
}
|
|
2797
1590
|
/**
|
|
@@ -2800,7 +1593,7 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2800
1593
|
async delete() {
|
|
2801
1594
|
await this.context.sessionRepository.deleteSession(this.sessionId);
|
|
2802
1595
|
await this.context.imageRepository.deleteImage(this.imageId);
|
|
2803
|
-
|
|
1596
|
+
logger8.info("Image deleted", { imageId: this.imageId, sessionId: this.sessionId });
|
|
2804
1597
|
}
|
|
2805
1598
|
/**
|
|
2806
1599
|
* Get the underlying record
|
|
@@ -2822,7 +1615,8 @@ var RuntimeImage = class _RuntimeImage {
|
|
|
2822
1615
|
};
|
|
2823
1616
|
|
|
2824
1617
|
// src/internal/RuntimeContainer.ts
|
|
2825
|
-
|
|
1618
|
+
import { createLogger as createLogger9 } from "@agentxjs/common";
|
|
1619
|
+
var logger9 = createLogger9("runtime/RuntimeContainer");
|
|
2826
1620
|
var RuntimeContainer = class _RuntimeContainer {
|
|
2827
1621
|
containerId;
|
|
2828
1622
|
createdAt;
|
|
@@ -2862,7 +1656,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2862
1656
|
containerId
|
|
2863
1657
|
}
|
|
2864
1658
|
});
|
|
2865
|
-
|
|
1659
|
+
logger9.info("Container created", { containerId });
|
|
2866
1660
|
return container;
|
|
2867
1661
|
}
|
|
2868
1662
|
/**
|
|
@@ -2871,7 +1665,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2871
1665
|
static async load(containerId, context) {
|
|
2872
1666
|
const record = await context.persistence.containers.findContainerById(containerId);
|
|
2873
1667
|
if (!record) return null;
|
|
2874
|
-
|
|
1668
|
+
logger9.info("Container loaded", { containerId });
|
|
2875
1669
|
return new _RuntimeContainer(containerId, record.createdAt, context);
|
|
2876
1670
|
}
|
|
2877
1671
|
// ==================== Image → Agent Lifecycle ====================
|
|
@@ -2884,7 +1678,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2884
1678
|
if (existingAgentId) {
|
|
2885
1679
|
const existingAgent = this.agents.get(existingAgentId);
|
|
2886
1680
|
if (existingAgent) {
|
|
2887
|
-
|
|
1681
|
+
logger9.info("Reusing existing agent for image", {
|
|
2888
1682
|
containerId: this.containerId,
|
|
2889
1683
|
imageId: image.imageId,
|
|
2890
1684
|
agentId: existingAgentId
|
|
@@ -2896,6 +1690,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2896
1690
|
const agentId = this.generateAgentId();
|
|
2897
1691
|
const sandbox = new RuntimeSandbox({
|
|
2898
1692
|
agentId,
|
|
1693
|
+
imageId: image.imageId,
|
|
2899
1694
|
containerId: this.containerId,
|
|
2900
1695
|
basePath: this.context.basePath
|
|
2901
1696
|
});
|
|
@@ -2943,7 +1738,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2943
1738
|
agentId
|
|
2944
1739
|
}
|
|
2945
1740
|
});
|
|
2946
|
-
|
|
1741
|
+
logger9.info("Agent created for image", {
|
|
2947
1742
|
containerId: this.containerId,
|
|
2948
1743
|
imageId: image.imageId,
|
|
2949
1744
|
agentId
|
|
@@ -2956,17 +1751,17 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
2956
1751
|
async stopImage(imageId) {
|
|
2957
1752
|
const agentId = this.imageToAgent.get(imageId);
|
|
2958
1753
|
if (!agentId) {
|
|
2959
|
-
|
|
1754
|
+
logger9.debug("Image not running, nothing to stop", {
|
|
2960
1755
|
imageId,
|
|
2961
1756
|
containerId: this.containerId
|
|
2962
1757
|
});
|
|
2963
1758
|
return false;
|
|
2964
1759
|
}
|
|
2965
|
-
|
|
1760
|
+
logger9.info("Stopping image", { imageId, agentId, containerId: this.containerId });
|
|
2966
1761
|
const success = await this.destroyAgent(agentId);
|
|
2967
1762
|
if (success) {
|
|
2968
1763
|
this.imageToAgent.delete(imageId);
|
|
2969
|
-
|
|
1764
|
+
logger9.info("Image stopped", { imageId, agentId, containerId: this.containerId });
|
|
2970
1765
|
}
|
|
2971
1766
|
return success;
|
|
2972
1767
|
}
|
|
@@ -3023,7 +1818,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3023
1818
|
agentId
|
|
3024
1819
|
}
|
|
3025
1820
|
});
|
|
3026
|
-
|
|
1821
|
+
logger9.info("Agent destroyed", { containerId: this.containerId, agentId });
|
|
3027
1822
|
return true;
|
|
3028
1823
|
}
|
|
3029
1824
|
async destroyAllAgents() {
|
|
@@ -3051,7 +1846,7 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3051
1846
|
}
|
|
3052
1847
|
});
|
|
3053
1848
|
this.context.onDisposed?.(this.containerId);
|
|
3054
|
-
|
|
1849
|
+
logger9.info("Container disposed", { containerId: this.containerId, agentCount });
|
|
3055
1850
|
}
|
|
3056
1851
|
// ==================== Private Helpers ====================
|
|
3057
1852
|
generateAgentId() {
|
|
@@ -3062,7 +1857,8 @@ var RuntimeContainer = class _RuntimeContainer {
|
|
|
3062
1857
|
};
|
|
3063
1858
|
|
|
3064
1859
|
// src/internal/BaseEventHandler.ts
|
|
3065
|
-
|
|
1860
|
+
import { createLogger as createLogger10 } from "@agentxjs/common";
|
|
1861
|
+
var logger10 = createLogger10("runtime/BaseEventHandler");
|
|
3066
1862
|
var BaseEventHandler = class {
|
|
3067
1863
|
bus;
|
|
3068
1864
|
unsubscribes = [];
|
|
@@ -3101,7 +1897,7 @@ var BaseEventHandler = class {
|
|
|
3101
1897
|
handleError(err, context) {
|
|
3102
1898
|
const message = err instanceof Error ? err.message : String(err);
|
|
3103
1899
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
3104
|
-
|
|
1900
|
+
logger10.error(`Error in ${context.operation || "handler"}`, {
|
|
3105
1901
|
message,
|
|
3106
1902
|
requestId: context.requestId,
|
|
3107
1903
|
details: context.details
|
|
@@ -3128,7 +1924,7 @@ var BaseEventHandler = class {
|
|
|
3128
1924
|
try {
|
|
3129
1925
|
context.onError(err);
|
|
3130
1926
|
} catch (callbackErr) {
|
|
3131
|
-
|
|
1927
|
+
logger10.error("Error in onError callback", { error: callbackErr });
|
|
3132
1928
|
}
|
|
3133
1929
|
}
|
|
3134
1930
|
}
|
|
@@ -3146,12 +1942,13 @@ var BaseEventHandler = class {
|
|
|
3146
1942
|
unsubscribe();
|
|
3147
1943
|
}
|
|
3148
1944
|
this.unsubscribes = [];
|
|
3149
|
-
|
|
1945
|
+
logger10.debug(`${this.constructor.name} disposed`);
|
|
3150
1946
|
}
|
|
3151
1947
|
};
|
|
3152
1948
|
|
|
3153
1949
|
// src/internal/CommandHandler.ts
|
|
3154
|
-
|
|
1950
|
+
import { createLogger as createLogger11 } from "@agentxjs/common";
|
|
1951
|
+
var logger11 = createLogger11("runtime/CommandHandler");
|
|
3155
1952
|
function createResponse(type, data) {
|
|
3156
1953
|
return {
|
|
3157
1954
|
type,
|
|
@@ -3184,7 +1981,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3184
1981
|
super(bus);
|
|
3185
1982
|
this.ops = operations;
|
|
3186
1983
|
this.bindHandlers();
|
|
3187
|
-
|
|
1984
|
+
logger11.debug("CommandHandler created");
|
|
3188
1985
|
}
|
|
3189
1986
|
/**
|
|
3190
1987
|
* Log error and emit system_error event
|
|
@@ -3192,7 +1989,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3192
1989
|
emitError(operation, err, requestId, context) {
|
|
3193
1990
|
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
3194
1991
|
const stack = err instanceof Error ? err.stack : void 0;
|
|
3195
|
-
|
|
1992
|
+
logger11.error(operation, {
|
|
3196
1993
|
requestId,
|
|
3197
1994
|
...context,
|
|
3198
1995
|
error: errorMessage,
|
|
@@ -3249,12 +2046,12 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3249
2046
|
this.subscribe(
|
|
3250
2047
|
this.bus.onCommand("image_messages_request", (event) => this.handleImageMessages(event))
|
|
3251
2048
|
);
|
|
3252
|
-
|
|
2049
|
+
logger11.debug("Command handlers bound");
|
|
3253
2050
|
}
|
|
3254
2051
|
// ==================== Container Handlers ====================
|
|
3255
2052
|
async handleContainerCreate(event) {
|
|
3256
2053
|
const { requestId, containerId } = event.data;
|
|
3257
|
-
|
|
2054
|
+
logger11.debug("Handling container_create_request", { requestId, containerId });
|
|
3258
2055
|
try {
|
|
3259
2056
|
await this.ops.createContainer(containerId);
|
|
3260
2057
|
this.bus.emit(
|
|
@@ -3276,7 +2073,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3276
2073
|
}
|
|
3277
2074
|
handleContainerGet(event) {
|
|
3278
2075
|
const { requestId, containerId } = event.data;
|
|
3279
|
-
|
|
2076
|
+
logger11.debug("Handling container_get_request", { requestId, containerId });
|
|
3280
2077
|
const container = this.ops.getContainer(containerId);
|
|
3281
2078
|
this.bus.emit(
|
|
3282
2079
|
createResponse("container_get_response", {
|
|
@@ -3288,7 +2085,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3288
2085
|
}
|
|
3289
2086
|
handleContainerList(event) {
|
|
3290
2087
|
const { requestId } = event.data;
|
|
3291
|
-
|
|
2088
|
+
logger11.debug("Handling container_list_request", { requestId });
|
|
3292
2089
|
const containers = this.ops.listContainers();
|
|
3293
2090
|
this.bus.emit(
|
|
3294
2091
|
createResponse("container_list_response", {
|
|
@@ -3300,7 +2097,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3300
2097
|
// ==================== Agent Handlers ====================
|
|
3301
2098
|
handleAgentGet(event) {
|
|
3302
2099
|
const { requestId, agentId } = event.data;
|
|
3303
|
-
|
|
2100
|
+
logger11.debug("Handling agent_get_request", { requestId, agentId });
|
|
3304
2101
|
const agent = this.ops.getAgent(agentId);
|
|
3305
2102
|
this.bus.emit(
|
|
3306
2103
|
createResponse("agent_get_response", {
|
|
@@ -3313,7 +2110,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3313
2110
|
}
|
|
3314
2111
|
handleAgentList(event) {
|
|
3315
2112
|
const { requestId, containerId } = event.data;
|
|
3316
|
-
|
|
2113
|
+
logger11.debug("Handling agent_list_request", { requestId, containerId });
|
|
3317
2114
|
const agents = this.ops.listAgents(containerId);
|
|
3318
2115
|
this.bus.emit(
|
|
3319
2116
|
createResponse("agent_list_response", {
|
|
@@ -3328,7 +2125,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3328
2125
|
}
|
|
3329
2126
|
async handleAgentDestroy(event) {
|
|
3330
2127
|
const { requestId, agentId } = event.data;
|
|
3331
|
-
|
|
2128
|
+
logger11.debug("Handling agent_destroy_request", { requestId, agentId });
|
|
3332
2129
|
try {
|
|
3333
2130
|
const success = await this.ops.destroyAgent(agentId);
|
|
3334
2131
|
this.bus.emit(
|
|
@@ -3352,7 +2149,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3352
2149
|
}
|
|
3353
2150
|
async handleAgentDestroyAll(event) {
|
|
3354
2151
|
const { requestId, containerId } = event.data;
|
|
3355
|
-
|
|
2152
|
+
logger11.debug("Handling agent_destroy_all_request", { requestId, containerId });
|
|
3356
2153
|
try {
|
|
3357
2154
|
await this.ops.destroyAllAgents(containerId);
|
|
3358
2155
|
this.bus.emit(
|
|
@@ -3374,7 +2171,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3374
2171
|
}
|
|
3375
2172
|
async handleMessageSend(event) {
|
|
3376
2173
|
const { requestId, imageId, agentId, content } = event.data;
|
|
3377
|
-
|
|
2174
|
+
logger11.debug("Handling message_send_request", { requestId, imageId, agentId });
|
|
3378
2175
|
try {
|
|
3379
2176
|
const result = await this.ops.receiveMessage(imageId, agentId, content, requestId);
|
|
3380
2177
|
this.bus.emit(
|
|
@@ -3398,7 +2195,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3398
2195
|
}
|
|
3399
2196
|
handleAgentInterrupt(event) {
|
|
3400
2197
|
const { requestId, imageId, agentId } = event.data;
|
|
3401
|
-
|
|
2198
|
+
logger11.debug("Handling agent_interrupt_request", { requestId, imageId, agentId });
|
|
3402
2199
|
try {
|
|
3403
2200
|
const result = this.ops.interruptAgent(imageId, agentId, requestId);
|
|
3404
2201
|
this.bus.emit(
|
|
@@ -3423,7 +2220,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3423
2220
|
// ==================== Image Handlers ====================
|
|
3424
2221
|
async handleImageCreate(event) {
|
|
3425
2222
|
const { requestId, containerId, config } = event.data;
|
|
3426
|
-
|
|
2223
|
+
logger11.debug("Handling image_create_request", { requestId, containerId });
|
|
3427
2224
|
try {
|
|
3428
2225
|
const record = await this.ops.createImage(containerId, config);
|
|
3429
2226
|
this.bus.emit(
|
|
@@ -3445,7 +2242,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3445
2242
|
}
|
|
3446
2243
|
async handleImageRun(event) {
|
|
3447
2244
|
const { requestId, imageId } = event.data;
|
|
3448
|
-
|
|
2245
|
+
logger11.debug("Handling image_run_request", { requestId, imageId });
|
|
3449
2246
|
try {
|
|
3450
2247
|
const result = await this.ops.runImage(imageId);
|
|
3451
2248
|
this.bus.emit(
|
|
@@ -3471,7 +2268,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3471
2268
|
}
|
|
3472
2269
|
async handleImageStop(event) {
|
|
3473
2270
|
const { requestId, imageId } = event.data;
|
|
3474
|
-
|
|
2271
|
+
logger11.debug("Handling image_stop_request", { requestId, imageId });
|
|
3475
2272
|
try {
|
|
3476
2273
|
await this.ops.stopImage(imageId);
|
|
3477
2274
|
this.bus.emit(
|
|
@@ -3493,7 +2290,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3493
2290
|
}
|
|
3494
2291
|
async handleImageUpdate(event) {
|
|
3495
2292
|
const { requestId, imageId, updates } = event.data;
|
|
3496
|
-
|
|
2293
|
+
logger11.debug("Handling image_update_request", { requestId, imageId });
|
|
3497
2294
|
try {
|
|
3498
2295
|
const record = await this.ops.updateImage(imageId, updates);
|
|
3499
2296
|
this.bus.emit(
|
|
@@ -3515,7 +2312,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3515
2312
|
}
|
|
3516
2313
|
async handleImageList(event) {
|
|
3517
2314
|
const { requestId, containerId } = event.data;
|
|
3518
|
-
|
|
2315
|
+
logger11.debug("Handling image_list_request", { requestId, containerId });
|
|
3519
2316
|
try {
|
|
3520
2317
|
const images = await this.ops.listImages(containerId);
|
|
3521
2318
|
this.bus.emit(
|
|
@@ -3537,7 +2334,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3537
2334
|
}
|
|
3538
2335
|
async handleImageGet(event) {
|
|
3539
2336
|
const { requestId, imageId } = event.data;
|
|
3540
|
-
|
|
2337
|
+
logger11.debug("Handling image_get_request", { requestId, imageId });
|
|
3541
2338
|
try {
|
|
3542
2339
|
const image = await this.ops.getImage(imageId);
|
|
3543
2340
|
this.bus.emit(
|
|
@@ -3558,7 +2355,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3558
2355
|
}
|
|
3559
2356
|
async handleImageDelete(event) {
|
|
3560
2357
|
const { requestId, imageId } = event.data;
|
|
3561
|
-
|
|
2358
|
+
logger11.debug("Handling image_delete_request", { requestId, imageId });
|
|
3562
2359
|
try {
|
|
3563
2360
|
await this.ops.deleteImage(imageId);
|
|
3564
2361
|
this.bus.emit(
|
|
@@ -3580,10 +2377,10 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3580
2377
|
}
|
|
3581
2378
|
async handleImageMessages(event) {
|
|
3582
2379
|
const { requestId, imageId } = event.data;
|
|
3583
|
-
|
|
2380
|
+
logger11.info("Handling image_messages_request", { requestId, imageId });
|
|
3584
2381
|
try {
|
|
3585
2382
|
const messages = await this.ops.getImageMessages(imageId);
|
|
3586
|
-
|
|
2383
|
+
logger11.info("Got messages for image", { imageId, count: messages.length });
|
|
3587
2384
|
this.bus.emit(
|
|
3588
2385
|
createResponse("image_messages_response", {
|
|
3589
2386
|
requestId,
|
|
@@ -3591,7 +2388,7 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3591
2388
|
messages
|
|
3592
2389
|
})
|
|
3593
2390
|
);
|
|
3594
|
-
|
|
2391
|
+
logger11.info("Emitted image_messages_response", { requestId, imageId });
|
|
3595
2392
|
} catch (err) {
|
|
3596
2393
|
this.emitError("Failed to get image messages", err, requestId, { imageId });
|
|
3597
2394
|
this.bus.emit(
|
|
@@ -3608,9 +2405,8 @@ var CommandHandler = class extends BaseEventHandler {
|
|
|
3608
2405
|
};
|
|
3609
2406
|
|
|
3610
2407
|
// src/RuntimeImpl.ts
|
|
3611
|
-
import {
|
|
3612
|
-
|
|
3613
|
-
var logger14 = createLogger("runtime/RuntimeImpl");
|
|
2408
|
+
import { createLogger as createLogger12 } from "@agentxjs/common";
|
|
2409
|
+
var logger12 = createLogger12("runtime/RuntimeImpl");
|
|
3614
2410
|
var RuntimeImpl = class {
|
|
3615
2411
|
persistence;
|
|
3616
2412
|
llmProvider;
|
|
@@ -3621,20 +2417,20 @@ var RuntimeImpl = class {
|
|
|
3621
2417
|
/** Container registry: containerId -> RuntimeContainer */
|
|
3622
2418
|
containerRegistry = /* @__PURE__ */ new Map();
|
|
3623
2419
|
constructor(config) {
|
|
3624
|
-
|
|
2420
|
+
logger12.info("RuntimeImpl constructor start");
|
|
3625
2421
|
this.persistence = config.persistence;
|
|
3626
2422
|
this.llmProvider = config.llmProvider;
|
|
3627
|
-
this.basePath =
|
|
3628
|
-
|
|
2423
|
+
this.basePath = config.basePath;
|
|
2424
|
+
logger12.info("Creating SystemBus");
|
|
3629
2425
|
this.bus = new SystemBusImpl();
|
|
3630
2426
|
this.llmConfig = this.llmProvider.provide();
|
|
3631
|
-
|
|
2427
|
+
logger12.info("LLM config loaded", {
|
|
3632
2428
|
hasApiKey: !!this.llmConfig.apiKey,
|
|
3633
2429
|
model: this.llmConfig.model
|
|
3634
2430
|
});
|
|
3635
|
-
|
|
2431
|
+
logger12.info("Creating CommandHandler");
|
|
3636
2432
|
this.commandHandler = new CommandHandler(this.bus, this.createRuntimeOperations());
|
|
3637
|
-
|
|
2433
|
+
logger12.info("RuntimeImpl constructor done");
|
|
3638
2434
|
}
|
|
3639
2435
|
// ==================== SystemBus delegation ====================
|
|
3640
2436
|
emit(event) {
|
|
@@ -3717,7 +2513,7 @@ var RuntimeImpl = class {
|
|
|
3717
2513
|
// Agent operations (by imageId - with auto-activation)
|
|
3718
2514
|
receiveMessage: async (imageId, agentId, content, requestId) => {
|
|
3719
2515
|
if (imageId) {
|
|
3720
|
-
|
|
2516
|
+
logger12.debug("Receiving message by imageId", {
|
|
3721
2517
|
imageId,
|
|
3722
2518
|
contentLength: content.length,
|
|
3723
2519
|
requestId
|
|
@@ -3726,7 +2522,7 @@ var RuntimeImpl = class {
|
|
|
3726
2522
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3727
2523
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
3728
2524
|
const { agent, reused } = await container.runImage(record);
|
|
3729
|
-
|
|
2525
|
+
logger12.info("Message routed to agent", {
|
|
3730
2526
|
imageId,
|
|
3731
2527
|
agentId: agent.agentId,
|
|
3732
2528
|
reused,
|
|
@@ -3736,7 +2532,7 @@ var RuntimeImpl = class {
|
|
|
3736
2532
|
return { agentId: agent.agentId, imageId };
|
|
3737
2533
|
}
|
|
3738
2534
|
if (agentId) {
|
|
3739
|
-
|
|
2535
|
+
logger12.debug("Receiving message by agentId (legacy)", {
|
|
3740
2536
|
agentId,
|
|
3741
2537
|
contentLength: content.length,
|
|
3742
2538
|
requestId
|
|
@@ -3753,12 +2549,12 @@ var RuntimeImpl = class {
|
|
|
3753
2549
|
if (imageId) {
|
|
3754
2550
|
const foundAgentId = this.findAgentIdForImage(imageId);
|
|
3755
2551
|
if (!foundAgentId) {
|
|
3756
|
-
|
|
2552
|
+
logger12.debug("Image is offline, nothing to interrupt", { imageId });
|
|
3757
2553
|
return { imageId, agentId: void 0 };
|
|
3758
2554
|
}
|
|
3759
2555
|
const agent = this.findAgent(foundAgentId);
|
|
3760
2556
|
if (agent) {
|
|
3761
|
-
|
|
2557
|
+
logger12.info("Interrupting agent by imageId", {
|
|
3762
2558
|
imageId,
|
|
3763
2559
|
agentId: foundAgentId,
|
|
3764
2560
|
requestId
|
|
@@ -3770,7 +2566,7 @@ var RuntimeImpl = class {
|
|
|
3770
2566
|
if (agentId) {
|
|
3771
2567
|
const agent = this.findAgent(agentId);
|
|
3772
2568
|
if (!agent) throw new Error(`Agent not found: ${agentId}`);
|
|
3773
|
-
|
|
2569
|
+
logger12.info("Interrupting agent by agentId (legacy)", { agentId, requestId });
|
|
3774
2570
|
agent.interrupt(requestId);
|
|
3775
2571
|
const foundImageId = this.findImageIdForAgent(agentId);
|
|
3776
2572
|
return { agentId, imageId: foundImageId };
|
|
@@ -3779,32 +2575,32 @@ var RuntimeImpl = class {
|
|
|
3779
2575
|
},
|
|
3780
2576
|
// Image operations (new model)
|
|
3781
2577
|
createImage: async (containerId, config) => {
|
|
3782
|
-
|
|
2578
|
+
logger12.debug("Creating image", { containerId, name: config.name });
|
|
3783
2579
|
await this.getOrCreateContainer(containerId);
|
|
3784
2580
|
const image = await RuntimeImage.create(
|
|
3785
2581
|
{ containerId, ...config },
|
|
3786
2582
|
this.createImageContext()
|
|
3787
2583
|
);
|
|
3788
|
-
|
|
2584
|
+
logger12.info("Image created via RuntimeOps", { imageId: image.imageId, containerId });
|
|
3789
2585
|
return this.toImageListItemResult(image.toRecord(), false);
|
|
3790
2586
|
},
|
|
3791
2587
|
runImage: async (imageId) => {
|
|
3792
|
-
|
|
2588
|
+
logger12.debug("Running image", { imageId });
|
|
3793
2589
|
const record = await this.persistence.images.findImageById(imageId);
|
|
3794
2590
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3795
2591
|
const container = await this.getOrCreateContainer(record.containerId);
|
|
3796
2592
|
const { agent, reused } = await container.runImage(record);
|
|
3797
|
-
|
|
2593
|
+
logger12.info("Image running", { imageId, agentId: agent.agentId, reused });
|
|
3798
2594
|
return { imageId, agentId: agent.agentId, reused };
|
|
3799
2595
|
},
|
|
3800
2596
|
stopImage: async (imageId) => {
|
|
3801
|
-
|
|
2597
|
+
logger12.debug("Stopping image", { imageId });
|
|
3802
2598
|
const record = await this.persistence.images.findImageById(imageId);
|
|
3803
2599
|
if (!record) throw new Error(`Image not found: ${imageId}`);
|
|
3804
2600
|
const container = this.containerRegistry.get(record.containerId);
|
|
3805
2601
|
if (container) {
|
|
3806
2602
|
await container.stopImage(imageId);
|
|
3807
|
-
|
|
2603
|
+
logger12.info("Image stopped via RuntimeOps", { imageId });
|
|
3808
2604
|
}
|
|
3809
2605
|
},
|
|
3810
2606
|
updateImage: async (imageId, updates) => {
|
|
@@ -3828,10 +2624,10 @@ var RuntimeImpl = class {
|
|
|
3828
2624
|
return this.toImageListItemResult(record, online);
|
|
3829
2625
|
},
|
|
3830
2626
|
deleteImage: async (imageId) => {
|
|
3831
|
-
|
|
2627
|
+
logger12.debug("Deleting image", { imageId });
|
|
3832
2628
|
const agentId = this.findAgentIdForImage(imageId);
|
|
3833
2629
|
if (agentId) {
|
|
3834
|
-
|
|
2630
|
+
logger12.debug("Stopping running agent before delete", { imageId, agentId });
|
|
3835
2631
|
for (const container of this.containerRegistry.values()) {
|
|
3836
2632
|
if (container.getAgent(agentId)) {
|
|
3837
2633
|
await container.destroyAgent(agentId);
|
|
@@ -3842,42 +2638,18 @@ var RuntimeImpl = class {
|
|
|
3842
2638
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
3843
2639
|
if (image) {
|
|
3844
2640
|
await image.delete();
|
|
3845
|
-
|
|
2641
|
+
logger12.info("Image deleted via RuntimeOps", { imageId });
|
|
3846
2642
|
}
|
|
3847
2643
|
},
|
|
3848
2644
|
getImageMessages: async (imageId) => {
|
|
3849
|
-
|
|
2645
|
+
logger12.debug("Getting messages for image", { imageId });
|
|
3850
2646
|
const image = await RuntimeImage.load(imageId, this.createImageContext());
|
|
3851
2647
|
if (!image) {
|
|
3852
2648
|
throw new Error(`Image not found: ${imageId}`);
|
|
3853
2649
|
}
|
|
3854
2650
|
const messages = await image.getMessages();
|
|
3855
|
-
|
|
3856
|
-
return messages
|
|
3857
|
-
let content;
|
|
3858
|
-
let role = m.role;
|
|
3859
|
-
let errorCode;
|
|
3860
|
-
if (m.subtype === "user" || m.subtype === "assistant") {
|
|
3861
|
-
content = m.content;
|
|
3862
|
-
} else if (m.subtype === "tool-call") {
|
|
3863
|
-
content = m.toolCall;
|
|
3864
|
-
role = "tool_call";
|
|
3865
|
-
} else if (m.subtype === "tool-result") {
|
|
3866
|
-
content = m.toolResult;
|
|
3867
|
-
role = "tool_result";
|
|
3868
|
-
} else if (m.subtype === "error") {
|
|
3869
|
-
content = m.content;
|
|
3870
|
-
role = "error";
|
|
3871
|
-
errorCode = m.errorCode;
|
|
3872
|
-
}
|
|
3873
|
-
return {
|
|
3874
|
-
id: m.id,
|
|
3875
|
-
role,
|
|
3876
|
-
content,
|
|
3877
|
-
timestamp: m.timestamp,
|
|
3878
|
-
errorCode
|
|
3879
|
-
};
|
|
3880
|
-
});
|
|
2651
|
+
logger12.debug("Got messages from storage", { imageId, count: messages.length });
|
|
2652
|
+
return messages;
|
|
3881
2653
|
}
|
|
3882
2654
|
};
|
|
3883
2655
|
}
|
|
@@ -3969,14 +2741,14 @@ var RuntimeImpl = class {
|
|
|
3969
2741
|
}
|
|
3970
2742
|
// ==================== Lifecycle ====================
|
|
3971
2743
|
async dispose() {
|
|
3972
|
-
|
|
2744
|
+
logger12.info("Disposing RuntimeImpl");
|
|
3973
2745
|
this.commandHandler.dispose();
|
|
3974
2746
|
for (const container of this.containerRegistry.values()) {
|
|
3975
2747
|
await container.dispose();
|
|
3976
2748
|
}
|
|
3977
2749
|
this.bus.destroy();
|
|
3978
2750
|
this.containerRegistry.clear();
|
|
3979
|
-
|
|
2751
|
+
logger12.info("RuntimeImpl disposed");
|
|
3980
2752
|
}
|
|
3981
2753
|
};
|
|
3982
2754
|
|
|
@@ -3987,9 +2759,11 @@ function createRuntime(config) {
|
|
|
3987
2759
|
|
|
3988
2760
|
// src/internal/persistence/PersistenceImpl.ts
|
|
3989
2761
|
import { createStorage } from "unstorage";
|
|
2762
|
+
import { createLogger as createLogger16 } from "@agentxjs/common";
|
|
3990
2763
|
|
|
3991
2764
|
// src/internal/persistence/repository/StorageImageRepository.ts
|
|
3992
|
-
|
|
2765
|
+
import { createLogger as createLogger13 } from "@agentxjs/common";
|
|
2766
|
+
var logger13 = createLogger13("persistence/ImageRepository");
|
|
3993
2767
|
var PREFIX = "images";
|
|
3994
2768
|
var INDEX_BY_NAME = "idx:images:name";
|
|
3995
2769
|
var INDEX_BY_CONTAINER = "idx:images:container";
|
|
@@ -4013,7 +2787,7 @@ var StorageImageRepository = class {
|
|
|
4013
2787
|
this.containerIndexKey(record.containerId, record.imageId),
|
|
4014
2788
|
record.imageId
|
|
4015
2789
|
);
|
|
4016
|
-
|
|
2790
|
+
logger13.debug("Image saved", { imageId: record.imageId });
|
|
4017
2791
|
}
|
|
4018
2792
|
async findImageById(imageId) {
|
|
4019
2793
|
const record = await this.storage.getItem(this.key(imageId));
|
|
@@ -4068,7 +2842,7 @@ var StorageImageRepository = class {
|
|
|
4068
2842
|
await this.storage.removeItem(this.nameIndexKey(record.name, imageId));
|
|
4069
2843
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, imageId));
|
|
4070
2844
|
}
|
|
4071
|
-
|
|
2845
|
+
logger13.debug("Image deleted", { imageId });
|
|
4072
2846
|
}
|
|
4073
2847
|
async imageExists(imageId) {
|
|
4074
2848
|
return await this.storage.hasItem(this.key(imageId));
|
|
@@ -4087,12 +2861,13 @@ var StorageImageRepository = class {
|
|
|
4087
2861
|
updatedAt: Date.now()
|
|
4088
2862
|
};
|
|
4089
2863
|
await this.storage.setItem(this.key(imageId), updatedRecord);
|
|
4090
|
-
|
|
2864
|
+
logger13.debug("Image metadata updated", { imageId, metadata });
|
|
4091
2865
|
}
|
|
4092
2866
|
};
|
|
4093
2867
|
|
|
4094
2868
|
// src/internal/persistence/repository/StorageContainerRepository.ts
|
|
4095
|
-
|
|
2869
|
+
import { createLogger as createLogger14 } from "@agentxjs/common";
|
|
2870
|
+
var logger14 = createLogger14("persistence/ContainerRepository");
|
|
4096
2871
|
var PREFIX2 = "containers";
|
|
4097
2872
|
var StorageContainerRepository = class {
|
|
4098
2873
|
constructor(storage) {
|
|
@@ -4103,7 +2878,7 @@ var StorageContainerRepository = class {
|
|
|
4103
2878
|
}
|
|
4104
2879
|
async saveContainer(record) {
|
|
4105
2880
|
await this.storage.setItem(this.key(record.containerId), record);
|
|
4106
|
-
|
|
2881
|
+
logger14.debug("Container saved", { containerId: record.containerId });
|
|
4107
2882
|
}
|
|
4108
2883
|
async findContainerById(containerId) {
|
|
4109
2884
|
const record = await this.storage.getItem(this.key(containerId));
|
|
@@ -4122,7 +2897,7 @@ var StorageContainerRepository = class {
|
|
|
4122
2897
|
}
|
|
4123
2898
|
async deleteContainer(containerId) {
|
|
4124
2899
|
await this.storage.removeItem(this.key(containerId));
|
|
4125
|
-
|
|
2900
|
+
logger14.debug("Container deleted", { containerId });
|
|
4126
2901
|
}
|
|
4127
2902
|
async containerExists(containerId) {
|
|
4128
2903
|
return await this.storage.hasItem(this.key(containerId));
|
|
@@ -4130,7 +2905,8 @@ var StorageContainerRepository = class {
|
|
|
4130
2905
|
};
|
|
4131
2906
|
|
|
4132
2907
|
// src/internal/persistence/repository/StorageSessionRepository.ts
|
|
4133
|
-
|
|
2908
|
+
import { createLogger as createLogger15 } from "@agentxjs/common";
|
|
2909
|
+
var logger15 = createLogger15("persistence/SessionRepository");
|
|
4134
2910
|
var PREFIX3 = "sessions";
|
|
4135
2911
|
var MESSAGES_PREFIX = "messages";
|
|
4136
2912
|
var INDEX_BY_IMAGE = "idx:sessions:image";
|
|
@@ -4161,7 +2937,7 @@ var StorageSessionRepository = class {
|
|
|
4161
2937
|
this.containerIndexKey(record.containerId, record.sessionId),
|
|
4162
2938
|
record.sessionId
|
|
4163
2939
|
);
|
|
4164
|
-
|
|
2940
|
+
logger15.debug("Session saved", { sessionId: record.sessionId });
|
|
4165
2941
|
}
|
|
4166
2942
|
async findSessionById(sessionId) {
|
|
4167
2943
|
const record = await this.storage.getItem(this.key(sessionId));
|
|
@@ -4210,7 +2986,7 @@ var StorageSessionRepository = class {
|
|
|
4210
2986
|
await this.storage.removeItem(this.imageIndexKey(record.imageId, sessionId));
|
|
4211
2987
|
await this.storage.removeItem(this.containerIndexKey(record.containerId, sessionId));
|
|
4212
2988
|
}
|
|
4213
|
-
|
|
2989
|
+
logger15.debug("Session deleted", { sessionId });
|
|
4214
2990
|
}
|
|
4215
2991
|
async sessionExists(sessionId) {
|
|
4216
2992
|
return await this.storage.hasItem(this.key(sessionId));
|
|
@@ -4220,13 +2996,13 @@ var StorageSessionRepository = class {
|
|
|
4220
2996
|
const messages = await this.getMessages(sessionId);
|
|
4221
2997
|
messages.push(message);
|
|
4222
2998
|
await this.storage.setItem(this.messagesKey(sessionId), messages);
|
|
4223
|
-
|
|
2999
|
+
logger15.debug("Message added to session", { sessionId, subtype: message.subtype });
|
|
4224
3000
|
}
|
|
4225
3001
|
async getMessages(sessionId) {
|
|
4226
3002
|
const messages = await this.storage.getItem(this.messagesKey(sessionId));
|
|
4227
3003
|
if (!messages || !Array.isArray(messages)) {
|
|
4228
3004
|
if (messages) {
|
|
4229
|
-
|
|
3005
|
+
logger15.warn("Messages data is not an array, resetting", {
|
|
4230
3006
|
sessionId,
|
|
4231
3007
|
type: typeof messages
|
|
4232
3008
|
});
|
|
@@ -4237,12 +3013,12 @@ var StorageSessionRepository = class {
|
|
|
4237
3013
|
}
|
|
4238
3014
|
async clearMessages(sessionId) {
|
|
4239
3015
|
await this.storage.removeItem(this.messagesKey(sessionId));
|
|
4240
|
-
|
|
3016
|
+
logger15.debug("Messages cleared for session", { sessionId });
|
|
4241
3017
|
}
|
|
4242
3018
|
};
|
|
4243
3019
|
|
|
4244
3020
|
// src/internal/persistence/PersistenceImpl.ts
|
|
4245
|
-
var
|
|
3021
|
+
var logger16 = createLogger16("persistence/Persistence");
|
|
4246
3022
|
var PersistenceImpl = class _PersistenceImpl {
|
|
4247
3023
|
images;
|
|
4248
3024
|
containers;
|
|
@@ -4256,7 +3032,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
4256
3032
|
this.images = new StorageImageRepository(this.storage);
|
|
4257
3033
|
this.containers = new StorageContainerRepository(this.storage);
|
|
4258
3034
|
this.sessions = new StorageSessionRepository(this.storage);
|
|
4259
|
-
|
|
3035
|
+
logger16.info("Persistence created", { driver: driverName });
|
|
4260
3036
|
}
|
|
4261
3037
|
/**
|
|
4262
3038
|
* Create a PersistenceImpl instance (async factory)
|
|
@@ -4277,7 +3053,7 @@ var PersistenceImpl = class _PersistenceImpl {
|
|
|
4277
3053
|
*/
|
|
4278
3054
|
async dispose() {
|
|
4279
3055
|
await this.storage.dispose();
|
|
4280
|
-
|
|
3056
|
+
logger16.info("Persistence disposed");
|
|
4281
3057
|
}
|
|
4282
3058
|
};
|
|
4283
3059
|
async function createStorageFromConfig(config) {
|