@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,1151 @@
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/opentelemetry/propagation.ts
53
+ function padLeft(str, length) {
54
+ return str.padStart(length, "0");
55
+ }
56
+ function isValidHex(str) {
57
+ return /^[0-9a-f]+$/i.test(str);
58
+ }
59
+ function serialize(context) {
60
+ const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);
61
+ const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
62
+ const parts = [
63
+ TRACE_CONTEXT_VERSION,
64
+ traceId,
65
+ spanId,
66
+ TRACE_FLAGS_SAMPLED
67
+ ];
68
+ return parts.join("-");
69
+ }
70
+ function parse(traceparent) {
71
+ if (!traceparent || typeof traceparent !== "string") {
72
+ return;
73
+ }
74
+ const trimmed = traceparent.trim();
75
+ const parts = trimmed.split("-");
76
+ if (parts.length !== 4) {
77
+ return;
78
+ }
79
+ const [version, traceId, senderSpanId, flags] = parts;
80
+ if (version !== TRACE_CONTEXT_VERSION) {
81
+ if (version > TRACE_CONTEXT_VERSION) {
82
+ return;
83
+ }
84
+ }
85
+ if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
86
+ return;
87
+ }
88
+ if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
89
+ return;
90
+ }
91
+ if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
92
+ return;
93
+ }
94
+ return {
95
+ traceId: traceId.toLowerCase(),
96
+ spanId: senderSpanId.toLowerCase()
97
+ };
98
+ }
99
+ 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;
100
+ var init_propagation = __esm(() => {
101
+ propagation = {
102
+ inject(carrier, context) {
103
+ carrier[TRACEPARENT_HEADER] = serialize(context);
104
+ },
105
+ extract(carrier) {
106
+ const traceparent = carrier[TRACEPARENT_HEADER];
107
+ if (!traceparent) {
108
+ return;
109
+ }
110
+ return parse(traceparent);
111
+ },
112
+ getTraceparentHeader() {
113
+ return TRACEPARENT_HEADER;
114
+ }
115
+ };
116
+ });
117
+
118
+ // packages/core/src/env/log-trace/span-storage.ts
119
+ var exports_span_storage = {};
120
+ __export(exports_span_storage, {
121
+ SQLiteSpanStorage: () => SQLiteSpanStorage
122
+ });
123
+
124
+ class SQLiteSpanStorage {
125
+ db = null;
126
+ dbPath;
127
+ initialized = false;
128
+ constructor(dbPath) {
129
+ if (!dbPath) {
130
+ throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
131
+ }
132
+ if (dbPath === ":memory:") {
133
+ throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
134
+ }
135
+ this.dbPath = dbPath;
136
+ }
137
+ async initialize() {
138
+ if (this.initialized)
139
+ return;
140
+ const { Database } = __require("bun:sqlite");
141
+ const fs = __require("fs");
142
+ const path = __require("path");
143
+ const dir = path.dirname(this.dbPath);
144
+ if (!fs.existsSync(dir)) {
145
+ fs.mkdirSync(dir, { recursive: true });
146
+ }
147
+ this.db = new Database(this.dbPath);
148
+ this.db.run("PRAGMA journal_mode=WAL");
149
+ this.db.run("PRAGMA busy_timeout=5000");
150
+ this.db.run("PRAGMA synchronous=NORMAL");
151
+ this.db.run(`
152
+ CREATE TABLE IF NOT EXISTS span (
153
+ span_id TEXT PRIMARY KEY,
154
+ trace_id TEXT NOT NULL,
155
+ parent_span_id TEXT,
156
+ name TEXT NOT NULL,
157
+ kind TEXT NOT NULL,
158
+ status TEXT NOT NULL,
159
+ start_time INTEGER NOT NULL,
160
+ end_time INTEGER,
161
+ attributes TEXT,
162
+ result TEXT,
163
+ error TEXT,
164
+ time_created INTEGER NOT NULL
165
+ )
166
+ `);
167
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
168
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
169
+ this.initialized = true;
170
+ }
171
+ save(span) {
172
+ if (!this.db)
173
+ return;
174
+ const stmt = this.db.prepare(`
175
+ INSERT OR REPLACE INTO span
176
+ (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
177
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
178
+ `);
179
+ const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
180
+ 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());
181
+ }
182
+ saveBatch(spans) {
183
+ for (const span of spans) {
184
+ this.save(span);
185
+ }
186
+ }
187
+ findByTraceId(traceId) {
188
+ if (!this.db)
189
+ return [];
190
+ const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
191
+ return this.buildTree(rows.map(this.rowToSpan));
192
+ }
193
+ findBySpanId(spanId) {
194
+ if (!this.db)
195
+ return;
196
+ const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
197
+ return row ? this.rowToSpan(row) : undefined;
198
+ }
199
+ listTraces(limit = 10) {
200
+ if (!this.db)
201
+ return [];
202
+ const rows = this.db.prepare(`
203
+ SELECT trace_id,
204
+ MIN(start_time) as start_time,
205
+ MAX(end_time) as end_time,
206
+ COUNT(*) as span_count
207
+ FROM span
208
+ GROUP BY trace_id
209
+ ORDER BY start_time DESC
210
+ LIMIT ?
211
+ `).all(limit);
212
+ return rows.map((row) => ({
213
+ traceId: row.trace_id,
214
+ rootSpanName: "unknown",
215
+ startTime: row.start_time,
216
+ endTime: row.end_time,
217
+ duration: row.end_time - row.start_time,
218
+ spanCount: row.span_count,
219
+ status: "ok"
220
+ }));
221
+ }
222
+ deleteByTraceId(traceId) {
223
+ if (this.db) {
224
+ this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
225
+ }
226
+ }
227
+ close() {
228
+ if (this.db) {
229
+ this.db.close();
230
+ this.db = null;
231
+ }
232
+ }
233
+ rowToSpan(row) {
234
+ return {
235
+ traceId: row.trace_id,
236
+ spanId: row.span_id,
237
+ parentSpanId: row.parent_span_id,
238
+ name: row.name,
239
+ kind: row.kind,
240
+ status: row.status,
241
+ startTime: row.start_time,
242
+ endTime: row.end_time,
243
+ attributes: row.attributes ? JSON.parse(row.attributes) : {},
244
+ result: row.result || undefined,
245
+ error: row.error || undefined
246
+ };
247
+ }
248
+ buildTree(spans) {
249
+ const spanMap = new Map;
250
+ const roots = [];
251
+ for (const span of spans) {
252
+ spanMap.set(span.spanId, { ...span, children: [] });
253
+ }
254
+ for (const span of spanMap.values()) {
255
+ if (span.parentSpanId) {
256
+ const parent = spanMap.get(span.parentSpanId);
257
+ if (parent) {
258
+ parent.children.push(span);
259
+ } else {
260
+ roots.push(span);
261
+ }
262
+ } else {
263
+ roots.push(span);
264
+ }
265
+ }
266
+ return roots;
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/tool/built-in/bash.ts
561
+ import { z } from "zod";
562
+ import { exec } from "child_process";
563
+ import { promisify } from "util";
564
+ function getCurrentSpanContext() {
565
+ try {
566
+ const { getTracerProvider: getTracerProvider2 } = (init_tracer_provider(), __toCommonJS(exports_tracer_provider));
567
+ const provider = getTracerProvider2();
568
+ if (!provider.isInitialized()) {
569
+ throw new Error("Provider not initialized");
570
+ }
571
+ const tracer = provider.getTracer("roy-tracer");
572
+ const ctx = tracer.getCurrentContext();
573
+ if (ctx && ctx.traceId && ctx.spanId) {
574
+ return ctx;
575
+ }
576
+ } catch {}
577
+ return;
578
+ }
579
+ function getCurrentTraceId() {
580
+ const ctx = getCurrentSpanContext();
581
+ if (ctx) {
582
+ return ctx.traceId;
583
+ }
584
+ return process.env.TRACE_ID;
585
+ }
586
+ var execAsync, bashTool;
587
+ var init_bash = __esm(() => {
588
+ init_propagation();
589
+ execAsync = promisify(exec);
590
+ bashTool = {
591
+ name: "bash",
592
+ description: "Execute shell commands in the terminal. Use this to run system commands, scripts, or interact with the file system.",
593
+ parameters: z.object({
594
+ command: z.string().describe("The shell command to execute"),
595
+ workdir: z.string().optional().describe("Working directory for the command"),
596
+ timeout: z.number().int().positive().optional().describe("Timeout in milliseconds"),
597
+ env: z.record(z.string()).optional().describe("Additional environment variables")
598
+ }),
599
+ sandbox: {
600
+ enabled: true,
601
+ config: {
602
+ filesystem: {
603
+ denyRead: ["/etc/shadow", "/etc/sudoers", "/etc/sudoers.d/*"],
604
+ denyWrite: ["/etc", "/usr/bin", "/usr/sbin", "/bin", "/sbin"]
605
+ }
606
+ }
607
+ },
608
+ permission: {
609
+ requireConfirmation: true,
610
+ level: "dangerous"
611
+ },
612
+ metadata: {
613
+ category: "system",
614
+ tags: ["shell", "command", "terminal", "exec"],
615
+ version: "1.2.0"
616
+ },
617
+ execute: async (args, ctx) => {
618
+ const startTime = Date.now();
619
+ const { command, workdir, timeout = 60000, env } = args;
620
+ const currentSpanCtx = getCurrentSpanContext();
621
+ const traceId = currentSpanCtx?.traceId || getCurrentTraceId();
622
+ const options = {
623
+ timeout
624
+ };
625
+ if (workdir || ctx.workdir) {
626
+ options.cwd = workdir || ctx.workdir;
627
+ }
628
+ const childEnv = {};
629
+ for (const [key, value] of Object.entries(process.env)) {
630
+ if (value !== undefined) {
631
+ childEnv[key] = value;
632
+ }
633
+ }
634
+ if (currentSpanCtx) {
635
+ const carrier = {};
636
+ propagation.inject(carrier, currentSpanCtx);
637
+ if (carrier["TRACEPARENT"]) {
638
+ childEnv["TRACEPARENT"] = carrier["TRACEPARENT"];
639
+ }
640
+ childEnv["TRACE_ID"] = currentSpanCtx.traceId;
641
+ childEnv["PARENT_SPAN_ID"] = currentSpanCtx.spanId;
642
+ } else if (traceId) {
643
+ const spanId2 = Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
644
+ childEnv["TRACEPARENT"] = `00-${traceId}-${spanId2}-01`;
645
+ childEnv["TRACE_ID"] = traceId;
646
+ }
647
+ if (env) {
648
+ Object.assign(childEnv, env);
649
+ }
650
+ options.env = childEnv;
651
+ let otelSpan = undefined;
652
+ try {
653
+ const { getTracerProvider: getTracerProvider2 } = (init_tracer_provider(), __toCommonJS(exports_tracer_provider));
654
+ const provider = getTracerProvider2();
655
+ const tracer = provider.getTracer("roy-tracer");
656
+ otelSpan = tracer.startSpan(`bash: ${command.slice(0, 50)}${command.length > 50 ? "..." : ""}`, {
657
+ attributes: {
658
+ "bash.command": command.slice(0, 200),
659
+ "bash.workdir": workdir || ctx.workdir || "",
660
+ "bash.timeout": timeout
661
+ }
662
+ });
663
+ } catch {}
664
+ const spanId = otelSpan?.spanContext?.spanId;
665
+ try {
666
+ const { stdout, stderr } = await execAsync(command, options);
667
+ if (otelSpan) {
668
+ otelSpan.end({ stdout, stderr });
669
+ }
670
+ return {
671
+ success: true,
672
+ output: stdout || "(no output)",
673
+ metadata: {
674
+ execution_time_ms: Date.now() - startTime,
675
+ stdout,
676
+ stderr,
677
+ exit_code: 0,
678
+ trace_id: traceId,
679
+ parent_span_id: currentSpanCtx?.spanId,
680
+ span_id: spanId
681
+ }
682
+ };
683
+ } catch (error) {
684
+ const exitCode = error.code || 1;
685
+ const stdout = error.stdout || "";
686
+ const stderr = error.stderr || error.message;
687
+ const execError = new Error(stderr);
688
+ execError.name = "BashExecutionError";
689
+ if (otelSpan) {
690
+ otelSpan.end(undefined, execError);
691
+ }
692
+ return {
693
+ success: exitCode === 0,
694
+ output: stdout || "(no output)",
695
+ error: stderr,
696
+ metadata: {
697
+ execution_time_ms: Date.now() - startTime,
698
+ stdout,
699
+ stderr,
700
+ exit_code: exitCode,
701
+ trace_id: traceId,
702
+ parent_span_id: currentSpanCtx?.spanId,
703
+ span_id: spanId
704
+ }
705
+ };
706
+ }
707
+ }
708
+ };
709
+ });
710
+
711
+ // packages/core/src/env/tool/built-in/echo.ts
712
+ var echoTool;
713
+ var init_echo = __esm(() => {
714
+ echoTool = {
715
+ name: "echo",
716
+ description: "Echo a message to the console. Useful for logging in workflows.",
717
+ parameters: {
718
+ name: "message",
719
+ schema: {
720
+ type: "string",
721
+ description: "The message to echo"
722
+ }
723
+ },
724
+ execute: async (args, _ctx) => {
725
+ const message = args?.message || "(no message)";
726
+ return {
727
+ success: true,
728
+ output: message,
729
+ metadata: {
730
+ execution_time_ms: 0
731
+ }
732
+ };
733
+ }
734
+ };
735
+ });
736
+
737
+ // packages/core/src/env/tool/built-in/glob.ts
738
+ import { z as z2 } from "zod";
739
+ import { glob as globAsync } from "glob";
740
+ var globTool;
741
+ var init_glob = __esm(() => {
742
+ globTool = {
743
+ name: "glob",
744
+ description: "Search for files matching a glob pattern. Use this to find files by name patterns like **/*.ts or **/*.md.",
745
+ parameters: z2.object({
746
+ pattern: z2.string().describe("Glob pattern to match (e.g., **/*.ts, **/*.md)"),
747
+ cwd: z2.string().optional().describe("Working directory to search in"),
748
+ maxResults: z2.number().int().positive().optional().describe("Maximum number of results to return"),
749
+ ignore: z2.array(z2.string()).optional().describe("Patterns to ignore")
750
+ }),
751
+ sandbox: {
752
+ enabled: true
753
+ },
754
+ metadata: {
755
+ category: "file",
756
+ tags: ["search", "file", "glob", "pattern"],
757
+ version: "1.0.0"
758
+ },
759
+ execute: async (args, ctx) => {
760
+ const startTime = Date.now();
761
+ const { pattern, cwd, maxResults = 100, ignore } = args;
762
+ const searchDir = cwd || ctx.workdir || process.cwd();
763
+ try {
764
+ const files = await globAsync(pattern, {
765
+ cwd: searchDir,
766
+ ignore: ignore || ["**/node_modules/**", "**/.git/**"],
767
+ maxDepth: 20
768
+ });
769
+ const limitedFiles = files.slice(0, maxResults);
770
+ const output = limitedFiles.join(`
771
+ `);
772
+ return {
773
+ success: true,
774
+ output,
775
+ metadata: {
776
+ execution_time_ms: Date.now() - startTime,
777
+ output_size: output.length,
778
+ total_matches: files.length,
779
+ returned_matches: limitedFiles.length
780
+ }
781
+ };
782
+ } catch (error) {
783
+ return {
784
+ success: false,
785
+ output: "",
786
+ error: error instanceof Error ? error.message : String(error),
787
+ metadata: {
788
+ execution_time_ms: Date.now() - startTime
789
+ }
790
+ };
791
+ }
792
+ }
793
+ };
794
+ });
795
+
796
+ // packages/core/src/env/tool/built-in/read-file.ts
797
+ import { z as z3 } from "zod";
798
+ import { readFile } from "fs/promises";
799
+ var readFileTool;
800
+ var init_read_file = __esm(() => {
801
+ readFileTool = {
802
+ name: "read_file",
803
+ description: "Read the contents of a file. Use this to read source code, configuration files, or any text files.",
804
+ parameters: z3.object({
805
+ path: z3.string().describe("The file path to read"),
806
+ offset: z3.number().int().nonnegative().optional().describe("Line offset to start reading from"),
807
+ limit: z3.number().int().positive().optional().describe("Number of lines to read"),
808
+ encoding: z3.enum(["utf-8", "base64"]).default("utf-8").optional().describe("File encoding")
809
+ }),
810
+ sandbox: {
811
+ enabled: true,
812
+ config: {
813
+ filesystem: {
814
+ denyRead: ["/etc/shadow", "/etc/sudoers", "/root/.ssh"]
815
+ }
816
+ }
817
+ },
818
+ permission: {
819
+ level: "safe"
820
+ },
821
+ metadata: {
822
+ category: "file",
823
+ tags: ["read", "file", "io"],
824
+ version: "1.0.0"
825
+ },
826
+ execute: async (args, ctx) => {
827
+ const startTime = Date.now();
828
+ const { path: filePath, offset, limit, encoding = "utf-8" } = args;
829
+ try {
830
+ const content = await readFile(filePath, encoding);
831
+ let output;
832
+ const contentBuffer = content;
833
+ const contentStr = typeof contentBuffer === "string" ? contentBuffer : contentBuffer.toString(encoding);
834
+ if (offset !== undefined || limit !== undefined) {
835
+ const lines = contentStr.split(`
836
+ `);
837
+ const startLine = offset || 0;
838
+ const endLine = limit ? startLine + limit : lines.length;
839
+ output = lines.slice(startLine, endLine).join(`
840
+ `);
841
+ } else {
842
+ output = contentStr;
843
+ }
844
+ return {
845
+ success: true,
846
+ output,
847
+ metadata: {
848
+ execution_time_ms: Date.now() - startTime,
849
+ output_size: output.length,
850
+ file_path: filePath
851
+ }
852
+ };
853
+ } catch (error) {
854
+ return {
855
+ success: false,
856
+ output: "",
857
+ error: error instanceof Error ? error.message : String(error),
858
+ metadata: {
859
+ execution_time_ms: Date.now() - startTime
860
+ }
861
+ };
862
+ }
863
+ }
864
+ };
865
+ });
866
+
867
+ // packages/core/src/env/tool/built-in/write-file.ts
868
+ import { z as z4 } from "zod";
869
+ import { writeFile, mkdir } from "fs/promises";
870
+ import { dirname } from "path";
871
+ var writeFileTool;
872
+ var init_write_file = __esm(() => {
873
+ writeFileTool = {
874
+ name: "write_file",
875
+ description: "Write content to a file. Use this to create new files or overwrite existing ones.",
876
+ parameters: z4.object({
877
+ path: z4.string().describe("The file path to write to"),
878
+ content: z4.string().describe("The content to write"),
879
+ createDirs: z4.boolean().default(false).optional().describe("Create parent directories if they don't exist"),
880
+ append: z4.boolean().default(false).optional().describe("Append to file instead of overwrite")
881
+ }),
882
+ sandbox: {
883
+ enabled: true,
884
+ config: {
885
+ filesystem: {
886
+ denyWrite: ["/etc", "/usr", "/bin", "/sbin", "/boot", "/sys"]
887
+ }
888
+ }
889
+ },
890
+ permission: {
891
+ requireConfirmation: true,
892
+ level: "dangerous"
893
+ },
894
+ metadata: {
895
+ category: "file",
896
+ tags: ["write", "file", "io", "create"],
897
+ version: "1.0.0"
898
+ },
899
+ execute: async (args, ctx) => {
900
+ const startTime = Date.now();
901
+ const { path: filePath, content, createDirs = false, append = false } = args;
902
+ try {
903
+ if (createDirs) {
904
+ await mkdir(dirname(filePath), { recursive: true });
905
+ }
906
+ const flags = append ? "a" : "w";
907
+ await writeFile(filePath, content, { flag: flags });
908
+ return {
909
+ success: true,
910
+ output: append ? `Content appended to: ${filePath}` : `File written: ${filePath}`,
911
+ metadata: {
912
+ execution_time_ms: Date.now() - startTime,
913
+ output_size: content.length,
914
+ file_path: filePath
915
+ }
916
+ };
917
+ } catch (error) {
918
+ return {
919
+ success: false,
920
+ output: "",
921
+ error: error instanceof Error ? error.message : String(error),
922
+ metadata: {
923
+ execution_time_ms: Date.now() - startTime
924
+ }
925
+ };
926
+ }
927
+ }
928
+ };
929
+ });
930
+
931
+ // packages/core/src/env/tool/built-in/edit-file.ts
932
+ import { z as z5 } from "zod";
933
+ import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
934
+ function escapeRegExp(string) {
935
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
936
+ }
937
+ var editFileTool;
938
+ var init_edit_file = __esm(() => {
939
+ editFileTool = {
940
+ name: "edit_file",
941
+ description: "Edit a file by replacing specific text. Use this to make targeted changes to files by specifying what to find and what to replace.",
942
+ parameters: z5.object({
943
+ path: z5.string().describe("The file path to edit"),
944
+ oldString: z5.string().describe("The text to find and replace"),
945
+ newString: z5.string().describe("The replacement text"),
946
+ replaceAll: z5.boolean().default(false).optional().describe("Replace all occurrences instead of just the first")
947
+ }),
948
+ sandbox: {
949
+ enabled: true,
950
+ config: {
951
+ filesystem: {
952
+ denyWrite: ["/etc", "/usr/bin", "/usr/sbin", "/bin", "/sbin"]
953
+ }
954
+ }
955
+ },
956
+ permission: {
957
+ requireConfirmation: true,
958
+ level: "dangerous"
959
+ },
960
+ metadata: {
961
+ category: "file",
962
+ tags: ["edit", "file", "replace", "modify"],
963
+ version: "1.0.0"
964
+ },
965
+ execute: async (args, ctx) => {
966
+ const startTime = Date.now();
967
+ const { path: filePath, oldString, newString, replaceAll = false } = args;
968
+ try {
969
+ const content = await readFile2(filePath, "utf-8");
970
+ const searchPattern = replaceAll ? new RegExp(escapeRegExp(oldString), "g") : new RegExp(escapeRegExp(oldString));
971
+ if (!searchPattern.test(content)) {
972
+ return {
973
+ success: false,
974
+ output: "",
975
+ error: `Could not find "${oldString}" in file ${filePath}`,
976
+ metadata: {
977
+ execution_time_ms: Date.now() - startTime
978
+ }
979
+ };
980
+ }
981
+ const newContent = replaceAll ? content.replace(new RegExp(escapeRegExp(oldString), "g"), newString) : content.replace(oldString, newString);
982
+ await writeFile2(filePath, newContent, "utf-8");
983
+ return {
984
+ success: true,
985
+ output: replaceAll ? `Replaced all occurrences in: ${filePath}` : `Replaced text in: ${filePath}`,
986
+ metadata: {
987
+ execution_time_ms: Date.now() - startTime,
988
+ file_path: filePath
989
+ }
990
+ };
991
+ } catch (error) {
992
+ return {
993
+ success: false,
994
+ output: "",
995
+ error: error instanceof Error ? error.message : String(error),
996
+ metadata: {
997
+ execution_time_ms: Date.now() - startTime
998
+ }
999
+ };
1000
+ }
1001
+ }
1002
+ };
1003
+ });
1004
+
1005
+ // packages/core/src/env/tool/built-in/grep.ts
1006
+ import { z as z6 } from "zod";
1007
+ import { readFile as readFile3 } from "fs/promises";
1008
+ import { glob as globAsync2 } from "glob";
1009
+ var grepTool;
1010
+ var init_grep = __esm(() => {
1011
+ grepTool = {
1012
+ name: "grep",
1013
+ description: "Search for text patterns in files. Use this to find specific strings, code patterns, or content across multiple files.",
1014
+ parameters: z6.object({
1015
+ pattern: z6.string().describe("The pattern to search for"),
1016
+ path: z6.string().optional().describe("File or directory path to search in"),
1017
+ include: z6.string().optional().describe("Glob pattern for files to include (e.g., *.ts, *.js)"),
1018
+ caseSensitive: z6.boolean().default(true).optional().describe("Whether the search should be case sensitive"),
1019
+ maxResults: z6.number().int().positive().default(50).optional().describe("Maximum number of results"),
1020
+ showLineNumbers: z6.boolean().default(true).optional().describe("Show line numbers in results")
1021
+ }),
1022
+ sandbox: {
1023
+ enabled: true
1024
+ },
1025
+ metadata: {
1026
+ category: "file",
1027
+ tags: ["search", "grep", "find", "pattern"],
1028
+ version: "1.0.0"
1029
+ },
1030
+ execute: async (args, ctx) => {
1031
+ const startTime = Date.now();
1032
+ const {
1033
+ pattern,
1034
+ path: searchPath,
1035
+ include,
1036
+ caseSensitive = true,
1037
+ maxResults = 50,
1038
+ showLineNumbers = true
1039
+ } = args;
1040
+ const basePath = searchPath || ctx.workdir || process.cwd();
1041
+ try {
1042
+ let files = [];
1043
+ if (include) {
1044
+ files = await globAsync2(include, {
1045
+ cwd: basePath,
1046
+ ignore: ["**/node_modules/**", "**/.git/**"],
1047
+ maxDepth: 10
1048
+ });
1049
+ } else {
1050
+ files = await globAsync2("**/*", {
1051
+ cwd: basePath,
1052
+ ignore: ["**/node_modules/**", "**/.git/**"],
1053
+ maxDepth: 10
1054
+ });
1055
+ }
1056
+ const results = [];
1057
+ const regexFlags = caseSensitive ? "" : "i";
1058
+ const regex = new RegExp(pattern, regexFlags);
1059
+ for (const file of files) {
1060
+ if (results.length >= maxResults)
1061
+ break;
1062
+ try {
1063
+ const content = await readFile3(`${basePath}/${file}`, "utf-8");
1064
+ const lines = content.split(`
1065
+ `);
1066
+ for (let i = 0;i < lines.length; i++) {
1067
+ if (regex.test(lines[i])) {
1068
+ const lineNum = showLineNumbers ? `${i + 1}:` : "";
1069
+ results.push(`${file}:${lineNum}${lines[i]}`);
1070
+ if (results.length >= maxResults)
1071
+ break;
1072
+ }
1073
+ }
1074
+ } catch {}
1075
+ }
1076
+ const output = results.join(`
1077
+ `) || "(no matches found)";
1078
+ return {
1079
+ success: true,
1080
+ output,
1081
+ metadata: {
1082
+ execution_time_ms: Date.now() - startTime,
1083
+ output_size: output.length,
1084
+ matches_count: results.length,
1085
+ files_searched: files.length
1086
+ }
1087
+ };
1088
+ } catch (error) {
1089
+ return {
1090
+ success: false,
1091
+ output: "",
1092
+ error: error instanceof Error ? error.message : String(error),
1093
+ metadata: {
1094
+ execution_time_ms: Date.now() - startTime
1095
+ }
1096
+ };
1097
+ }
1098
+ }
1099
+ };
1100
+ });
1101
+
1102
+ // packages/core/src/env/tool/built-in/index.ts
1103
+ var exports_built_in = {};
1104
+ __export(exports_built_in, {
1105
+ writeFileTool: () => writeFileTool,
1106
+ readFileTool: () => readFileTool,
1107
+ grepTool: () => grepTool,
1108
+ globTool: () => globTool,
1109
+ getBuiltInTool: () => getBuiltInTool,
1110
+ getAllBuiltInTools: () => getAllBuiltInTools,
1111
+ editFileTool: () => editFileTool,
1112
+ echoTool: () => echoTool,
1113
+ bashTool: () => bashTool
1114
+ });
1115
+ function getAllBuiltInTools() {
1116
+ return [
1117
+ bashTool,
1118
+ echoTool,
1119
+ globTool,
1120
+ readFileTool,
1121
+ writeFileTool,
1122
+ editFileTool,
1123
+ grepTool
1124
+ ];
1125
+ }
1126
+ function getBuiltInTool(name) {
1127
+ const tools = getAllBuiltInTools();
1128
+ return tools.find((t) => t.name === name);
1129
+ }
1130
+ var init_built_in = __esm(() => {
1131
+ init_bash();
1132
+ init_echo();
1133
+ init_glob();
1134
+ init_read_file();
1135
+ init_write_file();
1136
+ init_edit_file();
1137
+ init_grep();
1138
+ });
1139
+ init_built_in();
1140
+
1141
+ export {
1142
+ writeFileTool,
1143
+ readFileTool,
1144
+ grepTool,
1145
+ globTool,
1146
+ getBuiltInTool,
1147
+ getAllBuiltInTools,
1148
+ editFileTool,
1149
+ echoTool,
1150
+ bashTool
1151
+ };