@ai-setting/roy-agent-core 1.4.10 → 1.4.12

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.
Files changed (39) hide show
  1. package/dist/config/index.js +23 -0
  2. package/dist/env/agent/index.js +3035 -0
  3. package/dist/env/commands/index.js +1685 -0
  4. package/dist/env/debug/formatters/index.js +639 -0
  5. package/dist/env/debug/index.js +2300 -0
  6. package/dist/env/hook/index.js +273 -0
  7. package/dist/env/index.js +12591 -0
  8. package/dist/env/llm/index.js +2736 -0
  9. package/dist/env/log-trace/index.js +1779 -0
  10. package/dist/env/mcp/index.js +2173 -0
  11. package/dist/env/mcp/tool/index.js +1149 -0
  12. package/dist/env/memory/built-in/index.js +225 -0
  13. package/dist/env/memory/index.js +2171 -0
  14. package/dist/env/memory/plugin/index.js +1263 -0
  15. package/dist/env/prompt/index.js +2107 -0
  16. package/dist/env/session/index.js +3594 -0
  17. package/dist/env/session/storage/index.js +2049 -0
  18. package/dist/env/skill/index.js +1635 -0
  19. package/dist/env/skill/tool/index.js +114 -0
  20. package/dist/env/task/delegate/index.js +1844 -0
  21. package/dist/env/task/hooks/index.js +67 -0
  22. package/dist/env/task/index.js +3578 -0
  23. package/dist/env/task/plugins/index.js +1626 -0
  24. package/dist/env/task/storage/index.js +1464 -0
  25. package/dist/env/task/tools/index.js +344 -0
  26. package/dist/env/task/tools/operation/index.js +270 -0
  27. package/dist/env/tool/built-in/index.js +1151 -0
  28. package/dist/env/tool/index.js +2284 -0
  29. package/dist/env/workflow/decorators/index.js +449 -0
  30. package/dist/env/workflow/engine/index.js +4391 -0
  31. package/dist/env/workflow/index.js +6214 -0
  32. package/dist/env/workflow/nodes/index.js +650 -0
  33. package/dist/env/workflow/service/index.js +262 -0
  34. package/dist/env/workflow/storage/index.js +1236 -0
  35. package/dist/env/workflow/tools/index.js +1081 -0
  36. package/dist/env/workflow/types/index.js +479 -0
  37. package/dist/env/workflow/utils/index.js +1631 -0
  38. package/dist/index.js +15006 -14265
  39. package/package.json +2 -2
