@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,2107 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
function __accessProp(key) {
|
|
7
|
+
return this[key];
|
|
8
|
+
}
|
|
9
|
+
var __toCommonJS = (from) => {
|
|
10
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
11
|
+
if (entry)
|
|
12
|
+
return entry;
|
|
13
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (var key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(entry, key))
|
|
17
|
+
__defProp(entry, key, {
|
|
18
|
+
get: __accessProp.bind(from, key),
|
|
19
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
__moduleCache.set(from, entry);
|
|
23
|
+
return entry;
|
|
24
|
+
};
|
|
25
|
+
var __moduleCache;
|
|
26
|
+
var __returnValue = (v) => v;
|
|
27
|
+
function __exportSetter(name, newValue) {
|
|
28
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
29
|
+
}
|
|
30
|
+
var __export = (target, all) => {
|
|
31
|
+
for (var name in all)
|
|
32
|
+
__defProp(target, name, {
|
|
33
|
+
get: all[name],
|
|
34
|
+
enumerable: true,
|
|
35
|
+
configurable: true,
|
|
36
|
+
set: __exportSetter.bind(all, name)
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
|
|
40
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
41
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
|
|
42
|
+
r = Reflect.decorate(decorators, target, key, desc);
|
|
43
|
+
else
|
|
44
|
+
for (var i = decorators.length - 1;i >= 0; i--)
|
|
45
|
+
if (d = decorators[i])
|
|
46
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
47
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
48
|
+
};
|
|
49
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
50
|
+
var __require = import.meta.require;
|
|
51
|
+
|
|
52
|
+
// packages/core/src/env/log-trace/span-storage.ts
|
|
53
|
+
var exports_span_storage = {};
|
|
54
|
+
__export(exports_span_storage, {
|
|
55
|
+
SQLiteSpanStorage: () => SQLiteSpanStorage
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
class SQLiteSpanStorage {
|
|
59
|
+
db = null;
|
|
60
|
+
dbPath;
|
|
61
|
+
initialized = false;
|
|
62
|
+
constructor(dbPath) {
|
|
63
|
+
if (!dbPath) {
|
|
64
|
+
throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
|
|
65
|
+
}
|
|
66
|
+
if (dbPath === ":memory:") {
|
|
67
|
+
throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
|
|
68
|
+
}
|
|
69
|
+
this.dbPath = dbPath;
|
|
70
|
+
}
|
|
71
|
+
async initialize() {
|
|
72
|
+
if (this.initialized)
|
|
73
|
+
return;
|
|
74
|
+
const { Database } = __require("bun:sqlite");
|
|
75
|
+
const fs = __require("fs");
|
|
76
|
+
const path = __require("path");
|
|
77
|
+
const dir = path.dirname(this.dbPath);
|
|
78
|
+
if (!fs.existsSync(dir)) {
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
this.db = new Database(this.dbPath);
|
|
82
|
+
this.db.run("PRAGMA journal_mode=WAL");
|
|
83
|
+
this.db.run("PRAGMA busy_timeout=5000");
|
|
84
|
+
this.db.run("PRAGMA synchronous=NORMAL");
|
|
85
|
+
this.db.run(`
|
|
86
|
+
CREATE TABLE IF NOT EXISTS span (
|
|
87
|
+
span_id TEXT PRIMARY KEY,
|
|
88
|
+
trace_id TEXT NOT NULL,
|
|
89
|
+
parent_span_id TEXT,
|
|
90
|
+
name TEXT NOT NULL,
|
|
91
|
+
kind TEXT NOT NULL,
|
|
92
|
+
status TEXT NOT NULL,
|
|
93
|
+
start_time INTEGER NOT NULL,
|
|
94
|
+
end_time INTEGER,
|
|
95
|
+
attributes TEXT,
|
|
96
|
+
result TEXT,
|
|
97
|
+
error TEXT,
|
|
98
|
+
time_created INTEGER NOT NULL
|
|
99
|
+
)
|
|
100
|
+
`);
|
|
101
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
|
|
102
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
|
|
103
|
+
this.initialized = true;
|
|
104
|
+
}
|
|
105
|
+
save(span) {
|
|
106
|
+
if (!this.db)
|
|
107
|
+
return;
|
|
108
|
+
const stmt = this.db.prepare(`
|
|
109
|
+
INSERT OR REPLACE INTO span
|
|
110
|
+
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
111
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
112
|
+
`);
|
|
113
|
+
const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
|
|
114
|
+
stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, JSON.stringify(span.attributes), resultValue, span.error || null, Date.now());
|
|
115
|
+
}
|
|
116
|
+
saveBatch(spans) {
|
|
117
|
+
for (const span of spans) {
|
|
118
|
+
this.save(span);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
findByTraceId(traceId) {
|
|
122
|
+
if (!this.db)
|
|
123
|
+
return [];
|
|
124
|
+
const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
|
|
125
|
+
return this.buildTree(rows.map(this.rowToSpan));
|
|
126
|
+
}
|
|
127
|
+
findBySpanId(spanId) {
|
|
128
|
+
if (!this.db)
|
|
129
|
+
return;
|
|
130
|
+
const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
|
|
131
|
+
return row ? this.rowToSpan(row) : undefined;
|
|
132
|
+
}
|
|
133
|
+
listTraces(limit = 10) {
|
|
134
|
+
if (!this.db)
|
|
135
|
+
return [];
|
|
136
|
+
const rows = this.db.prepare(`
|
|
137
|
+
SELECT trace_id,
|
|
138
|
+
MIN(start_time) as start_time,
|
|
139
|
+
MAX(end_time) as end_time,
|
|
140
|
+
COUNT(*) as span_count
|
|
141
|
+
FROM span
|
|
142
|
+
GROUP BY trace_id
|
|
143
|
+
ORDER BY start_time DESC
|
|
144
|
+
LIMIT ?
|
|
145
|
+
`).all(limit);
|
|
146
|
+
return rows.map((row) => ({
|
|
147
|
+
traceId: row.trace_id,
|
|
148
|
+
rootSpanName: "unknown",
|
|
149
|
+
startTime: row.start_time,
|
|
150
|
+
endTime: row.end_time,
|
|
151
|
+
duration: row.end_time - row.start_time,
|
|
152
|
+
spanCount: row.span_count,
|
|
153
|
+
status: "ok"
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
deleteByTraceId(traceId) {
|
|
157
|
+
if (this.db) {
|
|
158
|
+
this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
close() {
|
|
162
|
+
if (this.db) {
|
|
163
|
+
this.db.close();
|
|
164
|
+
this.db = null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
rowToSpan(row) {
|
|
168
|
+
return {
|
|
169
|
+
traceId: row.trace_id,
|
|
170
|
+
spanId: row.span_id,
|
|
171
|
+
parentSpanId: row.parent_span_id,
|
|
172
|
+
name: row.name,
|
|
173
|
+
kind: row.kind,
|
|
174
|
+
status: row.status,
|
|
175
|
+
startTime: row.start_time,
|
|
176
|
+
endTime: row.end_time,
|
|
177
|
+
attributes: row.attributes ? JSON.parse(row.attributes) : {},
|
|
178
|
+
result: row.result || undefined,
|
|
179
|
+
error: row.error || undefined
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
buildTree(spans) {
|
|
183
|
+
const spanMap = new Map;
|
|
184
|
+
const roots = [];
|
|
185
|
+
for (const span of spans) {
|
|
186
|
+
spanMap.set(span.spanId, { ...span, children: [] });
|
|
187
|
+
}
|
|
188
|
+
for (const span of spanMap.values()) {
|
|
189
|
+
if (span.parentSpanId) {
|
|
190
|
+
const parent = spanMap.get(span.parentSpanId);
|
|
191
|
+
if (parent) {
|
|
192
|
+
parent.children.push(span);
|
|
193
|
+
} else {
|
|
194
|
+
roots.push(span);
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
roots.push(span);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return roots;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// packages/core/src/env/log-trace/opentelemetry/propagation.ts
|
|
205
|
+
function padLeft(str, length) {
|
|
206
|
+
return str.padStart(length, "0");
|
|
207
|
+
}
|
|
208
|
+
function isValidHex(str) {
|
|
209
|
+
return /^[0-9a-f]+$/i.test(str);
|
|
210
|
+
}
|
|
211
|
+
function serialize(context) {
|
|
212
|
+
const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);
|
|
213
|
+
const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
|
|
214
|
+
const parts = [
|
|
215
|
+
TRACE_CONTEXT_VERSION,
|
|
216
|
+
traceId,
|
|
217
|
+
spanId,
|
|
218
|
+
TRACE_FLAGS_SAMPLED
|
|
219
|
+
];
|
|
220
|
+
return parts.join("-");
|
|
221
|
+
}
|
|
222
|
+
function parse(traceparent) {
|
|
223
|
+
if (!traceparent || typeof traceparent !== "string") {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const trimmed = traceparent.trim();
|
|
227
|
+
const parts = trimmed.split("-");
|
|
228
|
+
if (parts.length !== 4) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const [version, traceId, senderSpanId, flags] = parts;
|
|
232
|
+
if (version !== TRACE_CONTEXT_VERSION) {
|
|
233
|
+
if (version > TRACE_CONTEXT_VERSION) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
traceId: traceId.toLowerCase(),
|
|
248
|
+
spanId: senderSpanId.toLowerCase()
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
var TRACE_CONTEXT_VERSION = "00", TRACE_FLAGS_SAMPLED = "01", TRACEPARENT_HEADER = "TRACEPARENT", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;
|
|
252
|
+
var init_propagation = __esm(() => {
|
|
253
|
+
propagation = {
|
|
254
|
+
inject(carrier, context) {
|
|
255
|
+
carrier[TRACEPARENT_HEADER] = serialize(context);
|
|
256
|
+
},
|
|
257
|
+
extract(carrier) {
|
|
258
|
+
const traceparent = carrier[TRACEPARENT_HEADER];
|
|
259
|
+
if (!traceparent) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
return parse(traceparent);
|
|
263
|
+
},
|
|
264
|
+
getTraceparentHeader() {
|
|
265
|
+
return TRACEPARENT_HEADER;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// packages/core/src/env/log-trace/types.ts
|
|
271
|
+
var SpanKind, SpanStatus;
|
|
272
|
+
var init_types = __esm(() => {
|
|
273
|
+
((SpanKind2) => {
|
|
274
|
+
SpanKind2["CLIENT"] = "client";
|
|
275
|
+
SpanKind2["SERVER"] = "server";
|
|
276
|
+
SpanKind2["INTERNAL"] = "internal";
|
|
277
|
+
})(SpanKind ||= {});
|
|
278
|
+
((SpanStatus2) => {
|
|
279
|
+
SpanStatus2["OK"] = "ok";
|
|
280
|
+
SpanStatus2["ERROR"] = "error";
|
|
281
|
+
})(SpanStatus ||= {});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// packages/core/src/env/log-trace/opentelemetry/tracer-provider.ts
|
|
285
|
+
var exports_tracer_provider = {};
|
|
286
|
+
__export(exports_tracer_provider, {
|
|
287
|
+
resetTracerProvider: () => resetTracerProvider,
|
|
288
|
+
getTracerProvider: () => getTracerProvider,
|
|
289
|
+
OTelTracerProvider: () => OTelTracerProvider
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
class OTelSpanImpl {
|
|
293
|
+
name;
|
|
294
|
+
kind;
|
|
295
|
+
spanContext;
|
|
296
|
+
attributes = {};
|
|
297
|
+
startTime;
|
|
298
|
+
endTime;
|
|
299
|
+
error;
|
|
300
|
+
storage;
|
|
301
|
+
parentSpanContext;
|
|
302
|
+
onEnd;
|
|
303
|
+
constructor(name, spanContext, storage, parentSpanContext, onEnd) {
|
|
304
|
+
this.name = name;
|
|
305
|
+
this.kind = "internal";
|
|
306
|
+
this.spanContext = spanContext;
|
|
307
|
+
this.parentSpanContext = parentSpanContext;
|
|
308
|
+
this.startTime = Date.now();
|
|
309
|
+
this.storage = storage;
|
|
310
|
+
this.onEnd = onEnd;
|
|
311
|
+
}
|
|
312
|
+
setAttribute(key, value) {
|
|
313
|
+
this.attributes[key] = value;
|
|
314
|
+
}
|
|
315
|
+
addEvent(name, attributes) {
|
|
316
|
+
const events = this.attributes._events || [];
|
|
317
|
+
events.push({ name, attributes });
|
|
318
|
+
this.attributes._events = events;
|
|
319
|
+
}
|
|
320
|
+
end(result, error) {
|
|
321
|
+
this.endTime = Date.now();
|
|
322
|
+
if (error) {
|
|
323
|
+
this.error = error.message;
|
|
324
|
+
}
|
|
325
|
+
this.storage.save({
|
|
326
|
+
traceId: this.spanContext.traceId,
|
|
327
|
+
spanId: this.spanContext.spanId,
|
|
328
|
+
parentSpanId: this.spanContext.parentSpanId,
|
|
329
|
+
name: this.name,
|
|
330
|
+
kind: this.kind,
|
|
331
|
+
status: error ? "error" /* ERROR */ : "ok" /* OK */,
|
|
332
|
+
startTime: this.startTime,
|
|
333
|
+
endTime: this.endTime,
|
|
334
|
+
attributes: this.attributes,
|
|
335
|
+
result,
|
|
336
|
+
error: this.error
|
|
337
|
+
});
|
|
338
|
+
this.onEnd?.();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
class OTelTracerImpl {
|
|
343
|
+
name;
|
|
344
|
+
version;
|
|
345
|
+
storage;
|
|
346
|
+
currentContext;
|
|
347
|
+
activeSpans = new Map;
|
|
348
|
+
onSpanEndCallback;
|
|
349
|
+
provider;
|
|
350
|
+
constructor(name, version, storage, provider) {
|
|
351
|
+
this.name = name;
|
|
352
|
+
this.version = version;
|
|
353
|
+
this.storage = storage;
|
|
354
|
+
this.provider = provider;
|
|
355
|
+
}
|
|
356
|
+
setOnSpanEndCallback(callback) {
|
|
357
|
+
this.onSpanEndCallback = callback;
|
|
358
|
+
}
|
|
359
|
+
getActiveSpanCount() {
|
|
360
|
+
return this.activeSpans.size;
|
|
361
|
+
}
|
|
362
|
+
startSpan(name, options) {
|
|
363
|
+
const parentFromOptions = options?.parent;
|
|
364
|
+
const hasExplicitParent = options && "parent" in options;
|
|
365
|
+
const globalContext = this.provider.getGlobalContext();
|
|
366
|
+
let effectiveParentContext;
|
|
367
|
+
if (hasExplicitParent) {
|
|
368
|
+
effectiveParentContext = parentFromOptions;
|
|
369
|
+
} else if (this.currentContext) {
|
|
370
|
+
effectiveParentContext = this.currentContext;
|
|
371
|
+
} else if (globalContext) {
|
|
372
|
+
effectiveParentContext = globalContext;
|
|
373
|
+
}
|
|
374
|
+
const traceId = effectiveParentContext?.traceId || this.generateTraceId();
|
|
375
|
+
const spanId = this.generateSpanId();
|
|
376
|
+
let parentSpanId;
|
|
377
|
+
if (hasExplicitParent && parentFromOptions) {
|
|
378
|
+
parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;
|
|
379
|
+
} else if (this.currentContext) {
|
|
380
|
+
parentSpanId = this.currentContext.spanId;
|
|
381
|
+
} else if (globalContext) {
|
|
382
|
+
parentSpanId = globalContext.spanId;
|
|
383
|
+
}
|
|
384
|
+
const spanContext = {
|
|
385
|
+
traceId,
|
|
386
|
+
spanId,
|
|
387
|
+
parentSpanId
|
|
388
|
+
};
|
|
389
|
+
this.currentContext = {
|
|
390
|
+
traceId,
|
|
391
|
+
spanId,
|
|
392
|
+
parentSpanId
|
|
393
|
+
};
|
|
394
|
+
const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));
|
|
395
|
+
if (options?.attributes) {
|
|
396
|
+
for (const [key, value] of Object.entries(options.attributes)) {
|
|
397
|
+
span.setAttribute(key, value);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.activeSpans.set(spanId, span);
|
|
401
|
+
return span;
|
|
402
|
+
}
|
|
403
|
+
injectToEnv(env) {
|
|
404
|
+
if (this.currentContext) {
|
|
405
|
+
propagation.inject(env, this.currentContext);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
getCurrentContext() {
|
|
409
|
+
return this.currentContext;
|
|
410
|
+
}
|
|
411
|
+
setCurrentContext(context) {
|
|
412
|
+
this.currentContext = context;
|
|
413
|
+
}
|
|
414
|
+
endSpan(span) {
|
|
415
|
+
const spanContext = span.spanContext;
|
|
416
|
+
this.activeSpans.delete(spanContext.spanId);
|
|
417
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
418
|
+
if (spanContext.parentSpanId) {
|
|
419
|
+
const parentSpan = this.activeSpans.get(spanContext.parentSpanId);
|
|
420
|
+
if (parentSpan) {
|
|
421
|
+
const parentContext = {
|
|
422
|
+
traceId: spanContext.traceId,
|
|
423
|
+
spanId: parentSpan.spanContext.spanId,
|
|
424
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
425
|
+
};
|
|
426
|
+
this.currentContext = parentContext;
|
|
427
|
+
return parentContext;
|
|
428
|
+
}
|
|
429
|
+
if (currentTraceId) {
|
|
430
|
+
const parentContext = {
|
|
431
|
+
traceId: currentTraceId,
|
|
432
|
+
spanId: spanContext.parentSpanId,
|
|
433
|
+
parentSpanId: undefined
|
|
434
|
+
};
|
|
435
|
+
this.currentContext = parentContext;
|
|
436
|
+
return parentContext;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
this.currentContext = undefined;
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
generateTraceId() {
|
|
443
|
+
const timestamp = Date.now().toString(16).padStart(12, "0");
|
|
444
|
+
const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")).join("");
|
|
445
|
+
return (timestamp + random).slice(0, 32).padStart(32, "0");
|
|
446
|
+
}
|
|
447
|
+
generateSpanId() {
|
|
448
|
+
return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
|
|
449
|
+
}
|
|
450
|
+
handleSpanEnd(spanId, parentSpanId) {
|
|
451
|
+
this.activeSpans.delete(spanId);
|
|
452
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
453
|
+
if (parentSpanId) {
|
|
454
|
+
const parentSpan = this.activeSpans.get(parentSpanId);
|
|
455
|
+
if (parentSpan) {
|
|
456
|
+
this.currentContext = {
|
|
457
|
+
traceId: parentSpan.spanContext.traceId,
|
|
458
|
+
spanId: parentSpan.spanContext.spanId,
|
|
459
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
460
|
+
};
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (currentTraceId) {
|
|
464
|
+
this.currentContext = {
|
|
465
|
+
traceId: currentTraceId,
|
|
466
|
+
spanId: parentSpanId,
|
|
467
|
+
parentSpanId: undefined
|
|
468
|
+
};
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
this.currentContext = undefined;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
class OTelTracerProvider {
|
|
477
|
+
tracers = new Map;
|
|
478
|
+
storage;
|
|
479
|
+
initialized = false;
|
|
480
|
+
globalContext;
|
|
481
|
+
constructor(storage, dbPath) {
|
|
482
|
+
this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());
|
|
483
|
+
}
|
|
484
|
+
async initialize() {
|
|
485
|
+
if (this.initialized)
|
|
486
|
+
return;
|
|
487
|
+
await this.storage.initialize();
|
|
488
|
+
this.initialized = true;
|
|
489
|
+
}
|
|
490
|
+
isInitialized() {
|
|
491
|
+
return this.initialized;
|
|
492
|
+
}
|
|
493
|
+
getGlobalContext() {
|
|
494
|
+
return this.globalContext;
|
|
495
|
+
}
|
|
496
|
+
setGlobalContext(context) {
|
|
497
|
+
this.globalContext = context;
|
|
498
|
+
}
|
|
499
|
+
getTracer(name, version) {
|
|
500
|
+
const key = `${name}@${version || "0.0.0"}`;
|
|
501
|
+
let tracer = this.tracers.get(key);
|
|
502
|
+
if (!tracer) {
|
|
503
|
+
tracer = new OTelTracerImpl(name, version, this.storage, this);
|
|
504
|
+
this.tracers.set(key, tracer);
|
|
505
|
+
if (this.initialized) {
|
|
506
|
+
this.restoreFromEnv(tracer);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return tracer;
|
|
510
|
+
}
|
|
511
|
+
restoreFromEnv(tracer) {
|
|
512
|
+
const extracted = propagation.extract(process.env);
|
|
513
|
+
if (extracted) {
|
|
514
|
+
tracer.setCurrentContext({
|
|
515
|
+
traceId: extracted.traceId,
|
|
516
|
+
spanId: extracted.spanId,
|
|
517
|
+
parentSpanId: undefined
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
shutdown() {
|
|
522
|
+
for (const tracer of this.tracers.values()) {}
|
|
523
|
+
this.tracers.clear();
|
|
524
|
+
this.storage.close();
|
|
525
|
+
this.initialized = false;
|
|
526
|
+
this.globalContext = undefined;
|
|
527
|
+
delete process.env["TRACEPARENT"];
|
|
528
|
+
delete process.env["TRACE_ID"];
|
|
529
|
+
delete process.env["LOG_TRACE_REQUEST_ID"];
|
|
530
|
+
}
|
|
531
|
+
getStorage() {
|
|
532
|
+
return this.storage;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function getTracerProvider() {
|
|
536
|
+
if (!providerInstance) {
|
|
537
|
+
providerInstance = new OTelTracerProvider;
|
|
538
|
+
}
|
|
539
|
+
return providerInstance;
|
|
540
|
+
}
|
|
541
|
+
function resetTracerProvider() {
|
|
542
|
+
if (providerInstance) {
|
|
543
|
+
providerInstance.shutdown();
|
|
544
|
+
providerInstance = null;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function getDefaultDbPath() {
|
|
548
|
+
const os = __require("os");
|
|
549
|
+
const path = __require("path");
|
|
550
|
+
const home = os.homedir();
|
|
551
|
+
const dataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
552
|
+
return path.join(dataHome, "roy-agent", "traces.db");
|
|
553
|
+
}
|
|
554
|
+
var providerInstance = null;
|
|
555
|
+
var init_tracer_provider = __esm(() => {
|
|
556
|
+
init_propagation();
|
|
557
|
+
init_types();
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// packages/core/src/env/log-trace/logger.ts
|
|
561
|
+
import { appendFileSync, existsSync, mkdirSync } from "fs";
|
|
562
|
+
import { join } from "path";
|
|
563
|
+
function simplifyFilePath(fullPath) {
|
|
564
|
+
let path = fullPath.replace(/\\/g, "/");
|
|
565
|
+
const bunfsMatch = path.match(/\/\$bunfs\/root\/(.+)$/);
|
|
566
|
+
if (bunfsMatch) {
|
|
567
|
+
const virtualPath = bunfsMatch[1];
|
|
568
|
+
const packagesMatch = virtualPath.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
569
|
+
if (packagesMatch) {
|
|
570
|
+
return packagesMatch[1];
|
|
571
|
+
}
|
|
572
|
+
return virtualPath;
|
|
573
|
+
}
|
|
574
|
+
const fileProtocolMatch = path.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);
|
|
575
|
+
if (fileProtocolMatch) {
|
|
576
|
+
const rootPkg = fileProtocolMatch[1].replace(/\+/g, "/");
|
|
577
|
+
const remaining = fileProtocolMatch[2];
|
|
578
|
+
const prefix = rootPkg;
|
|
579
|
+
const suffix = remaining.startsWith("src/") ? remaining : `src/${remaining}`;
|
|
580
|
+
return `${prefix}/${suffix}`;
|
|
581
|
+
}
|
|
582
|
+
const packagesRootMatch = path.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
583
|
+
if (packagesRootMatch) {
|
|
584
|
+
return packagesRootMatch[1];
|
|
585
|
+
}
|
|
586
|
+
const rootMarkers = ["packages/core/src", "packages/core", "packages"];
|
|
587
|
+
for (const marker of rootMarkers) {
|
|
588
|
+
const idx = path.indexOf(marker);
|
|
589
|
+
if (idx !== -1) {
|
|
590
|
+
return path.substring(idx);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return path;
|
|
594
|
+
}
|
|
595
|
+
function getDefaultLogDir() {
|
|
596
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
597
|
+
try {
|
|
598
|
+
const xdg = __require("xdg-basedir");
|
|
599
|
+
if (xdg.xdgData) {
|
|
600
|
+
return join(xdg.xdgData, "roy-agent", "logs");
|
|
601
|
+
}
|
|
602
|
+
} catch {}
|
|
603
|
+
return join(home, ".local", "share", "roy-agent", "logs");
|
|
604
|
+
}
|
|
605
|
+
function isQuietMode() {
|
|
606
|
+
return quietMode;
|
|
607
|
+
}
|
|
608
|
+
function setQuietMode(enabled) {
|
|
609
|
+
quietMode = enabled;
|
|
610
|
+
}
|
|
611
|
+
function setConfigComponent(component) {
|
|
612
|
+
configComponentInstance = component;
|
|
613
|
+
}
|
|
614
|
+
function getLogLevel() {
|
|
615
|
+
if (configComponentInstance) {
|
|
616
|
+
const level = configComponentInstance.get("log_trace.logging.level");
|
|
617
|
+
if (level && ["debug", "info", "warn", "error"].includes(level)) {
|
|
618
|
+
return level;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const envLevel = process.env.LOG_LEVEL;
|
|
622
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
623
|
+
return envLevel;
|
|
624
|
+
}
|
|
625
|
+
return "info";
|
|
626
|
+
}
|
|
627
|
+
function getCategoryLogLevel(category) {
|
|
628
|
+
if (configComponentInstance) {
|
|
629
|
+
const levels = configComponentInstance.get("log_trace.logging.levels");
|
|
630
|
+
if (levels && typeof levels === "object") {
|
|
631
|
+
const categoryLevel = levels[category];
|
|
632
|
+
if (categoryLevel && ["debug", "info", "warn", "error"].includes(categoryLevel)) {
|
|
633
|
+
return categoryLevel;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);
|
|
637
|
+
if (directLevel && ["debug", "info", "warn", "error"].includes(directLevel)) {
|
|
638
|
+
return directLevel;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, "_")}`;
|
|
642
|
+
const envLevel = process.env[envKey];
|
|
643
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
644
|
+
return envLevel;
|
|
645
|
+
}
|
|
646
|
+
return getLogLevel();
|
|
647
|
+
}
|
|
648
|
+
function isAbsolutePath(path) {
|
|
649
|
+
if (path.startsWith("/")) {
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
if (/^[a-zA-Z]:[/\\]/.test(path)) {
|
|
653
|
+
return true;
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
function expandHomeDir(path) {
|
|
658
|
+
if (path.startsWith("~")) {
|
|
659
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
660
|
+
return join(home, path.slice(1));
|
|
661
|
+
}
|
|
662
|
+
return path;
|
|
663
|
+
}
|
|
664
|
+
function getLogFile() {
|
|
665
|
+
if (configComponentInstance) {
|
|
666
|
+
const file = configComponentInstance.get("log_trace.logging.file");
|
|
667
|
+
if (file) {
|
|
668
|
+
return file;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
return "app.log";
|
|
672
|
+
}
|
|
673
|
+
function getLogDir() {
|
|
674
|
+
if (configComponentInstance) {
|
|
675
|
+
const dir = configComponentInstance.get("log_trace.logging.dir");
|
|
676
|
+
if (dir) {
|
|
677
|
+
return dir;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
return getDefaultLogDir();
|
|
681
|
+
}
|
|
682
|
+
function getMaxOutput() {
|
|
683
|
+
if (configComponentInstance) {
|
|
684
|
+
const maxOutput = configComponentInstance.get("log-trace.logging.maxOutput");
|
|
685
|
+
if (typeof maxOutput === "number") {
|
|
686
|
+
return maxOutput;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
function setLogDirOverride(dir) {
|
|
692
|
+
logDirOverride = dir;
|
|
693
|
+
}
|
|
694
|
+
function getLogDirOverride() {
|
|
695
|
+
return logDirOverride;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
class Logger {
|
|
699
|
+
prefix;
|
|
700
|
+
constructor(prefix) {
|
|
701
|
+
this.prefix = prefix;
|
|
702
|
+
}
|
|
703
|
+
shouldLog(level) {
|
|
704
|
+
const categoryLevel = getCategoryLogLevel(this.prefix);
|
|
705
|
+
return levelPriority[level] >= levelPriority[categoryLevel];
|
|
706
|
+
}
|
|
707
|
+
ensureLogDirectory(dir) {
|
|
708
|
+
if (!existsSync(dir)) {
|
|
709
|
+
try {
|
|
710
|
+
mkdirSync(dir, { recursive: true });
|
|
711
|
+
} catch (err) {
|
|
712
|
+
console.error("[Logger] Failed to create log directory:", dir, err);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
getCallerLocation() {
|
|
717
|
+
const originalLimit = Error.stackTraceLimit;
|
|
718
|
+
Error.stackTraceLimit = 10;
|
|
719
|
+
const err = new Error;
|
|
720
|
+
Error.captureStackTrace(err, this.formatMessage);
|
|
721
|
+
const stack = err.stack?.split(`
|
|
722
|
+
`) || [];
|
|
723
|
+
Error.stackTraceLimit = originalLimit;
|
|
724
|
+
for (let i = 1;i < stack.length; i++) {
|
|
725
|
+
const line = stack[i];
|
|
726
|
+
if (line.includes("at ") && !line.includes("logger.ts") && !line.includes("formatMessage")) {
|
|
727
|
+
const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
|
|
728
|
+
if (match) {
|
|
729
|
+
const filePath = match[1];
|
|
730
|
+
const relativePath = this.getRelativePath(filePath);
|
|
731
|
+
return {
|
|
732
|
+
file: relativePath,
|
|
733
|
+
line: parseInt(match[2], 10)
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
getRelativePath(fullPath) {
|
|
741
|
+
return simplifyFilePath(fullPath);
|
|
742
|
+
}
|
|
743
|
+
formatMessage(level, message, data) {
|
|
744
|
+
const now = new Date;
|
|
745
|
+
const timestamp = now.toLocaleString("zh-CN", {
|
|
746
|
+
timeZone: "Asia/Shanghai",
|
|
747
|
+
year: "numeric",
|
|
748
|
+
month: "2-digit",
|
|
749
|
+
day: "2-digit",
|
|
750
|
+
hour: "2-digit",
|
|
751
|
+
minute: "2-digit",
|
|
752
|
+
second: "2-digit",
|
|
753
|
+
hour12: false
|
|
754
|
+
}).replace(/\//g, "-") + "." + String(now.getMilliseconds()).padStart(3, "0");
|
|
755
|
+
const prefix = this.prefix ? `[${this.prefix}]` : "";
|
|
756
|
+
let traceIdStr = "";
|
|
757
|
+
try {
|
|
758
|
+
const provider = getTracerProvider();
|
|
759
|
+
const tracer = provider.getTracer("roy-tracer");
|
|
760
|
+
const context = tracer.getCurrentContext();
|
|
761
|
+
if (context?.traceId) {
|
|
762
|
+
traceIdStr = `[traceId=${context.traceId}]`;
|
|
763
|
+
}
|
|
764
|
+
} catch {}
|
|
765
|
+
let locationStr = "";
|
|
766
|
+
if (data && typeof data === "object" && "callerLocation" in data) {
|
|
767
|
+
const logData = data;
|
|
768
|
+
locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : "";
|
|
769
|
+
const { callerLocation: _callerLocation, ...rest } = logData;
|
|
770
|
+
data = Object.keys(rest).length > 0 ? rest : undefined;
|
|
771
|
+
} else {
|
|
772
|
+
const location = this.getCallerLocation();
|
|
773
|
+
if (location) {
|
|
774
|
+
locationStr = ` [${location.file}:${location.line}]`;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;
|
|
778
|
+
if (data !== undefined) {
|
|
779
|
+
if (typeof data === "object") {
|
|
780
|
+
formatted += " " + JSON.stringify(data).replace(/\n/g, "");
|
|
781
|
+
} else {
|
|
782
|
+
formatted += " " + String(data);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const maxOutput = getMaxOutput();
|
|
786
|
+
if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {
|
|
787
|
+
formatted = formatted.substring(0, maxOutput) + " [TRUNCATED]";
|
|
788
|
+
}
|
|
789
|
+
return formatted;
|
|
790
|
+
}
|
|
791
|
+
writeToFile(message) {
|
|
792
|
+
try {
|
|
793
|
+
const dir = getLogDir();
|
|
794
|
+
const filename = getLogFile();
|
|
795
|
+
const expandedDir = expandHomeDir(dir);
|
|
796
|
+
const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);
|
|
797
|
+
this.ensureLogDirectory(resolvedDir);
|
|
798
|
+
const logFile = join(resolvedDir, filename);
|
|
799
|
+
appendFileSync(logFile, message + `
|
|
800
|
+
`, "utf-8");
|
|
801
|
+
} catch (err) {
|
|
802
|
+
console.error("[Logger] Failed to write to log file:", err);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
log(level, message, data) {
|
|
806
|
+
if (!this.shouldLog(level))
|
|
807
|
+
return;
|
|
808
|
+
const formatted = this.formatMessage(level, message, data);
|
|
809
|
+
this.writeToFile(formatted);
|
|
810
|
+
if (!isQuietMode()) {
|
|
811
|
+
const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.log : console.debug;
|
|
812
|
+
consoleMethod(formatted);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
debug(message, data) {
|
|
816
|
+
this.log("debug", message, data);
|
|
817
|
+
}
|
|
818
|
+
info(message, data) {
|
|
819
|
+
this.log("info", message, data);
|
|
820
|
+
}
|
|
821
|
+
warn(message, data) {
|
|
822
|
+
this.log("warn", message, data);
|
|
823
|
+
}
|
|
824
|
+
error(message, data) {
|
|
825
|
+
this.log("error", message, data);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function createLogger(prefix) {
|
|
829
|
+
if (!loggerCache.has(prefix)) {
|
|
830
|
+
loggerCache.set(prefix, new Logger(prefix));
|
|
831
|
+
}
|
|
832
|
+
return loggerCache.get(prefix);
|
|
833
|
+
}
|
|
834
|
+
function getLogLevels() {
|
|
835
|
+
return ["debug", "info", "warn", "error"];
|
|
836
|
+
}
|
|
837
|
+
var configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;
|
|
838
|
+
var init_logger = __esm(() => {
|
|
839
|
+
init_tracer_provider();
|
|
840
|
+
levelPriority = {
|
|
841
|
+
debug: 0,
|
|
842
|
+
info: 1,
|
|
843
|
+
warn: 2,
|
|
844
|
+
error: 3
|
|
845
|
+
};
|
|
846
|
+
loggerCache = new Map;
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
// packages/core/src/env/hook/types.ts
|
|
850
|
+
function createHook(meta, fn) {
|
|
851
|
+
return {
|
|
852
|
+
...meta,
|
|
853
|
+
execute: fn
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function createPriorityHook(name, fn, priority) {
|
|
857
|
+
return createHook({ name, priority }, fn);
|
|
858
|
+
}
|
|
859
|
+
// packages/core/src/env/hook/hook-manager.ts
|
|
860
|
+
class HookManager {
|
|
861
|
+
_hooks = new Map;
|
|
862
|
+
componentName;
|
|
863
|
+
componentVersion;
|
|
864
|
+
defaultPriority;
|
|
865
|
+
constructor(options = {}) {
|
|
866
|
+
this.componentName = options.componentName ?? "unknown";
|
|
867
|
+
this.componentVersion = options.componentVersion ?? "0.0.0";
|
|
868
|
+
this.defaultPriority = options.defaultPriority ?? 0;
|
|
869
|
+
}
|
|
870
|
+
register(hookPoint, hook) {
|
|
871
|
+
const hooks = this.getOrCreateHooks(hookPoint);
|
|
872
|
+
hooks.push(hook);
|
|
873
|
+
}
|
|
874
|
+
registerMany(hookPoint, hooks) {
|
|
875
|
+
const hookList = this.getOrCreateHooks(hookPoint);
|
|
876
|
+
hookList.push(...hooks);
|
|
877
|
+
}
|
|
878
|
+
unregister(hookPoint, name) {
|
|
879
|
+
const hooks = this._hooks.get(hookPoint);
|
|
880
|
+
if (!hooks)
|
|
881
|
+
return false;
|
|
882
|
+
const index = hooks.findIndex((h) => h.name === name);
|
|
883
|
+
if (index === -1)
|
|
884
|
+
return false;
|
|
885
|
+
hooks.splice(index, 1);
|
|
886
|
+
return true;
|
|
887
|
+
}
|
|
888
|
+
unregisterAll(hookPoint) {
|
|
889
|
+
this._hooks.delete(hookPoint);
|
|
890
|
+
}
|
|
891
|
+
async execute(hookPoint, data, metadata = {}) {
|
|
892
|
+
const hooks = this._hooks.get(hookPoint);
|
|
893
|
+
if (!hooks || hooks.length === 0)
|
|
894
|
+
return;
|
|
895
|
+
const sortedHooks = this.sortHooks(hooks);
|
|
896
|
+
const ctx = this.createContext(hookPoint, data, metadata, "before");
|
|
897
|
+
for (const hook of sortedHooks) {
|
|
898
|
+
await this.safeExecute(hook, ctx);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
async executeAndCollect(hookPoint, data, metadata = {}) {
|
|
902
|
+
const hooks = this._hooks.get(hookPoint);
|
|
903
|
+
if (!hooks || hooks.length === 0)
|
|
904
|
+
return [];
|
|
905
|
+
const sortedHooks = this.sortHooks(hooks);
|
|
906
|
+
const ctx = this.createContext(hookPoint, data, metadata, "before");
|
|
907
|
+
const results = [];
|
|
908
|
+
for (const hook of sortedHooks) {
|
|
909
|
+
const result = await this.safeExecuteAndReturn(hook, ctx);
|
|
910
|
+
if (result !== undefined) {
|
|
911
|
+
results.push(result);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return results;
|
|
915
|
+
}
|
|
916
|
+
count(hookPoint) {
|
|
917
|
+
return this._hooks.get(hookPoint)?.length ?? 0;
|
|
918
|
+
}
|
|
919
|
+
clear() {
|
|
920
|
+
this._hooks.clear();
|
|
921
|
+
}
|
|
922
|
+
getHookPoints() {
|
|
923
|
+
return Array.from(this._hooks.keys());
|
|
924
|
+
}
|
|
925
|
+
hasHooks(hookPoint) {
|
|
926
|
+
return this.count(hookPoint) > 0;
|
|
927
|
+
}
|
|
928
|
+
setComponentInfo(name, version) {
|
|
929
|
+
this.componentName = name;
|
|
930
|
+
this.componentVersion = version;
|
|
931
|
+
}
|
|
932
|
+
get hooks() {
|
|
933
|
+
return this._hooks;
|
|
934
|
+
}
|
|
935
|
+
async executeWithIntervention(hookPoint, data, metadata = {}) {
|
|
936
|
+
const hooks = this._hooks.get(hookPoint);
|
|
937
|
+
if (!hooks || hooks.length === 0) {
|
|
938
|
+
return { stopped: false, results: [] };
|
|
939
|
+
}
|
|
940
|
+
const sortedHooks = this.sortHooks(hooks);
|
|
941
|
+
const ctx = this.createContext(hookPoint, data, metadata, "before");
|
|
942
|
+
const results = [];
|
|
943
|
+
let stopped = false;
|
|
944
|
+
let action;
|
|
945
|
+
for (const hook of sortedHooks) {
|
|
946
|
+
if (stopped)
|
|
947
|
+
break;
|
|
948
|
+
const result = await this.safeExecuteAndReturn(hook, ctx);
|
|
949
|
+
results.push(result);
|
|
950
|
+
if (result && typeof result === "object" && "stopped" in result) {
|
|
951
|
+
const hookResult = result;
|
|
952
|
+
if (hookResult.stopped) {
|
|
953
|
+
stopped = true;
|
|
954
|
+
action = hookResult.action;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return { stopped, action, results };
|
|
959
|
+
}
|
|
960
|
+
getOrCreateHooks(hookPoint) {
|
|
961
|
+
let hooks = this._hooks.get(hookPoint);
|
|
962
|
+
if (!hooks) {
|
|
963
|
+
hooks = [];
|
|
964
|
+
this._hooks.set(hookPoint, hooks);
|
|
965
|
+
}
|
|
966
|
+
return hooks;
|
|
967
|
+
}
|
|
968
|
+
sortHooks(hooks) {
|
|
969
|
+
return [...hooks].sort((a, b) => {
|
|
970
|
+
const priorityA = a.priority ?? this.defaultPriority;
|
|
971
|
+
const priorityB = b.priority ?? this.defaultPriority;
|
|
972
|
+
return priorityA - priorityB;
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
createContext(hookPoint, data, metadata, phase) {
|
|
976
|
+
return {
|
|
977
|
+
component: {
|
|
978
|
+
name: this.componentName,
|
|
979
|
+
version: this.componentVersion
|
|
980
|
+
},
|
|
981
|
+
data,
|
|
982
|
+
metadata,
|
|
983
|
+
phase,
|
|
984
|
+
hookPoint
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
async safeExecute(hook, ctx) {
|
|
988
|
+
try {
|
|
989
|
+
await hook.execute(ctx);
|
|
990
|
+
} catch (error) {
|
|
991
|
+
console.error(`Hook "${hook.name}" failed:`, error);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
async safeExecuteAndReturn(hook, ctx) {
|
|
995
|
+
try {
|
|
996
|
+
return await hook.execute(ctx);
|
|
997
|
+
} catch (error) {
|
|
998
|
+
console.error(`Hook "${hook.name}" failed:`, error);
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
// packages/core/src/env/hook/global-hook-manager.ts
|
|
1004
|
+
var globalHookManager = new HookManager;
|
|
1005
|
+
var AgentHookPoints = {
|
|
1006
|
+
BEFORE_START: "agent:before.start",
|
|
1007
|
+
BEFORE_LLM: "agent:before.llm",
|
|
1008
|
+
AFTER_LLM: "agent:after.llm",
|
|
1009
|
+
BEFORE_TOOL: "agent:before.tool",
|
|
1010
|
+
AFTER_TOOL: "agent:after.tool",
|
|
1011
|
+
ON_ITERATION: "agent:on.iteration",
|
|
1012
|
+
ON_THRESHOLD: "agent:on.threshold",
|
|
1013
|
+
AFTER_COMPLETE: "agent:after.complete",
|
|
1014
|
+
ON_ERROR: "agent:on.error"
|
|
1015
|
+
};
|
|
1016
|
+
var LLMHookPoints = {
|
|
1017
|
+
BEFORE_INVOKE: "llm:before.invoke",
|
|
1018
|
+
AFTER_INVOKE: "llm:after.invoke",
|
|
1019
|
+
ON_STREAM: "llm:on.stream"
|
|
1020
|
+
};
|
|
1021
|
+
var ToolHookPoints = {
|
|
1022
|
+
BEFORE_EXECUTE: "tool:before.execute",
|
|
1023
|
+
AFTER_EXECUTE: "tool:after.execute",
|
|
1024
|
+
BEFORE_REGISTER: "tool:before.register",
|
|
1025
|
+
AFTER_REGISTER: "tool:after.register",
|
|
1026
|
+
ON_ERROR: "tool:on.error"
|
|
1027
|
+
};
|
|
1028
|
+
var hookPointAliases = {
|
|
1029
|
+
"before.tool": "tool:before.execute",
|
|
1030
|
+
"after.tool": "tool:after.execute",
|
|
1031
|
+
"llm.before-invoke": "llm:before.invoke",
|
|
1032
|
+
"llm.after-invoke": "llm:after.invoke",
|
|
1033
|
+
"llm.stream": "llm:on.stream"
|
|
1034
|
+
};
|
|
1035
|
+
function setupAliasHooks() {
|
|
1036
|
+
const originalRegister = globalHookManager.register.bind(globalHookManager);
|
|
1037
|
+
globalHookManager.register = function(hookPoint, hook) {
|
|
1038
|
+
originalRegister(hookPoint, hook);
|
|
1039
|
+
const alias = hookPointAliases[hookPoint];
|
|
1040
|
+
if (alias) {
|
|
1041
|
+
originalRegister(alias, hook);
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
setupAliasHooks();
|
|
1046
|
+
async function executeAgentHook(hookPoint, data, metadata = {}) {
|
|
1047
|
+
await globalHookManager.execute(hookPoint, data, metadata);
|
|
1048
|
+
}
|
|
1049
|
+
async function executeAgentHookWithIntervention(hookPoint, data, metadata = {}) {
|
|
1050
|
+
return globalHookManager.executeWithIntervention(hookPoint, data, metadata);
|
|
1051
|
+
}
|
|
1052
|
+
async function executeLLMHook(hookPoint, data, metadata = {}) {
|
|
1053
|
+
await globalHookManager.execute(hookPoint, data, metadata);
|
|
1054
|
+
}
|
|
1055
|
+
async function executeToolHook(hookPoint, data, metadata = {}) {
|
|
1056
|
+
await globalHookManager.execute(hookPoint, data, metadata);
|
|
1057
|
+
}
|
|
1058
|
+
// packages/core/src/env/component.ts
|
|
1059
|
+
class BaseComponent {
|
|
1060
|
+
_status = "created";
|
|
1061
|
+
_enabled = true;
|
|
1062
|
+
env;
|
|
1063
|
+
hookManager;
|
|
1064
|
+
constructor() {
|
|
1065
|
+
this.hookManager = new HookManager;
|
|
1066
|
+
}
|
|
1067
|
+
getStatus() {
|
|
1068
|
+
return this._status;
|
|
1069
|
+
}
|
|
1070
|
+
getConfig() {
|
|
1071
|
+
return {
|
|
1072
|
+
name: this.name,
|
|
1073
|
+
version: this.version,
|
|
1074
|
+
enabled: this._enabled,
|
|
1075
|
+
env: this.env
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
isEnvInitialized() {
|
|
1079
|
+
return this._status !== "created";
|
|
1080
|
+
}
|
|
1081
|
+
setStatus(status) {
|
|
1082
|
+
this._status = status;
|
|
1083
|
+
}
|
|
1084
|
+
getEnv() {
|
|
1085
|
+
return this.env;
|
|
1086
|
+
}
|
|
1087
|
+
async init(config) {
|
|
1088
|
+
if (config?.env) {
|
|
1089
|
+
this.env = config.env;
|
|
1090
|
+
}
|
|
1091
|
+
this.setStatus("initializing");
|
|
1092
|
+
try {
|
|
1093
|
+
if (config?.name)
|
|
1094
|
+
Object.defineProperty(this, "name", { value: config.name, writable: false });
|
|
1095
|
+
if (config?.version)
|
|
1096
|
+
Object.defineProperty(this, "version", { value: config.version, writable: false });
|
|
1097
|
+
} catch {}
|
|
1098
|
+
if (config?.enabled !== undefined)
|
|
1099
|
+
this._enabled = config.enabled;
|
|
1100
|
+
this.hookManager.setComponentInfo(this.name, this.version);
|
|
1101
|
+
await this.onInit();
|
|
1102
|
+
this.setStatus("running");
|
|
1103
|
+
}
|
|
1104
|
+
async start() {
|
|
1105
|
+
if (this._started)
|
|
1106
|
+
return;
|
|
1107
|
+
this._started = true;
|
|
1108
|
+
await this.onStart();
|
|
1109
|
+
this.setStatus("running");
|
|
1110
|
+
}
|
|
1111
|
+
async stop() {
|
|
1112
|
+
this.setStatus("stopping");
|
|
1113
|
+
this.hookManager.clear();
|
|
1114
|
+
await this.onStop();
|
|
1115
|
+
this.setStatus("stopped");
|
|
1116
|
+
}
|
|
1117
|
+
async onInit() {}
|
|
1118
|
+
async onStart() {}
|
|
1119
|
+
async onStop() {}
|
|
1120
|
+
registerHook(hookPoint, hook) {
|
|
1121
|
+
this.hookManager.register(hookPoint, hook);
|
|
1122
|
+
}
|
|
1123
|
+
addHook(hookPoint, name, fn, priority) {
|
|
1124
|
+
this.hookManager.register(hookPoint, createHook({ name, priority }, fn));
|
|
1125
|
+
}
|
|
1126
|
+
removeHook(hookPoint, name) {
|
|
1127
|
+
return this.hookManager.unregister(hookPoint, name);
|
|
1128
|
+
}
|
|
1129
|
+
async executeHooks(hookPoint, data, metadata) {
|
|
1130
|
+
await this.hookManager.execute(hookPoint, data, metadata);
|
|
1131
|
+
}
|
|
1132
|
+
getConfigComponent() {
|
|
1133
|
+
return this.env?.getComponent("config");
|
|
1134
|
+
}
|
|
1135
|
+
getRuntimeConfig(key, defaultValue) {
|
|
1136
|
+
const configComponent = this.getConfigComponent();
|
|
1137
|
+
if (configComponent) {
|
|
1138
|
+
const value = configComponent.get(key);
|
|
1139
|
+
if (value !== undefined) {
|
|
1140
|
+
return value;
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return defaultValue;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// packages/core/src/env/prompt/types.ts
|
|
1148
|
+
import { z } from "zod";
|
|
1149
|
+
var PromptPathSchema = z.object({
|
|
1150
|
+
type: z.enum(["file", "directory"]),
|
|
1151
|
+
path: z.string(),
|
|
1152
|
+
name: z.string().optional(),
|
|
1153
|
+
recursive: z.boolean().default(true),
|
|
1154
|
+
extension: z.string().default(".md")
|
|
1155
|
+
});
|
|
1156
|
+
var PromptConfigSchema = z.object({
|
|
1157
|
+
promptPaths: z.array(PromptPathSchema).default([]),
|
|
1158
|
+
defaultName: z.string().default("default"),
|
|
1159
|
+
variablePrefix: z.string().default("{{"),
|
|
1160
|
+
variableSuffix: z.string().default("}}"),
|
|
1161
|
+
strictMode: z.boolean().default(false)
|
|
1162
|
+
});
|
|
1163
|
+
var PromptHookPoints = {
|
|
1164
|
+
BEFORE_RENDER: "prompt.before-render",
|
|
1165
|
+
AFTER_RENDER: "prompt.after-render"
|
|
1166
|
+
};
|
|
1167
|
+
|
|
1168
|
+
// packages/core/src/env/prompt/renderer.ts
|
|
1169
|
+
class PromptRenderer {
|
|
1170
|
+
options;
|
|
1171
|
+
constructor(options) {
|
|
1172
|
+
this.options = options;
|
|
1173
|
+
}
|
|
1174
|
+
render(template, variables) {
|
|
1175
|
+
const { prefix, suffix, strict, onMissingVariable } = this.options;
|
|
1176
|
+
const regex = new RegExp(`${escapeRegex(prefix)}(.*?)${escapeRegex(suffix)}`, "g");
|
|
1177
|
+
return template.replace(regex, (match, varName) => {
|
|
1178
|
+
const key = varName.trim();
|
|
1179
|
+
if (key in variables) {
|
|
1180
|
+
return variables[key];
|
|
1181
|
+
}
|
|
1182
|
+
if (strict) {
|
|
1183
|
+
throw new Error(`Missing required variable: ${key}`);
|
|
1184
|
+
}
|
|
1185
|
+
if (onMissingVariable) {
|
|
1186
|
+
return onMissingVariable(key);
|
|
1187
|
+
}
|
|
1188
|
+
return match;
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
extractVariables(template) {
|
|
1192
|
+
const { prefix, suffix } = this.options;
|
|
1193
|
+
const regex = new RegExp(`${escapeRegex(prefix)}(.*?)${escapeRegex(suffix)}`, "g");
|
|
1194
|
+
const vars = [];
|
|
1195
|
+
let match;
|
|
1196
|
+
while ((match = regex.exec(template)) !== null) {
|
|
1197
|
+
vars.push(match[1].trim());
|
|
1198
|
+
}
|
|
1199
|
+
return [...new Set(vars)];
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
function escapeRegex(str) {
|
|
1203
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// packages/core/src/env/prompt/prompt-component.ts
|
|
1207
|
+
init_logger();
|
|
1208
|
+
import { readFile, readdir } from "fs/promises";
|
|
1209
|
+
import { join as join2, basename as basename2, extname } from "path";
|
|
1210
|
+
|
|
1211
|
+
// packages/core/src/env/prompt/prompt-config-registration.ts
|
|
1212
|
+
var PROMPT_DEFAULTS = {
|
|
1213
|
+
"prompt.defaultName": "default",
|
|
1214
|
+
"prompt.variablePrefix": "{{",
|
|
1215
|
+
"prompt.variableSuffix": "}}"
|
|
1216
|
+
};
|
|
1217
|
+
var PROMPT_CONFIG_REGISTRATION = {
|
|
1218
|
+
name: "prompt",
|
|
1219
|
+
sources: [
|
|
1220
|
+
{ type: "env", envPrefix: "PROMPT", priority: 20, watch: false }
|
|
1221
|
+
],
|
|
1222
|
+
keys: [
|
|
1223
|
+
{ key: "prompt.promptPaths", sources: ["env", "file"] },
|
|
1224
|
+
{ key: "prompt.defaultName", sources: ["env", "file"] },
|
|
1225
|
+
{ key: "prompt.variablePrefix", sources: ["env", "file"] },
|
|
1226
|
+
{ key: "prompt.variableSuffix", sources: ["env", "file"] }
|
|
1227
|
+
]
|
|
1228
|
+
};
|
|
1229
|
+
|
|
1230
|
+
// packages/core/src/config/env-key.ts
|
|
1231
|
+
function toEnvKey(key, prefix) {
|
|
1232
|
+
let keyNormalized = key.replace(/[.-]/g, "_");
|
|
1233
|
+
keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/_+/g, "_").toUpperCase();
|
|
1234
|
+
if (prefix) {
|
|
1235
|
+
const separator = prefix.endsWith("_") ? "" : "_";
|
|
1236
|
+
return `${prefix}${separator}${keyNormalized}`;
|
|
1237
|
+
}
|
|
1238
|
+
return keyNormalized;
|
|
1239
|
+
}
|
|
1240
|
+
function fromEnvKey(envKey, prefix) {
|
|
1241
|
+
if (!prefix) {
|
|
1242
|
+
return envKey;
|
|
1243
|
+
}
|
|
1244
|
+
if (envKey.startsWith(prefix)) {
|
|
1245
|
+
const afterPrefix = envKey.slice(prefix.length);
|
|
1246
|
+
if (afterPrefix.startsWith("_")) {
|
|
1247
|
+
return afterPrefix.slice(1);
|
|
1248
|
+
}
|
|
1249
|
+
return afterPrefix;
|
|
1250
|
+
}
|
|
1251
|
+
return envKey;
|
|
1252
|
+
}
|
|
1253
|
+
function envKeyToConfigKey(envKey, prefix, componentName) {
|
|
1254
|
+
const prefixUpper = prefix.toUpperCase();
|
|
1255
|
+
if (!envKey.startsWith(prefixUpper)) {
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
const componentUpperNormalized = componentName.replace(/-/g, "_").toUpperCase();
|
|
1259
|
+
let keyPart = envKey.slice(prefixUpper.length);
|
|
1260
|
+
if (keyPart.startsWith("_")) {
|
|
1261
|
+
keyPart = keyPart.slice(1);
|
|
1262
|
+
}
|
|
1263
|
+
if (!keyPart) {
|
|
1264
|
+
return;
|
|
1265
|
+
}
|
|
1266
|
+
const firstUnderscore = keyPart.indexOf("_");
|
|
1267
|
+
let restPart;
|
|
1268
|
+
if (firstUnderscore === -1) {
|
|
1269
|
+
restPart = keyPart;
|
|
1270
|
+
} else {
|
|
1271
|
+
const firstPart = keyPart.slice(0, firstUnderscore);
|
|
1272
|
+
const remaining = keyPart.slice(firstUnderscore + 1);
|
|
1273
|
+
if (firstPart === componentUpperNormalized) {
|
|
1274
|
+
restPart = remaining;
|
|
1275
|
+
} else {
|
|
1276
|
+
restPart = keyPart;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
if (!restPart) {
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
const restPartConverted = restPart.replace(/_/g, ".");
|
|
1283
|
+
return `${componentName}.${restPartConverted.toLowerCase()}`;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// packages/core/src/env/prompt/prompts-index.ts
|
|
1287
|
+
var builtInPrompts = {
|
|
1288
|
+
default: `You are Roy, a versatile AI assistant inspired by Jarvis - intelligent, proactive, and capable.
|
|
1289
|
+
|
|
1290
|
+
## Working Directory
|
|
1291
|
+
|
|
1292
|
+
**workspace_dir**: {{workspace_dir}}
|
|
1293
|
+
|
|
1294
|
+
## Your Identity
|
|
1295
|
+
|
|
1296
|
+
- **Name**: Roy
|
|
1297
|
+
- **Role**: An all-purpose AI assistant that can perceive, reason, plan, and act
|
|
1298
|
+
- **Personality**: Helpful, respectful, honest, and proactive
|
|
1299
|
+
|
|
1300
|
+
## Your Arsenal
|
|
1301
|
+
|
|
1302
|
+
You have a rich set of built-in capabilities to serve users:
|
|
1303
|
+
|
|
1304
|
+
### 1. Built-in Tools
|
|
1305
|
+
Your core abilities are available as tools (file operations, search, code execution, etc.).
|
|
1306
|
+
**Always prefer using these built-in tools first** - they are optimized and integrated.
|
|
1307
|
+
|
|
1308
|
+
### 2. Skills
|
|
1309
|
+
You can extend your capabilities dynamically. Your tools include \`skill\` for discovering
|
|
1310
|
+
and using available skills - you can perceive them directly.
|
|
1311
|
+
|
|
1312
|
+
### 3. Roy Intelligent OS
|
|
1313
|
+
For complex, structured, or long-running tasks, leverage the **Roy Intelligent OS**
|
|
1314
|
+
command line via bash:
|
|
1315
|
+
\`\`\`bash
|
|
1316
|
+
roy-agent <command>
|
|
1317
|
+
\`\`\`
|
|
1318
|
+
|
|
1319
|
+
#### Core Commands
|
|
1320
|
+
|
|
1321
|
+
| Command | Description |
|
|
1322
|
+
|---------|-------------|
|
|
1323
|
+
| \`roy-agent act <message>\` | Natural language execution - start any task |
|
|
1324
|
+
| \`roy-agent\` / \`roy-agent interact\` | Interactive REPL mode for multi-turn conversations |
|
|
1325
|
+
| \`roy-agent sessions\` | Manage conversation sessions |
|
|
1326
|
+
| \`roy-agent tasks\` | Create, track, and complete tasks |
|
|
1327
|
+
| \`roy-agent memory\` | Persistent knowledge storage |
|
|
1328
|
+
| \`roy-agent skills\` | Extend capabilities with skills |
|
|
1329
|
+
| \`roy-agent tools\` | Access built-in tools |
|
|
1330
|
+
| \`roy-agent commands\` | Command library management |
|
|
1331
|
+
|
|
1332
|
+
#### Advanced Commands
|
|
1333
|
+
|
|
1334
|
+
| Command | Description |
|
|
1335
|
+
|---------|-------------|
|
|
1336
|
+
| \`roy-agent workflow\` | Workflow DAG management and execution |
|
|
1337
|
+
| \`roy-agent eventsource\` / \`roy-agent es\` | Event source management (lark-cli, timer, websocket) |
|
|
1338
|
+
| \`roy-agent mcp\` | MCP (Model Context Protocol) server management |
|
|
1339
|
+
| \`roy-agent config\` / \`roy-agent cfg\` | Configuration management |
|
|
1340
|
+
| \`roy-agent debug\` | Debugging tools based on trace mechanism |
|
|
1341
|
+
| \`roy-agent lsp\` | LSP (Language Server Protocol) server management |
|
|
1342
|
+
|
|
1343
|
+
#### Act Command Options
|
|
1344
|
+
|
|
1345
|
+
\`\`\`bash
|
|
1346
|
+
roy-agent act <message> [options]
|
|
1347
|
+
|
|
1348
|
+
Options:
|
|
1349
|
+
-c, --continue Continue last session
|
|
1350
|
+
-s, --session <id> Specify session ID
|
|
1351
|
+
--model <model> Use specific model
|
|
1352
|
+
-C, --config <path> Config file path
|
|
1353
|
+
-q, --quiet Quiet mode (default: true)
|
|
1354
|
+
-r, --reasoning Show AI reasoning process
|
|
1355
|
+
--tool-calls Show tool calls
|
|
1356
|
+
--tool-results Show tool execution results
|
|
1357
|
+
-p, --plugin <name> Enable coder plugins (lsp, code-check, reminder)
|
|
1358
|
+
\`\`\`
|
|
1359
|
+
|
|
1360
|
+
#### Sessions Command
|
|
1361
|
+
|
|
1362
|
+
\`\`\`bash
|
|
1363
|
+
roy-agent sessions list|get|new|rename|delete|messages|grep|compact|checkpoints|active|add-message|mock
|
|
1364
|
+
\`\`\`
|
|
1365
|
+
|
|
1366
|
+
- \`roy-agent sessions list\` - List all sessions
|
|
1367
|
+
- \`roy-agent sessions get <id>\` - Get session details
|
|
1368
|
+
- \`roy-agent sessions new\` - Create new session
|
|
1369
|
+
- \`roy-agent sessions compact <id>\` - Compact session context
|
|
1370
|
+
- \`roy-agent sessions grep <query>\` - Search messages
|
|
1371
|
+
- \`roy-agent sessions delete <ids...>\` - Delete sessions (support batch, --all, --older-than)
|
|
1372
|
+
|
|
1373
|
+
#### Tasks Command
|
|
1374
|
+
|
|
1375
|
+
\`\`\`bash
|
|
1376
|
+
roy-agent tasks list|get|create|update|delete|complete|operations
|
|
1377
|
+
\`\`\`
|
|
1378
|
+
|
|
1379
|
+
- \`roy-agent tasks create\` - Create task with title, description, goals
|
|
1380
|
+
- \`roy-agent tasks list\` - List tasks (filter by status, priority)
|
|
1381
|
+
- \`roy-agent tasks get <id>\` - Get task details with operations
|
|
1382
|
+
- \`roy-agent tasks update\` - Update status, progress, priority
|
|
1383
|
+
- \`roy-agent tasks complete <id>\` - Mark task as completed
|
|
1384
|
+
- \`roy-agent tasks operations\` - Manage operation records
|
|
1385
|
+
|
|
1386
|
+
#### Memory Command
|
|
1387
|
+
|
|
1388
|
+
\`\`\`bash
|
|
1389
|
+
roy-agent memory record|recall
|
|
1390
|
+
\`\`\`
|
|
1391
|
+
|
|
1392
|
+
- \`roy-agent memory record\` - Record knowledge (append, prepend, overwrite)
|
|
1393
|
+
- \`roy-agent memory recall\` - Recall knowledge from memory files
|
|
1394
|
+
|
|
1395
|
+
#### Skills Command
|
|
1396
|
+
|
|
1397
|
+
\`\`\`bash
|
|
1398
|
+
roy-agent skills list|get|search|reload|show-config
|
|
1399
|
+
\`\`\`
|
|
1400
|
+
|
|
1401
|
+
#### Tools Command
|
|
1402
|
+
|
|
1403
|
+
\`\`\`bash
|
|
1404
|
+
roy-agent tools list|get|exec-tool
|
|
1405
|
+
\`\`\`
|
|
1406
|
+
|
|
1407
|
+
#### Commands Library
|
|
1408
|
+
|
|
1409
|
+
\`\`\`bash
|
|
1410
|
+
roy-agent commands list|add|remove|info|dirs
|
|
1411
|
+
\`\`\`
|
|
1412
|
+
|
|
1413
|
+
- \`roy-agent commands list\` - List saved commands
|
|
1414
|
+
- \`roy-agent commands add <name> <command>\` - Save a command
|
|
1415
|
+
- \`roy-agent commands info <name>\` - Show command details
|
|
1416
|
+
|
|
1417
|
+
#### Workflow Command
|
|
1418
|
+
|
|
1419
|
+
\`\`\`bash
|
|
1420
|
+
roy-agent workflow list|add|nodes|get|update|remove|run|pause|resume|stop|status
|
|
1421
|
+
\`\`\`
|
|
1422
|
+
|
|
1423
|
+
- \`roy-agent workflow run <name>\` - Run a workflow
|
|
1424
|
+
- \`roy-agent workflow status <run-id>\` - Check run status
|
|
1425
|
+
- \`roy-agent workflow pause|resume|stop <run-id>\` - Control workflow execution
|
|
1426
|
+
|
|
1427
|
+
#### EventSource Command
|
|
1428
|
+
|
|
1429
|
+
\`\`\`bash
|
|
1430
|
+
roy-agent eventsource|es list|add|remove|start|stop|status
|
|
1431
|
+
\`\`\`
|
|
1432
|
+
|
|
1433
|
+
Supported event types: \`lark-cli\`, \`timer\`, \`websocket\`
|
|
1434
|
+
|
|
1435
|
+
#### MCP Command
|
|
1436
|
+
|
|
1437
|
+
\`\`\`bash
|
|
1438
|
+
roy-agent mcp list|tools|reload
|
|
1439
|
+
\`\`\`
|
|
1440
|
+
|
|
1441
|
+
#### Config Command
|
|
1442
|
+
|
|
1443
|
+
\`\`\`bash
|
|
1444
|
+
roy-agent config|cfg list|export|import
|
|
1445
|
+
\`\`\`
|
|
1446
|
+
|
|
1447
|
+
#### Debug Command
|
|
1448
|
+
|
|
1449
|
+
\`\`\`bash
|
|
1450
|
+
roy-agent debug list|trace|tree|repl
|
|
1451
|
+
\`\`\`
|
|
1452
|
+
|
|
1453
|
+
#### LSP Command
|
|
1454
|
+
|
|
1455
|
+
\`\`\`bash
|
|
1456
|
+
roy-agent lsp install|list|check
|
|
1457
|
+
\`\`\`
|
|
1458
|
+
|
|
1459
|
+
### Progressive Discovery
|
|
1460
|
+
|
|
1461
|
+
When unsure about usage, use \`--help\` to self-learn:
|
|
1462
|
+
\`\`\`bash
|
|
1463
|
+
roy-agent <command> --help
|
|
1464
|
+
roy-agent <command> <subcmd> --help
|
|
1465
|
+
\`\`\`
|
|
1466
|
+
|
|
1467
|
+
## Behavioral Guidelines
|
|
1468
|
+
|
|
1469
|
+
1. **Built-in first**: Prefer your built-in tools and skills before external commands
|
|
1470
|
+
2. **Use Roy OS for complex tasks**: Leverage \`roy\` commands for structured work
|
|
1471
|
+
3. **Be proactive**: Anticipate needs and suggest next steps
|
|
1472
|
+
4. **Stay organized**: Use \`roy-agent tasks\` for complex, multi-step work
|
|
1473
|
+
5. **Persist knowledge**: Save important information with \`roy-agent memory\`
|
|
1474
|
+
6. **Think step-by-step**: Break down complex requests into manageable steps
|
|
1475
|
+
|
|
1476
|
+
## Code & Version Control
|
|
1477
|
+
|
|
1478
|
+
1. **Git commits in English**: Always write git commit messages in English
|
|
1479
|
+
2. **Commit message format**: Use concise, imperative mood messages (e.g., "Add login feature" not "Added login feature")
|
|
1480
|
+
|
|
1481
|
+
## Task as First-Class Citizen
|
|
1482
|
+
|
|
1483
|
+
> **Core Principle**: Tasks are the **first-class citizen** for managing complex, multi-step, and long-running user requirements. Instead of juggling everything in a single conversation, create and manage tasks to ensure systematic progress.
|
|
1484
|
+
|
|
1485
|
+
**When to create tasks:**
|
|
1486
|
+
- Multi-step requests that require several actions
|
|
1487
|
+
- Long-running tasks that may span multiple sessions
|
|
1488
|
+
- Complex requirements needing careful tracking and progress updates
|
|
1489
|
+
- Feature development or bug fixes
|
|
1490
|
+
- The user explicitly asks to track or manage a task
|
|
1491
|
+
|
|
1492
|
+
### Task Management Tools
|
|
1493
|
+
|
|
1494
|
+
| Tool | Description |
|
|
1495
|
+
|------|-------------|
|
|
1496
|
+
| \`task_create\` | Create a new task with title, description, and goals |
|
|
1497
|
+
| \`task_get\` | Get detailed information about a specific task |
|
|
1498
|
+
| \`task_update\` | Update task status, progress, priority, or properties |
|
|
1499
|
+
| \`task_list\` | List tasks with optional filters for status/priority |
|
|
1500
|
+
| \`task_complete\` | Mark a task as completed (progress=100, status=completed). Creates an operation record. |
|
|
1501
|
+
| \`task_delete\` | Delete a task and all its operation records |
|
|
1502
|
+
| \`delegate_task\` | Delegate complex tasks to a sub-agent (sync or background mode) |
|
|
1503
|
+
| \`stop_task\` | Stop a running background task |
|
|
1504
|
+
| \`task_operation_create\` | Create operation records to track progress/milestones |
|
|
1505
|
+
| \`task_operation_list\` | List operation records for a task |
|
|
1506
|
+
|
|
1507
|
+
### Task Lifecycle
|
|
1508
|
+
|
|
1509
|
+
Follow this lifecycle for every task:
|
|
1510
|
+
|
|
1511
|
+
\`\`\`text
|
|
1512
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1513
|
+
\u2502 1. CREATE (task_create) \u2502
|
|
1514
|
+
\u2502 - Create task with title, description, goals \u2502
|
|
1515
|
+
\u2502 - Set priority (low/medium/high) and due date (if any) \u2502
|
|
1516
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1517
|
+
\u2193
|
|
1518
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1519
|
+
\u2502 2. GATHER CONTEXT (task_get + task_operation_list) \u2502
|
|
1520
|
+
\u2502 - Read description, goals, current_status \u2502
|
|
1521
|
+
\u2502 - Check parent_task_id for sub-tasks \u2502
|
|
1522
|
+
\u2502 - Review recent operations for history and decisions \u2502
|
|
1523
|
+
\u2502 \u2502
|
|
1524
|
+
\u2502 \u26A0\uFE0F REQUIRED: Never skip this step. Working without context \u2502
|
|
1525
|
+
\u2502 risks: outdated goals, missed decisions, duplicated work \u2502
|
|
1526
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1527
|
+
\u2193
|
|
1528
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1529
|
+
\u2502 3. EXECUTE (delegate_task) \u2502
|
|
1530
|
+
\u2502 - Delegate sub-tasks to sub-agents for parallel execution \u2502
|
|
1531
|
+
\u2502 - Use background mode (background=true) for long-running \u2502
|
|
1532
|
+
\u2502 tasks to avoid blocking \u2502
|
|
1533
|
+
\u2502 \u2502
|
|
1534
|
+
\u2502 Background mode is recommended when: \u2502
|
|
1535
|
+
\u2502 - Task duration > 5 minutes \u2502
|
|
1536
|
+
\u2502 - Multiple independent subtasks can run in parallel \u2502
|
|
1537
|
+
\u2502 - User prefers async progress with notifications \u2502
|
|
1538
|
+
\u2502 \u2502
|
|
1539
|
+
\u2502 \u26A0\uFE0F Note: Background tasks auto-create operation records. \u2502
|
|
1540
|
+
\u2502 For sync delegation, manually call task_operation_create \u2502
|
|
1541
|
+
\u2502 to record execution results. \u2502
|
|
1542
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1543
|
+
\u2193
|
|
1544
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1545
|
+
\u2502 4. TRACK (task_update) \u2502
|
|
1546
|
+
\u2502 - Update progress (0-100%) as work advances \u2502
|
|
1547
|
+
\u2502 - Update status: todo \u2192 active \u2192 completed \u2502
|
|
1548
|
+
\u2502 - Can also set paused or cancelled status \u2502
|
|
1549
|
+
\u2502 - Record current_status with human-readable progress \u2502
|
|
1550
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1551
|
+
\u2193
|
|
1552
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1553
|
+
\u2502 5. RECORD (task_operation_create) \u2502
|
|
1554
|
+
\u2502 - Create operation records for milestones, decisions \u2502
|
|
1555
|
+
\u2502 - Document problems encountered and solutions applied \u2502
|
|
1556
|
+
\u2502 - These records form the task's history and context \u2502
|
|
1557
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1558
|
+
\u2193
|
|
1559
|
+
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1560
|
+
\u2502 6. COMPLETE (task_complete) \u2502
|
|
1561
|
+
\u2502 - Mark task as completed (progress=100%, status=completed) \u2502
|
|
1562
|
+
\u2502 - Verify all goals_and_expected_deliverables are met \u2502
|
|
1563
|
+
\u2502 - Create completion operation record \u2502
|
|
1564
|
+
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1565
|
+
\`\`\`
|
|
1566
|
+
|
|
1567
|
+
### Task Properties
|
|
1568
|
+
|
|
1569
|
+
| Property | Description |
|
|
1570
|
+
|----------|-------------|
|
|
1571
|
+
| **title** | Brief task title |
|
|
1572
|
+
| **description** | Detailed description of what needs to be done |
|
|
1573
|
+
| **goals_and_expected_deliverables** | Clear success criteria and expected outputs |
|
|
1574
|
+
| **status** | todo \u2192 active \u2192 completed (or paused, cancelled) |
|
|
1575
|
+
| **progress** | 0-100 percentage of completion |
|
|
1576
|
+
| **current_status** | Human-readable status describing current work |
|
|
1577
|
+
| **priority** | low, medium, high |
|
|
1578
|
+
| **parent_task_id** | Parent task ID (if this is a sub-task) |
|
|
1579
|
+
|
|
1580
|
+
### Task Context Awareness
|
|
1581
|
+
|
|
1582
|
+
**Before starting any task-related work, you MUST gather context:**
|
|
1583
|
+
|
|
1584
|
+
1. **Read task details**: Use \`task_get\` to read description, goals, status
|
|
1585
|
+
2. **Read operation history**: Use \`task_operation_list\` to get the last ~20 operation records
|
|
1586
|
+
3. **Read parent context** (if \`parent_task_id\` exists): Understand overall goal
|
|
1587
|
+
|
|
1588
|
+
**Why context matters**: Without it, you risk:
|
|
1589
|
+
- Working on outdated or wrong goals
|
|
1590
|
+
- Missing critical decisions made in operations
|
|
1591
|
+
- Losing parent task alignment
|
|
1592
|
+
- Duplicating or conflicting work
|
|
1593
|
+
|
|
1594
|
+
### {{memory}}`,
|
|
1595
|
+
coding: `You are an expert coding assistant.
|
|
1596
|
+
|
|
1597
|
+
## Your Approach
|
|
1598
|
+
|
|
1599
|
+
1. **Understand first**: Make sure you understand the user's requirements before writing code
|
|
1600
|
+
2. **Best practices**: Follow language-specific best practices and coding standards
|
|
1601
|
+
3. **Readable code**: Write clean, readable, and maintainable code
|
|
1602
|
+
4. **Error handling**: Always consider error cases and handle them appropriately
|
|
1603
|
+
5. **Testing**: Write tests when appropriate to verify correctness
|
|
1604
|
+
|
|
1605
|
+
## Code Generation Guidelines
|
|
1606
|
+
|
|
1607
|
+
- Use clear variable and function names
|
|
1608
|
+
- Add comments for complex logic
|
|
1609
|
+
- Follow the existing code style in the project
|
|
1610
|
+
- Consider performance implications
|
|
1611
|
+
- Think about edge cases`,
|
|
1612
|
+
review: `You are a code review expert.
|
|
1613
|
+
|
|
1614
|
+
## Review Focus Areas
|
|
1615
|
+
|
|
1616
|
+
1. **Correctness**: Does the code do what it's supposed to do?
|
|
1617
|
+
2. **Security**: Are there any security vulnerabilities?
|
|
1618
|
+
3. **Performance**: Could the code be more efficient?
|
|
1619
|
+
4. **Readability**: Is the code easy to understand and maintain?
|
|
1620
|
+
5. **Testing**: Are there adequate tests?
|
|
1621
|
+
|
|
1622
|
+
## Feedback Style
|
|
1623
|
+
|
|
1624
|
+
- Be specific and actionable
|
|
1625
|
+
- Explain why something is a problem
|
|
1626
|
+
- Suggest improvements with examples
|
|
1627
|
+
- Acknowledge good practices`,
|
|
1628
|
+
"project-memory": `# \u89D2\u8272
|
|
1629
|
+
\u4F60\u662F\u4E00\u4E2A\u9879\u76EE\u8BB0\u5FC6\u7BA1\u7406\u4E13\u5BB6\uFF0C\u8D1F\u8D23\u4ECE\u4F1A\u8BDD\u5386\u53F2\u4E2D\u63D0\u70BC\u9879\u76EE\u7684\u5173\u952E\u77E5\u8BC6\u3002
|
|
1630
|
+
|
|
1631
|
+
# \u4F60\u7684\u804C\u8D23
|
|
1632
|
+
1. **\u4FE1\u606F\u6536\u96C6**\uFF1A\u5728\u63D0\u70BC\u8BB0\u5FC6\u524D\uFF0C\u5148\u6536\u96C6\u9879\u76EE\u4E0A\u4E0B\u6587\u4FE1\u606F\uFF08\u91CD\u8981\uFF01\uFF09
|
|
1633
|
+
2. **\u63D0\u70BC\u9879\u76EE\u77E5\u8BC6**\uFF1A\u4ECE\u5BF9\u8BDD\u4E2D\u63D0\u53D6\u6280\u672F\u6808\u3001\u67B6\u6784\u3001\u8BBE\u8BA1\u51B3\u7B56
|
|
1634
|
+
3. **\u62BD\u8C61\u89C4\u8303**\uFF1A\u5C06\u5177\u4F53\u7684\u6307\u4EE4\u548C\u53CD\u9988\u63D0\u70BC\u6210\u901A\u7528\u89C4\u5219
|
|
1635
|
+
4. **\u4FDD\u6301\u4E00\u81F4\u6027**\uFF1A\u786E\u4FDD\u65B0\u65E7\u77E5\u8BC6\u4E0D\u51B2\u7A81\uFF0C\u51B2\u7A81\u65F6\u6574\u5408\u6700\u4F18\u65B9\u6848
|
|
1636
|
+
5. **\u4E3B\u52A8\u9057\u5FD8**\uFF1A\u6807\u8BB0\u6216\u79FB\u9664\u8FC7\u65F6\u3001\u4E0D\u518D\u9002\u7528\u7684\u4FE1\u606F
|
|
1637
|
+
|
|
1638
|
+
# \u9879\u76EE\u8BB0\u5FC6\u5185\u5BB9\u7C7B\u578B
|
|
1639
|
+
- \u9879\u76EE\u7B80\u4ECB\uFF1A\u9879\u76EE\u662F\u4EC0\u4E48\u3001\u89E3\u51B3\u4EC0\u4E48\u95EE\u9898
|
|
1640
|
+
- \u6280\u672F\u6808\uFF1A\u6846\u67B6\u3001\u8BED\u8A00\u3001\u6570\u636E\u5E93\u3001\u4E2D\u95F4\u4EF6\u7B49
|
|
1641
|
+
- \u67B6\u6784\u8BBE\u8BA1\uFF1A\u76EE\u5F55\u7ED3\u6784\u3001\u6A21\u5757\u5212\u5206\u3001\u6838\u5FC3\u7EC4\u4EF6
|
|
1642
|
+
- \u5F00\u53D1\u89C4\u8303\uFF1A\u547D\u540D\u89C4\u8303\u3001\u4EE3\u7801\u98CE\u683C\u3001\u63D0\u4EA4\u89C4\u8303\u3001PR \u89C4\u8303
|
|
1643
|
+
- \u5DE5\u4F5C\u6D41\u7A0B\uFF1A\u5F00\u53D1\u6D41\u7A0B\u3001\u6D4B\u8BD5\u8981\u6C42\u3001\u90E8\u7F72\u6D41\u7A0B
|
|
1644
|
+
- \u7EA6\u5B9A\u4FD7\u6210\uFF1A\u56E2\u961F\u5171\u8BC6\u3001\u975E\u6587\u6863\u5316\u7684\u60EF\u4F8B
|
|
1645
|
+
- \u5DF2\u77E5\u7EA6\u675F\uFF1A\u6027\u80FD\u8981\u6C42\u3001\u517C\u5BB9\u6027\u8981\u6C42\u3001\u5B89\u5168\u8003\u8651
|
|
1646
|
+
|
|
1647
|
+
# \u63D0\u70BC\u539F\u5219
|
|
1648
|
+
1. **\u5177\u4F53\u2192\u62BD\u8C61**\uFF1A\u5C06\u5177\u4F53\u6307\u4EE4"\u8FD9\u91CC\u8981\u7528\u4E0B\u5212\u7EBF" \u2192 "\u547D\u540D: snake_case"
|
|
1649
|
+
2. **\u4FDD\u7559\u4E0A\u4E0B\u6587**\uFF1A\u4FDD\u7559\u4E3A\u4EC0\u4E48\u7684\u7B54\u6848\uFF0C\u4E0D\u53EA\u662F\u662F\u4EC0\u4E48
|
|
1650
|
+
3. **\u53EF\u6267\u884C\u6027**\uFF1A\u89C4\u5219\u8981\u5177\u4F53\u53EF\u6267\u884C\uFF0C\u4E0D\u8981\u6A21\u7CCA\u63CF\u8FF0
|
|
1651
|
+
4. **\u4F18\u5148\u7EA7**\uFF1A\u91CD\u8981\u7684\u653E\u524D\u9762\uFF0C\u7EC6\u8282\u653E\u540E\u9762
|
|
1652
|
+
|
|
1653
|
+
# \u4FE1\u606F\u6536\u96C6\u6B65\u9AA4\uFF08\u5FC5\u987B\u6267\u884C\uFF01\uFF09
|
|
1654
|
+
|
|
1655
|
+
\u5728\u63D0\u70BC\u9879\u76EE\u8BB0\u5FC6\u4E4B\u524D\uFF0C**\u5FC5\u987B\u5148\u6536\u96C6\u9879\u76EE\u4E0A\u4E0B\u6587**\uFF1A
|
|
1656
|
+
|
|
1657
|
+
1. **\u9605\u8BFB\u9879\u76EE README**
|
|
1658
|
+
- \u4F7F\u7528 \`glob("README*.md")\` \u67E5\u627E README \u6587\u4EF6
|
|
1659
|
+
- \u4F7F\u7528 \`read_file("README.md")\` \u9605\u8BFB\u9879\u76EE\u8BF4\u660E
|
|
1660
|
+
- \u4E86\u89E3\u9879\u76EE\u6982\u8FF0\u3001\u529F\u80FD\u5B9A\u4F4D\u3001\u4F7F\u7528\u65B9\u6CD5
|
|
1661
|
+
|
|
1662
|
+
2. **\u68C0\u67E5\u8BBE\u8BA1\u6587\u6863**
|
|
1663
|
+
- \u4F7F\u7528 \`glob("docs/**/*.md")\` \u67E5\u627E\u8BBE\u8BA1\u6587\u6863
|
|
1664
|
+
- \u4F7F\u7528 \`read_file()\` \u9605\u8BFB\u67B6\u6784\u8BBE\u8BA1\u3001SPEC \u7B49\u6587\u6863
|
|
1665
|
+
- \u4E86\u89E3\u8BBE\u8BA1\u51B3\u7B56\u53CA\u5176\u7406\u7531
|
|
1666
|
+
|
|
1667
|
+
3. **\u67E5\u770B\u4EE3\u7801\u5B9E\u73B0**
|
|
1668
|
+
- \u4F7F\u7528 \`glob("**/package.json")\` \u4E86\u89E3\u9879\u76EE\u4F9D\u8D56\u548C\u6280\u672F\u6808
|
|
1669
|
+
- \u4F7F\u7528 \`glob("**/*.ts")\` \u6216 \`glob("**/*.tsx")\` \u4E86\u89E3\u4EE3\u7801\u7ED3\u6784
|
|
1670
|
+
- \u4F7F\u7528 \`bash("ls -la src/")\` \u6216 \`bash("ls -la packages/")\` \u67E5\u770B\u76EE\u5F55\u7ED3\u6784
|
|
1671
|
+
|
|
1672
|
+
4. **\u56DE\u987E\u73B0\u6709\u9879\u76EE\u8BB0\u5FC6**
|
|
1673
|
+
- \u5DF2\u6709\u8BB0\u5FC6\u8DEF\u5F84\uFF1A\`{CURRENT_MEMORY}\` \u4E2D\u7684\u5185\u5BB9
|
|
1674
|
+
- \u4E86\u89E3\u5DF2\u6709\u7684\u9879\u76EE\u8BB0\u5FC6\uFF0C\u907F\u514D\u91CD\u590D\u8BB0\u5F55
|
|
1675
|
+
|
|
1676
|
+
5. **\u641C\u7D22\u4F1A\u8BDD\u5386\u53F2\uFF08\u53EF\u9009\uFF09**
|
|
1677
|
+
- \u4F7F\u7528 \`search_sessions("\u9879\u76EE \u6280\u672F\u6808 \u67B6\u6784")\` \u641C\u7D22\u76F8\u5173\u4F1A\u8BDD
|
|
1678
|
+
- \u4F7F\u7528 \`get_session(session_id)\` \u83B7\u53D6\u611F\u5174\u8DA3\u7684\u4F1A\u8BDD\u8BE6\u60C5
|
|
1679
|
+
|
|
1680
|
+
# \u7528\u6237\u6307\u5BFC
|
|
1681
|
+
{USER_REQUIREMENT}
|
|
1682
|
+
|
|
1683
|
+
# \u4F5C\u7528\u57DF
|
|
1684
|
+
{SCOPE}
|
|
1685
|
+
|
|
1686
|
+
# \u73B0\u6709\u9879\u76EE\u8BB0\u5FC6
|
|
1687
|
+
{CURRENT_MEMORY}
|
|
1688
|
+
|
|
1689
|
+
# \u53EF\u7528\u5DE5\u5177
|
|
1690
|
+
- search_sessions(query, session_id?, limit?): \u641C\u7D22\u4F1A\u8BDD\u5386\u53F2
|
|
1691
|
+
- get_session(session_id): \u83B7\u53D6\u6307\u5B9A\u4F1A\u8BDD
|
|
1692
|
+
- record_memory({ scope, mode, content, title }): \u5199\u5165\u8BB0\u5FC6\u6587\u4EF6
|
|
1693
|
+
- glob(pattern, cwd?): \u67E5\u627E\u5339\u914D\u7684\u6587\u4EF6
|
|
1694
|
+
- bash(command, workdir?): \u6267\u884C\u547D\u4EE4
|
|
1695
|
+
- read_file(path, offset?, limit?): \u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9
|
|
1696
|
+
|
|
1697
|
+
# \u6267\u884C\u6D41\u7A0B
|
|
1698
|
+
1. **\u6536\u96C6\u9879\u76EE\u4FE1\u606F**\uFF08\u5FC5\u987B\u6B65\u9AA4\uFF09
|
|
1699
|
+
- \u4F7F\u7528 glob + read_file \u9605\u8BFB README.md\u3001\u8BBE\u8BA1\u6587\u6863
|
|
1700
|
+
- \u4F7F\u7528 bash + glob \u4E86\u89E3\u4EE3\u7801\u7ED3\u6784\u548C\u4F9D\u8D56
|
|
1701
|
+
- \u56DE\u987E\u73B0\u6709\u9879\u76EE\u8BB0\u5FC6
|
|
1702
|
+
|
|
1703
|
+
2. \u7406\u89E3\u73B0\u6709\u9879\u76EE\u8BB0\u5FC6
|
|
1704
|
+
3. \u6839\u636E\u7528\u6237\u6307\u5BFC\u786E\u5B9A\u63D0\u70BC\u91CD\u70B9
|
|
1705
|
+
4. \u5206\u6790\u63D0\u70BC\u65B0\u77E5\u8BC6
|
|
1706
|
+
5. \u6574\u5408\u65B0\u65E7\u77E5\u8BC6\uFF0C\u751F\u6210\u5B8C\u6574\u7684\u9879\u76EE\u8BB0\u5FC6
|
|
1707
|
+
6. \u4F7F\u7528 record_memory({ scope: "project", mode: "overwrite", content, title }) \u5199\u5165
|
|
1708
|
+
|
|
1709
|
+
# \u8F93\u51FA\u8981\u6C42
|
|
1710
|
+
\u76F4\u63A5\u8C03\u7528 record_memory \u5DE5\u5177\uFF0C\u5199\u5165\u65B0\u7684\u9879\u76EE\u8BB0\u5FC6\u3002
|
|
1711
|
+
\u8F93\u51FA\u683C\u5F0F\u4E3A Markdown\uFF0C\u4FDD\u6301\u7ED3\u6784\u6E05\u6670\u3002`,
|
|
1712
|
+
"global-memory": `# \u89D2\u8272
|
|
1713
|
+
\u4F60\u662F\u4E00\u4E2A\u5168\u5C40\u8BB0\u5FC6\u7BA1\u7406\u4E13\u5BB6\uFF0C\u8D1F\u8D23\u63D0\u70BC\u8DE8\u9879\u76EE\u7684\u901A\u7528\u77E5\u8BC6\u548C\u7528\u6237\u504F\u597D\u3002
|
|
1714
|
+
|
|
1715
|
+
# \u4F60\u7684\u804C\u8D23
|
|
1716
|
+
1. **\u7528\u6237\u753B\u50CF**\uFF1A\u63D0\u70BC\u7528\u6237\u7684\u6C9F\u901A\u98CE\u683C\u3001\u6280\u672F\u504F\u597D\u3001\u5DE5\u4F5C\u4E60\u60EF
|
|
1717
|
+
2. **\u76EE\u6807\u8FFD\u8E2A**\uFF1A\u8BB0\u5F55\u7528\u6237\u7684\u957F\u671F\u76EE\u6807\u3001\u5F53\u524D\u4EFB\u52A1\u3001\u8FDB\u5EA6
|
|
1718
|
+
3. **\u901A\u7528\u89C4\u5219**\uFF1A\u63D0\u70BC\u8DE8\u9879\u76EE\u90FD\u9002\u7528\u7684\u884C\u4E3A\u89C4\u8303
|
|
1719
|
+
4. **\u9057\u5FD8\u5904\u7406**\uFF1A\u6807\u8BB0\u6216\u79FB\u9664\u4E0D\u518D\u76F8\u5173\u7684\u76EE\u6807\u548C\u4FE1\u606F
|
|
1720
|
+
|
|
1721
|
+
# \u5168\u5C40\u8BB0\u5FC6\u5185\u5BB9\u7C7B\u578B
|
|
1722
|
+
- \u7528\u6237\u504F\u597D\uFF1A\u6C9F\u901A\u98CE\u683C\uFF08\u7B80\u6D01/\u8BE6\u7EC6\uFF09\u3001\u53CD\u9988\u504F\u597D\u3001\u51B3\u7B56\u98CE\u683C
|
|
1723
|
+
- \u6280\u672F\u503E\u5411\uFF1A\u504F\u597D\u7684\u6280\u672F\u6808\u3001\u6846\u67B6\u3001\u8BED\u8A00\u3001\u5F00\u53D1\u5DE5\u5177
|
|
1724
|
+
- \u5DE5\u4F5C\u4E60\u60EF\uFF1A\u5DE5\u4F5C\u65F6\u95F4\u3001\u4E13\u6CE8\u5468\u671F\u3001\u504F\u597D\u65F6\u6BB5
|
|
1725
|
+
- \u5F53\u524D\u76EE\u6807\uFF1A\u6B63\u5728\u8FDB\u884C\u7684\u4E8B\u9879\u3001\u77ED\u671F\u76EE\u6807\uFF081-3\u6708\uFF09
|
|
1726
|
+
- \u957F\u671F\u613F\u666F\uFF1A\u5927\u65B9\u5411\u3001\u6218\u7565\u76EE\u6807\u3001\u4EBA\u751F\u9636\u6BB5
|
|
1727
|
+
- \u8DE8\u9879\u76EE\u89C4\u8303\uFF1A\u6240\u6709\u9879\u76EE\u90FD\u9075\u5FAA\u7684\u901A\u7528\u89C4\u5219
|
|
1728
|
+
|
|
1729
|
+
# \u63D0\u70BC\u539F\u5219
|
|
1730
|
+
1. **\u4EE5\u7528\u6237\u4E3A\u4E2D\u5FC3**\uFF1A\u5173\u6CE8\u7528\u6237\u600E\u4E48\u8BF4\u3001\u600E\u4E48\u60F3\uFF0C\u4E0D\u53EA\u662F\u505A\u4EC0\u4E48
|
|
1731
|
+
2. **\u76EE\u6807\u5BFC\u5411**\uFF1A\u533A\u5206\u5DF2\u5B8C\u6210\u3001\u8FDB\u884C\u4E2D\u3001\u8BA1\u5212\u4E2D
|
|
1732
|
+
3. **\u53EF\u64CD\u4F5C\u6027**\uFF1A\u504F\u597D\u8981\u5177\u4F53\uFF0C\u5982"\u7528\u6237\u559C\u6B22\u5148\u770B\u7ED3\u8BBA"\u800C\u975E"\u7528\u6237\u5F88\u5FD9"
|
|
1733
|
+
4. **\u65F6\u95F4\u654F\u611F**\uFF1A\u6807\u8BB0\u6709\u65F6\u95F4\u9650\u5236\u7684\u76EE\u6807
|
|
1734
|
+
|
|
1735
|
+
# \u7528\u6237\u6307\u5BFC
|
|
1736
|
+
{USER_REQUIREMENT}
|
|
1737
|
+
|
|
1738
|
+
# \u4F5C\u7528\u57DF
|
|
1739
|
+
{SCOPE}
|
|
1740
|
+
|
|
1741
|
+
# \u73B0\u6709\u5168\u5C40\u8BB0\u5FC6
|
|
1742
|
+
{CURRENT_MEMORY}
|
|
1743
|
+
|
|
1744
|
+
# \u53EF\u7528\u5DE5\u5177
|
|
1745
|
+
- search_sessions(query, session_id?, limit?): \u641C\u7D22\u4F1A\u8BDD\u5386\u53F2
|
|
1746
|
+
- get_session(session_id): \u83B7\u53D6\u6307\u5B9A\u4F1A\u8BDD
|
|
1747
|
+
- record_memory({ scope, mode, content, title }): \u5199\u5165\u8BB0\u5FC6\u6587\u4EF6
|
|
1748
|
+
|
|
1749
|
+
# \u6267\u884C\u6D41\u7A0B
|
|
1750
|
+
1. \u7406\u89E3\u73B0\u6709\u5168\u5C40\u8BB0\u5FC6
|
|
1751
|
+
2. \u6839\u636E\u7528\u6237\u6307\u5BFC\u786E\u5B9A\u63D0\u70BC\u91CD\u70B9
|
|
1752
|
+
3. \u4F7F\u7528\u5DE5\u5177\u641C\u7D22\u76F8\u5173\u4F1A\u8BDD\u5386\u53F2
|
|
1753
|
+
4. \u5206\u6790\u63D0\u70BC\u65B0\u77E5\u8BC6
|
|
1754
|
+
5. \u6574\u5408\u65B0\u65E7\u77E5\u8BC6\uFF0C\u751F\u6210\u5B8C\u6574\u7684\u5168\u5C40\u8BB0\u5FC6
|
|
1755
|
+
6. \u4F7F\u7528 record_memory({ scope: "global", mode: "overwrite", content, title }) \u5199\u5165
|
|
1756
|
+
|
|
1757
|
+
# \u8F93\u51FA\u8981\u6C42
|
|
1758
|
+
\u76F4\u63A5\u8C03\u7528 record_memory \u5DE5\u5177\uFF0C\u5199\u5165\u65B0\u7684\u5168\u5C40\u8BB0\u5FC6\u3002
|
|
1759
|
+
\u8F93\u51FA\u683C\u5F0F\u4E3A Markdown\uFF0C\u4FDD\u6301\u7ED3\u6784\u6E05\u6670\u3002`
|
|
1760
|
+
};
|
|
1761
|
+
function getBuiltInPromptNames() {
|
|
1762
|
+
return Object.keys(builtInPrompts);
|
|
1763
|
+
}
|
|
1764
|
+
function getBuiltInPrompt(name) {
|
|
1765
|
+
return builtInPrompts[name];
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
// packages/core/src/env/prompt/prompt-component.ts
|
|
1769
|
+
var logger = createLogger("prompt");
|
|
1770
|
+
|
|
1771
|
+
class PromptComponent extends BaseComponent {
|
|
1772
|
+
name = "prompt";
|
|
1773
|
+
version = "1.0.0";
|
|
1774
|
+
prompts = new Map;
|
|
1775
|
+
config;
|
|
1776
|
+
configComponent;
|
|
1777
|
+
renderer;
|
|
1778
|
+
configWatcher;
|
|
1779
|
+
constructor() {
|
|
1780
|
+
super();
|
|
1781
|
+
}
|
|
1782
|
+
async init(config) {
|
|
1783
|
+
await super.init(config);
|
|
1784
|
+
const options = config.options;
|
|
1785
|
+
if (!options?.configComponent) {
|
|
1786
|
+
throw new Error("ConfigComponent is required for PromptComponent initialization");
|
|
1787
|
+
}
|
|
1788
|
+
this.configComponent = options.configComponent;
|
|
1789
|
+
await this.registerConfig(options);
|
|
1790
|
+
this.initRenderer();
|
|
1791
|
+
await this.loadPrompts();
|
|
1792
|
+
this.setStatus("running");
|
|
1793
|
+
logger.info(`[PromptComponent] Initialized with ${this.prompts.size} prompts`);
|
|
1794
|
+
}
|
|
1795
|
+
async registerConfig(options) {
|
|
1796
|
+
const configComponent = options.configComponent;
|
|
1797
|
+
if (!configComponent)
|
|
1798
|
+
return;
|
|
1799
|
+
const { config, defaultName, promptPaths, variablePrefix, variableSuffix } = options;
|
|
1800
|
+
configComponent.registerComponent(PROMPT_CONFIG_REGISTRATION);
|
|
1801
|
+
await configComponent.load("prompt");
|
|
1802
|
+
const prefix = "PROMPT";
|
|
1803
|
+
const promptKeys = [
|
|
1804
|
+
"prompt.defaultName",
|
|
1805
|
+
"prompt.promptPaths",
|
|
1806
|
+
"prompt.variablePrefix",
|
|
1807
|
+
"prompt.variableSuffix",
|
|
1808
|
+
"prompt.strictMode"
|
|
1809
|
+
];
|
|
1810
|
+
for (const key of promptKeys) {
|
|
1811
|
+
const envKey = toEnvKey(key, prefix);
|
|
1812
|
+
const value = process.env[envKey];
|
|
1813
|
+
if (value !== undefined) {
|
|
1814
|
+
await configComponent.set(key, value);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
const loadedKeys = new Set(promptKeys);
|
|
1818
|
+
for (const envKey of Object.keys(process.env)) {
|
|
1819
|
+
const configKey = envKeyToConfigKey(envKey, prefix, "prompt");
|
|
1820
|
+
if (!configKey)
|
|
1821
|
+
continue;
|
|
1822
|
+
if (loadedKeys.has(configKey))
|
|
1823
|
+
continue;
|
|
1824
|
+
loadedKeys.add(configKey);
|
|
1825
|
+
const value = process.env[envKey];
|
|
1826
|
+
if (value !== undefined) {
|
|
1827
|
+
await configComponent.set(configKey, value);
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
for (const [key, value] of Object.entries(PROMPT_DEFAULTS)) {
|
|
1831
|
+
if (configComponent.get(key) === undefined) {
|
|
1832
|
+
await configComponent.set(key, value);
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
if (config) {
|
|
1836
|
+
const flatConfig = this.flattenConfig(config);
|
|
1837
|
+
for (const [key, value] of Object.entries(flatConfig)) {
|
|
1838
|
+
await configComponent.set(key, value);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
if (defaultName !== undefined) {
|
|
1842
|
+
await configComponent.set("prompt.defaultName", defaultName);
|
|
1843
|
+
}
|
|
1844
|
+
if (promptPaths !== undefined) {
|
|
1845
|
+
await configComponent.set("prompt.promptPaths", promptPaths);
|
|
1846
|
+
}
|
|
1847
|
+
if (variablePrefix !== undefined) {
|
|
1848
|
+
await configComponent.set("prompt.variablePrefix", variablePrefix);
|
|
1849
|
+
}
|
|
1850
|
+
if (variableSuffix !== undefined) {
|
|
1851
|
+
await configComponent.set("prompt.variableSuffix", variableSuffix);
|
|
1852
|
+
}
|
|
1853
|
+
this.registerConfigWatcher(configComponent);
|
|
1854
|
+
this.config = {
|
|
1855
|
+
defaultName: configComponent.get("prompt.defaultName") || "default",
|
|
1856
|
+
promptPaths: configComponent.get("prompt.promptPaths") || [],
|
|
1857
|
+
variablePrefix: configComponent.get("prompt.variablePrefix") || "{{",
|
|
1858
|
+
variableSuffix: configComponent.get("prompt.variableSuffix") || "}}",
|
|
1859
|
+
strictMode: configComponent.get("prompt.strictMode") || false
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
flattenConfig(obj, prefix = "prompt") {
|
|
1863
|
+
const result = {};
|
|
1864
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
1865
|
+
const fullKey = `${prefix}.${key}`;
|
|
1866
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
1867
|
+
Object.assign(result, this.flattenConfig(value, fullKey));
|
|
1868
|
+
} else {
|
|
1869
|
+
result[fullKey] = value;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
return result;
|
|
1873
|
+
}
|
|
1874
|
+
registerConfigWatcher(configComponent) {
|
|
1875
|
+
if (typeof configComponent.watch !== "function") {
|
|
1876
|
+
return;
|
|
1877
|
+
}
|
|
1878
|
+
this.configWatcher = configComponent.watch("prompt.*", (event) => {
|
|
1879
|
+
this.onConfigChange(event);
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
onConfigChange(event) {
|
|
1883
|
+
const key = event.key;
|
|
1884
|
+
const value = event.newValue;
|
|
1885
|
+
if (value === undefined)
|
|
1886
|
+
return;
|
|
1887
|
+
logger.debug(`[PromptComponent] Config updated: ${key} = ${JSON.stringify(value)}`);
|
|
1888
|
+
switch (key) {
|
|
1889
|
+
case "prompt.defaultName":
|
|
1890
|
+
if (this.config)
|
|
1891
|
+
this.config.defaultName = value;
|
|
1892
|
+
break;
|
|
1893
|
+
case "prompt.promptPaths":
|
|
1894
|
+
if (this.config)
|
|
1895
|
+
this.config.promptPaths = value;
|
|
1896
|
+
break;
|
|
1897
|
+
case "prompt.variablePrefix":
|
|
1898
|
+
if (this.config) {
|
|
1899
|
+
this.config.variablePrefix = value;
|
|
1900
|
+
this.initRenderer();
|
|
1901
|
+
}
|
|
1902
|
+
break;
|
|
1903
|
+
case "prompt.variableSuffix":
|
|
1904
|
+
if (this.config) {
|
|
1905
|
+
this.config.variableSuffix = value;
|
|
1906
|
+
this.initRenderer();
|
|
1907
|
+
}
|
|
1908
|
+
break;
|
|
1909
|
+
case "prompt.strictMode":
|
|
1910
|
+
if (this.config)
|
|
1911
|
+
this.config.strictMode = value;
|
|
1912
|
+
break;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
initRenderer() {
|
|
1916
|
+
const config = this.config || {
|
|
1917
|
+
defaultName: "default",
|
|
1918
|
+
promptPaths: [],
|
|
1919
|
+
variablePrefix: "{{",
|
|
1920
|
+
variableSuffix: "}}",
|
|
1921
|
+
strictMode: false
|
|
1922
|
+
};
|
|
1923
|
+
this.renderer = new PromptRenderer({
|
|
1924
|
+
prefix: config.variablePrefix,
|
|
1925
|
+
suffix: config.variableSuffix,
|
|
1926
|
+
strict: config.strictMode,
|
|
1927
|
+
onMissingVariable: (name) => {
|
|
1928
|
+
logger.warn(`Undefined variable: ${name}`);
|
|
1929
|
+
return `{{${name}}}`;
|
|
1930
|
+
}
|
|
1931
|
+
});
|
|
1932
|
+
}
|
|
1933
|
+
async onStart() {
|
|
1934
|
+
logger.info("[PromptComponent] Started");
|
|
1935
|
+
}
|
|
1936
|
+
async onStop() {
|
|
1937
|
+
this.prompts.clear();
|
|
1938
|
+
this.setStatus("stopped");
|
|
1939
|
+
logger.info("[PromptComponent] Stopped");
|
|
1940
|
+
}
|
|
1941
|
+
getPromptConfig(key, defaultValue) {
|
|
1942
|
+
if (this.config && key in this.config) {
|
|
1943
|
+
return this.config[key] ?? defaultValue;
|
|
1944
|
+
}
|
|
1945
|
+
return defaultValue;
|
|
1946
|
+
}
|
|
1947
|
+
add(name, content, source = "inline") {
|
|
1948
|
+
const entry = {
|
|
1949
|
+
name,
|
|
1950
|
+
content,
|
|
1951
|
+
source,
|
|
1952
|
+
overridable: true,
|
|
1953
|
+
loadedAt: Date.now()
|
|
1954
|
+
};
|
|
1955
|
+
const existing = this.prompts.get(name);
|
|
1956
|
+
if (existing && !existing.overridable) {
|
|
1957
|
+
logger.debug(`[PromptComponent] Skip override for non-overridable prompt: ${name}`);
|
|
1958
|
+
return;
|
|
1959
|
+
}
|
|
1960
|
+
this.prompts.set(name, entry);
|
|
1961
|
+
logger.debug(`[PromptComponent] Added prompt: ${name} (${source})`);
|
|
1962
|
+
}
|
|
1963
|
+
get(name) {
|
|
1964
|
+
return this.prompts.get(name)?.content;
|
|
1965
|
+
}
|
|
1966
|
+
getEntry(name) {
|
|
1967
|
+
return this.prompts.get(name);
|
|
1968
|
+
}
|
|
1969
|
+
has(name) {
|
|
1970
|
+
return this.prompts.has(name);
|
|
1971
|
+
}
|
|
1972
|
+
delete(name) {
|
|
1973
|
+
return this.prompts.delete(name);
|
|
1974
|
+
}
|
|
1975
|
+
list() {
|
|
1976
|
+
return Array.from(this.prompts.keys());
|
|
1977
|
+
}
|
|
1978
|
+
size() {
|
|
1979
|
+
return this.prompts.size;
|
|
1980
|
+
}
|
|
1981
|
+
async getPrompt(name, variables = {}) {
|
|
1982
|
+
const defaultName = this.getPromptConfig("defaultName", "default");
|
|
1983
|
+
const targetName = this.has(name) ? name : defaultName;
|
|
1984
|
+
const entry = this.prompts.get(targetName);
|
|
1985
|
+
if (!entry) {
|
|
1986
|
+
logger.warn(`[PromptComponent] Prompt not found: ${name}, using fallback`);
|
|
1987
|
+
return "You are a helpful assistant.";
|
|
1988
|
+
}
|
|
1989
|
+
return this.render(entry.content, variables, { name: targetName });
|
|
1990
|
+
}
|
|
1991
|
+
async render(content, variables = {}, context) {
|
|
1992
|
+
const hookContext = {
|
|
1993
|
+
name: context?.name || "anonymous",
|
|
1994
|
+
originalContent: content,
|
|
1995
|
+
renderedContent: content,
|
|
1996
|
+
variables
|
|
1997
|
+
};
|
|
1998
|
+
await this.executeHooks(PromptHookPoints.BEFORE_RENDER, hookContext);
|
|
1999
|
+
hookContext.renderedContent = this.renderer.render(hookContext.originalContent, variables);
|
|
2000
|
+
await this.executeHooks(PromptHookPoints.AFTER_RENDER, hookContext);
|
|
2001
|
+
return hookContext.renderedContent;
|
|
2002
|
+
}
|
|
2003
|
+
extractVariables(content) {
|
|
2004
|
+
return this.renderer.extractVariables(content);
|
|
2005
|
+
}
|
|
2006
|
+
async loadPrompts() {
|
|
2007
|
+
await this.loadBuiltInPrompts();
|
|
2008
|
+
await this.loadExternalPrompts();
|
|
2009
|
+
}
|
|
2010
|
+
async loadBuiltInPrompts() {
|
|
2011
|
+
for (const [name, content] of Object.entries(builtInPrompts)) {
|
|
2012
|
+
if (content) {
|
|
2013
|
+
this.prompts.set(name, {
|
|
2014
|
+
name,
|
|
2015
|
+
content,
|
|
2016
|
+
source: "built-in",
|
|
2017
|
+
overridable: false,
|
|
2018
|
+
loadedAt: Date.now()
|
|
2019
|
+
});
|
|
2020
|
+
logger.debug(`[PromptComponent] Loaded built-in prompt: ${name}`);
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
logger.info(`[PromptComponent] Loaded ${this.prompts.size} built-in prompts`);
|
|
2024
|
+
}
|
|
2025
|
+
async loadExternalPrompts() {
|
|
2026
|
+
const promptPaths = this.getPromptConfig("promptPaths", []);
|
|
2027
|
+
for (const pathConfig of promptPaths) {
|
|
2028
|
+
try {
|
|
2029
|
+
if (pathConfig.type === "file") {
|
|
2030
|
+
await this.loadFromFile(pathConfig.path, pathConfig.name);
|
|
2031
|
+
} else if (pathConfig.type === "directory") {
|
|
2032
|
+
await this.loadFromDirectory(pathConfig.path, pathConfig.extension || ".md", pathConfig.recursive !== false);
|
|
2033
|
+
}
|
|
2034
|
+
} catch (error) {
|
|
2035
|
+
logger.error(`[PromptComponent] Failed to load from ${pathConfig.path}:`, error);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
async loadFromFile(filePath, name) {
|
|
2040
|
+
try {
|
|
2041
|
+
const content = await readFile(filePath, "utf-8");
|
|
2042
|
+
const promptName = name || basename2(filePath, extname(filePath));
|
|
2043
|
+
this.add(promptName, content.trim(), "file");
|
|
2044
|
+
const entry = this.prompts.get(promptName);
|
|
2045
|
+
if (entry)
|
|
2046
|
+
entry.filePath = filePath;
|
|
2047
|
+
logger.debug(`[PromptComponent] Loaded prompt from file: ${filePath}`);
|
|
2048
|
+
return true;
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
logger.error(`[PromptComponent] Failed to load file ${filePath}:`, error);
|
|
2051
|
+
return false;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
async loadFromDirectory(directory, extension = ".md", recursive = true) {
|
|
2055
|
+
let loaded = 0;
|
|
2056
|
+
try {
|
|
2057
|
+
const files = await this.findFiles(directory, extension, recursive);
|
|
2058
|
+
for (const filePath of files) {
|
|
2059
|
+
const relativePath = filePath.replace(directory + "/", "");
|
|
2060
|
+
const promptName = relativePath.replace(/\\/g, "/").replace(new RegExp(escapeRegex2(extension) + "$"), "").replace(/\//g, "-");
|
|
2061
|
+
const content = await readFile(filePath, "utf-8");
|
|
2062
|
+
this.add(promptName, content.trim(), "directory");
|
|
2063
|
+
const entry = this.prompts.get(promptName);
|
|
2064
|
+
if (entry)
|
|
2065
|
+
entry.filePath = filePath;
|
|
2066
|
+
loaded++;
|
|
2067
|
+
}
|
|
2068
|
+
logger.info(`[PromptComponent] Loaded ${loaded} prompts from directory: ${directory}`);
|
|
2069
|
+
} catch (error) {
|
|
2070
|
+
logger.error(`[PromptComponent] Failed to load directory ${directory}:`, error);
|
|
2071
|
+
}
|
|
2072
|
+
return loaded;
|
|
2073
|
+
}
|
|
2074
|
+
async findFiles(dir, extension, recursive) {
|
|
2075
|
+
const files = [];
|
|
2076
|
+
try {
|
|
2077
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
2078
|
+
for (const entry of entries) {
|
|
2079
|
+
const fullPath = join2(dir, entry.name);
|
|
2080
|
+
if (entry.isDirectory() && recursive) {
|
|
2081
|
+
const subFiles = await this.findFiles(fullPath, extension, true);
|
|
2082
|
+
files.push(...subFiles);
|
|
2083
|
+
} else if (entry.isFile() && entry.name.endsWith(extension)) {
|
|
2084
|
+
files.push(fullPath);
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
} catch (error) {
|
|
2088
|
+
logger.warn(`[PromptComponent] Cannot read directory ${dir}:`, error);
|
|
2089
|
+
}
|
|
2090
|
+
return files;
|
|
2091
|
+
}
|
|
2092
|
+
registerPromptHook(hookPoint, name, fn, priority) {
|
|
2093
|
+
this.addHook(hookPoint, name, fn, priority);
|
|
2094
|
+
}
|
|
2095
|
+
getHookPoints() {
|
|
2096
|
+
return [PromptHookPoints.BEFORE_RENDER, PromptHookPoints.AFTER_RENDER];
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
function escapeRegex2(str) {
|
|
2100
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2101
|
+
}
|
|
2102
|
+
export {
|
|
2103
|
+
PromptRenderer,
|
|
2104
|
+
PromptPathSchema,
|
|
2105
|
+
PromptConfigSchema,
|
|
2106
|
+
PromptComponent
|
|
2107
|
+
};
|