@ai-setting/roy-agent-core 1.4.10 → 1.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/index.js +23 -0
- package/dist/env/agent/index.js +3035 -0
- package/dist/env/commands/index.js +1685 -0
- package/dist/env/debug/formatters/index.js +639 -0
- package/dist/env/debug/index.js +2300 -0
- package/dist/env/hook/index.js +273 -0
- package/dist/env/index.js +12591 -0
- package/dist/env/llm/index.js +2736 -0
- package/dist/env/log-trace/index.js +1779 -0
- package/dist/env/mcp/index.js +2173 -0
- package/dist/env/mcp/tool/index.js +1149 -0
- package/dist/env/memory/built-in/index.js +225 -0
- package/dist/env/memory/index.js +2171 -0
- package/dist/env/memory/plugin/index.js +1263 -0
- package/dist/env/prompt/index.js +2107 -0
- package/dist/env/session/index.js +3594 -0
- package/dist/env/session/storage/index.js +2049 -0
- package/dist/env/skill/index.js +1635 -0
- package/dist/env/skill/tool/index.js +114 -0
- package/dist/env/task/delegate/index.js +1844 -0
- package/dist/env/task/hooks/index.js +67 -0
- package/dist/env/task/index.js +3578 -0
- package/dist/env/task/plugins/index.js +1626 -0
- package/dist/env/task/storage/index.js +1464 -0
- package/dist/env/task/tools/index.js +344 -0
- package/dist/env/task/tools/operation/index.js +270 -0
- package/dist/env/tool/built-in/index.js +1151 -0
- package/dist/env/tool/index.js +2284 -0
- package/dist/env/workflow/decorators/index.js +449 -0
- package/dist/env/workflow/engine/index.js +4391 -0
- package/dist/env/workflow/index.js +6214 -0
- package/dist/env/workflow/nodes/index.js +650 -0
- package/dist/env/workflow/service/index.js +262 -0
- package/dist/env/workflow/storage/index.js +1236 -0
- package/dist/env/workflow/tools/index.js +1081 -0
- package/dist/env/workflow/types/index.js +479 -0
- package/dist/env/workflow/utils/index.js +1631 -0
- package/dist/index.js +15006 -14265
- package/package.json +2 -2
|
@@ -0,0 +1,1631 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
function __accessProp(key) {
|
|
7
|
+
return this[key];
|
|
8
|
+
}
|
|
9
|
+
var __toCommonJS = (from) => {
|
|
10
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
11
|
+
if (entry)
|
|
12
|
+
return entry;
|
|
13
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (var key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(entry, key))
|
|
17
|
+
__defProp(entry, key, {
|
|
18
|
+
get: __accessProp.bind(from, key),
|
|
19
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
__moduleCache.set(from, entry);
|
|
23
|
+
return entry;
|
|
24
|
+
};
|
|
25
|
+
var __moduleCache;
|
|
26
|
+
var __returnValue = (v) => v;
|
|
27
|
+
function __exportSetter(name, newValue) {
|
|
28
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
29
|
+
}
|
|
30
|
+
var __export = (target, all) => {
|
|
31
|
+
for (var name in all)
|
|
32
|
+
__defProp(target, name, {
|
|
33
|
+
get: all[name],
|
|
34
|
+
enumerable: true,
|
|
35
|
+
configurable: true,
|
|
36
|
+
set: __exportSetter.bind(all, name)
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
|
|
40
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
41
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
|
|
42
|
+
r = Reflect.decorate(decorators, target, key, desc);
|
|
43
|
+
else
|
|
44
|
+
for (var i = decorators.length - 1;i >= 0; i--)
|
|
45
|
+
if (d = decorators[i])
|
|
46
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
47
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
48
|
+
};
|
|
49
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
50
|
+
var __require = import.meta.require;
|
|
51
|
+
|
|
52
|
+
// packages/core/src/env/log-trace/span-storage.ts
|
|
53
|
+
var exports_span_storage = {};
|
|
54
|
+
__export(exports_span_storage, {
|
|
55
|
+
SQLiteSpanStorage: () => SQLiteSpanStorage
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
class SQLiteSpanStorage {
|
|
59
|
+
db = null;
|
|
60
|
+
dbPath;
|
|
61
|
+
initialized = false;
|
|
62
|
+
constructor(dbPath) {
|
|
63
|
+
if (!dbPath) {
|
|
64
|
+
throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
|
|
65
|
+
}
|
|
66
|
+
if (dbPath === ":memory:") {
|
|
67
|
+
throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
|
|
68
|
+
}
|
|
69
|
+
this.dbPath = dbPath;
|
|
70
|
+
}
|
|
71
|
+
async initialize() {
|
|
72
|
+
if (this.initialized)
|
|
73
|
+
return;
|
|
74
|
+
const { Database } = __require("bun:sqlite");
|
|
75
|
+
const fs = __require("fs");
|
|
76
|
+
const path = __require("path");
|
|
77
|
+
const dir = path.dirname(this.dbPath);
|
|
78
|
+
if (!fs.existsSync(dir)) {
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
this.db = new Database(this.dbPath);
|
|
82
|
+
this.db.run("PRAGMA journal_mode=WAL");
|
|
83
|
+
this.db.run("PRAGMA busy_timeout=5000");
|
|
84
|
+
this.db.run("PRAGMA synchronous=NORMAL");
|
|
85
|
+
this.db.run(`
|
|
86
|
+
CREATE TABLE IF NOT EXISTS span (
|
|
87
|
+
span_id TEXT PRIMARY KEY,
|
|
88
|
+
trace_id TEXT NOT NULL,
|
|
89
|
+
parent_span_id TEXT,
|
|
90
|
+
name TEXT NOT NULL,
|
|
91
|
+
kind TEXT NOT NULL,
|
|
92
|
+
status TEXT NOT NULL,
|
|
93
|
+
start_time INTEGER NOT NULL,
|
|
94
|
+
end_time INTEGER,
|
|
95
|
+
attributes TEXT,
|
|
96
|
+
result TEXT,
|
|
97
|
+
error TEXT,
|
|
98
|
+
time_created INTEGER NOT NULL
|
|
99
|
+
)
|
|
100
|
+
`);
|
|
101
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
|
|
102
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
|
|
103
|
+
this.initialized = true;
|
|
104
|
+
}
|
|
105
|
+
save(span) {
|
|
106
|
+
if (!this.db)
|
|
107
|
+
return;
|
|
108
|
+
const stmt = this.db.prepare(`
|
|
109
|
+
INSERT OR REPLACE INTO span
|
|
110
|
+
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
111
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
112
|
+
`);
|
|
113
|
+
const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
|
|
114
|
+
stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, JSON.stringify(span.attributes), resultValue, span.error || null, Date.now());
|
|
115
|
+
}
|
|
116
|
+
saveBatch(spans) {
|
|
117
|
+
for (const span of spans) {
|
|
118
|
+
this.save(span);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
findByTraceId(traceId) {
|
|
122
|
+
if (!this.db)
|
|
123
|
+
return [];
|
|
124
|
+
const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
|
|
125
|
+
return this.buildTree(rows.map(this.rowToSpan));
|
|
126
|
+
}
|
|
127
|
+
findBySpanId(spanId) {
|
|
128
|
+
if (!this.db)
|
|
129
|
+
return;
|
|
130
|
+
const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
|
|
131
|
+
return row ? this.rowToSpan(row) : undefined;
|
|
132
|
+
}
|
|
133
|
+
listTraces(limit = 10) {
|
|
134
|
+
if (!this.db)
|
|
135
|
+
return [];
|
|
136
|
+
const rows = this.db.prepare(`
|
|
137
|
+
SELECT trace_id,
|
|
138
|
+
MIN(start_time) as start_time,
|
|
139
|
+
MAX(end_time) as end_time,
|
|
140
|
+
COUNT(*) as span_count
|
|
141
|
+
FROM span
|
|
142
|
+
GROUP BY trace_id
|
|
143
|
+
ORDER BY start_time DESC
|
|
144
|
+
LIMIT ?
|
|
145
|
+
`).all(limit);
|
|
146
|
+
return rows.map((row) => ({
|
|
147
|
+
traceId: row.trace_id,
|
|
148
|
+
rootSpanName: "unknown",
|
|
149
|
+
startTime: row.start_time,
|
|
150
|
+
endTime: row.end_time,
|
|
151
|
+
duration: row.end_time - row.start_time,
|
|
152
|
+
spanCount: row.span_count,
|
|
153
|
+
status: "ok"
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
deleteByTraceId(traceId) {
|
|
157
|
+
if (this.db) {
|
|
158
|
+
this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
close() {
|
|
162
|
+
if (this.db) {
|
|
163
|
+
this.db.close();
|
|
164
|
+
this.db = null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
rowToSpan(row) {
|
|
168
|
+
return {
|
|
169
|
+
traceId: row.trace_id,
|
|
170
|
+
spanId: row.span_id,
|
|
171
|
+
parentSpanId: row.parent_span_id,
|
|
172
|
+
name: row.name,
|
|
173
|
+
kind: row.kind,
|
|
174
|
+
status: row.status,
|
|
175
|
+
startTime: row.start_time,
|
|
176
|
+
endTime: row.end_time,
|
|
177
|
+
attributes: row.attributes ? JSON.parse(row.attributes) : {},
|
|
178
|
+
result: row.result || undefined,
|
|
179
|
+
error: row.error || undefined
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
buildTree(spans) {
|
|
183
|
+
const spanMap = new Map;
|
|
184
|
+
const roots = [];
|
|
185
|
+
for (const span of spans) {
|
|
186
|
+
spanMap.set(span.spanId, { ...span, children: [] });
|
|
187
|
+
}
|
|
188
|
+
for (const span of spanMap.values()) {
|
|
189
|
+
if (span.parentSpanId) {
|
|
190
|
+
const parent = spanMap.get(span.parentSpanId);
|
|
191
|
+
if (parent) {
|
|
192
|
+
parent.children.push(span);
|
|
193
|
+
} else {
|
|
194
|
+
roots.push(span);
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
roots.push(span);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return roots;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// packages/core/src/env/log-trace/opentelemetry/propagation.ts
|
|
205
|
+
function padLeft(str, length) {
|
|
206
|
+
return str.padStart(length, "0");
|
|
207
|
+
}
|
|
208
|
+
function isValidHex(str) {
|
|
209
|
+
return /^[0-9a-f]+$/i.test(str);
|
|
210
|
+
}
|
|
211
|
+
function serialize(context) {
|
|
212
|
+
const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);
|
|
213
|
+
const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
|
|
214
|
+
const parts = [
|
|
215
|
+
TRACE_CONTEXT_VERSION,
|
|
216
|
+
traceId,
|
|
217
|
+
spanId,
|
|
218
|
+
TRACE_FLAGS_SAMPLED
|
|
219
|
+
];
|
|
220
|
+
return parts.join("-");
|
|
221
|
+
}
|
|
222
|
+
function parse(traceparent) {
|
|
223
|
+
if (!traceparent || typeof traceparent !== "string") {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const trimmed = traceparent.trim();
|
|
227
|
+
const parts = trimmed.split("-");
|
|
228
|
+
if (parts.length !== 4) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const [version, traceId, senderSpanId, flags] = parts;
|
|
232
|
+
if (version !== TRACE_CONTEXT_VERSION) {
|
|
233
|
+
if (version > TRACE_CONTEXT_VERSION) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
traceId: traceId.toLowerCase(),
|
|
248
|
+
spanId: senderSpanId.toLowerCase()
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
var TRACE_CONTEXT_VERSION = "00", TRACE_FLAGS_SAMPLED = "01", TRACEPARENT_HEADER = "TRACEPARENT", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;
|
|
252
|
+
var init_propagation = __esm(() => {
|
|
253
|
+
propagation = {
|
|
254
|
+
inject(carrier, context) {
|
|
255
|
+
carrier[TRACEPARENT_HEADER] = serialize(context);
|
|
256
|
+
},
|
|
257
|
+
extract(carrier) {
|
|
258
|
+
const traceparent = carrier[TRACEPARENT_HEADER];
|
|
259
|
+
if (!traceparent) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
return parse(traceparent);
|
|
263
|
+
},
|
|
264
|
+
getTraceparentHeader() {
|
|
265
|
+
return TRACEPARENT_HEADER;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// packages/core/src/env/log-trace/types.ts
|
|
271
|
+
var SpanKind, SpanStatus;
|
|
272
|
+
var init_types = __esm(() => {
|
|
273
|
+
((SpanKind2) => {
|
|
274
|
+
SpanKind2["CLIENT"] = "client";
|
|
275
|
+
SpanKind2["SERVER"] = "server";
|
|
276
|
+
SpanKind2["INTERNAL"] = "internal";
|
|
277
|
+
})(SpanKind ||= {});
|
|
278
|
+
((SpanStatus2) => {
|
|
279
|
+
SpanStatus2["OK"] = "ok";
|
|
280
|
+
SpanStatus2["ERROR"] = "error";
|
|
281
|
+
})(SpanStatus ||= {});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// packages/core/src/env/log-trace/opentelemetry/tracer-provider.ts
|
|
285
|
+
var exports_tracer_provider = {};
|
|
286
|
+
__export(exports_tracer_provider, {
|
|
287
|
+
resetTracerProvider: () => resetTracerProvider,
|
|
288
|
+
getTracerProvider: () => getTracerProvider,
|
|
289
|
+
OTelTracerProvider: () => OTelTracerProvider
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
class OTelSpanImpl {
|
|
293
|
+
name;
|
|
294
|
+
kind;
|
|
295
|
+
spanContext;
|
|
296
|
+
attributes = {};
|
|
297
|
+
startTime;
|
|
298
|
+
endTime;
|
|
299
|
+
error;
|
|
300
|
+
storage;
|
|
301
|
+
parentSpanContext;
|
|
302
|
+
onEnd;
|
|
303
|
+
constructor(name, spanContext, storage, parentSpanContext, onEnd) {
|
|
304
|
+
this.name = name;
|
|
305
|
+
this.kind = "internal";
|
|
306
|
+
this.spanContext = spanContext;
|
|
307
|
+
this.parentSpanContext = parentSpanContext;
|
|
308
|
+
this.startTime = Date.now();
|
|
309
|
+
this.storage = storage;
|
|
310
|
+
this.onEnd = onEnd;
|
|
311
|
+
}
|
|
312
|
+
setAttribute(key, value) {
|
|
313
|
+
this.attributes[key] = value;
|
|
314
|
+
}
|
|
315
|
+
addEvent(name, attributes) {
|
|
316
|
+
const events = this.attributes._events || [];
|
|
317
|
+
events.push({ name, attributes });
|
|
318
|
+
this.attributes._events = events;
|
|
319
|
+
}
|
|
320
|
+
end(result, error) {
|
|
321
|
+
this.endTime = Date.now();
|
|
322
|
+
if (error) {
|
|
323
|
+
this.error = error.message;
|
|
324
|
+
}
|
|
325
|
+
this.storage.save({
|
|
326
|
+
traceId: this.spanContext.traceId,
|
|
327
|
+
spanId: this.spanContext.spanId,
|
|
328
|
+
parentSpanId: this.spanContext.parentSpanId,
|
|
329
|
+
name: this.name,
|
|
330
|
+
kind: this.kind,
|
|
331
|
+
status: error ? "error" /* ERROR */ : "ok" /* OK */,
|
|
332
|
+
startTime: this.startTime,
|
|
333
|
+
endTime: this.endTime,
|
|
334
|
+
attributes: this.attributes,
|
|
335
|
+
result,
|
|
336
|
+
error: this.error
|
|
337
|
+
});
|
|
338
|
+
this.onEnd?.();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
class OTelTracerImpl {
|
|
343
|
+
name;
|
|
344
|
+
version;
|
|
345
|
+
storage;
|
|
346
|
+
currentContext;
|
|
347
|
+
activeSpans = new Map;
|
|
348
|
+
onSpanEndCallback;
|
|
349
|
+
provider;
|
|
350
|
+
constructor(name, version, storage, provider) {
|
|
351
|
+
this.name = name;
|
|
352
|
+
this.version = version;
|
|
353
|
+
this.storage = storage;
|
|
354
|
+
this.provider = provider;
|
|
355
|
+
}
|
|
356
|
+
setOnSpanEndCallback(callback) {
|
|
357
|
+
this.onSpanEndCallback = callback;
|
|
358
|
+
}
|
|
359
|
+
getActiveSpanCount() {
|
|
360
|
+
return this.activeSpans.size;
|
|
361
|
+
}
|
|
362
|
+
startSpan(name, options) {
|
|
363
|
+
const parentFromOptions = options?.parent;
|
|
364
|
+
const hasExplicitParent = options && "parent" in options;
|
|
365
|
+
const globalContext = this.provider.getGlobalContext();
|
|
366
|
+
let effectiveParentContext;
|
|
367
|
+
if (hasExplicitParent) {
|
|
368
|
+
effectiveParentContext = parentFromOptions;
|
|
369
|
+
} else if (this.currentContext) {
|
|
370
|
+
effectiveParentContext = this.currentContext;
|
|
371
|
+
} else if (globalContext) {
|
|
372
|
+
effectiveParentContext = globalContext;
|
|
373
|
+
}
|
|
374
|
+
const traceId = effectiveParentContext?.traceId || this.generateTraceId();
|
|
375
|
+
const spanId = this.generateSpanId();
|
|
376
|
+
let parentSpanId;
|
|
377
|
+
if (hasExplicitParent && parentFromOptions) {
|
|
378
|
+
parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;
|
|
379
|
+
} else if (this.currentContext) {
|
|
380
|
+
parentSpanId = this.currentContext.spanId;
|
|
381
|
+
} else if (globalContext) {
|
|
382
|
+
parentSpanId = globalContext.spanId;
|
|
383
|
+
}
|
|
384
|
+
const spanContext = {
|
|
385
|
+
traceId,
|
|
386
|
+
spanId,
|
|
387
|
+
parentSpanId
|
|
388
|
+
};
|
|
389
|
+
this.currentContext = {
|
|
390
|
+
traceId,
|
|
391
|
+
spanId,
|
|
392
|
+
parentSpanId
|
|
393
|
+
};
|
|
394
|
+
const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));
|
|
395
|
+
if (options?.attributes) {
|
|
396
|
+
for (const [key, value] of Object.entries(options.attributes)) {
|
|
397
|
+
span.setAttribute(key, value);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.activeSpans.set(spanId, span);
|
|
401
|
+
return span;
|
|
402
|
+
}
|
|
403
|
+
injectToEnv(env) {
|
|
404
|
+
if (this.currentContext) {
|
|
405
|
+
propagation.inject(env, this.currentContext);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
getCurrentContext() {
|
|
409
|
+
return this.currentContext;
|
|
410
|
+
}
|
|
411
|
+
setCurrentContext(context) {
|
|
412
|
+
this.currentContext = context;
|
|
413
|
+
}
|
|
414
|
+
endSpan(span) {
|
|
415
|
+
const spanContext = span.spanContext;
|
|
416
|
+
this.activeSpans.delete(spanContext.spanId);
|
|
417
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
418
|
+
if (spanContext.parentSpanId) {
|
|
419
|
+
const parentSpan = this.activeSpans.get(spanContext.parentSpanId);
|
|
420
|
+
if (parentSpan) {
|
|
421
|
+
const parentContext = {
|
|
422
|
+
traceId: spanContext.traceId,
|
|
423
|
+
spanId: parentSpan.spanContext.spanId,
|
|
424
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
425
|
+
};
|
|
426
|
+
this.currentContext = parentContext;
|
|
427
|
+
return parentContext;
|
|
428
|
+
}
|
|
429
|
+
if (currentTraceId) {
|
|
430
|
+
const parentContext = {
|
|
431
|
+
traceId: currentTraceId,
|
|
432
|
+
spanId: spanContext.parentSpanId,
|
|
433
|
+
parentSpanId: undefined
|
|
434
|
+
};
|
|
435
|
+
this.currentContext = parentContext;
|
|
436
|
+
return parentContext;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
this.currentContext = undefined;
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
generateTraceId() {
|
|
443
|
+
const timestamp = Date.now().toString(16).padStart(12, "0");
|
|
444
|
+
const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")).join("");
|
|
445
|
+
return (timestamp + random).slice(0, 32).padStart(32, "0");
|
|
446
|
+
}
|
|
447
|
+
generateSpanId() {
|
|
448
|
+
return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
|
|
449
|
+
}
|
|
450
|
+
handleSpanEnd(spanId, parentSpanId) {
|
|
451
|
+
this.activeSpans.delete(spanId);
|
|
452
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
453
|
+
if (parentSpanId) {
|
|
454
|
+
const parentSpan = this.activeSpans.get(parentSpanId);
|
|
455
|
+
if (parentSpan) {
|
|
456
|
+
this.currentContext = {
|
|
457
|
+
traceId: parentSpan.spanContext.traceId,
|
|
458
|
+
spanId: parentSpan.spanContext.spanId,
|
|
459
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
460
|
+
};
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (currentTraceId) {
|
|
464
|
+
this.currentContext = {
|
|
465
|
+
traceId: currentTraceId,
|
|
466
|
+
spanId: parentSpanId,
|
|
467
|
+
parentSpanId: undefined
|
|
468
|
+
};
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
this.currentContext = undefined;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
class OTelTracerProvider {
|
|
477
|
+
tracers = new Map;
|
|
478
|
+
storage;
|
|
479
|
+
initialized = false;
|
|
480
|
+
globalContext;
|
|
481
|
+
constructor(storage, dbPath) {
|
|
482
|
+
this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());
|
|
483
|
+
}
|
|
484
|
+
async initialize() {
|
|
485
|
+
if (this.initialized)
|
|
486
|
+
return;
|
|
487
|
+
await this.storage.initialize();
|
|
488
|
+
this.initialized = true;
|
|
489
|
+
}
|
|
490
|
+
isInitialized() {
|
|
491
|
+
return this.initialized;
|
|
492
|
+
}
|
|
493
|
+
getGlobalContext() {
|
|
494
|
+
return this.globalContext;
|
|
495
|
+
}
|
|
496
|
+
setGlobalContext(context) {
|
|
497
|
+
this.globalContext = context;
|
|
498
|
+
}
|
|
499
|
+
getTracer(name, version) {
|
|
500
|
+
const key = `${name}@${version || "0.0.0"}`;
|
|
501
|
+
let tracer = this.tracers.get(key);
|
|
502
|
+
if (!tracer) {
|
|
503
|
+
tracer = new OTelTracerImpl(name, version, this.storage, this);
|
|
504
|
+
this.tracers.set(key, tracer);
|
|
505
|
+
if (this.initialized) {
|
|
506
|
+
this.restoreFromEnv(tracer);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return tracer;
|
|
510
|
+
}
|
|
511
|
+
restoreFromEnv(tracer) {
|
|
512
|
+
const extracted = propagation.extract(process.env);
|
|
513
|
+
if (extracted) {
|
|
514
|
+
tracer.setCurrentContext({
|
|
515
|
+
traceId: extracted.traceId,
|
|
516
|
+
spanId: extracted.spanId,
|
|
517
|
+
parentSpanId: undefined
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
shutdown() {
|
|
522
|
+
for (const tracer of this.tracers.values()) {}
|
|
523
|
+
this.tracers.clear();
|
|
524
|
+
this.storage.close();
|
|
525
|
+
this.initialized = false;
|
|
526
|
+
this.globalContext = undefined;
|
|
527
|
+
delete process.env["TRACEPARENT"];
|
|
528
|
+
delete process.env["TRACE_ID"];
|
|
529
|
+
delete process.env["LOG_TRACE_REQUEST_ID"];
|
|
530
|
+
}
|
|
531
|
+
getStorage() {
|
|
532
|
+
return this.storage;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function getTracerProvider() {
|
|
536
|
+
if (!providerInstance) {
|
|
537
|
+
providerInstance = new OTelTracerProvider;
|
|
538
|
+
}
|
|
539
|
+
return providerInstance;
|
|
540
|
+
}
|
|
541
|
+
function resetTracerProvider() {
|
|
542
|
+
if (providerInstance) {
|
|
543
|
+
providerInstance.shutdown();
|
|
544
|
+
providerInstance = null;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function getDefaultDbPath() {
|
|
548
|
+
const os = __require("os");
|
|
549
|
+
const path = __require("path");
|
|
550
|
+
const home = os.homedir();
|
|
551
|
+
const dataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
552
|
+
return path.join(dataHome, "roy-agent", "traces.db");
|
|
553
|
+
}
|
|
554
|
+
var providerInstance = null;
|
|
555
|
+
var init_tracer_provider = __esm(() => {
|
|
556
|
+
init_propagation();
|
|
557
|
+
init_types();
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// packages/core/src/env/log-trace/logger.ts
|
|
561
|
+
import { appendFileSync, existsSync, mkdirSync } from "fs";
|
|
562
|
+
import { join } from "path";
|
|
563
|
+
function simplifyFilePath(fullPath) {
|
|
564
|
+
let path = fullPath.replace(/\\/g, "/");
|
|
565
|
+
const bunfsMatch = path.match(/\/\$bunfs\/root\/(.+)$/);
|
|
566
|
+
if (bunfsMatch) {
|
|
567
|
+
const virtualPath = bunfsMatch[1];
|
|
568
|
+
const packagesMatch = virtualPath.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
569
|
+
if (packagesMatch) {
|
|
570
|
+
return packagesMatch[1];
|
|
571
|
+
}
|
|
572
|
+
return virtualPath;
|
|
573
|
+
}
|
|
574
|
+
const fileProtocolMatch = path.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);
|
|
575
|
+
if (fileProtocolMatch) {
|
|
576
|
+
const rootPkg = fileProtocolMatch[1].replace(/\+/g, "/");
|
|
577
|
+
const remaining = fileProtocolMatch[2];
|
|
578
|
+
const prefix = rootPkg;
|
|
579
|
+
const suffix = remaining.startsWith("src/") ? remaining : `src/${remaining}`;
|
|
580
|
+
return `${prefix}/${suffix}`;
|
|
581
|
+
}
|
|
582
|
+
const packagesRootMatch = path.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
583
|
+
if (packagesRootMatch) {
|
|
584
|
+
return packagesRootMatch[1];
|
|
585
|
+
}
|
|
586
|
+
const rootMarkers = ["packages/core/src", "packages/core", "packages"];
|
|
587
|
+
for (const marker of rootMarkers) {
|
|
588
|
+
const idx = path.indexOf(marker);
|
|
589
|
+
if (idx !== -1) {
|
|
590
|
+
return path.substring(idx);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return path;
|
|
594
|
+
}
|
|
595
|
+
function getDefaultLogDir() {
|
|
596
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
597
|
+
try {
|
|
598
|
+
const xdg = __require("xdg-basedir");
|
|
599
|
+
if (xdg.xdgData) {
|
|
600
|
+
return join(xdg.xdgData, "roy-agent", "logs");
|
|
601
|
+
}
|
|
602
|
+
} catch {}
|
|
603
|
+
return join(home, ".local", "share", "roy-agent", "logs");
|
|
604
|
+
}
|
|
605
|
+
function isQuietMode() {
|
|
606
|
+
return quietMode;
|
|
607
|
+
}
|
|
608
|
+
function setQuietMode(enabled) {
|
|
609
|
+
quietMode = enabled;
|
|
610
|
+
}
|
|
611
|
+
function setConfigComponent(component) {
|
|
612
|
+
configComponentInstance = component;
|
|
613
|
+
}
|
|
614
|
+
function getLogLevel() {
|
|
615
|
+
if (configComponentInstance) {
|
|
616
|
+
const level = configComponentInstance.get("log_trace.logging.level");
|
|
617
|
+
if (level && ["debug", "info", "warn", "error"].includes(level)) {
|
|
618
|
+
return level;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const envLevel = process.env.LOG_LEVEL;
|
|
622
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
623
|
+
return envLevel;
|
|
624
|
+
}
|
|
625
|
+
return "info";
|
|
626
|
+
}
|
|
627
|
+
function getCategoryLogLevel(category) {
|
|
628
|
+
if (configComponentInstance) {
|
|
629
|
+
const levels = configComponentInstance.get("log_trace.logging.levels");
|
|
630
|
+
if (levels && typeof levels === "object") {
|
|
631
|
+
const categoryLevel = levels[category];
|
|
632
|
+
if (categoryLevel && ["debug", "info", "warn", "error"].includes(categoryLevel)) {
|
|
633
|
+
return categoryLevel;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);
|
|
637
|
+
if (directLevel && ["debug", "info", "warn", "error"].includes(directLevel)) {
|
|
638
|
+
return directLevel;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, "_")}`;
|
|
642
|
+
const envLevel = process.env[envKey];
|
|
643
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
644
|
+
return envLevel;
|
|
645
|
+
}
|
|
646
|
+
return getLogLevel();
|
|
647
|
+
}
|
|
648
|
+
function isAbsolutePath(path) {
|
|
649
|
+
if (path.startsWith("/")) {
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
if (/^[a-zA-Z]:[/\\]/.test(path)) {
|
|
653
|
+
return true;
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
function expandHomeDir(path) {
|
|
658
|
+
if (path.startsWith("~")) {
|
|
659
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
660
|
+
return join(home, path.slice(1));
|
|
661
|
+
}
|
|
662
|
+
return path;
|
|
663
|
+
}
|
|
664
|
+
function getLogFile() {
|
|
665
|
+
if (configComponentInstance) {
|
|
666
|
+
const file = configComponentInstance.get("log_trace.logging.file");
|
|
667
|
+
if (file) {
|
|
668
|
+
return file;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
return "app.log";
|
|
672
|
+
}
|
|
673
|
+
function getLogDir() {
|
|
674
|
+
if (configComponentInstance) {
|
|
675
|
+
const dir = configComponentInstance.get("log_trace.logging.dir");
|
|
676
|
+
if (dir) {
|
|
677
|
+
return dir;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
return getDefaultLogDir();
|
|
681
|
+
}
|
|
682
|
+
function getMaxOutput() {
|
|
683
|
+
if (configComponentInstance) {
|
|
684
|
+
const maxOutput = configComponentInstance.get("log-trace.logging.maxOutput");
|
|
685
|
+
if (typeof maxOutput === "number") {
|
|
686
|
+
return maxOutput;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
function setLogDirOverride(dir) {
|
|
692
|
+
logDirOverride = dir;
|
|
693
|
+
}
|
|
694
|
+
function getLogDirOverride() {
|
|
695
|
+
return logDirOverride;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
class Logger {
|
|
699
|
+
prefix;
|
|
700
|
+
constructor(prefix) {
|
|
701
|
+
this.prefix = prefix;
|
|
702
|
+
}
|
|
703
|
+
shouldLog(level) {
|
|
704
|
+
const categoryLevel = getCategoryLogLevel(this.prefix);
|
|
705
|
+
return levelPriority[level] >= levelPriority[categoryLevel];
|
|
706
|
+
}
|
|
707
|
+
ensureLogDirectory(dir) {
|
|
708
|
+
if (!existsSync(dir)) {
|
|
709
|
+
try {
|
|
710
|
+
mkdirSync(dir, { recursive: true });
|
|
711
|
+
} catch (err) {
|
|
712
|
+
console.error("[Logger] Failed to create log directory:", dir, err);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
getCallerLocation() {
|
|
717
|
+
const originalLimit = Error.stackTraceLimit;
|
|
718
|
+
Error.stackTraceLimit = 10;
|
|
719
|
+
const err = new Error;
|
|
720
|
+
Error.captureStackTrace(err, this.formatMessage);
|
|
721
|
+
const stack = err.stack?.split(`
|
|
722
|
+
`) || [];
|
|
723
|
+
Error.stackTraceLimit = originalLimit;
|
|
724
|
+
for (let i = 1;i < stack.length; i++) {
|
|
725
|
+
const line = stack[i];
|
|
726
|
+
if (line.includes("at ") && !line.includes("logger.ts") && !line.includes("formatMessage")) {
|
|
727
|
+
const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
|
|
728
|
+
if (match) {
|
|
729
|
+
const filePath = match[1];
|
|
730
|
+
const relativePath = this.getRelativePath(filePath);
|
|
731
|
+
return {
|
|
732
|
+
file: relativePath,
|
|
733
|
+
line: parseInt(match[2], 10)
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
getRelativePath(fullPath) {
|
|
741
|
+
return simplifyFilePath(fullPath);
|
|
742
|
+
}
|
|
743
|
+
formatMessage(level, message, data) {
|
|
744
|
+
const now = new Date;
|
|
745
|
+
const timestamp = now.toLocaleString("zh-CN", {
|
|
746
|
+
timeZone: "Asia/Shanghai",
|
|
747
|
+
year: "numeric",
|
|
748
|
+
month: "2-digit",
|
|
749
|
+
day: "2-digit",
|
|
750
|
+
hour: "2-digit",
|
|
751
|
+
minute: "2-digit",
|
|
752
|
+
second: "2-digit",
|
|
753
|
+
hour12: false
|
|
754
|
+
}).replace(/\//g, "-") + "." + String(now.getMilliseconds()).padStart(3, "0");
|
|
755
|
+
const prefix = this.prefix ? `[${this.prefix}]` : "";
|
|
756
|
+
let traceIdStr = "";
|
|
757
|
+
try {
|
|
758
|
+
const provider = getTracerProvider();
|
|
759
|
+
const tracer = provider.getTracer("roy-tracer");
|
|
760
|
+
const context = tracer.getCurrentContext();
|
|
761
|
+
if (context?.traceId) {
|
|
762
|
+
traceIdStr = `[traceId=${context.traceId}]`;
|
|
763
|
+
}
|
|
764
|
+
} catch {}
|
|
765
|
+
let locationStr = "";
|
|
766
|
+
if (data && typeof data === "object" && "callerLocation" in data) {
|
|
767
|
+
const logData = data;
|
|
768
|
+
locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : "";
|
|
769
|
+
const { callerLocation: _callerLocation, ...rest } = logData;
|
|
770
|
+
data = Object.keys(rest).length > 0 ? rest : undefined;
|
|
771
|
+
} else {
|
|
772
|
+
const location = this.getCallerLocation();
|
|
773
|
+
if (location) {
|
|
774
|
+
locationStr = ` [${location.file}:${location.line}]`;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;
|
|
778
|
+
if (data !== undefined) {
|
|
779
|
+
if (typeof data === "object") {
|
|
780
|
+
formatted += " " + JSON.stringify(data).replace(/\n/g, "");
|
|
781
|
+
} else {
|
|
782
|
+
formatted += " " + String(data);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const maxOutput = getMaxOutput();
|
|
786
|
+
if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {
|
|
787
|
+
formatted = formatted.substring(0, maxOutput) + " [TRUNCATED]";
|
|
788
|
+
}
|
|
789
|
+
return formatted;
|
|
790
|
+
}
|
|
791
|
+
writeToFile(message) {
|
|
792
|
+
try {
|
|
793
|
+
const dir = getLogDir();
|
|
794
|
+
const filename = getLogFile();
|
|
795
|
+
const expandedDir = expandHomeDir(dir);
|
|
796
|
+
const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);
|
|
797
|
+
this.ensureLogDirectory(resolvedDir);
|
|
798
|
+
const logFile = join(resolvedDir, filename);
|
|
799
|
+
appendFileSync(logFile, message + `
|
|
800
|
+
`, "utf-8");
|
|
801
|
+
} catch (err) {
|
|
802
|
+
console.error("[Logger] Failed to write to log file:", err);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
log(level, message, data) {
|
|
806
|
+
if (!this.shouldLog(level))
|
|
807
|
+
return;
|
|
808
|
+
const formatted = this.formatMessage(level, message, data);
|
|
809
|
+
this.writeToFile(formatted);
|
|
810
|
+
if (!isQuietMode()) {
|
|
811
|
+
const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.log : console.debug;
|
|
812
|
+
consoleMethod(formatted);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
debug(message, data) {
|
|
816
|
+
this.log("debug", message, data);
|
|
817
|
+
}
|
|
818
|
+
info(message, data) {
|
|
819
|
+
this.log("info", message, data);
|
|
820
|
+
}
|
|
821
|
+
warn(message, data) {
|
|
822
|
+
this.log("warn", message, data);
|
|
823
|
+
}
|
|
824
|
+
error(message, data) {
|
|
825
|
+
this.log("error", message, data);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function createLogger(prefix) {
|
|
829
|
+
if (!loggerCache.has(prefix)) {
|
|
830
|
+
loggerCache.set(prefix, new Logger(prefix));
|
|
831
|
+
}
|
|
832
|
+
return loggerCache.get(prefix);
|
|
833
|
+
}
|
|
834
|
+
function getLogLevels() {
|
|
835
|
+
return ["debug", "info", "warn", "error"];
|
|
836
|
+
}
|
|
837
|
+
var configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;
|
|
838
|
+
var init_logger = __esm(() => {
|
|
839
|
+
init_tracer_provider();
|
|
840
|
+
levelPriority = {
|
|
841
|
+
debug: 0,
|
|
842
|
+
info: 1,
|
|
843
|
+
warn: 2,
|
|
844
|
+
error: 3
|
|
845
|
+
};
|
|
846
|
+
loggerCache = new Map;
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
// packages/core/src/env/log-trace/decorator.ts
|
|
850
|
+
function Traced(options) {
|
|
851
|
+
return function(target, propertyKey, descriptor) {
|
|
852
|
+
const originalFn = descriptor.value;
|
|
853
|
+
const spanName = options?.name || propertyKey;
|
|
854
|
+
descriptor.value = wrapFunction(originalFn, spanName, {
|
|
855
|
+
recordParams: options?.recordParams ?? true,
|
|
856
|
+
recordResult: options?.recordResult ?? false,
|
|
857
|
+
recordError: options?.recordError ?? true,
|
|
858
|
+
log: options?.log ?? false,
|
|
859
|
+
maxLogSize: options?.maxLogSize,
|
|
860
|
+
paramFilter: options?.paramFilter
|
|
861
|
+
});
|
|
862
|
+
return descriptor;
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
function TracedAs(name, options) {
|
|
866
|
+
return Traced({ name, ...options });
|
|
867
|
+
}
|
|
868
|
+
function TracedLightweight(options) {
|
|
869
|
+
return Traced({ recordParams: false, recordResult: false, log: options?.log ?? false, maxLogSize: options?.maxLogSize });
|
|
870
|
+
}
|
|
871
|
+
function wrapFunction(fn, name, options) {
|
|
872
|
+
const shouldLog = options?.log ?? false;
|
|
873
|
+
const getMaxLogSize = () => {
|
|
874
|
+
if (options?.maxLogSize !== undefined) {
|
|
875
|
+
return options.maxLogSize;
|
|
876
|
+
}
|
|
877
|
+
const configMaxOutput = getMaxOutput();
|
|
878
|
+
return configMaxOutput !== undefined ? configMaxOutput : 500;
|
|
879
|
+
};
|
|
880
|
+
const truncate = (obj) => {
|
|
881
|
+
if (obj === undefined)
|
|
882
|
+
return;
|
|
883
|
+
if (obj === null)
|
|
884
|
+
return null;
|
|
885
|
+
const maxLogSize = getMaxLogSize();
|
|
886
|
+
let str;
|
|
887
|
+
try {
|
|
888
|
+
str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
|
|
889
|
+
} catch (e) {
|
|
890
|
+
str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
|
|
891
|
+
}
|
|
892
|
+
if (maxLogSize > 0 && str.length > maxLogSize) {
|
|
893
|
+
return str.slice(0, maxLogSize) + " [TRUNCATED]";
|
|
894
|
+
}
|
|
895
|
+
try {
|
|
896
|
+
return JSON.parse(str);
|
|
897
|
+
} catch {
|
|
898
|
+
return str;
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
const truncateString = (obj) => {
|
|
902
|
+
if (obj === undefined)
|
|
903
|
+
return "undefined";
|
|
904
|
+
if (obj === null)
|
|
905
|
+
return "null";
|
|
906
|
+
const maxLogSize = getMaxLogSize();
|
|
907
|
+
let str;
|
|
908
|
+
try {
|
|
909
|
+
str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
|
|
910
|
+
} catch (e) {
|
|
911
|
+
str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
|
|
912
|
+
}
|
|
913
|
+
return maxLogSize > 0 && str.length > maxLogSize ? str.slice(0, maxLogSize) + " [TRUNCATED]" : str;
|
|
914
|
+
};
|
|
915
|
+
const TRACE_LOG_PREFIX = "[TRACE]";
|
|
916
|
+
const getCallerLocation = () => {
|
|
917
|
+
const originalLimit = Error.stackTraceLimit;
|
|
918
|
+
Error.stackTraceLimit = 15;
|
|
919
|
+
const err = new Error;
|
|
920
|
+
Error.captureStackTrace(err, getCallerLocation);
|
|
921
|
+
const stack = err.stack?.split(`
|
|
922
|
+
`) || [];
|
|
923
|
+
Error.stackTraceLimit = originalLimit;
|
|
924
|
+
for (let i = 1;i < stack.length; i++) {
|
|
925
|
+
const line = stack[i];
|
|
926
|
+
if (line.includes("decorator.ts") || line.includes("decorator.js") || line.includes("logFn") || line.includes("getCallerLocation"))
|
|
927
|
+
continue;
|
|
928
|
+
const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
|
|
929
|
+
if (match) {
|
|
930
|
+
const filePath = match[1];
|
|
931
|
+
if (!filePath || filePath === "native")
|
|
932
|
+
continue;
|
|
933
|
+
const relativePath = simplifyFilePath(filePath);
|
|
934
|
+
return `${relativePath}:${match[2]}`;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
return "";
|
|
938
|
+
};
|
|
939
|
+
const logFn = (event, argsOrData, callerLocation) => {
|
|
940
|
+
if (!shouldLog)
|
|
941
|
+
return;
|
|
942
|
+
const logger = createLogger("traced:" + name);
|
|
943
|
+
const tag = event === "enter" ? ">>>" : event === "quit" ? "<<<" : "!!!";
|
|
944
|
+
const prefix = `${TRACE_LOG_PREFIX} ${tag} ${name}`;
|
|
945
|
+
const originalFnLocation = callerLocation || getCallerLocation();
|
|
946
|
+
const logMessage = (msg, data) => {
|
|
947
|
+
if (data !== undefined) {
|
|
948
|
+
logger.info(`${prefix} ${msg}: ${truncateString(data)}`, { callerLocation: originalFnLocation });
|
|
949
|
+
} else {
|
|
950
|
+
logger.info(`${prefix} ${msg}`, { callerLocation: originalFnLocation });
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
if (event === "enter") {
|
|
954
|
+
logMessage("enter", argsOrData);
|
|
955
|
+
} else if (event === "quit") {
|
|
956
|
+
logMessage("quit", options?.recordResult ? argsOrData : undefined);
|
|
957
|
+
} else {
|
|
958
|
+
logMessage("error", argsOrData);
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
return function(...args) {
|
|
962
|
+
const tracer = getTracerProvider().getTracer("roy-tracer");
|
|
963
|
+
const attributes = {};
|
|
964
|
+
if (options?.recordParams !== false) {
|
|
965
|
+
if (options?.paramFilter) {
|
|
966
|
+
attributes["params"] = truncate(options.paramFilter(args));
|
|
967
|
+
} else {
|
|
968
|
+
attributes["params"] = truncate(args);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
const callerLocation = getCallerLocation();
|
|
972
|
+
logFn("enter", args, callerLocation);
|
|
973
|
+
const span = tracer.startSpan(name, { attributes });
|
|
974
|
+
try {
|
|
975
|
+
const result = fn.call(this, ...args);
|
|
976
|
+
if (result && typeof result === "object" && typeof result.then === "function") {
|
|
977
|
+
return result.then((resolved) => {
|
|
978
|
+
span.setAttribute("result", JSON.stringify(truncate(resolved)));
|
|
979
|
+
span.end(resolved);
|
|
980
|
+
logFn("quit", options?.recordResult ? resolved : undefined, callerLocation);
|
|
981
|
+
return resolved;
|
|
982
|
+
}, (rejected) => {
|
|
983
|
+
span.setAttribute("error", String(rejected));
|
|
984
|
+
span.end(undefined, rejected instanceof Error ? rejected : new Error(String(rejected)));
|
|
985
|
+
logFn("error", rejected.message, callerLocation);
|
|
986
|
+
throw rejected;
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
span.setAttribute("result", JSON.stringify(truncate(result)));
|
|
990
|
+
span.end(result);
|
|
991
|
+
logFn("quit", options?.recordResult ? result : undefined, callerLocation);
|
|
992
|
+
return result;
|
|
993
|
+
} catch (error) {
|
|
994
|
+
span.setAttribute("error", String(error));
|
|
995
|
+
span.end(undefined, error instanceof Error ? error : new Error(String(error)));
|
|
996
|
+
logFn("error", error.message, callerLocation);
|
|
997
|
+
throw error;
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
var init_decorator = __esm(() => {
|
|
1002
|
+
init_tracer_provider();
|
|
1003
|
+
init_logger();
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
// packages/core/src/env/workflow/utils/template-resolver.ts
|
|
1007
|
+
class TemplateResolver {
|
|
1008
|
+
input;
|
|
1009
|
+
previousOutputs;
|
|
1010
|
+
constructor(options = {}) {
|
|
1011
|
+
this.input = options.input ?? {};
|
|
1012
|
+
this.previousOutputs = options.previousOutputs ?? new Map;
|
|
1013
|
+
}
|
|
1014
|
+
static fromContext(context) {
|
|
1015
|
+
return new TemplateResolver({
|
|
1016
|
+
input: context.input,
|
|
1017
|
+
previousOutputs: context.previousOutputs
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
resolveValue(input) {
|
|
1021
|
+
if (input === null || input === undefined) {
|
|
1022
|
+
return input;
|
|
1023
|
+
}
|
|
1024
|
+
if (typeof input === "string") {
|
|
1025
|
+
const pureTemplate = this.extractPureTemplate(input);
|
|
1026
|
+
if (pureTemplate) {
|
|
1027
|
+
return this.resolvePureTemplate(pureTemplate);
|
|
1028
|
+
}
|
|
1029
|
+
return this.resolveString(input);
|
|
1030
|
+
}
|
|
1031
|
+
if (Array.isArray(input)) {
|
|
1032
|
+
return input.map((item) => this.resolveValue(item));
|
|
1033
|
+
}
|
|
1034
|
+
if (typeof input === "object") {
|
|
1035
|
+
const resolved = {};
|
|
1036
|
+
for (const [key, value] of Object.entries(input)) {
|
|
1037
|
+
resolved[key] = this.resolveValue(value);
|
|
1038
|
+
}
|
|
1039
|
+
return resolved;
|
|
1040
|
+
}
|
|
1041
|
+
return input;
|
|
1042
|
+
}
|
|
1043
|
+
extractPureTemplate(str) {
|
|
1044
|
+
const trimmed = str.trim();
|
|
1045
|
+
if (trimmed.startsWith("{{") && trimmed.endsWith("}}") && trimmed.length > 4) {
|
|
1046
|
+
const content = trimmed.slice(2, -2).trim();
|
|
1047
|
+
if (!content.includes("{{") && !content.includes("}}")) {
|
|
1048
|
+
return content;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
return null;
|
|
1052
|
+
}
|
|
1053
|
+
resolvePureTemplate(templateContent) {
|
|
1054
|
+
const value = this.resolveTemplateContent(templateContent);
|
|
1055
|
+
return value;
|
|
1056
|
+
}
|
|
1057
|
+
resolveTemplateContent(templateContent) {
|
|
1058
|
+
const trimmed = templateContent.trim();
|
|
1059
|
+
if (trimmed.startsWith("input.")) {
|
|
1060
|
+
return this.getNestedValue(this.input, trimmed.slice(6));
|
|
1061
|
+
}
|
|
1062
|
+
if (trimmed.startsWith("nodes.")) {
|
|
1063
|
+
return this.resolveNodePath(trimmed.slice(6));
|
|
1064
|
+
}
|
|
1065
|
+
if (trimmed !== "input" && trimmed !== "nodes") {
|
|
1066
|
+
const segments = trimmed.split(".");
|
|
1067
|
+
const nodeId = segments[0];
|
|
1068
|
+
const restPath = segments.slice(1).join(".") || undefined;
|
|
1069
|
+
return this.resolveNodePath(`${nodeId}${restPath ? "." + restPath : ""}`);
|
|
1070
|
+
}
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
resolveString(template) {
|
|
1074
|
+
if (!template || typeof template !== "string") {
|
|
1075
|
+
return template;
|
|
1076
|
+
}
|
|
1077
|
+
let resolved = template;
|
|
1078
|
+
resolved = resolved.replace(/\{\{input\.([^}]+)\}\}/g, (match, path) => {
|
|
1079
|
+
const value = this.getNestedValue(this.input, path);
|
|
1080
|
+
return this.stringify(value, match);
|
|
1081
|
+
});
|
|
1082
|
+
resolved = resolved.replace(/\{\{nodes\.([^}]+)\}\}/g, (match, path) => {
|
|
1083
|
+
const value = this.resolveNodePath(path);
|
|
1084
|
+
return this.stringify(value, match);
|
|
1085
|
+
});
|
|
1086
|
+
resolved = resolved.replace(/\{\{([a-zA-Z_][a-zA-Z0-9_-]*)(?:\.([^}]+))?\}\}/g, (match, nodeId, path) => {
|
|
1087
|
+
if (nodeId === "input") {
|
|
1088
|
+
return match;
|
|
1089
|
+
}
|
|
1090
|
+
if (nodeId === "nodes") {
|
|
1091
|
+
return match;
|
|
1092
|
+
}
|
|
1093
|
+
const value = this.resolveNodePath(`${nodeId}${path ? "." + path : ""}`);
|
|
1094
|
+
return this.stringify(value, match);
|
|
1095
|
+
});
|
|
1096
|
+
return resolved;
|
|
1097
|
+
}
|
|
1098
|
+
resolveNodePath(path) {
|
|
1099
|
+
const segments = path.split(".");
|
|
1100
|
+
const nodeId = segments[0];
|
|
1101
|
+
if (!nodeId) {
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
let value = this.previousOutputs.get(nodeId);
|
|
1105
|
+
if (value === undefined) {
|
|
1106
|
+
const normalizedUnderscore = nodeId.replace(/-/g, "_");
|
|
1107
|
+
const normalizedHyphen = nodeId.replace(/_/g, "-");
|
|
1108
|
+
if (normalizedUnderscore !== nodeId) {
|
|
1109
|
+
value = this.previousOutputs.get(normalizedUnderscore);
|
|
1110
|
+
}
|
|
1111
|
+
if (value === undefined && normalizedHyphen !== nodeId) {
|
|
1112
|
+
value = this.previousOutputs.get(normalizedHyphen);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
if (value === undefined) {
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
if (segments.length === 1) {
|
|
1119
|
+
if (value && typeof value === "object" && "result" in value && !("nodes" in value)) {
|
|
1120
|
+
value = value.result;
|
|
1121
|
+
}
|
|
1122
|
+
return value;
|
|
1123
|
+
}
|
|
1124
|
+
const secondSegment = segments[1];
|
|
1125
|
+
if (secondSegment === "result" || secondSegment === "output") {
|
|
1126
|
+
if (value && typeof value === "object" && "result" in value) {
|
|
1127
|
+
value = value.result;
|
|
1128
|
+
if (segments.length === 2) {
|
|
1129
|
+
return value;
|
|
1130
|
+
}
|
|
1131
|
+
for (let i = 2;i < segments.length; i++) {
|
|
1132
|
+
if (value === null || value === undefined) {
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
value = value[segments[i]];
|
|
1136
|
+
}
|
|
1137
|
+
return value;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
for (let i = 1;i < segments.length; i++) {
|
|
1141
|
+
if (value === null || value === undefined) {
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
value = value[segments[i]];
|
|
1145
|
+
}
|
|
1146
|
+
return value;
|
|
1147
|
+
}
|
|
1148
|
+
getNestedValue(obj, path) {
|
|
1149
|
+
if (!obj || !path) {
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
const segments = path.split(".");
|
|
1153
|
+
let current = obj;
|
|
1154
|
+
for (const segment of segments) {
|
|
1155
|
+
if (current === null || current === undefined) {
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (typeof current !== "object") {
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
current = current[segment];
|
|
1162
|
+
}
|
|
1163
|
+
return current;
|
|
1164
|
+
}
|
|
1165
|
+
stringify(value, originalTemplate) {
|
|
1166
|
+
if (value === undefined) {
|
|
1167
|
+
return originalTemplate;
|
|
1168
|
+
}
|
|
1169
|
+
if (typeof value === "string") {
|
|
1170
|
+
return value;
|
|
1171
|
+
}
|
|
1172
|
+
if (value === null) {
|
|
1173
|
+
return "null";
|
|
1174
|
+
}
|
|
1175
|
+
return JSON.stringify(value);
|
|
1176
|
+
}
|
|
1177
|
+
containsTemplates(str) {
|
|
1178
|
+
if (typeof str !== "string") {
|
|
1179
|
+
return false;
|
|
1180
|
+
}
|
|
1181
|
+
return /\{\{[^}]+\}\}/.test(str);
|
|
1182
|
+
}
|
|
1183
|
+
extractTemplates(str) {
|
|
1184
|
+
if (typeof str !== "string") {
|
|
1185
|
+
return [];
|
|
1186
|
+
}
|
|
1187
|
+
const matches = str.match(/\{\{[^}]+\}\}/g);
|
|
1188
|
+
return matches ?? [];
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
function resolveTemplates(input, context) {
|
|
1192
|
+
const resolver = TemplateResolver.fromContext(context);
|
|
1193
|
+
return resolver.resolveValue(input);
|
|
1194
|
+
}
|
|
1195
|
+
function resolveTemplateString(template, context) {
|
|
1196
|
+
const resolver = TemplateResolver.fromContext(context);
|
|
1197
|
+
return resolver.resolveString(template);
|
|
1198
|
+
}
|
|
1199
|
+
// packages/core/src/env/workflow/utils/recovery-validator.ts
|
|
1200
|
+
init_decorator();
|
|
1201
|
+
|
|
1202
|
+
// packages/core/src/env/workflow/utils/validation-rules.ts
|
|
1203
|
+
var ValidationErrorType;
|
|
1204
|
+
((ValidationErrorType2) => {
|
|
1205
|
+
ValidationErrorType2["MISSING_VARIABLE"] = "MISSING_VARIABLE";
|
|
1206
|
+
ValidationErrorType2["INCOMPLETE_PARALLEL"] = "INCOMPLETE_PARALLEL";
|
|
1207
|
+
ValidationErrorType2["AMBIGUOUS_BRANCH"] = "AMBIGUOUS_BRANCH";
|
|
1208
|
+
ValidationErrorType2["LOOP_STATE_LOST"] = "LOOP_STATE_LOST";
|
|
1209
|
+
ValidationErrorType2["NESTED_WORKFLOW_INVALID"] = "NESTED_WORKFLOW_INVALID";
|
|
1210
|
+
ValidationErrorType2["NODE_STATE_INCONSISTENT"] = "NODE_STATE_INCONSISTENT";
|
|
1211
|
+
ValidationErrorType2["MISSING_DEPENDENCY"] = "MISSING_DEPENDENCY";
|
|
1212
|
+
})(ValidationErrorType ||= {});
|
|
1213
|
+
var SuggestedAction;
|
|
1214
|
+
((SuggestedAction2) => {
|
|
1215
|
+
SuggestedAction2["RE_RUN"] = "RE_RUN";
|
|
1216
|
+
SuggestedAction2["CONFIRM"] = "CONFIRM";
|
|
1217
|
+
SuggestedAction2["SKIP"] = "SKIP";
|
|
1218
|
+
SuggestedAction2["PROVIDE_VALUE"] = "PROVIDE_VALUE";
|
|
1219
|
+
SuggestedAction2["IGNORE"] = "IGNORE";
|
|
1220
|
+
})(SuggestedAction ||= {});
|
|
1221
|
+
|
|
1222
|
+
// packages/core/src/env/workflow/utils/execution-state.ts
|
|
1223
|
+
init_decorator();
|
|
1224
|
+
class ExecutionStateBuilder {
|
|
1225
|
+
build(messages, definition) {
|
|
1226
|
+
const state = {
|
|
1227
|
+
completedNodes: new Set,
|
|
1228
|
+
inProgressNodes: new Set,
|
|
1229
|
+
pendingNodes: new Set,
|
|
1230
|
+
nodeOutputs: new Map,
|
|
1231
|
+
nodeInputs: new Map,
|
|
1232
|
+
variables: new Map,
|
|
1233
|
+
loopCounts: new Map
|
|
1234
|
+
};
|
|
1235
|
+
this.parseMessages(messages, state);
|
|
1236
|
+
this.buildPendingNodes(definition, state);
|
|
1237
|
+
return state;
|
|
1238
|
+
}
|
|
1239
|
+
parseMessages(messages, state) {
|
|
1240
|
+
let lastCallNodeId = null;
|
|
1241
|
+
let lastCallInput = null;
|
|
1242
|
+
for (const msg of messages) {
|
|
1243
|
+
const metadata = msg.metadata;
|
|
1244
|
+
const msgType = metadata?.type;
|
|
1245
|
+
switch (msgType) {
|
|
1246
|
+
case "workflow.node.call": {
|
|
1247
|
+
const nodeId = metadata?.workflowNodeId;
|
|
1248
|
+
if (nodeId) {
|
|
1249
|
+
lastCallNodeId = nodeId;
|
|
1250
|
+
lastCallInput = this.extractInput(msg);
|
|
1251
|
+
state.inProgressNodes.add(nodeId);
|
|
1252
|
+
state.nodeInputs.set(nodeId, lastCallInput);
|
|
1253
|
+
}
|
|
1254
|
+
break;
|
|
1255
|
+
}
|
|
1256
|
+
case "workflow.node.result": {
|
|
1257
|
+
if (lastCallNodeId) {
|
|
1258
|
+
state.inProgressNodes.delete(lastCallNodeId);
|
|
1259
|
+
state.completedNodes.add(lastCallNodeId);
|
|
1260
|
+
const output = this.extractOutput(msg);
|
|
1261
|
+
state.nodeOutputs.set(lastCallNodeId, output);
|
|
1262
|
+
this.extractVariables(output, state);
|
|
1263
|
+
lastCallNodeId = null;
|
|
1264
|
+
lastCallInput = null;
|
|
1265
|
+
}
|
|
1266
|
+
break;
|
|
1267
|
+
}
|
|
1268
|
+
case "workflow.node.interrupt": {
|
|
1269
|
+
if (lastCallNodeId) {
|
|
1270
|
+
state.inProgressNodes.add(lastCallNodeId);
|
|
1271
|
+
}
|
|
1272
|
+
break;
|
|
1273
|
+
}
|
|
1274
|
+
case "workflow.node.resume": {
|
|
1275
|
+
if (lastCallNodeId) {
|
|
1276
|
+
state.inProgressNodes.add(lastCallNodeId);
|
|
1277
|
+
}
|
|
1278
|
+
break;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
buildPendingNodes(definition, state) {
|
|
1284
|
+
const nodeIds = new Set((definition.nodes || []).map((n) => n.id));
|
|
1285
|
+
const allNodeIds = Array.from(nodeIds);
|
|
1286
|
+
const entryNodes = this.getEntryNodes(definition);
|
|
1287
|
+
for (const entryNode of entryNodes) {
|
|
1288
|
+
if (!state.completedNodes.has(entryNode)) {
|
|
1289
|
+
this.markPendingFromNode(entryNode, definition, state);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
for (const completedId of state.completedNodes) {
|
|
1293
|
+
const children = this.getDirectChildren(completedId, definition);
|
|
1294
|
+
for (const childId of children) {
|
|
1295
|
+
if (!state.completedNodes.has(childId) && !state.inProgressNodes.has(childId)) {
|
|
1296
|
+
state.pendingNodes.add(childId);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
getEntryNodes(definition) {
|
|
1302
|
+
const entry = definition.entry;
|
|
1303
|
+
if (!entry) {
|
|
1304
|
+
return [];
|
|
1305
|
+
}
|
|
1306
|
+
if (Array.isArray(entry)) {
|
|
1307
|
+
return entry;
|
|
1308
|
+
}
|
|
1309
|
+
return [entry];
|
|
1310
|
+
}
|
|
1311
|
+
markPendingFromNode(startNodeId, definition, state) {
|
|
1312
|
+
const visited = new Set;
|
|
1313
|
+
const queue = [startNodeId];
|
|
1314
|
+
while (queue.length > 0) {
|
|
1315
|
+
const nodeId = queue.shift();
|
|
1316
|
+
if (visited.has(nodeId)) {
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
visited.add(nodeId);
|
|
1320
|
+
if (!state.completedNodes.has(nodeId)) {
|
|
1321
|
+
state.pendingNodes.add(nodeId);
|
|
1322
|
+
}
|
|
1323
|
+
const children = this.getDirectChildren(nodeId, definition);
|
|
1324
|
+
for (const childId of children) {
|
|
1325
|
+
if (!visited.has(childId)) {
|
|
1326
|
+
queue.push(childId);
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
getDirectChildren(nodeId, definition) {
|
|
1332
|
+
const edges = definition.edges || definition.connections || [];
|
|
1333
|
+
return edges.filter((edge) => edge.source === nodeId || edge.from === nodeId).map((edge) => edge.target || edge.to);
|
|
1334
|
+
}
|
|
1335
|
+
extractInput(msg) {
|
|
1336
|
+
try {
|
|
1337
|
+
return JSON.parse(msg.content);
|
|
1338
|
+
} catch {
|
|
1339
|
+
return msg.content;
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
extractOutput(msg) {
|
|
1343
|
+
try {
|
|
1344
|
+
return JSON.parse(msg.content);
|
|
1345
|
+
} catch {
|
|
1346
|
+
return msg.content;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
extractVariables(output, state) {
|
|
1350
|
+
if (!output || typeof output !== "object") {
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
const outputObj = output;
|
|
1354
|
+
for (const [key, value] of Object.entries(outputObj)) {
|
|
1355
|
+
if (key.startsWith("_") || key.startsWith("$")) {
|
|
1356
|
+
continue;
|
|
1357
|
+
}
|
|
1358
|
+
if (!state.variables.has(key)) {
|
|
1359
|
+
state.variables.set(key, value);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
__legacyDecorateClassTS([
|
|
1365
|
+
TracedAs("recovery.builder.build", { recordParams: true, recordResult: true, log: true })
|
|
1366
|
+
], ExecutionStateBuilder.prototype, "build", null);
|
|
1367
|
+
__legacyDecorateClassTS([
|
|
1368
|
+
TracedAs("recovery.builder.parseMessages", { recordParams: true, recordResult: true, log: true })
|
|
1369
|
+
], ExecutionStateBuilder.prototype, "parseMessages", null);
|
|
1370
|
+
__legacyDecorateClassTS([
|
|
1371
|
+
TracedAs("recovery.builder.buildPendingNodes", { recordParams: true, recordResult: true, log: true })
|
|
1372
|
+
], ExecutionStateBuilder.prototype, "buildPendingNodes", null);
|
|
1373
|
+
|
|
1374
|
+
// packages/core/src/env/workflow/utils/recovery-validator.ts
|
|
1375
|
+
class RecoveryValidator {
|
|
1376
|
+
stateBuilder;
|
|
1377
|
+
constructor() {
|
|
1378
|
+
this.stateBuilder = new ExecutionStateBuilder;
|
|
1379
|
+
}
|
|
1380
|
+
async validate(messages, definition) {
|
|
1381
|
+
const state = this.stateBuilder.build(messages, definition);
|
|
1382
|
+
const errors = [];
|
|
1383
|
+
const warnings = [];
|
|
1384
|
+
errors.push(...this.validateStateIntegrity(state, definition));
|
|
1385
|
+
errors.push(...this.validateParallelBranches(state, definition));
|
|
1386
|
+
errors.push(...this.validateConditionBranches(state, definition));
|
|
1387
|
+
errors.push(...this.validateLoopState(state, definition));
|
|
1388
|
+
errors.push(...this.validateNestedWorkflows(state, definition));
|
|
1389
|
+
return {
|
|
1390
|
+
isValid: errors.length === 0,
|
|
1391
|
+
errors,
|
|
1392
|
+
warnings
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
async generatePlan(messages, definition) {
|
|
1396
|
+
const state = this.stateBuilder.build(messages, definition);
|
|
1397
|
+
const validationResult = await this.validate(messages, definition);
|
|
1398
|
+
const pendingNodes = Array.from(state.pendingNodes);
|
|
1399
|
+
const completedNodes = Array.from(state.completedNodes);
|
|
1400
|
+
const resumePoint = this.determineResumePoint(state, definition);
|
|
1401
|
+
const summary = this.generateSummary(state, validationResult);
|
|
1402
|
+
return {
|
|
1403
|
+
canResume: validationResult.isValid,
|
|
1404
|
+
resumePoint,
|
|
1405
|
+
completedNodes,
|
|
1406
|
+
pendingNodes,
|
|
1407
|
+
skippedNodes: [],
|
|
1408
|
+
validationErrors: validationResult.errors,
|
|
1409
|
+
summary
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
validateStateIntegrity(state, definition) {
|
|
1413
|
+
const errors = [];
|
|
1414
|
+
for (const nodeId of state.pendingNodes) {
|
|
1415
|
+
const node = definition.nodes?.find((n) => n.id === nodeId);
|
|
1416
|
+
if (!node?.config)
|
|
1417
|
+
continue;
|
|
1418
|
+
const variableRefs = this.extractVariableRefs(node.config);
|
|
1419
|
+
for (const varRef of variableRefs) {
|
|
1420
|
+
if (!state.nodeOutputs.has(varRef) && !state.variables.has(varRef)) {
|
|
1421
|
+
errors.push({
|
|
1422
|
+
type: "MISSING_VARIABLE" /* MISSING_VARIABLE */,
|
|
1423
|
+
nodeId,
|
|
1424
|
+
description: `\u53D8\u91CF ${varRef} \u4E0D\u5B58\u5728\uFF0C\u9700\u8981\u91CD\u65B0\u8FD0\u884C`,
|
|
1425
|
+
suggestedAction: "RE_RUN" /* RE_RUN */,
|
|
1426
|
+
context: { variable: varRef, nodeConfig: node.config }
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
return errors;
|
|
1432
|
+
}
|
|
1433
|
+
validateParallelBranches(state, definition) {
|
|
1434
|
+
const errors = [];
|
|
1435
|
+
const parallelGroups = this.identifyParallelGroups(definition);
|
|
1436
|
+
for (const group of parallelGroups) {
|
|
1437
|
+
const completedInGroup = group.filter((id) => state.completedNodes.has(id));
|
|
1438
|
+
const inProgressInGroup = group.filter((id) => state.inProgressNodes.has(id));
|
|
1439
|
+
if (inProgressInGroup.length > 0 || completedInGroup.length < group.length) {
|
|
1440
|
+
const mergeNode = this.findMergeNodeForParallel(group, definition);
|
|
1441
|
+
if (mergeNode && !state.completedNodes.has(mergeNode)) {
|
|
1442
|
+
const incomplete = group.filter((id) => !state.completedNodes.has(id));
|
|
1443
|
+
errors.push({
|
|
1444
|
+
type: "INCOMPLETE_PARALLEL" /* INCOMPLETE_PARALLEL */,
|
|
1445
|
+
nodeId: mergeNode,
|
|
1446
|
+
description: `\u5E76\u884C\u5206\u652F ${incomplete.join(", ")} \u672A\u5B8C\u6210`,
|
|
1447
|
+
suggestedAction: "RE_RUN" /* RE_RUN */,
|
|
1448
|
+
context: { incompleteBranches: incomplete, mergeNode }
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return errors;
|
|
1454
|
+
}
|
|
1455
|
+
validateConditionBranches(state, definition) {
|
|
1456
|
+
const errors = [];
|
|
1457
|
+
const edges = definition.edges || definition.connections || [];
|
|
1458
|
+
const conditionalEdges = edges.filter((e) => e.condition);
|
|
1459
|
+
for (const edge of conditionalEdges) {
|
|
1460
|
+
const conditionVars = this.extractVariableRefs(edge.condition);
|
|
1461
|
+
for (const varRef of conditionVars) {
|
|
1462
|
+
if (!state.nodeOutputs.has(varRef) && !state.variables.has(varRef)) {
|
|
1463
|
+
errors.push({
|
|
1464
|
+
type: "AMBIGUOUS_BRANCH" /* AMBIGUOUS_BRANCH */,
|
|
1465
|
+
nodeId: edge.target || edge.to,
|
|
1466
|
+
description: `\u6761\u4EF6\u5206\u652F\u65E0\u6CD5\u786E\u5B9A\uFF1A\u53D8\u91CF ${varRef} \u4E0D\u5B58\u5728`,
|
|
1467
|
+
suggestedAction: "CONFIRM" /* CONFIRM */,
|
|
1468
|
+
context: { variable: varRef, condition: edge.condition }
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
return errors;
|
|
1474
|
+
}
|
|
1475
|
+
validateLoopState(state, definition) {
|
|
1476
|
+
const errors = [];
|
|
1477
|
+
const loops = this.identifyLoops(definition);
|
|
1478
|
+
for (const loop of loops) {
|
|
1479
|
+
const loopCounter = `loop_count_${loop.header}`;
|
|
1480
|
+
if (!state.nodeOutputs.has(loopCounter) && state.pendingNodes.has(loop.header)) {
|
|
1481
|
+
errors.push({
|
|
1482
|
+
type: "LOOP_STATE_LOST" /* LOOP_STATE_LOST */,
|
|
1483
|
+
nodeId: loop.header,
|
|
1484
|
+
description: `\u5FAA\u73AF\u72B6\u6001\u4E22\u5931\uFF0C\u5FAA\u73AF\u8BA1\u6570\u5668 ${loopCounter} \u4E0D\u5B58\u5728`,
|
|
1485
|
+
suggestedAction: "RE_RUN" /* RE_RUN */,
|
|
1486
|
+
context: { loopHeader: loop.header }
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
return errors;
|
|
1491
|
+
}
|
|
1492
|
+
validateNestedWorkflows(state, definition) {
|
|
1493
|
+
const errors = [];
|
|
1494
|
+
const workflowNodes = (definition.nodes || []).filter((n) => n.type === "workflow");
|
|
1495
|
+
for (const node of workflowNodes) {
|
|
1496
|
+
const nodeOutput = state.nodeOutputs.get(node.id);
|
|
1497
|
+
const subSessionId = nodeOutput?.sessionId;
|
|
1498
|
+
if (subSessionId && state.pendingNodes.has(node.id)) {}
|
|
1499
|
+
}
|
|
1500
|
+
return errors;
|
|
1501
|
+
}
|
|
1502
|
+
extractVariableRefs(obj) {
|
|
1503
|
+
const refs = [];
|
|
1504
|
+
if (!obj)
|
|
1505
|
+
return refs;
|
|
1506
|
+
const str = JSON.stringify(obj);
|
|
1507
|
+
const regex = /\{\{([^}]+)\}\}/g;
|
|
1508
|
+
let match;
|
|
1509
|
+
while ((match = regex.exec(str)) !== null) {
|
|
1510
|
+
refs.push(match[1].trim());
|
|
1511
|
+
}
|
|
1512
|
+
return refs;
|
|
1513
|
+
}
|
|
1514
|
+
identifyParallelGroups(definition) {
|
|
1515
|
+
const groups = [];
|
|
1516
|
+
const sources = new Map;
|
|
1517
|
+
const edges = definition.edges || definition.connections || [];
|
|
1518
|
+
for (const edge of edges) {
|
|
1519
|
+
const source = edge.source || edge.from;
|
|
1520
|
+
const target = edge.target || edge.to;
|
|
1521
|
+
const targets = sources.get(source) || [];
|
|
1522
|
+
targets.push(target);
|
|
1523
|
+
sources.set(source, targets);
|
|
1524
|
+
}
|
|
1525
|
+
for (const [_source, targets] of sources) {
|
|
1526
|
+
if (targets.length > 1) {
|
|
1527
|
+
groups.push(targets);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
return groups;
|
|
1531
|
+
}
|
|
1532
|
+
findMergeNodeForParallel(parallelIds, definition) {
|
|
1533
|
+
const edges = definition.edges || definition.connections || [];
|
|
1534
|
+
for (const edge of edges) {
|
|
1535
|
+
const target = edge.target || edge.to;
|
|
1536
|
+
const source = edge.source || edge.from;
|
|
1537
|
+
const allSourcesFromParallel = parallelIds.includes(source);
|
|
1538
|
+
const hasIncomingFromParallel = parallelIds.some((id) => edges.some((e) => (e.source || e.from) === id && (e.target || e.to) === target));
|
|
1539
|
+
if (allSourcesFromParallel && hasIncomingFromParallel) {
|
|
1540
|
+
return target;
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
return null;
|
|
1544
|
+
}
|
|
1545
|
+
identifyLoops(definition) {
|
|
1546
|
+
const loops = [];
|
|
1547
|
+
const visited = new Set;
|
|
1548
|
+
const recStack = new Set;
|
|
1549
|
+
const edges = definition.edges || definition.connections || [];
|
|
1550
|
+
const getChildren = (nodeId) => {
|
|
1551
|
+
return edges.filter((e) => (e.source || e.from) === nodeId).map((e) => e.target || e.to);
|
|
1552
|
+
};
|
|
1553
|
+
const dfs = (nodeId, path) => {
|
|
1554
|
+
visited.add(nodeId);
|
|
1555
|
+
recStack.add(nodeId);
|
|
1556
|
+
const outgoing = getChildren(nodeId);
|
|
1557
|
+
for (const childId of outgoing) {
|
|
1558
|
+
if (!visited.has(childId)) {
|
|
1559
|
+
dfs(childId, [...path, childId]);
|
|
1560
|
+
} else if (recStack.has(childId)) {
|
|
1561
|
+
const loopStart = path.indexOf(childId);
|
|
1562
|
+
if (loopStart !== -1) {
|
|
1563
|
+
loops.push({
|
|
1564
|
+
header: childId,
|
|
1565
|
+
body: path.slice(loopStart)
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
recStack.delete(nodeId);
|
|
1571
|
+
};
|
|
1572
|
+
for (const node of definition.nodes || []) {
|
|
1573
|
+
if (!visited.has(node.id)) {
|
|
1574
|
+
dfs(node.id, [node.id]);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
return loops;
|
|
1578
|
+
}
|
|
1579
|
+
determineResumePoint(state, definition) {
|
|
1580
|
+
const inProgress = Array.from(state.inProgressNodes);
|
|
1581
|
+
if (inProgress.length > 0) {
|
|
1582
|
+
return inProgress[0];
|
|
1583
|
+
}
|
|
1584
|
+
const pending = Array.from(state.pendingNodes);
|
|
1585
|
+
if (pending.length > 0) {
|
|
1586
|
+
return pending[0];
|
|
1587
|
+
}
|
|
1588
|
+
const entry = definition.entry;
|
|
1589
|
+
if (Array.isArray(entry)) {
|
|
1590
|
+
return entry[0] || "";
|
|
1591
|
+
}
|
|
1592
|
+
return entry || "";
|
|
1593
|
+
}
|
|
1594
|
+
generateSummary(state, result) {
|
|
1595
|
+
if (result.isValid) {
|
|
1596
|
+
return `\u6062\u590D\u9A8C\u8BC1\u901A\u8FC7\u3002\u5DF2\u5B8C\u6210 ${state.completedNodes.size} \u4E2A\u8282\u70B9\uFF0C\u5F85\u6267\u884C ${state.pendingNodes.size} \u4E2A\u8282\u70B9\u3002`;
|
|
1597
|
+
}
|
|
1598
|
+
const errorTypes = result.errors.map((e) => e.type).join(", ");
|
|
1599
|
+
return `\u6062\u590D\u9A8C\u8BC1\u5931\u8D25\uFF1A${errorTypes}\u3002${result.errors.length} \u4E2A\u9519\u8BEF\u9700\u8981\u5904\u7406\u3002`;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
__legacyDecorateClassTS([
|
|
1603
|
+
TracedAs("recovery.validator.validate", { recordParams: true, recordResult: true, log: true })
|
|
1604
|
+
], RecoveryValidator.prototype, "validate", null);
|
|
1605
|
+
__legacyDecorateClassTS([
|
|
1606
|
+
TracedAs("recovery.generate.plan", { recordParams: true, recordResult: true, log: true })
|
|
1607
|
+
], RecoveryValidator.prototype, "generatePlan", null);
|
|
1608
|
+
__legacyDecorateClassTS([
|
|
1609
|
+
TracedAs("recovery.validator.validateStateIntegrity", { recordParams: true, recordResult: true, log: true })
|
|
1610
|
+
], RecoveryValidator.prototype, "validateStateIntegrity", null);
|
|
1611
|
+
__legacyDecorateClassTS([
|
|
1612
|
+
TracedAs("recovery.validator.validateParallel", { recordParams: true, recordResult: true, log: true })
|
|
1613
|
+
], RecoveryValidator.prototype, "validateParallelBranches", null);
|
|
1614
|
+
__legacyDecorateClassTS([
|
|
1615
|
+
TracedAs("recovery.validator.validateCondition", { recordParams: true, recordResult: true, log: true })
|
|
1616
|
+
], RecoveryValidator.prototype, "validateConditionBranches", null);
|
|
1617
|
+
__legacyDecorateClassTS([
|
|
1618
|
+
TracedAs("recovery.validator.validateLoop", { recordParams: true, recordResult: true, log: true })
|
|
1619
|
+
], RecoveryValidator.prototype, "validateLoopState", null);
|
|
1620
|
+
__legacyDecorateClassTS([
|
|
1621
|
+
TracedAs("recovery.validator.validateNested", { recordParams: true, recordResult: true, log: true })
|
|
1622
|
+
], RecoveryValidator.prototype, "validateNestedWorkflows", null);
|
|
1623
|
+
export {
|
|
1624
|
+
resolveTemplates,
|
|
1625
|
+
resolveTemplateString,
|
|
1626
|
+
ValidationErrorType,
|
|
1627
|
+
TemplateResolver,
|
|
1628
|
+
SuggestedAction,
|
|
1629
|
+
RecoveryValidator,
|
|
1630
|
+
ExecutionStateBuilder
|
|
1631
|
+
};
|