@@ -0,0 +1,3035 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
26
+ var __returnValue = (v) => v;
27
+ function __exportSetter(name, newValue) {
28
+ this[name] = __returnValue.bind(null, newValue);
29
+ }
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, {
33
+ get: all[name],
34
+ enumerable: true,
35
+ configurable: true,
36
+ set: __exportSetter.bind(all, name)
37
+ });
38
+ };
39
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
40
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
41
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
42
+ r = Reflect.decorate(decorators, target, key, desc);
43
+ else
44
+ for (var i = decorators.length - 1;i >= 0; i--)
45
+ if (d = decorators[i])
46
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
47
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
48
+ };
49
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
50
+ var __require = import.meta.require;
51
+
52
+ // packages/core/src/env/log-trace/span-storage.ts
53
+ var exports_span_storage = {};
54
+ __export(exports_span_storage, {
55
+ SQLiteSpanStorage: () => SQLiteSpanStorage
56
+ });
57
+
58
+ class SQLiteSpanStorage {
59
+ db = null;
60
+ dbPath;
61
+ initialized = false;
62
+ constructor(dbPath) {
63
+ if (!dbPath) {
64
+ throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
65
+ }
66
+ if (dbPath === ":memory:") {
67
+ throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
68
+ }
69
+ this.dbPath = dbPath;
70
+ }
71
+ async initialize() {
72
+ if (this.initialized)
73
+ return;
74
+ const { Database } = __require("bun:sqlite");
75
+ const fs = __require("fs");
76
+ const path = __require("path");
77
+ const dir = path.dirname(this.dbPath);
78
+ if (!fs.existsSync(dir)) {
79
+ fs.mkdirSync(dir, { recursive: true });
80
+ }
81
+ this.db = new Database(this.dbPath);
82
+ this.db.run("PRAGMA journal_mode=WAL");
83
+ this.db.run("PRAGMA busy_timeout=5000");
84
+ this.db.run("PRAGMA synchronous=NORMAL");
85
+ this.db.run(`
86
+ CREATE TABLE IF NOT EXISTS span (
87
+ span_id TEXT PRIMARY KEY,
88
+ trace_id TEXT NOT NULL,
89
+ parent_span_id TEXT,
90
+ name TEXT NOT NULL,
91
+ kind TEXT NOT NULL,
92
+ status TEXT NOT NULL,
93
+ start_time INTEGER NOT NULL,
94
+ end_time INTEGER,
95
+ attributes TEXT,
96
+ result TEXT,
97
+ error TEXT,
98
+ time_created INTEGER NOT NULL
99
+ )
100
+ `);
101
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
102
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
103
+ this.initialized = true;
104
+ }
105
+ save(span) {
106
+ if (!this.db)
107
+ return;
108
+ const stmt = this.db.prepare(`
109
+ INSERT OR REPLACE INTO span
110
+ (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
111
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
112
+ `);
113
+ const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
114
+ stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, JSON.stringify(span.attributes), resultValue, span.error || null, Date.now());
115
+ }
116
+ saveBatch(spans) {
117
+ for (const span of spans) {
118
+ this.save(span);
119
+ }
120
+ }
121
+ findByTraceId(traceId) {
122
+ if (!this.db)
123
+ return [];
124
+ const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
125
+ return this.buildTree(rows.map(this.rowToSpan));
126
+ }
127
+ findBySpanId(spanId) {
128
+ if (!this.db)
129
+ return;
130
+ const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
131
+ return row ? this.rowToSpan(row) : undefined;
132
+ }
133
+ listTraces(limit = 10) {
134
+ if (!this.db)
135
+ return [];
136
+ const rows = this.db.prepare(`
137
+ SELECT trace_id,
138
+ MIN(start_time) as start_time,
139
+ MAX(end_time) as end_time,
140
+ COUNT(*) as span_count
141
+ FROM span
142
+ GROUP BY trace_id
143
+ ORDER BY start_time DESC
144
+ LIMIT ?
145
+ `).all(limit);
146
+ return rows.map((row) => ({
147
+ traceId: row.trace_id,
148
+ rootSpanName: "unknown",
149
+ startTime: row.start_time,
150
+ endTime: row.end_time,
151
+ duration: row.end_time - row.start_time,
152
+ spanCount: row.span_count,
153
+ status: "ok"
154
+ }));
155
+ }
156
+ deleteByTraceId(traceId) {
157
+ if (this.db) {
158
+ this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
159
+ }
160
+ }
161
+ close() {
162
+ if (this.db) {
163
+ this.db.close();
164
+ this.db = null;
165
+ }
166
+ }
167
+ rowToSpan(row) {
168
+ return {
169
+ traceId: row.trace_id,
170
+ spanId: row.span_id,
171
+ parentSpanId: row.parent_span_id,
172
+ name: row.name,
173
+ kind: row.kind,
174
+ status: row.status,
175
+ startTime: row.start_time,
176
+ endTime: row.end_time,
177
+ attributes: row.attributes ? JSON.parse(row.attributes) : {},
178
+ result: row.result || undefined,
179
+ error: row.error || undefined
180
+ };
181
+ }
182
+ buildTree(spans) {
183
+ const spanMap = new Map;
184
+ const roots = [];
185
+ for (const span of spans) {
186
+ spanMap.set(span.spanId, { ...span, children: [] });
187
+ }
188
+ for (const span of spanMap.values()) {
189
+ if (span.parentSpanId) {
190
+ const parent = spanMap.get(span.parentSpanId);
191
+ if (parent) {
192
+ parent.children.push(span);
193
+ } else {
194
+ roots.push(span);
195
+ }
196
+ } else {
197
+ roots.push(span);
198
+ }
199
+ }
200
+ return roots;
201
+ }
202
+ }
203
+
204
+ // packages/core/src/env/log-trace/opentelemetry/propagation.ts
205
+ function padLeft(str, length) {
206
+ return str.padStart(length, "0");
207
+ }
208
+ function isValidHex(str) {
209
+ return /^[0-9a-f]+$/i.test(str);
210
+ }
211
+ function serialize(context) {
212
+ const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);
213
+ const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
214
+ const parts = [
215
+ TRACE_CONTEXT_VERSION,
216
+ traceId,
217
+ spanId,
218
+ TRACE_FLAGS_SAMPLED
219
+ ];
220
+ return parts.join("-");
221
+ }
222
+ function parse(traceparent) {
223
+ if (!traceparent || typeof traceparent !== "string") {
224
+ return;
225
+ }
226
+ const trimmed = traceparent.trim();
227
+ const parts = trimmed.split("-");
228
+ if (parts.length !== 4) {
229
+ return;
230
+ }
231
+ const [version, traceId, senderSpanId, flags] = parts;
232
+ if (version !== TRACE_CONTEXT_VERSION) {
233
+ if (version > TRACE_CONTEXT_VERSION) {
234
+ return;
235
+ }
236
+ }
237
+ if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
238
+ return;
239
+ }
240
+ if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
241
+ return;
242
+ }
243
+ if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
244
+ return;
245
+ }
246
+ return {
247
+ traceId: traceId.toLowerCase(),
248
+ spanId: senderSpanId.toLowerCase()
249
+ };
250
+ }
251
+ var TRACE_CONTEXT_VERSION = "00", TRACE_FLAGS_SAMPLED = "01", TRACEPARENT_HEADER = "TRACEPARENT", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;
252
+ var init_propagation = __esm(() => {
253
+ propagation = {
254
+ inject(carrier, context) {
255
+ carrier[TRACEPARENT_HEADER] = serialize(context);
256
+ },
257
+ extract(carrier) {
258
+ const traceparent = carrier[TRACEPARENT_HEADER];
259
+ if (!traceparent) {
260
+ return;
261
+ }
262
+ return parse(traceparent);
263
+ },
264
+ getTraceparentHeader() {
265
+ return TRACEPARENT_HEADER;
266
+ }
267
+ };
268
+ });
269
+
270
+ // packages/core/src/env/log-trace/types.ts
271
+ var SpanKind, SpanStatus;
272
+ var init_types = __esm(() => {
273
+ ((SpanKind2) => {
274
+ SpanKind2["CLIENT"] = "client";
275
+ SpanKind2["SERVER"] = "server";
276
+ SpanKind2["INTERNAL"] = "internal";
277
+ })(SpanKind ||= {});
278
+ ((SpanStatus2) => {
279
+ SpanStatus2["OK"] = "ok";
280
+ SpanStatus2["ERROR"] = "error";
281
+ })(SpanStatus ||= {});
282
+ });
283
+
284
+ // packages/core/src/env/log-trace/opentelemetry/tracer-provider.ts
285
+ var exports_tracer_provider = {};
286
+ __export(exports_tracer_provider, {
287
+ resetTracerProvider: () => resetTracerProvider,
288
+ getTracerProvider: () => getTracerProvider,
289
+ OTelTracerProvider: () => OTelTracerProvider
290
+ });
291
+
292
+ class OTelSpanImpl {
293
+ name;
294
+ kind;
295
+ spanContext;
296
+ attributes = {};
297
+ startTime;
298
+ endTime;
299
+ error;
300
+ storage;
301
+ parentSpanContext;
302
+ onEnd;
303
+ constructor(name, spanContext, storage, parentSpanContext, onEnd) {
304
+ this.name = name;
305
+ this.kind = "internal";
306
+ this.spanContext = spanContext;
307
+ this.parentSpanContext = parentSpanContext;
308
+ this.startTime = Date.now();
309
+ this.storage = storage;
310
+ this.onEnd = onEnd;
311
+ }
312
+ setAttribute(key, value) {
313
+ this.attributes[key] = value;
314
+ }
315
+ addEvent(name, attributes) {
316
+ const events = this.attributes._events || [];
317
+ events.push({ name, attributes });
318
+ this.attributes._events = events;
319
+ }
320
+ end(result, error) {
321
+ this.endTime = Date.now();
322
+ if (error) {
323
+ this.error = error.message;
324
+ }
325
+ this.storage.save({
326
+ traceId: this.spanContext.traceId,
327
+ spanId: this.spanContext.spanId,
328
+ parentSpanId: this.spanContext.parentSpanId,
329
+ name: this.name,
330
+ kind: this.kind,
331
+ status: error ? "error" /* ERROR */ : "ok" /* OK */,
332
+ startTime: this.startTime,
333
+ endTime: this.endTime,
334
+ attributes: this.attributes,
335
+ result,
336
+ error: this.error
337
+ });
338
+ this.onEnd?.();
339
+ }
340
+ }
341
+
342
+ class OTelTracerImpl {
343
+ name;
344
+ version;
345
+ storage;
346
+ currentContext;
347
+ activeSpans = new Map;
348
+ onSpanEndCallback;
349
+ provider;
350
+ constructor(name, version, storage, provider) {
351
+ this.name = name;
352
+ this.version = version;
353
+ this.storage = storage;
354
+ this.provider = provider;
355
+ }
356
+ setOnSpanEndCallback(callback) {
357
+ this.onSpanEndCallback = callback;
358
+ }
359
+ getActiveSpanCount() {
360
+ return this.activeSpans.size;
361
+ }
362
+ startSpan(name, options) {
363
+ const parentFromOptions = options?.parent;
364
+ const hasExplicitParent = options && "parent" in options;
365
+ const globalContext = this.provider.getGlobalContext();
366
+ let effectiveParentContext;
367
+ if (hasExplicitParent) {
368
+ effectiveParentContext = parentFromOptions;
369
+ } else if (this.currentContext) {
370
+ effectiveParentContext = this.currentContext;
371
+ } else if (globalContext) {
372
+ effectiveParentContext = globalContext;
373
+ }
374
+ const traceId = effectiveParentContext?.traceId || this.generateTraceId();
375
+ const spanId = this.generateSpanId();
376
+ let parentSpanId;
377
+ if (hasExplicitParent && parentFromOptions) {
378
+ parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;
379
+ } else if (this.currentContext) {
380
+ parentSpanId = this.currentContext.spanId;
381
+ } else if (globalContext) {
382
+ parentSpanId = globalContext.spanId;
383
+ }
384
+ const spanContext = {
385
+ traceId,
386
+ spanId,
387
+ parentSpanId
388
+ };
389
+ this.currentContext = {
390
+ traceId,
391
+ spanId,
392
+ parentSpanId
393
+ };
394
+ const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));
395
+ if (options?.attributes) {
396
+ for (const [key, value] of Object.entries(options.attributes)) {
397
+ span.setAttribute(key, value);
398
+ }
399
+ }
400
+ this.activeSpans.set(spanId, span);
401
+ return span;
402
+ }
403
+ injectToEnv(env) {
404
+ if (this.currentContext) {
405
+ propagation.inject(env, this.currentContext);
406
+ }
407
+ }
408
+ getCurrentContext() {
409
+ return this.currentContext;
410
+ }
411
+ setCurrentContext(context) {
412
+ this.currentContext = context;
413
+ }
414
+ endSpan(span) {
415
+ const spanContext = span.spanContext;
416
+ this.activeSpans.delete(spanContext.spanId);
417
+ const currentTraceId = this.currentContext?.traceId;
418
+ if (spanContext.parentSpanId) {
419
+ const parentSpan = this.activeSpans.get(spanContext.parentSpanId);
420
+ if (parentSpan) {
421
+ const parentContext = {
422
+ traceId: spanContext.traceId,
423
+ spanId: parentSpan.spanContext.spanId,
424
+ parentSpanId: parentSpan.spanContext.parentSpanId
425
+ };
426
+ this.currentContext = parentContext;
427
+ return parentContext;
428
+ }
429
+ if (currentTraceId) {
430
+ const parentContext = {
431
+ traceId: currentTraceId,
432
+ spanId: spanContext.parentSpanId,
433
+ parentSpanId: undefined
434
+ };
435
+ this.currentContext = parentContext;
436
+ return parentContext;
437
+ }
438
+ }
439
+ this.currentContext = undefined;
440
+ return;
441
+ }
442
+ generateTraceId() {
443
+ const timestamp = Date.now().toString(16).padStart(12, "0");
444
+ const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")).join("");
445
+ return (timestamp + random).slice(0, 32).padStart(32, "0");
446
+ }
447
+ generateSpanId() {
448
+ return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
449
+ }
450
+ handleSpanEnd(spanId, parentSpanId) {
451
+ this.activeSpans.delete(spanId);
452
+ const currentTraceId = this.currentContext?.traceId;
453
+ if (parentSpanId) {
454
+ const parentSpan = this.activeSpans.get(parentSpanId);
455
+ if (parentSpan) {
456
+ this.currentContext = {
457
+ traceId: parentSpan.spanContext.traceId,
458
+ spanId: parentSpan.spanContext.spanId,
459
+ parentSpanId: parentSpan.spanContext.parentSpanId
460
+ };
461
+ return;
462
+ }
463
+ if (currentTraceId) {
464
+ this.currentContext = {
465
+ traceId: currentTraceId,
466
+ spanId: parentSpanId,
467
+ parentSpanId: undefined
468
+ };
469
+ return;
470
+ }
471
+ }
472
+ this.currentContext = undefined;
473
+ }
474
+ }
475
+
476
+ class OTelTracerProvider {
477
+ tracers = new Map;
478
+ storage;
479
+ initialized = false;
480
+ globalContext;
481
+ constructor(storage, dbPath) {
482
+ this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());
483
+ }
484
+ async initialize() {
485
+ if (this.initialized)
486
+ return;
487
+ await this.storage.initialize();
488
+ this.initialized = true;
489
+ }
490
+ isInitialized() {
491
+ return this.initialized;
492
+ }
493
+ getGlobalContext() {
494
+ return this.globalContext;
495
+ }
496
+ setGlobalContext(context) {
497
+ this.globalContext = context;
498
+ }
499
+ getTracer(name, version) {
500
+ const key = `${name}@${version || "0.0.0"}`;
501
+ let tracer = this.tracers.get(key);
502
+ if (!tracer) {
503
+ tracer = new OTelTracerImpl(name, version, this.storage, this);
504
+ this.tracers.set(key, tracer);
505
+ if (this.initialized) {
506
+ this.restoreFromEnv(tracer);
507
+ }
508
+ }
509
+ return tracer;
510
+ }
511
+ restoreFromEnv(tracer) {
512
+ const extracted = propagation.extract(process.env);
513
+ if (extracted) {
514
+ tracer.setCurrentContext({
515
+ traceId: extracted.traceId,
516
+ spanId: extracted.spanId,
517
+ parentSpanId: undefined
518
+ });
519
+ }
520
+ }
521
+ shutdown() {
522
+ for (const tracer of this.tracers.values()) {}
523
+ this.tracers.clear();
524
+ this.storage.close();
525
+ this.initialized = false;
526
+ this.globalContext = undefined;
527
+ delete process.env["TRACEPARENT"];
528
+ delete process.env["TRACE_ID"];
529
+ delete process.env["LOG_TRACE_REQUEST_ID"];
530
+ }
531
+ getStorage() {
532
+ return this.storage;
533
+ }
534
+ }
535
+ function getTracerProvider() {
536
+ if (!providerInstance) {
537
+ providerInstance = new OTelTracerProvider;
538
+ }
539
+ return providerInstance;
540
+ }
541
+ function resetTracerProvider() {
542
+ if (providerInstance) {
543
+ providerInstance.shutdown();
544
+ providerInstance = null;
545
+ }
546
+ }
547
+ function getDefaultDbPath() {
548
+ const os = __require("os");
549
+ const path = __require("path");
550
+ const home = os.homedir();
551
+ const dataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
552
+ return path.join(dataHome, "roy-agent", "traces.db");
553
+ }
554
+ var providerInstance = null;
555
+ var init_tracer_provider = __esm(() => {
556
+ init_propagation();
557
+ init_types();
558
+ });
559
+
560
+ // packages/core/src/env/log-trace/logger.ts
561
+ import { appendFileSync, existsSync, mkdirSync } from "fs";
562
+ import { join } from "path";
563
+ function simplifyFilePath(fullPath) {
564
+ let path = fullPath.replace(/\\/g, "/");
565
+ const bunfsMatch = path.match(/\/\$bunfs\/root\/(.+)$/);
566
+ if (bunfsMatch) {
567
+ const virtualPath = bunfsMatch[1];
568
+ const packagesMatch = virtualPath.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
569
+ if (packagesMatch) {
570
+ return packagesMatch[1];
571
+ }
572
+ return virtualPath;
573
+ }
574
+ const fileProtocolMatch = path.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);
575
+ if (fileProtocolMatch) {
576
+ const rootPkg = fileProtocolMatch[1].replace(/\+/g, "/");
577
+ const remaining = fileProtocolMatch[2];
578
+ const prefix = rootPkg;
579
+ const suffix = remaining.startsWith("src/") ? remaining : `src/${remaining}`;
580
+ return `${prefix}/${suffix}`;
581
+ }
582
+ const packagesRootMatch = path.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
583
+ if (packagesRootMatch) {
584
+ return packagesRootMatch[1];
585
+ }
586
+ const rootMarkers = ["packages/core/src", "packages/core", "packages"];
587
+ for (const marker of rootMarkers) {
588
+ const idx = path.indexOf(marker);
589
+ if (idx !== -1) {
590
+ return path.substring(idx);
591
+ }
592
+ }
593
+ return path;
594
+ }
595
+ function getDefaultLogDir() {
596
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
597
+ try {
598
+ const xdg = __require("xdg-basedir");
599
+ if (xdg.xdgData) {
600
+ return join(xdg.xdgData, "roy-agent", "logs");
601
+ }
602
+ } catch {}
603
+ return join(home, ".local", "share", "roy-agent", "logs");
604
+ }
605
+ function isQuietMode() {
606
+ return quietMode;
607
+ }
608
+ function setQuietMode(enabled) {
609
+ quietMode = enabled;
610
+ }
611
+ function setConfigComponent(component) {
612
+ configComponentInstance = component;
613
+ }
614
+ function getLogLevel() {
615
+ if (configComponentInstance) {
616
+ const level = configComponentInstance.get("log_trace.logging.level");
617
+ if (level && ["debug", "info", "warn", "error"].includes(level)) {
618
+ return level;
619
+ }
620
+ }
621
+ const envLevel = process.env.LOG_LEVEL;
622
+ if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
623
+ return envLevel;
624
+ }
625
+ return "info";
626
+ }
627
+ function getCategoryLogLevel(category) {
628
+ if (configComponentInstance) {
629
+ const levels = configComponentInstance.get("log_trace.logging.levels");
630
+ if (levels && typeof levels === "object") {
631
+ const categoryLevel = levels[category];
632
+ if (categoryLevel && ["debug", "info", "warn", "error"].includes(categoryLevel)) {
633
+ return categoryLevel;
634
+ }
635
+ }
636
+ const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);
637
+ if (directLevel && ["debug", "info", "warn", "error"].includes(directLevel)) {
638
+ return directLevel;
639
+ }
640
+ }
641
+ const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, "_")}`;
642
+ const envLevel = process.env[envKey];
643
+ if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
644
+ return envLevel;
645
+ }
646
+ return getLogLevel();
647
+ }
648
+ function isAbsolutePath(path) {
649
+ if (path.startsWith("/")) {
650
+ return true;
651
+ }
652
+ if (/^[a-zA-Z]:[/\\]/.test(path)) {
653
+ return true;
654
+ }
655
+ return false;
656
+ }
657
+ function expandHomeDir(path) {
658
+ if (path.startsWith("~")) {
659
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
660
+ return join(home, path.slice(1));
661
+ }
662
+ return path;
663
+ }
664
+ function getLogFile() {
665
+ if (configComponentInstance) {
666
+ const file = configComponentInstance.get("log_trace.logging.file");
667
+ if (file) {
668
+ return file;
669
+ }
670
+ }
671
+ return "app.log";
672
+ }
673
+ function getLogDir() {
674
+ if (configComponentInstance) {
675
+ const dir = configComponentInstance.get("log_trace.logging.dir");
676
+ if (dir) {
677
+ return dir;
678
+ }
679
+ }
680
+ return getDefaultLogDir();
681
+ }
682
+ function getMaxOutput() {
683
+ if (configComponentInstance) {
684
+ const maxOutput = configComponentInstance.get("log-trace.logging.maxOutput");
685
+ if (typeof maxOutput === "number") {
686
+ return maxOutput;
687
+ }
688
+ }
689
+ return;
690
+ }
691
+ function setLogDirOverride(dir) {
692
+ logDirOverride = dir;
693
+ }
694
+ function getLogDirOverride() {
695
+ return logDirOverride;
696
+ }
697
+
698
+ class Logger {
699
+ prefix;
700
+ constructor(prefix) {
701
+ this.prefix = prefix;
702
+ }
703
+ shouldLog(level) {
704
+ const categoryLevel = getCategoryLogLevel(this.prefix);
705
+ return levelPriority[level] >= levelPriority[categoryLevel];
706
+ }
707
+ ensureLogDirectory(dir) {
708
+ if (!existsSync(dir)) {
709
+ try {
710
+ mkdirSync(dir, { recursive: true });
711
+ } catch (err) {
712
+ console.error("[Logger] Failed to create log directory:", dir, err);
713
+ }
714
+ }
715
+ }
716
+ getCallerLocation() {
717
+ const originalLimit = Error.stackTraceLimit;
718
+ Error.stackTraceLimit = 10;
719
+ const err = new Error;
720
+ Error.captureStackTrace(err, this.formatMessage);
721
+ const stack = err.stack?.split(`
722
+ `) || [];
723
+ Error.stackTraceLimit = originalLimit;
724
+ for (let i = 1;i < stack.length; i++) {
725
+ const line = stack[i];
726
+ if (line.includes("at ") && !line.includes("logger.ts") && !line.includes("formatMessage")) {
727
+ const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
728
+ if (match) {
729
+ const filePath = match[1];
730
+ const relativePath = this.getRelativePath(filePath);
731
+ return {
732
+ file: relativePath,
733
+ line: parseInt(match[2], 10)
734
+ };
735
+ }
736
+ }
737
+ }
738
+ return null;
739
+ }
740
+ getRelativePath(fullPath) {
741
+ return simplifyFilePath(fullPath);
742
+ }
743
+ formatMessage(level, message, data) {
744
+ const now = new Date;
745
+ const timestamp = now.toLocaleString("zh-CN", {
746
+ timeZone: "Asia/Shanghai",
747
+ year: "numeric",
748
+ month: "2-digit",
749
+ day: "2-digit",
750
+ hour: "2-digit",
751
+ minute: "2-digit",
752
+ second: "2-digit",
753
+ hour12: false
754
+ }).replace(/\//g, "-") + "." + String(now.getMilliseconds()).padStart(3, "0");
755
+ const prefix = this.prefix ? `[${this.prefix}]` : "";
756
+ let traceIdStr = "";
757
+ try {
758
+ const provider = getTracerProvider();
759
+ const tracer = provider.getTracer("roy-tracer");
760
+ const context = tracer.getCurrentContext();
761
+ if (context?.traceId) {
762
+ traceIdStr = `[traceId=${context.traceId}]`;
763
+ }
764
+ } catch {}
765
+ let locationStr = "";
766
+ if (data && typeof data === "object" && "callerLocation" in data) {
767
+ const logData = data;
768
+ locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : "";
769
+ const { callerLocation: _callerLocation, ...rest } = logData;
770
+ data = Object.keys(rest).length > 0 ? rest : undefined;
771
+ } else {
772
+ const location = this.getCallerLocation();
773
+ if (location) {
774
+ locationStr = ` [${location.file}:${location.line}]`;
775
+ }
776
+ }
777
+ let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;
778
+ if (data !== undefined) {
779
+ if (typeof data === "object") {
780
+ formatted += " " + JSON.stringify(data).replace(/\n/g, "");
781
+ } else {
782
+ formatted += " " + String(data);
783
+ }
784
+ }
785
+ const maxOutput = getMaxOutput();
786
+ if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {
787
+ formatted = formatted.substring(0, maxOutput) + " [TRUNCATED]";
788
+ }
789
+ return formatted;
790
+ }
791
+ writeToFile(message) {
792
+ try {
793
+ const dir = getLogDir();
794
+ const filename = getLogFile();
795
+ const expandedDir = expandHomeDir(dir);
796
+ const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);
797
+ this.ensureLogDirectory(resolvedDir);
798
+ const logFile = join(resolvedDir, filename);
799
+ appendFileSync(logFile, message + `
800
+ `, "utf-8");
801
+ } catch (err) {
802
+ console.error("[Logger] Failed to write to log file:", err);
803
+ }
804
+ }
805
+ log(level, message, data) {
806
+ if (!this.shouldLog(level))
807
+ return;
808
+ const formatted = this.formatMessage(level, message, data);
809
+ this.writeToFile(formatted);
810
+ if (!isQuietMode()) {
811
+ const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.log : console.debug;
812
+ consoleMethod(formatted);
813
+ }
814
+ }
815
+ debug(message, data) {
816
+ this.log("debug", message, data);
817
+ }
818
+ info(message, data) {
819
+ this.log("info", message, data);
820
+ }
821
+ warn(message, data) {
822
+ this.log("warn", message, data);
823
+ }
824
+ error(message, data) {
825
+ this.log("error", message, data);
826
+ }
827
+ }
828
+ function createLogger(prefix) {
829
+ if (!loggerCache.has(prefix)) {
830
+ loggerCache.set(prefix, new Logger(prefix));
831
+ }
832
+ return loggerCache.get(prefix);
833
+ }
834
+ function getLogLevels() {
835
+ return ["debug", "info", "warn", "error"];
836
+ }
837
+ var configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;
838
+ var init_logger = __esm(() => {
839
+ init_tracer_provider();
840
+ levelPriority = {
841
+ debug: 0,
842
+ info: 1,
843
+ warn: 2,
844
+ error: 3
845
+ };
846
+ loggerCache = new Map;
847
+ });
848
+
849
+ // packages/core/src/env/log-trace/decorator.ts
850
+ function Traced(options) {
851
+ return function(target, propertyKey, descriptor) {
852
+ const originalFn = descriptor.value;
853
+ const spanName = options?.name || propertyKey;
854
+ descriptor.value = wrapFunction(originalFn, spanName, {
855
+ recordParams: options?.recordParams ?? true,
856
+ recordResult: options?.recordResult ?? false,
857
+ recordError: options?.recordError ?? true,
858
+ log: options?.log ?? false,
859
+ maxLogSize: options?.maxLogSize,
860
+ paramFilter: options?.paramFilter
861
+ });
862
+ return descriptor;
863
+ };
864
+ }
865
+ function TracedAs(name, options) {
866
+ return Traced({ name, ...options });
867
+ }
868
+ function TracedLightweight(options) {
869
+ return Traced({ recordParams: false, recordResult: false, log: options?.log ?? false, maxLogSize: options?.maxLogSize });
870
+ }
871
+ function wrapFunction(fn, name, options) {
872
+ const shouldLog = options?.log ?? false;
873
+ const getMaxLogSize = () => {
874
+ if (options?.maxLogSize !== undefined) {
875
+ return options.maxLogSize;
876
+ }
877
+ const configMaxOutput = getMaxOutput();
878
+ return configMaxOutput !== undefined ? configMaxOutput : 500;
879
+ };
880
+ const truncate = (obj) => {
881
+ if (obj === undefined)
882
+ return;
883
+ if (obj === null)
884
+ return null;
885
+ const maxLogSize = getMaxLogSize();
886
+ let str;
887
+ try {
888
+ str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
889
+ } catch (e) {
890
+ str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
891
+ }
892
+ if (maxLogSize > 0 && str.length > maxLogSize) {
893
+ return str.slice(0, maxLogSize) + " [TRUNCATED]";
894
+ }
895
+ try {
896
+ return JSON.parse(str);
897
+ } catch {
898
+ return str;
899
+ }
900
+ };
901
+ const truncateString = (obj) => {
902
+ if (obj === undefined)
903
+ return "undefined";
904
+ if (obj === null)
905
+ return "null";
906
+ const maxLogSize = getMaxLogSize();
907
+ let str;
908
+ try {
909
+ str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
910
+ } catch (e) {
911
+ str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
912
+ }
913
+ return maxLogSize > 0 && str.length > maxLogSize ? str.slice(0, maxLogSize) + " [TRUNCATED]" : str;
914
+ };
915
+ const TRACE_LOG_PREFIX = "[TRACE]";
916
+ const getCallerLocation = () => {
917
+ const originalLimit = Error.stackTraceLimit;
918
+ Error.stackTraceLimit = 15;
919
+ const err = new Error;
920
+ Error.captureStackTrace(err, getCallerLocation);
921
+ const stack = err.stack?.split(`
922
+ `) || [];
923
+ Error.stackTraceLimit = originalLimit;
924
+ for (let i = 1;i < stack.length; i++) {
925
+ const line = stack[i];
926
+ if (line.includes("decorator.ts") || line.includes("decorator.js") || line.includes("logFn") || line.includes("getCallerLocation"))
927
+ continue;
928
+ const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
929
+ if (match) {
930
+ const filePath = match[1];
931
+ if (!filePath || filePath === "native")
932
+ continue;
933
+ const relativePath = simplifyFilePath(filePath);
934
+ return `${relativePath}:${match[2]}`;
935
+ }
936
+ }
937
+ return "";
938
+ };
939
+ const logFn = (event, argsOrData, callerLocation) => {
940
+ if (!shouldLog)
941
+ return;
942
+ const logger = createLogger("traced:" + name);
943
+ const tag = event === "enter" ? ">>>" : event === "quit" ? "<<<" : "!!!";
944
+ const prefix = `${TRACE_LOG_PREFIX} ${tag} ${name}`;
945
+ const originalFnLocation = callerLocation || getCallerLocation();
946
+ const logMessage = (msg, data) => {
947
+ if (data !== undefined) {
948
+ logger.info(`${prefix} ${msg}: ${truncateString(data)}`, { callerLocation: originalFnLocation });
949
+ } else {
950
+ logger.info(`${prefix} ${msg}`, { callerLocation: originalFnLocation });
951
+ }
952
+ };
953
+ if (event === "enter") {
954
+ logMessage("enter", argsOrData);
955
+ } else if (event === "quit") {
956
+ logMessage("quit", options?.recordResult ? argsOrData : undefined);
957
+ } else {
958
+ logMessage("error", argsOrData);
959
+ }
960
+ };
961
+ return function(...args) {
962
+ const tracer = getTracerProvider().getTracer("roy-tracer");
963
+ const attributes = {};
964
+ if (options?.recordParams !== false) {
965
+ if (options?.paramFilter) {
966
+ attributes["params"] = truncate(options.paramFilter(args));
967
+ } else {
968
+ attributes["params"] = truncate(args);
969
+ }
970
+ }
971
+ const callerLocation = getCallerLocation();
972
+ logFn("enter", args, callerLocation);
973
+ const span = tracer.startSpan(name, { attributes });
974
+ try {
975
+ const result = fn.call(this, ...args);
976
+ if (result && typeof result === "object" && typeof result.then === "function") {
977
+ return result.then((resolved) => {
978
+ span.setAttribute("result", JSON.stringify(truncate(resolved)));
979
+ span.end(resolved);
980
+ logFn("quit", options?.recordResult ? resolved : undefined, callerLocation);
981
+ return resolved;
982
+ }, (rejected) => {
983
+ span.setAttribute("error", String(rejected));
984
+ span.end(undefined, rejected instanceof Error ? rejected : new Error(String(rejected)));
985
+ logFn("error", rejected.message, callerLocation);
986
+ throw rejected;
987
+ });
988
+ }
989
+ span.setAttribute("result", JSON.stringify(truncate(result)));
990
+ span.end(result);
991
+ logFn("quit", options?.recordResult ? result : undefined, callerLocation);
992
+ return result;
993
+ } catch (error) {
994
+ span.setAttribute("error", String(error));
995
+ span.end(undefined, error instanceof Error ? error : new Error(String(error)));
996
+ logFn("error", error.message, callerLocation);
997
+ throw error;
998
+ }
999
+ };
1000
+ }
1001
+ var init_decorator = __esm(() => {
1002
+ init_tracer_provider();
1003
+ init_logger();
1004
+ });
1005
+
1006
+ // packages/core/src/env/workflow/types/workflow-hil.ts
1007
+ function createNodeInterruptEvent(runId, nodeId, nodeType, query, agentSessionId) {
1008
+ return {
1009
+ type: "node.interrupt",
1010
+ run_id: runId,
1011
+ timestamp: Date.now(),
1012
+ node_id: nodeId,
1013
+ node_type: nodeType,
1014
+ query,
1015
+ ...agentSessionId ? { agent_session_id: agentSessionId } : {}
1016
+ };
1017
+ }
1018
+ function createWorkflowAskUserEvent(runId, sessionId, nodeId, nodeType, query) {
1019
+ return {
1020
+ type: "workflow.ask-user",
1021
+ run_id: runId,
1022
+ timestamp: Date.now(),
1023
+ session_id: sessionId,
1024
+ node_id: nodeId,
1025
+ node_type: nodeType,
1026
+ query
1027
+ };
1028
+ }
1029
+ var AskUserError;
1030
+ var init_workflow_hil = __esm(() => {
1031
+ AskUserError = class AskUserError extends Error {
1032
+ runId;
1033
+ sessionId;
1034
+ nodeId;
1035
+ nodeType;
1036
+ query;
1037
+ agentSessionId;
1038
+ timestamp;
1039
+ type = "ask-user";
1040
+ name = "AskUserError";
1041
+ constructor(runId, sessionId, nodeId, nodeType, query, agentSessionId, timestamp = Date.now()) {
1042
+ super(`[${nodeType}:${nodeId}] Ask user: ${query}`);
1043
+ this.runId = runId;
1044
+ this.sessionId = sessionId;
1045
+ this.nodeId = nodeId;
1046
+ this.nodeType = nodeType;
1047
+ this.query = query;
1048
+ this.agentSessionId = agentSessionId;
1049
+ this.timestamp = timestamp;
1050
+ }
1051
+ toEvent() {
1052
+ return {
1053
+ type: "workflow.ask-user",
1054
+ run_id: this.runId,
1055
+ timestamp: this.timestamp,
1056
+ session_id: this.sessionId,
1057
+ node_id: this.nodeId,
1058
+ node_type: this.nodeType,
1059
+ query: this.query
1060
+ };
1061
+ }
1062
+ };
1063
+ });
1064
+
1065
+ // packages/core/src/env/hook/types.ts
1066
+ function createHook(meta, fn) {
1067
+ return {
1068
+ ...meta,
1069
+ execute: fn
1070
+ };
1071
+ }
1072
+ function createPriorityHook(name, fn, priority) {
1073
+ return createHook({ name, priority }, fn);
1074
+ }
1075
+ // packages/core/src/env/hook/hook-manager.ts
1076
+ class HookManager {
1077
+ _hooks = new Map;
1078
+ componentName;
1079
+ componentVersion;
1080
+ defaultPriority;
1081
+ constructor(options = {}) {
1082
+ this.componentName = options.componentName ?? "unknown";
1083
+ this.componentVersion = options.componentVersion ?? "0.0.0";
1084
+ this.defaultPriority = options.defaultPriority ?? 0;
1085
+ }
1086
+ register(hookPoint, hook) {
1087
+ const hooks = this.getOrCreateHooks(hookPoint);
1088
+ hooks.push(hook);
1089
+ }
1090
+ registerMany(hookPoint, hooks) {
1091
+ const hookList = this.getOrCreateHooks(hookPoint);
1092
+ hookList.push(...hooks);
1093
+ }
1094
+ unregister(hookPoint, name) {
1095
+ const hooks = this._hooks.get(hookPoint);
1096
+ if (!hooks)
1097
+ return false;
1098
+ const index = hooks.findIndex((h) => h.name === name);
1099
+ if (index === -1)
1100
+ return false;
1101
+ hooks.splice(index, 1);
1102
+ return true;
1103
+ }
1104
+ unregisterAll(hookPoint) {
1105
+ this._hooks.delete(hookPoint);
1106
+ }
1107
+ async execute(hookPoint, data, metadata = {}) {
1108
+ const hooks = this._hooks.get(hookPoint);
1109
+ if (!hooks || hooks.length === 0)
1110
+ return;
1111
+ const sortedHooks = this.sortHooks(hooks);
1112
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
1113
+ for (const hook of sortedHooks) {
1114
+ await this.safeExecute(hook, ctx);
1115
+ }
1116
+ }
1117
+ async executeAndCollect(hookPoint, data, metadata = {}) {
1118
+ const hooks = this._hooks.get(hookPoint);
1119
+ if (!hooks || hooks.length === 0)
1120
+ return [];
1121
+ const sortedHooks = this.sortHooks(hooks);
1122
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
1123
+ const results = [];
1124
+ for (const hook of sortedHooks) {
1125
+ const result = await this.safeExecuteAndReturn(hook, ctx);
1126
+ if (result !== undefined) {
1127
+ results.push(result);
1128
+ }
1129
+ }
1130
+ return results;
1131
+ }
1132
+ count(hookPoint) {
1133
+ return this._hooks.get(hookPoint)?.length ?? 0;
1134
+ }
1135
+ clear() {
1136
+ this._hooks.clear();
1137
+ }
1138
+ getHookPoints() {
1139
+ return Array.from(this._hooks.keys());
1140
+ }
1141
+ hasHooks(hookPoint) {
1142
+ return this.count(hookPoint) > 0;
1143
+ }
1144
+ setComponentInfo(name, version) {
1145
+ this.componentName = name;
1146
+ this.componentVersion = version;
1147
+ }
1148
+ get hooks() {
1149
+ return this._hooks;
1150
+ }
1151
+ async executeWithIntervention(hookPoint, data, metadata = {}) {
1152
+ const hooks = this._hooks.get(hookPoint);
1153
+ if (!hooks || hooks.length === 0) {
1154
+ return { stopped: false, results: [] };
1155
+ }
1156
+ const sortedHooks = this.sortHooks(hooks);
1157
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
1158
+ const results = [];
1159
+ let stopped = false;
1160
+ let action;
1161
+ for (const hook of sortedHooks) {
1162
+ if (stopped)
1163
+ break;
1164
+ const result = await this.safeExecuteAndReturn(hook, ctx);
1165
+ results.push(result);
1166
+ if (result && typeof result === "object" && "stopped" in result) {
1167
+ const hookResult = result;
1168
+ if (hookResult.stopped) {
1169
+ stopped = true;
1170
+ action = hookResult.action;
1171
+ }
1172
+ }
1173
+ }
1174
+ return { stopped, action, results };
1175
+ }
1176
+ getOrCreateHooks(hookPoint) {
1177
+ let hooks = this._hooks.get(hookPoint);
1178
+ if (!hooks) {
1179
+ hooks = [];
1180
+ this._hooks.set(hookPoint, hooks);
1181
+ }
1182
+ return hooks;
1183
+ }
1184
+ sortHooks(hooks) {
1185
+ return [...hooks].sort((a, b) => {
1186
+ const priorityA = a.priority ?? this.defaultPriority;
1187
+ const priorityB = b.priority ?? this.defaultPriority;
1188
+ return priorityA - priorityB;
1189
+ });
1190
+ }
1191
+ createContext(hookPoint, data, metadata, phase) {
1192
+ return {
1193
+ component: {
1194
+ name: this.componentName,
1195
+ version: this.componentVersion
1196
+ },
1197
+ data,
1198
+ metadata,
1199
+ phase,
1200
+ hookPoint
1201
+ };
1202
+ }
1203
+ async safeExecute(hook, ctx) {
1204
+ try {
1205
+ await hook.execute(ctx);
1206
+ } catch (error) {
1207
+ console.error(`Hook "${hook.name}" failed:`, error);
1208
+ }
1209
+ }
1210
+ async safeExecuteAndReturn(hook, ctx) {
1211
+ try {
1212
+ return await hook.execute(ctx);
1213
+ } catch (error) {
1214
+ console.error(`Hook "${hook.name}" failed:`, error);
1215
+ return;
1216
+ }
1217
+ }
1218
+ }
1219
+ // packages/core/src/env/hook/global-hook-manager.ts
1220
+ var globalHookManager = new HookManager;
1221
+ var AgentHookPoints = {
1222
+ BEFORE_START: "agent:before.start",
1223
+ BEFORE_LLM: "agent:before.llm",
1224
+ AFTER_LLM: "agent:after.llm",
1225
+ BEFORE_TOOL: "agent:before.tool",
1226
+ AFTER_TOOL: "agent:after.tool",
1227
+ ON_ITERATION: "agent:on.iteration",
1228
+ ON_THRESHOLD: "agent:on.threshold",
1229
+ AFTER_COMPLETE: "agent:after.complete",
1230
+ ON_ERROR: "agent:on.error"
1231
+ };
1232
+ var LLMHookPoints = {
1233
+ BEFORE_INVOKE: "llm:before.invoke",
1234
+ AFTER_INVOKE: "llm:after.invoke",
1235
+ ON_STREAM: "llm:on.stream"
1236
+ };
1237
+ var ToolHookPoints = {
1238
+ BEFORE_EXECUTE: "tool:before.execute",
1239
+ AFTER_EXECUTE: "tool:after.execute",
1240
+ BEFORE_REGISTER: "tool:before.register",
1241
+ AFTER_REGISTER: "tool:after.register",
1242
+ ON_ERROR: "tool:on.error"
1243
+ };
1244
+ var hookPointAliases = {
1245
+ "before.tool": "tool:before.execute",
1246
+ "after.tool": "tool:after.execute",
1247
+ "llm.before-invoke": "llm:before.invoke",
1248
+ "llm.after-invoke": "llm:after.invoke",
1249
+ "llm.stream": "llm:on.stream"
1250
+ };
1251
+ function setupAliasHooks() {
1252
+ const originalRegister = globalHookManager.register.bind(globalHookManager);
1253
+ globalHookManager.register = function(hookPoint, hook) {
1254
+ originalRegister(hookPoint, hook);
1255
+ const alias = hookPointAliases[hookPoint];
1256
+ if (alias) {
1257
+ originalRegister(alias, hook);
1258
+ }
1259
+ };
1260
+ }
1261
+ setupAliasHooks();
1262
+ async function executeAgentHook(hookPoint, data, metadata = {}) {
1263
+ await globalHookManager.execute(hookPoint, data, metadata);
1264
+ }
1265
+ async function executeAgentHookWithIntervention(hookPoint, data, metadata = {}) {
1266
+ return globalHookManager.executeWithIntervention(hookPoint, data, metadata);
1267
+ }
1268
+ async function executeLLMHook(hookPoint, data, metadata = {}) {
1269
+ await globalHookManager.execute(hookPoint, data, metadata);
1270
+ }
1271
+ async function executeToolHook(hookPoint, data, metadata = {}) {
1272
+ await globalHookManager.execute(hookPoint, data, metadata);
1273
+ }
1274
+ // packages/core/src/env/component.ts
1275
+ class BaseComponent {
1276
+ _status = "created";
1277
+ _enabled = true;
1278
+ env;
1279
+ hookManager;
1280
+ constructor() {
1281
+ this.hookManager = new HookManager;
1282
+ }
1283
+ getStatus() {
1284
+ return this._status;
1285
+ }
1286
+ getConfig() {
1287
+ return {
1288
+ name: this.name,
1289
+ version: this.version,
1290
+ enabled: this._enabled,
1291
+ env: this.env
1292
+ };
1293
+ }
1294
+ isEnvInitialized() {
1295
+ return this._status !== "created";
1296
+ }
1297
+ setStatus(status) {
1298
+ this._status = status;
1299
+ }
1300
+ getEnv() {
1301
+ return this.env;
1302
+ }
1303
+ async init(config) {
1304
+ if (config?.env) {
1305
+ this.env = config.env;
1306
+ }
1307
+ this.setStatus("initializing");
1308
+ try {
1309
+ if (config?.name)
1310
+ Object.defineProperty(this, "name", { value: config.name, writable: false });
1311
+ if (config?.version)
1312
+ Object.defineProperty(this, "version", { value: config.version, writable: false });
1313
+ } catch {}
1314
+ if (config?.enabled !== undefined)
1315
+ this._enabled = config.enabled;
1316
+ this.hookManager.setComponentInfo(this.name, this.version);
1317
+ await this.onInit();
1318
+ this.setStatus("running");
1319
+ }
1320
+ async start() {
1321
+ if (this._started)
1322
+ return;
1323
+ this._started = true;
1324
+ await this.onStart();
1325
+ this.setStatus("running");
1326
+ }
1327
+ async stop() {
1328
+ this.setStatus("stopping");
1329
+ this.hookManager.clear();
1330
+ await this.onStop();
1331
+ this.setStatus("stopped");
1332
+ }
1333
+ async onInit() {}
1334
+ async onStart() {}
1335
+ async onStop() {}
1336
+ registerHook(hookPoint, hook) {
1337
+ this.hookManager.register(hookPoint, hook);
1338
+ }
1339
+ addHook(hookPoint, name, fn, priority) {
1340
+ this.hookManager.register(hookPoint, createHook({ name, priority }, fn));
1341
+ }
1342
+ removeHook(hookPoint, name) {
1343
+ return this.hookManager.unregister(hookPoint, name);
1344
+ }
1345
+ async executeHooks(hookPoint, data, metadata) {
1346
+ await this.hookManager.execute(hookPoint, data, metadata);
1347
+ }
1348
+ getConfigComponent() {
1349
+ return this.env?.getComponent("config");
1350
+ }
1351
+ getRuntimeConfig(key, defaultValue) {
1352
+ const configComponent = this.getConfigComponent();
1353
+ if (configComponent) {
1354
+ const value = configComponent.get(key);
1355
+ if (value !== undefined) {
1356
+ return value;
1357
+ }
1358
+ }
1359
+ return defaultValue;
1360
+ }
1361
+ }
1362
+
1363
+ // packages/core/src/env/agent/agent-component.ts
1364
+ init_logger();
1365
+ import { z } from "zod";
1366
+
1367
+ // packages/core/src/config/env-key.ts
1368
+ function toEnvKey(key, prefix) {
1369
+ let keyNormalized = key.replace(/[.-]/g, "_");
1370
+ keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/_+/g, "_").toUpperCase();
1371
+ if (prefix) {
1372
+ const separator = prefix.endsWith("_") ? "" : "_";
1373
+ return `${prefix}${separator}${keyNormalized}`;
1374
+ }
1375
+ return keyNormalized;
1376
+ }
1377
+ function fromEnvKey(envKey, prefix) {
1378
+ if (!prefix) {
1379
+ return envKey;
1380
+ }
1381
+ if (envKey.startsWith(prefix)) {
1382
+ const afterPrefix = envKey.slice(prefix.length);
1383
+ if (afterPrefix.startsWith("_")) {
1384
+ return afterPrefix.slice(1);
1385
+ }
1386
+ return afterPrefix;
1387
+ }
1388
+ return envKey;
1389
+ }
1390
+ function envKeyToConfigKey(envKey, prefix, componentName) {
1391
+ const prefixUpper = prefix.toUpperCase();
1392
+ if (!envKey.startsWith(prefixUpper)) {
1393
+ return;
1394
+ }
1395
+ const componentUpperNormalized = componentName.replace(/-/g, "_").toUpperCase();
1396
+ let keyPart = envKey.slice(prefixUpper.length);
1397
+ if (keyPart.startsWith("_")) {
1398
+ keyPart = keyPart.slice(1);
1399
+ }
1400
+ if (!keyPart) {
1401
+ return;
1402
+ }
1403
+ const firstUnderscore = keyPart.indexOf("_");
1404
+ let restPart;
1405
+ if (firstUnderscore === -1) {
1406
+ restPart = keyPart;
1407
+ } else {
1408
+ const firstPart = keyPart.slice(0, firstUnderscore);
1409
+ const remaining = keyPart.slice(firstUnderscore + 1);
1410
+ if (firstPart === componentUpperNormalized) {
1411
+ restPart = remaining;
1412
+ } else {
1413
+ restPart = keyPart;
1414
+ }
1415
+ }
1416
+ if (!restPart) {
1417
+ return;
1418
+ }
1419
+ const restPartConverted = restPart.replace(/_/g, ".");
1420
+ return `${componentName}.${restPartConverted.toLowerCase()}`;
1421
+ }
1422
+
1423
+ // packages/core/src/env/agent/agent-config-registration.ts
1424
+ var AGENT_DEFAULTS = {
1425
+ "agent.defaultAgent.maxIterations": 200,
1426
+ "agent.defaultAgent.temperature": 0,
1427
+ "agent.defaultAgent.timeout": 300000,
1428
+ "agent.defaultAgent.streaming": false,
1429
+ "agent.defaultAgent.filterHistory": false
1430
+ };
1431
+ var AGENT_CONFIG_REGISTRATION = {
1432
+ name: "agent",
1433
+ sources: [
1434
+ { type: "env", envPrefix: "AGENT", priority: 20, watch: false }
1435
+ ],
1436
+ keys: [
1437
+ { key: "agent.defaultAgent.model", sources: ["env", "file"] },
1438
+ { key: "agent.defaultAgent.maxIterations", sources: ["env", "file"] },
1439
+ { key: "agent.defaultAgent.temperature", sources: ["env", "file"] },
1440
+ { key: "agent.defaultAgent.timeout", sources: ["env", "file"] },
1441
+ { key: "agent.defaultAgent.systemPrompt", sources: ["env", "file"] },
1442
+ { key: "agent.defaultAgent.streaming", sources: ["env", "file"] },
1443
+ { key: "agent.defaultAgent.tools", sources: ["env", "file"] },
1444
+ { key: "agent.defaultAgent.maxErrorRetries", sources: ["env", "file"] },
1445
+ { key: "agent.defaultAgent.filterHistory", sources: ["env", "file"] }
1446
+ ]
1447
+ };
1448
+
1449
+ // packages/core/src/env/agent/agent-component.ts
1450
+ init_decorator();
1451
+
1452
+ // packages/core/src/env/session/session-message-converter.ts
1453
+ init_decorator();
1454
+ import { randomUUID } from "crypto";
1455
+ var DEFAULT_REASONING_BUDGET_TOKENS = 1e4;
1456
+
1457
+ class SessionMessageConverter {
1458
+ toModelMessage(msg) {
1459
+ if (msg.role === "assistant") {
1460
+ const content = [];
1461
+ for (const part of msg.parts || []) {
1462
+ if (part.type === "text") {
1463
+ const textPart = part;
1464
+ content.push({
1465
+ type: "text",
1466
+ text: textPart.content,
1467
+ ...textPart.synthetic !== undefined && { synthetic: textPart.synthetic }
1468
+ });
1469
+ } else if (part.type === "reasoning") {
1470
+ const reasoningPart = part;
1471
+ content.push({
1472
+ type: "reasoning",
1473
+ text: reasoningPart.content,
1474
+ reasoningType: reasoningPart.reasoningType
1475
+ });
1476
+ } else if (part.type === "tool-call") {
1477
+ const toolPart = part;
1478
+ let parsedArgs = {};
1479
+ if (typeof toolPart.arguments === "string") {
1480
+ try {
1481
+ parsedArgs = JSON.parse(toolPart.arguments);
1482
+ } catch {
1483
+ parsedArgs = { _raw: toolPart.arguments };
1484
+ }
1485
+ } else {
1486
+ parsedArgs = toolPart.arguments;
1487
+ }
1488
+ content.push({
1489
+ type: "tool-call",
1490
+ toolCallId: toolPart.toolCallId,
1491
+ toolName: toolPart.toolName,
1492
+ input: parsedArgs
1493
+ });
1494
+ } else if (part.type === "file") {
1495
+ const filePart = part;
1496
+ content.push({
1497
+ type: "file",
1498
+ url: filePart.url,
1499
+ mimeType: filePart.mime,
1500
+ filename: filePart.filename
1501
+ });
1502
+ } else if (part.type === "tool-result" || part.type === "checkpoint") {} else {
1503
+ console.debug(`[session-message-converter] Skipping unsupported part type in assistant: ${part.type}`);
1504
+ }
1505
+ }
1506
+ if (content.length === 0 && msg.content) {
1507
+ return { role: "assistant", content: msg.content };
1508
+ }
1509
+ return { role: "assistant", content };
1510
+ }
1511
+ if (msg.role === "tool") {
1512
+ const toolPart = msg.parts?.find((p) => p.type === "tool-result");
1513
+ return {
1514
+ role: "tool",
1515
+ content: [{
1516
+ type: "tool-result",
1517
+ toolCallId: toolPart?.toolCallId || "",
1518
+ toolName: toolPart?.toolName || "",
1519
+ output: toolPart?.output || msg.content || ""
1520
+ }]
1521
+ };
1522
+ }
1523
+ return {
1524
+ role: msg.role,
1525
+ content: msg.content || ""
1526
+ };
1527
+ }
1528
+ fromModelMessage(aiMsg, options) {
1529
+ const parts = [];
1530
+ const content = typeof aiMsg.content === "string" || Array.isArray(aiMsg.content) ? aiMsg.content : "";
1531
+ let hasToolCallPart = false;
1532
+ let hasToolResultPart = false;
1533
+ if (typeof content === "string") {
1534
+ parts.push({ type: "text", content });
1535
+ } else if (Array.isArray(content)) {
1536
+ for (const part of content) {
1537
+ const p = part;
1538
+ if (p.type === "text") {
1539
+ parts.push({ type: "text", content: p.text || "" });
1540
+ } else if (p.type === "reasoning") {
1541
+ parts.push({
1542
+ type: "reasoning",
1543
+ content: p.text || "",
1544
+ reasoningType: p.reasoningType,
1545
+ state: "completed"
1546
+ });
1547
+ } else if (p.type === "tool-call") {
1548
+ hasToolCallPart = true;
1549
+ parts.push({
1550
+ type: "tool-call",
1551
+ toolCallId: p.toolCallId,
1552
+ toolName: p.toolName,
1553
+ arguments: p.input,
1554
+ state: "pending"
1555
+ });
1556
+ } else if (p.type === "tool-result") {
1557
+ hasToolResultPart = true;
1558
+ parts.push({
1559
+ type: "tool-result",
1560
+ toolCallId: p.toolCallId,
1561
+ toolName: p.toolName,
1562
+ output: typeof p.output === "string" ? p.output : JSON.stringify(p.output),
1563
+ state: "completed"
1564
+ });
1565
+ } else if (p.type === "file") {
1566
+ parts.push({
1567
+ type: "file",
1568
+ mime: p.mimeType || "application/octet-stream",
1569
+ url: p.url,
1570
+ filename: p.filename
1571
+ });
1572
+ } else {
1573
+ console.debug(`[session-message-converter] Unknown part type: ${p.type}`);
1574
+ }
1575
+ }
1576
+ }
1577
+ let metadataType;
1578
+ if (aiMsg.role === "assistant" && hasToolCallPart) {
1579
+ metadataType = "tool_call";
1580
+ } else if (aiMsg.role === "tool") {
1581
+ metadataType = "tool_result";
1582
+ }
1583
+ const result = {
1584
+ id: options?.messageID || `msg_${randomUUID()}`,
1585
+ sessionID: options?.sessionID || "",
1586
+ role: aiMsg.role,
1587
+ timestamp: Date.now(),
1588
+ parts,
1589
+ content: typeof content === "string" ? content : ""
1590
+ };
1591
+ if (metadataType) {
1592
+ result.metadata = { type: metadataType };
1593
+ }
1594
+ return result;
1595
+ }
1596
+ sessionToHistory(messages) {
1597
+ return messages.filter((msg) => !msg.metadata?.isArchived && !msg.isArchived).map((msg) => this.toModelMessage(msg));
1598
+ }
1599
+ extractProviderOptions(msg) {
1600
+ const options = {};
1601
+ const reasoningParts = msg.parts?.filter((p) => p.type === "reasoning");
1602
+ if (reasoningParts && reasoningParts.length > 0) {
1603
+ const firstReasoning = reasoningParts[0];
1604
+ if (firstReasoning.reasoningType) {
1605
+ options.openai = {
1606
+ thinking: {
1607
+ type: firstReasoning.reasoningType === "effort" ? "extended" : "core"
1608
+ }
1609
+ };
1610
+ if (firstReasoning.reasoningType === "effort") {
1611
+ const budgetTokens = firstReasoning.metadata?.tokenCount || DEFAULT_REASONING_BUDGET_TOKENS;
1612
+ options.anthropic = {
1613
+ thinking: {
1614
+ type: "enabled",
1615
+ budgetTokens
1616
+ }
1617
+ };
1618
+ }
1619
+ }
1620
+ }
1621
+ return options;
1622
+ }
1623
+ migrateMessage(oldMsg) {
1624
+ if (oldMsg.parts && oldMsg.parts.length > 0) {
1625
+ const firstPart = oldMsg.parts[0];
1626
+ if (firstPart && typeof firstPart.type === "string" && firstPart.type.length > 0) {
1627
+ return {
1628
+ ...oldMsg,
1629
+ content: oldMsg.content || ""
1630
+ };
1631
+ }
1632
+ }
1633
+ return {
1634
+ ...oldMsg,
1635
+ content: oldMsg.content || "",
1636
+ parts: oldMsg.content ? [{ type: "text", content: oldMsg.content }] : []
1637
+ };
1638
+ }
1639
+ }
1640
+ __legacyDecorateClassTS([
1641
+ TracedAs("session-message-converter.toModelMessage", { recordParams: true, recordResult: true, log: true })
1642
+ ], SessionMessageConverter.prototype, "toModelMessage", null);
1643
+ __legacyDecorateClassTS([
1644
+ TracedAs("session-message-converter.fromModelMessage", { recordParams: true, recordResult: true, log: true })
1645
+ ], SessionMessageConverter.prototype, "fromModelMessage", null);
1646
+
1647
+ // packages/core/src/env/agent/agent-component.ts
1648
+ init_workflow_hil();
1649
+ var logger = createLogger("agent:component");
1650
+ function toLLMMessage(msg) {
1651
+ let content;
1652
+ let toolCallId;
1653
+ let toolName;
1654
+ let toolCalls;
1655
+ if (typeof msg.content === "string") {
1656
+ content = msg.content;
1657
+ if (msg.role === "tool") {
1658
+ toolCallId = msg.toolCallId;
1659
+ toolName = msg.toolName;
1660
+ }
1661
+ if (msg.role === "assistant" && msg.toolCalls) {
1662
+ toolCalls = msg.toolCalls;
1663
+ }
1664
+ } else if (Array.isArray(msg.content)) {
1665
+ if (msg.role === "tool") {
1666
+ const toolResult = msg.content.find((part) => part.type === "tool-result");
1667
+ const output = toolResult?.output;
1668
+ if (typeof output === "string") {
1669
+ content = output;
1670
+ } else if (output && typeof output === "object" && "value" in output) {
1671
+ content = output.value?.toString() || "";
1672
+ } else {
1673
+ content = JSON.stringify(output) || "";
1674
+ }
1675
+ toolCallId = toolResult?.toolCallId;
1676
+ toolName = toolResult?.toolName;
1677
+ } else {
1678
+ const textParts = msg.content.filter((part) => part.type === "text");
1679
+ const toolCallParts = msg.content.filter((part) => part.type === "tool-call");
1680
+ content = textParts.map((part) => part.text || "").join("");
1681
+ if (msg.role === "assistant" && toolCallParts.length > 0) {
1682
+ toolCalls = toolCallParts.map((part) => {
1683
+ const argsString = typeof part.input === "string" ? part.input : JSON.stringify(part.input || {});
1684
+ const toolName2 = part.toolName || "unknown";
1685
+ return {
1686
+ id: part.toolCallId,
1687
+ name: toolName2,
1688
+ arguments: argsString,
1689
+ function: {
1690
+ name: toolName2,
1691
+ arguments: argsString
1692
+ }
1693
+ };
1694
+ });
1695
+ }
1696
+ }
1697
+ } else {
1698
+ content = "";
1699
+ }
1700
+ return {
1701
+ role: msg.role,
1702
+ content,
1703
+ ...toolCallId ? { toolCallId } : {},
1704
+ ...toolName ? { name: toolName } : {},
1705
+ ...toolCalls && toolCalls.length > 0 ? { toolCalls } : {}
1706
+ };
1707
+ }
1708
+ var DEFAULT_AGENT_CONFIG = {
1709
+ type: "primary",
1710
+ maxIterations: 200,
1711
+ maxErrorRetries: 3,
1712
+ doomLoopThreshold: 5,
1713
+ toolTimeout: 60000,
1714
+ toolRetries: 3,
1715
+ filterHistory: false
1716
+ };
1717
+ var AgentInstanceSchema = z.object({
1718
+ type: z.enum(["primary", "sub"]).default("primary"),
1719
+ systemPrompt: z.string().optional(),
1720
+ behaviorSpecId: z.string().optional(),
1721
+ model: z.string().optional(),
1722
+ maxIterations: z.number().default(200),
1723
+ maxErrorRetries: z.number().default(3),
1724
+ doomLoopThreshold: z.number().default(5),
1725
+ allowedTools: z.array(z.string()).optional(),
1726
+ deniedTools: z.array(z.string()).optional(),
1727
+ toolTimeout: z.number().default(60000),
1728
+ toolRetries: z.number().default(3),
1729
+ filterHistory: z.boolean().default(false)
1730
+ });
1731
+ var AgentComponentConfigSchema = z.object({
1732
+ defaultAgent: AgentInstanceSchema
1733
+ });
1734
+
1735
+ class AgentComponent extends BaseComponent {
1736
+ name = "agent";
1737
+ version = "1.0.0";
1738
+ agents = new Map;
1739
+ config;
1740
+ llmComponent = null;
1741
+ toolComponent = null;
1742
+ aborted = new Map;
1743
+ abortControllers = new Map;
1744
+ defaultTools = [];
1745
+ doomLoopCaches = new Map;
1746
+ configComponent;
1747
+ configWatcher;
1748
+ messageConverter = new SessionMessageConverter;
1749
+ _constructorConfig;
1750
+ runCounter = 0;
1751
+ constructor(options = {}) {
1752
+ super();
1753
+ this._constructorConfig = options.config;
1754
+ this.config = {
1755
+ defaultAgent: {
1756
+ ...DEFAULT_AGENT_CONFIG,
1757
+ ...options.config?.defaultAgent
1758
+ }
1759
+ };
1760
+ }
1761
+ async init(config) {
1762
+ await super.init(config);
1763
+ const options = config.options;
1764
+ if (!options?.configComponent) {
1765
+ throw new Error("ConfigComponent is required for AgentComponent initialization");
1766
+ }
1767
+ this.configComponent = options.configComponent;
1768
+ await this.registerConfig(options);
1769
+ this.setStatus("running");
1770
+ }
1771
+ async registerConfig(options) {
1772
+ const configComponent = options.configComponent;
1773
+ if (!configComponent)
1774
+ return;
1775
+ const { configPath, envPrefix, config } = options;
1776
+ const prefix = envPrefix ?? "AGENT";
1777
+ configComponent.registerComponent(AGENT_CONFIG_REGISTRATION);
1778
+ if (configPath) {
1779
+ configComponent.registerSource({
1780
+ type: "file",
1781
+ relativePath: configPath,
1782
+ optional: true,
1783
+ watch: false
1784
+ });
1785
+ }
1786
+ configComponent.registerSource({
1787
+ type: "env",
1788
+ envPrefix: prefix,
1789
+ priority: 20,
1790
+ watch: false
1791
+ });
1792
+ await configComponent.load("agent");
1793
+ for (const envKey of Object.keys(process.env)) {
1794
+ const configKey = envKeyToConfigKey(envKey, prefix, "agent");
1795
+ if (!configKey)
1796
+ continue;
1797
+ const value = process.env[envKey];
1798
+ if (value !== undefined) {
1799
+ await configComponent.set(configKey, value);
1800
+ }
1801
+ }
1802
+ for (const [key, value] of Object.entries(AGENT_DEFAULTS)) {
1803
+ if (configComponent.get(key) === undefined) {
1804
+ await configComponent.set(key, value);
1805
+ }
1806
+ }
1807
+ if (config) {
1808
+ const flatConfig = this.flattenConfig(config);
1809
+ for (const [key, value] of Object.entries(flatConfig)) {
1810
+ await configComponent.set(key, value);
1811
+ }
1812
+ }
1813
+ const constructorDefaultAgent = this._constructorConfig?.defaultAgent;
1814
+ this.config.defaultAgent = {
1815
+ maxIterations: constructorDefaultAgent?.maxIterations ?? configComponent.get("agent.defaultAgent.maxIterations") ?? 200,
1816
+ maxErrorRetries: constructorDefaultAgent?.maxErrorRetries ?? configComponent.get("agent.defaultAgent.maxErrorRetries") ?? 3,
1817
+ doomLoopThreshold: constructorDefaultAgent?.doomLoopThreshold ?? configComponent.get("agent.defaultAgent.doomLoopThreshold") ?? 5,
1818
+ toolTimeout: constructorDefaultAgent?.toolTimeout ?? configComponent.get("agent.defaultAgent.toolTimeout") ?? 60000,
1819
+ toolRetries: constructorDefaultAgent?.toolRetries ?? configComponent.get("agent.defaultAgent.toolRetries") ?? 3,
1820
+ filterHistory: constructorDefaultAgent?.filterHistory ?? configComponent.get("agent.defaultAgent.filterHistory") ?? false,
1821
+ type: constructorDefaultAgent?.type ?? configComponent.get("agent.defaultAgent.type") ?? "primary",
1822
+ systemPrompt: constructorDefaultAgent?.systemPrompt ?? configComponent.get("agent.defaultAgent.systemPrompt"),
1823
+ model: constructorDefaultAgent?.model ?? configComponent.get("agent.defaultAgent.model"),
1824
+ behaviorSpecId: constructorDefaultAgent?.behaviorSpecId ?? configComponent.get("agent.defaultAgent.behaviorSpecId")
1825
+ };
1826
+ logger.info(`[registerConfig] Synced config from ConfigComponent: maxIterations=${this.config.defaultAgent.maxIterations}`);
1827
+ this.registerConfigWatcher(configComponent);
1828
+ }
1829
+ flattenConfig(obj, prefix = "agent") {
1830
+ const result = {};
1831
+ for (const [key, value] of Object.entries(obj)) {
1832
+ const fullKey = `${prefix}.${key}`;
1833
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1834
+ Object.assign(result, this.flattenConfig(value, fullKey));
1835
+ } else {
1836
+ result[fullKey] = value;
1837
+ }
1838
+ }
1839
+ return result;
1840
+ }
1841
+ registerConfigWatcher(configComponent) {
1842
+ if (typeof configComponent.watch !== "function") {
1843
+ return;
1844
+ }
1845
+ this.configWatcher = configComponent.watch("agent.*", (event) => {
1846
+ this.onConfigChange(event);
1847
+ });
1848
+ }
1849
+ onConfigChange(event) {
1850
+ logger.info(`Agent config changed: ${event.key}`, {
1851
+ oldValue: event.oldValue,
1852
+ newValue: event.newValue
1853
+ });
1854
+ }
1855
+ async onStop() {
1856
+ logger.info("[AgentComponent] Stopping and cleaning up resources...");
1857
+ for (const [name, agent] of this.agents) {
1858
+ if (agent.status === "running" || agent.status === "idle") {
1859
+ this.abort(name);
1860
+ logger.debug(`[AgentComponent] Aborted agent: ${name}`);
1861
+ }
1862
+ }
1863
+ this.abortControllers.clear();
1864
+ this.doomLoopCaches.clear();
1865
+ if (this.configWatcher) {
1866
+ this.configWatcher();
1867
+ this.configWatcher = undefined;
1868
+ }
1869
+ this.agents.clear();
1870
+ this.setStatus("stopped");
1871
+ logger.info("[AgentComponent] Cleanup completed");
1872
+ }
1873
+ refreshDependencies() {
1874
+ if (this.env) {
1875
+ const llm = this.env.getComponent("llm");
1876
+ const tool = this.env.getComponent("tool");
1877
+ this.llmComponent = llm ? llm : null;
1878
+ this.toolComponent = tool ? tool : null;
1879
+ logger.debug("[refreshDependencies] AgentComponent refreshed", {
1880
+ hasLLM: !!this.llmComponent,
1881
+ hasTool: !!this.toolComponent
1882
+ });
1883
+ }
1884
+ }
1885
+ getAgent(agentName) {
1886
+ return this.agents.get(agentName);
1887
+ }
1888
+ listAgents() {
1889
+ return Array.from(this.agents.values());
1890
+ }
1891
+ addRemainingToolResults(ctx, allToolCalls, processedCount, reason) {
1892
+ const remainingToolCalls = allToolCalls.slice(processedCount);
1893
+ for (const tc of remainingToolCalls) {
1894
+ const tcName = tc.function?.name || tc.name || "unknown";
1895
+ this.pushMessage(ctx, {
1896
+ role: "tool",
1897
+ content: [{
1898
+ type: "tool-result",
1899
+ toolCallId: tc.id,
1900
+ toolName: tcName,
1901
+ output: JSON.stringify({ error: reason })
1902
+ }]
1903
+ });
1904
+ }
1905
+ }
1906
+ registerAgent(name, config) {
1907
+ const mergedConfig = {
1908
+ type: config.type ?? this.config.defaultAgent.type,
1909
+ name,
1910
+ maxIterations: config.maxIterations ?? this.config.defaultAgent.maxIterations,
1911
+ maxErrorRetries: config.maxErrorRetries ?? this.config.defaultAgent.maxErrorRetries,
1912
+ doomLoopThreshold: config.doomLoopThreshold ?? this.config.defaultAgent.doomLoopThreshold,
1913
+ toolTimeout: config.toolTimeout ?? this.config.defaultAgent.toolTimeout,
1914
+ toolRetries: config.toolRetries ?? this.config.defaultAgent.toolRetries,
1915
+ systemPrompt: config.systemPrompt ?? this.config.defaultAgent.systemPrompt,
1916
+ model: config.model ?? this.config.defaultAgent.model,
1917
+ behaviorSpecId: config.behaviorSpecId ?? this.config.defaultAgent.behaviorSpecId,
1918
+ allowedTools: config.allowedTools ?? this.config.defaultAgent.allowedTools,
1919
+ deniedTools: config.deniedTools ?? this.config.defaultAgent.deniedTools,
1920
+ filterHistory: config.filterHistory ?? this.config.defaultAgent.filterHistory
1921
+ };
1922
+ const instance = {
1923
+ name,
1924
+ config: mergedConfig,
1925
+ status: "idle",
1926
+ plugins: new Map
1927
+ };
1928
+ this.agents.set(name, instance);
1929
+ logger.info(`Agent registered: ${name}`, { type: instance.config.type });
1930
+ return instance;
1931
+ }
1932
+ unregisterAgent(name) {
1933
+ const deleted = this.agents.delete(name);
1934
+ if (deleted) {
1935
+ logger.info(`Agent unregistered: ${name}`);
1936
+ }
1937
+ return deleted;
1938
+ }
1939
+ registerPlugin(agentName, plugin) {
1940
+ const agent = this.agents.get(agentName);
1941
+ if (!agent) {
1942
+ throw new Error(`Agent not found: ${agentName}`);
1943
+ }
1944
+ agent.plugins.set(plugin.name, plugin);
1945
+ logger.info(`Plugin registered: ${plugin.name} to ${agentName}`, {
1946
+ hooks: plugin.hooks.map((h) => h.point)
1947
+ });
1948
+ }
1949
+ unregisterPlugin(agentName, pluginName) {
1950
+ const agent = this.agents.get(agentName);
1951
+ if (!agent) {
1952
+ return false;
1953
+ }
1954
+ const deleted = agent.plugins.delete(pluginName);
1955
+ if (deleted) {
1956
+ logger.info(`Plugin unregistered: ${pluginName} from ${agentName}`);
1957
+ }
1958
+ return deleted;
1959
+ }
1960
+ setDefaultTools(tools) {
1961
+ this.defaultTools = tools;
1962
+ }
1963
+ getAvailableTools(agent, context) {
1964
+ let tools = [...this.defaultTools];
1965
+ logger.debug(`[getAvailableTools] After defaultTools: ${tools.length} tools`, {
1966
+ toolNames: tools.map((t) => t.name)
1967
+ });
1968
+ if (this.toolComponent?.listTools) {
1969
+ const componentTools = this.toolComponent.listTools();
1970
+ tools = [...tools, ...componentTools];
1971
+ logger.debug(`[getAvailableTools] After adding componentTools: ${tools.length} tools`, {
1972
+ componentToolNames: componentTools.map((t) => t.name)
1973
+ });
1974
+ }
1975
+ const allowedTools = context?.allowedTools ?? agent.config.allowedTools;
1976
+ const deniedTools = context?.deniedTools ?? agent.config.deniedTools;
1977
+ logger.debug(`[getAvailableTools] Filtering: allowed=${allowedTools}, denied=${deniedTools}`);
1978
+ if (allowedTools?.length) {
1979
+ tools = tools.filter((t) => allowedTools.includes(t.name));
1980
+ logger.debug(`[getAvailableTools] After allowedTools filter: ${tools.length} tools`, {
1981
+ toolNames: tools.map((t) => t.name)
1982
+ });
1983
+ }
1984
+ if (deniedTools?.length) {
1985
+ tools = tools.filter((t) => !deniedTools.includes(t.name));
1986
+ logger.debug(`[getAvailableTools] After deniedTools filter: ${tools.length} tools`, {
1987
+ toolNames: tools.map((t) => t.name)
1988
+ });
1989
+ }
1990
+ logger.debug(`[getAvailableTools] Final tools: ${tools.length}`, {
1991
+ toolNames: tools.map((t) => t.name)
1992
+ });
1993
+ return tools;
1994
+ }
1995
+ async run(agentName, query, context) {
1996
+ return this._run(agentName, query, context);
1997
+ }
1998
+ pushMessage(hookCtx, message) {
1999
+ hookCtx.messages.push(message);
2000
+ this.notifyMessageAdded(message);
2001
+ }
2002
+ async _run(agentName, query, context) {
2003
+ this.refreshDependencies();
2004
+ const agent = this.getAgent(agentName);
2005
+ if (!agent) {
2006
+ throw new Error(`Agent not found: ${agentName}`);
2007
+ }
2008
+ const runId = `${agentName}:${++this.runCounter}`;
2009
+ logger.info(`Starting agent run: ${agentName} (runId=${runId})`, { query: query.substring(0, 100) });
2010
+ agent.status = "running";
2011
+ this.aborted.set(runId, false);
2012
+ const abortController = new AbortController;
2013
+ this.abortControllers.set(runId, abortController);
2014
+ if (!this.doomLoopCaches.has(runId)) {
2015
+ this.doomLoopCaches.set(runId, new Map);
2016
+ }
2017
+ const effectiveContext = {
2018
+ ...context,
2019
+ agentType: agent.config.type,
2020
+ model: agent.config.model,
2021
+ abort: abortController.signal
2022
+ };
2023
+ const result = {
2024
+ iterations: 0,
2025
+ toolCalls: []
2026
+ };
2027
+ const hookCtx = {
2028
+ agent,
2029
+ iteration: 0,
2030
+ maxIterations: agent.config.maxIterations,
2031
+ messages: [],
2032
+ tools: this.getAvailableTools(agent, effectiveContext),
2033
+ systemPrompt: agent.config.systemPrompt || "You are a helpful assistant.",
2034
+ context: effectiveContext
2035
+ };
2036
+ let historyMessageCount = 0;
2037
+ if (effectiveContext.sessionId) {
2038
+ try {
2039
+ const sessionComponent = this.env.getComponent("session");
2040
+ if (sessionComponent) {
2041
+ const filterHistory = effectiveContext.filterHistory ?? agent.config.filterHistory ?? false;
2042
+ const messages = await this.getConversationHistory(sessionComponent, effectiveContext.sessionId, { minUserMessages: 100, filterHistory });
2043
+ hookCtx.messages = messages.map((msg) => this.messageConverter.toModelMessage(msg));
2044
+ historyMessageCount = hookCtx.messages.length;
2045
+ }
2046
+ } catch (err) {
2047
+ logger.warn(`Failed to load session history: ${err}`);
2048
+ }
2049
+ }
2050
+ this.pushEnvEvent({
2051
+ type: "agent.start",
2052
+ payload: {
2053
+ sessionId: effectiveContext.sessionId,
2054
+ model: effectiveContext.model
2055
+ }
2056
+ });
2057
+ this.pushMessage(hookCtx, {
2058
+ role: "user",
2059
+ content: query
2060
+ });
2061
+ await this.executePluginHooks(agent, "agent:before.start", hookCtx);
2062
+ if (hookCtx._stopped) {
2063
+ return this.finalizeResult(result, hookCtx);
2064
+ }
2065
+ let iteration = 0;
2066
+ let finalText;
2067
+ while (iteration < agent.config.maxIterations) {
2068
+ if (hookCtx._stopped) {
2069
+ break;
2070
+ }
2071
+ if (this.aborted.get(runId)) {
2072
+ hookCtx._stopped = true;
2073
+ hookCtx._stopReason = "aborted";
2074
+ break;
2075
+ }
2076
+ if (effectiveContext.abort?.aborted) {
2077
+ hookCtx._stopped = true;
2078
+ hookCtx._stopReason = "abort_signal";
2079
+ break;
2080
+ }
2081
+ iteration++;
2082
+ hookCtx.iteration = iteration;
2083
+ result.iterations = iteration;
2084
+ logger.debug(`Iteration ${iteration} started`);
2085
+ this.doomLoopCaches.set(runId, new Map);
2086
+ hookCtx.maxIterations = agent.config.maxIterations;
2087
+ try {
2088
+ logger.debug(`[ReAct] Iteration ${iteration} buildMessages result: ${hookCtx.messages.length} messages`);
2089
+ await this.executePluginHooks(agent, "agent:before.llm", hookCtx);
2090
+ if (hookCtx._stopped)
2091
+ break;
2092
+ const llmOutput = await this.invokeLLM(hookCtx);
2093
+ hookCtx.llmOutput = llmOutput;
2094
+ if (this.aborted.get(runId) || effectiveContext.abort?.aborted) {
2095
+ hookCtx._stopped = true;
2096
+ hookCtx._stopReason = "aborted";
2097
+ break;
2098
+ }
2099
+ await this.executePluginHooks(agent, "agent:after.llm", hookCtx);
2100
+ if (hookCtx._stopped)
2101
+ break;
2102
+ if (llmOutput.content && !llmOutput.toolCalls?.length) {
2103
+ if (this.aborted.get(runId) || effectiveContext.abort?.aborted) {
2104
+ hookCtx._stopped = true;
2105
+ hookCtx._stopReason = "aborted";
2106
+ break;
2107
+ }
2108
+ finalText = llmOutput.content;
2109
+ this.pushMessage(hookCtx, {
2110
+ role: "assistant",
2111
+ content: llmOutput.content
2112
+ });
2113
+ break;
2114
+ }
2115
+ if (llmOutput.toolCalls?.length) {
2116
+ const assistantParts = [];
2117
+ if (llmOutput.content) {
2118
+ assistantParts.push({
2119
+ type: "text",
2120
+ text: llmOutput.content
2121
+ });
2122
+ }
2123
+ if (llmOutput.reasoning) {
2124
+ assistantParts.push({
2125
+ type: "reasoning",
2126
+ text: llmOutput.reasoning,
2127
+ reasoningType: "core"
2128
+ });
2129
+ }
2130
+ for (const tc of llmOutput.toolCalls) {
2131
+ let argsStr = "";
2132
+ let argsObj = {};
2133
+ if (tc.function?.arguments) {
2134
+ if (typeof tc.function.arguments === "string") {
2135
+ argsStr = tc.function.arguments;
2136
+ try {
2137
+ argsObj = JSON.parse(argsStr);
2138
+ } catch {
2139
+ argsObj = { _raw: argsStr };
2140
+ }
2141
+ } else {
2142
+ argsObj = tc.function.arguments;
2143
+ argsStr = JSON.stringify(argsObj);
2144
+ }
2145
+ } else if (tc.arguments) {
2146
+ if (typeof tc.arguments === "string") {
2147
+ argsStr = tc.arguments;
2148
+ try {
2149
+ argsObj = JSON.parse(argsStr);
2150
+ } catch {
2151
+ argsObj = { _raw: argsStr };
2152
+ }
2153
+ } else {
2154
+ argsObj = tc.arguments;
2155
+ argsStr = JSON.stringify(argsObj);
2156
+ }
2157
+ }
2158
+ assistantParts.push({
2159
+ type: "tool-call",
2160
+ toolCallId: tc.id,
2161
+ toolName: tc.function?.name || tc.name || "unknown",
2162
+ input: argsObj,
2163
+ toolCall: {
2164
+ name: tc.function?.name || tc.name || "unknown",
2165
+ arguments: argsStr
2166
+ }
2167
+ });
2168
+ }
2169
+ const assistantContent = llmOutput.content?.substring(0, 80) || "(no text)";
2170
+ const toolCallNames = llmOutput.toolCalls?.map((tc) => tc.function?.name || tc.name).join(", ") || "none";
2171
+ logger.debug(`[ReAct] Iteration ${iteration} Adding assistant message: text="${assistantContent}" toolCalls=[${toolCallNames}]`);
2172
+ this.pushMessage(hookCtx, {
2173
+ role: "assistant",
2174
+ content: assistantParts
2175
+ });
2176
+ const allToolCalls = llmOutput.toolCalls;
2177
+ let processedCount = 0;
2178
+ for (const toolCall of allToolCalls) {
2179
+ if (this.aborted.get(runId) || effectiveContext.abort?.aborted) {
2180
+ hookCtx._stopped = true;
2181
+ hookCtx._stopReason = "aborted";
2182
+ this.addRemainingToolResults(hookCtx, allToolCalls, processedCount, "Execution aborted");
2183
+ break;
2184
+ }
2185
+ const func = toolCall.function;
2186
+ const tcName = func?.name || toolCall.name || "unknown";
2187
+ const tcArgs = func?.arguments ? typeof func.arguments === "string" ? JSON.parse(func.arguments) : func.arguments : toolCall.arguments;
2188
+ hookCtx.currentToolCall = {
2189
+ id: toolCall.id,
2190
+ name: tcName,
2191
+ arguments: tcArgs
2192
+ };
2193
+ const doomKey = `${tcName}:${JSON.stringify(tcArgs)}`;
2194
+ const agentCache = this.doomLoopCaches.get(runId) || new Map;
2195
+ const doomCount = agentCache.get(doomKey) || 0;
2196
+ if (doomCount >= agent.config.doomLoopThreshold) {
2197
+ hookCtx.error = new Error(`Doom loop detected: ${tcName}`);
2198
+ await this.executePluginHooks(agent, "on.error", hookCtx);
2199
+ result.error = hookCtx.error.message;
2200
+ this.addRemainingToolResults(hookCtx, allToolCalls, processedCount, "Execution aborted: Doom loop detected");
2201
+ break;
2202
+ }
2203
+ agentCache.set(doomKey, doomCount + 1);
2204
+ this.doomLoopCaches.set(runId, agentCache);
2205
+ await this.executePluginHooks(agent, "agent:before.tool", hookCtx);
2206
+ if (hookCtx._stopped) {
2207
+ this.addRemainingToolResults(hookCtx, allToolCalls, processedCount, "Execution aborted by plugin hook");
2208
+ break;
2209
+ }
2210
+ const toolResult = await this.executeTool(hookCtx);
2211
+ hookCtx.toolResult = toolResult;
2212
+ await this.executePluginHooks(agent, "agent:after.tool", hookCtx);
2213
+ if (hookCtx._stopped) {
2214
+ this.addRemainingToolResults(hookCtx, allToolCalls, processedCount + 1, "Execution aborted by plugin hook");
2215
+ break;
2216
+ }
2217
+ const toolOutput = toolResult.success ? toolResult.result.output || "" : toolResult.result.error || "Unknown error";
2218
+ const toolOutputPreview = typeof toolOutput === "string" ? toolOutput.substring(0, 50) : JSON.stringify(toolOutput).substring(0, 50);
2219
+ logger.debug(`[ReAct] Iteration ${iteration} Adding tool message: tool=${toolResult.name} output="${toolOutputPreview}..."`);
2220
+ this.pushMessage(hookCtx, {
2221
+ role: "tool",
2222
+ content: [{
2223
+ type: "tool-result",
2224
+ toolCallId: hookCtx.currentToolCall.id,
2225
+ toolName: toolResult.name,
2226
+ output: toolOutput
2227
+ }]
2228
+ });
2229
+ result.toolCalls.push(hookCtx.currentToolCall);
2230
+ processedCount++;
2231
+ }
2232
+ await this.executePluginHooks(agent, "agent:on.iteration", hookCtx);
2233
+ }
2234
+ } catch (error) {
2235
+ logger.error(`Iteration ${iteration} error`, { error });
2236
+ hookCtx.error = error instanceof Error ? error : new Error(String(error));
2237
+ await this.executePluginHooks(agent, "agent:on.error", hookCtx);
2238
+ if (!hookCtx._stopped) {
2239
+ hookCtx._stopped = true;
2240
+ if (error instanceof AskUserError) {
2241
+ hookCtx._stopReason = "ask-user";
2242
+ if (hookCtx.currentToolCall) {
2243
+ this.pushMessage(hookCtx, {
2244
+ role: "tool",
2245
+ content: [{
2246
+ type: "tool-result",
2247
+ toolCallId: hookCtx.currentToolCall.id,
2248
+ toolName: "ask_user",
2249
+ output: JSON.stringify({
2250
+ error: "AskUserError",
2251
+ query: error.query,
2252
+ message: error.message
2253
+ })
2254
+ }]
2255
+ });
2256
+ }
2257
+ const errorInfo = {
2258
+ query: error.query,
2259
+ sessionId: error.sessionId,
2260
+ nodeId: error.nodeId,
2261
+ nodeType: error.nodeType
2262
+ };
2263
+ result.error = `__ASK_USER_ERROR__:${JSON.stringify(errorInfo)}`;
2264
+ } else {
2265
+ result.error = hookCtx.error.message;
2266
+ if (error?.name === "AbortError") {
2267
+ hookCtx._stopReason = hookCtx._stopReason || "aborted";
2268
+ } else {
2269
+ hookCtx._stopReason = "error";
2270
+ }
2271
+ if (hookCtx.currentToolCall) {
2272
+ this.pushMessage(hookCtx, {
2273
+ role: "tool",
2274
+ content: [{
2275
+ type: "tool-result",
2276
+ toolCallId: hookCtx.currentToolCall.id,
2277
+ toolName: hookCtx.currentToolCall.name,
2278
+ output: JSON.stringify({ error: hookCtx.error.message })
2279
+ }]
2280
+ });
2281
+ }
2282
+ }
2283
+ } else {
2284
+ result.error = hookCtx.error.message;
2285
+ if (hookCtx.currentToolCall) {
2286
+ const errorMsg = hookCtx.error?.message || "Execution interrupted";
2287
+ this.pushMessage(hookCtx, {
2288
+ role: "tool",
2289
+ content: [{
2290
+ type: "tool-result",
2291
+ toolCallId: hookCtx.currentToolCall.id,
2292
+ toolName: hookCtx.currentToolCall.name,
2293
+ output: JSON.stringify({ error: errorMsg })
2294
+ }]
2295
+ });
2296
+ }
2297
+ }
2298
+ break;
2299
+ }
2300
+ }
2301
+ result.finalText = finalText;
2302
+ if (iteration >= agent.config.maxIterations && !result.finalText) {
2303
+ result.finalText = "Maximum iterations reached.";
2304
+ }
2305
+ const reactContext = {
2306
+ messages: hookCtx.messages,
2307
+ sessionId: effectiveContext.sessionId,
2308
+ summary: result.finalText
2309
+ };
2310
+ await this.executePluginHooks(agent, "agent:after.react", {
2311
+ ...hookCtx,
2312
+ ...reactContext
2313
+ });
2314
+ await this.executePluginHooks(agent, "agent:after.complete", hookCtx);
2315
+ if (this.aborted.get(runId) === true || hookCtx._stopped) {
2316
+ agent.status = "stopped";
2317
+ } else {
2318
+ agent.status = "idle";
2319
+ }
2320
+ this.aborted.delete(runId);
2321
+ this.abortControllers.delete(runId);
2322
+ if (result.error) {
2323
+ this.pushEnvEvent({
2324
+ type: "agent.error",
2325
+ payload: {
2326
+ error: result.error,
2327
+ iterations: result.iterations,
2328
+ stopReason: result.stopReason
2329
+ }
2330
+ });
2331
+ } else {
2332
+ this.pushEnvEvent({
2333
+ type: "agent.completed",
2334
+ payload: {
2335
+ finalText: result.finalText,
2336
+ iterations: result.iterations,
2337
+ stopReason: result.stopReason
2338
+ }
2339
+ });
2340
+ }
2341
+ let newMessages = hookCtx.messages.slice(historyMessageCount);
2342
+ logger.info(`Agent run completed: ${agentName}`, {
2343
+ iterations: result.iterations,
2344
+ hasError: !!result.error,
2345
+ hookCtxMessages: hookCtx.messages.length,
2346
+ historyMessageCount,
2347
+ sessionId: effectiveContext.sessionId
2348
+ });
2349
+ await this.recordSessionMessages(effectiveContext.sessionId, newMessages);
2350
+ return this.finalizeResult(result, hookCtx);
2351
+ }
2352
+ abort(agentName) {
2353
+ for (const key of this.aborted.keys()) {
2354
+ if (key.startsWith(agentName + ":")) {
2355
+ this.aborted.set(key, true);
2356
+ }
2357
+ }
2358
+ for (const [key, controller] of this.abortControllers) {
2359
+ if (key.startsWith(agentName + ":")) {
2360
+ controller.abort();
2361
+ logger.debug(`[abort] AbortController.abort() called for run: ${key}`);
2362
+ }
2363
+ }
2364
+ logger.info(`Agent aborted: ${agentName}`);
2365
+ }
2366
+ async buildMessages(ctx) {
2367
+ const messages = [];
2368
+ if (ctx.systemPrompt) {
2369
+ messages.push({
2370
+ role: "system",
2371
+ content: ctx.systemPrompt
2372
+ });
2373
+ }
2374
+ if (ctx.additionInfo) {
2375
+ messages.push({
2376
+ role: "user",
2377
+ content: `\u989D\u5916\u4FE1\u606F\uFF1A
2378
+ ${ctx.additionInfo}`
2379
+ });
2380
+ }
2381
+ messages.push(...ctx.messages);
2382
+ return messages;
2383
+ }
2384
+ async invokeLLM(ctx) {
2385
+ logger.debug("[invokeLLM] Starting LLM invocation");
2386
+ if (this.llmComponent?.invoke) {
2387
+ const messages = await this.buildMessages(ctx);
2388
+ const convertedMessages = messages.map(toLLMMessage);
2389
+ logger.debug(`[invokeLLM] Calling LLMComponent.invoke with ${convertedMessages.length} messages`);
2390
+ try {
2391
+ const result = await this.llmComponent.invoke({
2392
+ messages: convertedMessages,
2393
+ tools: ctx.tools.map((t) => ({
2394
+ name: t.name,
2395
+ description: t.description || "",
2396
+ parameters: t.parameters ?? {}
2397
+ })),
2398
+ model: ctx.context.model,
2399
+ context: {
2400
+ sessionId: ctx.context.sessionId,
2401
+ messageId: ctx.context.messageId
2402
+ },
2403
+ abortSignal: ctx.context.abort
2404
+ });
2405
+ logger.debug("[invokeLLM] LLMComponent.invoke returned successfully");
2406
+ return {
2407
+ content: result.output?.content || "",
2408
+ reasoning: result.output?.reasoning,
2409
+ toolCalls: result.output?.toolCalls?.map((tc) => ({
2410
+ id: tc.id,
2411
+ function: tc.function ? {
2412
+ name: tc.function.name,
2413
+ arguments: typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments)
2414
+ } : undefined,
2415
+ name: tc.name,
2416
+ arguments: tc.arguments
2417
+ })),
2418
+ finishReason: result.output?.finishReason
2419
+ };
2420
+ } catch (error) {
2421
+ logger.error("[invokeLLM] LLMComponent.invoke threw an error:", error);
2422
+ throw error;
2423
+ }
2424
+ }
2425
+ logger.warn("[invokeLLM] No LLMComponent available, using mock");
2426
+ return {
2427
+ content: "Mock response: Hello!",
2428
+ finishReason: "stop"
2429
+ };
2430
+ }
2431
+ async executeTool(ctx) {
2432
+ const toolCall = ctx.currentToolCall;
2433
+ const toolName = toolCall.function?.name || toolCall.name || "unknown";
2434
+ logger.debug(`[executeTool] Looking for tool: "${toolName}"`);
2435
+ logger.debug(`[executeTool] Available tools: [${ctx.tools.map((t) => t.name).join(", ")}]`);
2436
+ const tool = ctx.tools.find((t) => t.name === toolName);
2437
+ if (!tool) {
2438
+ this.pushEnvEvent({
2439
+ type: "tool.error",
2440
+ payload: {
2441
+ error: `Tool not found: ${toolName}`,
2442
+ toolName
2443
+ }
2444
+ });
2445
+ return {
2446
+ id: toolCall.id,
2447
+ name: toolName,
2448
+ success: false,
2449
+ result: {
2450
+ success: false,
2451
+ output: "",
2452
+ error: `Tool not found: ${toolName}`
2453
+ }
2454
+ };
2455
+ }
2456
+ try {
2457
+ const toolContext = {
2458
+ session_id: ctx.context.sessionId,
2459
+ message_id: ctx.context.messageId,
2460
+ abort: ctx.context.abort,
2461
+ workdir: ctx.context.metadata?.workdir,
2462
+ metadata: ctx.context.metadata
2463
+ };
2464
+ const request = {
2465
+ name: toolName,
2466
+ args: toolCall.arguments,
2467
+ context: toolContext
2468
+ };
2469
+ let result;
2470
+ if (this.toolComponent?.execute) {
2471
+ result = await this.toolComponent.execute(request);
2472
+ } else {
2473
+ logger.debug(`[executeTool] No ToolComponent available, executing tool directly`);
2474
+ result = await tool.execute(toolCall.arguments, toolContext);
2475
+ }
2476
+ this.pushEnvEvent({
2477
+ type: "tool.result",
2478
+ payload: {
2479
+ id: toolCall.id,
2480
+ name: toolName,
2481
+ result,
2482
+ success: result.success
2483
+ }
2484
+ });
2485
+ return {
2486
+ id: toolCall.id,
2487
+ name: toolName,
2488
+ success: result.success,
2489
+ result
2490
+ };
2491
+ } catch (error) {
2492
+ if (error instanceof AskUserError) {
2493
+ throw error;
2494
+ }
2495
+ this.pushEnvEvent({
2496
+ type: "tool.error",
2497
+ payload: {
2498
+ error: error instanceof Error ? error.message : String(error),
2499
+ toolName
2500
+ }
2501
+ });
2502
+ return {
2503
+ id: toolCall.id,
2504
+ name: toolName,
2505
+ success: false,
2506
+ result: {
2507
+ success: false,
2508
+ output: "",
2509
+ error: error instanceof Error ? error.message : String(error)
2510
+ }
2511
+ };
2512
+ }
2513
+ }
2514
+ async executePluginHooks(agent, point, ctx) {
2515
+ const hooks = [];
2516
+ for (const [name, plugin] of agent.plugins) {
2517
+ for (const hook of plugin.hooks) {
2518
+ if (hook.point === point) {
2519
+ hooks.push({
2520
+ plugin,
2521
+ priority: hook.priority ?? 0,
2522
+ execute: plugin.execute
2523
+ });
2524
+ }
2525
+ }
2526
+ }
2527
+ hooks.sort((a, b) => b.priority - a.priority);
2528
+ for (const { plugin, execute } of hooks) {
2529
+ try {
2530
+ const result = await execute(ctx);
2531
+ if (!result.continue) {
2532
+ ctx._stopped = true;
2533
+ ctx._stopReason = `Plugin ${plugin.name} stopped execution`;
2534
+ logger.info(`Hook ${point} stopped by plugin ${plugin.name}`);
2535
+ break;
2536
+ }
2537
+ if (result.action) {
2538
+ await this.handleHookAction(result.action, ctx);
2539
+ }
2540
+ } catch (error) {
2541
+ logger.error(`Hook ${point} error in plugin ${plugin.name}`, { error });
2542
+ ctx._errors = ctx._errors || [];
2543
+ ctx._errors.push({
2544
+ plugin: plugin.name,
2545
+ error: error instanceof Error ? error.message : String(error)
2546
+ });
2547
+ }
2548
+ }
2549
+ }
2550
+ async handleHookAction(action, ctx) {
2551
+ switch (action.type) {
2552
+ case "stop":
2553
+ ctx._stopped = true;
2554
+ ctx._stopReason = "stopped_by_hook";
2555
+ break;
2556
+ case "inject_message":
2557
+ if (action.payload && typeof action.payload === "object") {
2558
+ const msg = action.payload;
2559
+ ctx.messages.push(msg);
2560
+ }
2561
+ break;
2562
+ case "skip_tool":
2563
+ ctx._pendingAction = action;
2564
+ break;
2565
+ }
2566
+ }
2567
+ notifyMessageAdded(message) {
2568
+ logger.debug(`Message added: ${message.role}`);
2569
+ }
2570
+ finalizeResult(result, ctx) {
2571
+ return {
2572
+ ...result,
2573
+ stopped: ctx._stopped,
2574
+ stopReason: ctx._stopReason
2575
+ };
2576
+ }
2577
+ async recordSessionMessages(sessionId, allMessages = []) {
2578
+ if (!sessionId) {
2579
+ return;
2580
+ }
2581
+ try {
2582
+ const sessionComponent = this.env.getComponent("session");
2583
+ if (!sessionComponent) {
2584
+ logger.warn("SessionComponent not found, skipping session recording");
2585
+ return;
2586
+ }
2587
+ for (const msg of allMessages) {
2588
+ if (msg.role === "system") {
2589
+ continue;
2590
+ }
2591
+ if (msg.role === "assistant" || msg.role === "tool") {
2592
+ if (this.isEmptyMessage(msg.content)) {
2593
+ continue;
2594
+ }
2595
+ }
2596
+ await sessionComponent.addMessage(sessionId, this.messageConverter.fromModelMessage(msg, { sessionID: sessionId }));
2597
+ }
2598
+ } catch (err) {
2599
+ logger.warn(`Failed to record session messages: ${err}`);
2600
+ }
2601
+ }
2602
+ isEmptyMessage(content) {
2603
+ if (content === null || content === undefined) {
2604
+ return true;
2605
+ }
2606
+ if (typeof content === "string" && content.trim() === "") {
2607
+ return true;
2608
+ }
2609
+ if (Array.isArray(content) && content.length === 0) {
2610
+ return true;
2611
+ }
2612
+ return false;
2613
+ }
2614
+ pushEnvEvent(event) {
2615
+ if (this.env && "pushEnvEvent" in this.env) {
2616
+ try {
2617
+ const fullEvent = {
2618
+ id: `evt_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
2619
+ type: event.type,
2620
+ timestamp: Date.now(),
2621
+ metadata: {
2622
+ source: "agent",
2623
+ agent_name: this.name
2624
+ },
2625
+ payload: event.payload
2626
+ };
2627
+ this.env?.pushEnvEvent(fullEvent);
2628
+ } catch (err) {
2629
+ logger.warn(`[pushEnvEvent] Failed to push event: ${err}`);
2630
+ }
2631
+ }
2632
+ }
2633
+ async getConversationHistory(sessionComponent, sessionId, options = {}) {
2634
+ const minUserMessages = options.minUserMessages ?? 100;
2635
+ const filterHistory = options.filterHistory ?? false;
2636
+ const ctx = await sessionComponent.getContext(sessionId, {
2637
+ fullHistory: false,
2638
+ minUserMessages
2639
+ });
2640
+ let messages = ctx.messages;
2641
+ if (filterHistory) {
2642
+ messages = messages.filter((msg) => {
2643
+ if (msg.metadata?.type === "tool_call" || msg.metadata?.type === "tool_result") {
2644
+ return false;
2645
+ }
2646
+ return msg.role === "user" || msg.role === "assistant";
2647
+ });
2648
+ }
2649
+ return messages;
2650
+ }
2651
+ }
2652
+ __legacyDecorateClassTS([
2653
+ TracedAs("agent.component.run", { recordParams: true, recordResult: true, log: true })
2654
+ ], AgentComponent.prototype, "_run", null);
2655
+ __legacyDecorateClassTS([
2656
+ TracedAs("agent.component.invokeLLM", { recordParams: true, recordResult: true, log: true })
2657
+ ], AgentComponent.prototype, "invokeLLM", null);
2658
+ __legacyDecorateClassTS([
2659
+ TracedAs("agent.component.executeTool", { recordParams: true, recordResult: true, log: true })
2660
+ ], AgentComponent.prototype, "executeTool", null);
2661
+ __legacyDecorateClassTS([
2662
+ TracedAs("agent.component.recordSessionMessages", { recordParams: true, recordResult: true, log: true })
2663
+ ], AgentComponent.prototype, "recordSessionMessages", null);
2664
+ __legacyDecorateClassTS([
2665
+ TracedAs("agent.component.getConversationHistory", { recordParams: true, recordResult: true, log: true })
2666
+ ], AgentComponent.prototype, "getConversationHistory", null);
2667
+ // packages/core/src/env/agent/summary-agent.ts
2668
+ init_logger();
2669
+ init_decorator();
2670
+ var logger2 = createLogger("agent:summary");
2671
+
2672
+ class SummaryAgent {
2673
+ promptComponent;
2674
+ llmComponent;
2675
+ config;
2676
+ constructor(promptComponent, llmComponent, config) {
2677
+ this.promptComponent = promptComponent;
2678
+ this.llmComponent = llmComponent;
2679
+ this.config = {
2680
+ type: "summary",
2681
+ promptName: "session/compact",
2682
+ maxIterations: 1,
2683
+ model: undefined,
2684
+ ...config
2685
+ };
2686
+ }
2687
+ async generateCompactHint(options) {
2688
+ const { messages, sessionContext } = options;
2689
+ logger2.info("[SummaryAgent] Generating compact hint for session");
2690
+ const formattedMessages = this.formatMessages(messages);
2691
+ const systemPrompt = this.getHintGenerationSystemPrompt();
2692
+ const userPrompt = this.buildHintGenerationUserPrompt(formattedMessages, sessionContext);
2693
+ let response;
2694
+ try {
2695
+ response = await this.llmComponent.invoke({
2696
+ messages: [
2697
+ { role: "system", content: systemPrompt },
2698
+ { role: "user", content: userPrompt }
2699
+ ],
2700
+ skipThresholdCheck: true
2701
+ });
2702
+ } catch (error) {
2703
+ logger2.error(`[SummaryAgent] Hint generation LLM invoke failed: ${error}`);
2704
+ throw new Error(`LLM invoke failed: ${error}`);
2705
+ }
2706
+ const responseContent = response.output?.content || response.content || "";
2707
+ const hint = this.parseHintResponse(responseContent);
2708
+ logger2.info("[SummaryAgent] Compact hint generated", { hint: hint.substring(0, 100) });
2709
+ return {
2710
+ hint,
2711
+ rawResponse: responseContent
2712
+ };
2713
+ }
2714
+ async run(options) {
2715
+ const { messages, userContext, outputFormat, scenarioHint } = options;
2716
+ logger2.info("[SummaryAgent] Starting checkpoint generation", {
2717
+ hasScenarioHint: !!scenarioHint
2718
+ });
2719
+ const formattedMessages = this.formatMessages(messages);
2720
+ const systemPrompt = this.getSystemPrompt(scenarioHint);
2721
+ const userPrompt = this.buildUserPrompt(formattedMessages, userContext);
2722
+ let response;
2723
+ try {
2724
+ response = await this.llmComponent.invoke({
2725
+ messages: [
2726
+ { role: "system", content: systemPrompt },
2727
+ { role: "user", content: userPrompt }
2728
+ ],
2729
+ model: this.config.model,
2730
+ skipThresholdCheck: true
2731
+ });
2732
+ } catch (error) {
2733
+ logger2.error(`[SummaryAgent] LLM invoke failed: ${error}`);
2734
+ throw new Error(`LLM invoke failed: ${error}`);
2735
+ }
2736
+ const responseContent = response.output?.content || response.content || "";
2737
+ if (outputFormat === "json") {
2738
+ const result = this.parseJsonResponse(responseContent);
2739
+ logger2.info(`[SummaryAgent] Checkpoint generated: "${result.title}"`);
2740
+ return {
2741
+ title: result.title || "Untitled Checkpoint",
2742
+ processKeyPoints: result.processKeyPoints || [],
2743
+ currentState: result.currentState || "",
2744
+ nextSteps: result.nextSteps || [],
2745
+ userIntents: result.userIntents || [],
2746
+ rawResponse: responseContent
2747
+ };
2748
+ }
2749
+ throw new Error(`Unsupported output format: ${outputFormat}`);
2750
+ }
2751
+ getSystemPrompt(scenarioHint) {
2752
+ let prompt = `You are a professional session analyst assistant. Your task is to extract key information from a conversation and generate a structured checkpoint.
2753
+
2754
+ A checkpoint captures the progress and state of a session at a point in time. It should contain:
2755
+
2756
+ 1. **Process Key Points**: The key steps, discoveries, or decisions made during this part of the conversation
2757
+ 2. **Current State**: The current progress and status at the end of the conversation
2758
+ 3. **Next Steps**: Follow-up items and what needs to be done next
2759
+ 4. **User Intents**: The underlying goals and intentions of the user (what they want to accomplish)
2760
+
2761
+ Be concise and accurate. Avoid redundancy. Each section should be appropriately sized - not too long.`;
2762
+ if (scenarioHint && scenarioHint.trim()) {
2763
+ prompt += `
2764
+
2765
+ ## Scenario Context
2766
+
2767
+ ${scenarioHint.trim()}`;
2768
+ }
2769
+ return prompt;
2770
+ }
2771
+ getHintGenerationSystemPrompt() {
2772
+ return `You are a compact guidance prompt engineer. Your task is to analyze a conversation and generate a "compact guidance prompt" that will instruct the checkpoint generator on what information to extract and preserve during session compression.
2773
+
2774
+ **Purpose**: The guidance prompt will be used by the checkpoint generator to understand:
2775
+ 1. What work is currently in progress
2776
+ 2. What progress has been made
2777
+ 3. What information MUST be preserved during compression (this is critical for task continuation)
2778
+ 4. What information should be the focus of extraction
2779
+
2780
+ **Key Principle**: The preserved information should enable seamless task continuation. If critical details are lost during compression, the user will have to re-explain context when continuing this work later.
2781
+
2782
+ **Output Format**: A structured guidance prompt (3-4 sentences) covering:
2783
+ 1. Current work type and what the user is trying to accomplish
2784
+ 2. Current progress and key achievements
2785
+ 3. CRITICAL information that MUST be preserved (decisions, findings, remaining issues)
2786
+ 4. What the checkpoint generator should focus on when extracting information
2787
+
2788
+ **Example good outputs**:
2789
+ 1. "Bug investigation: User is debugging LSP diagnostics not updating after file edits. Progress: identified root cause (getDiagnostics needs to read latest file content and trigger didChange notification), implemented fix, CI verified. CRITICAL to preserve: the fix implementation details (file path, code changes), that 2 agent-node-integration tests still fail due to test assertion timing issue (expects 'running' but completes in ~78ms) - this is unrelated to LSP work. Focus extraction on: root cause analysis, fix implementation, known remaining test issues."
2790
+ 2. "Feature development: User is implementing JWT authentication for auth-service. Progress: designed auth flow, implemented token refresh logic, middleware partially done. CRITICAL to preserve: auth flow decisions (token storage, refresh strategy), completed middleware components, modules pending implementation. Focus extraction on: architectural decisions, completed components, pending work."
2791
+ 3. "Refactoring: User is migrating data layer to repository pattern. Progress: migrated UserRepository and OrderRepository, 3 more pending. CRITICAL to preserve: pattern decisions (interface definitions, dependency injection approach), completed repositories, modules pending migration. Focus extraction on: pattern implementation details, completed vs pending modules."`;
2792
+ }
2793
+ buildHintGenerationUserPrompt(messages, sessionContext) {
2794
+ let prompt = `Analyze the following conversation and generate a compact guidance prompt for checkpoint generation.
2795
+
2796
+ ## Your Task
2797
+ Generate a structured guidance prompt (3-4 sentences) that will help the checkpoint generator understand:
2798
+ 1. What work is currently in progress
2799
+ 2. What progress has been made
2800
+ 3. What information MUST be preserved during compression (critical for task continuation)
2801
+ 4. What the checkpoint generator should focus on when extracting information
2802
+
2803
+ `;
2804
+ if (sessionContext) {
2805
+ const ctxLines = ["## Session Context"];
2806
+ if (sessionContext.activeTaskTitle) {
2807
+ ctxLines.push(`- Active Task: ${sessionContext.activeTaskTitle}`);
2808
+ }
2809
+ if (sessionContext.workingDirectory) {
2810
+ ctxLines.push(`- Working Directory: ${sessionContext.workingDirectory}`);
2811
+ }
2812
+ if (sessionContext.recentActions && sessionContext.recentActions.length > 0) {
2813
+ ctxLines.push(`- Recent Actions: ${sessionContext.recentActions.slice(-3).join(" \u2192 ")}`);
2814
+ }
2815
+ if (ctxLines.length > 1) {
2816
+ prompt += ctxLines.join(`
2817
+ `) + `
2818
+
2819
+ `;
2820
+ }
2821
+ }
2822
+ prompt += `## Conversation to Analyze
2823
+
2824
+ ${messages}
2825
+
2826
+ `;
2827
+ prompt += `---
2828
+
2829
+ `;
2830
+ prompt += `## Output Format
2831
+
2832
+ `;
2833
+ prompt += `Generate a structured guidance prompt covering:
2834
+ `;
2835
+ prompt += `1. Current work type and what the user is trying to accomplish
2836
+ `;
2837
+ prompt += `2. Current progress and key achievements
2838
+ `;
2839
+ prompt += `3. CRITICAL information that MUST be preserved (decisions, findings, remaining issues)
2840
+ `;
2841
+ prompt += `4. What to focus on during extraction
2842
+
2843
+ `;
2844
+ prompt += `Wrap the output in a JSON object with a \`guidance_prompt\` key:
2845
+
2846
+ `;
2847
+ prompt += `\`\`\`json
2848
+ `;
2849
+ prompt += `{
2850
+ `;
2851
+ prompt += ` "guidance_prompt": "Work type: ... Progress: ... CRITICAL to preserve: ... Focus extraction on: ..."
2852
+ `;
2853
+ prompt += `}
2854
+ `;
2855
+ prompt += `\`\`\`
2856
+
2857
+ `;
2858
+ prompt += `IMPORTANT: The preserved information should enable seamless task continuation. If critical details are lost, the user will need to re-explain context when continuing this work.`;
2859
+ return prompt;
2860
+ }
2861
+ buildUserPrompt(messages, userContext) {
2862
+ let prompt = `Please analyze the following conversation and generate a checkpoint:
2863
+
2864
+ `;
2865
+ if (userContext && userContext !== "\u65E0\u989D\u5916\u4E0A\u4E0B\u6587") {
2866
+ prompt += `## Context
2867
+ ${userContext}
2868
+
2869
+ `;
2870
+ }
2871
+ prompt += `## Conversation Content
2872
+
2873
+ ${messages}
2874
+
2875
+ `;
2876
+ prompt += `---
2877
+
2878
+ `;
2879
+ prompt += `## Output Format
2880
+
2881
+ Please output in the following JSON format:
2882
+
2883
+ \`\`\`json
2884
+ {
2885
+ "title": "Brief checkpoint title (max 30 characters)",
2886
+ "processKeyPoints": [
2887
+ "Point 1: Description of key discovery or decision",
2888
+ "Point 2: Description of important step or conclusion",
2889
+ "Point 3: ..."
2890
+ ],
2891
+ "currentState": "Current state description explaining progress and status (50-100 characters)",
2892
+ "nextSteps": [
2893
+ "Next follow-up item 1",
2894
+ "Next follow-up item 2"
2895
+ ],
2896
+ "userIntents": [
2897
+ "User intent 1: what the user wants to accomplish",
2898
+ "User intent 2: another goal or request",
2899
+ "User intent 3: ..."
2900
+ ]
2901
+ }
2902
+ \`\`\`
2903
+
2904
+ `;
2905
+ prompt += `## Intent Extraction Guidelines
2906
+
2907
+ `;
2908
+ prompt += `- Extract user intents from the ENTIRE conversation flow (both user and assistant messages)
2909
+ `;
2910
+ prompt += `- Focus on what the user WANTS to accomplish, not just what was discussed
2911
+ `;
2912
+ prompt += `- Include both explicit requests and inferred goals
2913
+ `;
2914
+ prompt += `- Aim for 2-5 intents, prioritize the most important ones
2915
+ `;
2916
+ prompt += `- Be concise and specific in intent descriptions
2917
+ `;
2918
+ prompt += `- Examples: "Fix authentication bug", "Optimize database performance", "Add unit tests for auth module"
2919
+
2920
+ `;
2921
+ prompt += `Make sure the JSON output is valid and can be parsed.`;
2922
+ return prompt;
2923
+ }
2924
+ formatMessages(messages) {
2925
+ return messages.map((m, i) => `[${i}] ${m.role}: ${m.content}`).join(`
2926
+
2927
+ `);
2928
+ }
2929
+ parseJsonResponse(content) {
2930
+ const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) || content.match(/```\s*([\s\S]*?)\s*```/) || [null, content];
2931
+ const jsonStr = jsonMatch[1] || content;
2932
+ try {
2933
+ return JSON.parse(jsonStr.trim());
2934
+ } catch {
2935
+ const fixed = jsonStr.replace(/,\s*}/g, "}").replace(/,\s*]/g, "]").replace(/'/g, '"').trim();
2936
+ try {
2937
+ return JSON.parse(fixed);
2938
+ } catch (e) {
2939
+ logger2.error(`[SummaryAgent] Failed to parse JSON: ${content}`);
2940
+ throw new Error(`Failed to parse checkpoint JSON: ${e}`);
2941
+ }
2942
+ }
2943
+ }
2944
+ parseHintResponse(content) {
2945
+ return parseCompactHintResponse(content);
2946
+ }
2947
+ }
2948
+ __legacyDecorateClassTS([
2949
+ TracedAs("summary-agent.generateCompactHint")
2950
+ ], SummaryAgent.prototype, "generateCompactHint", null);
2951
+ __legacyDecorateClassTS([
2952
+ TracedAs("summary-agent.run", { recordParams: true, recordResult: true })
2953
+ ], SummaryAgent.prototype, "run", null);
2954
+ __legacyDecorateClassTS([
2955
+ TracedAs("summary-agent.getHintGenerationSystemPrompt")
2956
+ ], SummaryAgent.prototype, "getHintGenerationSystemPrompt", null);
2957
+ __legacyDecorateClassTS([
2958
+ TracedAs("summary-agent.buildHintGenerationUserPrompt")
2959
+ ], SummaryAgent.prototype, "buildHintGenerationUserPrompt", null);
2960
+ __legacyDecorateClassTS([
2961
+ TracedAs("summary-agent.parseHintResponse")
2962
+ ], SummaryAgent.prototype, "parseHintResponse", null);
2963
+ function parseCompactHintResponse(content) {
2964
+ const jsonResult = extractGuidanceFromJson(content);
2965
+ if (jsonResult !== null) {
2966
+ const trimmed = jsonResult.trim();
2967
+ if (!trimmed) {
2968
+ return "[Hint extraction failed]";
2969
+ }
2970
+ if (trimmed.length > 500) {
2971
+ return trimmed.substring(0, 500) + "...";
2972
+ }
2973
+ return trimmed;
2974
+ }
2975
+ let text = content.replace(/```json\s*([\s\S]*?)\s*```/g, "$1").replace(/```markdown\s*([\s\S]*?)\s*```/g, "$1").replace(/```\s*([\s\S]*?)\s*```/g, "$1").trim();
2976
+ if (!text) {
2977
+ return "[Hint extraction failed]";
2978
+ }
2979
+ if (text.length > 500) {
2980
+ return text.substring(0, 500) + "...";
2981
+ }
2982
+ return text;
2983
+ }
2984
+ function extractGuidanceFromJson(content) {
2985
+ const jsonBlockMatch = content.match(/```json\s*([\s\S]*?)\s*```/);
2986
+ if (jsonBlockMatch) {
2987
+ const parsed2 = tryParseJson(jsonBlockMatch[1]);
2988
+ const guidancePrompt2 = parsed2?.guidance_prompt;
2989
+ if (typeof guidancePrompt2 === "string") {
2990
+ return guidancePrompt2;
2991
+ }
2992
+ }
2993
+ const plainBlockMatch = content.match(/```\s*([\s\S]*?)\s*```/);
2994
+ if (plainBlockMatch) {
2995
+ const parsed2 = tryParseJson(plainBlockMatch[1]);
2996
+ const guidancePrompt2 = parsed2?.guidance_prompt;
2997
+ if (typeof guidancePrompt2 === "string") {
2998
+ return guidancePrompt2;
2999
+ }
3000
+ }
3001
+ const jsonMatch = content.match(/\{[\s\S]*"guidance_prompt"[\s\S]*\}/);
3002
+ if (jsonMatch) {
3003
+ const parsed2 = tryParseJson(jsonMatch[0]);
3004
+ const guidancePrompt2 = parsed2?.guidance_prompt;
3005
+ if (typeof guidancePrompt2 === "string") {
3006
+ return guidancePrompt2;
3007
+ }
3008
+ }
3009
+ const parsed = tryParseJson(content.trim());
3010
+ const guidancePrompt = parsed?.guidance_prompt;
3011
+ if (typeof guidancePrompt === "string") {
3012
+ return guidancePrompt;
3013
+ }
3014
+ return null;
3015
+ }
3016
+ function tryParseJson(str) {
3017
+ if (!str || !str.trim()) {
3018
+ return null;
3019
+ }
3020
+ try {
3021
+ return JSON.parse(str.trim());
3022
+ } catch {
3023
+ try {
3024
+ const fixed = str.replace(/,\s*}/g, "}").replace(/,\s*]/g, "]").trim();
3025
+ return JSON.parse(fixed);
3026
+ } catch {
3027
+ return null;
3028
+ }
3029
+ }
3030
+ }
3031
+ export {
3032
+ SummaryAgent,
3033
+ AgentComponentConfigSchema,
3034
+ AgentComponent
3035
+ };