@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,1626 @@
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/workflow/storage/sqlite.ts
850
+ var exports_sqlite = {};
851
+ __export(exports_sqlite, {
852
+ resetDatabase: () => resetDatabase,
853
+ initializeTables: () => initializeTables,
854
+ initDatabase: () => initDatabase,
855
+ getDatabasePath: () => getDatabasePath,
856
+ getDatabase: () => getDatabase,
857
+ closeDatabase: () => closeDatabase
858
+ });
859
+ import { join as join2 } from "path";
860
+ function getDefaultDataDir() {
861
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
862
+ return join2(home, ".local", "share", "roy-agent");
863
+ }
864
+ function getDatabasePath() {
865
+ return join2(getDefaultDataDir(), "workflows.db");
866
+ }
867
+ function getDatabase(path) {
868
+ if (!dbInstance) {
869
+ const dbPath = path ?? getDatabasePath();
870
+ const dbDir = dbPath.substring(0, dbPath.lastIndexOf("/"));
871
+ if (dbDir && dbDir !== "/") {
872
+ try {
873
+ const { mkdirSync: mkdirSync2 } = __require("fs");
874
+ mkdirSync2(dbDir, { recursive: true });
875
+ } catch {}
876
+ }
877
+ const { Database } = __require("bun:sqlite");
878
+ dbInstance = new Database(dbPath);
879
+ try {
880
+ if (typeof dbInstance.pragma === "function") {
881
+ dbInstance.pragma("journal_mode = WAL");
882
+ }
883
+ } catch {
884
+ logger?.debug("WAL mode not available, using default journal mode");
885
+ }
886
+ }
887
+ return dbInstance;
888
+ }
889
+ function closeDatabase() {
890
+ if (dbInstance) {
891
+ dbInstance.close();
892
+ dbInstance = null;
893
+ }
894
+ }
895
+ function initializeTables() {
896
+ const db = getDatabase();
897
+ db.exec(`
898
+ CREATE TABLE IF NOT EXISTS workflows (
899
+ id TEXT PRIMARY KEY,
900
+ name TEXT NOT NULL UNIQUE,
901
+ version TEXT NOT NULL DEFAULT '1.0',
902
+ description TEXT,
903
+ definition TEXT NOT NULL,
904
+ config TEXT NOT NULL DEFAULT '{}',
905
+ metadata TEXT NOT NULL DEFAULT '{}',
906
+ tags TEXT NOT NULL DEFAULT '[]',
907
+ task_id INTEGER,
908
+ created_at TEXT NOT NULL,
909
+ updated_at TEXT NOT NULL
910
+ )
911
+ `);
912
+ db.exec(`
913
+ CREATE INDEX IF NOT EXISTS idx_workflows_name ON workflows(name);
914
+ CREATE INDEX IF NOT EXISTS idx_workflows_tags ON workflows(tags);
915
+ CREATE INDEX IF NOT EXISTS idx_workflows_task_id ON workflows(task_id);
916
+ `);
917
+ }
918
+ function resetDatabase() {
919
+ closeDatabase();
920
+ dbInstance = null;
921
+ }
922
+ function initDatabase(path) {
923
+ const db = getDatabase(path);
924
+ initializeTables();
925
+ return db;
926
+ }
927
+ var logger, dbInstance = null;
928
+ var init_sqlite = __esm(() => {
929
+ init_logger();
930
+ logger = createLogger("workflow:sqlite");
931
+ });
932
+
933
+ // packages/core/src/env/session/search-query-parser.ts
934
+ var exports_search_query_parser = {};
935
+ __export(exports_search_query_parser, {
936
+ parseSearchQuery: () => parseSearchQuery,
937
+ matchesQuery: () => matchesQuery
938
+ });
939
+ function parseSearchQuery(query) {
940
+ const result = {
941
+ required: [],
942
+ excluded: [],
943
+ phrases: []
944
+ };
945
+ if (!query || !query.trim()) {
946
+ return result;
947
+ }
948
+ const phraseRegex = /"([^"]+)"/g;
949
+ let match;
950
+ while ((match = phraseRegex.exec(query)) !== null) {
951
+ result.phrases.push(match[1].toLowerCase());
952
+ }
953
+ query = query.replace(phraseRegex, "");
954
+ query = query.replace(/\s+/g, " ").trim();
955
+ if (!query) {
956
+ return result;
957
+ }
958
+ const parts = [];
959
+ let remaining = query;
960
+ const singleOpRegex = /\s+(AND|OR|NOT)\s+/gi;
961
+ let opMatch;
962
+ while ((opMatch = singleOpRegex.exec(remaining)) !== null) {
963
+ const op = opMatch[1].toUpperCase();
964
+ const beforeText = remaining.slice(0, opMatch.index).trim();
965
+ if (beforeText) {
966
+ parts.push({ text: beforeText, operator: undefined });
967
+ }
968
+ parts.push({ text: op, operator: op });
969
+ remaining = remaining.slice(opMatch.index + opMatch[0].length);
970
+ singleOpRegex.lastIndex = 0;
971
+ }
972
+ if (remaining.trim()) {
973
+ parts.push({ text: remaining.trim(), operator: undefined });
974
+ }
975
+ let currentOperator = "AND";
976
+ for (const part of parts) {
977
+ if (part.operator) {
978
+ currentOperator = part.operator;
979
+ } else {
980
+ const wordRegex = /[\w\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]+/gu;
981
+ const words = part.text.match(wordRegex) || [];
982
+ for (const word of words) {
983
+ const lowerWord = word.toLowerCase();
984
+ if (lowerWord === "and" || lowerWord === "or" || lowerWord === "not") {
985
+ currentOperator = lowerWord.toUpperCase();
986
+ continue;
987
+ }
988
+ if (currentOperator === "NOT") {
989
+ if (!result.excluded.includes(lowerWord)) {
990
+ result.excluded.push(lowerWord);
991
+ }
992
+ } else {
993
+ if (!result.required.includes(lowerWord)) {
994
+ result.required.push(lowerWord);
995
+ }
996
+ }
997
+ currentOperator = "AND";
998
+ }
999
+ }
1000
+ }
1001
+ return result;
1002
+ }
1003
+ function matchesQuery(content, query) {
1004
+ if (!content) {
1005
+ return query.required.length === 0 && query.phrases.length === 0;
1006
+ }
1007
+ const lowerContent = content.toLowerCase();
1008
+ for (const term of query.excluded) {
1009
+ if (lowerContent.includes(term.toLowerCase())) {
1010
+ return false;
1011
+ }
1012
+ }
1013
+ for (const phrase of query.phrases) {
1014
+ if (!lowerContent.includes(phrase)) {
1015
+ return false;
1016
+ }
1017
+ }
1018
+ if (query.required.length > 0) {
1019
+ for (const term of query.required) {
1020
+ if (!lowerContent.includes(term)) {
1021
+ return false;
1022
+ }
1023
+ }
1024
+ }
1025
+ return true;
1026
+ }
1027
+
1028
+ // packages/core/src/env/workflow/storage/workflow-repo.ts
1029
+ var exports_workflow_repo = {};
1030
+ __export(exports_workflow_repo, {
1031
+ rowToWorkflow: () => rowToWorkflow,
1032
+ WorkflowRepository: () => WorkflowRepository
1033
+ });
1034
+ import { randomUUID } from "crypto";
1035
+ function rowToWorkflow(row) {
1036
+ const metadata = JSON.parse(row.metadata);
1037
+ if (row.task_id !== null) {
1038
+ metadata.taskId = row.task_id;
1039
+ }
1040
+ return {
1041
+ id: row.id,
1042
+ name: row.name,
1043
+ version: row.version,
1044
+ description: row.description || undefined,
1045
+ definition: JSON.parse(row.definition),
1046
+ config: JSON.parse(row.config),
1047
+ metadata,
1048
+ tags: JSON.parse(row.tags),
1049
+ createdAt: new Date(row.created_at),
1050
+ updatedAt: new Date(row.updated_at)
1051
+ };
1052
+ }
1053
+
1054
+ class WorkflowRepository {
1055
+ db;
1056
+ constructor(db) {
1057
+ this.db = db || getDatabase();
1058
+ }
1059
+ create(workflow) {
1060
+ const id = randomUUID();
1061
+ const now = new Date().toISOString();
1062
+ const stmt = this.db.prepare(`
1063
+ INSERT INTO workflows (id, name, version, description, definition, config, metadata, tags, task_id, created_at, updated_at)
1064
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1065
+ `);
1066
+ stmt.run(id, workflow.name, workflow.version, workflow.description || null, JSON.stringify(workflow.definition), JSON.stringify(workflow.config), JSON.stringify(workflow.metadata), JSON.stringify(workflow.tags), workflow.metadata?.taskId || null, now, now);
1067
+ return {
1068
+ ...workflow,
1069
+ id,
1070
+ createdAt: new Date(now),
1071
+ updatedAt: new Date(now)
1072
+ };
1073
+ }
1074
+ createFromDefinition(definition, options) {
1075
+ const workflow = {
1076
+ name: definition.name,
1077
+ version: definition.version,
1078
+ description: definition.description,
1079
+ definition,
1080
+ config: options?.config || definition.config || {},
1081
+ metadata: options?.metadata || definition.metadata || {},
1082
+ tags: options?.tags || definition.metadata?.tags || []
1083
+ };
1084
+ return this.create(workflow);
1085
+ }
1086
+ getById(id) {
1087
+ const row = this.db.prepare("SELECT * FROM workflows WHERE id = ?").get(id);
1088
+ if (!row)
1089
+ return;
1090
+ return rowToWorkflow(row);
1091
+ }
1092
+ getByName(name) {
1093
+ const row = this.db.prepare("SELECT * FROM workflows WHERE name = ? ORDER BY updated_at DESC LIMIT 1").get(name);
1094
+ if (!row)
1095
+ return;
1096
+ return rowToWorkflow(row);
1097
+ }
1098
+ getByNameAndVersion(name, version) {
1099
+ const row = this.db.prepare("SELECT * FROM workflows WHERE name = ? AND version = ?").get(name, version);
1100
+ if (!row)
1101
+ return;
1102
+ return rowToWorkflow(row);
1103
+ }
1104
+ list(options) {
1105
+ let sql = "SELECT * FROM workflows";
1106
+ const params = [];
1107
+ const conditions = [];
1108
+ if (options?.tag) {
1109
+ conditions.push("tags LIKE ?");
1110
+ params.push(`%${options.tag}%`);
1111
+ }
1112
+ if (options?.taskId !== undefined) {
1113
+ conditions.push("task_id = ?");
1114
+ params.push(options.taskId);
1115
+ }
1116
+ if (conditions.length > 0) {
1117
+ sql += " WHERE " + conditions.join(" AND ");
1118
+ }
1119
+ const orderBy = options?.orderBy || "updated_at";
1120
+ const order = options?.order || "desc";
1121
+ sql += ` ORDER BY ${orderBy} ${order.toUpperCase()}`;
1122
+ if (options?.limit !== undefined) {
1123
+ sql += " LIMIT ?";
1124
+ params.push(options.limit);
1125
+ }
1126
+ if (options?.offset !== undefined) {
1127
+ sql += " OFFSET ?";
1128
+ params.push(options.offset);
1129
+ }
1130
+ const rows = this.db.prepare(sql).all(...params);
1131
+ let workflows = rows.map(rowToWorkflow);
1132
+ if (options?.search) {
1133
+ const { parseSearchQuery: parseSearchQuery2, matchesQuery: matchesQuery2 } = __toCommonJS(exports_search_query_parser);
1134
+ const query = parseSearchQuery2(options.search);
1135
+ workflows = workflows.filter((w) => {
1136
+ const descMatch = w.description ? matchesQuery2(w.description, query) : false;
1137
+ const tagsMatch = w.tags.some((tag) => matchesQuery2(tag, query));
1138
+ return descMatch || tagsMatch;
1139
+ });
1140
+ }
1141
+ return workflows;
1142
+ }
1143
+ listVersions(name) {
1144
+ const rows = this.db.prepare("SELECT * FROM workflows WHERE name = ? ORDER BY version DESC").all(name);
1145
+ return rows.map(rowToWorkflow);
1146
+ }
1147
+ update(id, updates) {
1148
+ const existing = this.getById(id);
1149
+ if (!existing)
1150
+ return;
1151
+ const now = new Date().toISOString();
1152
+ const setClauses = ["updated_at = ?"];
1153
+ const params = [now];
1154
+ if (updates.name !== undefined) {
1155
+ setClauses.push("name = ?");
1156
+ params.push(updates.name);
1157
+ }
1158
+ if (updates.version !== undefined) {
1159
+ setClauses.push("version = ?");
1160
+ params.push(updates.version);
1161
+ }
1162
+ if (updates.description !== undefined) {
1163
+ setClauses.push("description = ?");
1164
+ params.push(updates.description);
1165
+ }
1166
+ if (updates.definition !== undefined) {
1167
+ setClauses.push("definition = ?");
1168
+ params.push(JSON.stringify(updates.definition));
1169
+ }
1170
+ if (updates.config !== undefined) {
1171
+ setClauses.push("config = ?");
1172
+ params.push(JSON.stringify(updates.config));
1173
+ }
1174
+ if (updates.metadata !== undefined) {
1175
+ setClauses.push("metadata = ?");
1176
+ params.push(JSON.stringify(updates.metadata));
1177
+ if (updates.metadata.taskId !== undefined) {
1178
+ setClauses.push("task_id = ?");
1179
+ params.push(updates.metadata.taskId);
1180
+ }
1181
+ }
1182
+ if (updates.tags !== undefined) {
1183
+ setClauses.push("tags = ?");
1184
+ params.push(JSON.stringify(updates.tags));
1185
+ }
1186
+ params.push(id);
1187
+ this.db.prepare(`UPDATE workflows SET ${setClauses.join(", ")} WHERE id = ?`).run(...params);
1188
+ return this.getById(id);
1189
+ }
1190
+ delete(id) {
1191
+ const existing = this.getById(id);
1192
+ if (!existing)
1193
+ return false;
1194
+ this.db.prepare("DELETE FROM workflows WHERE id = ?").run(id);
1195
+ return true;
1196
+ }
1197
+ exists(id) {
1198
+ const result = this.db.prepare("SELECT 1 FROM workflows WHERE id = ?").get(id);
1199
+ return result !== undefined;
1200
+ }
1201
+ existsByNameAndVersion(name, version) {
1202
+ const result = this.db.prepare("SELECT 1 FROM workflows WHERE name = ? AND version = ?").get(name, version);
1203
+ return result !== undefined;
1204
+ }
1205
+ count() {
1206
+ const result = this.db.prepare("SELECT COUNT(*) as count FROM workflows").get();
1207
+ return result.count;
1208
+ }
1209
+ search(query, limit) {
1210
+ let sql = "SELECT * FROM workflows WHERE name LIKE ? ORDER BY updated_at DESC";
1211
+ const params = [`%${query}%`];
1212
+ if (limit !== undefined) {
1213
+ sql += " LIMIT ?";
1214
+ params.push(limit);
1215
+ }
1216
+ const rows = this.db.prepare(sql).all(...params);
1217
+ return rows.map(rowToWorkflow);
1218
+ }
1219
+ }
1220
+ var init_workflow_repo = __esm(() => {
1221
+ init_sqlite();
1222
+ });
1223
+
1224
+ // packages/core/src/env/task/hooks/task-hook-points.ts
1225
+ var TaskHookPoints = {
1226
+ BEFORE_CREATE: "task:before.create",
1227
+ AFTER_CREATE: "task:after.create",
1228
+ BEFORE_UPDATE: "task:before.update",
1229
+ AFTER_UPDATE: "task:after.update",
1230
+ BEFORE_DELETE: "task:before.delete",
1231
+ AFTER_DELETE: "task:after.delete",
1232
+ DELEGATE_BEFORE: "task:delegate:before",
1233
+ DELEGATE_AFTER: "task:delegate:after",
1234
+ OPERATION_BEFORE_CREATE: "task:operation:before.create",
1235
+ OPERATION_AFTER_CREATE: "task:operation:after.create"
1236
+ };
1237
+ // packages/core/src/env/task/plugins/task-plugin.ts
1238
+ class TaskPlugin {
1239
+ config;
1240
+ constructor(config = {}) {
1241
+ this.config = { enabled: true, priority: 0, ...config };
1242
+ }
1243
+ getHookPoints() {
1244
+ return this.hooks.map((h) => h.point);
1245
+ }
1246
+ getPriorityForHook(hookPoint) {
1247
+ const hook = this.hooks.find((h) => h.point === hookPoint);
1248
+ return hook?.priority ?? this.config.priority ?? 0;
1249
+ }
1250
+ isEnabled() {
1251
+ return this.config.enabled ?? true;
1252
+ }
1253
+ setEnabled(enabled) {
1254
+ this.config.enabled = enabled;
1255
+ }
1256
+ }
1257
+ // packages/core/src/env/task/plugins/task-tag-plugin.ts
1258
+ init_logger();
1259
+
1260
+ // packages/core/src/env/task/plugins/workflow-extractor-agent.ts
1261
+ var WORKFLOW_EXTRACTOR_PROMPT = `\u4F60\u662F Workflow \u63D0\u53D6\u4E13\u5BB6\uFF0C\u8D1F\u8D23\u5C06\u81EA\u7136\u8BED\u8A00\u63CF\u8FF0\u8F6C\u6362\u4E3A\u7B26\u5408\u89C4\u8303\u7684 Workflow YAML\u3002
1262
+
1263
+ ## \u63D0\u53D6\u539F\u5219
1264
+
1265
+ 1. **\u4F18\u5148\u5177\u8C61\u8282\u70B9**\uFF1A\u4F18\u5148\u4F7F\u7528\u7279\u5B9A\u5DE5\u5177\u8282\u70B9\uFF08\u5982 read_file, write_file, grep, bash \u7B49\uFF09
1266
+ 2. **Fallback \u5230\u901A\u7528\u8282\u70B9**\uFF1A\u6CA1\u6709\u5BF9\u5E94\u5DE5\u5177\u65F6\uFF0C\u4F7F\u7528 agent/llm/bash \u8282\u70B9
1267
+ 3. **\u907F\u514D\u6761\u4EF6\u5206\u652F**\uFF1A\u4E0D\u63D0\u53D6\u5FAA\u73AF\u548C\u6761\u4EF6\u5224\u65AD\uFF0C\u4FDD\u6301\u7EBF\u6027\u6D41\u7A0B
1268
+ 4. **\u6CDB\u5316\u4F46\u53EF\u6267\u884C**\uFF1A\u6B65\u9AA4\u63CF\u8FF0\u53EF\u6CDB\u5316\uFF0C\u4F46\u8282\u70B9\u7C7B\u578B\u548C\u5DE5\u5177\u8981\u5177\u4F53
1269
+
1270
+ ## \u6784\u5EFA\u6D41\u7A0B
1271
+
1272
+ **\u91CD\u8981**\uFF1A\u6784\u5EFA\u7684 Workflow \u5FC5\u987B\u901A\u8FC7 \`roy workflow validate\` \u9A8C\u8BC1\u624D\u80FD\u8F93\u51FA\u3002
1273
+
1274
+ \`\`\`
1275
+ 1. \u7406\u89E3\u7528\u6237\u9700\u6C42
1276
+ 2. \u53C2\u8003 roy workflow nodes \u67E5\u770B\u53EF\u7528\u8282\u70B9\u7C7B\u578B
1277
+ 3. \u53C2\u8003 roy workflow get <name> \u67E5\u770B\u5DF2\u6709 workflow \u793A\u4F8B
1278
+ 4. \u751F\u6210 Workflow YAML
1279
+ 5. \u4F7F\u7528 roy workflow validate --yaml "<\u751F\u6210\u7684YAML>" \u9A8C\u8BC1
1280
+ 6. \u9A8C\u8BC1\u901A\u8FC7\u540E\u8F93\u51FA\u6700\u7EC8\u7ED3\u679C
1281
+ \`\`\`
1282
+
1283
+ ## \u9A8C\u8BC1\u68C0\u67E5\u6E05\u5355
1284
+
1285
+ \u5B8C\u6210 Workflow \u6784\u5EFA\u540E\uFF0C\u5FC5\u987B\u4F7F\u7528\u4EE5\u4E0B\u547D\u4EE4\u9A8C\u8BC1\uFF1A
1286
+
1287
+ \`\`\`bash
1288
+ roy workflow validate --yaml "<your-yaml>"
1289
+ \`\`\`
1290
+
1291
+ \u9A8C\u8BC1\u901A\u8FC7\u540E\uFF08\u65E0\u9519\u8BEF\u8F93\u51FA\uFF09\u624D\u8F93\u51FA\u6700\u7EC8\u7ED3\u679C\u3002\u9A8C\u8BC1\u5931\u8D25\u65F6\u6839\u636E\u9519\u8BEF\u4FE1\u606F\u4FEE\u6B63\u540E\u91CD\u65B0\u9A8C\u8BC1\u3002
1292
+
1293
+ ## \u53EF\u7528\u7684 Workflow \u8282\u70B9\u7C7B\u578B
1294
+
1295
+ \u4F7F\u7528\u4EE5\u4E0B\u547D\u4EE4\u67E5\u770B\u6240\u6709\u8282\u70B9\u7C7B\u578B\u7684\u8BE6\u7EC6\u914D\u7F6E\uFF1A
1296
+
1297
+ \`\`\`bash
1298
+ roy workflow nodes # \u5217\u51FA\u6240\u6709\u8282\u70B9\u7C7B\u578B
1299
+ roy workflow nodes <type> # \u67E5\u770B\u7279\u5B9A\u8282\u70B9\u8BE6\u60C5\uFF08\u5982 tool, agent, skill\uFF09
1300
+ \`\`\`
1301
+
1302
+ **\u652F\u6301\u7684\u8282\u70B9\u7C7B\u578B\uFF1A**
1303
+ - **tool**\uFF1A\u6267\u884C\u5DE5\u5177\uFF08bash, read-file, write-file, grep \u7B49\uFF09
1304
+ - **skill**\uFF1A\u8C03\u7528\u6280\u80FD
1305
+ - **agent**\uFF1AAI Agent
1306
+ - **workflow**\uFF1A\u5B50\u5DE5\u4F5C\u6D41
1307
+ - **condition**\uFF1A\u6761\u4EF6\u5224\u65AD
1308
+ - **merge**\uFF1A\u5408\u5E76\u7ED3\u679C
1309
+ - **decorator**\uFF1A\u88C5\u9970\u5668\u65B9\u6CD5
1310
+
1311
+ ## \u67E5\u770B\u5DF2\u6709 Workflow \u793A\u4F8B
1312
+
1313
+ \u4F7F\u7528\u4EE5\u4E0B\u547D\u4EE4\u67E5\u770B\u5DF2\u6709 workflow \u7684 YAML \u7ED3\u6784\uFF1A
1314
+
1315
+ \`\`\`bash
1316
+ roy workflow list # \u5217\u51FA\u6240\u6709 workflow
1317
+ roy workflow get <name> # \u83B7\u53D6\u6307\u5B9A workflow \u8BE6\u60C5\uFF08YAML \u683C\u5F0F\uFF09
1318
+ \`\`\`
1319
+
1320
+ ## \u8F93\u51FA\u8981\u6C42
1321
+
1322
+ \u9A8C\u8BC1\u901A\u8FC7\u540E\uFF0C\u8F93\u51FA\u7B26\u5408\u4EE5\u4E0B\u683C\u5F0F\u7684 YAML Workflow\uFF1A
1323
+
1324
+ \`\`\`yaml
1325
+ name: {\u6CDB\u5316\u7684\u4EFB\u52A1\u540D\u79F0}
1326
+ version: "1.0"
1327
+ description: {\u4E00\u53E5\u8BDD\u63CF\u8FF0}
1328
+ nodes:
1329
+ - id: node-1
1330
+ type: tool|skill|agent|workflow|condition|merge|decorator
1331
+ name: {\u8282\u70B9\u540D\u79F0}
1332
+ config:
1333
+ # \u6839\u636E\u7C7B\u578B\u914D\u7F6E\u5FC5\u586B\u5B57\u6BB5\uFF1A
1334
+ # tool: tool, input/args
1335
+ # skill: skill, input
1336
+ # agent: agent_type, prompt, options
1337
+ # workflow: workflow_name, input
1338
+ # condition: condition
1339
+ # merge: strategy, depends_on
1340
+ # decorator: _methodName, _instance
1341
+ depends_on: []
1342
+ outputs: []
1343
+ \`\`\`
1344
+
1345
+ ## \u9650\u5236
1346
+
1347
+ - \u81F3\u5C11 2 \u4E2A\u8282\u70B9\u624D\u6709\u610F\u4E49
1348
+ - \u4E0D\u8981\u751F\u6210\u6761\u4EF6\u8282\u70B9\uFF08if/else/switch\uFF09
1349
+ - \u4E0D\u8981\u751F\u6210\u5FAA\u73AF\u8282\u70B9\uFF08while/for\uFF09
1350
+ - \u6BCF\u4E2A\u8282\u70B9\u8981\u6709\u6E05\u6670\u7684\u540D\u79F0\u548C\u63CF\u8FF0
1351
+ - \u5FC5\u987B\u4E3A tool \u8282\u70B9\u6307\u5B9A tool \u540D\u79F0
1352
+ - \u5FC5\u987B\u4E3A agent \u8282\u70B9\u6307\u5B9A agent_type \u548C prompt`;
1353
+ function createWorkflowExtractorAgent() {
1354
+ return {
1355
+ type: "sub",
1356
+ name: "workflow-extractor",
1357
+ systemPrompt: WORKFLOW_EXTRACTOR_PROMPT,
1358
+ maxIterations: 10,
1359
+ filterHistory: false
1360
+ };
1361
+ }
1362
+ function formatExtractorInput(params) {
1363
+ const lines = [];
1364
+ lines.push("# \u4EFB\u52A1\u4FE1\u606F");
1365
+ lines.push(`- \u6807\u9898: ${params.task.title}`);
1366
+ if (params.task.description) {
1367
+ lines.push(`- \u63CF\u8FF0: ${params.task.description}`);
1368
+ }
1369
+ if (params.task.goals_and_expected_deliverables) {
1370
+ lines.push(`- \u76EE\u6807: ${params.task.goals_and_expected_deliverables}`);
1371
+ }
1372
+ lines.push("");
1373
+ if (params.operations.length > 0) {
1374
+ lines.push("# \u64CD\u4F5C\u8BB0\u5F55");
1375
+ for (const op of params.operations) {
1376
+ lines.push(`- [${op.actionType}] ${op.actionTitle}`);
1377
+ if (op.actionDescription) {
1378
+ lines.push(` ${op.actionDescription.slice(0, 200)}`);
1379
+ }
1380
+ }
1381
+ lines.push("");
1382
+ }
1383
+ lines.push("# Session \u6D88\u606F\u5386\u53F2");
1384
+ lines.push("(\u4EE5\u4E0B\u662F\u76F8\u5173\u7684\u5BF9\u8BDD\u5386\u53F2\uFF0C\u8BF7\u4ECE\u4E2D\u63D0\u53D6 Workflow)");
1385
+ for (const msg of params.messages.slice(-50)) {
1386
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
1387
+ const truncated = content.slice(0, 500);
1388
+ lines.push(`**${msg.role}**: ${truncated}${content.length > 500 ? "..." : ""}`);
1389
+ }
1390
+ lines.push("");
1391
+ lines.push("## \u4EFB\u52A1");
1392
+ lines.push("\u8BF7\u5206\u6790\u4EE5\u4E0A\u4FE1\u606F\uFF0C\u6784\u5EFA\u4E00\u4E2A\u53EF\u590D\u7528\u7684 Workflow\u3002");
1393
+ lines.push("\u4F7F\u7528\u8FED\u4EE3\u5F0F\u6D41\u7A0B\uFF1A\u751F\u6210 YAML \u2192 validate \u9A8C\u8BC1 \u2192 \u4FEE\u6B63\u9519\u8BEF \u2192 \u91CD\u590D\u76F4\u5230\u901A\u8FC7\u9A8C\u8BC1\u3002");
1394
+ return lines.join(`
1395
+ `);
1396
+ }
1397
+ function formatExtractorInputFromDescription(params) {
1398
+ const lines = [];
1399
+ lines.push("# Workflow \u63CF\u8FF0");
1400
+ lines.push(params.description);
1401
+ lines.push("");
1402
+ lines.push("## \u4EFB\u52A1");
1403
+ lines.push("\u8BF7\u6839\u636E\u4EE5\u4E0A\u63CF\u8FF0\uFF0C\u6784\u5EFA\u4E00\u4E2A\u53EF\u590D\u7528\u7684 Workflow\u3002");
1404
+ lines.push("\u4F7F\u7528\u8FED\u4EE3\u5F0F\u6D41\u7A0B\uFF1A\u751F\u6210 YAML \u2192 validate \u9A8C\u8BC1 \u2192 \u4FEE\u6B63\u9519\u8BEF \u2192 \u91CD\u590D\u76F4\u5230\u901A\u8FC7\u9A8C\u8BC1\u3002");
1405
+ return lines.join(`
1406
+ `);
1407
+ }
1408
+ async function parseExtractorOutput(output) {
1409
+ const yamlMatch = output.match(/```yaml\n?([\s\S]*?)\n?```/) || output.match(/```\n?([\s\S]*?)\n?```/) || output.match(/(\|[\s\S]*?)(?:\n\n|$)/);
1410
+ const yamlContent = yamlMatch?.[1] || output;
1411
+ try {
1412
+ const YAML = await import("yaml");
1413
+ const parsed = YAML.parse(yamlContent);
1414
+ if (!parsed.name || !parsed.nodes || !Array.isArray(parsed.nodes)) {
1415
+ return null;
1416
+ }
1417
+ if (parsed.nodes.length < 2) {
1418
+ return null;
1419
+ }
1420
+ parsed.version = parsed.version || "1.0";
1421
+ return parsed;
1422
+ } catch {
1423
+ return null;
1424
+ }
1425
+ }
1426
+
1427
+ // packages/core/src/env/task/plugins/task-tag-plugin.ts
1428
+ var logger2 = createLogger("task:plugin:tag");
1429
+
1430
+ class TaskTagPlugin extends TaskPlugin {
1431
+ name = "TaskTagPlugin";
1432
+ hooks = [
1433
+ { point: TaskHookPoints.DELEGATE_BEFORE, priority: 20 },
1434
+ { point: TaskHookPoints.OPERATION_AFTER_CREATE, priority: 10 }
1435
+ ];
1436
+ taskComponent = null;
1437
+ agentComponent = null;
1438
+ constructor(config = {}) {
1439
+ super({ enabled: true, priority: 0, ...config });
1440
+ }
1441
+ static getRequiredAgents() {
1442
+ return [createWorkflowExtractorAgent()];
1443
+ }
1444
+ setComponents(_llmComponent, taskComponent) {
1445
+ this.taskComponent = taskComponent;
1446
+ if (taskComponent?.env) {
1447
+ this.agentComponent = taskComponent.env.getComponent("agent");
1448
+ }
1449
+ }
1450
+ async execute(ctx) {
1451
+ if (!this.config.enabled)
1452
+ return;
1453
+ switch (ctx.hookPoint) {
1454
+ case TaskHookPoints.DELEGATE_BEFORE:
1455
+ await this.onDelegateBefore(ctx);
1456
+ break;
1457
+ case TaskHookPoints.OPERATION_AFTER_CREATE:
1458
+ await this.onOperationAfterCreate(ctx);
1459
+ break;
1460
+ }
1461
+ }
1462
+ async onDelegateBefore(ctx) {
1463
+ const { taskId, tagService, prompt } = ctx.data;
1464
+ if (!taskId || !this.taskComponent) {
1465
+ return;
1466
+ }
1467
+ try {
1468
+ const currentTask = await this.taskComponent.getTask(taskId);
1469
+ if (!currentTask)
1470
+ return;
1471
+ const keywords = this.extractKeywords(currentTask);
1472
+ if (keywords.length === 0)
1473
+ return;
1474
+ const tagServiceForSearch = tagService;
1475
+ const similarTasks = await tagServiceForSearch?.findSimilarTasksByKeywords?.(keywords, {
1476
+ limit: 5,
1477
+ excludeTaskId: taskId
1478
+ }) ?? [];
1479
+ if (similarTasks.length === 0)
1480
+ return;
1481
+ const hint = this.formatSimilarTasks(similarTasks);
1482
+ ctx.data.prompt = `${hint}
1483
+
1484
+ ---
1485
+
1486
+ ## \u7528\u6237\u6307\u4EE4
1487
+
1488
+ ${prompt}`;
1489
+ logger2.info(`[TaskTagPlugin] Injected ${similarTasks.length} similar tasks`);
1490
+ } catch (error) {
1491
+ logger2.warn(`[TaskTagPlugin] Similar tasks injection failed: ${error}`);
1492
+ }
1493
+ }
1494
+ extractKeywords(task) {
1495
+ const keywords = [];
1496
+ if (task.tags?.length) {
1497
+ keywords.push(...task.tags);
1498
+ }
1499
+ if (task.title) {
1500
+ const words = task.title.split(/[\s\-_,\uFF0C\u3002\u3001#]+/).filter((w) => w.length > 2 && !/^\d+$/.test(w)).slice(0, 5);
1501
+ keywords.push(...words);
1502
+ }
1503
+ return keywords;
1504
+ }
1505
+ formatSimilarTasks(tasks) {
1506
+ const lines = [
1507
+ "## \uD83D\uDD0D \u7C7B\u4F3C\u4EFB\u52A1\u53C2\u8003",
1508
+ "",
1509
+ "_\u63D0\u793A\uFF1A\u53EF\u901A\u8FC7 `task_get <id>` \u83B7\u53D6\u8BE6\u60C5\uFF0C`task_operation_list <id>` \u83B7\u53D6\u64CD\u4F5C\u8BB0\u5F55_",
1510
+ ""
1511
+ ];
1512
+ for (const task of tasks) {
1513
+ lines.push(`### Task #${task.id}`);
1514
+ lines.push(`**Title**: ${task.title}`);
1515
+ if (task.description) {
1516
+ const desc = task.description.slice(0, 100);
1517
+ lines.push(`**Description**: ${desc}${task.description.length > 100 ? "..." : ""}`);
1518
+ }
1519
+ if (task.goals_and_expected_deliverables) {
1520
+ const goal = task.goals_and_expected_deliverables.slice(0, 100);
1521
+ lines.push(`**Goal**: ${goal}${task.goals_and_expected_deliverables.length > 100 ? "..." : ""}`);
1522
+ }
1523
+ lines.push("");
1524
+ }
1525
+ return lines.join(`
1526
+ `);
1527
+ }
1528
+ async onOperationAfterCreate(ctx) {
1529
+ const data = ctx.data;
1530
+ const operation = data?.operation ?? data?.data?.operation;
1531
+ if (!operation || operation?.actionType !== "completed")
1532
+ return;
1533
+ await this.extractWorkflow(operation.taskId, operation.sessionId);
1534
+ }
1535
+ async extractWorkflow(taskId, sessionId) {
1536
+ try {
1537
+ const task = await this.taskComponent?.getTask(taskId);
1538
+ if (!task)
1539
+ return;
1540
+ const operations = await this.taskComponent?.listOperations({ taskId }) ?? [];
1541
+ const allSessionIds = [...new Set([sessionId, ...operations.map((op) => op.sessionId).filter(Boolean)])];
1542
+ const sessionComponent = this.taskComponent?.env?.getComponent("session");
1543
+ const allMessages = [];
1544
+ for (const sid of allSessionIds) {
1545
+ try {
1546
+ const ctx = await sessionComponent?.getContext(sid, { fullHistory: false, minUserMessages: 200 });
1547
+ if (ctx?.messages)
1548
+ allMessages.push(...ctx.messages);
1549
+ } catch {}
1550
+ }
1551
+ if (!this.agentComponent)
1552
+ return;
1553
+ const input = formatExtractorInput({ task, operations, messages: allMessages });
1554
+ const result = await this.agentComponent.run("workflow-extractor", input);
1555
+ const workflowDef = await parseExtractorOutput(result.finalText || "");
1556
+ if (!workflowDef)
1557
+ return;
1558
+ const workflowRepo = await this.getWorkflowRepository();
1559
+ if (!workflowRepo)
1560
+ return;
1561
+ let version = workflowDef.version || "1.0";
1562
+ const existingWf = workflowRepo.getByName(workflowDef.name);
1563
+ if (existingWf) {
1564
+ const parts = existingWf.version?.split(".") ?? ["1", "0"];
1565
+ version = `${parts[0]}.${parseInt(parts[1] || "0") + 1}`;
1566
+ }
1567
+ const workflow = workflowRepo.create({
1568
+ name: workflowDef.name,
1569
+ version,
1570
+ description: workflowDef.description,
1571
+ definition: workflowDef,
1572
+ config: workflowDef.config || {},
1573
+ metadata: { author: "workflow-extractor", created_at: new Date().toISOString() },
1574
+ tags: [`task:${taskId}`]
1575
+ });
1576
+ await this.taskComponent?.createOperation({
1577
+ taskId,
1578
+ sessionId,
1579
+ actionType: "workflow_extracted",
1580
+ actionTitle: `Workflow extracted: ${workflow.name}`,
1581
+ actionDescription: workflow.id
1582
+ });
1583
+ logger2.info(`Workflow extracted: ${workflow.id}`);
1584
+ } catch (error) {
1585
+ logger2.warn(`Workflow extraction failed: ${error}`);
1586
+ }
1587
+ }
1588
+ async getWorkflowRepository() {
1589
+ const workflowComponent = this.taskComponent?.env?.getComponent("workflow");
1590
+ if (workflowComponent?.workflowService?.workflowRepository) {
1591
+ return workflowComponent.workflowService.workflowRepository;
1592
+ }
1593
+ if (!this._workflowRepo) {
1594
+ try {
1595
+ const sqlite = await Promise.resolve().then(() => (init_sqlite(), exports_sqlite));
1596
+ this.ensureDataDir();
1597
+ const db = sqlite.getDatabase();
1598
+ sqlite.initializeTables();
1599
+ const { WorkflowRepository: WorkflowRepository2 } = await Promise.resolve().then(() => (init_workflow_repo(), exports_workflow_repo));
1600
+ this._workflowRepo = new WorkflowRepository2(db);
1601
+ return this._workflowRepo;
1602
+ } catch {
1603
+ return null;
1604
+ }
1605
+ }
1606
+ return this._workflowRepo;
1607
+ }
1608
+ ensureDataDir() {
1609
+ const { join: join3 } = __require("path");
1610
+ const { mkdirSync: mkdirSync2, existsSync: existsSync2 } = __require("fs");
1611
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1612
+ const dataDir = join3(home, ".local", "share", "roy-agent");
1613
+ if (!existsSync2(dataDir))
1614
+ mkdirSync2(dataDir, { recursive: true });
1615
+ }
1616
+ _workflowRepo = null;
1617
+ }
1618
+ export {
1619
+ parseExtractorOutput,
1620
+ formatExtractorInputFromDescription,
1621
+ formatExtractorInput,
1622
+ createWorkflowExtractorAgent,
1623
+ WORKFLOW_EXTRACTOR_PROMPT,
1624
+ TaskTagPlugin,
1625
+ TaskPlugin
1626
+ };