@agentxjs/ui 0.0.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/LICENSE +21 -0
- package/README.md +78 -0
- package/dist/api/index.d.ts +9 -0
- package/dist/components/container/AgentPane.d.ts +56 -0
- package/dist/components/container/ContainerView.d.ts +119 -0
- package/dist/components/container/DefinitionPane.d.ts +27 -0
- package/dist/components/container/InputPane.d.ts +44 -0
- package/dist/components/container/InputToolBar.d.ts +22 -0
- package/dist/components/container/MessagePane.d.ts +32 -0
- package/dist/components/container/SessionPane.d.ts +35 -0
- package/dist/components/container/index.d.ts +22 -0
- package/dist/components/container/types.d.ts +67 -0
- package/dist/components/element/ActionBar.d.ts +43 -0
- package/dist/components/element/AgentLogo.d.ts +21 -0
- package/dist/components/element/AppHeader.d.ts +84 -0
- package/dist/components/element/Badge.d.ts +9 -0
- package/dist/components/element/Button.d.ts +11 -0
- package/dist/components/element/EmptyState.d.ts +56 -0
- package/dist/components/element/ImageAttachment.d.ts +50 -0
- package/dist/components/element/Input.d.ts +5 -0
- package/dist/components/element/ListItem.d.ts +106 -0
- package/dist/components/element/LoadingState.d.ts +51 -0
- package/dist/components/element/MessageAvatar.d.ts +61 -0
- package/dist/components/element/PageHeader.d.ts +90 -0
- package/dist/components/element/Popover.d.ts +20 -0
- package/dist/components/element/ScrollArea.d.ts +6 -0
- package/dist/components/element/SearchInput.d.ts +75 -0
- package/dist/components/element/TabNavigation.d.ts +91 -0
- package/dist/components/element/TimeAgo.d.ts +46 -0
- package/dist/components/element/TokenUsagePie.d.ts +33 -0
- package/dist/components/element/index.d.ts +18 -0
- package/dist/components/input/InputBox.d.ts +43 -0
- package/dist/components/input/index.d.ts +1 -0
- package/dist/components/layout/ActivityBar.d.ts +62 -0
- package/dist/components/layout/Header.d.ts +36 -0
- package/dist/components/layout/MainContent.d.ts +21 -0
- package/dist/components/layout/Panel.d.ts +44 -0
- package/dist/components/layout/RightSidebar.d.ts +43 -0
- package/dist/components/layout/Sidebar.d.ts +34 -0
- package/dist/components/layout/StatusBar.d.ts +66 -0
- package/dist/components/layout/index.d.ts +7 -0
- package/dist/components/message/MessageList.d.ts +16 -0
- package/dist/components/message/StatusIndicator.d.ts +28 -0
- package/dist/components/message/index.d.ts +4 -0
- package/dist/components/message/items/AssistantMessage.d.ts +33 -0
- package/dist/components/message/items/ErrorAlert.d.ts +33 -0
- package/dist/components/message/items/SystemMessage.d.ts +25 -0
- package/dist/components/message/items/ToolCallMessage.d.ts +31 -0
- package/dist/components/message/items/ToolResultMessage.d.ts +33 -0
- package/dist/components/message/items/ToolUseMessage.d.ts +30 -0
- package/dist/components/message/items/UserMessage.d.ts +27 -0
- package/dist/components/message/items/index.d.ts +7 -0
- package/dist/components/message/parts/FileContent.d.ts +24 -0
- package/dist/components/message/parts/ImageContent.d.ts +32 -0
- package/dist/components/message/parts/TextContent.d.ts +20 -0
- package/dist/components/message/parts/ThinkingContent.d.ts +28 -0
- package/dist/components/message/parts/ToolCallContent.d.ts +31 -0
- package/dist/components/message/parts/ToolResultContent.d.ts +32 -0
- package/dist/components/message/parts/index.d.ts +6 -0
- package/dist/components/studio/Studio.d.ts +47 -0
- package/dist/components/studio/index.d.ts +9 -0
- package/dist/components/typography/DiffViewer.d.ts +41 -0
- package/dist/components/typography/JSONRenderer.d.ts +23 -0
- package/dist/components/typography/MarkdownText.d.ts +25 -0
- package/dist/components/typography/index.d.ts +3 -0
- package/dist/globals.css +201 -0
- package/dist/hooks/index.d.ts +28 -0
- package/dist/hooks/useAgent.d.ts +71 -0
- package/dist/hooks/useAgentX.d.ts +10 -0
- package/dist/hooks/useSession.d.ts +79 -0
- package/dist/index-CB5mSMCj.js +3041 -0
- package/dist/index-CB5mSMCj.js.map +1 -0
- package/dist/index-CyXGvO5F.js +27676 -0
- package/dist/index-CyXGvO5F.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +64 -0
- package/dist/index.js.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/utils/eventBus.d.ts +93 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/timeUtils.d.ts +14 -0
- package/dist/utils/utils.d.ts +13 -0
- package/package.json +87 -0
|
@@ -0,0 +1,3041 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
import { c as createLogger, i as isStateEvent, L as LogLevel } from "./index-CyXGvO5F.js";
|
|
5
|
+
var extendStatics = function(d, b) {
|
|
6
|
+
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
|
|
7
|
+
d2.__proto__ = b2;
|
|
8
|
+
} || function(d2, b2) {
|
|
9
|
+
for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
|
|
10
|
+
};
|
|
11
|
+
return extendStatics(d, b);
|
|
12
|
+
};
|
|
13
|
+
function __extends(d, b) {
|
|
14
|
+
if (typeof b !== "function" && b !== null)
|
|
15
|
+
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
|
16
|
+
extendStatics(d, b);
|
|
17
|
+
function __() {
|
|
18
|
+
this.constructor = d;
|
|
19
|
+
}
|
|
20
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
21
|
+
}
|
|
22
|
+
function __values(o) {
|
|
23
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
24
|
+
if (m) return m.call(o);
|
|
25
|
+
if (o && typeof o.length === "number") return {
|
|
26
|
+
next: function() {
|
|
27
|
+
if (o && i >= o.length) o = void 0;
|
|
28
|
+
return { value: o && o[i++], done: !o };
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
32
|
+
}
|
|
33
|
+
function __read(o, n) {
|
|
34
|
+
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
35
|
+
if (!m) return o;
|
|
36
|
+
var i = m.call(o), r, ar = [], e;
|
|
37
|
+
try {
|
|
38
|
+
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
e = { error };
|
|
41
|
+
} finally {
|
|
42
|
+
try {
|
|
43
|
+
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
44
|
+
} finally {
|
|
45
|
+
if (e) throw e.error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return ar;
|
|
49
|
+
}
|
|
50
|
+
function __spreadArray(to, from, pack) {
|
|
51
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
52
|
+
if (ar || !(i in from)) {
|
|
53
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
54
|
+
ar[i] = from[i];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
58
|
+
}
|
|
59
|
+
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
|
|
60
|
+
var e = new Error(message);
|
|
61
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
62
|
+
};
|
|
63
|
+
function isFunction(value) {
|
|
64
|
+
return typeof value === "function";
|
|
65
|
+
}
|
|
66
|
+
function createErrorClass(createImpl) {
|
|
67
|
+
var _super = function(instance) {
|
|
68
|
+
Error.call(instance);
|
|
69
|
+
instance.stack = new Error().stack;
|
|
70
|
+
};
|
|
71
|
+
var ctorFunc = createImpl(_super);
|
|
72
|
+
ctorFunc.prototype = Object.create(Error.prototype);
|
|
73
|
+
ctorFunc.prototype.constructor = ctorFunc;
|
|
74
|
+
return ctorFunc;
|
|
75
|
+
}
|
|
76
|
+
var UnsubscriptionError = createErrorClass(function(_super) {
|
|
77
|
+
return function UnsubscriptionErrorImpl(errors) {
|
|
78
|
+
_super(this);
|
|
79
|
+
this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
|
|
80
|
+
return i + 1 + ") " + err.toString();
|
|
81
|
+
}).join("\n ") : "";
|
|
82
|
+
this.name = "UnsubscriptionError";
|
|
83
|
+
this.errors = errors;
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
function arrRemove(arr, item) {
|
|
87
|
+
if (arr) {
|
|
88
|
+
var index = arr.indexOf(item);
|
|
89
|
+
0 <= index && arr.splice(index, 1);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
var Subscription = (function() {
|
|
93
|
+
function Subscription2(initialTeardown) {
|
|
94
|
+
this.initialTeardown = initialTeardown;
|
|
95
|
+
this.closed = false;
|
|
96
|
+
this._parentage = null;
|
|
97
|
+
this._finalizers = null;
|
|
98
|
+
}
|
|
99
|
+
Subscription2.prototype.unsubscribe = function() {
|
|
100
|
+
var e_1, _a, e_2, _b;
|
|
101
|
+
var errors;
|
|
102
|
+
if (!this.closed) {
|
|
103
|
+
this.closed = true;
|
|
104
|
+
var _parentage = this._parentage;
|
|
105
|
+
if (_parentage) {
|
|
106
|
+
this._parentage = null;
|
|
107
|
+
if (Array.isArray(_parentage)) {
|
|
108
|
+
try {
|
|
109
|
+
for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
|
|
110
|
+
var parent_1 = _parentage_1_1.value;
|
|
111
|
+
parent_1.remove(this);
|
|
112
|
+
}
|
|
113
|
+
} catch (e_1_1) {
|
|
114
|
+
e_1 = { error: e_1_1 };
|
|
115
|
+
} finally {
|
|
116
|
+
try {
|
|
117
|
+
if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
|
|
118
|
+
} finally {
|
|
119
|
+
if (e_1) throw e_1.error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
_parentage.remove(this);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
var initialFinalizer = this.initialTeardown;
|
|
127
|
+
if (isFunction(initialFinalizer)) {
|
|
128
|
+
try {
|
|
129
|
+
initialFinalizer();
|
|
130
|
+
} catch (e) {
|
|
131
|
+
errors = e instanceof UnsubscriptionError ? e.errors : [e];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
var _finalizers = this._finalizers;
|
|
135
|
+
if (_finalizers) {
|
|
136
|
+
this._finalizers = null;
|
|
137
|
+
try {
|
|
138
|
+
for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
|
|
139
|
+
var finalizer = _finalizers_1_1.value;
|
|
140
|
+
try {
|
|
141
|
+
execFinalizer(finalizer);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
errors = errors !== null && errors !== void 0 ? errors : [];
|
|
144
|
+
if (err instanceof UnsubscriptionError) {
|
|
145
|
+
errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
|
|
146
|
+
} else {
|
|
147
|
+
errors.push(err);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch (e_2_1) {
|
|
152
|
+
e_2 = { error: e_2_1 };
|
|
153
|
+
} finally {
|
|
154
|
+
try {
|
|
155
|
+
if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
|
|
156
|
+
} finally {
|
|
157
|
+
if (e_2) throw e_2.error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (errors) {
|
|
162
|
+
throw new UnsubscriptionError(errors);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
Subscription2.prototype.add = function(teardown) {
|
|
167
|
+
var _a;
|
|
168
|
+
if (teardown && teardown !== this) {
|
|
169
|
+
if (this.closed) {
|
|
170
|
+
execFinalizer(teardown);
|
|
171
|
+
} else {
|
|
172
|
+
if (teardown instanceof Subscription2) {
|
|
173
|
+
if (teardown.closed || teardown._hasParent(this)) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
teardown._addParent(this);
|
|
177
|
+
}
|
|
178
|
+
(this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
Subscription2.prototype._hasParent = function(parent) {
|
|
183
|
+
var _parentage = this._parentage;
|
|
184
|
+
return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
|
|
185
|
+
};
|
|
186
|
+
Subscription2.prototype._addParent = function(parent) {
|
|
187
|
+
var _parentage = this._parentage;
|
|
188
|
+
this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
|
|
189
|
+
};
|
|
190
|
+
Subscription2.prototype._removeParent = function(parent) {
|
|
191
|
+
var _parentage = this._parentage;
|
|
192
|
+
if (_parentage === parent) {
|
|
193
|
+
this._parentage = null;
|
|
194
|
+
} else if (Array.isArray(_parentage)) {
|
|
195
|
+
arrRemove(_parentage, parent);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
Subscription2.prototype.remove = function(teardown) {
|
|
199
|
+
var _finalizers = this._finalizers;
|
|
200
|
+
_finalizers && arrRemove(_finalizers, teardown);
|
|
201
|
+
if (teardown instanceof Subscription2) {
|
|
202
|
+
teardown._removeParent(this);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
Subscription2.EMPTY = (function() {
|
|
206
|
+
var empty = new Subscription2();
|
|
207
|
+
empty.closed = true;
|
|
208
|
+
return empty;
|
|
209
|
+
})();
|
|
210
|
+
return Subscription2;
|
|
211
|
+
})();
|
|
212
|
+
var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
|
|
213
|
+
function isSubscription(value) {
|
|
214
|
+
return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
|
|
215
|
+
}
|
|
216
|
+
function execFinalizer(finalizer) {
|
|
217
|
+
if (isFunction(finalizer)) {
|
|
218
|
+
finalizer();
|
|
219
|
+
} else {
|
|
220
|
+
finalizer.unsubscribe();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
var config = {
|
|
224
|
+
Promise: void 0
|
|
225
|
+
};
|
|
226
|
+
var timeoutProvider = {
|
|
227
|
+
setTimeout: function(handler, timeout) {
|
|
228
|
+
var args = [];
|
|
229
|
+
for (var _i = 2; _i < arguments.length; _i++) {
|
|
230
|
+
args[_i - 2] = arguments[_i];
|
|
231
|
+
}
|
|
232
|
+
return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
|
|
233
|
+
},
|
|
234
|
+
clearTimeout: function(handle) {
|
|
235
|
+
return clearTimeout(handle);
|
|
236
|
+
},
|
|
237
|
+
delegate: void 0
|
|
238
|
+
};
|
|
239
|
+
function reportUnhandledError(err) {
|
|
240
|
+
timeoutProvider.setTimeout(function() {
|
|
241
|
+
{
|
|
242
|
+
throw err;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
function noop() {
|
|
247
|
+
}
|
|
248
|
+
function errorContext(cb) {
|
|
249
|
+
{
|
|
250
|
+
cb();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
var Subscriber = (function(_super) {
|
|
254
|
+
__extends(Subscriber2, _super);
|
|
255
|
+
function Subscriber2(destination) {
|
|
256
|
+
var _this = _super.call(this) || this;
|
|
257
|
+
_this.isStopped = false;
|
|
258
|
+
if (destination) {
|
|
259
|
+
_this.destination = destination;
|
|
260
|
+
if (isSubscription(destination)) {
|
|
261
|
+
destination.add(_this);
|
|
262
|
+
}
|
|
263
|
+
} else {
|
|
264
|
+
_this.destination = EMPTY_OBSERVER;
|
|
265
|
+
}
|
|
266
|
+
return _this;
|
|
267
|
+
}
|
|
268
|
+
Subscriber2.create = function(next, error, complete) {
|
|
269
|
+
return new SafeSubscriber(next, error, complete);
|
|
270
|
+
};
|
|
271
|
+
Subscriber2.prototype.next = function(value) {
|
|
272
|
+
if (this.isStopped) ;
|
|
273
|
+
else {
|
|
274
|
+
this._next(value);
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
Subscriber2.prototype.error = function(err) {
|
|
278
|
+
if (this.isStopped) ;
|
|
279
|
+
else {
|
|
280
|
+
this.isStopped = true;
|
|
281
|
+
this._error(err);
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
Subscriber2.prototype.complete = function() {
|
|
285
|
+
if (this.isStopped) ;
|
|
286
|
+
else {
|
|
287
|
+
this.isStopped = true;
|
|
288
|
+
this._complete();
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
Subscriber2.prototype.unsubscribe = function() {
|
|
292
|
+
if (!this.closed) {
|
|
293
|
+
this.isStopped = true;
|
|
294
|
+
_super.prototype.unsubscribe.call(this);
|
|
295
|
+
this.destination = null;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
Subscriber2.prototype._next = function(value) {
|
|
299
|
+
this.destination.next(value);
|
|
300
|
+
};
|
|
301
|
+
Subscriber2.prototype._error = function(err) {
|
|
302
|
+
try {
|
|
303
|
+
this.destination.error(err);
|
|
304
|
+
} finally {
|
|
305
|
+
this.unsubscribe();
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
Subscriber2.prototype._complete = function() {
|
|
309
|
+
try {
|
|
310
|
+
this.destination.complete();
|
|
311
|
+
} finally {
|
|
312
|
+
this.unsubscribe();
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
return Subscriber2;
|
|
316
|
+
})(Subscription);
|
|
317
|
+
var ConsumerObserver = (function() {
|
|
318
|
+
function ConsumerObserver2(partialObserver) {
|
|
319
|
+
this.partialObserver = partialObserver;
|
|
320
|
+
}
|
|
321
|
+
ConsumerObserver2.prototype.next = function(value) {
|
|
322
|
+
var partialObserver = this.partialObserver;
|
|
323
|
+
if (partialObserver.next) {
|
|
324
|
+
try {
|
|
325
|
+
partialObserver.next(value);
|
|
326
|
+
} catch (error) {
|
|
327
|
+
handleUnhandledError(error);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
ConsumerObserver2.prototype.error = function(err) {
|
|
332
|
+
var partialObserver = this.partialObserver;
|
|
333
|
+
if (partialObserver.error) {
|
|
334
|
+
try {
|
|
335
|
+
partialObserver.error(err);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
handleUnhandledError(error);
|
|
338
|
+
}
|
|
339
|
+
} else {
|
|
340
|
+
handleUnhandledError(err);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
ConsumerObserver2.prototype.complete = function() {
|
|
344
|
+
var partialObserver = this.partialObserver;
|
|
345
|
+
if (partialObserver.complete) {
|
|
346
|
+
try {
|
|
347
|
+
partialObserver.complete();
|
|
348
|
+
} catch (error) {
|
|
349
|
+
handleUnhandledError(error);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
return ConsumerObserver2;
|
|
354
|
+
})();
|
|
355
|
+
var SafeSubscriber = (function(_super) {
|
|
356
|
+
__extends(SafeSubscriber2, _super);
|
|
357
|
+
function SafeSubscriber2(observerOrNext, error, complete) {
|
|
358
|
+
var _this = _super.call(this) || this;
|
|
359
|
+
var partialObserver;
|
|
360
|
+
if (isFunction(observerOrNext) || !observerOrNext) {
|
|
361
|
+
partialObserver = {
|
|
362
|
+
next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
|
|
363
|
+
error: error !== null && error !== void 0 ? error : void 0,
|
|
364
|
+
complete: complete !== null && complete !== void 0 ? complete : void 0
|
|
365
|
+
};
|
|
366
|
+
} else {
|
|
367
|
+
{
|
|
368
|
+
partialObserver = observerOrNext;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
_this.destination = new ConsumerObserver(partialObserver);
|
|
372
|
+
return _this;
|
|
373
|
+
}
|
|
374
|
+
return SafeSubscriber2;
|
|
375
|
+
})(Subscriber);
|
|
376
|
+
function handleUnhandledError(error) {
|
|
377
|
+
{
|
|
378
|
+
reportUnhandledError(error);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
function defaultErrorHandler(err) {
|
|
382
|
+
throw err;
|
|
383
|
+
}
|
|
384
|
+
var EMPTY_OBSERVER = {
|
|
385
|
+
closed: true,
|
|
386
|
+
next: noop,
|
|
387
|
+
error: defaultErrorHandler,
|
|
388
|
+
complete: noop
|
|
389
|
+
};
|
|
390
|
+
var observable = (function() {
|
|
391
|
+
return typeof Symbol === "function" && Symbol.observable || "@@observable";
|
|
392
|
+
})();
|
|
393
|
+
function identity(x) {
|
|
394
|
+
return x;
|
|
395
|
+
}
|
|
396
|
+
function pipeFromArray(fns) {
|
|
397
|
+
if (fns.length === 0) {
|
|
398
|
+
return identity;
|
|
399
|
+
}
|
|
400
|
+
if (fns.length === 1) {
|
|
401
|
+
return fns[0];
|
|
402
|
+
}
|
|
403
|
+
return function piped(input) {
|
|
404
|
+
return fns.reduce(function(prev, fn) {
|
|
405
|
+
return fn(prev);
|
|
406
|
+
}, input);
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
var Observable = (function() {
|
|
410
|
+
function Observable2(subscribe) {
|
|
411
|
+
if (subscribe) {
|
|
412
|
+
this._subscribe = subscribe;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
Observable2.prototype.lift = function(operator) {
|
|
416
|
+
var observable2 = new Observable2();
|
|
417
|
+
observable2.source = this;
|
|
418
|
+
observable2.operator = operator;
|
|
419
|
+
return observable2;
|
|
420
|
+
};
|
|
421
|
+
Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
|
|
422
|
+
var _this = this;
|
|
423
|
+
var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
|
|
424
|
+
errorContext(function() {
|
|
425
|
+
var _a = _this, operator = _a.operator, source = _a.source;
|
|
426
|
+
subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
|
|
427
|
+
});
|
|
428
|
+
return subscriber;
|
|
429
|
+
};
|
|
430
|
+
Observable2.prototype._trySubscribe = function(sink) {
|
|
431
|
+
try {
|
|
432
|
+
return this._subscribe(sink);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
sink.error(err);
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
Observable2.prototype.forEach = function(next, promiseCtor) {
|
|
438
|
+
var _this = this;
|
|
439
|
+
promiseCtor = getPromiseCtor(promiseCtor);
|
|
440
|
+
return new promiseCtor(function(resolve, reject) {
|
|
441
|
+
var subscriber = new SafeSubscriber({
|
|
442
|
+
next: function(value) {
|
|
443
|
+
try {
|
|
444
|
+
next(value);
|
|
445
|
+
} catch (err) {
|
|
446
|
+
reject(err);
|
|
447
|
+
subscriber.unsubscribe();
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
error: reject,
|
|
451
|
+
complete: resolve
|
|
452
|
+
});
|
|
453
|
+
_this.subscribe(subscriber);
|
|
454
|
+
});
|
|
455
|
+
};
|
|
456
|
+
Observable2.prototype._subscribe = function(subscriber) {
|
|
457
|
+
var _a;
|
|
458
|
+
return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
|
|
459
|
+
};
|
|
460
|
+
Observable2.prototype[observable] = function() {
|
|
461
|
+
return this;
|
|
462
|
+
};
|
|
463
|
+
Observable2.prototype.pipe = function() {
|
|
464
|
+
var operations = [];
|
|
465
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
466
|
+
operations[_i] = arguments[_i];
|
|
467
|
+
}
|
|
468
|
+
return pipeFromArray(operations)(this);
|
|
469
|
+
};
|
|
470
|
+
Observable2.prototype.toPromise = function(promiseCtor) {
|
|
471
|
+
var _this = this;
|
|
472
|
+
promiseCtor = getPromiseCtor(promiseCtor);
|
|
473
|
+
return new promiseCtor(function(resolve, reject) {
|
|
474
|
+
var value;
|
|
475
|
+
_this.subscribe(function(x) {
|
|
476
|
+
return value = x;
|
|
477
|
+
}, function(err) {
|
|
478
|
+
return reject(err);
|
|
479
|
+
}, function() {
|
|
480
|
+
return resolve(value);
|
|
481
|
+
});
|
|
482
|
+
});
|
|
483
|
+
};
|
|
484
|
+
Observable2.create = function(subscribe) {
|
|
485
|
+
return new Observable2(subscribe);
|
|
486
|
+
};
|
|
487
|
+
return Observable2;
|
|
488
|
+
})();
|
|
489
|
+
function getPromiseCtor(promiseCtor) {
|
|
490
|
+
var _a;
|
|
491
|
+
return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
|
|
492
|
+
}
|
|
493
|
+
function isObserver(value) {
|
|
494
|
+
return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
|
|
495
|
+
}
|
|
496
|
+
function isSubscriber(value) {
|
|
497
|
+
return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
|
|
498
|
+
}
|
|
499
|
+
function hasLift(source) {
|
|
500
|
+
return isFunction(source === null || source === void 0 ? void 0 : source.lift);
|
|
501
|
+
}
|
|
502
|
+
function operate(init) {
|
|
503
|
+
return function(source) {
|
|
504
|
+
if (hasLift(source)) {
|
|
505
|
+
return source.lift(function(liftedSource) {
|
|
506
|
+
try {
|
|
507
|
+
return init(liftedSource, this);
|
|
508
|
+
} catch (err) {
|
|
509
|
+
this.error(err);
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
throw new TypeError("Unable to lift unknown Observable type");
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
|
|
517
|
+
return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
|
|
518
|
+
}
|
|
519
|
+
var OperatorSubscriber = (function(_super) {
|
|
520
|
+
__extends(OperatorSubscriber2, _super);
|
|
521
|
+
function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
|
|
522
|
+
var _this = _super.call(this, destination) || this;
|
|
523
|
+
_this.onFinalize = onFinalize;
|
|
524
|
+
_this.shouldUnsubscribe = shouldUnsubscribe;
|
|
525
|
+
_this._next = onNext ? function(value) {
|
|
526
|
+
try {
|
|
527
|
+
onNext(value);
|
|
528
|
+
} catch (err) {
|
|
529
|
+
destination.error(err);
|
|
530
|
+
}
|
|
531
|
+
} : _super.prototype._next;
|
|
532
|
+
_this._error = onError ? function(err) {
|
|
533
|
+
try {
|
|
534
|
+
onError(err);
|
|
535
|
+
} catch (err2) {
|
|
536
|
+
destination.error(err2);
|
|
537
|
+
} finally {
|
|
538
|
+
this.unsubscribe();
|
|
539
|
+
}
|
|
540
|
+
} : _super.prototype._error;
|
|
541
|
+
_this._complete = onComplete ? function() {
|
|
542
|
+
try {
|
|
543
|
+
onComplete();
|
|
544
|
+
} catch (err) {
|
|
545
|
+
destination.error(err);
|
|
546
|
+
} finally {
|
|
547
|
+
this.unsubscribe();
|
|
548
|
+
}
|
|
549
|
+
} : _super.prototype._complete;
|
|
550
|
+
return _this;
|
|
551
|
+
}
|
|
552
|
+
OperatorSubscriber2.prototype.unsubscribe = function() {
|
|
553
|
+
var _a;
|
|
554
|
+
if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
|
|
555
|
+
var closed_1 = this.closed;
|
|
556
|
+
_super.prototype.unsubscribe.call(this);
|
|
557
|
+
!closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
return OperatorSubscriber2;
|
|
561
|
+
})(Subscriber);
|
|
562
|
+
var ObjectUnsubscribedError = createErrorClass(function(_super) {
|
|
563
|
+
return function ObjectUnsubscribedErrorImpl() {
|
|
564
|
+
_super(this);
|
|
565
|
+
this.name = "ObjectUnsubscribedError";
|
|
566
|
+
this.message = "object unsubscribed";
|
|
567
|
+
};
|
|
568
|
+
});
|
|
569
|
+
var Subject = (function(_super) {
|
|
570
|
+
__extends(Subject2, _super);
|
|
571
|
+
function Subject2() {
|
|
572
|
+
var _this = _super.call(this) || this;
|
|
573
|
+
_this.closed = false;
|
|
574
|
+
_this.currentObservers = null;
|
|
575
|
+
_this.observers = [];
|
|
576
|
+
_this.isStopped = false;
|
|
577
|
+
_this.hasError = false;
|
|
578
|
+
_this.thrownError = null;
|
|
579
|
+
return _this;
|
|
580
|
+
}
|
|
581
|
+
Subject2.prototype.lift = function(operator) {
|
|
582
|
+
var subject = new AnonymousSubject(this, this);
|
|
583
|
+
subject.operator = operator;
|
|
584
|
+
return subject;
|
|
585
|
+
};
|
|
586
|
+
Subject2.prototype._throwIfClosed = function() {
|
|
587
|
+
if (this.closed) {
|
|
588
|
+
throw new ObjectUnsubscribedError();
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
Subject2.prototype.next = function(value) {
|
|
592
|
+
var _this = this;
|
|
593
|
+
errorContext(function() {
|
|
594
|
+
var e_1, _a;
|
|
595
|
+
_this._throwIfClosed();
|
|
596
|
+
if (!_this.isStopped) {
|
|
597
|
+
if (!_this.currentObservers) {
|
|
598
|
+
_this.currentObservers = Array.from(_this.observers);
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
|
|
602
|
+
var observer = _c.value;
|
|
603
|
+
observer.next(value);
|
|
604
|
+
}
|
|
605
|
+
} catch (e_1_1) {
|
|
606
|
+
e_1 = { error: e_1_1 };
|
|
607
|
+
} finally {
|
|
608
|
+
try {
|
|
609
|
+
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
610
|
+
} finally {
|
|
611
|
+
if (e_1) throw e_1.error;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
};
|
|
617
|
+
Subject2.prototype.error = function(err) {
|
|
618
|
+
var _this = this;
|
|
619
|
+
errorContext(function() {
|
|
620
|
+
_this._throwIfClosed();
|
|
621
|
+
if (!_this.isStopped) {
|
|
622
|
+
_this.hasError = _this.isStopped = true;
|
|
623
|
+
_this.thrownError = err;
|
|
624
|
+
var observers = _this.observers;
|
|
625
|
+
while (observers.length) {
|
|
626
|
+
observers.shift().error(err);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
});
|
|
630
|
+
};
|
|
631
|
+
Subject2.prototype.complete = function() {
|
|
632
|
+
var _this = this;
|
|
633
|
+
errorContext(function() {
|
|
634
|
+
_this._throwIfClosed();
|
|
635
|
+
if (!_this.isStopped) {
|
|
636
|
+
_this.isStopped = true;
|
|
637
|
+
var observers = _this.observers;
|
|
638
|
+
while (observers.length) {
|
|
639
|
+
observers.shift().complete();
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
};
|
|
644
|
+
Subject2.prototype.unsubscribe = function() {
|
|
645
|
+
this.isStopped = this.closed = true;
|
|
646
|
+
this.observers = this.currentObservers = null;
|
|
647
|
+
};
|
|
648
|
+
Object.defineProperty(Subject2.prototype, "observed", {
|
|
649
|
+
get: function() {
|
|
650
|
+
var _a;
|
|
651
|
+
return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
|
|
652
|
+
},
|
|
653
|
+
enumerable: false,
|
|
654
|
+
configurable: true
|
|
655
|
+
});
|
|
656
|
+
Subject2.prototype._trySubscribe = function(subscriber) {
|
|
657
|
+
this._throwIfClosed();
|
|
658
|
+
return _super.prototype._trySubscribe.call(this, subscriber);
|
|
659
|
+
};
|
|
660
|
+
Subject2.prototype._subscribe = function(subscriber) {
|
|
661
|
+
this._throwIfClosed();
|
|
662
|
+
this._checkFinalizedStatuses(subscriber);
|
|
663
|
+
return this._innerSubscribe(subscriber);
|
|
664
|
+
};
|
|
665
|
+
Subject2.prototype._innerSubscribe = function(subscriber) {
|
|
666
|
+
var _this = this;
|
|
667
|
+
var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
|
|
668
|
+
if (hasError || isStopped) {
|
|
669
|
+
return EMPTY_SUBSCRIPTION;
|
|
670
|
+
}
|
|
671
|
+
this.currentObservers = null;
|
|
672
|
+
observers.push(subscriber);
|
|
673
|
+
return new Subscription(function() {
|
|
674
|
+
_this.currentObservers = null;
|
|
675
|
+
arrRemove(observers, subscriber);
|
|
676
|
+
});
|
|
677
|
+
};
|
|
678
|
+
Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
|
|
679
|
+
var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
|
|
680
|
+
if (hasError) {
|
|
681
|
+
subscriber.error(thrownError);
|
|
682
|
+
} else if (isStopped) {
|
|
683
|
+
subscriber.complete();
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
Subject2.prototype.asObservable = function() {
|
|
687
|
+
var observable2 = new Observable();
|
|
688
|
+
observable2.source = this;
|
|
689
|
+
return observable2;
|
|
690
|
+
};
|
|
691
|
+
Subject2.create = function(destination, source) {
|
|
692
|
+
return new AnonymousSubject(destination, source);
|
|
693
|
+
};
|
|
694
|
+
return Subject2;
|
|
695
|
+
})(Observable);
|
|
696
|
+
var AnonymousSubject = (function(_super) {
|
|
697
|
+
__extends(AnonymousSubject2, _super);
|
|
698
|
+
function AnonymousSubject2(destination, source) {
|
|
699
|
+
var _this = _super.call(this) || this;
|
|
700
|
+
_this.destination = destination;
|
|
701
|
+
_this.source = source;
|
|
702
|
+
return _this;
|
|
703
|
+
}
|
|
704
|
+
AnonymousSubject2.prototype.next = function(value) {
|
|
705
|
+
var _a, _b;
|
|
706
|
+
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
|
|
707
|
+
};
|
|
708
|
+
AnonymousSubject2.prototype.error = function(err) {
|
|
709
|
+
var _a, _b;
|
|
710
|
+
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
|
|
711
|
+
};
|
|
712
|
+
AnonymousSubject2.prototype.complete = function() {
|
|
713
|
+
var _a, _b;
|
|
714
|
+
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
715
|
+
};
|
|
716
|
+
AnonymousSubject2.prototype._subscribe = function(subscriber) {
|
|
717
|
+
var _a, _b;
|
|
718
|
+
return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
|
|
719
|
+
};
|
|
720
|
+
return AnonymousSubject2;
|
|
721
|
+
})(Subject);
|
|
722
|
+
var EMPTY = new Observable(function(subscriber) {
|
|
723
|
+
return subscriber.complete();
|
|
724
|
+
});
|
|
725
|
+
function filter(predicate, thisArg) {
|
|
726
|
+
return operate(function(source, subscriber) {
|
|
727
|
+
var index = 0;
|
|
728
|
+
source.subscribe(createOperatorSubscriber(subscriber, function(value) {
|
|
729
|
+
return predicate.call(thisArg, value, index++) && subscriber.next(value);
|
|
730
|
+
}));
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
function take(count) {
|
|
734
|
+
return count <= 0 ? function() {
|
|
735
|
+
return EMPTY;
|
|
736
|
+
} : operate(function(source, subscriber) {
|
|
737
|
+
var seen = 0;
|
|
738
|
+
source.subscribe(createOperatorSubscriber(subscriber, function(value) {
|
|
739
|
+
if (++seen <= count) {
|
|
740
|
+
subscriber.next(value);
|
|
741
|
+
if (count <= seen) {
|
|
742
|
+
subscriber.complete();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
}));
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
var logger$1 = createLogger("core/AgentStateMachine");
|
|
749
|
+
var AgentStateMachine = class {
|
|
750
|
+
constructor() {
|
|
751
|
+
__publicField(this, "_state", "idle");
|
|
752
|
+
__publicField(this, "handlers", /* @__PURE__ */ new Set());
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Current agent state
|
|
756
|
+
*/
|
|
757
|
+
get state() {
|
|
758
|
+
return this._state;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Process a StateEvent and update internal state
|
|
762
|
+
*
|
|
763
|
+
* @param event - StateEvent from Engine layer
|
|
764
|
+
*/
|
|
765
|
+
process(event) {
|
|
766
|
+
const prev = this._state;
|
|
767
|
+
const next = this.mapEventToState(event);
|
|
768
|
+
if (next !== null && prev !== next) {
|
|
769
|
+
this._state = next;
|
|
770
|
+
logger$1.debug("State transition", {
|
|
771
|
+
eventType: event.type,
|
|
772
|
+
from: prev,
|
|
773
|
+
to: next
|
|
774
|
+
});
|
|
775
|
+
this.notifyHandlers({ prev, current: next });
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Subscribe to state changes
|
|
780
|
+
*
|
|
781
|
+
* @param handler - Callback receiving { prev, current } state change
|
|
782
|
+
* @returns Unsubscribe function
|
|
783
|
+
*/
|
|
784
|
+
onStateChange(handler) {
|
|
785
|
+
this.handlers.add(handler);
|
|
786
|
+
return () => {
|
|
787
|
+
this.handlers.delete(handler);
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Reset state machine (used on destroy)
|
|
792
|
+
*/
|
|
793
|
+
reset() {
|
|
794
|
+
this._state;
|
|
795
|
+
this._state = "idle";
|
|
796
|
+
this.handlers.clear();
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Map StateEvent type to AgentState
|
|
800
|
+
*
|
|
801
|
+
* @param event - StateEvent from Engine
|
|
802
|
+
* @returns New AgentState or null if no transition needed
|
|
803
|
+
*/
|
|
804
|
+
mapEventToState(event) {
|
|
805
|
+
switch (event.type) {
|
|
806
|
+
// Agent lifecycle
|
|
807
|
+
case "agent_initializing":
|
|
808
|
+
return "initializing";
|
|
809
|
+
case "agent_ready":
|
|
810
|
+
return "idle";
|
|
811
|
+
case "agent_destroyed":
|
|
812
|
+
return "idle";
|
|
813
|
+
// Conversation lifecycle
|
|
814
|
+
case "conversation_queued":
|
|
815
|
+
return "queued";
|
|
816
|
+
case "conversation_start":
|
|
817
|
+
return "conversation_active";
|
|
818
|
+
case "conversation_thinking":
|
|
819
|
+
return "thinking";
|
|
820
|
+
case "conversation_responding":
|
|
821
|
+
return "responding";
|
|
822
|
+
case "conversation_end":
|
|
823
|
+
return "idle";
|
|
824
|
+
case "conversation_interrupted":
|
|
825
|
+
return "idle";
|
|
826
|
+
// Return to idle on interrupt
|
|
827
|
+
// Tool lifecycle
|
|
828
|
+
case "tool_planned":
|
|
829
|
+
return "planning_tool";
|
|
830
|
+
case "tool_executing":
|
|
831
|
+
return "awaiting_tool_result";
|
|
832
|
+
case "tool_completed":
|
|
833
|
+
return "responding";
|
|
834
|
+
// Back to responding after tool completes
|
|
835
|
+
case "tool_failed":
|
|
836
|
+
return "responding";
|
|
837
|
+
// Continue responding after tool failure
|
|
838
|
+
// Error
|
|
839
|
+
case "error_occurred":
|
|
840
|
+
return "idle";
|
|
841
|
+
// Reset to idle on error
|
|
842
|
+
default:
|
|
843
|
+
return null;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Notify all registered handlers of state change
|
|
848
|
+
*/
|
|
849
|
+
notifyHandlers(change) {
|
|
850
|
+
for (const handler of this.handlers) {
|
|
851
|
+
try {
|
|
852
|
+
handler(change);
|
|
853
|
+
} catch (error) {
|
|
854
|
+
logger$1.error("State change handler error", {
|
|
855
|
+
from: change.prev,
|
|
856
|
+
to: change.current,
|
|
857
|
+
error
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
var logger2$2 = createLogger("core/AgentEventBus");
|
|
864
|
+
var AgentEventBus = class {
|
|
865
|
+
constructor() {
|
|
866
|
+
__publicField(this, "subject", new Subject());
|
|
867
|
+
__publicField(this, "typeSubscriptions", /* @__PURE__ */ new Map());
|
|
868
|
+
__publicField(this, "globalSubscriptions", []);
|
|
869
|
+
__publicField(this, "nextId", 0);
|
|
870
|
+
__publicField(this, "isDestroyed", false);
|
|
871
|
+
// Cached views
|
|
872
|
+
__publicField(this, "producerView", null);
|
|
873
|
+
__publicField(this, "consumerView", null);
|
|
874
|
+
}
|
|
875
|
+
// ===== Producer Methods =====
|
|
876
|
+
emit(event) {
|
|
877
|
+
if (this.isDestroyed) {
|
|
878
|
+
logger2$2.warn("Emit called on destroyed EventBus", { eventType: event.type });
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
this.subject.next(event);
|
|
882
|
+
}
|
|
883
|
+
emitBatch(events) {
|
|
884
|
+
for (const event of events) {
|
|
885
|
+
this.emit(event);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
on(typeOrTypes, handler, options = {}) {
|
|
889
|
+
if (this.isDestroyed) {
|
|
890
|
+
logger2$2.warn("Subscribe called on destroyed EventBus");
|
|
891
|
+
return () => {
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes];
|
|
895
|
+
const unsubscribes = [];
|
|
896
|
+
for (const type of types) {
|
|
897
|
+
const unsub = this.subscribeToType(type, handler, options);
|
|
898
|
+
unsubscribes.push(unsub);
|
|
899
|
+
}
|
|
900
|
+
return () => unsubscribes.forEach((u) => u());
|
|
901
|
+
}
|
|
902
|
+
onAny(handler, options = {}) {
|
|
903
|
+
if (this.isDestroyed) {
|
|
904
|
+
logger2$2.warn("Subscribe called on destroyed EventBus");
|
|
905
|
+
return () => {
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
return this.subscribeGlobal(handler, options);
|
|
909
|
+
}
|
|
910
|
+
once(type, handler) {
|
|
911
|
+
return this.on(type, handler, { once: true });
|
|
912
|
+
}
|
|
913
|
+
// ===== View Methods =====
|
|
914
|
+
asConsumer() {
|
|
915
|
+
if (!this.consumerView) {
|
|
916
|
+
this.consumerView = {
|
|
917
|
+
on: this.on.bind(this),
|
|
918
|
+
onAny: this.onAny.bind(this),
|
|
919
|
+
once: this.once.bind(this)
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
return this.consumerView;
|
|
923
|
+
}
|
|
924
|
+
asProducer() {
|
|
925
|
+
if (!this.producerView) {
|
|
926
|
+
this.producerView = {
|
|
927
|
+
emit: this.emit.bind(this),
|
|
928
|
+
emitBatch: this.emitBatch.bind(this)
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
return this.producerView;
|
|
932
|
+
}
|
|
933
|
+
// ===== Lifecycle =====
|
|
934
|
+
destroy() {
|
|
935
|
+
if (this.isDestroyed) return;
|
|
936
|
+
this.isDestroyed = true;
|
|
937
|
+
for (const records of this.typeSubscriptions.values()) {
|
|
938
|
+
for (const record of records) {
|
|
939
|
+
record.unsubscribe();
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
this.typeSubscriptions.clear();
|
|
943
|
+
for (const record of this.globalSubscriptions) {
|
|
944
|
+
record.unsubscribe();
|
|
945
|
+
}
|
|
946
|
+
this.globalSubscriptions.length = 0;
|
|
947
|
+
this.subject.complete();
|
|
948
|
+
logger2$2.debug("EventBus destroyed");
|
|
949
|
+
}
|
|
950
|
+
// ===== Private Methods =====
|
|
951
|
+
subscribeToType(type, handler, options) {
|
|
952
|
+
const { filter: filter$1, priority = 0, once = false } = options;
|
|
953
|
+
const id = this.nextId++;
|
|
954
|
+
let observable2 = this.subject.pipe(filter((e) => e.type === type));
|
|
955
|
+
if (filter$1) {
|
|
956
|
+
observable2 = observable2.pipe(filter(filter$1));
|
|
957
|
+
}
|
|
958
|
+
if (once) {
|
|
959
|
+
observable2 = observable2.pipe(take(1));
|
|
960
|
+
}
|
|
961
|
+
const subscription = observable2.subscribe({
|
|
962
|
+
next: (event) => {
|
|
963
|
+
this.executeWithPriority(type, event, handler, id);
|
|
964
|
+
}
|
|
965
|
+
});
|
|
966
|
+
const unsubscribe = () => {
|
|
967
|
+
subscription.unsubscribe();
|
|
968
|
+
const records2 = this.typeSubscriptions.get(type);
|
|
969
|
+
if (records2) {
|
|
970
|
+
const idx = records2.findIndex((r) => r.id === id);
|
|
971
|
+
if (idx !== -1) records2.splice(idx, 1);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
if (!this.typeSubscriptions.has(type)) {
|
|
975
|
+
this.typeSubscriptions.set(type, []);
|
|
976
|
+
}
|
|
977
|
+
const record = { id, priority, handler, unsubscribe };
|
|
978
|
+
const records = this.typeSubscriptions.get(type);
|
|
979
|
+
records.push(record);
|
|
980
|
+
records.sort((a, b) => b.priority - a.priority);
|
|
981
|
+
return unsubscribe;
|
|
982
|
+
}
|
|
983
|
+
subscribeGlobal(handler, options) {
|
|
984
|
+
const { filter: filter$1, priority = 0, once = false } = options;
|
|
985
|
+
const id = this.nextId++;
|
|
986
|
+
let observable2 = this.subject.asObservable();
|
|
987
|
+
if (filter$1) {
|
|
988
|
+
observable2 = observable2.pipe(filter(filter$1));
|
|
989
|
+
}
|
|
990
|
+
if (once) {
|
|
991
|
+
observable2 = observable2.pipe(take(1));
|
|
992
|
+
}
|
|
993
|
+
const subscription = observable2.subscribe({
|
|
994
|
+
next: (event) => {
|
|
995
|
+
this.executeGlobalWithPriority(event, handler, id);
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
const unsubscribe = () => {
|
|
999
|
+
subscription.unsubscribe();
|
|
1000
|
+
const idx = this.globalSubscriptions.findIndex((r) => r.id === id);
|
|
1001
|
+
if (idx !== -1) this.globalSubscriptions.splice(idx, 1);
|
|
1002
|
+
};
|
|
1003
|
+
const record = { id, priority, handler, unsubscribe };
|
|
1004
|
+
this.globalSubscriptions.push(record);
|
|
1005
|
+
this.globalSubscriptions.sort((a, b) => b.priority - a.priority);
|
|
1006
|
+
return unsubscribe;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Execute handler respecting priority order for typed subscriptions
|
|
1010
|
+
*/
|
|
1011
|
+
executeWithPriority(type, event, handler, handlerId) {
|
|
1012
|
+
const records = this.typeSubscriptions.get(type) || [];
|
|
1013
|
+
const record = records.find((r) => r.id === handlerId);
|
|
1014
|
+
if (record) {
|
|
1015
|
+
try {
|
|
1016
|
+
handler(event);
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
logger2$2.error("Event handler error", { eventType: type, error });
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Execute handler respecting priority order for global subscriptions
|
|
1024
|
+
*/
|
|
1025
|
+
executeGlobalWithPriority(event, handler, handlerId) {
|
|
1026
|
+
const record = this.globalSubscriptions.find((r) => r.id === handlerId);
|
|
1027
|
+
if (record) {
|
|
1028
|
+
try {
|
|
1029
|
+
handler(event);
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
logger2$2.error("Global event handler error", { eventType: event.type, error });
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
var AgentErrorClassifier = class {
|
|
1037
|
+
constructor(agentId) {
|
|
1038
|
+
this.agentId = agentId;
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* Classify an unknown error into an AgentError
|
|
1042
|
+
*/
|
|
1043
|
+
classify(error) {
|
|
1044
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1045
|
+
const message = err.message;
|
|
1046
|
+
if (message.includes("rate limit") || message.includes("429")) {
|
|
1047
|
+
return this.create("llm", "RATE_LIMITED", message, true, err);
|
|
1048
|
+
}
|
|
1049
|
+
if (message.includes("api key") || message.includes("401") || message.includes("unauthorized")) {
|
|
1050
|
+
return this.create("llm", "INVALID_API_KEY", message, false, err);
|
|
1051
|
+
}
|
|
1052
|
+
if (message.includes("context") && message.includes("long")) {
|
|
1053
|
+
return this.create("llm", "CONTEXT_TOO_LONG", message, true, err);
|
|
1054
|
+
}
|
|
1055
|
+
if (message.includes("overloaded") || message.includes("503")) {
|
|
1056
|
+
return this.create("llm", "OVERLOADED", message, true, err);
|
|
1057
|
+
}
|
|
1058
|
+
if (message.includes("timeout") || message.includes("ETIMEDOUT")) {
|
|
1059
|
+
return this.create("network", "TIMEOUT", message, true, err);
|
|
1060
|
+
}
|
|
1061
|
+
if (message.includes("ECONNREFUSED") || message.includes("connection")) {
|
|
1062
|
+
return this.create("network", "CONNECTION_FAILED", message, true, err);
|
|
1063
|
+
}
|
|
1064
|
+
if (message.includes("network") || message.includes("fetch")) {
|
|
1065
|
+
return this.create("network", "CONNECTION_FAILED", message, true, err);
|
|
1066
|
+
}
|
|
1067
|
+
if (message.includes("driver")) {
|
|
1068
|
+
return this.create("driver", "RECEIVE_FAILED", message, true, err);
|
|
1069
|
+
}
|
|
1070
|
+
return this.create("system", "UNKNOWN", message, true, err);
|
|
1071
|
+
}
|
|
1072
|
+
/**
|
|
1073
|
+
* Create an AgentError with the specified category and code
|
|
1074
|
+
*/
|
|
1075
|
+
create(category, code, message, recoverable, cause) {
|
|
1076
|
+
return {
|
|
1077
|
+
category,
|
|
1078
|
+
code,
|
|
1079
|
+
message,
|
|
1080
|
+
severity: recoverable ? "error" : "fatal",
|
|
1081
|
+
recoverable,
|
|
1082
|
+
cause
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* Create an ErrorEvent from an AgentError
|
|
1087
|
+
*
|
|
1088
|
+
* ErrorEvent is independent from Message layer and transportable via SSE.
|
|
1089
|
+
*/
|
|
1090
|
+
createEvent(error) {
|
|
1091
|
+
return {
|
|
1092
|
+
type: "error",
|
|
1093
|
+
uuid: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1094
|
+
agentId: this.agentId,
|
|
1095
|
+
timestamp: Date.now(),
|
|
1096
|
+
data: {
|
|
1097
|
+
error
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
var MiddlewareChain = class {
|
|
1103
|
+
constructor() {
|
|
1104
|
+
__publicField(this, "middlewares", []);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Add middleware to the chain
|
|
1108
|
+
*
|
|
1109
|
+
* @param middleware - Middleware function
|
|
1110
|
+
* @returns Unsubscribe function to remove the middleware
|
|
1111
|
+
*/
|
|
1112
|
+
use(middleware) {
|
|
1113
|
+
this.middlewares.push(middleware);
|
|
1114
|
+
return () => {
|
|
1115
|
+
const index = this.middlewares.indexOf(middleware);
|
|
1116
|
+
if (index !== -1) {
|
|
1117
|
+
this.middlewares.splice(index, 1);
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
/**
|
|
1122
|
+
* Execute the middleware chain
|
|
1123
|
+
*
|
|
1124
|
+
* @param message - User message to process
|
|
1125
|
+
* @param finalHandler - Handler called at the end of the chain
|
|
1126
|
+
*/
|
|
1127
|
+
async execute(message, finalHandler) {
|
|
1128
|
+
let index = 0;
|
|
1129
|
+
const next = async (msg) => {
|
|
1130
|
+
if (index < this.middlewares.length) {
|
|
1131
|
+
const middleware = this.middlewares[index++];
|
|
1132
|
+
await middleware(msg, next);
|
|
1133
|
+
} else {
|
|
1134
|
+
await finalHandler(msg);
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
await next(message);
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Clear all middlewares
|
|
1141
|
+
*/
|
|
1142
|
+
clear() {
|
|
1143
|
+
this.middlewares.length = 0;
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Get the number of middlewares
|
|
1147
|
+
*/
|
|
1148
|
+
get size() {
|
|
1149
|
+
return this.middlewares.length;
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
var logger3$2 = createLogger("core/InterceptorChain");
|
|
1153
|
+
var InterceptorChain = class {
|
|
1154
|
+
constructor(agentId) {
|
|
1155
|
+
__publicField(this, "interceptors", []);
|
|
1156
|
+
__publicField(this, "agentId");
|
|
1157
|
+
this.agentId = agentId;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Add interceptor to the chain
|
|
1161
|
+
*
|
|
1162
|
+
* @param interceptor - Interceptor function
|
|
1163
|
+
* @returns Unsubscribe function to remove the interceptor
|
|
1164
|
+
*/
|
|
1165
|
+
intercept(interceptor) {
|
|
1166
|
+
this.interceptors.push(interceptor);
|
|
1167
|
+
return () => {
|
|
1168
|
+
const index = this.interceptors.indexOf(interceptor);
|
|
1169
|
+
if (index !== -1) {
|
|
1170
|
+
this.interceptors.splice(index, 1);
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Execute the interceptor chain
|
|
1176
|
+
*
|
|
1177
|
+
* @param event - Event to process
|
|
1178
|
+
* @param finalHandler - Handler called at the end of the chain
|
|
1179
|
+
*/
|
|
1180
|
+
execute(event, finalHandler) {
|
|
1181
|
+
let index = 0;
|
|
1182
|
+
const next = (e) => {
|
|
1183
|
+
if (index < this.interceptors.length) {
|
|
1184
|
+
const interceptor = this.interceptors[index++];
|
|
1185
|
+
try {
|
|
1186
|
+
interceptor(e, next);
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
logger3$2.error("Interceptor error", {
|
|
1189
|
+
agentId: this.agentId,
|
|
1190
|
+
eventType: e.type,
|
|
1191
|
+
interceptorIndex: index - 1,
|
|
1192
|
+
error
|
|
1193
|
+
});
|
|
1194
|
+
next(e);
|
|
1195
|
+
}
|
|
1196
|
+
} else {
|
|
1197
|
+
finalHandler(e);
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
next(event);
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Clear all interceptors
|
|
1204
|
+
*/
|
|
1205
|
+
clear() {
|
|
1206
|
+
this.interceptors.length = 0;
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Get the number of interceptors
|
|
1210
|
+
*/
|
|
1211
|
+
get size() {
|
|
1212
|
+
return this.interceptors.length;
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
var REACT_TO_EVENT_MAP = {
|
|
1216
|
+
// Stream Layer Events
|
|
1217
|
+
onMessageStart: "message_start",
|
|
1218
|
+
onMessageDelta: "message_delta",
|
|
1219
|
+
onMessageStop: "message_stop",
|
|
1220
|
+
onTextContentBlockStart: "text_content_block_start",
|
|
1221
|
+
onTextDelta: "text_delta",
|
|
1222
|
+
onTextContentBlockStop: "text_content_block_stop",
|
|
1223
|
+
onToolUseContentBlockStart: "tool_use_content_block_start",
|
|
1224
|
+
onInputJsonDelta: "input_json_delta",
|
|
1225
|
+
onToolUseContentBlockStop: "tool_use_content_block_stop",
|
|
1226
|
+
onToolCall: "tool_call",
|
|
1227
|
+
onToolResult: "tool_result",
|
|
1228
|
+
// Message Layer Events
|
|
1229
|
+
onUserMessage: "user_message",
|
|
1230
|
+
onAssistantMessage: "assistant_message",
|
|
1231
|
+
onToolCallMessage: "tool_call_message",
|
|
1232
|
+
onToolResultMessage: "tool_result_message",
|
|
1233
|
+
// Error Layer Events (independent, transportable via SSE)
|
|
1234
|
+
onError: "error",
|
|
1235
|
+
// Turn Layer Events
|
|
1236
|
+
onTurnRequest: "turn_request",
|
|
1237
|
+
onTurnResponse: "turn_response"
|
|
1238
|
+
};
|
|
1239
|
+
function mapReactHandlers(reactHandlers) {
|
|
1240
|
+
const eventHandlerMap = {};
|
|
1241
|
+
for (const [reactKey, eventKey] of Object.entries(REACT_TO_EVENT_MAP)) {
|
|
1242
|
+
const handler = reactHandlers[reactKey];
|
|
1243
|
+
if (handler) {
|
|
1244
|
+
eventHandlerMap[eventKey] = handler;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return eventHandlerMap;
|
|
1248
|
+
}
|
|
1249
|
+
var logger4$1 = createLogger("core/AgentInstance");
|
|
1250
|
+
var AgentInstance = class {
|
|
1251
|
+
constructor(definition, context, engine, driver, sandbox) {
|
|
1252
|
+
__publicField(this, "agentId");
|
|
1253
|
+
__publicField(this, "definition");
|
|
1254
|
+
__publicField(this, "context");
|
|
1255
|
+
__publicField(this, "createdAt");
|
|
1256
|
+
__publicField(this, "sandbox");
|
|
1257
|
+
__publicField(this, "_lifecycle", "running");
|
|
1258
|
+
__publicField(this, "engine");
|
|
1259
|
+
/**
|
|
1260
|
+
* Driver instance - created from definition.driver class
|
|
1261
|
+
*/
|
|
1262
|
+
__publicField(this, "driver");
|
|
1263
|
+
/**
|
|
1264
|
+
* State machine - manages state transitions driven by StateEvents
|
|
1265
|
+
*/
|
|
1266
|
+
__publicField(this, "stateMachine", new AgentStateMachine());
|
|
1267
|
+
/**
|
|
1268
|
+
* Event bus - centralized event pub/sub
|
|
1269
|
+
*/
|
|
1270
|
+
__publicField(this, "eventBus", new AgentEventBus());
|
|
1271
|
+
/**
|
|
1272
|
+
* Error classifier - classifies and creates error events
|
|
1273
|
+
*/
|
|
1274
|
+
__publicField(this, "errorClassifier");
|
|
1275
|
+
/**
|
|
1276
|
+
* Middleware chain for receive() interception
|
|
1277
|
+
*/
|
|
1278
|
+
__publicField(this, "middlewareChain", new MiddlewareChain());
|
|
1279
|
+
/**
|
|
1280
|
+
* Interceptor chain for event dispatch interception
|
|
1281
|
+
*/
|
|
1282
|
+
__publicField(this, "interceptorChain");
|
|
1283
|
+
/**
|
|
1284
|
+
* Lifecycle handlers for onReady
|
|
1285
|
+
*/
|
|
1286
|
+
__publicField(this, "readyHandlers", /* @__PURE__ */ new Set());
|
|
1287
|
+
/**
|
|
1288
|
+
* Lifecycle handlers for onDestroy
|
|
1289
|
+
*/
|
|
1290
|
+
__publicField(this, "destroyHandlers", /* @__PURE__ */ new Set());
|
|
1291
|
+
this.agentId = context.agentId;
|
|
1292
|
+
this.definition = definition;
|
|
1293
|
+
this.context = context;
|
|
1294
|
+
this.engine = engine;
|
|
1295
|
+
this.createdAt = context.createdAt;
|
|
1296
|
+
this.sandbox = sandbox;
|
|
1297
|
+
this.driver = driver;
|
|
1298
|
+
this.errorClassifier = new AgentErrorClassifier(this.agentId);
|
|
1299
|
+
this.interceptorChain = new InterceptorChain(this.agentId);
|
|
1300
|
+
logger4$1.debug("AgentInstance created", {
|
|
1301
|
+
agentId: this.agentId,
|
|
1302
|
+
definitionName: definition.name,
|
|
1303
|
+
driverName: this.driver.name
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Current lifecycle state
|
|
1308
|
+
*/
|
|
1309
|
+
get lifecycle() {
|
|
1310
|
+
return this._lifecycle;
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Current conversation state (delegated to StateMachine)
|
|
1314
|
+
*/
|
|
1315
|
+
get state() {
|
|
1316
|
+
return this.stateMachine.state;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Receive a message from user
|
|
1320
|
+
*
|
|
1321
|
+
* Runs through middleware chain before actual processing.
|
|
1322
|
+
*
|
|
1323
|
+
* Error Handling:
|
|
1324
|
+
* - Errors are caught and converted to ErrorMessageEvent
|
|
1325
|
+
* - Handlers receive the error event before re-throwing
|
|
1326
|
+
* - This ensures UI can display errors
|
|
1327
|
+
*/
|
|
1328
|
+
async receive(message) {
|
|
1329
|
+
if (this._lifecycle === "destroyed") {
|
|
1330
|
+
logger4$1.warn("Receive called on destroyed agent", { agentId: this.agentId });
|
|
1331
|
+
const error = this.errorClassifier.create(
|
|
1332
|
+
"system",
|
|
1333
|
+
"AGENT_DESTROYED",
|
|
1334
|
+
"Agent has been destroyed",
|
|
1335
|
+
false
|
|
1336
|
+
);
|
|
1337
|
+
const errorEvent = this.errorClassifier.createEvent(error);
|
|
1338
|
+
this.notifyHandlers(errorEvent);
|
|
1339
|
+
throw new Error("[Agent] Agent has been destroyed");
|
|
1340
|
+
}
|
|
1341
|
+
if (this.state !== "idle") {
|
|
1342
|
+
logger4$1.warn("Receive called while agent is busy", {
|
|
1343
|
+
agentId: this.agentId,
|
|
1344
|
+
currentState: this.state
|
|
1345
|
+
});
|
|
1346
|
+
const error = this.errorClassifier.create(
|
|
1347
|
+
"system",
|
|
1348
|
+
"AGENT_BUSY",
|
|
1349
|
+
`Agent is busy (state: ${this.state}), please wait for current operation to complete`,
|
|
1350
|
+
false
|
|
1351
|
+
);
|
|
1352
|
+
const errorEvent = this.errorClassifier.createEvent(error);
|
|
1353
|
+
this.notifyHandlers(errorEvent);
|
|
1354
|
+
throw new Error(`[Agent] Agent is busy (state: ${this.state})`);
|
|
1355
|
+
}
|
|
1356
|
+
const userMessage = typeof message === "string" ? {
|
|
1357
|
+
id: `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1358
|
+
role: "user",
|
|
1359
|
+
subtype: "user",
|
|
1360
|
+
content: message,
|
|
1361
|
+
timestamp: Date.now()
|
|
1362
|
+
} : message;
|
|
1363
|
+
logger4$1.debug("Receiving message", {
|
|
1364
|
+
agentId: this.agentId,
|
|
1365
|
+
messageId: userMessage.id
|
|
1366
|
+
});
|
|
1367
|
+
const userMessageEvent = {
|
|
1368
|
+
uuid: `evt_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1369
|
+
type: "user_message",
|
|
1370
|
+
agentId: this.agentId,
|
|
1371
|
+
timestamp: Date.now(),
|
|
1372
|
+
data: userMessage
|
|
1373
|
+
};
|
|
1374
|
+
this.presentOutput(userMessageEvent);
|
|
1375
|
+
this.notifyHandlers(userMessageEvent);
|
|
1376
|
+
await this.executeMiddlewareChain(userMessage);
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Execute middleware chain and then process the message
|
|
1380
|
+
*/
|
|
1381
|
+
async executeMiddlewareChain(message) {
|
|
1382
|
+
await this.middlewareChain.execute(message, (msg) => this.doReceive(msg));
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Process a single stream event through the engine
|
|
1386
|
+
*
|
|
1387
|
+
* Used by:
|
|
1388
|
+
* - doReceive() - normal message flow
|
|
1389
|
+
* - AgentInterrupter - interrupt event injection
|
|
1390
|
+
*
|
|
1391
|
+
* @param streamEvent - Stream event to process
|
|
1392
|
+
*/
|
|
1393
|
+
processStreamEvent(streamEvent) {
|
|
1394
|
+
const outputs = this.engine.process(this.agentId, streamEvent);
|
|
1395
|
+
for (const output of outputs) {
|
|
1396
|
+
this.presentOutput(output);
|
|
1397
|
+
}
|
|
1398
|
+
for (const output of outputs) {
|
|
1399
|
+
this.notifyHandlers(output);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Actual message processing logic
|
|
1404
|
+
*
|
|
1405
|
+
* Coordinates the flow:
|
|
1406
|
+
* 1. Driver receives message → produces StreamEvents
|
|
1407
|
+
* 2. Engine processes events → produces outputs
|
|
1408
|
+
* 3. Presenters handle outputs
|
|
1409
|
+
* 4. Handlers receive outputs
|
|
1410
|
+
*/
|
|
1411
|
+
async doReceive(userMessage) {
|
|
1412
|
+
try {
|
|
1413
|
+
logger4$1.debug("Processing message through driver", {
|
|
1414
|
+
agentId: this.agentId,
|
|
1415
|
+
messageId: userMessage.id
|
|
1416
|
+
});
|
|
1417
|
+
const queuedEvent = {
|
|
1418
|
+
type: "conversation_queued",
|
|
1419
|
+
uuid: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
1420
|
+
agentId: this.agentId,
|
|
1421
|
+
timestamp: Date.now(),
|
|
1422
|
+
data: {
|
|
1423
|
+
userMessage
|
|
1424
|
+
}
|
|
1425
|
+
};
|
|
1426
|
+
this.notifyHandlers(queuedEvent);
|
|
1427
|
+
const streamEvents = this.driver.receive(userMessage);
|
|
1428
|
+
for await (const streamEvent of streamEvents) {
|
|
1429
|
+
this.processStreamEvent(streamEvent);
|
|
1430
|
+
}
|
|
1431
|
+
logger4$1.debug("Message processing completed", {
|
|
1432
|
+
agentId: this.agentId,
|
|
1433
|
+
messageId: userMessage.id
|
|
1434
|
+
});
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
const agentError = this.errorClassifier.classify(error);
|
|
1437
|
+
const errorEvent = this.errorClassifier.createEvent(agentError);
|
|
1438
|
+
logger4$1.error("Message processing failed", {
|
|
1439
|
+
agentId: this.agentId,
|
|
1440
|
+
messageId: userMessage.id,
|
|
1441
|
+
errorCategory: agentError.category,
|
|
1442
|
+
errorCode: agentError.code,
|
|
1443
|
+
error
|
|
1444
|
+
});
|
|
1445
|
+
this.notifyHandlers(errorEvent);
|
|
1446
|
+
throw error;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Send output to all presenters
|
|
1451
|
+
*
|
|
1452
|
+
* Note: Presenters are no longer part of AgentDefinition.
|
|
1453
|
+
* This is a placeholder for future presenter injection via Runtime or middleware.
|
|
1454
|
+
*/
|
|
1455
|
+
presentOutput(_output) {
|
|
1456
|
+
}
|
|
1457
|
+
on(typeOrHandlerOrMap, handler) {
|
|
1458
|
+
if (typeof typeOrHandlerOrMap === "function") {
|
|
1459
|
+
return this.eventBus.onAny(typeOrHandlerOrMap);
|
|
1460
|
+
}
|
|
1461
|
+
if (this.isEventHandlerMap(typeOrHandlerOrMap)) {
|
|
1462
|
+
const unsubscribes = [];
|
|
1463
|
+
for (const [eventType, eventHandler] of Object.entries(typeOrHandlerOrMap)) {
|
|
1464
|
+
if (eventHandler) {
|
|
1465
|
+
unsubscribes.push(this.eventBus.on(eventType, eventHandler));
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
return () => {
|
|
1469
|
+
for (const unsub of unsubscribes) {
|
|
1470
|
+
unsub();
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
const types = Array.isArray(typeOrHandlerOrMap) ? typeOrHandlerOrMap : [typeOrHandlerOrMap];
|
|
1475
|
+
const h = handler;
|
|
1476
|
+
return this.eventBus.on(types, h);
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Check if the argument is an EventHandlerMap (object with event type keys)
|
|
1480
|
+
*/
|
|
1481
|
+
isEventHandlerMap(arg) {
|
|
1482
|
+
if (typeof arg !== "object" || arg === null || Array.isArray(arg)) {
|
|
1483
|
+
return false;
|
|
1484
|
+
}
|
|
1485
|
+
const keys = Object.keys(arg);
|
|
1486
|
+
if (keys.length === 0) {
|
|
1487
|
+
return false;
|
|
1488
|
+
}
|
|
1489
|
+
return keys.every((key) => {
|
|
1490
|
+
const value = arg[key];
|
|
1491
|
+
return value === void 0 || typeof value === "function";
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Subscribe to state changes (delegated to StateMachine)
|
|
1496
|
+
*
|
|
1497
|
+
* @param handler - Callback receiving { prev, current } state change
|
|
1498
|
+
* @returns Unsubscribe function
|
|
1499
|
+
*/
|
|
1500
|
+
onStateChange(handler) {
|
|
1501
|
+
return this.stateMachine.onStateChange(handler);
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* React-style fluent event subscription
|
|
1505
|
+
*
|
|
1506
|
+
* Converts onXxx handlers to event type keys and delegates to on(handlers)
|
|
1507
|
+
*/
|
|
1508
|
+
react(handlers) {
|
|
1509
|
+
const eventHandlerMap = mapReactHandlers(handlers);
|
|
1510
|
+
return this.on(eventHandlerMap);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Subscribe to agent ready event
|
|
1514
|
+
*
|
|
1515
|
+
* If already running, handler is called immediately.
|
|
1516
|
+
*/
|
|
1517
|
+
onReady(handler) {
|
|
1518
|
+
if (this._lifecycle === "running") {
|
|
1519
|
+
try {
|
|
1520
|
+
handler();
|
|
1521
|
+
} catch (error) {
|
|
1522
|
+
logger4$1.error("onReady handler error", {
|
|
1523
|
+
agentId: this.agentId,
|
|
1524
|
+
error
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
this.readyHandlers.add(handler);
|
|
1529
|
+
return () => {
|
|
1530
|
+
this.readyHandlers.delete(handler);
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Subscribe to agent destroy event
|
|
1535
|
+
*/
|
|
1536
|
+
onDestroy(handler) {
|
|
1537
|
+
this.destroyHandlers.add(handler);
|
|
1538
|
+
return () => {
|
|
1539
|
+
this.destroyHandlers.delete(handler);
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* Add middleware to intercept incoming messages
|
|
1544
|
+
*/
|
|
1545
|
+
use(middleware) {
|
|
1546
|
+
return this.middlewareChain.use(middleware);
|
|
1547
|
+
}
|
|
1548
|
+
/**
|
|
1549
|
+
* Add interceptor to intercept outgoing events
|
|
1550
|
+
*/
|
|
1551
|
+
intercept(interceptor) {
|
|
1552
|
+
return this.interceptorChain.intercept(interceptor);
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Interrupt - User-initiated stop
|
|
1556
|
+
*
|
|
1557
|
+
* Stops the current operation gracefully.
|
|
1558
|
+
* Flow:
|
|
1559
|
+
* 1. Call driver.interrupt() to abort active requests
|
|
1560
|
+
* 2. Driver yields InterruptedStreamEvent
|
|
1561
|
+
* 3. Event flows through engine pipeline
|
|
1562
|
+
* 4. StateEventProcessor generates conversation_interrupted
|
|
1563
|
+
* 5. StateMachine transitions to idle state
|
|
1564
|
+
* 6. UI receives state change notification
|
|
1565
|
+
*/
|
|
1566
|
+
interrupt() {
|
|
1567
|
+
logger4$1.debug("User interrupt requested", { agentId: this.agentId, currentState: this.state });
|
|
1568
|
+
this.driver.interrupt();
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Destroy - Clean up resources
|
|
1572
|
+
*/
|
|
1573
|
+
async destroy() {
|
|
1574
|
+
logger4$1.debug("Destroying agent", { agentId: this.agentId });
|
|
1575
|
+
for (const handler of this.destroyHandlers) {
|
|
1576
|
+
try {
|
|
1577
|
+
handler();
|
|
1578
|
+
} catch (error) {
|
|
1579
|
+
logger4$1.error("onDestroy handler error", {
|
|
1580
|
+
agentId: this.agentId,
|
|
1581
|
+
error
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
this._lifecycle = "destroyed";
|
|
1586
|
+
this.stateMachine.reset();
|
|
1587
|
+
this.eventBus.destroy();
|
|
1588
|
+
this.readyHandlers.clear();
|
|
1589
|
+
this.destroyHandlers.clear();
|
|
1590
|
+
this.middlewareChain.clear();
|
|
1591
|
+
this.interceptorChain.clear();
|
|
1592
|
+
this.engine.clearState(this.agentId);
|
|
1593
|
+
logger4$1.info("Agent destroyed", { agentId: this.agentId });
|
|
1594
|
+
}
|
|
1595
|
+
/**
|
|
1596
|
+
* Notify all registered handlers
|
|
1597
|
+
*
|
|
1598
|
+
* Flow:
|
|
1599
|
+
* 1. StateMachine processes StateEvents (for state transitions)
|
|
1600
|
+
* 2. Interceptor chain can modify/filter events
|
|
1601
|
+
* 3. EventBus emits to all subscribers
|
|
1602
|
+
*/
|
|
1603
|
+
notifyHandlers(event) {
|
|
1604
|
+
if (isStateEvent(event)) {
|
|
1605
|
+
this.stateMachine.process(event);
|
|
1606
|
+
}
|
|
1607
|
+
this.executeInterceptorChain(event);
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Execute interceptor chain and then emit to EventBus
|
|
1611
|
+
*/
|
|
1612
|
+
executeInterceptorChain(event) {
|
|
1613
|
+
this.interceptorChain.execute(event, (e) => this.eventBus.emit(e));
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* Get the event consumer for external subscriptions
|
|
1617
|
+
*
|
|
1618
|
+
* Use this to expose event subscription without emit capability.
|
|
1619
|
+
*/
|
|
1620
|
+
getEventConsumer() {
|
|
1621
|
+
return this.eventBus.asConsumer();
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
var MemoryStore = class {
|
|
1625
|
+
constructor() {
|
|
1626
|
+
__publicField(this, "states", /* @__PURE__ */ new Map());
|
|
1627
|
+
}
|
|
1628
|
+
get(id) {
|
|
1629
|
+
return this.states.get(id);
|
|
1630
|
+
}
|
|
1631
|
+
set(id, state) {
|
|
1632
|
+
this.states.set(id, state);
|
|
1633
|
+
}
|
|
1634
|
+
delete(id) {
|
|
1635
|
+
this.states.delete(id);
|
|
1636
|
+
}
|
|
1637
|
+
has(id) {
|
|
1638
|
+
return this.states.has(id);
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* Clear all stored states
|
|
1642
|
+
*/
|
|
1643
|
+
clear() {
|
|
1644
|
+
this.states.clear();
|
|
1645
|
+
}
|
|
1646
|
+
/**
|
|
1647
|
+
* Get the number of stored states
|
|
1648
|
+
*/
|
|
1649
|
+
get size() {
|
|
1650
|
+
return this.states.size;
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Get all stored IDs
|
|
1654
|
+
*/
|
|
1655
|
+
keys() {
|
|
1656
|
+
return this.states.keys();
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
createLogger("engine/Mealy");
|
|
1660
|
+
function combineProcessors(processors) {
|
|
1661
|
+
return (state, event) => {
|
|
1662
|
+
const newState = {};
|
|
1663
|
+
const allOutputs = [];
|
|
1664
|
+
for (const key in processors) {
|
|
1665
|
+
const processor = processors[key];
|
|
1666
|
+
const subState = state[key];
|
|
1667
|
+
const [newSubState, outputs] = processor(subState, event);
|
|
1668
|
+
newState[key] = newSubState;
|
|
1669
|
+
allOutputs.push(...outputs);
|
|
1670
|
+
}
|
|
1671
|
+
return [newState, allOutputs];
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
function combineInitialStates(initialStates) {
|
|
1675
|
+
return () => {
|
|
1676
|
+
const state = {};
|
|
1677
|
+
for (const key in initialStates) {
|
|
1678
|
+
state[key] = initialStates[key]();
|
|
1679
|
+
}
|
|
1680
|
+
return state;
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
function createInitialMessageAssemblerState() {
|
|
1684
|
+
return {
|
|
1685
|
+
currentMessageId: null,
|
|
1686
|
+
messageStartTime: null,
|
|
1687
|
+
pendingContents: {},
|
|
1688
|
+
pendingToolCalls: {}
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
function generateId() {
|
|
1692
|
+
return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1693
|
+
}
|
|
1694
|
+
var messageAssemblerProcessor = (state, input) => {
|
|
1695
|
+
switch (input.type) {
|
|
1696
|
+
case "message_start":
|
|
1697
|
+
return handleMessageStart(state, input);
|
|
1698
|
+
case "text_delta":
|
|
1699
|
+
return handleTextDelta(state, input);
|
|
1700
|
+
case "tool_use_content_block_start":
|
|
1701
|
+
return handleToolUseContentBlockStart(state, input);
|
|
1702
|
+
case "input_json_delta":
|
|
1703
|
+
return handleInputJsonDelta(state, input);
|
|
1704
|
+
case "tool_use_content_block_stop":
|
|
1705
|
+
return handleToolUseContentBlockStop(state, input);
|
|
1706
|
+
case "tool_result":
|
|
1707
|
+
return handleToolResult(state, input);
|
|
1708
|
+
case "message_stop":
|
|
1709
|
+
return handleMessageStop(state, input);
|
|
1710
|
+
default:
|
|
1711
|
+
return [state, []];
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
function handleMessageStart(state, event) {
|
|
1715
|
+
return [
|
|
1716
|
+
{
|
|
1717
|
+
...state,
|
|
1718
|
+
currentMessageId: generateId(),
|
|
1719
|
+
messageStartTime: event.timestamp,
|
|
1720
|
+
pendingContents: {}
|
|
1721
|
+
},
|
|
1722
|
+
[]
|
|
1723
|
+
];
|
|
1724
|
+
}
|
|
1725
|
+
function handleTextDelta(state, event) {
|
|
1726
|
+
const index = 0;
|
|
1727
|
+
const existingContent = state.pendingContents[index];
|
|
1728
|
+
const pendingContent = (existingContent == null ? void 0 : existingContent.type) === "text" ? {
|
|
1729
|
+
...existingContent,
|
|
1730
|
+
textDeltas: [...existingContent.textDeltas || [], event.data.text]
|
|
1731
|
+
} : {
|
|
1732
|
+
type: "text",
|
|
1733
|
+
index,
|
|
1734
|
+
textDeltas: [event.data.text]
|
|
1735
|
+
};
|
|
1736
|
+
return [
|
|
1737
|
+
{
|
|
1738
|
+
...state,
|
|
1739
|
+
pendingContents: {
|
|
1740
|
+
...state.pendingContents,
|
|
1741
|
+
[index]: pendingContent
|
|
1742
|
+
}
|
|
1743
|
+
},
|
|
1744
|
+
[]
|
|
1745
|
+
];
|
|
1746
|
+
}
|
|
1747
|
+
function handleToolUseContentBlockStart(state, event) {
|
|
1748
|
+
const index = 1;
|
|
1749
|
+
const pendingContent = {
|
|
1750
|
+
type: "tool_use",
|
|
1751
|
+
index,
|
|
1752
|
+
toolId: event.data.id,
|
|
1753
|
+
toolName: event.data.name,
|
|
1754
|
+
toolInputJson: ""
|
|
1755
|
+
};
|
|
1756
|
+
return [
|
|
1757
|
+
{
|
|
1758
|
+
...state,
|
|
1759
|
+
pendingContents: {
|
|
1760
|
+
...state.pendingContents,
|
|
1761
|
+
[index]: pendingContent
|
|
1762
|
+
}
|
|
1763
|
+
},
|
|
1764
|
+
[]
|
|
1765
|
+
];
|
|
1766
|
+
}
|
|
1767
|
+
function handleInputJsonDelta(state, event) {
|
|
1768
|
+
const index = 1;
|
|
1769
|
+
const existingContent = state.pendingContents[index];
|
|
1770
|
+
if (!existingContent || existingContent.type !== "tool_use") {
|
|
1771
|
+
return [state, []];
|
|
1772
|
+
}
|
|
1773
|
+
const pendingContent = {
|
|
1774
|
+
...existingContent,
|
|
1775
|
+
toolInputJson: (existingContent.toolInputJson || "") + event.data.partialJson
|
|
1776
|
+
};
|
|
1777
|
+
return [
|
|
1778
|
+
{
|
|
1779
|
+
...state,
|
|
1780
|
+
pendingContents: {
|
|
1781
|
+
...state.pendingContents,
|
|
1782
|
+
[index]: pendingContent
|
|
1783
|
+
}
|
|
1784
|
+
},
|
|
1785
|
+
[]
|
|
1786
|
+
];
|
|
1787
|
+
}
|
|
1788
|
+
function handleToolUseContentBlockStop(state, event) {
|
|
1789
|
+
const index = 1;
|
|
1790
|
+
const pendingContent = state.pendingContents[index];
|
|
1791
|
+
if (!pendingContent || pendingContent.type !== "tool_use") {
|
|
1792
|
+
return [state, []];
|
|
1793
|
+
}
|
|
1794
|
+
let toolInput = {};
|
|
1795
|
+
try {
|
|
1796
|
+
toolInput = pendingContent.toolInputJson ? JSON.parse(pendingContent.toolInputJson) : {};
|
|
1797
|
+
} catch {
|
|
1798
|
+
toolInput = {};
|
|
1799
|
+
}
|
|
1800
|
+
const outputs = [];
|
|
1801
|
+
const toolId = pendingContent.toolId;
|
|
1802
|
+
const toolName = pendingContent.toolName;
|
|
1803
|
+
const toolCallEvent = {
|
|
1804
|
+
type: "tool_call",
|
|
1805
|
+
uuid: generateId(),
|
|
1806
|
+
agentId: event.agentId,
|
|
1807
|
+
timestamp: Date.now(),
|
|
1808
|
+
data: {
|
|
1809
|
+
id: toolId,
|
|
1810
|
+
name: toolName,
|
|
1811
|
+
input: toolInput
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
outputs.push(toolCallEvent);
|
|
1815
|
+
const toolCall = {
|
|
1816
|
+
type: "tool-call",
|
|
1817
|
+
id: toolId,
|
|
1818
|
+
name: toolName,
|
|
1819
|
+
input: toolInput
|
|
1820
|
+
};
|
|
1821
|
+
const toolCallMessage = {
|
|
1822
|
+
id: generateId(),
|
|
1823
|
+
role: "assistant",
|
|
1824
|
+
subtype: "tool-call",
|
|
1825
|
+
toolCall,
|
|
1826
|
+
timestamp: Date.now()
|
|
1827
|
+
};
|
|
1828
|
+
const toolCallMessageEvent = {
|
|
1829
|
+
type: "tool_call_message",
|
|
1830
|
+
uuid: generateId(),
|
|
1831
|
+
agentId: event.agentId,
|
|
1832
|
+
timestamp: Date.now(),
|
|
1833
|
+
data: toolCallMessage
|
|
1834
|
+
};
|
|
1835
|
+
outputs.push(toolCallMessageEvent);
|
|
1836
|
+
const { [index]: _, ...remainingContents } = state.pendingContents;
|
|
1837
|
+
return [
|
|
1838
|
+
{
|
|
1839
|
+
...state,
|
|
1840
|
+
pendingContents: remainingContents,
|
|
1841
|
+
pendingToolCalls: {
|
|
1842
|
+
...state.pendingToolCalls,
|
|
1843
|
+
[toolId]: { id: toolId, name: toolName }
|
|
1844
|
+
}
|
|
1845
|
+
},
|
|
1846
|
+
outputs
|
|
1847
|
+
];
|
|
1848
|
+
}
|
|
1849
|
+
function handleToolResult(state, event) {
|
|
1850
|
+
const { toolId, content, isError } = event.data;
|
|
1851
|
+
const pendingToolCall = state.pendingToolCalls[toolId];
|
|
1852
|
+
const toolName = (pendingToolCall == null ? void 0 : pendingToolCall.name) || "unknown";
|
|
1853
|
+
const toolResult = {
|
|
1854
|
+
type: "tool-result",
|
|
1855
|
+
id: toolId,
|
|
1856
|
+
name: toolName,
|
|
1857
|
+
output: {
|
|
1858
|
+
type: isError ? "error-text" : "text",
|
|
1859
|
+
value: typeof content === "string" ? content : JSON.stringify(content)
|
|
1860
|
+
}
|
|
1861
|
+
};
|
|
1862
|
+
const toolResultMessage = {
|
|
1863
|
+
id: generateId(),
|
|
1864
|
+
role: "tool",
|
|
1865
|
+
subtype: "tool-result",
|
|
1866
|
+
toolResult,
|
|
1867
|
+
toolCallId: toolId,
|
|
1868
|
+
timestamp: Date.now()
|
|
1869
|
+
};
|
|
1870
|
+
const toolResultMessageEvent = {
|
|
1871
|
+
type: "tool_result_message",
|
|
1872
|
+
uuid: generateId(),
|
|
1873
|
+
agentId: event.agentId,
|
|
1874
|
+
timestamp: Date.now(),
|
|
1875
|
+
data: toolResultMessage
|
|
1876
|
+
};
|
|
1877
|
+
const { [toolId]: _, ...remainingToolCalls } = state.pendingToolCalls;
|
|
1878
|
+
return [
|
|
1879
|
+
{
|
|
1880
|
+
...state,
|
|
1881
|
+
pendingToolCalls: remainingToolCalls
|
|
1882
|
+
},
|
|
1883
|
+
[toolResultMessageEvent]
|
|
1884
|
+
];
|
|
1885
|
+
}
|
|
1886
|
+
function handleMessageStop(state, event) {
|
|
1887
|
+
if (!state.currentMessageId) {
|
|
1888
|
+
return [state, []];
|
|
1889
|
+
}
|
|
1890
|
+
const textParts = [];
|
|
1891
|
+
const sortedContents = Object.values(state.pendingContents).sort((a, b) => a.index - b.index);
|
|
1892
|
+
for (const pending of sortedContents) {
|
|
1893
|
+
if (pending.type === "text" && pending.textDeltas) {
|
|
1894
|
+
textParts.push(pending.textDeltas.join(""));
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
const content = textParts.join("");
|
|
1898
|
+
const stopReason = event.data.stopReason;
|
|
1899
|
+
if (!content || content.trim().length === 0) {
|
|
1900
|
+
const shouldPreserveToolCalls2 = stopReason === "tool_use";
|
|
1901
|
+
return [
|
|
1902
|
+
{
|
|
1903
|
+
...createInitialMessageAssemblerState(),
|
|
1904
|
+
pendingToolCalls: shouldPreserveToolCalls2 ? state.pendingToolCalls : {}
|
|
1905
|
+
},
|
|
1906
|
+
[]
|
|
1907
|
+
];
|
|
1908
|
+
}
|
|
1909
|
+
const assistantMessage = {
|
|
1910
|
+
id: state.currentMessageId,
|
|
1911
|
+
role: "assistant",
|
|
1912
|
+
subtype: "assistant",
|
|
1913
|
+
content,
|
|
1914
|
+
timestamp: state.messageStartTime || Date.now(),
|
|
1915
|
+
// Usage data is not available in message_stop event
|
|
1916
|
+
// It would need to be tracked separately if needed
|
|
1917
|
+
usage: void 0
|
|
1918
|
+
};
|
|
1919
|
+
const assistantEvent = {
|
|
1920
|
+
type: "assistant_message",
|
|
1921
|
+
uuid: generateId(),
|
|
1922
|
+
agentId: event.agentId,
|
|
1923
|
+
timestamp: Date.now(),
|
|
1924
|
+
data: assistantMessage
|
|
1925
|
+
};
|
|
1926
|
+
const shouldPreserveToolCalls = stopReason === "tool_use";
|
|
1927
|
+
return [
|
|
1928
|
+
{
|
|
1929
|
+
...createInitialMessageAssemblerState(),
|
|
1930
|
+
pendingToolCalls: shouldPreserveToolCalls ? state.pendingToolCalls : {}
|
|
1931
|
+
},
|
|
1932
|
+
[assistantEvent]
|
|
1933
|
+
];
|
|
1934
|
+
}
|
|
1935
|
+
var logger2$1 = createLogger("engine/stateEventProcessor");
|
|
1936
|
+
function createInitialStateEventProcessorContext() {
|
|
1937
|
+
return {};
|
|
1938
|
+
}
|
|
1939
|
+
function generateId2() {
|
|
1940
|
+
return `state_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
1941
|
+
}
|
|
1942
|
+
var stateEventProcessor = (context, input) => {
|
|
1943
|
+
logger2$1.debug(`[Stream Event] ${input.type}`, {
|
|
1944
|
+
context,
|
|
1945
|
+
eventData: "data" in input ? input.data : void 0
|
|
1946
|
+
});
|
|
1947
|
+
switch (input.type) {
|
|
1948
|
+
case "message_start":
|
|
1949
|
+
return handleMessageStart2(context, input);
|
|
1950
|
+
case "message_delta":
|
|
1951
|
+
return handleMessageDelta(context);
|
|
1952
|
+
case "message_stop":
|
|
1953
|
+
return handleMessageStop2(context, input);
|
|
1954
|
+
case "text_content_block_start":
|
|
1955
|
+
return handleTextContentBlockStart(context, input);
|
|
1956
|
+
case "tool_use_content_block_start":
|
|
1957
|
+
return handleToolUseContentBlockStart2(context, input);
|
|
1958
|
+
case "tool_use_content_block_stop":
|
|
1959
|
+
return handleToolUseContentBlockStop2(context);
|
|
1960
|
+
case "tool_call":
|
|
1961
|
+
return handleToolCall(context);
|
|
1962
|
+
case "interrupted":
|
|
1963
|
+
return handleInterrupted(context, input);
|
|
1964
|
+
default:
|
|
1965
|
+
logger2$1.debug(`[Stream Event] ${input.type} (unhandled)`);
|
|
1966
|
+
return [context, []];
|
|
1967
|
+
}
|
|
1968
|
+
};
|
|
1969
|
+
function handleMessageStart2(context, event) {
|
|
1970
|
+
const conversationStartEvent = {
|
|
1971
|
+
type: "conversation_start",
|
|
1972
|
+
uuid: generateId2(),
|
|
1973
|
+
agentId: event.agentId,
|
|
1974
|
+
timestamp: event.timestamp,
|
|
1975
|
+
transition: {
|
|
1976
|
+
reason: "conversation_started",
|
|
1977
|
+
trigger: "message_start"
|
|
1978
|
+
},
|
|
1979
|
+
data: {
|
|
1980
|
+
userMessage: {}
|
|
1981
|
+
// Will be populated by higher-level component
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
return [context, [conversationStartEvent]];
|
|
1985
|
+
}
|
|
1986
|
+
function handleMessageDelta(context, _event) {
|
|
1987
|
+
return [context, []];
|
|
1988
|
+
}
|
|
1989
|
+
function handleMessageStop2(context, event) {
|
|
1990
|
+
const stopReason = event.data.stopReason;
|
|
1991
|
+
logger2$1.debug("message_stop received", { stopReason });
|
|
1992
|
+
if (stopReason === "tool_use") {
|
|
1993
|
+
logger2$1.debug("Skipping conversation_end (tool_use in progress)");
|
|
1994
|
+
return [context, []];
|
|
1995
|
+
}
|
|
1996
|
+
const conversationEndEvent = {
|
|
1997
|
+
type: "conversation_end",
|
|
1998
|
+
uuid: generateId2(),
|
|
1999
|
+
agentId: event.agentId,
|
|
2000
|
+
timestamp: event.timestamp,
|
|
2001
|
+
transition: {
|
|
2002
|
+
reason: "conversation_completed",
|
|
2003
|
+
trigger: "message_stop"
|
|
2004
|
+
},
|
|
2005
|
+
data: {
|
|
2006
|
+
assistantMessage: {},
|
|
2007
|
+
// Will be populated by higher-level component
|
|
2008
|
+
durationMs: 0,
|
|
2009
|
+
// Will be calculated by StateMachine or TurnTracker
|
|
2010
|
+
durationApiMs: 0,
|
|
2011
|
+
numTurns: 0,
|
|
2012
|
+
result: "completed",
|
|
2013
|
+
totalCostUsd: 0,
|
|
2014
|
+
usage: {
|
|
2015
|
+
input: 0,
|
|
2016
|
+
output: 0
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
return [context, [conversationEndEvent]];
|
|
2021
|
+
}
|
|
2022
|
+
function handleTextContentBlockStart(context, event) {
|
|
2023
|
+
const respondingEvent = {
|
|
2024
|
+
type: "conversation_responding",
|
|
2025
|
+
uuid: generateId2(),
|
|
2026
|
+
agentId: event.agentId,
|
|
2027
|
+
timestamp: Date.now(),
|
|
2028
|
+
transition: {
|
|
2029
|
+
reason: "assistant_responding",
|
|
2030
|
+
trigger: "text_content_block_start"
|
|
2031
|
+
},
|
|
2032
|
+
data: {}
|
|
2033
|
+
};
|
|
2034
|
+
return [context, [respondingEvent]];
|
|
2035
|
+
}
|
|
2036
|
+
function handleToolUseContentBlockStart2(context, event) {
|
|
2037
|
+
const outputs = [];
|
|
2038
|
+
const toolPlannedEvent = {
|
|
2039
|
+
type: "tool_planned",
|
|
2040
|
+
uuid: generateId2(),
|
|
2041
|
+
agentId: event.agentId,
|
|
2042
|
+
timestamp: event.timestamp,
|
|
2043
|
+
data: {
|
|
2044
|
+
id: event.data.id,
|
|
2045
|
+
name: event.data.name,
|
|
2046
|
+
input: {}
|
|
2047
|
+
}
|
|
2048
|
+
};
|
|
2049
|
+
outputs.push(toolPlannedEvent);
|
|
2050
|
+
const toolExecutingEvent = {
|
|
2051
|
+
type: "tool_executing",
|
|
2052
|
+
uuid: generateId2(),
|
|
2053
|
+
agentId: event.agentId,
|
|
2054
|
+
timestamp: event.timestamp,
|
|
2055
|
+
transition: {
|
|
2056
|
+
reason: "tool_planning_started",
|
|
2057
|
+
trigger: "tool_use_content_block_start"
|
|
2058
|
+
},
|
|
2059
|
+
data: {}
|
|
2060
|
+
};
|
|
2061
|
+
outputs.push(toolExecutingEvent);
|
|
2062
|
+
return [context, outputs];
|
|
2063
|
+
}
|
|
2064
|
+
function handleToolUseContentBlockStop2(context, _event) {
|
|
2065
|
+
return [context, []];
|
|
2066
|
+
}
|
|
2067
|
+
function handleToolCall(context, _event) {
|
|
2068
|
+
return [context, []];
|
|
2069
|
+
}
|
|
2070
|
+
function handleInterrupted(context, event) {
|
|
2071
|
+
logger2$1.debug("interrupted event received", { reason: event.data.reason });
|
|
2072
|
+
const conversationInterruptedEvent = {
|
|
2073
|
+
type: "conversation_interrupted",
|
|
2074
|
+
uuid: generateId2(),
|
|
2075
|
+
agentId: event.agentId,
|
|
2076
|
+
timestamp: event.timestamp,
|
|
2077
|
+
transition: {
|
|
2078
|
+
reason: event.data.reason,
|
|
2079
|
+
trigger: "interrupted"
|
|
2080
|
+
},
|
|
2081
|
+
data: {
|
|
2082
|
+
reason: event.data.reason
|
|
2083
|
+
}
|
|
2084
|
+
};
|
|
2085
|
+
return [context, [conversationInterruptedEvent]];
|
|
2086
|
+
}
|
|
2087
|
+
function createInitialTurnTrackerState() {
|
|
2088
|
+
return {
|
|
2089
|
+
pendingTurn: null,
|
|
2090
|
+
costPerInputToken: 3e-6,
|
|
2091
|
+
// $3 per 1M tokens
|
|
2092
|
+
costPerOutputToken: 15e-6
|
|
2093
|
+
// $15 per 1M tokens
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
function generateId3() {
|
|
2097
|
+
return `turn_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
2098
|
+
}
|
|
2099
|
+
function calculateCost(usage, costPerInputToken, costPerOutputToken) {
|
|
2100
|
+
const inputCost = usage.input * costPerInputToken;
|
|
2101
|
+
const outputCost = usage.output * costPerOutputToken;
|
|
2102
|
+
return inputCost + outputCost;
|
|
2103
|
+
}
|
|
2104
|
+
var turnTrackerProcessor = (state, input) => {
|
|
2105
|
+
switch (input.type) {
|
|
2106
|
+
case "user_message":
|
|
2107
|
+
return handleUserMessage(state, input);
|
|
2108
|
+
case "message_stop":
|
|
2109
|
+
return handleMessageStop3(state, input);
|
|
2110
|
+
case "assistant_message":
|
|
2111
|
+
return [state, []];
|
|
2112
|
+
default:
|
|
2113
|
+
return [state, []];
|
|
2114
|
+
}
|
|
2115
|
+
};
|
|
2116
|
+
function handleUserMessage(state, event) {
|
|
2117
|
+
const turnId = generateId3();
|
|
2118
|
+
const pendingTurn = {
|
|
2119
|
+
turnId,
|
|
2120
|
+
userMessage: event.data,
|
|
2121
|
+
requestedAt: event.timestamp
|
|
2122
|
+
};
|
|
2123
|
+
const turnRequestEvent = {
|
|
2124
|
+
type: "turn_request",
|
|
2125
|
+
uuid: generateId3(),
|
|
2126
|
+
agentId: event.agentId,
|
|
2127
|
+
timestamp: Date.now(),
|
|
2128
|
+
turnId,
|
|
2129
|
+
data: {
|
|
2130
|
+
userMessage: event.data,
|
|
2131
|
+
requestedAt: event.timestamp
|
|
2132
|
+
}
|
|
2133
|
+
};
|
|
2134
|
+
return [
|
|
2135
|
+
{
|
|
2136
|
+
...state,
|
|
2137
|
+
pendingTurn
|
|
2138
|
+
},
|
|
2139
|
+
[turnRequestEvent]
|
|
2140
|
+
];
|
|
2141
|
+
}
|
|
2142
|
+
function handleMessageStop3(state, event) {
|
|
2143
|
+
if (!state.pendingTurn) {
|
|
2144
|
+
return [state, []];
|
|
2145
|
+
}
|
|
2146
|
+
const stopReason = event.data.stopReason;
|
|
2147
|
+
if (stopReason === "end_turn" || stopReason === "max_tokens" || stopReason === "stop_sequence") {
|
|
2148
|
+
return completeTurn(state, event.agentId, event.timestamp);
|
|
2149
|
+
}
|
|
2150
|
+
return [state, []];
|
|
2151
|
+
}
|
|
2152
|
+
function completeTurn(state, agentId, completedAt) {
|
|
2153
|
+
if (!state.pendingTurn) {
|
|
2154
|
+
return [state, []];
|
|
2155
|
+
}
|
|
2156
|
+
const { turnId, requestedAt } = state.pendingTurn;
|
|
2157
|
+
const duration = completedAt - requestedAt;
|
|
2158
|
+
const usage = { input: 0, output: 0 };
|
|
2159
|
+
const cost = calculateCost(usage, state.costPerInputToken, state.costPerOutputToken);
|
|
2160
|
+
const turnResponseEvent = {
|
|
2161
|
+
type: "turn_response",
|
|
2162
|
+
uuid: generateId3(),
|
|
2163
|
+
agentId,
|
|
2164
|
+
timestamp: Date.now(),
|
|
2165
|
+
turnId,
|
|
2166
|
+
data: {
|
|
2167
|
+
assistantMessage: {
|
|
2168
|
+
id: generateId3(),
|
|
2169
|
+
role: "assistant",
|
|
2170
|
+
subtype: "assistant",
|
|
2171
|
+
content: "",
|
|
2172
|
+
timestamp: completedAt
|
|
2173
|
+
},
|
|
2174
|
+
respondedAt: completedAt,
|
|
2175
|
+
durationMs: duration,
|
|
2176
|
+
usage,
|
|
2177
|
+
costUsd: cost
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
return [
|
|
2181
|
+
{
|
|
2182
|
+
...state,
|
|
2183
|
+
pendingTurn: null
|
|
2184
|
+
},
|
|
2185
|
+
[turnResponseEvent]
|
|
2186
|
+
];
|
|
2187
|
+
}
|
|
2188
|
+
var agentProcessor = combineProcessors({
|
|
2189
|
+
messageAssembler: messageAssemblerProcessor,
|
|
2190
|
+
stateEventProcessor,
|
|
2191
|
+
turnTracker: turnTrackerProcessor
|
|
2192
|
+
});
|
|
2193
|
+
var createInitialAgentEngineState = combineInitialStates({
|
|
2194
|
+
messageAssembler: createInitialMessageAssemblerState,
|
|
2195
|
+
stateEventProcessor: createInitialStateEventProcessorContext,
|
|
2196
|
+
turnTracker: createInitialTurnTrackerState
|
|
2197
|
+
});
|
|
2198
|
+
var logger3$1 = createLogger("engine/AgentEngine");
|
|
2199
|
+
var AgentEngine = class {
|
|
2200
|
+
constructor() {
|
|
2201
|
+
__publicField(this, "store");
|
|
2202
|
+
this.store = new MemoryStore();
|
|
2203
|
+
logger3$1.debug("AgentEngine initialized");
|
|
2204
|
+
}
|
|
2205
|
+
/**
|
|
2206
|
+
* Process a single stream event and return output events
|
|
2207
|
+
*
|
|
2208
|
+
* This is the core Mealy Machine operation:
|
|
2209
|
+
* process(agentId, event) → outputs[]
|
|
2210
|
+
*
|
|
2211
|
+
* @param agentId - The agent identifier (for state isolation)
|
|
2212
|
+
* @param event - Stream event to process
|
|
2213
|
+
* @returns Array of output events (state, message, turn events)
|
|
2214
|
+
*/
|
|
2215
|
+
process(agentId, event) {
|
|
2216
|
+
const eventType = event.type || "unknown";
|
|
2217
|
+
logger3$1.debug("Processing event", { agentId, eventType });
|
|
2218
|
+
const isNewState = !this.store.has(agentId);
|
|
2219
|
+
let state = this.store.get(agentId) ?? createInitialAgentEngineState();
|
|
2220
|
+
if (isNewState) {
|
|
2221
|
+
logger3$1.debug("Created initial state for agent", { agentId });
|
|
2222
|
+
}
|
|
2223
|
+
const allOutputs = [];
|
|
2224
|
+
allOutputs.push(event);
|
|
2225
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
2226
|
+
state = newState;
|
|
2227
|
+
for (const output of outputs) {
|
|
2228
|
+
allOutputs.push(output);
|
|
2229
|
+
const [chainedState, chainedOutputs] = this.processChained(state, output);
|
|
2230
|
+
state = chainedState;
|
|
2231
|
+
allOutputs.push(...chainedOutputs);
|
|
2232
|
+
}
|
|
2233
|
+
this.store.set(agentId, state);
|
|
2234
|
+
if (outputs.length > 0) {
|
|
2235
|
+
logger3$1.debug("Produced outputs", {
|
|
2236
|
+
agentId,
|
|
2237
|
+
inputEvent: eventType,
|
|
2238
|
+
outputCount: allOutputs.length,
|
|
2239
|
+
processorOutputs: outputs.length
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
return allOutputs;
|
|
2243
|
+
}
|
|
2244
|
+
/**
|
|
2245
|
+
* Process chained events recursively
|
|
2246
|
+
*
|
|
2247
|
+
* Some processors produce events that trigger other processors:
|
|
2248
|
+
* - MessageAssembler produces MessageEvents
|
|
2249
|
+
* - TurnTracker consumes MessageEvents to produce TurnEvents
|
|
2250
|
+
*/
|
|
2251
|
+
processChained(state, event) {
|
|
2252
|
+
const [newState, outputs] = agentProcessor(state, event);
|
|
2253
|
+
if (outputs.length === 0) {
|
|
2254
|
+
return [newState, []];
|
|
2255
|
+
}
|
|
2256
|
+
const allOutputs = [...outputs];
|
|
2257
|
+
let currentState = newState;
|
|
2258
|
+
for (const output of outputs) {
|
|
2259
|
+
const [chainedState, chainedOutputs] = this.processChained(currentState, output);
|
|
2260
|
+
currentState = chainedState;
|
|
2261
|
+
allOutputs.push(...chainedOutputs);
|
|
2262
|
+
}
|
|
2263
|
+
return [currentState, allOutputs];
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* Clear state for an agent
|
|
2267
|
+
*
|
|
2268
|
+
* Call this when an agent is destroyed to free memory.
|
|
2269
|
+
*/
|
|
2270
|
+
clearState(agentId) {
|
|
2271
|
+
logger3$1.debug("Clearing state", { agentId });
|
|
2272
|
+
this.store.delete(agentId);
|
|
2273
|
+
}
|
|
2274
|
+
/**
|
|
2275
|
+
* Check if state exists for an agent
|
|
2276
|
+
*/
|
|
2277
|
+
hasState(agentId) {
|
|
2278
|
+
return this.store.has(agentId);
|
|
2279
|
+
}
|
|
2280
|
+
};
|
|
2281
|
+
var __defProp2 = Object.defineProperty;
|
|
2282
|
+
var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
2283
|
+
var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
2284
|
+
var logger = createLogger("agentx/DefinitionManager");
|
|
2285
|
+
function generateMetaImageId(definitionName) {
|
|
2286
|
+
return `meta_${definitionName}`;
|
|
2287
|
+
}
|
|
2288
|
+
function toDefinitionRecord(definition) {
|
|
2289
|
+
const now = /* @__PURE__ */ new Date();
|
|
2290
|
+
return {
|
|
2291
|
+
name: definition.name,
|
|
2292
|
+
description: definition.description,
|
|
2293
|
+
systemPrompt: definition.systemPrompt,
|
|
2294
|
+
definition,
|
|
2295
|
+
source: "code",
|
|
2296
|
+
createdAt: now,
|
|
2297
|
+
updatedAt: now
|
|
2298
|
+
};
|
|
2299
|
+
}
|
|
2300
|
+
var DefinitionManagerImpl = class {
|
|
2301
|
+
constructor(repository) {
|
|
2302
|
+
this.repository = repository;
|
|
2303
|
+
__publicField2(this, "cache", /* @__PURE__ */ new Map());
|
|
2304
|
+
}
|
|
2305
|
+
register(definition) {
|
|
2306
|
+
if (this.cache.has(definition.name)) {
|
|
2307
|
+
throw new Error(`Definition already exists: ${definition.name}`);
|
|
2308
|
+
}
|
|
2309
|
+
this.cache.set(definition.name, definition);
|
|
2310
|
+
const definitionRecord = toDefinitionRecord(definition);
|
|
2311
|
+
this.repository.saveDefinition(definitionRecord).catch((err) => {
|
|
2312
|
+
logger.error("Failed to save definition", { name: definition.name, error: err });
|
|
2313
|
+
});
|
|
2314
|
+
const metaImageId = generateMetaImageId(definition.name);
|
|
2315
|
+
const imageRecord = {
|
|
2316
|
+
imageId: metaImageId,
|
|
2317
|
+
type: "meta",
|
|
2318
|
+
definitionName: definition.name,
|
|
2319
|
+
parentImageId: null,
|
|
2320
|
+
definition,
|
|
2321
|
+
config: {},
|
|
2322
|
+
messages: [],
|
|
2323
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
2324
|
+
};
|
|
2325
|
+
this.repository.saveImage(imageRecord).catch((err) => {
|
|
2326
|
+
logger.error("Failed to save MetaImage", { definitionName: definition.name, error: err });
|
|
2327
|
+
});
|
|
2328
|
+
logger.info("Definition registered", {
|
|
2329
|
+
name: definition.name,
|
|
2330
|
+
metaImageId
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
get(name) {
|
|
2334
|
+
return this.cache.get(name);
|
|
2335
|
+
}
|
|
2336
|
+
list() {
|
|
2337
|
+
return Array.from(this.cache.values());
|
|
2338
|
+
}
|
|
2339
|
+
has(name) {
|
|
2340
|
+
return this.cache.has(name);
|
|
2341
|
+
}
|
|
2342
|
+
unregister(name) {
|
|
2343
|
+
const definition = this.cache.get(name);
|
|
2344
|
+
if (!definition) {
|
|
2345
|
+
return false;
|
|
2346
|
+
}
|
|
2347
|
+
this.cache.delete(name);
|
|
2348
|
+
this.repository.deleteDefinition(name).catch((err) => {
|
|
2349
|
+
logger.error("Failed to delete definition", { name, error: err });
|
|
2350
|
+
});
|
|
2351
|
+
const metaImageId = generateMetaImageId(name);
|
|
2352
|
+
this.repository.deleteImage(metaImageId).catch((err) => {
|
|
2353
|
+
logger.error("Failed to delete MetaImage", { definitionName: name, error: err });
|
|
2354
|
+
});
|
|
2355
|
+
logger.info("Definition unregistered", { name });
|
|
2356
|
+
return true;
|
|
2357
|
+
}
|
|
2358
|
+
};
|
|
2359
|
+
var logger2 = createLogger("agentx/ImageManager");
|
|
2360
|
+
function generateMetaImageId2(definitionName) {
|
|
2361
|
+
return `meta_${definitionName}`;
|
|
2362
|
+
}
|
|
2363
|
+
function toAgentImage(record) {
|
|
2364
|
+
const definition = record.definition;
|
|
2365
|
+
if (record.type === "meta") {
|
|
2366
|
+
const metaImage = {
|
|
2367
|
+
type: "meta",
|
|
2368
|
+
imageId: record.imageId,
|
|
2369
|
+
definitionName: record.definitionName,
|
|
2370
|
+
definition,
|
|
2371
|
+
config: record.config,
|
|
2372
|
+
messages: [],
|
|
2373
|
+
createdAt: record.createdAt
|
|
2374
|
+
};
|
|
2375
|
+
return metaImage;
|
|
2376
|
+
} else {
|
|
2377
|
+
return {
|
|
2378
|
+
type: "derived",
|
|
2379
|
+
imageId: record.imageId,
|
|
2380
|
+
parentImageId: record.parentImageId,
|
|
2381
|
+
definitionName: record.definitionName,
|
|
2382
|
+
definition,
|
|
2383
|
+
config: record.config,
|
|
2384
|
+
messages: record.messages,
|
|
2385
|
+
createdAt: record.createdAt
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
var ImageManagerImpl = class {
|
|
2390
|
+
constructor(repository, containerManager, defaultContainerId) {
|
|
2391
|
+
__publicField2(this, "repository");
|
|
2392
|
+
__publicField2(this, "containerManager");
|
|
2393
|
+
__publicField2(this, "defaultContainerId");
|
|
2394
|
+
this.repository = repository;
|
|
2395
|
+
this.containerManager = containerManager;
|
|
2396
|
+
this.defaultContainerId = defaultContainerId;
|
|
2397
|
+
}
|
|
2398
|
+
async get(imageId) {
|
|
2399
|
+
const record = await this.repository.findImageById(imageId);
|
|
2400
|
+
if (!record) {
|
|
2401
|
+
return void 0;
|
|
2402
|
+
}
|
|
2403
|
+
return toAgentImage(record);
|
|
2404
|
+
}
|
|
2405
|
+
async getMetaImage(definitionName) {
|
|
2406
|
+
const metaImageId = generateMetaImageId2(definitionName);
|
|
2407
|
+
const record = await this.repository.findImageById(metaImageId);
|
|
2408
|
+
if (!record || record.type !== "meta") {
|
|
2409
|
+
return void 0;
|
|
2410
|
+
}
|
|
2411
|
+
return toAgentImage(record);
|
|
2412
|
+
}
|
|
2413
|
+
async list() {
|
|
2414
|
+
const records = await this.repository.findAllImages();
|
|
2415
|
+
return records.map(toAgentImage);
|
|
2416
|
+
}
|
|
2417
|
+
async listByDefinition(definitionName) {
|
|
2418
|
+
const allRecords = await this.repository.findAllImages();
|
|
2419
|
+
const filtered = allRecords.filter((r) => r.definitionName === definitionName);
|
|
2420
|
+
return filtered.map(toAgentImage);
|
|
2421
|
+
}
|
|
2422
|
+
async exists(imageId) {
|
|
2423
|
+
return this.repository.imageExists(imageId);
|
|
2424
|
+
}
|
|
2425
|
+
async delete(imageId) {
|
|
2426
|
+
const record = await this.repository.findImageById(imageId);
|
|
2427
|
+
if (!record) {
|
|
2428
|
+
return false;
|
|
2429
|
+
}
|
|
2430
|
+
if (record.type === "meta") {
|
|
2431
|
+
logger2.warn("Cannot delete MetaImage directly", { imageId });
|
|
2432
|
+
return false;
|
|
2433
|
+
}
|
|
2434
|
+
await this.repository.deleteImage(imageId);
|
|
2435
|
+
logger2.info("Image deleted", { imageId });
|
|
2436
|
+
return true;
|
|
2437
|
+
}
|
|
2438
|
+
async run(imageId, options) {
|
|
2439
|
+
logger2.info("Running agent from image", { imageId, containerId: options == null ? void 0 : options.containerId });
|
|
2440
|
+
const image = await this.get(imageId);
|
|
2441
|
+
if (!image) {
|
|
2442
|
+
throw new Error(`Image not found: ${imageId}`);
|
|
2443
|
+
}
|
|
2444
|
+
let containerId = (options == null ? void 0 : options.containerId) || this.defaultContainerId;
|
|
2445
|
+
if (!containerId) {
|
|
2446
|
+
const container = await this.containerManager.create();
|
|
2447
|
+
containerId = container.containerId;
|
|
2448
|
+
this.defaultContainerId = containerId;
|
|
2449
|
+
logger2.debug("Auto-created default container", { containerId });
|
|
2450
|
+
}
|
|
2451
|
+
return this.containerManager.run(image, containerId);
|
|
2452
|
+
}
|
|
2453
|
+
};
|
|
2454
|
+
var logger3 = createLogger("agentx/AgentManager");
|
|
2455
|
+
var AgentManager = class {
|
|
2456
|
+
constructor(containerManager) {
|
|
2457
|
+
this.containerManager = containerManager;
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* Get an existing agent by ID
|
|
2461
|
+
*/
|
|
2462
|
+
get(agentId) {
|
|
2463
|
+
return this.containerManager.getAgent(agentId);
|
|
2464
|
+
}
|
|
2465
|
+
/**
|
|
2466
|
+
* Check if an agent exists
|
|
2467
|
+
*/
|
|
2468
|
+
has(agentId) {
|
|
2469
|
+
return this.containerManager.hasAgent(agentId);
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* List all agents
|
|
2473
|
+
*/
|
|
2474
|
+
list() {
|
|
2475
|
+
return this.containerManager.listAgents();
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Destroy an agent by ID
|
|
2479
|
+
*/
|
|
2480
|
+
async destroy(agentId) {
|
|
2481
|
+
logger3.debug("Destroying agent", { agentId });
|
|
2482
|
+
await this.containerManager.destroyAgent(agentId);
|
|
2483
|
+
logger3.info("Agent destroyed", { agentId });
|
|
2484
|
+
}
|
|
2485
|
+
/**
|
|
2486
|
+
* Destroy all agents
|
|
2487
|
+
*/
|
|
2488
|
+
async destroyAll() {
|
|
2489
|
+
const agents = this.containerManager.listAgents();
|
|
2490
|
+
logger3.debug("Destroying all agents", { count: agents.length });
|
|
2491
|
+
await this.containerManager.destroyAllAgents();
|
|
2492
|
+
logger3.info("All agents destroyed", { count: agents.length });
|
|
2493
|
+
}
|
|
2494
|
+
};
|
|
2495
|
+
var logger4 = createLogger("agentx/SessionManager");
|
|
2496
|
+
function generateSessionId() {
|
|
2497
|
+
const timestamp = Date.now().toString(36);
|
|
2498
|
+
const random = Math.random().toString(36).substring(2, 8);
|
|
2499
|
+
return `session_${timestamp}_${random}`;
|
|
2500
|
+
}
|
|
2501
|
+
function generateImageId() {
|
|
2502
|
+
const timestamp = Date.now().toString(36);
|
|
2503
|
+
const random = Math.random().toString(36).substring(2, 8);
|
|
2504
|
+
return `image_${timestamp}_${random}`;
|
|
2505
|
+
}
|
|
2506
|
+
var SessionImpl = class _SessionImpl {
|
|
2507
|
+
constructor(record, repository, containerManager, defaultContainerId) {
|
|
2508
|
+
__publicField2(this, "sessionId");
|
|
2509
|
+
__publicField2(this, "userId");
|
|
2510
|
+
__publicField2(this, "imageId");
|
|
2511
|
+
__publicField2(this, "createdAt");
|
|
2512
|
+
__publicField2(this, "_title");
|
|
2513
|
+
__publicField2(this, "_updatedAt");
|
|
2514
|
+
__publicField2(this, "repository");
|
|
2515
|
+
__publicField2(this, "containerManager");
|
|
2516
|
+
__publicField2(this, "defaultContainerId");
|
|
2517
|
+
this.sessionId = record.sessionId;
|
|
2518
|
+
this.userId = record.userId;
|
|
2519
|
+
this.imageId = record.imageId;
|
|
2520
|
+
this._title = record.title;
|
|
2521
|
+
this.createdAt = record.createdAt.getTime();
|
|
2522
|
+
this._updatedAt = record.updatedAt.getTime();
|
|
2523
|
+
this.repository = repository;
|
|
2524
|
+
this.containerManager = containerManager;
|
|
2525
|
+
this.defaultContainerId = defaultContainerId;
|
|
2526
|
+
}
|
|
2527
|
+
get title() {
|
|
2528
|
+
return this._title;
|
|
2529
|
+
}
|
|
2530
|
+
get updatedAt() {
|
|
2531
|
+
return this._updatedAt;
|
|
2532
|
+
}
|
|
2533
|
+
async resume(options) {
|
|
2534
|
+
logger4.info("Resuming agent from session", {
|
|
2535
|
+
sessionId: this.sessionId,
|
|
2536
|
+
imageId: this.imageId,
|
|
2537
|
+
containerId: options == null ? void 0 : options.containerId
|
|
2538
|
+
});
|
|
2539
|
+
let containerId = (options == null ? void 0 : options.containerId) || this.defaultContainerId;
|
|
2540
|
+
if (!containerId) {
|
|
2541
|
+
const container = await this.containerManager.create();
|
|
2542
|
+
containerId = container.containerId;
|
|
2543
|
+
logger4.debug("Auto-created default container for session", {
|
|
2544
|
+
containerId,
|
|
2545
|
+
sessionId: this.sessionId
|
|
2546
|
+
});
|
|
2547
|
+
}
|
|
2548
|
+
const agent = await this.containerManager.resume(this, containerId);
|
|
2549
|
+
this.collect(agent);
|
|
2550
|
+
return agent;
|
|
2551
|
+
}
|
|
2552
|
+
collect(agent) {
|
|
2553
|
+
logger4.debug("Collecting messages from agent", {
|
|
2554
|
+
sessionId: this.sessionId,
|
|
2555
|
+
agentId: agent.agentId
|
|
2556
|
+
});
|
|
2557
|
+
const sessionId = this.sessionId;
|
|
2558
|
+
const repository = this.repository;
|
|
2559
|
+
const saveMessage = (data, role) => {
|
|
2560
|
+
const record = {
|
|
2561
|
+
messageId: data.id,
|
|
2562
|
+
sessionId,
|
|
2563
|
+
role,
|
|
2564
|
+
content: data,
|
|
2565
|
+
createdAt: new Date(data.timestamp ?? Date.now())
|
|
2566
|
+
};
|
|
2567
|
+
repository.saveMessage(record).catch((error) => {
|
|
2568
|
+
logger4.error("Failed to persist message", {
|
|
2569
|
+
sessionId,
|
|
2570
|
+
messageId: record.messageId,
|
|
2571
|
+
error
|
|
2572
|
+
});
|
|
2573
|
+
});
|
|
2574
|
+
};
|
|
2575
|
+
agent.on("user_message", (event) => saveMessage(event.data, "user"));
|
|
2576
|
+
agent.on("assistant_message", (event) => saveMessage(event.data, "assistant"));
|
|
2577
|
+
agent.on("tool_call_message", (event) => saveMessage(event.data, "tool"));
|
|
2578
|
+
agent.on("tool_result_message", (event) => saveMessage(event.data, "tool"));
|
|
2579
|
+
}
|
|
2580
|
+
async getMessages() {
|
|
2581
|
+
logger4.debug("Getting messages for session", { sessionId: this.sessionId });
|
|
2582
|
+
const records = await this.repository.findMessagesBySessionId(this.sessionId);
|
|
2583
|
+
return records.map((record) => record.content);
|
|
2584
|
+
}
|
|
2585
|
+
async fork() {
|
|
2586
|
+
logger4.info("Forking session", { sessionId: this.sessionId });
|
|
2587
|
+
const imageRecord = await this.repository.findImageById(this.imageId);
|
|
2588
|
+
if (!imageRecord) {
|
|
2589
|
+
throw new Error(`Image not found: ${this.imageId}`);
|
|
2590
|
+
}
|
|
2591
|
+
const newImageId = generateImageId();
|
|
2592
|
+
const newImageRecord = {
|
|
2593
|
+
imageId: newImageId,
|
|
2594
|
+
type: "derived",
|
|
2595
|
+
definitionName: imageRecord.definitionName,
|
|
2596
|
+
parentImageId: imageRecord.imageId,
|
|
2597
|
+
definition: imageRecord.definition,
|
|
2598
|
+
config: imageRecord.config,
|
|
2599
|
+
messages: [...imageRecord.messages],
|
|
2600
|
+
// Copy messages
|
|
2601
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
2602
|
+
};
|
|
2603
|
+
await this.repository.saveImage(newImageRecord);
|
|
2604
|
+
const newSessionId = generateSessionId();
|
|
2605
|
+
const now = /* @__PURE__ */ new Date();
|
|
2606
|
+
const newSessionRecord = {
|
|
2607
|
+
sessionId: newSessionId,
|
|
2608
|
+
userId: this.userId,
|
|
2609
|
+
imageId: newImageId,
|
|
2610
|
+
title: this._title ? `Fork of ${this._title}` : null,
|
|
2611
|
+
createdAt: now,
|
|
2612
|
+
updatedAt: now
|
|
2613
|
+
};
|
|
2614
|
+
await this.repository.saveSession(newSessionRecord);
|
|
2615
|
+
logger4.info("Session forked", {
|
|
2616
|
+
originalSessionId: this.sessionId,
|
|
2617
|
+
newSessionId,
|
|
2618
|
+
newImageId
|
|
2619
|
+
});
|
|
2620
|
+
return new _SessionImpl(
|
|
2621
|
+
newSessionRecord,
|
|
2622
|
+
this.repository,
|
|
2623
|
+
this.containerManager,
|
|
2624
|
+
this.defaultContainerId
|
|
2625
|
+
);
|
|
2626
|
+
}
|
|
2627
|
+
async setTitle(title) {
|
|
2628
|
+
logger4.debug("Setting session title", { sessionId: this.sessionId, title });
|
|
2629
|
+
const now = /* @__PURE__ */ new Date();
|
|
2630
|
+
await this.repository.saveSession({
|
|
2631
|
+
sessionId: this.sessionId,
|
|
2632
|
+
userId: this.userId,
|
|
2633
|
+
imageId: this.imageId,
|
|
2634
|
+
title,
|
|
2635
|
+
createdAt: new Date(this.createdAt),
|
|
2636
|
+
updatedAt: now
|
|
2637
|
+
});
|
|
2638
|
+
this._title = title;
|
|
2639
|
+
this._updatedAt = now.getTime();
|
|
2640
|
+
logger4.info("Session title updated", { sessionId: this.sessionId, title });
|
|
2641
|
+
}
|
|
2642
|
+
};
|
|
2643
|
+
var SessionManagerImpl = class {
|
|
2644
|
+
constructor(repository, containerManager, defaultContainerId) {
|
|
2645
|
+
__publicField2(this, "repository");
|
|
2646
|
+
__publicField2(this, "containerManager");
|
|
2647
|
+
__publicField2(this, "defaultContainerId");
|
|
2648
|
+
this.repository = repository;
|
|
2649
|
+
this.containerManager = containerManager;
|
|
2650
|
+
this.defaultContainerId = defaultContainerId;
|
|
2651
|
+
}
|
|
2652
|
+
async create(imageId, userId) {
|
|
2653
|
+
const sessionId = generateSessionId();
|
|
2654
|
+
const now = /* @__PURE__ */ new Date();
|
|
2655
|
+
const record = {
|
|
2656
|
+
sessionId,
|
|
2657
|
+
userId,
|
|
2658
|
+
imageId,
|
|
2659
|
+
title: null,
|
|
2660
|
+
createdAt: now,
|
|
2661
|
+
updatedAt: now
|
|
2662
|
+
};
|
|
2663
|
+
await this.repository.saveSession(record);
|
|
2664
|
+
logger4.info("Session created", { sessionId, imageId, userId });
|
|
2665
|
+
return new SessionImpl(record, this.repository, this.containerManager, this.defaultContainerId);
|
|
2666
|
+
}
|
|
2667
|
+
async get(sessionId) {
|
|
2668
|
+
const record = await this.repository.findSessionById(sessionId);
|
|
2669
|
+
if (!record) return void 0;
|
|
2670
|
+
return new SessionImpl(record, this.repository, this.containerManager, this.defaultContainerId);
|
|
2671
|
+
}
|
|
2672
|
+
async has(sessionId) {
|
|
2673
|
+
return this.repository.sessionExists(sessionId);
|
|
2674
|
+
}
|
|
2675
|
+
async list() {
|
|
2676
|
+
const records = await this.repository.findAllSessions();
|
|
2677
|
+
return records.map(
|
|
2678
|
+
(r) => new SessionImpl(r, this.repository, this.containerManager, this.defaultContainerId)
|
|
2679
|
+
);
|
|
2680
|
+
}
|
|
2681
|
+
async listByImage(imageId) {
|
|
2682
|
+
const records = await this.repository.findSessionsByImageId(imageId);
|
|
2683
|
+
return records.map(
|
|
2684
|
+
(r) => new SessionImpl(r, this.repository, this.containerManager, this.defaultContainerId)
|
|
2685
|
+
);
|
|
2686
|
+
}
|
|
2687
|
+
async listByUser(userId) {
|
|
2688
|
+
const records = await this.repository.findSessionsByUserId(userId);
|
|
2689
|
+
return records.map(
|
|
2690
|
+
(r) => new SessionImpl(r, this.repository, this.containerManager, this.defaultContainerId)
|
|
2691
|
+
);
|
|
2692
|
+
}
|
|
2693
|
+
async destroy(sessionId) {
|
|
2694
|
+
await this.repository.deleteSession(sessionId);
|
|
2695
|
+
logger4.info("Session destroyed", { sessionId });
|
|
2696
|
+
}
|
|
2697
|
+
async destroyByImage(imageId) {
|
|
2698
|
+
await this.repository.deleteSessionsByImageId(imageId);
|
|
2699
|
+
logger4.info("Sessions destroyed by image", { imageId });
|
|
2700
|
+
}
|
|
2701
|
+
async destroyAll() {
|
|
2702
|
+
const sessions = await this.repository.findAllSessions();
|
|
2703
|
+
for (const session of sessions) {
|
|
2704
|
+
await this.repository.deleteSession(session.sessionId);
|
|
2705
|
+
}
|
|
2706
|
+
logger4.info("All sessions destroyed");
|
|
2707
|
+
}
|
|
2708
|
+
};
|
|
2709
|
+
var logger5 = createLogger("agentx/ErrorManager");
|
|
2710
|
+
var ErrorManager = class {
|
|
2711
|
+
constructor() {
|
|
2712
|
+
__publicField2(this, "handlers", /* @__PURE__ */ new Set());
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Handle an error from any agent
|
|
2716
|
+
*
|
|
2717
|
+
* Called internally when an agent emits an error event.
|
|
2718
|
+
* 1. Default logging (always)
|
|
2719
|
+
* 2. Custom handlers (user-registered)
|
|
2720
|
+
*/
|
|
2721
|
+
handle(agentId, error, event) {
|
|
2722
|
+
this.logError(agentId, error);
|
|
2723
|
+
for (const handler of this.handlers) {
|
|
2724
|
+
try {
|
|
2725
|
+
handler.handle(agentId, error, event);
|
|
2726
|
+
} catch (e) {
|
|
2727
|
+
logger5.error("ErrorHandler failed", { error: e });
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
/**
|
|
2732
|
+
* Add a custom error handler
|
|
2733
|
+
*/
|
|
2734
|
+
addHandler(handler) {
|
|
2735
|
+
this.handlers.add(handler);
|
|
2736
|
+
return () => {
|
|
2737
|
+
this.handlers.delete(handler);
|
|
2738
|
+
};
|
|
2739
|
+
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Remove an error handler
|
|
2742
|
+
*/
|
|
2743
|
+
removeHandler(handler) {
|
|
2744
|
+
this.handlers.delete(handler);
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* Default error logging
|
|
2748
|
+
*/
|
|
2749
|
+
logError(agentId, error) {
|
|
2750
|
+
const prefix = `[${agentId}] ${error.category}/${error.code}`;
|
|
2751
|
+
if (error.severity === "fatal") {
|
|
2752
|
+
logger5.error(`${prefix}: ${error.message}`, { error });
|
|
2753
|
+
} else if (error.severity === "error") {
|
|
2754
|
+
logger5.error(`${prefix}: ${error.message}`);
|
|
2755
|
+
} else {
|
|
2756
|
+
logger5.warn(`${prefix}: ${error.message}`);
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
};
|
|
2760
|
+
var logger6 = createLogger("agentx/ContainerManager");
|
|
2761
|
+
function generateContainerId() {
|
|
2762
|
+
const timestamp = Date.now().toString(36);
|
|
2763
|
+
const random = Math.random().toString(36).substring(2, 8);
|
|
2764
|
+
return `container_${timestamp}_${random}`;
|
|
2765
|
+
}
|
|
2766
|
+
function generateAgentId() {
|
|
2767
|
+
const timestamp = Date.now().toString(36);
|
|
2768
|
+
const random = Math.random().toString(36).substring(2, 8);
|
|
2769
|
+
return `agent_${timestamp}_${random}`;
|
|
2770
|
+
}
|
|
2771
|
+
var ContainerManagerImpl = class {
|
|
2772
|
+
constructor(runtime, repository) {
|
|
2773
|
+
__publicField2(this, "agents", /* @__PURE__ */ new Map());
|
|
2774
|
+
__publicField2(this, "engine");
|
|
2775
|
+
__publicField2(this, "runtime");
|
|
2776
|
+
__publicField2(this, "repository");
|
|
2777
|
+
this.runtime = runtime;
|
|
2778
|
+
this.repository = repository;
|
|
2779
|
+
this.engine = new AgentEngine();
|
|
2780
|
+
}
|
|
2781
|
+
// ==================== Container Lifecycle ====================
|
|
2782
|
+
async create(config2) {
|
|
2783
|
+
const containerId = generateContainerId();
|
|
2784
|
+
const now = Date.now();
|
|
2785
|
+
const record = {
|
|
2786
|
+
containerId,
|
|
2787
|
+
createdAt: now,
|
|
2788
|
+
updatedAt: now,
|
|
2789
|
+
config: config2
|
|
2790
|
+
};
|
|
2791
|
+
await this.repository.saveContainer(record);
|
|
2792
|
+
logger6.info("Container created", { containerId });
|
|
2793
|
+
return record;
|
|
2794
|
+
}
|
|
2795
|
+
async get(containerId) {
|
|
2796
|
+
return this.repository.findContainerById(containerId);
|
|
2797
|
+
}
|
|
2798
|
+
async list() {
|
|
2799
|
+
return this.repository.findAllContainers();
|
|
2800
|
+
}
|
|
2801
|
+
async delete(containerId) {
|
|
2802
|
+
const exists = await this.repository.containerExists(containerId);
|
|
2803
|
+
if (!exists) {
|
|
2804
|
+
return false;
|
|
2805
|
+
}
|
|
2806
|
+
await this.repository.deleteContainer(containerId);
|
|
2807
|
+
logger6.info("Container deleted", { containerId });
|
|
2808
|
+
return true;
|
|
2809
|
+
}
|
|
2810
|
+
async exists(containerId) {
|
|
2811
|
+
return this.repository.containerExists(containerId);
|
|
2812
|
+
}
|
|
2813
|
+
// ==================== Agent Runtime ====================
|
|
2814
|
+
async run(image, containerId) {
|
|
2815
|
+
logger6.info("Running agent from image", {
|
|
2816
|
+
imageId: image.imageId,
|
|
2817
|
+
containerId
|
|
2818
|
+
});
|
|
2819
|
+
const container = await this.repository.findContainerById(containerId);
|
|
2820
|
+
if (!container) {
|
|
2821
|
+
throw new Error(`Container not found: ${containerId}`);
|
|
2822
|
+
}
|
|
2823
|
+
let agentId;
|
|
2824
|
+
if (this.runtime.agentIdResolver) {
|
|
2825
|
+
agentId = await this.runtime.agentIdResolver.resolveForRun(image.imageId, containerId);
|
|
2826
|
+
} else {
|
|
2827
|
+
agentId = generateAgentId();
|
|
2828
|
+
}
|
|
2829
|
+
const context = {
|
|
2830
|
+
agentId,
|
|
2831
|
+
createdAt: Date.now()
|
|
2832
|
+
};
|
|
2833
|
+
const sandbox = this.runtime.createSandbox(containerId);
|
|
2834
|
+
const driver = this.runtime.createDriver(image.definition, context, sandbox);
|
|
2835
|
+
const agent = new AgentInstance(image.definition, context, this.engine, driver, sandbox);
|
|
2836
|
+
this.agents.set(agentId, agent);
|
|
2837
|
+
logger6.info("Agent started", {
|
|
2838
|
+
agentId,
|
|
2839
|
+
imageId: image.imageId,
|
|
2840
|
+
containerId,
|
|
2841
|
+
definitionName: image.definition.name
|
|
2842
|
+
});
|
|
2843
|
+
return agent;
|
|
2844
|
+
}
|
|
2845
|
+
async resume(session, containerId) {
|
|
2846
|
+
logger6.info("Resuming agent from session", {
|
|
2847
|
+
sessionId: session.sessionId,
|
|
2848
|
+
imageId: session.imageId,
|
|
2849
|
+
containerId
|
|
2850
|
+
});
|
|
2851
|
+
const container = await this.repository.findContainerById(containerId);
|
|
2852
|
+
if (!container) {
|
|
2853
|
+
throw new Error(`Container not found: ${containerId}`);
|
|
2854
|
+
}
|
|
2855
|
+
const imageRecord = await this.repository.findImageById(session.imageId);
|
|
2856
|
+
if (!imageRecord) {
|
|
2857
|
+
throw new Error(`Image not found: ${session.imageId}`);
|
|
2858
|
+
}
|
|
2859
|
+
let agentId;
|
|
2860
|
+
if (this.runtime.agentIdResolver) {
|
|
2861
|
+
agentId = await this.runtime.agentIdResolver.resolveForResume(session.sessionId, containerId);
|
|
2862
|
+
} else {
|
|
2863
|
+
agentId = generateAgentId();
|
|
2864
|
+
}
|
|
2865
|
+
const context = {
|
|
2866
|
+
agentId,
|
|
2867
|
+
createdAt: Date.now()
|
|
2868
|
+
};
|
|
2869
|
+
const sandbox = this.runtime.createSandbox(containerId);
|
|
2870
|
+
const definition = imageRecord.definition;
|
|
2871
|
+
const driver = this.runtime.createDriver(definition, context, sandbox);
|
|
2872
|
+
const agent = new AgentInstance(definition, context, this.engine, driver, sandbox);
|
|
2873
|
+
this.agents.set(agentId, agent);
|
|
2874
|
+
logger6.info("Agent resumed", {
|
|
2875
|
+
agentId,
|
|
2876
|
+
sessionId: session.sessionId,
|
|
2877
|
+
imageId: session.imageId,
|
|
2878
|
+
containerId
|
|
2879
|
+
});
|
|
2880
|
+
return agent;
|
|
2881
|
+
}
|
|
2882
|
+
async destroyAgent(agentId) {
|
|
2883
|
+
const agent = this.agents.get(agentId);
|
|
2884
|
+
if (!agent) {
|
|
2885
|
+
logger6.warn("Agent not found for destroy", { agentId });
|
|
2886
|
+
return;
|
|
2887
|
+
}
|
|
2888
|
+
logger6.debug("Destroying agent", { agentId });
|
|
2889
|
+
await agent.destroy();
|
|
2890
|
+
this.agents.delete(agentId);
|
|
2891
|
+
logger6.info("Agent destroyed", { agentId });
|
|
2892
|
+
}
|
|
2893
|
+
getAgent(agentId) {
|
|
2894
|
+
return this.agents.get(agentId);
|
|
2895
|
+
}
|
|
2896
|
+
hasAgent(agentId) {
|
|
2897
|
+
return this.agents.has(agentId);
|
|
2898
|
+
}
|
|
2899
|
+
listAgents() {
|
|
2900
|
+
return Array.from(this.agents.values());
|
|
2901
|
+
}
|
|
2902
|
+
async destroyAllAgents() {
|
|
2903
|
+
const agentIds = Array.from(this.agents.keys());
|
|
2904
|
+
logger6.debug("Destroying all agents", { count: agentIds.length });
|
|
2905
|
+
await Promise.all(agentIds.map((id) => this.destroyAgent(id)));
|
|
2906
|
+
logger6.info("All agents destroyed", { count: agentIds.length });
|
|
2907
|
+
}
|
|
2908
|
+
};
|
|
2909
|
+
var logger7 = createLogger("agentx/AgentX");
|
|
2910
|
+
function createAgentX(runtime, options) {
|
|
2911
|
+
logger7.info("Creating AgentX instance", { runtime: runtime.name });
|
|
2912
|
+
if (!runtime.repository) {
|
|
2913
|
+
throw new Error("Runtime must have a repository for persistence");
|
|
2914
|
+
}
|
|
2915
|
+
const repository = runtime.repository;
|
|
2916
|
+
const containerManager = new ContainerManagerImpl(runtime, repository);
|
|
2917
|
+
const errorManager = new ErrorManager();
|
|
2918
|
+
const definitionManager = new DefinitionManagerImpl(repository);
|
|
2919
|
+
const agentManager = new AgentManager(containerManager);
|
|
2920
|
+
const imageManager = new ImageManagerImpl(repository, containerManager, options == null ? void 0 : options.containerId);
|
|
2921
|
+
const sessionManager = new SessionManagerImpl(repository, containerManager, options == null ? void 0 : options.containerId);
|
|
2922
|
+
logger7.debug("AgentX instance created", { runtime: runtime.name });
|
|
2923
|
+
return {
|
|
2924
|
+
mode: "local",
|
|
2925
|
+
containers: containerManager,
|
|
2926
|
+
definitions: definitionManager,
|
|
2927
|
+
images: imageManager,
|
|
2928
|
+
agents: agentManager,
|
|
2929
|
+
sessions: sessionManager,
|
|
2930
|
+
errors: errorManager
|
|
2931
|
+
};
|
|
2932
|
+
}
|
|
2933
|
+
createLogger("agentx/RemoteRepository");
|
|
2934
|
+
var _BrowserLogger = class _BrowserLogger2 {
|
|
2935
|
+
constructor(name, options = {}) {
|
|
2936
|
+
__publicField2(this, "name");
|
|
2937
|
+
__publicField2(this, "level");
|
|
2938
|
+
__publicField2(this, "collapsed");
|
|
2939
|
+
this.name = name;
|
|
2940
|
+
this.level = options.level ?? LogLevel.INFO;
|
|
2941
|
+
this.collapsed = options.collapsed ?? true;
|
|
2942
|
+
}
|
|
2943
|
+
debug(message, context) {
|
|
2944
|
+
if (this.isDebugEnabled()) {
|
|
2945
|
+
this.log("DEBUG", message, context);
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
info(message, context) {
|
|
2949
|
+
if (this.isInfoEnabled()) {
|
|
2950
|
+
this.log("INFO", message, context);
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
warn(message, context) {
|
|
2954
|
+
if (this.isWarnEnabled()) {
|
|
2955
|
+
this.log("WARN", message, context);
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
error(message, context) {
|
|
2959
|
+
if (this.isErrorEnabled()) {
|
|
2960
|
+
if (message instanceof Error) {
|
|
2961
|
+
this.log("ERROR", message.message, { ...context, stack: message.stack });
|
|
2962
|
+
} else {
|
|
2963
|
+
this.log("ERROR", message, context);
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
isDebugEnabled() {
|
|
2968
|
+
return this.level <= LogLevel.DEBUG;
|
|
2969
|
+
}
|
|
2970
|
+
isInfoEnabled() {
|
|
2971
|
+
return this.level <= LogLevel.INFO;
|
|
2972
|
+
}
|
|
2973
|
+
isWarnEnabled() {
|
|
2974
|
+
return this.level <= LogLevel.WARN;
|
|
2975
|
+
}
|
|
2976
|
+
isErrorEnabled() {
|
|
2977
|
+
return this.level <= LogLevel.ERROR;
|
|
2978
|
+
}
|
|
2979
|
+
log(level, message, context) {
|
|
2980
|
+
const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
2981
|
+
const consoleMethod = this.getConsoleMethod(level);
|
|
2982
|
+
const badgeStyle = _BrowserLogger2.BADGE_STYLES[level];
|
|
2983
|
+
const format = `%c${timestamp} %c${level}%c %c[${this.name}]%c ${message}`;
|
|
2984
|
+
const styles = [
|
|
2985
|
+
_BrowserLogger2.STYLES.TIMESTAMP,
|
|
2986
|
+
badgeStyle,
|
|
2987
|
+
"",
|
|
2988
|
+
// reset after badge
|
|
2989
|
+
_BrowserLogger2.STYLES.NAME,
|
|
2990
|
+
_BrowserLogger2.STYLES.MESSAGE
|
|
2991
|
+
];
|
|
2992
|
+
if (context && Object.keys(context).length > 0) {
|
|
2993
|
+
const groupMethod = this.collapsed ? console.groupCollapsed : console.group;
|
|
2994
|
+
groupMethod.call(console, format, ...styles);
|
|
2995
|
+
console.log("Context:", context);
|
|
2996
|
+
console.groupEnd();
|
|
2997
|
+
} else {
|
|
2998
|
+
consoleMethod(format, ...styles);
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
getConsoleMethod(level) {
|
|
3002
|
+
switch (level) {
|
|
3003
|
+
case "DEBUG":
|
|
3004
|
+
return console.debug.bind(console);
|
|
3005
|
+
case "INFO":
|
|
3006
|
+
return console.info.bind(console);
|
|
3007
|
+
case "WARN":
|
|
3008
|
+
return console.warn.bind(console);
|
|
3009
|
+
case "ERROR":
|
|
3010
|
+
return console.error.bind(console);
|
|
3011
|
+
default:
|
|
3012
|
+
return console.log.bind(console);
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
};
|
|
3016
|
+
__publicField2(_BrowserLogger, "STYLES", {
|
|
3017
|
+
DEBUG: "color: #6B7280; font-weight: normal;",
|
|
3018
|
+
// gray
|
|
3019
|
+
INFO: "color: #10B981; font-weight: normal;",
|
|
3020
|
+
// green
|
|
3021
|
+
WARN: "color: #F59E0B; font-weight: bold;",
|
|
3022
|
+
// amber
|
|
3023
|
+
ERROR: "color: #EF4444; font-weight: bold;",
|
|
3024
|
+
// red
|
|
3025
|
+
TIMESTAMP: "color: #9CA3AF; font-weight: normal;",
|
|
3026
|
+
// light gray
|
|
3027
|
+
NAME: "color: #8B5CF6; font-weight: normal;",
|
|
3028
|
+
// purple
|
|
3029
|
+
MESSAGE: "color: inherit; font-weight: normal;"
|
|
3030
|
+
});
|
|
3031
|
+
__publicField2(_BrowserLogger, "BADGE_STYLES", {
|
|
3032
|
+
DEBUG: "background: #E5E7EB; color: #374151; padding: 2px 6px; border-radius: 3px; font-size: 11px;",
|
|
3033
|
+
INFO: "background: #D1FAE5; color: #065F46; padding: 2px 6px; border-radius: 3px; font-size: 11px;",
|
|
3034
|
+
WARN: "background: #FEF3C7; color: #92400E; padding: 2px 6px; border-radius: 3px; font-size: 11px;",
|
|
3035
|
+
ERROR: "background: #FEE2E2; color: #991B1B; padding: 2px 6px; border-radius: 3px; font-size: 11px;"
|
|
3036
|
+
});
|
|
3037
|
+
createLogger("agentx/RemoteAgentIdResolver");
|
|
3038
|
+
export {
|
|
3039
|
+
createAgentX
|
|
3040
|
+
};
|
|
3041
|
+
//# sourceMappingURL=index-CB5mSMCj.js.map
|