@ai-setting/roy-agent-core 1.4.11 → 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,2171 @@
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/hook/types.ts
850
+ function createHook(meta, fn) {
851
+ return {
852
+ ...meta,
853
+ execute: fn
854
+ };
855
+ }
856
+ function createPriorityHook(name, fn, priority) {
857
+ return createHook({ name, priority }, fn);
858
+ }
859
+ // packages/core/src/env/hook/hook-manager.ts
860
+ class HookManager {
861
+ _hooks = new Map;
862
+ componentName;
863
+ componentVersion;
864
+ defaultPriority;
865
+ constructor(options = {}) {
866
+ this.componentName = options.componentName ?? "unknown";
867
+ this.componentVersion = options.componentVersion ?? "0.0.0";
868
+ this.defaultPriority = options.defaultPriority ?? 0;
869
+ }
870
+ register(hookPoint, hook) {
871
+ const hooks = this.getOrCreateHooks(hookPoint);
872
+ hooks.push(hook);
873
+ }
874
+ registerMany(hookPoint, hooks) {
875
+ const hookList = this.getOrCreateHooks(hookPoint);
876
+ hookList.push(...hooks);
877
+ }
878
+ unregister(hookPoint, name) {
879
+ const hooks = this._hooks.get(hookPoint);
880
+ if (!hooks)
881
+ return false;
882
+ const index = hooks.findIndex((h) => h.name === name);
883
+ if (index === -1)
884
+ return false;
885
+ hooks.splice(index, 1);
886
+ return true;
887
+ }
888
+ unregisterAll(hookPoint) {
889
+ this._hooks.delete(hookPoint);
890
+ }
891
+ async execute(hookPoint, data, metadata = {}) {
892
+ const hooks = this._hooks.get(hookPoint);
893
+ if (!hooks || hooks.length === 0)
894
+ return;
895
+ const sortedHooks = this.sortHooks(hooks);
896
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
897
+ for (const hook of sortedHooks) {
898
+ await this.safeExecute(hook, ctx);
899
+ }
900
+ }
901
+ async executeAndCollect(hookPoint, data, metadata = {}) {
902
+ const hooks = this._hooks.get(hookPoint);
903
+ if (!hooks || hooks.length === 0)
904
+ return [];
905
+ const sortedHooks = this.sortHooks(hooks);
906
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
907
+ const results = [];
908
+ for (const hook of sortedHooks) {
909
+ const result = await this.safeExecuteAndReturn(hook, ctx);
910
+ if (result !== undefined) {
911
+ results.push(result);
912
+ }
913
+ }
914
+ return results;
915
+ }
916
+ count(hookPoint) {
917
+ return this._hooks.get(hookPoint)?.length ?? 0;
918
+ }
919
+ clear() {
920
+ this._hooks.clear();
921
+ }
922
+ getHookPoints() {
923
+ return Array.from(this._hooks.keys());
924
+ }
925
+ hasHooks(hookPoint) {
926
+ return this.count(hookPoint) > 0;
927
+ }
928
+ setComponentInfo(name, version) {
929
+ this.componentName = name;
930
+ this.componentVersion = version;
931
+ }
932
+ get hooks() {
933
+ return this._hooks;
934
+ }
935
+ async executeWithIntervention(hookPoint, data, metadata = {}) {
936
+ const hooks = this._hooks.get(hookPoint);
937
+ if (!hooks || hooks.length === 0) {
938
+ return { stopped: false, results: [] };
939
+ }
940
+ const sortedHooks = this.sortHooks(hooks);
941
+ const ctx = this.createContext(hookPoint, data, metadata, "before");
942
+ const results = [];
943
+ let stopped = false;
944
+ let action;
945
+ for (const hook of sortedHooks) {
946
+ if (stopped)
947
+ break;
948
+ const result = await this.safeExecuteAndReturn(hook, ctx);
949
+ results.push(result);
950
+ if (result && typeof result === "object" && "stopped" in result) {
951
+ const hookResult = result;
952
+ if (hookResult.stopped) {
953
+ stopped = true;
954
+ action = hookResult.action;
955
+ }
956
+ }
957
+ }
958
+ return { stopped, action, results };
959
+ }
960
+ getOrCreateHooks(hookPoint) {
961
+ let hooks = this._hooks.get(hookPoint);
962
+ if (!hooks) {
963
+ hooks = [];
964
+ this._hooks.set(hookPoint, hooks);
965
+ }
966
+ return hooks;
967
+ }
968
+ sortHooks(hooks) {
969
+ return [...hooks].sort((a, b) => {
970
+ const priorityA = a.priority ?? this.defaultPriority;
971
+ const priorityB = b.priority ?? this.defaultPriority;
972
+ return priorityA - priorityB;
973
+ });
974
+ }
975
+ createContext(hookPoint, data, metadata, phase) {
976
+ return {
977
+ component: {
978
+ name: this.componentName,
979
+ version: this.componentVersion
980
+ },
981
+ data,
982
+ metadata,
983
+ phase,
984
+ hookPoint
985
+ };
986
+ }
987
+ async safeExecute(hook, ctx) {
988
+ try {
989
+ await hook.execute(ctx);
990
+ } catch (error) {
991
+ console.error(`Hook "${hook.name}" failed:`, error);
992
+ }
993
+ }
994
+ async safeExecuteAndReturn(hook, ctx) {
995
+ try {
996
+ return await hook.execute(ctx);
997
+ } catch (error) {
998
+ console.error(`Hook "${hook.name}" failed:`, error);
999
+ return;
1000
+ }
1001
+ }
1002
+ }
1003
+ // packages/core/src/env/hook/global-hook-manager.ts
1004
+ var globalHookManager = new HookManager;
1005
+ var AgentHookPoints = {
1006
+ BEFORE_START: "agent:before.start",
1007
+ BEFORE_LLM: "agent:before.llm",
1008
+ AFTER_LLM: "agent:after.llm",
1009
+ BEFORE_TOOL: "agent:before.tool",
1010
+ AFTER_TOOL: "agent:after.tool",
1011
+ ON_ITERATION: "agent:on.iteration",
1012
+ ON_THRESHOLD: "agent:on.threshold",
1013
+ AFTER_COMPLETE: "agent:after.complete",
1014
+ ON_ERROR: "agent:on.error"
1015
+ };
1016
+ var LLMHookPoints = {
1017
+ BEFORE_INVOKE: "llm:before.invoke",
1018
+ AFTER_INVOKE: "llm:after.invoke",
1019
+ ON_STREAM: "llm:on.stream"
1020
+ };
1021
+ var ToolHookPoints = {
1022
+ BEFORE_EXECUTE: "tool:before.execute",
1023
+ AFTER_EXECUTE: "tool:after.execute",
1024
+ BEFORE_REGISTER: "tool:before.register",
1025
+ AFTER_REGISTER: "tool:after.register",
1026
+ ON_ERROR: "tool:on.error"
1027
+ };
1028
+ var hookPointAliases = {
1029
+ "before.tool": "tool:before.execute",
1030
+ "after.tool": "tool:after.execute",
1031
+ "llm.before-invoke": "llm:before.invoke",
1032
+ "llm.after-invoke": "llm:after.invoke",
1033
+ "llm.stream": "llm:on.stream"
1034
+ };
1035
+ function setupAliasHooks() {
1036
+ const originalRegister = globalHookManager.register.bind(globalHookManager);
1037
+ globalHookManager.register = function(hookPoint, hook) {
1038
+ originalRegister(hookPoint, hook);
1039
+ const alias = hookPointAliases[hookPoint];
1040
+ if (alias) {
1041
+ originalRegister(alias, hook);
1042
+ }
1043
+ };
1044
+ }
1045
+ setupAliasHooks();
1046
+ async function executeAgentHook(hookPoint, data, metadata = {}) {
1047
+ await globalHookManager.execute(hookPoint, data, metadata);
1048
+ }
1049
+ async function executeAgentHookWithIntervention(hookPoint, data, metadata = {}) {
1050
+ return globalHookManager.executeWithIntervention(hookPoint, data, metadata);
1051
+ }
1052
+ async function executeLLMHook(hookPoint, data, metadata = {}) {
1053
+ await globalHookManager.execute(hookPoint, data, metadata);
1054
+ }
1055
+ async function executeToolHook(hookPoint, data, metadata = {}) {
1056
+ await globalHookManager.execute(hookPoint, data, metadata);
1057
+ }
1058
+ // packages/core/src/env/memory/built-in/record-memory.ts
1059
+ import { z } from "zod";
1060
+ var RecordMemorySchema = z.object({
1061
+ scope: z.enum(["project", "global"]).describe("\u4F5C\u7528\u57DF: project/global"),
1062
+ mode: z.enum(["append", "prepend", "overwrite", "delete"]).describe("\u6A21\u5F0F: append(\u8FFD\u52A0)/prepend(\u63D2\u5165)/overwrite(\u8986\u76D6)/delete(\u5220\u9664)"),
1063
+ content: z.string().optional().describe("\u8BB0\u5FC6\u5185\u5BB9"),
1064
+ title: z.string().optional().describe("\u7AE0\u8282\u6807\u9898")
1065
+ });
1066
+ function createRecordMemoryTool(recordMemory, getMemoryPaths, getMemoryFile) {
1067
+ return {
1068
+ name: "record_memory",
1069
+ description: buildDescription(getMemoryPaths, getMemoryFile),
1070
+ parameters: RecordMemorySchema,
1071
+ execute: async (args, _ctx) => {
1072
+ const params = RecordMemorySchema.parse(args);
1073
+ const startTime = Date.now();
1074
+ try {
1075
+ const result = await recordMemory({
1076
+ scope: params.scope,
1077
+ mode: params.mode,
1078
+ content: params.content,
1079
+ title: params.title
1080
+ });
1081
+ if (!result) {
1082
+ return {
1083
+ success: false,
1084
+ output: "",
1085
+ error: "\u672A\u914D\u7F6E memory \u8DEF\u5F84\uFF0C\u65E0\u6CD5\u8BB0\u5F55\u8BB0\u5FC6",
1086
+ metadata: { execution_time_ms: Date.now() - startTime }
1087
+ };
1088
+ }
1089
+ const actionMessages = {
1090
+ created: "\u5DF2\u521B\u5EFA\u8BB0\u5FC6\u6587\u4EF6",
1091
+ overwrite: "\u5DF2\u8986\u76D6\u8BB0\u5FC6\u6587\u4EF6",
1092
+ append: "\u5DF2\u8FFD\u52A0\u5185\u5BB9\u5230\u8BB0\u5FC6\u6587\u4EF6",
1093
+ prepend: "\u5DF2\u63D2\u5165\u5185\u5BB9\u5230\u8BB0\u5FC6\u6587\u4EF6\u5F00\u5934",
1094
+ delete: "\u5DF2\u5220\u9664\u8BB0\u5FC6\u6587\u4EF6"
1095
+ };
1096
+ return {
1097
+ success: true,
1098
+ output: `${actionMessages[result.action]}: ${result.path}`,
1099
+ metadata: {
1100
+ execution_time_ms: Date.now() - startTime,
1101
+ path: result.path,
1102
+ action: result.action
1103
+ }
1104
+ };
1105
+ } catch (error) {
1106
+ return {
1107
+ success: false,
1108
+ output: "",
1109
+ error: error instanceof Error ? error.message : String(error),
1110
+ metadata: { execution_time_ms: Date.now() - startTime }
1111
+ };
1112
+ }
1113
+ }
1114
+ };
1115
+ }
1116
+ function buildDescription(getMemoryPaths, getMemoryFile) {
1117
+ const paths = getMemoryPaths();
1118
+ const memoryFile = getMemoryFile();
1119
+ const lines = [
1120
+ `# Record Memory Tool`,
1121
+ "",
1122
+ `Record memory to file. Writes to the memory.md file in the specified scope.`,
1123
+ "",
1124
+ `## Modes`,
1125
+ "",
1126
+ "| Mode | Description |",
1127
+ "|------|-------------|",
1128
+ "| **append** | \u8FFD\u52A0\u5185\u5BB9\u5230 ${memoryFile} \u5C3E\u90E8 |",
1129
+ "| **prepend** | \u63D2\u5165\u5185\u5BB9\u5230 ${memoryFile} \u5F00\u5934 |",
1130
+ "| **overwrite** | \u8986\u76D6 ${memoryFile} |",
1131
+ "| **delete** | \u5220\u9664 ${memoryFile} |",
1132
+ "",
1133
+ `## Parameters`,
1134
+ "",
1135
+ "- **scope** (required): \u4F5C\u7528\u57DF - project \u6216 global",
1136
+ "- **mode** (required): \u64CD\u4F5C\u6A21\u5F0F",
1137
+ "- **content** (optional): \u8BB0\u5FC6\u5185\u5BB9",
1138
+ "- **title** (optional): \u7AE0\u8282\u6807\u9898",
1139
+ "",
1140
+ `## Memory Paths`,
1141
+ ""
1142
+ ];
1143
+ if (paths.length === 0) {
1144
+ lines.push("No memory paths configured.");
1145
+ } else {
1146
+ lines.push("Files will be written to:");
1147
+ for (const p of paths) {
1148
+ lines.push(`- **[${p.type}]** ${p.path}/${memoryFile}`);
1149
+ }
1150
+ }
1151
+ return lines.join(`
1152
+ `);
1153
+ }
1154
+
1155
+ // packages/core/src/env/memory/built-in/recall-memory.ts
1156
+ import { z as z2 } from "zod";
1157
+ var RecallMemorySchema = z2.object({
1158
+ scope: z2.enum(["project", "global"]).optional().describe("\u4F5C\u7528\u57DF\uFF08\u53EF\u9009\uFF0C\u4E0D\u4F20\u5219\u8BFB\u53D6\u6240\u6709\uFF09")
1159
+ });
1160
+ function createRecallMemoryTool(recallMemory, getMemoryPaths, getMemoryFile) {
1161
+ return {
1162
+ name: "recall_memory",
1163
+ description: buildDescription2(getMemoryPaths, getMemoryFile),
1164
+ parameters: RecallMemorySchema,
1165
+ execute: async (args, _ctx) => {
1166
+ const params = RecallMemorySchema.parse(args);
1167
+ const startTime = Date.now();
1168
+ try {
1169
+ const content = await recallMemory(params.scope);
1170
+ if (!content) {
1171
+ return {
1172
+ success: true,
1173
+ output: "(No memory files found)",
1174
+ metadata: { execution_time_ms: Date.now() - startTime }
1175
+ };
1176
+ }
1177
+ return {
1178
+ success: true,
1179
+ output: content,
1180
+ metadata: { execution_time_ms: Date.now() - startTime }
1181
+ };
1182
+ } catch (error) {
1183
+ return {
1184
+ success: false,
1185
+ output: "",
1186
+ error: error instanceof Error ? error.message : String(error),
1187
+ metadata: { execution_time_ms: Date.now() - startTime }
1188
+ };
1189
+ }
1190
+ }
1191
+ };
1192
+ }
1193
+ function buildDescription2(getMemoryPaths, getMemoryFile) {
1194
+ const paths = getMemoryPaths();
1195
+ const memoryFile = getMemoryFile();
1196
+ const lines = [
1197
+ `# Recall Memory Tool`,
1198
+ "",
1199
+ `Recall memory from memory files. Reads from the memory.md file in the specified scope.`,
1200
+ "",
1201
+ `## Parameters`,
1202
+ "",
1203
+ "- **scope** (optional): \u4F5C\u7528\u57DF - project \u6216 global\uFF08\u4E0D\u4F20\u5219\u8BFB\u53D6\u6240\u6709\uFF09",
1204
+ "",
1205
+ `## Memory Files`,
1206
+ ""
1207
+ ];
1208
+ if (paths.length === 0) {
1209
+ lines.push("No memory paths configured.");
1210
+ } else {
1211
+ lines.push("Files will be read from:");
1212
+ for (const p of paths) {
1213
+ lines.push(`- **[${p.type}]** ${p.path}/${memoryFile}`);
1214
+ }
1215
+ }
1216
+ return lines.join(`
1217
+ `);
1218
+ }
1219
+
1220
+ // packages/core/src/env/memory/built-in/index.ts
1221
+ function createMemoryTools(recordMemory, recallMemory, config) {
1222
+ return [
1223
+ createRecordMemoryTool(recordMemory, config.getMemoryPaths, config.getMemoryFile),
1224
+ createRecallMemoryTool(recallMemory, config.getMemoryPaths, config.getMemoryFile)
1225
+ ];
1226
+ }
1227
+
1228
+ // packages/core/src/env/memory/plugin/memory-manager.ts
1229
+ init_logger();
1230
+ var logger = createLogger("MemoryManagerV3");
1231
+ function generateTaskId() {
1232
+ return `task_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1233
+ }
1234
+
1235
+ class MemoryManager {
1236
+ static MAX_QUEUE_SIZE = 100;
1237
+ queue = [];
1238
+ processing = false;
1239
+ shuttingDown = false;
1240
+ config;
1241
+ processingPromise = null;
1242
+ resolveProcessing = null;
1243
+ constructor(config = {}) {
1244
+ this.config = config;
1245
+ }
1246
+ updateConfig(config) {
1247
+ this.config = { ...this.config, ...config };
1248
+ }
1249
+ enqueue(task) {
1250
+ if (this.shuttingDown) {
1251
+ logger.debug("MemoryManager is shutting down, ignoring new task");
1252
+ return;
1253
+ }
1254
+ const fullTask = {
1255
+ ...task,
1256
+ id: generateTaskId()
1257
+ };
1258
+ if (this.queue.length >= MemoryManager.MAX_QUEUE_SIZE) {
1259
+ const dropped = this.queue.shift();
1260
+ logger.warn(`Queue full (${MemoryManager.MAX_QUEUE_SIZE}), dropping oldest task: ${dropped?.id}`);
1261
+ }
1262
+ this.queue.push(fullTask);
1263
+ logger.debug(`Task enqueued: ${task.type}, queue size: ${this.queue.length}`);
1264
+ if (!this.processing) {
1265
+ this.startProcessingLoop();
1266
+ }
1267
+ }
1268
+ startProcessingLoop() {
1269
+ const runLoop = async () => {
1270
+ while (this.queue.length > 0 && !this.shuttingDown) {
1271
+ const task = this.queue.shift();
1272
+ try {
1273
+ await this.processTask(task);
1274
+ } catch (error) {
1275
+ logger.error(`Task ${task.id} failed:`, error);
1276
+ }
1277
+ }
1278
+ this.processing = false;
1279
+ if (this.resolveProcessing) {
1280
+ this.resolveProcessing();
1281
+ this.resolveProcessing = null;
1282
+ this.processingPromise = null;
1283
+ }
1284
+ };
1285
+ this.processing = true;
1286
+ this.processingPromise = new Promise((resolve) => {
1287
+ this.resolveProcessing = resolve;
1288
+ });
1289
+ setImmediate(() => {
1290
+ runLoop().catch((error) => {
1291
+ logger.error("Processing loop error:", error);
1292
+ this.processing = false;
1293
+ });
1294
+ });
1295
+ }
1296
+ hasPendingTasks() {
1297
+ return this.queue.length > 0 || this.processing;
1298
+ }
1299
+ async waitForCompletion() {
1300
+ if (this.queue.length === 0 && !this.processing) {
1301
+ return;
1302
+ }
1303
+ if (this.processingPromise) {
1304
+ await this.processingPromise;
1305
+ }
1306
+ }
1307
+ prepareShutdown() {
1308
+ this.shuttingDown = true;
1309
+ logger.info("MemoryManager preparing for shutdown");
1310
+ }
1311
+ async dispose() {
1312
+ await this.waitForCompletion();
1313
+ this.queue = [];
1314
+ logger.info("MemoryManager disposed");
1315
+ }
1316
+ async processTask(task) {
1317
+ logger.debug(`Processing task: ${task.type}`);
1318
+ switch (task.type) {
1319
+ case "extract_memory":
1320
+ await this.handleExtractMemory(task.payload);
1321
+ break;
1322
+ default:
1323
+ logger.warn(`Unknown task type: ${task.type}`);
1324
+ }
1325
+ }
1326
+ async handleExtractMemory(payload) {
1327
+ const messageCount = payload.messages?.length || 0;
1328
+ logger.info(`Extracting memory from ${messageCount} messages`);
1329
+ if (this.config.onExtractMemory) {
1330
+ try {
1331
+ await this.config.onExtractMemory(payload);
1332
+ } catch (error) {
1333
+ logger.error("Memory extraction failed", { error });
1334
+ }
1335
+ }
1336
+ }
1337
+ }
1338
+ // packages/core/src/env/memory/plugin/types.ts
1339
+ var DEFAULT_MEMORY_PLUGIN_CONFIG = {
1340
+ enabled: true
1341
+ };
1342
+
1343
+ // packages/core/src/env/memory/plugin/memory-plugin.ts
1344
+ init_logger();
1345
+ import path from "path";
1346
+ import os from "os";
1347
+ var logger2 = createLogger("MemoryPlugin");
1348
+
1349
+ class MemoryPlugin {
1350
+ config;
1351
+ disposed = false;
1352
+ initialized = false;
1353
+ projectBaseDir = "";
1354
+ globalBaseDir = "";
1355
+ workDir = "";
1356
+ agentComponent = null;
1357
+ constructor(baseDir, config = {}) {
1358
+ this.config = { ...DEFAULT_MEMORY_PLUGIN_CONFIG, ...config };
1359
+ this.workDir = baseDir;
1360
+ this.projectBaseDir = path.join(baseDir, ".roy", "memory");
1361
+ this.globalBaseDir = path.join(os.homedir(), ".config", "roy-agent", "memory");
1362
+ logger2.info("MemoryPlugin (simplified) created", { baseDir, config: this.config });
1363
+ }
1364
+ get name() {
1365
+ return "MemoryPlugin";
1366
+ }
1367
+ get hookPoint() {
1368
+ return "agent:after.react";
1369
+ }
1370
+ get priority() {
1371
+ return 50;
1372
+ }
1373
+ get description() {
1374
+ return "Memory management plugin. Use 'roy memory recall --extract' to extract memories.";
1375
+ }
1376
+ get hooks() {
1377
+ return [
1378
+ {
1379
+ point: this.hookPoint,
1380
+ priority: this.priority
1381
+ }
1382
+ ];
1383
+ }
1384
+ async initialize() {
1385
+ if (this.initialized) {
1386
+ return;
1387
+ }
1388
+ this.initialized = true;
1389
+ logger2.info("MemoryPlugin (simplified) initialized");
1390
+ }
1391
+ async execute(ctx) {
1392
+ if (this.disposed || !this.config.enabled || !this.initialized) {
1393
+ return;
1394
+ }
1395
+ logger2.debug("MemoryPlugin hook executed. Use 'roy memory recall --extract' for memory extraction.");
1396
+ }
1397
+ prepareShutdown() {}
1398
+ hasPendingTasks() {
1399
+ return false;
1400
+ }
1401
+ async waitForCompletion() {}
1402
+ async dispose() {
1403
+ if (this.disposed) {
1404
+ return;
1405
+ }
1406
+ this.disposed = true;
1407
+ logger2.info("MemoryPlugin (simplified) disposed");
1408
+ }
1409
+ getProjectBaseDir() {
1410
+ return this.projectBaseDir;
1411
+ }
1412
+ getGlobalBaseDir() {
1413
+ return this.globalBaseDir;
1414
+ }
1415
+ }
1416
+ function createMemoryPlugin(baseDir, config) {
1417
+ return new MemoryPlugin(baseDir, config);
1418
+ }
1419
+ // packages/core/src/env/memory/plugin/recall-memory.ts
1420
+ import fs from "fs/promises";
1421
+ import path2 from "path";
1422
+ async function recallMemory(memoryPaths) {
1423
+ const results = [];
1424
+ for (const memoryPath of memoryPaths) {
1425
+ const scope = memoryPath.type;
1426
+ const baseDir = memoryPath.path;
1427
+ try {
1428
+ const memoryFile = path2.join(baseDir, "memory.md");
1429
+ try {
1430
+ const content = await fs.readFile(memoryFile, "utf-8");
1431
+ if (content.trim()) {
1432
+ results.push(`## [${scope}] memory.md
1433
+ ${content}`);
1434
+ }
1435
+ } catch {}
1436
+ } catch (error) {
1437
+ console.error(`Error processing memory path ${baseDir}:`, error);
1438
+ }
1439
+ }
1440
+ if (results.length === 0) {
1441
+ return "(No memory files found)";
1442
+ }
1443
+ return results.join(`
1444
+
1445
+ `);
1446
+ }
1447
+ // packages/core/src/env/memory/plugin/memory-agent.ts
1448
+ var PROJECT_MEMORY_AGENT_PROMPT = `\u4F60\u662F\u9879\u76EE\u7EA7 Memory Agent\uFF0C\u8D1F\u8D23\u6574\u7406\u548C\u66F4\u65B0\u5F53\u524D\u9879\u76EE\u7684\u8BB0\u5FC6\u3002
1449
+
1450
+ ## \u4F60\u7684\u804C\u8D23
1451
+
1452
+ 1. **\u4FE1\u606F\u6536\u96C6**\uFF1A\u5728\u63D0\u53D6\u8BB0\u5FC6\u524D\uFF0C\u5148\u6536\u96C6\u9879\u76EE\u4E0A\u4E0B\u6587\u4FE1\u606F
1453
+ 2. **\u4ECE\u5BF9\u8BDD\u4E2D\u63D0\u53D6\u8BB0\u5FC6**\uFF1A\u5206\u6790 messages\uFF0C\u63D0\u53D6\u4E0E\u9879\u76EE\u76F8\u5173\u7684\u77E5\u8BC6\u3001\u51B3\u7B56\u3001\u89E3\u51B3\u65B9\u6848
1454
+ 3. **\u751F\u6210 memory.md**\uFF1A\u66F4\u65B0\u9879\u76EE\u8BB0\u5FC6\u7D22\u5F15
1455
+
1456
+ ## \u4FE1\u606F\u6536\u96C6\u6B65\u9AA4\uFF08\u91CD\u8981\uFF01\uFF09
1457
+
1458
+ \u5728\u63D0\u53D6\u8BB0\u5FC6\u4E4B\u524D\uFF0C\u8BF7\u5148\u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u6536\u96C6\u9879\u76EE\u4E0A\u4E0B\u6587\uFF1A
1459
+
1460
+ 1. **\u9605\u8BFB\u9879\u76EE README**\uFF1A\u4E86\u89E3\u9879\u76EE\u6982\u8FF0\u3001\u529F\u80FD\u3001\u4F7F\u7528\u65B9\u6CD5
1461
+ - \u8DEF\u5F84\u793A\u4F8B\uFF1AREADME.md, README.zh-CN.md, docs/README.md
1462
+
1463
+ 2. **\u68C0\u67E5\u8BBE\u8BA1\u6587\u6863**\uFF1A\u4E86\u89E3\u9879\u76EE\u67B6\u6784\u548C\u8BBE\u8BA1\u51B3\u7B56
1464
+ - \u8DEF\u5F84\u793A\u4F8B\uFF1Adocs/design.md, docs/ARCHITECTURE.md, docs/superpowers/specs/*.md
1465
+
1466
+ 3. **\u67E5\u770B\u4EE3\u7801\u5B9E\u73B0**\uFF1A\u4E86\u89E3\u5173\u952E\u6A21\u5757\u548C\u5B9E\u73B0\u7EC6\u8282
1467
+ - \u8DEF\u5F84\u793A\u4F8B\uFF1Asrc/**/*.ts, packages/*/src/**/*.ts
1468
+
1469
+ 4. **\u56DE\u987E\u73B0\u6709 memory**\uFF1A\u4E86\u89E3\u5DF2\u6709\u7684\u9879\u76EE\u8BB0\u5FC6
1470
+ - \u8DEF\u5F84\uFF1A\u5F53\u524D\u76EE\u5F55\u4E0B\u7684 .roy/memory/memory.md
1471
+
1472
+ ## \u8F93\u5165\u4FE1\u606F
1473
+
1474
+ - \u5F53\u524D\u9879\u76EE\u7684 memory.md \u5185\u5BB9
1475
+ - \u5F53\u524D\u5BF9\u8BDD\u6D88\u606F
1476
+
1477
+ ## \u8F93\u51FA\u8981\u6C42
1478
+
1479
+ \u8BF7\u4EE5 JSON \u683C\u5F0F\u8F93\u51FA\u7ED3\u679C\uFF0C\u5305\u542B\u4EE5\u4E0B\u5B57\u6BB5\uFF1A
1480
+ - memoryMdContent: \u65B0\u7684 memory.md \u5185\u5BB9
1481
+ - projectSummary: \u9879\u76EE\u6458\u8981\uFF08\u5305\u542B summary, shortSummary \u7B49\uFF09
1482
+ - hasUpdates: \u662F\u5426\u6709\u66F4\u65B0
1483
+
1484
+ ## \u8BB0\u5FC6\u7EC4\u7EC7\u539F\u5219
1485
+
1486
+ - \u4F18\u5148\u8BB0\u5F55\u5177\u4F53\u3001\u53EF\u64CD\u4F5C\u7684\u8BB0\u5FC6\uFF08\u4EE3\u7801\u4F4D\u7F6E\u3001\u914D\u7F6E\u9879\u3001\u547D\u4EE4\uFF09
1487
+ - \u907F\u514D\u8FC7\u4E8E\u62BD\u8C61\u6216\u901A\u7528\u7684\u63CF\u8FF0
1488
+ - \u8BB0\u5F55\u8BBE\u8BA1\u51B3\u7B56\u53CA\u5176\u7406\u7531`;
1489
+ var GLOBAL_MEMORY_AGENT_PROMPT = `\u4F60\u662F\u5168\u5C40 Memory Agent\uFF0C\u8D1F\u8D23\u6574\u7406\u8DE8\u9879\u76EE\u7684\u901A\u7528\u8BB0\u5FC6\u3002
1490
+
1491
+ ## \u4F60\u7684\u804C\u8D23
1492
+
1493
+ 1. **\u805A\u5408\u9879\u76EE\u6458\u8981**\uFF1A\u5206\u6790 projectSummaries\uFF0C\u63D0\u53D6\u5171\u6027\u77E5\u8BC6
1494
+ 2. **\u7EF4\u62A4\u5168\u5C40\u8BB0\u5FC6**\uFF1A\u66F4\u65B0\u5168\u5C40 memory.md
1495
+ 3. **\u7EF4\u62A4\u9879\u76EE\u7D22\u5F15**\uFF1A\u5728 memory.md \u4E2D\u7EF4\u62A4\u9879\u76EE\u5217\u8868
1496
+ 4. **\u63D0\u53D6\u5171\u6027\u7ECF\u9A8C**\uFF1A\u5C06\u9879\u76EE\u7ECF\u9A8C\u63D0\u70BC\u4E3A\u901A\u7528\u6700\u4F73\u5B9E\u8DF5
1497
+
1498
+ ## \u8F93\u5165\u4FE1\u606F
1499
+
1500
+ - \u5168\u5C40 memory.md \u5185\u5BB9
1501
+ - \u5F53\u524D\u5BF9\u8BDD\u6D88\u606F
1502
+ - \u9879\u76EE\u6458\u8981\u5217\u8868\uFF08projectSummaries\uFF09
1503
+
1504
+ ## \u8F93\u51FA\u8981\u6C42
1505
+
1506
+ \u8BF7\u4EE5 JSON \u683C\u5F0F\u8F93\u51FA\u7ED3\u679C\uFF0C\u5305\u542B\u4EE5\u4E0B\u5B57\u6BB5\uFF1A
1507
+ - memoryMdContent: \u65B0\u7684 memory.md \u5185\u5BB9
1508
+ - hasUpdates: \u662F\u5426\u6709\u66F4\u65B0
1509
+
1510
+ ## \u8BB0\u5FC6\u7EC4\u7EC7\u539F\u5219
1511
+
1512
+ - \u5173\u6CE8\u8DE8\u9879\u76EE\u5171\u6027\uFF08\u5DE5\u4F5C\u6D41\u3001\u89C4\u8303\u3001\u504F\u597D\uFF09
1513
+ - \u9879\u76EE\u7D22\u5F15\u53EA\u8BB0\u5F55\u6458\u8981\u548C\u8DEF\u5F84\uFF0C\u4E0D\u590D\u5236\u5185\u5BB9
1514
+ - \u7528\u6237\u4E2A\u4EBA\u504F\u597D\uFF08\u996E\u98DF\u3001\u5DE5\u4F5C\u4E60\u60EF\uFF09\u4F18\u5148\u8BB0\u5F55`;
1515
+ function createMemoryAgent(scope) {
1516
+ const name = `memory-agent-${scope}-${Date.now()}`;
1517
+ const systemPrompt = scope === "project" ? PROJECT_MEMORY_AGENT_PROMPT : GLOBAL_MEMORY_AGENT_PROMPT;
1518
+ return {
1519
+ name,
1520
+ systemPrompt,
1521
+ maxIterations: 5
1522
+ };
1523
+ }
1524
+ function formatMemoryInput(input) {
1525
+ const lines = [];
1526
+ lines.push(`# Memory Agent Input (${input.scope} scope)
1527
+ `);
1528
+ lines.push("## Current memory.md");
1529
+ lines.push(input.currentMemoryMd || "_No existing memory_");
1530
+ lines.push("");
1531
+ lines.push("## Recent Messages");
1532
+ if (input.messages.length === 0) {
1533
+ lines.push("_No messages_");
1534
+ } else {
1535
+ for (const msg of input.messages.slice(-10)) {
1536
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1537
+ lines.push(`**${msg.role}**: ${content.substring(0, 500)}`);
1538
+ }
1539
+ }
1540
+ lines.push("");
1541
+ if (input.scope === "global" && input.projectSummaries && input.projectSummaries.length > 0) {
1542
+ lines.push("## Project Summaries");
1543
+ for (const ps of input.projectSummaries) {
1544
+ lines.push(`### ${ps.projectName}`);
1545
+ lines.push(`Path: ${ps.projectPath}`);
1546
+ lines.push(`Last Updated: ${new Date(ps.lastUpdated).toLocaleString()}`);
1547
+ lines.push(`Summary: ${ps.summary}`);
1548
+ lines.push(`Memory: ${ps.memoryMdPath}`);
1549
+ lines.push("---");
1550
+ }
1551
+ lines.push("");
1552
+ }
1553
+ lines.push("## Task");
1554
+ lines.push("\u8BF7\u5206\u6790\u4EE5\u4E0A\u4FE1\u606F\uFF0C\u66F4\u65B0\u8BB0\u5FC6\u5E76\u4EE5 JSON \u683C\u5F0F\u8F93\u51FA\u7ED3\u679C\u3002");
1555
+ return lines.join(`
1556
+ `);
1557
+ }
1558
+ function parseMemoryAgentOutput(output, scope) {
1559
+ let jsonStr = output;
1560
+ const jsonMatch = output.match(/```json\s*([\s\S]*?)\s*```/) || output.match(/```\s*([\s\S]*?)\s*```/) || output.match(/(\{[\s\S]*\})/);
1561
+ if (jsonMatch) {
1562
+ jsonStr = jsonMatch[1] || jsonMatch[0];
1563
+ }
1564
+ try {
1565
+ const parsed = JSON.parse(jsonStr);
1566
+ return {
1567
+ scope,
1568
+ memoryMdContent: parsed.memoryMdContent || "",
1569
+ projectSummary: parsed.projectSummary,
1570
+ hasUpdates: parsed.hasUpdates ?? false
1571
+ };
1572
+ } catch {
1573
+ return {
1574
+ scope,
1575
+ memoryMdContent: output,
1576
+ hasUpdates: false
1577
+ };
1578
+ }
1579
+ }
1580
+ function createEmptyResult(scope) {
1581
+ return {
1582
+ scope,
1583
+ memoryMdContent: "",
1584
+ hasUpdates: false
1585
+ };
1586
+ }
1587
+ async function buildProjectInput(params) {
1588
+ const baseDir = params.projectPath + "/.roy/memory";
1589
+ return {
1590
+ scope: "project",
1591
+ baseDir,
1592
+ currentMemoryMd: params.currentMemoryMd,
1593
+ messages: params.messages
1594
+ };
1595
+ }
1596
+ function buildGlobalInput(params) {
1597
+ return {
1598
+ scope: "global",
1599
+ baseDir: params.baseDir,
1600
+ currentMemoryMd: params.currentMemoryMd,
1601
+ messages: params.messages,
1602
+ projectSummaries: params.projectSummaries
1603
+ };
1604
+ }
1605
+ async function applyMemoryResult(result, baseDir) {
1606
+ const fs2 = await import("fs/promises");
1607
+ const path3 = await import("path");
1608
+ const memoryMdPath = path3.join(baseDir, "memory.md");
1609
+ await fs2.mkdir(path3.dirname(memoryMdPath), { recursive: true });
1610
+ await fs2.writeFile(memoryMdPath, result.memoryMdContent, "utf-8");
1611
+ }
1612
+ function generateProjectSummary(params) {
1613
+ const paragraphs = params.memoryMdContent.split(/\n\n+/);
1614
+ const firstParagraph = paragraphs[0] || "";
1615
+ const summary = firstParagraph.replace(/^#+\s*/g, "").trim() || "No summary available";
1616
+ const firstSentence = summary.split(/[.!?]/)[0] || summary;
1617
+ const shortSummary = firstSentence.substring(0, 50) + (firstSentence.length > 50 ? "..." : "");
1618
+ return {
1619
+ projectPath: params.projectPath,
1620
+ projectName: params.projectName,
1621
+ lastUpdated: Date.now(),
1622
+ summary,
1623
+ shortSummary,
1624
+ memoryMdPath: params.memoryMdPath
1625
+ };
1626
+ }
1627
+ // packages/core/src/env/memory/types.ts
1628
+ import { z as z3 } from "zod";
1629
+ var RecordMemorySchema3 = z3.object({
1630
+ scope: z3.enum(["project", "global"]).describe("\u4F5C\u7528\u57DF: project/global"),
1631
+ mode: z3.enum(["append", "prepend", "overwrite", "delete"]).describe("\u6A21\u5F0F: append(\u8FFD\u52A0)/prepend(\u63D2\u5165)/overwrite(\u8986\u76D6)/delete(\u5220\u9664)"),
1632
+ content: z3.string().optional().describe("\u8BB0\u5FC6\u5185\u5BB9"),
1633
+ title: z3.string().optional().describe("\u7AE0\u8282\u6807\u9898")
1634
+ });
1635
+ var RecallMemorySchema3 = z3.object({
1636
+ scope: z3.enum(["project", "global"]).optional().describe("\u4F5C\u7528\u57DF\uFF08\u53EF\u9009\uFF0C\u4E0D\u4F20\u5219\u8BFB\u53D6\u6240\u6709\uFF09")
1637
+ });
1638
+ // packages/core/src/env/memory/memory-config.ts
1639
+ import path3 from "path";
1640
+ import os2 from "os";
1641
+ var DEFAULT_MEMORY_CONFIG = {
1642
+ memoryPaths: [
1643
+ {
1644
+ type: "global",
1645
+ path: path3.join(os2.homedir(), ".config", "roy-agent", "memory")
1646
+ },
1647
+ {
1648
+ type: "project",
1649
+ path: ".roy/memory"
1650
+ }
1651
+ ],
1652
+ recursive: true,
1653
+ cacheEnabled: true,
1654
+ cacheTTL: 5 * 60 * 1000
1655
+ };
1656
+ var SOURCE_PRIORITY = {
1657
+ global: 0,
1658
+ project: 1
1659
+ };
1660
+ function getSourcePriority(source) {
1661
+ return SOURCE_PRIORITY[source] ?? 0;
1662
+ }
1663
+ // packages/core/src/env/component.ts
1664
+ class BaseComponent {
1665
+ _status = "created";
1666
+ _enabled = true;
1667
+ env;
1668
+ hookManager;
1669
+ constructor() {
1670
+ this.hookManager = new HookManager;
1671
+ }
1672
+ getStatus() {
1673
+ return this._status;
1674
+ }
1675
+ getConfig() {
1676
+ return {
1677
+ name: this.name,
1678
+ version: this.version,
1679
+ enabled: this._enabled,
1680
+ env: this.env
1681
+ };
1682
+ }
1683
+ isEnvInitialized() {
1684
+ return this._status !== "created";
1685
+ }
1686
+ setStatus(status) {
1687
+ this._status = status;
1688
+ }
1689
+ getEnv() {
1690
+ return this.env;
1691
+ }
1692
+ async init(config) {
1693
+ if (config?.env) {
1694
+ this.env = config.env;
1695
+ }
1696
+ this.setStatus("initializing");
1697
+ try {
1698
+ if (config?.name)
1699
+ Object.defineProperty(this, "name", { value: config.name, writable: false });
1700
+ if (config?.version)
1701
+ Object.defineProperty(this, "version", { value: config.version, writable: false });
1702
+ } catch {}
1703
+ if (config?.enabled !== undefined)
1704
+ this._enabled = config.enabled;
1705
+ this.hookManager.setComponentInfo(this.name, this.version);
1706
+ await this.onInit();
1707
+ this.setStatus("running");
1708
+ }
1709
+ async start() {
1710
+ if (this._started)
1711
+ return;
1712
+ this._started = true;
1713
+ await this.onStart();
1714
+ this.setStatus("running");
1715
+ }
1716
+ async stop() {
1717
+ this.setStatus("stopping");
1718
+ this.hookManager.clear();
1719
+ await this.onStop();
1720
+ this.setStatus("stopped");
1721
+ }
1722
+ async onInit() {}
1723
+ async onStart() {}
1724
+ async onStop() {}
1725
+ registerHook(hookPoint, hook) {
1726
+ this.hookManager.register(hookPoint, hook);
1727
+ }
1728
+ addHook(hookPoint, name, fn, priority) {
1729
+ this.hookManager.register(hookPoint, createHook({ name, priority }, fn));
1730
+ }
1731
+ removeHook(hookPoint, name) {
1732
+ return this.hookManager.unregister(hookPoint, name);
1733
+ }
1734
+ async executeHooks(hookPoint, data, metadata) {
1735
+ await this.hookManager.execute(hookPoint, data, metadata);
1736
+ }
1737
+ getConfigComponent() {
1738
+ return this.env?.getComponent("config");
1739
+ }
1740
+ getRuntimeConfig(key, defaultValue) {
1741
+ const configComponent = this.getConfigComponent();
1742
+ if (configComponent) {
1743
+ const value = configComponent.get(key);
1744
+ if (value !== undefined) {
1745
+ return value;
1746
+ }
1747
+ }
1748
+ return defaultValue;
1749
+ }
1750
+ }
1751
+
1752
+ // packages/core/src/env/memory/memory-component.ts
1753
+ init_logger();
1754
+
1755
+ // packages/core/src/env/memory/memory-config-registration.ts
1756
+ import path4 from "path";
1757
+ import os3 from "os";
1758
+ var MEMORY_DEFAULTS = {
1759
+ "memory.recursive": true,
1760
+ "memory.cacheEnabled": true,
1761
+ "memory.cacheTTL": 300000,
1762
+ "memory.memoryFile": "memory.md",
1763
+ "memory.memoryPaths": [
1764
+ { type: "global", path: path4.join(os3.homedir(), ".config", "roy-agent", "memory") },
1765
+ { type: "project", path: ".roy/memory" }
1766
+ ]
1767
+ };
1768
+ var MEMORY_CONFIG_REGISTRATION = {
1769
+ name: "memory",
1770
+ sources: [
1771
+ { type: "env", envPrefix: "MEMORY", priority: 20, watch: false }
1772
+ ],
1773
+ keys: [
1774
+ { key: "memory.recursive", sources: ["env", "file"] },
1775
+ { key: "memory.cacheEnabled", sources: ["env", "file"] },
1776
+ { key: "memory.cacheTTL", sources: ["env", "file"] },
1777
+ { key: "memory.memoryPaths", sources: ["env", "file"] },
1778
+ { key: "memory.memoryFile", sources: ["env", "file"] }
1779
+ ]
1780
+ };
1781
+
1782
+ // packages/core/src/config/env-key.ts
1783
+ function toEnvKey(key, prefix) {
1784
+ let keyNormalized = key.replace(/[.-]/g, "_");
1785
+ keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/_+/g, "_").toUpperCase();
1786
+ if (prefix) {
1787
+ const separator = prefix.endsWith("_") ? "" : "_";
1788
+ return `${prefix}${separator}${keyNormalized}`;
1789
+ }
1790
+ return keyNormalized;
1791
+ }
1792
+ function fromEnvKey(envKey, prefix) {
1793
+ if (!prefix) {
1794
+ return envKey;
1795
+ }
1796
+ if (envKey.startsWith(prefix)) {
1797
+ const afterPrefix = envKey.slice(prefix.length);
1798
+ if (afterPrefix.startsWith("_")) {
1799
+ return afterPrefix.slice(1);
1800
+ }
1801
+ return afterPrefix;
1802
+ }
1803
+ return envKey;
1804
+ }
1805
+ function envKeyToConfigKey(envKey, prefix, componentName) {
1806
+ const prefixUpper = prefix.toUpperCase();
1807
+ if (!envKey.startsWith(prefixUpper)) {
1808
+ return;
1809
+ }
1810
+ const componentUpperNormalized = componentName.replace(/-/g, "_").toUpperCase();
1811
+ let keyPart = envKey.slice(prefixUpper.length);
1812
+ if (keyPart.startsWith("_")) {
1813
+ keyPart = keyPart.slice(1);
1814
+ }
1815
+ if (!keyPart) {
1816
+ return;
1817
+ }
1818
+ const firstUnderscore = keyPart.indexOf("_");
1819
+ let restPart;
1820
+ if (firstUnderscore === -1) {
1821
+ restPart = keyPart;
1822
+ } else {
1823
+ const firstPart = keyPart.slice(0, firstUnderscore);
1824
+ const remaining = keyPart.slice(firstUnderscore + 1);
1825
+ if (firstPart === componentUpperNormalized) {
1826
+ restPart = remaining;
1827
+ } else {
1828
+ restPart = keyPart;
1829
+ }
1830
+ }
1831
+ if (!restPart) {
1832
+ return;
1833
+ }
1834
+ const restPartConverted = restPart.replace(/_/g, ".");
1835
+ return `${componentName}.${restPartConverted.toLowerCase()}`;
1836
+ }
1837
+
1838
+ // packages/core/src/env/memory/memory-component.ts
1839
+ import path5 from "path";
1840
+ import fs2 from "fs/promises";
1841
+ var logger3 = createLogger("memory");
1842
+
1843
+ class MemoryComponent extends BaseComponent {
1844
+ name = "memory";
1845
+ version = "2.0.0";
1846
+ config;
1847
+ toolComponent;
1848
+ configComponent;
1849
+ cache = new Map;
1850
+ configWatcher;
1851
+ async init(config) {
1852
+ await super.init(config);
1853
+ const options = config?.options;
1854
+ if (!options?.configComponent) {
1855
+ throw new Error("ConfigComponent is required for MemoryComponent initialization");
1856
+ }
1857
+ this.configComponent = options.configComponent;
1858
+ await this.registerConfig(options);
1859
+ logger3.info("[MemoryComponent] Initialized (simplified)");
1860
+ }
1861
+ async registerConfig(options) {
1862
+ const configComponent = this.configComponent;
1863
+ if (!configComponent)
1864
+ return;
1865
+ const { configPath, envPrefix, config } = options;
1866
+ const prefix = envPrefix ?? "MEMORY";
1867
+ configComponent.registerComponent(MEMORY_CONFIG_REGISTRATION);
1868
+ if (configPath) {
1869
+ configComponent.registerSource({
1870
+ type: "file",
1871
+ relativePath: configPath,
1872
+ optional: true,
1873
+ watch: false
1874
+ });
1875
+ }
1876
+ configComponent.registerSource({
1877
+ type: "env",
1878
+ envPrefix: prefix,
1879
+ priority: 20,
1880
+ watch: false
1881
+ });
1882
+ await configComponent.load("memory");
1883
+ for (const envKey of Object.keys(process.env)) {
1884
+ const configKey = envKeyToConfigKey(envKey, prefix, "memory");
1885
+ if (!configKey)
1886
+ continue;
1887
+ const value = process.env[envKey];
1888
+ if (value !== undefined) {
1889
+ await configComponent.set(configKey, value);
1890
+ }
1891
+ }
1892
+ for (const [key, value] of Object.entries(MEMORY_DEFAULTS)) {
1893
+ if (configComponent.get(key) === undefined) {
1894
+ await configComponent.set(key, value);
1895
+ }
1896
+ }
1897
+ if (config) {
1898
+ const flatConfig = this.flattenConfig(config);
1899
+ for (const [key, value] of Object.entries(flatConfig)) {
1900
+ await configComponent.set(key, value);
1901
+ }
1902
+ }
1903
+ this.registerConfigWatcher(configComponent);
1904
+ this.buildConfig(configComponent);
1905
+ }
1906
+ buildConfig(configComponent) {
1907
+ const recursive = configComponent.get("memory.recursive") ?? true;
1908
+ const cacheEnabled = configComponent.get("memory.cacheEnabled") ?? true;
1909
+ const cacheTTL = configComponent.get("memory.cacheTTL") ?? 300000;
1910
+ const memoryFile = configComponent.get("memory.memoryFile") ?? "memory.md";
1911
+ const memoryPathsConfig = configComponent.get("memory.memoryPaths");
1912
+ let memoryPaths = [];
1913
+ if (Array.isArray(memoryPathsConfig)) {
1914
+ memoryPaths = memoryPathsConfig;
1915
+ } else if (typeof memoryPathsConfig === "string") {
1916
+ try {
1917
+ memoryPaths = JSON.parse(memoryPathsConfig);
1918
+ } catch {
1919
+ memoryPaths = DEFAULT_MEMORY_CONFIG.memoryPaths;
1920
+ }
1921
+ }
1922
+ if (memoryPaths.length === 0) {
1923
+ memoryPaths = DEFAULT_MEMORY_CONFIG.memoryPaths;
1924
+ }
1925
+ this.config = {
1926
+ memoryPaths,
1927
+ recursive,
1928
+ cacheEnabled,
1929
+ cacheTTL,
1930
+ memoryFile
1931
+ };
1932
+ }
1933
+ flattenConfig(obj, prefix = "memory") {
1934
+ const result = {};
1935
+ for (const [key, value] of Object.entries(obj)) {
1936
+ const fullKey = `${prefix}.${key}`;
1937
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1938
+ Object.assign(result, this.flattenConfig(value, fullKey));
1939
+ } else {
1940
+ result[fullKey] = value;
1941
+ }
1942
+ }
1943
+ return result;
1944
+ }
1945
+ registerConfigWatcher(configComponent) {
1946
+ if (typeof configComponent.watch !== "function") {
1947
+ return;
1948
+ }
1949
+ this.configWatcher = configComponent.watch("memory.*", (event) => {
1950
+ this.onConfigChange(event);
1951
+ });
1952
+ }
1953
+ onConfigChange(event) {
1954
+ logger3.info(`[MemoryComponent] Config changed: ${event.key}`, {
1955
+ oldValue: event.oldValue,
1956
+ newValue: event.newValue
1957
+ });
1958
+ if (this.configComponent) {
1959
+ this.buildConfig(this.configComponent);
1960
+ }
1961
+ this.cache.clear();
1962
+ }
1963
+ async start() {
1964
+ await super.start();
1965
+ this.toolComponent = this.env?.getComponent("tool");
1966
+ if (!this.toolComponent) {
1967
+ logger3.warn("[MemoryComponent] ToolComponent not found, skipping tool registration");
1968
+ return;
1969
+ }
1970
+ await this.registerTools();
1971
+ this.setStatus("running");
1972
+ logger3.info(`[MemoryComponent] Started with ${this.toolComponent.getToolCount()} tools`);
1973
+ }
1974
+ async stop() {
1975
+ if (this.configWatcher) {
1976
+ this.configWatcher();
1977
+ this.configWatcher = undefined;
1978
+ }
1979
+ if (this.toolComponent) {
1980
+ this.toolComponent.unregister("record_memory");
1981
+ this.toolComponent.unregister("recall_memory");
1982
+ }
1983
+ this.cache.clear();
1984
+ await super.stop();
1985
+ logger3.info("[MemoryComponent] Stopped");
1986
+ }
1987
+ async registerTools() {
1988
+ if (!this.toolComponent)
1989
+ return;
1990
+ const tools = createMemoryTools((args) => this.recordMemory(args), (scope) => this.recallMemory(scope), {
1991
+ getMemoryPaths: () => this.getMemoryPaths(),
1992
+ getMemoryFile: () => this.getMemoryFile()
1993
+ });
1994
+ for (const tool of tools) {
1995
+ this.toolComponent.register(tool);
1996
+ }
1997
+ logger3.info("[MemoryComponent] Registered memory tools");
1998
+ }
1999
+ getMemoryPaths() {
2000
+ return this.config.memoryPaths;
2001
+ }
2002
+ updateMemoryPaths(paths) {
2003
+ this.config.memoryPaths = paths;
2004
+ this.clearCache();
2005
+ }
2006
+ getMemoryFile() {
2007
+ return this.config.memoryFile ?? "memory.md";
2008
+ }
2009
+ async recordMemory(args) {
2010
+ const { mode, content, title, filename, scope } = args;
2011
+ const memoryFile = filename ?? this.getMemoryFile();
2012
+ const paths = this.config.memoryPaths;
2013
+ if (paths.length === 0) {
2014
+ return null;
2015
+ }
2016
+ let basePath;
2017
+ if (scope) {
2018
+ const targetPath = paths.find((p) => p.type === scope);
2019
+ if (!targetPath) {
2020
+ logger3.warn(`[recordMemory] No ${scope} path configured, using first available path`);
2021
+ basePath = paths[0].path;
2022
+ } else {
2023
+ basePath = targetPath.path;
2024
+ }
2025
+ } else {
2026
+ basePath = paths[0].path;
2027
+ }
2028
+ const filePath = path5.join(basePath, memoryFile);
2029
+ try {
2030
+ let existingContent = "";
2031
+ let fileExists = false;
2032
+ try {
2033
+ existingContent = await fs2.readFile(filePath, "utf-8");
2034
+ fileExists = true;
2035
+ } catch {}
2036
+ let newContent;
2037
+ let action;
2038
+ switch (mode) {
2039
+ case "delete":
2040
+ if (fileExists) {
2041
+ await fs2.unlink(filePath);
2042
+ this.clearCache();
2043
+ return { path: filePath, action: "delete" };
2044
+ }
2045
+ return null;
2046
+ case "overwrite":
2047
+ if (title && content) {
2048
+ newContent = `## ${title}
2049
+
2050
+ ${content}
2051
+ `;
2052
+ } else {
2053
+ newContent = content ?? "";
2054
+ }
2055
+ action = fileExists ? "overwrite" : "created";
2056
+ break;
2057
+ case "append":
2058
+ if (!content) {
2059
+ throw new Error("content is required for append mode");
2060
+ }
2061
+ if (title) {
2062
+ newContent = existingContent + `
2063
+ ## ${title}
2064
+
2065
+ ${content}
2066
+ `;
2067
+ } else {
2068
+ newContent = existingContent + `
2069
+ ${content}
2070
+ `;
2071
+ }
2072
+ action = fileExists ? "append" : "created";
2073
+ break;
2074
+ case "prepend":
2075
+ if (!content) {
2076
+ throw new Error("content is required for prepend mode");
2077
+ }
2078
+ if (title) {
2079
+ newContent = `## ${title}
2080
+
2081
+ ${content}
2082
+
2083
+ ---
2084
+
2085
+ ${existingContent}`;
2086
+ } else {
2087
+ newContent = `${content}
2088
+
2089
+ ---
2090
+
2091
+ ${existingContent}`;
2092
+ }
2093
+ action = fileExists ? "prepend" : "created";
2094
+ break;
2095
+ default:
2096
+ throw new Error(`Unknown mode: ${mode}`);
2097
+ }
2098
+ await fs2.mkdir(basePath, { recursive: true });
2099
+ await fs2.writeFile(filePath, newContent, "utf-8");
2100
+ this.clearCache();
2101
+ return { path: filePath, action };
2102
+ } catch (error) {
2103
+ logger3.error(`[recordMemory] Failed: ${error}`);
2104
+ throw error;
2105
+ }
2106
+ }
2107
+ async recallMemory(scope) {
2108
+ const memoryFile = this.getMemoryFile();
2109
+ const paths = this.config.memoryPaths;
2110
+ const results = [];
2111
+ for (const memoryPath of paths) {
2112
+ if (scope && memoryPath.type !== scope) {
2113
+ continue;
2114
+ }
2115
+ const filePath = path5.join(memoryPath.path, memoryFile);
2116
+ try {
2117
+ const content = await fs2.readFile(filePath, "utf-8");
2118
+ if (content.trim()) {
2119
+ results.push(`## [${memoryPath.type}] ${memoryFile}
2120
+ ${content}`);
2121
+ }
2122
+ } catch {}
2123
+ }
2124
+ return results.join(`
2125
+
2126
+ `);
2127
+ }
2128
+ clearCache() {
2129
+ this.cache.clear();
2130
+ }
2131
+ getCache(key) {
2132
+ if (!this.config.cacheEnabled)
2133
+ return;
2134
+ const entry = this.cache.get(key);
2135
+ if (!entry)
2136
+ return;
2137
+ const age = Date.now() - entry.timestamp;
2138
+ if (age > (this.config.cacheTTL ?? 300000)) {
2139
+ this.cache.delete(key);
2140
+ return;
2141
+ }
2142
+ return entry.data;
2143
+ }
2144
+ setCache(key, data) {
2145
+ if (!this.config.cacheEnabled)
2146
+ return;
2147
+ this.cache.set(key, { data, timestamp: Date.now() });
2148
+ }
2149
+ }
2150
+ export {
2151
+ recallMemory,
2152
+ parseMemoryAgentOutput,
2153
+ getSourcePriority,
2154
+ generateProjectSummary,
2155
+ formatMemoryInput,
2156
+ createMemoryPlugin,
2157
+ createMemoryAgent,
2158
+ createEmptyResult,
2159
+ buildProjectInput,
2160
+ buildGlobalInput,
2161
+ applyMemoryResult,
2162
+ SOURCE_PRIORITY,
2163
+ RecordMemorySchema,
2164
+ RecallMemorySchema,
2165
+ PROJECT_MEMORY_AGENT_PROMPT,
2166
+ MemoryPlugin,
2167
+ MemoryManager,
2168
+ MemoryComponent,
2169
+ GLOBAL_MEMORY_AGENT_PROMPT,
2170
+ DEFAULT_MEMORY_CONFIG
2171
+ };