@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,1685 @@
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/commands/commands-component.ts
1059
+ import path from "path";
1060
+ import os from "os";
1061
+
1062
+ // packages/core/src/env/component.ts
1063
+ class BaseComponent {
1064
+ _status = "created";
1065
+ _enabled = true;
1066
+ env;
1067
+ hookManager;
1068
+ constructor() {
1069
+ this.hookManager = new HookManager;
1070
+ }
1071
+ getStatus() {
1072
+ return this._status;
1073
+ }
1074
+ getConfig() {
1075
+ return {
1076
+ name: this.name,
1077
+ version: this.version,
1078
+ enabled: this._enabled,
1079
+ env: this.env
1080
+ };
1081
+ }
1082
+ isEnvInitialized() {
1083
+ return this._status !== "created";
1084
+ }
1085
+ setStatus(status) {
1086
+ this._status = status;
1087
+ }
1088
+ getEnv() {
1089
+ return this.env;
1090
+ }
1091
+ async init(config) {
1092
+ if (config?.env) {
1093
+ this.env = config.env;
1094
+ }
1095
+ this.setStatus("initializing");
1096
+ try {
1097
+ if (config?.name)
1098
+ Object.defineProperty(this, "name", { value: config.name, writable: false });
1099
+ if (config?.version)
1100
+ Object.defineProperty(this, "version", { value: config.version, writable: false });
1101
+ } catch {}
1102
+ if (config?.enabled !== undefined)
1103
+ this._enabled = config.enabled;
1104
+ this.hookManager.setComponentInfo(this.name, this.version);
1105
+ await this.onInit();
1106
+ this.setStatus("running");
1107
+ }
1108
+ async start() {
1109
+ if (this._started)
1110
+ return;
1111
+ this._started = true;
1112
+ await this.onStart();
1113
+ this.setStatus("running");
1114
+ }
1115
+ async stop() {
1116
+ this.setStatus("stopping");
1117
+ this.hookManager.clear();
1118
+ await this.onStop();
1119
+ this.setStatus("stopped");
1120
+ }
1121
+ async onInit() {}
1122
+ async onStart() {}
1123
+ async onStop() {}
1124
+ registerHook(hookPoint, hook) {
1125
+ this.hookManager.register(hookPoint, hook);
1126
+ }
1127
+ addHook(hookPoint, name, fn, priority) {
1128
+ this.hookManager.register(hookPoint, createHook({ name, priority }, fn));
1129
+ }
1130
+ removeHook(hookPoint, name) {
1131
+ return this.hookManager.unregister(hookPoint, name);
1132
+ }
1133
+ async executeHooks(hookPoint, data, metadata) {
1134
+ await this.hookManager.execute(hookPoint, data, metadata);
1135
+ }
1136
+ getConfigComponent() {
1137
+ return this.env?.getComponent("config");
1138
+ }
1139
+ getRuntimeConfig(key, defaultValue) {
1140
+ const configComponent = this.getConfigComponent();
1141
+ if (configComponent) {
1142
+ const value = configComponent.get(key);
1143
+ if (value !== undefined) {
1144
+ return value;
1145
+ }
1146
+ }
1147
+ return defaultValue;
1148
+ }
1149
+ }
1150
+
1151
+ // packages/core/src/env/commands/commands-component.ts
1152
+ init_logger();
1153
+ import * as fs2 from "fs/promises";
1154
+ import { exec } from "child_process";
1155
+ import { promisify } from "util";
1156
+
1157
+ // packages/core/src/env/commands/parser.ts
1158
+ import fs from "fs/promises";
1159
+ init_logger();
1160
+ var logger = createLogger("commands-parser");
1161
+ function parseFrontmatter(text) {
1162
+ const result = {};
1163
+ const lines = text.split(`
1164
+ `);
1165
+ for (const line of lines) {
1166
+ const match = line.match(/^(\w+):\s*"?(.+?)"?\s*$/);
1167
+ if (match) {
1168
+ const key = match[1];
1169
+ let value = match[2];
1170
+ if (value.startsWith('"') && value.endsWith('"')) {
1171
+ value = value.slice(1, -1);
1172
+ }
1173
+ result[key] = value;
1174
+ }
1175
+ }
1176
+ return result;
1177
+ }
1178
+ async function parseMetaFile(filePath, source) {
1179
+ try {
1180
+ const content = await fs.readFile(filePath, "utf-8");
1181
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n?/);
1182
+ if (!frontmatterMatch) {
1183
+ logger.warn(`[Parser] Missing frontmatter in: ${filePath}`);
1184
+ return null;
1185
+ }
1186
+ const frontmatter = parseFrontmatter(frontmatterMatch[1]);
1187
+ const name = frontmatter.name;
1188
+ const description = frontmatter.description;
1189
+ if (!name) {
1190
+ logger.warn(`[Parser] Missing name in frontmatter: ${filePath}`);
1191
+ return null;
1192
+ }
1193
+ if (!description) {
1194
+ logger.warn(`[Parser] Missing description in frontmatter: ${filePath}`);
1195
+ return null;
1196
+ }
1197
+ return {
1198
+ name,
1199
+ description,
1200
+ tips: frontmatter.tips,
1201
+ filePath,
1202
+ source
1203
+ };
1204
+ } catch (error) {
1205
+ logger.error(`[Parser] Failed to parse file: ${filePath}`, error);
1206
+ return null;
1207
+ }
1208
+ }
1209
+
1210
+ // packages/core/src/config/env-key.ts
1211
+ function toEnvKey(key, prefix) {
1212
+ let keyNormalized = key.replace(/[.-]/g, "_");
1213
+ keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/_+/g, "_").toUpperCase();
1214
+ if (prefix) {
1215
+ const separator = prefix.endsWith("_") ? "" : "_";
1216
+ return `${prefix}${separator}${keyNormalized}`;
1217
+ }
1218
+ return keyNormalized;
1219
+ }
1220
+ function fromEnvKey(envKey, prefix) {
1221
+ if (!prefix) {
1222
+ return envKey;
1223
+ }
1224
+ if (envKey.startsWith(prefix)) {
1225
+ const afterPrefix = envKey.slice(prefix.length);
1226
+ if (afterPrefix.startsWith("_")) {
1227
+ return afterPrefix.slice(1);
1228
+ }
1229
+ return afterPrefix;
1230
+ }
1231
+ return envKey;
1232
+ }
1233
+ function envKeyToConfigKey(envKey, prefix, componentName) {
1234
+ const prefixUpper = prefix.toUpperCase();
1235
+ if (!envKey.startsWith(prefixUpper)) {
1236
+ return;
1237
+ }
1238
+ const componentUpperNormalized = componentName.replace(/-/g, "_").toUpperCase();
1239
+ let keyPart = envKey.slice(prefixUpper.length);
1240
+ if (keyPart.startsWith("_")) {
1241
+ keyPart = keyPart.slice(1);
1242
+ }
1243
+ if (!keyPart) {
1244
+ return;
1245
+ }
1246
+ const firstUnderscore = keyPart.indexOf("_");
1247
+ let restPart;
1248
+ if (firstUnderscore === -1) {
1249
+ restPart = keyPart;
1250
+ } else {
1251
+ const firstPart = keyPart.slice(0, firstUnderscore);
1252
+ const remaining = keyPart.slice(firstUnderscore + 1);
1253
+ if (firstPart === componentUpperNormalized) {
1254
+ restPart = remaining;
1255
+ } else {
1256
+ restPart = keyPart;
1257
+ }
1258
+ }
1259
+ if (!restPart) {
1260
+ return;
1261
+ }
1262
+ const restPartConverted = restPart.replace(/_/g, ".");
1263
+ return `${componentName}.${restPartConverted.toLowerCase()}`;
1264
+ }
1265
+
1266
+ // packages/core/src/env/commands/commands-config-registration.ts
1267
+ var COMMANDS_CONFIG_REGISTRATION = {
1268
+ name: "command",
1269
+ sources: [
1270
+ { type: "env", envPrefix: "COMMAND", priority: 20, watch: false }
1271
+ ],
1272
+ keys: [
1273
+ { key: "command.userCommandsDir", sources: ["env", "file"] },
1274
+ { key: "command.projectCommandsDir", sources: ["env", "file"] },
1275
+ { key: "command.cacheDir", sources: ["env", "file"] }
1276
+ ]
1277
+ };
1278
+
1279
+ // packages/core/src/env/commands/commands-component.ts
1280
+ var execAsync = promisify(exec);
1281
+ var logger2 = createLogger("commands");
1282
+ var DEFAULT_USER_DIR = ".roy-agent/commands";
1283
+ var DEFAULT_PROJECT_DIR = ".roy/commands";
1284
+ var DEFAULT_CACHE_DIR = ".cache/roy-agent/commands";
1285
+ var DESCRIPTIONS_FILE = "descriptions.json";
1286
+ var CONFIG_KEYS = [
1287
+ "command.userCommandsDir",
1288
+ "command.projectCommandsDir",
1289
+ "command.cacheDir"
1290
+ ];
1291
+
1292
+ class CommandsComponent extends BaseComponent {
1293
+ name = "commands";
1294
+ version = "2.0.0";
1295
+ config;
1296
+ configComponent;
1297
+ userCommandsDir = "";
1298
+ projectCommandsDir = "";
1299
+ descriptionCache = new Map;
1300
+ descriptionCacheFile = "";
1301
+ constructor() {
1302
+ super();
1303
+ this.initDefaultDirs();
1304
+ }
1305
+ initDefaultDirs() {
1306
+ const homeDir = os.homedir();
1307
+ this.userCommandsDir = path.join(homeDir, DEFAULT_USER_DIR);
1308
+ this.projectCommandsDir = DEFAULT_PROJECT_DIR;
1309
+ this.descriptionCacheFile = path.join(homeDir, DEFAULT_CACHE_DIR, DESCRIPTIONS_FILE);
1310
+ }
1311
+ async init(config) {
1312
+ await super.init(config);
1313
+ const options = config?.options;
1314
+ if (!options?.configComponent) {
1315
+ throw new Error("ConfigComponent is required for CommandsComponent initialization");
1316
+ }
1317
+ this.configComponent = options.configComponent;
1318
+ await this.registerConfig(options);
1319
+ await fs2.mkdir(this.userCommandsDir, { recursive: true });
1320
+ await this.loadDescriptionCache();
1321
+ logger2.info(`CommandsComponent initialized: user=${this.userCommandsDir}, project=${this.projectCommandsDir}`);
1322
+ }
1323
+ async registerConfig(options) {
1324
+ const configComponent = this.configComponent;
1325
+ if (!configComponent)
1326
+ return;
1327
+ const { configPath, envPrefix, config } = options;
1328
+ configComponent.registerComponent(COMMANDS_CONFIG_REGISTRATION);
1329
+ if (configPath) {
1330
+ configComponent.registerSource({
1331
+ type: "file",
1332
+ relativePath: configPath,
1333
+ optional: true,
1334
+ watch: false
1335
+ });
1336
+ }
1337
+ await configComponent.load("command");
1338
+ const prefix = envPrefix !== undefined ? envPrefix : "COMMAND";
1339
+ for (const key of CONFIG_KEYS) {
1340
+ const envKey = toEnvKey(key, prefix);
1341
+ const value = process.env[envKey];
1342
+ if (value !== undefined) {
1343
+ await configComponent.set(key, value);
1344
+ }
1345
+ }
1346
+ const loadedKeys = new Set(CONFIG_KEYS);
1347
+ for (const envKey of Object.keys(process.env)) {
1348
+ const configKey = envKeyToConfigKey(envKey, prefix, "command");
1349
+ if (!configKey)
1350
+ continue;
1351
+ if (loadedKeys.has(configKey))
1352
+ continue;
1353
+ loadedKeys.add(configKey);
1354
+ const value = process.env[envKey];
1355
+ if (value !== undefined) {
1356
+ await configComponent.set(configKey, value);
1357
+ }
1358
+ }
1359
+ if (config) {
1360
+ const flatConfig = this.flattenConfig(config);
1361
+ for (const [key, value] of Object.entries(flatConfig)) {
1362
+ if (value !== undefined) {
1363
+ await configComponent.set(key, value);
1364
+ }
1365
+ }
1366
+ }
1367
+ const homeDir = os.homedir();
1368
+ const defaultDirs = {
1369
+ "command.userCommandsDir": path.join(homeDir, DEFAULT_USER_DIR),
1370
+ "command.projectCommandsDir": DEFAULT_PROJECT_DIR,
1371
+ "command.cacheDir": path.join(homeDir, DEFAULT_CACHE_DIR)
1372
+ };
1373
+ for (const [key, value] of Object.entries(defaultDirs)) {
1374
+ if (configComponent.get(key) === undefined) {
1375
+ await configComponent.set(key, value);
1376
+ }
1377
+ }
1378
+ this.applyConfig(configComponent);
1379
+ }
1380
+ flattenConfig(config) {
1381
+ const result = {};
1382
+ if (config.userCommandsDir !== undefined) {
1383
+ result["command.userCommandsDir"] = config.userCommandsDir;
1384
+ }
1385
+ if (config.projectCommandsDir !== undefined) {
1386
+ result["command.projectCommandsDir"] = config.projectCommandsDir;
1387
+ }
1388
+ if (config.cacheDir !== undefined) {
1389
+ result["command.cacheDir"] = config.cacheDir;
1390
+ }
1391
+ return result;
1392
+ }
1393
+ applyConfig(configComponent) {
1394
+ const userDir = configComponent.get("command.userCommandsDir");
1395
+ const projectDir = configComponent.get("command.projectCommandsDir");
1396
+ const cacheDir = configComponent.get("command.cacheDir");
1397
+ this.userCommandsDir = userDir || path.join(os.homedir(), DEFAULT_USER_DIR);
1398
+ this.projectCommandsDir = projectDir || DEFAULT_PROJECT_DIR;
1399
+ this.descriptionCacheFile = path.join(cacheDir || path.join(os.homedir(), DEFAULT_CACHE_DIR), DESCRIPTIONS_FILE);
1400
+ this.config = {
1401
+ userCommandsDir: this.userCommandsDir,
1402
+ projectCommandsDir: this.projectCommandsDir,
1403
+ cacheDir
1404
+ };
1405
+ }
1406
+ async start() {
1407
+ await super.start();
1408
+ logger2.debug("CommandsComponent started");
1409
+ }
1410
+ async stop() {
1411
+ await this.saveDescriptionCache();
1412
+ await super.stop();
1413
+ logger2.debug("CommandsComponent stopped");
1414
+ }
1415
+ async getCommandDirs() {
1416
+ return {
1417
+ user: this.userCommandsDir,
1418
+ project: this.projectCommandsDir
1419
+ };
1420
+ }
1421
+ async discover(options) {
1422
+ const commands = [];
1423
+ let userCount = 0;
1424
+ let projectCount = 0;
1425
+ try {
1426
+ const projectCommands = await this.scanDir(this.projectCommandsDir, "project", options?.pattern);
1427
+ commands.push(...projectCommands);
1428
+ projectCount = projectCommands.length;
1429
+ } catch (error) {
1430
+ logger2.debug(`Failed to scan project dir: ${error}`);
1431
+ }
1432
+ try {
1433
+ const userCommands = await this.scanDir(this.userCommandsDir, "user", options?.pattern);
1434
+ for (const cmd of userCommands) {
1435
+ const exists = commands.find((c) => c.name === cmd.name);
1436
+ if (!exists) {
1437
+ commands.push(cmd);
1438
+ userCount++;
1439
+ }
1440
+ }
1441
+ } catch (error) {
1442
+ logger2.debug(`Failed to scan user dir: ${error}`);
1443
+ }
1444
+ commands.sort((a, b) => a.name.localeCompare(b.name));
1445
+ return {
1446
+ commands,
1447
+ stats: { userCount, projectCount }
1448
+ };
1449
+ }
1450
+ async add(options) {
1451
+ const { name, target, source = "user", description, tips } = options;
1452
+ const dir = source === "user" ? this.userCommandsDir : this.projectCommandsDir;
1453
+ const targetPath = path.resolve(target);
1454
+ await fs2.mkdir(dir, { recursive: true });
1455
+ const commandPath = path.join(dir, name);
1456
+ try {
1457
+ await fs2.access(commandPath);
1458
+ throw new Error(`Command '${name}' already exists`);
1459
+ } catch (error) {
1460
+ if (error.code !== "ENOENT") {
1461
+ throw error;
1462
+ }
1463
+ }
1464
+ await fs2.symlink(targetPath, commandPath);
1465
+ logger2.info(`Added command '${name}' -> ${targetPath} (${source})`);
1466
+ const commandDir = path.join(dir, name);
1467
+ await this.createCommandMeta(commandDir, {
1468
+ name,
1469
+ target: targetPath,
1470
+ description: description || `Command: ${name}`,
1471
+ tips,
1472
+ source
1473
+ });
1474
+ }
1475
+ async createCommandMeta(commandDir, options) {
1476
+ const parentDir = path.dirname(commandDir);
1477
+ const metaPath = path.join(parentDir, `${options.name}.meta.md`);
1478
+ const tipsContent = options.tips ? `
1479
+ tips: "${options.tips}"` : "";
1480
+ const content = `---
1481
+ name: ${options.name}
1482
+ description: ${options.description}${tipsContent}
1483
+ source: ${options.source}
1484
+ ---
1485
+
1486
+ # ${options.name} Command
1487
+
1488
+ ## Target
1489
+ \`${options.target}\`
1490
+
1491
+ ## \u529F\u80FD
1492
+ ${options.description}
1493
+
1494
+ ## \u63A2\u7D22\u63D0\u793A
1495
+ Run \`${options.name} --help\` to explore full capabilities.
1496
+ `;
1497
+ await fs2.writeFile(metaPath, content, "utf-8");
1498
+ logger2.info(`[CommandsComponent] Created meta.md for '${options.name}'`);
1499
+ }
1500
+ async getCommandsMeta() {
1501
+ const metaList = [];
1502
+ try {
1503
+ const entries = await fs2.readdir(this.userCommandsDir, { withFileTypes: true });
1504
+ for (const entry of entries) {
1505
+ if (entry.isFile() && entry.name.endsWith(".meta.md")) {
1506
+ const metaPath = path.join(this.userCommandsDir, entry.name);
1507
+ const meta = await parseMetaFile(metaPath, "user");
1508
+ if (meta) {
1509
+ metaList.push(meta);
1510
+ }
1511
+ }
1512
+ }
1513
+ } catch (error) {
1514
+ if (error.code !== "ENOENT") {
1515
+ logger2.debug(`Failed to scan user commands dir: ${error}`);
1516
+ }
1517
+ }
1518
+ try {
1519
+ const entries = await fs2.readdir(this.projectCommandsDir, { withFileTypes: true });
1520
+ for (const entry of entries) {
1521
+ if (entry.isFile() && entry.name.endsWith(".meta.md")) {
1522
+ const metaPath = path.join(this.projectCommandsDir, entry.name);
1523
+ const meta = await parseMetaFile(metaPath, "project");
1524
+ if (meta) {
1525
+ metaList.push(meta);
1526
+ }
1527
+ }
1528
+ }
1529
+ } catch (error) {
1530
+ if (error.code !== "ENOENT") {
1531
+ logger2.debug(`Failed to scan project commands dir: ${error}`);
1532
+ }
1533
+ }
1534
+ return metaList;
1535
+ }
1536
+ async remove(options) {
1537
+ const { name, source } = options;
1538
+ const dirsToCheck = source ? [source === "user" ? this.userCommandsDir : this.projectCommandsDir] : [this.userCommandsDir, this.projectCommandsDir];
1539
+ for (const dir of dirsToCheck) {
1540
+ const commandPath = path.join(dir, name);
1541
+ try {
1542
+ await fs2.unlink(commandPath);
1543
+ logger2.info(`Removed command '${name}' from ${dir}`);
1544
+ return;
1545
+ } catch (error) {
1546
+ if (error.code !== "ENOENT") {
1547
+ throw error;
1548
+ }
1549
+ }
1550
+ }
1551
+ throw new Error(`Command '${name}' not found`);
1552
+ }
1553
+ async getInfo(name) {
1554
+ const dirsToCheck = [this.projectCommandsDir, this.userCommandsDir];
1555
+ for (const dir of dirsToCheck) {
1556
+ const commandPath = path.join(dir, name);
1557
+ try {
1558
+ const stat = await fs2.lstat(commandPath);
1559
+ const realPath = stat.isSymbolicLink() ? await fs2.readlink(commandPath) : commandPath;
1560
+ const cmdSource = dir === this.projectCommandsDir ? "project" : "user";
1561
+ const shortDescription = await this.getDescription(realPath);
1562
+ return {
1563
+ name,
1564
+ path: realPath,
1565
+ source: cmdSource,
1566
+ shortDescription
1567
+ };
1568
+ } catch (error) {
1569
+ if (error.code !== "ENOENT") {
1570
+ throw error;
1571
+ }
1572
+ }
1573
+ }
1574
+ return null;
1575
+ }
1576
+ async exec(options) {
1577
+ const { name, args = [], cwd } = options;
1578
+ const info = await this.getInfo(name);
1579
+ if (!info) {
1580
+ return {
1581
+ stdout: "",
1582
+ stderr: `Command '${name}' not found`,
1583
+ exitCode: 127,
1584
+ success: false
1585
+ };
1586
+ }
1587
+ const cmd = `${info.path} ${args.join(" ")}`;
1588
+ try {
1589
+ const { stdout, stderr } = await execAsync(cmd, {
1590
+ cwd: cwd || process.cwd(),
1591
+ timeout: 30000
1592
+ });
1593
+ return {
1594
+ stdout,
1595
+ stderr,
1596
+ exitCode: 0,
1597
+ success: true
1598
+ };
1599
+ } catch (error) {
1600
+ return {
1601
+ stdout: error.stdout || "",
1602
+ stderr: error.stderr || error.message,
1603
+ exitCode: error.code || 1,
1604
+ success: false
1605
+ };
1606
+ }
1607
+ }
1608
+ async scanDir(dir, source, pattern) {
1609
+ const commands = [];
1610
+ try {
1611
+ const entries = await fs2.readdir(dir);
1612
+ for (const entry of entries) {
1613
+ if (entry.startsWith("."))
1614
+ continue;
1615
+ if (pattern && !this.matchPattern(entry, pattern))
1616
+ continue;
1617
+ const fullPath = path.join(dir, entry);
1618
+ try {
1619
+ const stat = await fs2.lstat(fullPath);
1620
+ if (!stat.isSymbolicLink() && !stat.isFile())
1621
+ continue;
1622
+ if (stat.isFile()) {
1623
+ try {
1624
+ await fs2.access(fullPath, fs2.constants.X_OK);
1625
+ } catch {
1626
+ continue;
1627
+ }
1628
+ }
1629
+ const realPath = stat.isSymbolicLink() ? await fs2.readlink(fullPath) : fullPath;
1630
+ const shortDescription = await this.getDescription(realPath);
1631
+ commands.push({
1632
+ name: entry,
1633
+ path: realPath,
1634
+ source,
1635
+ shortDescription
1636
+ });
1637
+ } catch (error) {
1638
+ logger2.debug(`Failed to stat ${fullPath}: ${error}`);
1639
+ }
1640
+ }
1641
+ } catch (error) {
1642
+ logger2.debug(`Failed to scan dir ${dir}: ${error}`);
1643
+ }
1644
+ return commands;
1645
+ }
1646
+ matchPattern(name, pattern) {
1647
+ const regex = new RegExp("^" + pattern.replace(/\*/g, ".*").replace(/\?/g, ".") + "$");
1648
+ return regex.test(name);
1649
+ }
1650
+ async getDescription(commandPath) {
1651
+ const cached = this.descriptionCache.get(commandPath);
1652
+ if (cached !== undefined)
1653
+ return cached;
1654
+ try {
1655
+ const { stdout } = await execAsync(`${commandPath} --help 2>/dev/null | head -1`, {
1656
+ timeout: 2000
1657
+ });
1658
+ const description = stdout.trim().split(`
1659
+ `)[0] || "";
1660
+ this.descriptionCache.set(commandPath, description);
1661
+ return description;
1662
+ } catch {
1663
+ return "";
1664
+ }
1665
+ }
1666
+ async loadDescriptionCache() {
1667
+ try {
1668
+ const content = await fs2.readFile(this.descriptionCacheFile, "utf-8");
1669
+ const data = JSON.parse(content);
1670
+ this.descriptionCache = new Map(Object.entries(data));
1671
+ } catch {}
1672
+ }
1673
+ async saveDescriptionCache() {
1674
+ try {
1675
+ await fs2.mkdir(path.dirname(this.descriptionCacheFile), { recursive: true });
1676
+ const data = Object.fromEntries(this.descriptionCache);
1677
+ await fs2.writeFile(this.descriptionCacheFile, JSON.stringify(data, null, 2));
1678
+ } catch (error) {
1679
+ logger2.debug(`Failed to save description cache: ${error}`);
1680
+ }
1681
+ }
1682
+ }
1683
+ export {
1684
+ CommandsComponent
1685
+ };