@ai-setting/roy-agent-core 1.4.11 → 1.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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,2049 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
function __accessProp(key) {
|
|
7
|
+
return this[key];
|
|
8
|
+
}
|
|
9
|
+
var __toCommonJS = (from) => {
|
|
10
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
11
|
+
if (entry)
|
|
12
|
+
return entry;
|
|
13
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (var key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(entry, key))
|
|
17
|
+
__defProp(entry, key, {
|
|
18
|
+
get: __accessProp.bind(from, key),
|
|
19
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
__moduleCache.set(from, entry);
|
|
23
|
+
return entry;
|
|
24
|
+
};
|
|
25
|
+
var __moduleCache;
|
|
26
|
+
var __returnValue = (v) => v;
|
|
27
|
+
function __exportSetter(name, newValue) {
|
|
28
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
29
|
+
}
|
|
30
|
+
var __export = (target, all) => {
|
|
31
|
+
for (var name in all)
|
|
32
|
+
__defProp(target, name, {
|
|
33
|
+
get: all[name],
|
|
34
|
+
enumerable: true,
|
|
35
|
+
configurable: true,
|
|
36
|
+
set: __exportSetter.bind(all, name)
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
|
|
40
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
41
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
|
|
42
|
+
r = Reflect.decorate(decorators, target, key, desc);
|
|
43
|
+
else
|
|
44
|
+
for (var i = decorators.length - 1;i >= 0; i--)
|
|
45
|
+
if (d = decorators[i])
|
|
46
|
+
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
47
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
48
|
+
};
|
|
49
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
50
|
+
var __require = import.meta.require;
|
|
51
|
+
|
|
52
|
+
// packages/core/src/env/log-trace/span-storage.ts
|
|
53
|
+
var exports_span_storage = {};
|
|
54
|
+
__export(exports_span_storage, {
|
|
55
|
+
SQLiteSpanStorage: () => SQLiteSpanStorage
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
class SQLiteSpanStorage {
|
|
59
|
+
db = null;
|
|
60
|
+
dbPath;
|
|
61
|
+
initialized = false;
|
|
62
|
+
constructor(dbPath) {
|
|
63
|
+
if (!dbPath) {
|
|
64
|
+
throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
|
|
65
|
+
}
|
|
66
|
+
if (dbPath === ":memory:") {
|
|
67
|
+
throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
|
|
68
|
+
}
|
|
69
|
+
this.dbPath = dbPath;
|
|
70
|
+
}
|
|
71
|
+
async initialize() {
|
|
72
|
+
if (this.initialized)
|
|
73
|
+
return;
|
|
74
|
+
const { Database } = __require("bun:sqlite");
|
|
75
|
+
const fs = __require("fs");
|
|
76
|
+
const path = __require("path");
|
|
77
|
+
const dir = path.dirname(this.dbPath);
|
|
78
|
+
if (!fs.existsSync(dir)) {
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
this.db = new Database(this.dbPath);
|
|
82
|
+
this.db.run("PRAGMA journal_mode=WAL");
|
|
83
|
+
this.db.run("PRAGMA busy_timeout=5000");
|
|
84
|
+
this.db.run("PRAGMA synchronous=NORMAL");
|
|
85
|
+
this.db.run(`
|
|
86
|
+
CREATE TABLE IF NOT EXISTS span (
|
|
87
|
+
span_id TEXT PRIMARY KEY,
|
|
88
|
+
trace_id TEXT NOT NULL,
|
|
89
|
+
parent_span_id TEXT,
|
|
90
|
+
name TEXT NOT NULL,
|
|
91
|
+
kind TEXT NOT NULL,
|
|
92
|
+
status TEXT NOT NULL,
|
|
93
|
+
start_time INTEGER NOT NULL,
|
|
94
|
+
end_time INTEGER,
|
|
95
|
+
attributes TEXT,
|
|
96
|
+
result TEXT,
|
|
97
|
+
error TEXT,
|
|
98
|
+
time_created INTEGER NOT NULL
|
|
99
|
+
)
|
|
100
|
+
`);
|
|
101
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
|
|
102
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
|
|
103
|
+
this.initialized = true;
|
|
104
|
+
}
|
|
105
|
+
save(span) {
|
|
106
|
+
if (!this.db)
|
|
107
|
+
return;
|
|
108
|
+
const stmt = this.db.prepare(`
|
|
109
|
+
INSERT OR REPLACE INTO span
|
|
110
|
+
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
111
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
112
|
+
`);
|
|
113
|
+
const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
|
|
114
|
+
stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, JSON.stringify(span.attributes), resultValue, span.error || null, Date.now());
|
|
115
|
+
}
|
|
116
|
+
saveBatch(spans) {
|
|
117
|
+
for (const span of spans) {
|
|
118
|
+
this.save(span);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
findByTraceId(traceId) {
|
|
122
|
+
if (!this.db)
|
|
123
|
+
return [];
|
|
124
|
+
const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
|
|
125
|
+
return this.buildTree(rows.map(this.rowToSpan));
|
|
126
|
+
}
|
|
127
|
+
findBySpanId(spanId) {
|
|
128
|
+
if (!this.db)
|
|
129
|
+
return;
|
|
130
|
+
const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
|
|
131
|
+
return row ? this.rowToSpan(row) : undefined;
|
|
132
|
+
}
|
|
133
|
+
listTraces(limit = 10) {
|
|
134
|
+
if (!this.db)
|
|
135
|
+
return [];
|
|
136
|
+
const rows = this.db.prepare(`
|
|
137
|
+
SELECT trace_id,
|
|
138
|
+
MIN(start_time) as start_time,
|
|
139
|
+
MAX(end_time) as end_time,
|
|
140
|
+
COUNT(*) as span_count
|
|
141
|
+
FROM span
|
|
142
|
+
GROUP BY trace_id
|
|
143
|
+
ORDER BY start_time DESC
|
|
144
|
+
LIMIT ?
|
|
145
|
+
`).all(limit);
|
|
146
|
+
return rows.map((row) => ({
|
|
147
|
+
traceId: row.trace_id,
|
|
148
|
+
rootSpanName: "unknown",
|
|
149
|
+
startTime: row.start_time,
|
|
150
|
+
endTime: row.end_time,
|
|
151
|
+
duration: row.end_time - row.start_time,
|
|
152
|
+
spanCount: row.span_count,
|
|
153
|
+
status: "ok"
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
deleteByTraceId(traceId) {
|
|
157
|
+
if (this.db) {
|
|
158
|
+
this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
close() {
|
|
162
|
+
if (this.db) {
|
|
163
|
+
this.db.close();
|
|
164
|
+
this.db = null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
rowToSpan(row) {
|
|
168
|
+
return {
|
|
169
|
+
traceId: row.trace_id,
|
|
170
|
+
spanId: row.span_id,
|
|
171
|
+
parentSpanId: row.parent_span_id,
|
|
172
|
+
name: row.name,
|
|
173
|
+
kind: row.kind,
|
|
174
|
+
status: row.status,
|
|
175
|
+
startTime: row.start_time,
|
|
176
|
+
endTime: row.end_time,
|
|
177
|
+
attributes: row.attributes ? JSON.parse(row.attributes) : {},
|
|
178
|
+
result: row.result || undefined,
|
|
179
|
+
error: row.error || undefined
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
buildTree(spans) {
|
|
183
|
+
const spanMap = new Map;
|
|
184
|
+
const roots = [];
|
|
185
|
+
for (const span of spans) {
|
|
186
|
+
spanMap.set(span.spanId, { ...span, children: [] });
|
|
187
|
+
}
|
|
188
|
+
for (const span of spanMap.values()) {
|
|
189
|
+
if (span.parentSpanId) {
|
|
190
|
+
const parent = spanMap.get(span.parentSpanId);
|
|
191
|
+
if (parent) {
|
|
192
|
+
parent.children.push(span);
|
|
193
|
+
} else {
|
|
194
|
+
roots.push(span);
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
roots.push(span);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return roots;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// packages/core/src/env/log-trace/opentelemetry/propagation.ts
|
|
205
|
+
function padLeft(str, length) {
|
|
206
|
+
return str.padStart(length, "0");
|
|
207
|
+
}
|
|
208
|
+
function isValidHex(str) {
|
|
209
|
+
return /^[0-9a-f]+$/i.test(str);
|
|
210
|
+
}
|
|
211
|
+
function serialize(context) {
|
|
212
|
+
const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);
|
|
213
|
+
const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
|
|
214
|
+
const parts = [
|
|
215
|
+
TRACE_CONTEXT_VERSION,
|
|
216
|
+
traceId,
|
|
217
|
+
spanId,
|
|
218
|
+
TRACE_FLAGS_SAMPLED
|
|
219
|
+
];
|
|
220
|
+
return parts.join("-");
|
|
221
|
+
}
|
|
222
|
+
function parse(traceparent) {
|
|
223
|
+
if (!traceparent || typeof traceparent !== "string") {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const trimmed = traceparent.trim();
|
|
227
|
+
const parts = trimmed.split("-");
|
|
228
|
+
if (parts.length !== 4) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const [version, traceId, senderSpanId, flags] = parts;
|
|
232
|
+
if (version !== TRACE_CONTEXT_VERSION) {
|
|
233
|
+
if (version > TRACE_CONTEXT_VERSION) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
traceId: traceId.toLowerCase(),
|
|
248
|
+
spanId: senderSpanId.toLowerCase()
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
var TRACE_CONTEXT_VERSION = "00", TRACE_FLAGS_SAMPLED = "01", TRACEPARENT_HEADER = "TRACEPARENT", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;
|
|
252
|
+
var init_propagation = __esm(() => {
|
|
253
|
+
propagation = {
|
|
254
|
+
inject(carrier, context) {
|
|
255
|
+
carrier[TRACEPARENT_HEADER] = serialize(context);
|
|
256
|
+
},
|
|
257
|
+
extract(carrier) {
|
|
258
|
+
const traceparent = carrier[TRACEPARENT_HEADER];
|
|
259
|
+
if (!traceparent) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
return parse(traceparent);
|
|
263
|
+
},
|
|
264
|
+
getTraceparentHeader() {
|
|
265
|
+
return TRACEPARENT_HEADER;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// packages/core/src/env/log-trace/types.ts
|
|
271
|
+
var SpanKind, SpanStatus;
|
|
272
|
+
var init_types = __esm(() => {
|
|
273
|
+
((SpanKind2) => {
|
|
274
|
+
SpanKind2["CLIENT"] = "client";
|
|
275
|
+
SpanKind2["SERVER"] = "server";
|
|
276
|
+
SpanKind2["INTERNAL"] = "internal";
|
|
277
|
+
})(SpanKind ||= {});
|
|
278
|
+
((SpanStatus2) => {
|
|
279
|
+
SpanStatus2["OK"] = "ok";
|
|
280
|
+
SpanStatus2["ERROR"] = "error";
|
|
281
|
+
})(SpanStatus ||= {});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// packages/core/src/env/log-trace/opentelemetry/tracer-provider.ts
|
|
285
|
+
var exports_tracer_provider = {};
|
|
286
|
+
__export(exports_tracer_provider, {
|
|
287
|
+
resetTracerProvider: () => resetTracerProvider,
|
|
288
|
+
getTracerProvider: () => getTracerProvider,
|
|
289
|
+
OTelTracerProvider: () => OTelTracerProvider
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
class OTelSpanImpl {
|
|
293
|
+
name;
|
|
294
|
+
kind;
|
|
295
|
+
spanContext;
|
|
296
|
+
attributes = {};
|
|
297
|
+
startTime;
|
|
298
|
+
endTime;
|
|
299
|
+
error;
|
|
300
|
+
storage;
|
|
301
|
+
parentSpanContext;
|
|
302
|
+
onEnd;
|
|
303
|
+
constructor(name, spanContext, storage, parentSpanContext, onEnd) {
|
|
304
|
+
this.name = name;
|
|
305
|
+
this.kind = "internal";
|
|
306
|
+
this.spanContext = spanContext;
|
|
307
|
+
this.parentSpanContext = parentSpanContext;
|
|
308
|
+
this.startTime = Date.now();
|
|
309
|
+
this.storage = storage;
|
|
310
|
+
this.onEnd = onEnd;
|
|
311
|
+
}
|
|
312
|
+
setAttribute(key, value) {
|
|
313
|
+
this.attributes[key] = value;
|
|
314
|
+
}
|
|
315
|
+
addEvent(name, attributes) {
|
|
316
|
+
const events = this.attributes._events || [];
|
|
317
|
+
events.push({ name, attributes });
|
|
318
|
+
this.attributes._events = events;
|
|
319
|
+
}
|
|
320
|
+
end(result, error) {
|
|
321
|
+
this.endTime = Date.now();
|
|
322
|
+
if (error) {
|
|
323
|
+
this.error = error.message;
|
|
324
|
+
}
|
|
325
|
+
this.storage.save({
|
|
326
|
+
traceId: this.spanContext.traceId,
|
|
327
|
+
spanId: this.spanContext.spanId,
|
|
328
|
+
parentSpanId: this.spanContext.parentSpanId,
|
|
329
|
+
name: this.name,
|
|
330
|
+
kind: this.kind,
|
|
331
|
+
status: error ? "error" /* ERROR */ : "ok" /* OK */,
|
|
332
|
+
startTime: this.startTime,
|
|
333
|
+
endTime: this.endTime,
|
|
334
|
+
attributes: this.attributes,
|
|
335
|
+
result,
|
|
336
|
+
error: this.error
|
|
337
|
+
});
|
|
338
|
+
this.onEnd?.();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
class OTelTracerImpl {
|
|
343
|
+
name;
|
|
344
|
+
version;
|
|
345
|
+
storage;
|
|
346
|
+
currentContext;
|
|
347
|
+
activeSpans = new Map;
|
|
348
|
+
onSpanEndCallback;
|
|
349
|
+
provider;
|
|
350
|
+
constructor(name, version, storage, provider) {
|
|
351
|
+
this.name = name;
|
|
352
|
+
this.version = version;
|
|
353
|
+
this.storage = storage;
|
|
354
|
+
this.provider = provider;
|
|
355
|
+
}
|
|
356
|
+
setOnSpanEndCallback(callback) {
|
|
357
|
+
this.onSpanEndCallback = callback;
|
|
358
|
+
}
|
|
359
|
+
getActiveSpanCount() {
|
|
360
|
+
return this.activeSpans.size;
|
|
361
|
+
}
|
|
362
|
+
startSpan(name, options) {
|
|
363
|
+
const parentFromOptions = options?.parent;
|
|
364
|
+
const hasExplicitParent = options && "parent" in options;
|
|
365
|
+
const globalContext = this.provider.getGlobalContext();
|
|
366
|
+
let effectiveParentContext;
|
|
367
|
+
if (hasExplicitParent) {
|
|
368
|
+
effectiveParentContext = parentFromOptions;
|
|
369
|
+
} else if (this.currentContext) {
|
|
370
|
+
effectiveParentContext = this.currentContext;
|
|
371
|
+
} else if (globalContext) {
|
|
372
|
+
effectiveParentContext = globalContext;
|
|
373
|
+
}
|
|
374
|
+
const traceId = effectiveParentContext?.traceId || this.generateTraceId();
|
|
375
|
+
const spanId = this.generateSpanId();
|
|
376
|
+
let parentSpanId;
|
|
377
|
+
if (hasExplicitParent && parentFromOptions) {
|
|
378
|
+
parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;
|
|
379
|
+
} else if (this.currentContext) {
|
|
380
|
+
parentSpanId = this.currentContext.spanId;
|
|
381
|
+
} else if (globalContext) {
|
|
382
|
+
parentSpanId = globalContext.spanId;
|
|
383
|
+
}
|
|
384
|
+
const spanContext = {
|
|
385
|
+
traceId,
|
|
386
|
+
spanId,
|
|
387
|
+
parentSpanId
|
|
388
|
+
};
|
|
389
|
+
this.currentContext = {
|
|
390
|
+
traceId,
|
|
391
|
+
spanId,
|
|
392
|
+
parentSpanId
|
|
393
|
+
};
|
|
394
|
+
const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));
|
|
395
|
+
if (options?.attributes) {
|
|
396
|
+
for (const [key, value] of Object.entries(options.attributes)) {
|
|
397
|
+
span.setAttribute(key, value);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.activeSpans.set(spanId, span);
|
|
401
|
+
return span;
|
|
402
|
+
}
|
|
403
|
+
injectToEnv(env) {
|
|
404
|
+
if (this.currentContext) {
|
|
405
|
+
propagation.inject(env, this.currentContext);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
getCurrentContext() {
|
|
409
|
+
return this.currentContext;
|
|
410
|
+
}
|
|
411
|
+
setCurrentContext(context) {
|
|
412
|
+
this.currentContext = context;
|
|
413
|
+
}
|
|
414
|
+
endSpan(span) {
|
|
415
|
+
const spanContext = span.spanContext;
|
|
416
|
+
this.activeSpans.delete(spanContext.spanId);
|
|
417
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
418
|
+
if (spanContext.parentSpanId) {
|
|
419
|
+
const parentSpan = this.activeSpans.get(spanContext.parentSpanId);
|
|
420
|
+
if (parentSpan) {
|
|
421
|
+
const parentContext = {
|
|
422
|
+
traceId: spanContext.traceId,
|
|
423
|
+
spanId: parentSpan.spanContext.spanId,
|
|
424
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
425
|
+
};
|
|
426
|
+
this.currentContext = parentContext;
|
|
427
|
+
return parentContext;
|
|
428
|
+
}
|
|
429
|
+
if (currentTraceId) {
|
|
430
|
+
const parentContext = {
|
|
431
|
+
traceId: currentTraceId,
|
|
432
|
+
spanId: spanContext.parentSpanId,
|
|
433
|
+
parentSpanId: undefined
|
|
434
|
+
};
|
|
435
|
+
this.currentContext = parentContext;
|
|
436
|
+
return parentContext;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
this.currentContext = undefined;
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
generateTraceId() {
|
|
443
|
+
const timestamp = Date.now().toString(16).padStart(12, "0");
|
|
444
|
+
const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")).join("");
|
|
445
|
+
return (timestamp + random).slice(0, 32).padStart(32, "0");
|
|
446
|
+
}
|
|
447
|
+
generateSpanId() {
|
|
448
|
+
return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
|
|
449
|
+
}
|
|
450
|
+
handleSpanEnd(spanId, parentSpanId) {
|
|
451
|
+
this.activeSpans.delete(spanId);
|
|
452
|
+
const currentTraceId = this.currentContext?.traceId;
|
|
453
|
+
if (parentSpanId) {
|
|
454
|
+
const parentSpan = this.activeSpans.get(parentSpanId);
|
|
455
|
+
if (parentSpan) {
|
|
456
|
+
this.currentContext = {
|
|
457
|
+
traceId: parentSpan.spanContext.traceId,
|
|
458
|
+
spanId: parentSpan.spanContext.spanId,
|
|
459
|
+
parentSpanId: parentSpan.spanContext.parentSpanId
|
|
460
|
+
};
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
if (currentTraceId) {
|
|
464
|
+
this.currentContext = {
|
|
465
|
+
traceId: currentTraceId,
|
|
466
|
+
spanId: parentSpanId,
|
|
467
|
+
parentSpanId: undefined
|
|
468
|
+
};
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
this.currentContext = undefined;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
class OTelTracerProvider {
|
|
477
|
+
tracers = new Map;
|
|
478
|
+
storage;
|
|
479
|
+
initialized = false;
|
|
480
|
+
globalContext;
|
|
481
|
+
constructor(storage, dbPath) {
|
|
482
|
+
this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());
|
|
483
|
+
}
|
|
484
|
+
async initialize() {
|
|
485
|
+
if (this.initialized)
|
|
486
|
+
return;
|
|
487
|
+
await this.storage.initialize();
|
|
488
|
+
this.initialized = true;
|
|
489
|
+
}
|
|
490
|
+
isInitialized() {
|
|
491
|
+
return this.initialized;
|
|
492
|
+
}
|
|
493
|
+
getGlobalContext() {
|
|
494
|
+
return this.globalContext;
|
|
495
|
+
}
|
|
496
|
+
setGlobalContext(context) {
|
|
497
|
+
this.globalContext = context;
|
|
498
|
+
}
|
|
499
|
+
getTracer(name, version) {
|
|
500
|
+
const key = `${name}@${version || "0.0.0"}`;
|
|
501
|
+
let tracer = this.tracers.get(key);
|
|
502
|
+
if (!tracer) {
|
|
503
|
+
tracer = new OTelTracerImpl(name, version, this.storage, this);
|
|
504
|
+
this.tracers.set(key, tracer);
|
|
505
|
+
if (this.initialized) {
|
|
506
|
+
this.restoreFromEnv(tracer);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return tracer;
|
|
510
|
+
}
|
|
511
|
+
restoreFromEnv(tracer) {
|
|
512
|
+
const extracted = propagation.extract(process.env);
|
|
513
|
+
if (extracted) {
|
|
514
|
+
tracer.setCurrentContext({
|
|
515
|
+
traceId: extracted.traceId,
|
|
516
|
+
spanId: extracted.spanId,
|
|
517
|
+
parentSpanId: undefined
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
shutdown() {
|
|
522
|
+
for (const tracer of this.tracers.values()) {}
|
|
523
|
+
this.tracers.clear();
|
|
524
|
+
this.storage.close();
|
|
525
|
+
this.initialized = false;
|
|
526
|
+
this.globalContext = undefined;
|
|
527
|
+
delete process.env["TRACEPARENT"];
|
|
528
|
+
delete process.env["TRACE_ID"];
|
|
529
|
+
delete process.env["LOG_TRACE_REQUEST_ID"];
|
|
530
|
+
}
|
|
531
|
+
getStorage() {
|
|
532
|
+
return this.storage;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function getTracerProvider() {
|
|
536
|
+
if (!providerInstance) {
|
|
537
|
+
providerInstance = new OTelTracerProvider;
|
|
538
|
+
}
|
|
539
|
+
return providerInstance;
|
|
540
|
+
}
|
|
541
|
+
function resetTracerProvider() {
|
|
542
|
+
if (providerInstance) {
|
|
543
|
+
providerInstance.shutdown();
|
|
544
|
+
providerInstance = null;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function getDefaultDbPath() {
|
|
548
|
+
const os = __require("os");
|
|
549
|
+
const path = __require("path");
|
|
550
|
+
const home = os.homedir();
|
|
551
|
+
const dataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
|
|
552
|
+
return path.join(dataHome, "roy-agent", "traces.db");
|
|
553
|
+
}
|
|
554
|
+
var providerInstance = null;
|
|
555
|
+
var init_tracer_provider = __esm(() => {
|
|
556
|
+
init_propagation();
|
|
557
|
+
init_types();
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// packages/core/src/env/log-trace/logger.ts
|
|
561
|
+
import { appendFileSync, existsSync, mkdirSync } from "fs";
|
|
562
|
+
import { join } from "path";
|
|
563
|
+
function simplifyFilePath(fullPath) {
|
|
564
|
+
let path = fullPath.replace(/\\/g, "/");
|
|
565
|
+
const bunfsMatch = path.match(/\/\$bunfs\/root\/(.+)$/);
|
|
566
|
+
if (bunfsMatch) {
|
|
567
|
+
const virtualPath = bunfsMatch[1];
|
|
568
|
+
const packagesMatch = virtualPath.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
569
|
+
if (packagesMatch) {
|
|
570
|
+
return packagesMatch[1];
|
|
571
|
+
}
|
|
572
|
+
return virtualPath;
|
|
573
|
+
}
|
|
574
|
+
const fileProtocolMatch = path.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);
|
|
575
|
+
if (fileProtocolMatch) {
|
|
576
|
+
const rootPkg = fileProtocolMatch[1].replace(/\+/g, "/");
|
|
577
|
+
const remaining = fileProtocolMatch[2];
|
|
578
|
+
const prefix = rootPkg;
|
|
579
|
+
const suffix = remaining.startsWith("src/") ? remaining : `src/${remaining}`;
|
|
580
|
+
return `${prefix}/${suffix}`;
|
|
581
|
+
}
|
|
582
|
+
const packagesRootMatch = path.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
|
|
583
|
+
if (packagesRootMatch) {
|
|
584
|
+
return packagesRootMatch[1];
|
|
585
|
+
}
|
|
586
|
+
const rootMarkers = ["packages/core/src", "packages/core", "packages"];
|
|
587
|
+
for (const marker of rootMarkers) {
|
|
588
|
+
const idx = path.indexOf(marker);
|
|
589
|
+
if (idx !== -1) {
|
|
590
|
+
return path.substring(idx);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return path;
|
|
594
|
+
}
|
|
595
|
+
function getDefaultLogDir() {
|
|
596
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
597
|
+
try {
|
|
598
|
+
const xdg = __require("xdg-basedir");
|
|
599
|
+
if (xdg.xdgData) {
|
|
600
|
+
return join(xdg.xdgData, "roy-agent", "logs");
|
|
601
|
+
}
|
|
602
|
+
} catch {}
|
|
603
|
+
return join(home, ".local", "share", "roy-agent", "logs");
|
|
604
|
+
}
|
|
605
|
+
function isQuietMode() {
|
|
606
|
+
return quietMode;
|
|
607
|
+
}
|
|
608
|
+
function setQuietMode(enabled) {
|
|
609
|
+
quietMode = enabled;
|
|
610
|
+
}
|
|
611
|
+
function setConfigComponent(component) {
|
|
612
|
+
configComponentInstance = component;
|
|
613
|
+
}
|
|
614
|
+
function getLogLevel() {
|
|
615
|
+
if (configComponentInstance) {
|
|
616
|
+
const level = configComponentInstance.get("log_trace.logging.level");
|
|
617
|
+
if (level && ["debug", "info", "warn", "error"].includes(level)) {
|
|
618
|
+
return level;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const envLevel = process.env.LOG_LEVEL;
|
|
622
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
623
|
+
return envLevel;
|
|
624
|
+
}
|
|
625
|
+
return "info";
|
|
626
|
+
}
|
|
627
|
+
function getCategoryLogLevel(category) {
|
|
628
|
+
if (configComponentInstance) {
|
|
629
|
+
const levels = configComponentInstance.get("log_trace.logging.levels");
|
|
630
|
+
if (levels && typeof levels === "object") {
|
|
631
|
+
const categoryLevel = levels[category];
|
|
632
|
+
if (categoryLevel && ["debug", "info", "warn", "error"].includes(categoryLevel)) {
|
|
633
|
+
return categoryLevel;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);
|
|
637
|
+
if (directLevel && ["debug", "info", "warn", "error"].includes(directLevel)) {
|
|
638
|
+
return directLevel;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, "_")}`;
|
|
642
|
+
const envLevel = process.env[envKey];
|
|
643
|
+
if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
|
|
644
|
+
return envLevel;
|
|
645
|
+
}
|
|
646
|
+
return getLogLevel();
|
|
647
|
+
}
|
|
648
|
+
function isAbsolutePath(path) {
|
|
649
|
+
if (path.startsWith("/")) {
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
if (/^[a-zA-Z]:[/\\]/.test(path)) {
|
|
653
|
+
return true;
|
|
654
|
+
}
|
|
655
|
+
return false;
|
|
656
|
+
}
|
|
657
|
+
function expandHomeDir(path) {
|
|
658
|
+
if (path.startsWith("~")) {
|
|
659
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
660
|
+
return join(home, path.slice(1));
|
|
661
|
+
}
|
|
662
|
+
return path;
|
|
663
|
+
}
|
|
664
|
+
function getLogFile() {
|
|
665
|
+
if (configComponentInstance) {
|
|
666
|
+
const file = configComponentInstance.get("log_trace.logging.file");
|
|
667
|
+
if (file) {
|
|
668
|
+
return file;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
return "app.log";
|
|
672
|
+
}
|
|
673
|
+
function getLogDir() {
|
|
674
|
+
if (configComponentInstance) {
|
|
675
|
+
const dir = configComponentInstance.get("log_trace.logging.dir");
|
|
676
|
+
if (dir) {
|
|
677
|
+
return dir;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
return getDefaultLogDir();
|
|
681
|
+
}
|
|
682
|
+
function getMaxOutput() {
|
|
683
|
+
if (configComponentInstance) {
|
|
684
|
+
const maxOutput = configComponentInstance.get("log-trace.logging.maxOutput");
|
|
685
|
+
if (typeof maxOutput === "number") {
|
|
686
|
+
return maxOutput;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
function setLogDirOverride(dir) {
|
|
692
|
+
logDirOverride = dir;
|
|
693
|
+
}
|
|
694
|
+
function getLogDirOverride() {
|
|
695
|
+
return logDirOverride;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
class Logger {
|
|
699
|
+
prefix;
|
|
700
|
+
constructor(prefix) {
|
|
701
|
+
this.prefix = prefix;
|
|
702
|
+
}
|
|
703
|
+
shouldLog(level) {
|
|
704
|
+
const categoryLevel = getCategoryLogLevel(this.prefix);
|
|
705
|
+
return levelPriority[level] >= levelPriority[categoryLevel];
|
|
706
|
+
}
|
|
707
|
+
ensureLogDirectory(dir) {
|
|
708
|
+
if (!existsSync(dir)) {
|
|
709
|
+
try {
|
|
710
|
+
mkdirSync(dir, { recursive: true });
|
|
711
|
+
} catch (err) {
|
|
712
|
+
console.error("[Logger] Failed to create log directory:", dir, err);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
getCallerLocation() {
|
|
717
|
+
const originalLimit = Error.stackTraceLimit;
|
|
718
|
+
Error.stackTraceLimit = 10;
|
|
719
|
+
const err = new Error;
|
|
720
|
+
Error.captureStackTrace(err, this.formatMessage);
|
|
721
|
+
const stack = err.stack?.split(`
|
|
722
|
+
`) || [];
|
|
723
|
+
Error.stackTraceLimit = originalLimit;
|
|
724
|
+
for (let i = 1;i < stack.length; i++) {
|
|
725
|
+
const line = stack[i];
|
|
726
|
+
if (line.includes("at ") && !line.includes("logger.ts") && !line.includes("formatMessage")) {
|
|
727
|
+
const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
|
|
728
|
+
if (match) {
|
|
729
|
+
const filePath = match[1];
|
|
730
|
+
const relativePath = this.getRelativePath(filePath);
|
|
731
|
+
return {
|
|
732
|
+
file: relativePath,
|
|
733
|
+
line: parseInt(match[2], 10)
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
getRelativePath(fullPath) {
|
|
741
|
+
return simplifyFilePath(fullPath);
|
|
742
|
+
}
|
|
743
|
+
formatMessage(level, message, data) {
|
|
744
|
+
const now = new Date;
|
|
745
|
+
const timestamp = now.toLocaleString("zh-CN", {
|
|
746
|
+
timeZone: "Asia/Shanghai",
|
|
747
|
+
year: "numeric",
|
|
748
|
+
month: "2-digit",
|
|
749
|
+
day: "2-digit",
|
|
750
|
+
hour: "2-digit",
|
|
751
|
+
minute: "2-digit",
|
|
752
|
+
second: "2-digit",
|
|
753
|
+
hour12: false
|
|
754
|
+
}).replace(/\//g, "-") + "." + String(now.getMilliseconds()).padStart(3, "0");
|
|
755
|
+
const prefix = this.prefix ? `[${this.prefix}]` : "";
|
|
756
|
+
let traceIdStr = "";
|
|
757
|
+
try {
|
|
758
|
+
const provider = getTracerProvider();
|
|
759
|
+
const tracer = provider.getTracer("roy-tracer");
|
|
760
|
+
const context = tracer.getCurrentContext();
|
|
761
|
+
if (context?.traceId) {
|
|
762
|
+
traceIdStr = `[traceId=${context.traceId}]`;
|
|
763
|
+
}
|
|
764
|
+
} catch {}
|
|
765
|
+
let locationStr = "";
|
|
766
|
+
if (data && typeof data === "object" && "callerLocation" in data) {
|
|
767
|
+
const logData = data;
|
|
768
|
+
locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : "";
|
|
769
|
+
const { callerLocation: _callerLocation, ...rest } = logData;
|
|
770
|
+
data = Object.keys(rest).length > 0 ? rest : undefined;
|
|
771
|
+
} else {
|
|
772
|
+
const location = this.getCallerLocation();
|
|
773
|
+
if (location) {
|
|
774
|
+
locationStr = ` [${location.file}:${location.line}]`;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;
|
|
778
|
+
if (data !== undefined) {
|
|
779
|
+
if (typeof data === "object") {
|
|
780
|
+
formatted += " " + JSON.stringify(data).replace(/\n/g, "");
|
|
781
|
+
} else {
|
|
782
|
+
formatted += " " + String(data);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const maxOutput = getMaxOutput();
|
|
786
|
+
if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {
|
|
787
|
+
formatted = formatted.substring(0, maxOutput) + " [TRUNCATED]";
|
|
788
|
+
}
|
|
789
|
+
return formatted;
|
|
790
|
+
}
|
|
791
|
+
writeToFile(message) {
|
|
792
|
+
try {
|
|
793
|
+
const dir = getLogDir();
|
|
794
|
+
const filename = getLogFile();
|
|
795
|
+
const expandedDir = expandHomeDir(dir);
|
|
796
|
+
const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);
|
|
797
|
+
this.ensureLogDirectory(resolvedDir);
|
|
798
|
+
const logFile = join(resolvedDir, filename);
|
|
799
|
+
appendFileSync(logFile, message + `
|
|
800
|
+
`, "utf-8");
|
|
801
|
+
} catch (err) {
|
|
802
|
+
console.error("[Logger] Failed to write to log file:", err);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
log(level, message, data) {
|
|
806
|
+
if (!this.shouldLog(level))
|
|
807
|
+
return;
|
|
808
|
+
const formatted = this.formatMessage(level, message, data);
|
|
809
|
+
this.writeToFile(formatted);
|
|
810
|
+
if (!isQuietMode()) {
|
|
811
|
+
const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.log : console.debug;
|
|
812
|
+
consoleMethod(formatted);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
debug(message, data) {
|
|
816
|
+
this.log("debug", message, data);
|
|
817
|
+
}
|
|
818
|
+
info(message, data) {
|
|
819
|
+
this.log("info", message, data);
|
|
820
|
+
}
|
|
821
|
+
warn(message, data) {
|
|
822
|
+
this.log("warn", message, data);
|
|
823
|
+
}
|
|
824
|
+
error(message, data) {
|
|
825
|
+
this.log("error", message, data);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function createLogger(prefix) {
|
|
829
|
+
if (!loggerCache.has(prefix)) {
|
|
830
|
+
loggerCache.set(prefix, new Logger(prefix));
|
|
831
|
+
}
|
|
832
|
+
return loggerCache.get(prefix);
|
|
833
|
+
}
|
|
834
|
+
function getLogLevels() {
|
|
835
|
+
return ["debug", "info", "warn", "error"];
|
|
836
|
+
}
|
|
837
|
+
var configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;
|
|
838
|
+
var init_logger = __esm(() => {
|
|
839
|
+
init_tracer_provider();
|
|
840
|
+
levelPriority = {
|
|
841
|
+
debug: 0,
|
|
842
|
+
info: 1,
|
|
843
|
+
warn: 2,
|
|
844
|
+
error: 3
|
|
845
|
+
};
|
|
846
|
+
loggerCache = new Map;
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
// packages/core/src/env/log-trace/decorator.ts
|
|
850
|
+
function Traced(options) {
|
|
851
|
+
return function(target, propertyKey, descriptor) {
|
|
852
|
+
const originalFn = descriptor.value;
|
|
853
|
+
const spanName = options?.name || propertyKey;
|
|
854
|
+
descriptor.value = wrapFunction(originalFn, spanName, {
|
|
855
|
+
recordParams: options?.recordParams ?? true,
|
|
856
|
+
recordResult: options?.recordResult ?? false,
|
|
857
|
+
recordError: options?.recordError ?? true,
|
|
858
|
+
log: options?.log ?? false,
|
|
859
|
+
maxLogSize: options?.maxLogSize,
|
|
860
|
+
paramFilter: options?.paramFilter
|
|
861
|
+
});
|
|
862
|
+
return descriptor;
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
function TracedAs(name, options) {
|
|
866
|
+
return Traced({ name, ...options });
|
|
867
|
+
}
|
|
868
|
+
function TracedLightweight(options) {
|
|
869
|
+
return Traced({ recordParams: false, recordResult: false, log: options?.log ?? false, maxLogSize: options?.maxLogSize });
|
|
870
|
+
}
|
|
871
|
+
function wrapFunction(fn, name, options) {
|
|
872
|
+
const shouldLog = options?.log ?? false;
|
|
873
|
+
const getMaxLogSize = () => {
|
|
874
|
+
if (options?.maxLogSize !== undefined) {
|
|
875
|
+
return options.maxLogSize;
|
|
876
|
+
}
|
|
877
|
+
const configMaxOutput = getMaxOutput();
|
|
878
|
+
return configMaxOutput !== undefined ? configMaxOutput : 500;
|
|
879
|
+
};
|
|
880
|
+
const truncate = (obj) => {
|
|
881
|
+
if (obj === undefined)
|
|
882
|
+
return;
|
|
883
|
+
if (obj === null)
|
|
884
|
+
return null;
|
|
885
|
+
const maxLogSize = getMaxLogSize();
|
|
886
|
+
let str;
|
|
887
|
+
try {
|
|
888
|
+
str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
|
|
889
|
+
} catch (e) {
|
|
890
|
+
str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
|
|
891
|
+
}
|
|
892
|
+
if (maxLogSize > 0 && str.length > maxLogSize) {
|
|
893
|
+
return str.slice(0, maxLogSize) + " [TRUNCATED]";
|
|
894
|
+
}
|
|
895
|
+
try {
|
|
896
|
+
return JSON.parse(str);
|
|
897
|
+
} catch {
|
|
898
|
+
return str;
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
const truncateString = (obj) => {
|
|
902
|
+
if (obj === undefined)
|
|
903
|
+
return "undefined";
|
|
904
|
+
if (obj === null)
|
|
905
|
+
return "null";
|
|
906
|
+
const maxLogSize = getMaxLogSize();
|
|
907
|
+
let str;
|
|
908
|
+
try {
|
|
909
|
+
str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
|
|
910
|
+
} catch (e) {
|
|
911
|
+
str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
|
|
912
|
+
}
|
|
913
|
+
return maxLogSize > 0 && str.length > maxLogSize ? str.slice(0, maxLogSize) + " [TRUNCATED]" : str;
|
|
914
|
+
};
|
|
915
|
+
const TRACE_LOG_PREFIX = "[TRACE]";
|
|
916
|
+
const getCallerLocation = () => {
|
|
917
|
+
const originalLimit = Error.stackTraceLimit;
|
|
918
|
+
Error.stackTraceLimit = 15;
|
|
919
|
+
const err = new Error;
|
|
920
|
+
Error.captureStackTrace(err, getCallerLocation);
|
|
921
|
+
const stack = err.stack?.split(`
|
|
922
|
+
`) || [];
|
|
923
|
+
Error.stackTraceLimit = originalLimit;
|
|
924
|
+
for (let i = 1;i < stack.length; i++) {
|
|
925
|
+
const line = stack[i];
|
|
926
|
+
if (line.includes("decorator.ts") || line.includes("decorator.js") || line.includes("logFn") || line.includes("getCallerLocation"))
|
|
927
|
+
continue;
|
|
928
|
+
const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
|
|
929
|
+
if (match) {
|
|
930
|
+
const filePath = match[1];
|
|
931
|
+
if (!filePath || filePath === "native")
|
|
932
|
+
continue;
|
|
933
|
+
const relativePath = simplifyFilePath(filePath);
|
|
934
|
+
return `${relativePath}:${match[2]}`;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
return "";
|
|
938
|
+
};
|
|
939
|
+
const logFn = (event, argsOrData, callerLocation) => {
|
|
940
|
+
if (!shouldLog)
|
|
941
|
+
return;
|
|
942
|
+
const logger = createLogger("traced:" + name);
|
|
943
|
+
const tag = event === "enter" ? ">>>" : event === "quit" ? "<<<" : "!!!";
|
|
944
|
+
const prefix = `${TRACE_LOG_PREFIX} ${tag} ${name}`;
|
|
945
|
+
const originalFnLocation = callerLocation || getCallerLocation();
|
|
946
|
+
const logMessage = (msg, data) => {
|
|
947
|
+
if (data !== undefined) {
|
|
948
|
+
logger.info(`${prefix} ${msg}: ${truncateString(data)}`, { callerLocation: originalFnLocation });
|
|
949
|
+
} else {
|
|
950
|
+
logger.info(`${prefix} ${msg}`, { callerLocation: originalFnLocation });
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
if (event === "enter") {
|
|
954
|
+
logMessage("enter", argsOrData);
|
|
955
|
+
} else if (event === "quit") {
|
|
956
|
+
logMessage("quit", options?.recordResult ? argsOrData : undefined);
|
|
957
|
+
} else {
|
|
958
|
+
logMessage("error", argsOrData);
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
return function(...args) {
|
|
962
|
+
const tracer = getTracerProvider().getTracer("roy-tracer");
|
|
963
|
+
const attributes = {};
|
|
964
|
+
if (options?.recordParams !== false) {
|
|
965
|
+
if (options?.paramFilter) {
|
|
966
|
+
attributes["params"] = truncate(options.paramFilter(args));
|
|
967
|
+
} else {
|
|
968
|
+
attributes["params"] = truncate(args);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
const callerLocation = getCallerLocation();
|
|
972
|
+
logFn("enter", args, callerLocation);
|
|
973
|
+
const span = tracer.startSpan(name, { attributes });
|
|
974
|
+
try {
|
|
975
|
+
const result = fn.call(this, ...args);
|
|
976
|
+
if (result && typeof result === "object" && typeof result.then === "function") {
|
|
977
|
+
return result.then((resolved) => {
|
|
978
|
+
span.setAttribute("result", JSON.stringify(truncate(resolved)));
|
|
979
|
+
span.end(resolved);
|
|
980
|
+
logFn("quit", options?.recordResult ? resolved : undefined, callerLocation);
|
|
981
|
+
return resolved;
|
|
982
|
+
}, (rejected) => {
|
|
983
|
+
span.setAttribute("error", String(rejected));
|
|
984
|
+
span.end(undefined, rejected instanceof Error ? rejected : new Error(String(rejected)));
|
|
985
|
+
logFn("error", rejected.message, callerLocation);
|
|
986
|
+
throw rejected;
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
span.setAttribute("result", JSON.stringify(truncate(result)));
|
|
990
|
+
span.end(result);
|
|
991
|
+
logFn("quit", options?.recordResult ? result : undefined, callerLocation);
|
|
992
|
+
return result;
|
|
993
|
+
} catch (error) {
|
|
994
|
+
span.setAttribute("error", String(error));
|
|
995
|
+
span.end(undefined, error instanceof Error ? error : new Error(String(error)));
|
|
996
|
+
logFn("error", error.message, callerLocation);
|
|
997
|
+
throw error;
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
var init_decorator = __esm(() => {
|
|
1002
|
+
init_tracer_provider();
|
|
1003
|
+
init_logger();
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
// packages/core/src/env/session/session-message-converter.ts
|
|
1007
|
+
init_decorator();
|
|
1008
|
+
import { randomUUID } from "crypto";
|
|
1009
|
+
var DEFAULT_REASONING_BUDGET_TOKENS = 1e4;
|
|
1010
|
+
|
|
1011
|
+
class SessionMessageConverter {
|
|
1012
|
+
toModelMessage(msg) {
|
|
1013
|
+
if (msg.role === "assistant") {
|
|
1014
|
+
const content = [];
|
|
1015
|
+
for (const part of msg.parts || []) {
|
|
1016
|
+
if (part.type === "text") {
|
|
1017
|
+
const textPart = part;
|
|
1018
|
+
content.push({
|
|
1019
|
+
type: "text",
|
|
1020
|
+
text: textPart.content,
|
|
1021
|
+
...textPart.synthetic !== undefined && { synthetic: textPart.synthetic }
|
|
1022
|
+
});
|
|
1023
|
+
} else if (part.type === "reasoning") {
|
|
1024
|
+
const reasoningPart = part;
|
|
1025
|
+
content.push({
|
|
1026
|
+
type: "reasoning",
|
|
1027
|
+
text: reasoningPart.content,
|
|
1028
|
+
reasoningType: reasoningPart.reasoningType
|
|
1029
|
+
});
|
|
1030
|
+
} else if (part.type === "tool-call") {
|
|
1031
|
+
const toolPart = part;
|
|
1032
|
+
let parsedArgs = {};
|
|
1033
|
+
if (typeof toolPart.arguments === "string") {
|
|
1034
|
+
try {
|
|
1035
|
+
parsedArgs = JSON.parse(toolPart.arguments);
|
|
1036
|
+
} catch {
|
|
1037
|
+
parsedArgs = { _raw: toolPart.arguments };
|
|
1038
|
+
}
|
|
1039
|
+
} else {
|
|
1040
|
+
parsedArgs = toolPart.arguments;
|
|
1041
|
+
}
|
|
1042
|
+
content.push({
|
|
1043
|
+
type: "tool-call",
|
|
1044
|
+
toolCallId: toolPart.toolCallId,
|
|
1045
|
+
toolName: toolPart.toolName,
|
|
1046
|
+
input: parsedArgs
|
|
1047
|
+
});
|
|
1048
|
+
} else if (part.type === "file") {
|
|
1049
|
+
const filePart = part;
|
|
1050
|
+
content.push({
|
|
1051
|
+
type: "file",
|
|
1052
|
+
url: filePart.url,
|
|
1053
|
+
mimeType: filePart.mime,
|
|
1054
|
+
filename: filePart.filename
|
|
1055
|
+
});
|
|
1056
|
+
} else if (part.type === "tool-result" || part.type === "checkpoint") {} else {
|
|
1057
|
+
console.debug(`[session-message-converter] Skipping unsupported part type in assistant: ${part.type}`);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (content.length === 0 && msg.content) {
|
|
1061
|
+
return { role: "assistant", content: msg.content };
|
|
1062
|
+
}
|
|
1063
|
+
return { role: "assistant", content };
|
|
1064
|
+
}
|
|
1065
|
+
if (msg.role === "tool") {
|
|
1066
|
+
const toolPart = msg.parts?.find((p) => p.type === "tool-result");
|
|
1067
|
+
return {
|
|
1068
|
+
role: "tool",
|
|
1069
|
+
content: [{
|
|
1070
|
+
type: "tool-result",
|
|
1071
|
+
toolCallId: toolPart?.toolCallId || "",
|
|
1072
|
+
toolName: toolPart?.toolName || "",
|
|
1073
|
+
output: toolPart?.output || msg.content || ""
|
|
1074
|
+
}]
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
return {
|
|
1078
|
+
role: msg.role,
|
|
1079
|
+
content: msg.content || ""
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
fromModelMessage(aiMsg, options) {
|
|
1083
|
+
const parts = [];
|
|
1084
|
+
const content = typeof aiMsg.content === "string" || Array.isArray(aiMsg.content) ? aiMsg.content : "";
|
|
1085
|
+
let hasToolCallPart = false;
|
|
1086
|
+
let hasToolResultPart = false;
|
|
1087
|
+
if (typeof content === "string") {
|
|
1088
|
+
parts.push({ type: "text", content });
|
|
1089
|
+
} else if (Array.isArray(content)) {
|
|
1090
|
+
for (const part of content) {
|
|
1091
|
+
const p = part;
|
|
1092
|
+
if (p.type === "text") {
|
|
1093
|
+
parts.push({ type: "text", content: p.text || "" });
|
|
1094
|
+
} else if (p.type === "reasoning") {
|
|
1095
|
+
parts.push({
|
|
1096
|
+
type: "reasoning",
|
|
1097
|
+
content: p.text || "",
|
|
1098
|
+
reasoningType: p.reasoningType,
|
|
1099
|
+
state: "completed"
|
|
1100
|
+
});
|
|
1101
|
+
} else if (p.type === "tool-call") {
|
|
1102
|
+
hasToolCallPart = true;
|
|
1103
|
+
parts.push({
|
|
1104
|
+
type: "tool-call",
|
|
1105
|
+
toolCallId: p.toolCallId,
|
|
1106
|
+
toolName: p.toolName,
|
|
1107
|
+
arguments: p.input,
|
|
1108
|
+
state: "pending"
|
|
1109
|
+
});
|
|
1110
|
+
} else if (p.type === "tool-result") {
|
|
1111
|
+
hasToolResultPart = true;
|
|
1112
|
+
parts.push({
|
|
1113
|
+
type: "tool-result",
|
|
1114
|
+
toolCallId: p.toolCallId,
|
|
1115
|
+
toolName: p.toolName,
|
|
1116
|
+
output: typeof p.output === "string" ? p.output : JSON.stringify(p.output),
|
|
1117
|
+
state: "completed"
|
|
1118
|
+
});
|
|
1119
|
+
} else if (p.type === "file") {
|
|
1120
|
+
parts.push({
|
|
1121
|
+
type: "file",
|
|
1122
|
+
mime: p.mimeType || "application/octet-stream",
|
|
1123
|
+
url: p.url,
|
|
1124
|
+
filename: p.filename
|
|
1125
|
+
});
|
|
1126
|
+
} else {
|
|
1127
|
+
console.debug(`[session-message-converter] Unknown part type: ${p.type}`);
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
let metadataType;
|
|
1132
|
+
if (aiMsg.role === "assistant" && hasToolCallPart) {
|
|
1133
|
+
metadataType = "tool_call";
|
|
1134
|
+
} else if (aiMsg.role === "tool") {
|
|
1135
|
+
metadataType = "tool_result";
|
|
1136
|
+
}
|
|
1137
|
+
const result = {
|
|
1138
|
+
id: options?.messageID || `msg_${randomUUID()}`,
|
|
1139
|
+
sessionID: options?.sessionID || "",
|
|
1140
|
+
role: aiMsg.role,
|
|
1141
|
+
timestamp: Date.now(),
|
|
1142
|
+
parts,
|
|
1143
|
+
content: typeof content === "string" ? content : ""
|
|
1144
|
+
};
|
|
1145
|
+
if (metadataType) {
|
|
1146
|
+
result.metadata = { type: metadataType };
|
|
1147
|
+
}
|
|
1148
|
+
return result;
|
|
1149
|
+
}
|
|
1150
|
+
sessionToHistory(messages) {
|
|
1151
|
+
return messages.filter((msg) => !msg.metadata?.isArchived && !msg.isArchived).map((msg) => this.toModelMessage(msg));
|
|
1152
|
+
}
|
|
1153
|
+
extractProviderOptions(msg) {
|
|
1154
|
+
const options = {};
|
|
1155
|
+
const reasoningParts = msg.parts?.filter((p) => p.type === "reasoning");
|
|
1156
|
+
if (reasoningParts && reasoningParts.length > 0) {
|
|
1157
|
+
const firstReasoning = reasoningParts[0];
|
|
1158
|
+
if (firstReasoning.reasoningType) {
|
|
1159
|
+
options.openai = {
|
|
1160
|
+
thinking: {
|
|
1161
|
+
type: firstReasoning.reasoningType === "effort" ? "extended" : "core"
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
if (firstReasoning.reasoningType === "effort") {
|
|
1165
|
+
const budgetTokens = firstReasoning.metadata?.tokenCount || DEFAULT_REASONING_BUDGET_TOKENS;
|
|
1166
|
+
options.anthropic = {
|
|
1167
|
+
thinking: {
|
|
1168
|
+
type: "enabled",
|
|
1169
|
+
budgetTokens
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
return options;
|
|
1176
|
+
}
|
|
1177
|
+
migrateMessage(oldMsg) {
|
|
1178
|
+
if (oldMsg.parts && oldMsg.parts.length > 0) {
|
|
1179
|
+
const firstPart = oldMsg.parts[0];
|
|
1180
|
+
if (firstPart && typeof firstPart.type === "string" && firstPart.type.length > 0) {
|
|
1181
|
+
return {
|
|
1182
|
+
...oldMsg,
|
|
1183
|
+
content: oldMsg.content || ""
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return {
|
|
1188
|
+
...oldMsg,
|
|
1189
|
+
content: oldMsg.content || "",
|
|
1190
|
+
parts: oldMsg.content ? [{ type: "text", content: oldMsg.content }] : []
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
__legacyDecorateClassTS([
|
|
1195
|
+
TracedAs("session-message-converter.toModelMessage", { recordParams: true, recordResult: true, log: true })
|
|
1196
|
+
], SessionMessageConverter.prototype, "toModelMessage", null);
|
|
1197
|
+
__legacyDecorateClassTS([
|
|
1198
|
+
TracedAs("session-message-converter.fromModelMessage", { recordParams: true, recordResult: true, log: true })
|
|
1199
|
+
], SessionMessageConverter.prototype, "fromModelMessage", null);
|
|
1200
|
+
|
|
1201
|
+
// packages/core/src/env/session/storage/memory.ts
|
|
1202
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1203
|
+
function generateSessionId() {
|
|
1204
|
+
return `session_${randomUUID2()}`;
|
|
1205
|
+
}
|
|
1206
|
+
function generateMessageId() {
|
|
1207
|
+
return `msg_${randomUUID2()}`;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
class MemorySessionStore {
|
|
1211
|
+
sessions = new Map;
|
|
1212
|
+
messages = new Map;
|
|
1213
|
+
checkpoints = new Map;
|
|
1214
|
+
messageConverter = new SessionMessageConverter;
|
|
1215
|
+
async create(options) {
|
|
1216
|
+
const now = Date.now();
|
|
1217
|
+
const session = {
|
|
1218
|
+
id: options.id ?? generateSessionId(),
|
|
1219
|
+
title: options.title ?? "Session",
|
|
1220
|
+
directory: options.directory ?? "/tmp",
|
|
1221
|
+
parentID: options.parentID,
|
|
1222
|
+
createdAt: now,
|
|
1223
|
+
updatedAt: now,
|
|
1224
|
+
messageCount: 0,
|
|
1225
|
+
metadata: {
|
|
1226
|
+
...options.metadata,
|
|
1227
|
+
messageCount: 0,
|
|
1228
|
+
checkpoints: { checkpoints: [] }
|
|
1229
|
+
}
|
|
1230
|
+
};
|
|
1231
|
+
if (this.sessions.has(session.id)) {
|
|
1232
|
+
throw new Error(`Session with ID '${session.id}' already exists`);
|
|
1233
|
+
}
|
|
1234
|
+
this.sessions.set(session.id, session);
|
|
1235
|
+
this.messages.set(session.id, []);
|
|
1236
|
+
this.checkpoints.set(session.id, []);
|
|
1237
|
+
return session;
|
|
1238
|
+
}
|
|
1239
|
+
async get(id) {
|
|
1240
|
+
return this.sessions.get(id);
|
|
1241
|
+
}
|
|
1242
|
+
async list(options) {
|
|
1243
|
+
let sessions = Array.from(this.sessions.values());
|
|
1244
|
+
if (options?.filter?.metadata) {
|
|
1245
|
+
sessions = sessions.filter((s) => {
|
|
1246
|
+
for (const [key, value] of Object.entries(options.filter.metadata)) {
|
|
1247
|
+
if (s.metadata?.[key] !== value)
|
|
1248
|
+
return false;
|
|
1249
|
+
}
|
|
1250
|
+
return true;
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
if (options?.filter?.startTime) {
|
|
1254
|
+
sessions = sessions.filter((s) => s.createdAt >= options.filter.startTime);
|
|
1255
|
+
}
|
|
1256
|
+
if (options?.filter?.endTime) {
|
|
1257
|
+
sessions = sessions.filter((s) => s.createdAt <= options.filter.endTime);
|
|
1258
|
+
}
|
|
1259
|
+
const sortField = options?.sort?.field ?? "updatedAt";
|
|
1260
|
+
const sortOrder = options?.sort?.order ?? "desc";
|
|
1261
|
+
sessions.sort((a, b) => {
|
|
1262
|
+
let aVal;
|
|
1263
|
+
let bVal;
|
|
1264
|
+
if (sortField === "title") {
|
|
1265
|
+
aVal = a.title;
|
|
1266
|
+
bVal = b.title;
|
|
1267
|
+
} else if (sortField === "createdAt") {
|
|
1268
|
+
aVal = a.createdAt;
|
|
1269
|
+
bVal = b.createdAt;
|
|
1270
|
+
} else {
|
|
1271
|
+
aVal = a.updatedAt;
|
|
1272
|
+
bVal = b.updatedAt;
|
|
1273
|
+
}
|
|
1274
|
+
if (aVal < bVal)
|
|
1275
|
+
return sortOrder === "asc" ? -1 : 1;
|
|
1276
|
+
if (aVal > bVal)
|
|
1277
|
+
return sortOrder === "asc" ? 1 : -1;
|
|
1278
|
+
return 0;
|
|
1279
|
+
});
|
|
1280
|
+
const offset = options?.offset ?? 0;
|
|
1281
|
+
const limit = options?.limit ?? 100;
|
|
1282
|
+
return sessions.slice(offset, offset + limit);
|
|
1283
|
+
}
|
|
1284
|
+
async update(id, updates) {
|
|
1285
|
+
const session = this.sessions.get(id);
|
|
1286
|
+
if (!session)
|
|
1287
|
+
return false;
|
|
1288
|
+
if (updates.title !== undefined) {
|
|
1289
|
+
session.title = updates.title;
|
|
1290
|
+
}
|
|
1291
|
+
if (updates.metadata !== undefined) {
|
|
1292
|
+
session.metadata = { ...session.metadata, ...updates.metadata };
|
|
1293
|
+
}
|
|
1294
|
+
session.updatedAt = Date.now();
|
|
1295
|
+
return true;
|
|
1296
|
+
}
|
|
1297
|
+
async delete(id) {
|
|
1298
|
+
const deleted = this.sessions.delete(id);
|
|
1299
|
+
if (deleted) {
|
|
1300
|
+
this.messages.delete(id);
|
|
1301
|
+
this.checkpoints.delete(id);
|
|
1302
|
+
}
|
|
1303
|
+
return deleted;
|
|
1304
|
+
}
|
|
1305
|
+
async getCount() {
|
|
1306
|
+
return this.sessions.size;
|
|
1307
|
+
}
|
|
1308
|
+
async addMessage(sessionId, message) {
|
|
1309
|
+
const session = this.sessions.get(sessionId);
|
|
1310
|
+
if (!session) {
|
|
1311
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
1312
|
+
}
|
|
1313
|
+
const rawMessage = {
|
|
1314
|
+
sessionID: sessionId,
|
|
1315
|
+
role: message.role,
|
|
1316
|
+
content: message.content,
|
|
1317
|
+
parts: message.parts,
|
|
1318
|
+
metadata: message.metadata
|
|
1319
|
+
};
|
|
1320
|
+
const msg = this.messageConverter.migrateMessage(rawMessage);
|
|
1321
|
+
msg.id = generateMessageId();
|
|
1322
|
+
msg.timestamp = Date.now();
|
|
1323
|
+
const sessionMessages = this.messages.get(sessionId) ?? [];
|
|
1324
|
+
sessionMessages.push(msg);
|
|
1325
|
+
this.messages.set(sessionId, sessionMessages);
|
|
1326
|
+
session.messageCount = sessionMessages.filter((m) => !m.isArchived).length;
|
|
1327
|
+
session.metadata = {
|
|
1328
|
+
...session.metadata,
|
|
1329
|
+
messageCount: session.messageCount
|
|
1330
|
+
};
|
|
1331
|
+
session.updatedAt = Date.now();
|
|
1332
|
+
return msg.id;
|
|
1333
|
+
}
|
|
1334
|
+
async getMessages(sessionId, offset = 0, limit = 50, options) {
|
|
1335
|
+
let messages = this.messages.get(sessionId) ?? [];
|
|
1336
|
+
if (!options?.includeArchived) {
|
|
1337
|
+
messages = messages.filter((m) => !m.isArchived);
|
|
1338
|
+
}
|
|
1339
|
+
if (options?.fromCheckpointId) {
|
|
1340
|
+
const checkpoint = await this.getCheckpoint(sessionId, options.fromCheckpointId);
|
|
1341
|
+
if (checkpoint) {
|
|
1342
|
+
const checkpointIndex = messages.findIndex((m) => m.metadata?.checkpointId === options.fromCheckpointId);
|
|
1343
|
+
if (checkpointIndex >= 0) {
|
|
1344
|
+
messages = messages.slice(checkpointIndex);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
let actualOffset = offset;
|
|
1349
|
+
if (offset < 0) {
|
|
1350
|
+
const total = messages.length;
|
|
1351
|
+
actualOffset = Math.max(0, total + offset * limit);
|
|
1352
|
+
}
|
|
1353
|
+
if (options?.reverse) {
|
|
1354
|
+
messages = messages.reverse();
|
|
1355
|
+
}
|
|
1356
|
+
return messages.slice(actualOffset, actualOffset + limit);
|
|
1357
|
+
}
|
|
1358
|
+
async getMessageCount(sessionId, includeArchived = false) {
|
|
1359
|
+
const messages = this.messages.get(sessionId) ?? [];
|
|
1360
|
+
if (includeArchived) {
|
|
1361
|
+
return messages.length;
|
|
1362
|
+
}
|
|
1363
|
+
return messages.filter((m) => !m.isArchived).length;
|
|
1364
|
+
}
|
|
1365
|
+
async getMessageIndexes(sessionId, role) {
|
|
1366
|
+
const messages = this.messages.get(sessionId) ?? [];
|
|
1367
|
+
const indexes = [];
|
|
1368
|
+
messages.filter((m) => !m.isArchived).forEach((msg, filteredIdx) => {
|
|
1369
|
+
if (msg.role === role) {
|
|
1370
|
+
indexes.push(filteredIdx);
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
return indexes;
|
|
1374
|
+
}
|
|
1375
|
+
async saveCheckpoint(sessionId, checkpoint) {
|
|
1376
|
+
const session = this.sessions.get(sessionId);
|
|
1377
|
+
if (!session) {
|
|
1378
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
1379
|
+
}
|
|
1380
|
+
const cps = this.checkpoints.get(sessionId) ?? [];
|
|
1381
|
+
cps.push(checkpoint);
|
|
1382
|
+
this.checkpoints.set(sessionId, cps);
|
|
1383
|
+
const meta = session.metadata || {};
|
|
1384
|
+
const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
|
|
1385
|
+
checkpointsMeta.checkpoints.push({
|
|
1386
|
+
id: checkpoint.id,
|
|
1387
|
+
messageIndex: checkpoint.messageIndex,
|
|
1388
|
+
title: checkpoint.title,
|
|
1389
|
+
createdAt: checkpoint.createdAt,
|
|
1390
|
+
type: checkpoint.type
|
|
1391
|
+
});
|
|
1392
|
+
checkpointsMeta.latestCheckpointId = checkpoint.id;
|
|
1393
|
+
meta.checkpoints = checkpointsMeta;
|
|
1394
|
+
if (!meta.checkpointDetails) {
|
|
1395
|
+
meta.checkpointDetails = {};
|
|
1396
|
+
}
|
|
1397
|
+
meta.checkpointDetails[checkpoint.id] = checkpoint;
|
|
1398
|
+
session.metadata = meta;
|
|
1399
|
+
session.updatedAt = Date.now();
|
|
1400
|
+
}
|
|
1401
|
+
async getCheckpoints(sessionId) {
|
|
1402
|
+
return this.checkpoints.get(sessionId) ?? [];
|
|
1403
|
+
}
|
|
1404
|
+
async getCheckpoint(sessionId, checkpointId) {
|
|
1405
|
+
const cps = this.checkpoints.get(sessionId) ?? [];
|
|
1406
|
+
return cps.find((cp) => cp.id === checkpointId);
|
|
1407
|
+
}
|
|
1408
|
+
async deleteCheckpoint(sessionId, checkpointId) {
|
|
1409
|
+
const session = this.sessions.get(sessionId);
|
|
1410
|
+
if (!session)
|
|
1411
|
+
return false;
|
|
1412
|
+
const cps = this.checkpoints.get(sessionId) ?? [];
|
|
1413
|
+
const index = cps.findIndex((cp) => cp.id === checkpointId);
|
|
1414
|
+
if (index === -1)
|
|
1415
|
+
return false;
|
|
1416
|
+
cps.splice(index, 1);
|
|
1417
|
+
this.checkpoints.set(sessionId, cps);
|
|
1418
|
+
const messages = this.messages.get(sessionId) ?? [];
|
|
1419
|
+
for (const msg of messages) {
|
|
1420
|
+
if (msg.checkpointId === checkpointId) {
|
|
1421
|
+
msg.isArchived = false;
|
|
1422
|
+
msg.archivedAt = undefined;
|
|
1423
|
+
msg.checkpointId = undefined;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
const meta = session.metadata || {};
|
|
1427
|
+
const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
|
|
1428
|
+
checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
|
|
1429
|
+
checkpointsMeta.latestCheckpointId = cps[cps.length - 1]?.id;
|
|
1430
|
+
if (meta.checkpointDetails) {
|
|
1431
|
+
delete meta.checkpointDetails[checkpointId];
|
|
1432
|
+
}
|
|
1433
|
+
session.metadata = meta;
|
|
1434
|
+
session.messageCount = messages.filter((m) => !m.isArchived).length;
|
|
1435
|
+
session.updatedAt = Date.now();
|
|
1436
|
+
return true;
|
|
1437
|
+
}
|
|
1438
|
+
async archiveMessages(sessionId, checkpointId, beforeIndex) {
|
|
1439
|
+
const session = this.sessions.get(sessionId);
|
|
1440
|
+
if (!session)
|
|
1441
|
+
return 0;
|
|
1442
|
+
const messages = this.messages.get(sessionId) ?? [];
|
|
1443
|
+
let archivedCount = 0;
|
|
1444
|
+
for (let i = 0;i < beforeIndex; i++) {
|
|
1445
|
+
if (!messages[i].isArchived) {
|
|
1446
|
+
messages[i].isArchived = true;
|
|
1447
|
+
messages[i].archivedAt = Date.now();
|
|
1448
|
+
messages[i].checkpointId = checkpointId;
|
|
1449
|
+
archivedCount++;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
session.messageCount = messages.filter((m) => !m.isArchived).length;
|
|
1453
|
+
session.updatedAt = Date.now();
|
|
1454
|
+
return archivedCount;
|
|
1455
|
+
}
|
|
1456
|
+
async getActiveMessages(sessionId, offset = 0, limit = 50) {
|
|
1457
|
+
const messages = this.messages.get(sessionId) ?? [];
|
|
1458
|
+
const activeMessages = messages.filter((m) => !m.isArchived);
|
|
1459
|
+
return activeMessages.slice(offset, offset + limit);
|
|
1460
|
+
}
|
|
1461
|
+
async searchMessages(options) {
|
|
1462
|
+
const matches = [];
|
|
1463
|
+
const {
|
|
1464
|
+
query,
|
|
1465
|
+
sessionId,
|
|
1466
|
+
limit = 10,
|
|
1467
|
+
beforeTime,
|
|
1468
|
+
afterTime,
|
|
1469
|
+
includeArchived = false
|
|
1470
|
+
} = options;
|
|
1471
|
+
let sessionsToSearch;
|
|
1472
|
+
if (sessionId) {
|
|
1473
|
+
const session = await this.get(sessionId);
|
|
1474
|
+
sessionsToSearch = session ? [session] : [];
|
|
1475
|
+
} else {
|
|
1476
|
+
sessionsToSearch = Array.from(this.sessions.values());
|
|
1477
|
+
}
|
|
1478
|
+
const queryTerms = this.parseQuery(query);
|
|
1479
|
+
for (const session of sessionsToSearch) {
|
|
1480
|
+
if (beforeTime && session.updatedAt > beforeTime)
|
|
1481
|
+
continue;
|
|
1482
|
+
if (afterTime && session.updatedAt < afterTime)
|
|
1483
|
+
continue;
|
|
1484
|
+
let messages = this.messages.get(session.id) ?? [];
|
|
1485
|
+
if (!includeArchived) {
|
|
1486
|
+
messages = messages.filter((m) => !m.isArchived);
|
|
1487
|
+
}
|
|
1488
|
+
for (const msg of messages) {
|
|
1489
|
+
if (beforeTime && msg.timestamp > beforeTime)
|
|
1490
|
+
continue;
|
|
1491
|
+
if (afterTime && msg.timestamp < afterTime)
|
|
1492
|
+
continue;
|
|
1493
|
+
const content = msg.content.toLowerCase();
|
|
1494
|
+
let matchesQuery = true;
|
|
1495
|
+
for (const term of queryTerms.required) {
|
|
1496
|
+
if (!content.includes(term.toLowerCase())) {
|
|
1497
|
+
matchesQuery = false;
|
|
1498
|
+
break;
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
for (const term of queryTerms.excluded) {
|
|
1502
|
+
if (content.includes(term.toLowerCase())) {
|
|
1503
|
+
matchesQuery = false;
|
|
1504
|
+
break;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
if (matchesQuery) {
|
|
1508
|
+
matches.push({
|
|
1509
|
+
messageId: msg.id,
|
|
1510
|
+
sessionId: session.id,
|
|
1511
|
+
role: msg.role,
|
|
1512
|
+
content: msg.content,
|
|
1513
|
+
timestamp: msg.timestamp
|
|
1514
|
+
});
|
|
1515
|
+
if (matches.length >= limit) {
|
|
1516
|
+
return matches;
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
return matches;
|
|
1522
|
+
}
|
|
1523
|
+
parseQuery(query) {
|
|
1524
|
+
const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
|
|
1525
|
+
const required = [];
|
|
1526
|
+
const excluded = [];
|
|
1527
|
+
for (const term of terms) {
|
|
1528
|
+
if (term.startsWith("-") || term.startsWith("NOT ")) {
|
|
1529
|
+
excluded.push(term.replace(/^-|^NOT /i, ""));
|
|
1530
|
+
} else {
|
|
1531
|
+
required.push(term);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
return { required, excluded };
|
|
1535
|
+
}
|
|
1536
|
+
async close() {
|
|
1537
|
+
this.sessions.clear();
|
|
1538
|
+
this.messages.clear();
|
|
1539
|
+
this.checkpoints.clear();
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
// packages/core/src/env/session/storage/sqlite.ts
|
|
1543
|
+
import { join as join2 } from "path";
|
|
1544
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
1545
|
+
function generateSessionId2() {
|
|
1546
|
+
return `session_${randomUUID3()}`;
|
|
1547
|
+
}
|
|
1548
|
+
function generateMessageId2() {
|
|
1549
|
+
return `msg_${randomUUID3()}`;
|
|
1550
|
+
}
|
|
1551
|
+
function getDefaultDataDir() {
|
|
1552
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
1553
|
+
return join2(home, ".local", "share");
|
|
1554
|
+
}
|
|
1555
|
+
function getDefaultSessionDbPath() {
|
|
1556
|
+
return join2(getDefaultDataDir(), "roy-agent", "sessions.db");
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
class SQLiteSessionStore {
|
|
1560
|
+
db = null;
|
|
1561
|
+
dbPath;
|
|
1562
|
+
initialized = false;
|
|
1563
|
+
sessionsCache = new Map;
|
|
1564
|
+
messagesCache = new Map;
|
|
1565
|
+
checkpointsCache = new Map;
|
|
1566
|
+
messageConverter = new SessionMessageConverter;
|
|
1567
|
+
constructor(dbPath) {
|
|
1568
|
+
this.dbPath = dbPath || getDefaultSessionDbPath();
|
|
1569
|
+
}
|
|
1570
|
+
async initialize() {
|
|
1571
|
+
if (this.initialized)
|
|
1572
|
+
return;
|
|
1573
|
+
const { Database } = __require("bun:sqlite");
|
|
1574
|
+
if (this.dbPath !== ":memory:") {
|
|
1575
|
+
const fs = __require("fs");
|
|
1576
|
+
const path = __require("path");
|
|
1577
|
+
const dir = path.dirname(this.dbPath);
|
|
1578
|
+
if (!fs.existsSync(dir)) {
|
|
1579
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
this.db = new Database(this.dbPath);
|
|
1583
|
+
this.db.run(`
|
|
1584
|
+
CREATE TABLE IF NOT EXISTS session (
|
|
1585
|
+
id TEXT PRIMARY KEY,
|
|
1586
|
+
title TEXT NOT NULL,
|
|
1587
|
+
directory TEXT NOT NULL,
|
|
1588
|
+
parent_id TEXT,
|
|
1589
|
+
created_at INTEGER NOT NULL,
|
|
1590
|
+
updated_at INTEGER NOT NULL,
|
|
1591
|
+
message_count INTEGER DEFAULT 0,
|
|
1592
|
+
metadata TEXT
|
|
1593
|
+
)
|
|
1594
|
+
`);
|
|
1595
|
+
this.db.run(`
|
|
1596
|
+
CREATE TABLE IF NOT EXISTS message (
|
|
1597
|
+
id TEXT PRIMARY KEY,
|
|
1598
|
+
session_id TEXT NOT NULL,
|
|
1599
|
+
role TEXT NOT NULL,
|
|
1600
|
+
content TEXT NOT NULL,
|
|
1601
|
+
timestamp INTEGER NOT NULL,
|
|
1602
|
+
parts TEXT,
|
|
1603
|
+
is_archived INTEGER DEFAULT 0,
|
|
1604
|
+
archived_at INTEGER,
|
|
1605
|
+
checkpoint_id TEXT,
|
|
1606
|
+
metadata TEXT,
|
|
1607
|
+
FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE
|
|
1608
|
+
)
|
|
1609
|
+
`);
|
|
1610
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_message_session ON message(session_id)");
|
|
1611
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_message_checkpoint ON message(checkpoint_id)");
|
|
1612
|
+
this.initialized = true;
|
|
1613
|
+
}
|
|
1614
|
+
async create(options) {
|
|
1615
|
+
await this.initialize();
|
|
1616
|
+
const now = Date.now();
|
|
1617
|
+
const session = {
|
|
1618
|
+
id: options.id ?? generateSessionId2(),
|
|
1619
|
+
title: options.title ?? "Session",
|
|
1620
|
+
directory: options.directory ?? "/tmp",
|
|
1621
|
+
parentID: options.parentID,
|
|
1622
|
+
createdAt: now,
|
|
1623
|
+
updatedAt: now,
|
|
1624
|
+
messageCount: 0,
|
|
1625
|
+
metadata: {
|
|
1626
|
+
...options.metadata,
|
|
1627
|
+
messageCount: 0,
|
|
1628
|
+
checkpoints: { checkpoints: [] }
|
|
1629
|
+
}
|
|
1630
|
+
};
|
|
1631
|
+
const existing = this.db.prepare("SELECT id FROM session WHERE id = ?").get(session.id);
|
|
1632
|
+
if (existing) {
|
|
1633
|
+
throw new Error(`Session with ID '${session.id}' already exists`);
|
|
1634
|
+
}
|
|
1635
|
+
const stmt = this.db.prepare(`
|
|
1636
|
+
INSERT INTO session (id, title, directory, parent_id, created_at, updated_at, message_count, metadata)
|
|
1637
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
1638
|
+
`);
|
|
1639
|
+
stmt.run(session.id, session.title, session.directory, session.parentID || null, session.createdAt, session.updatedAt, session.messageCount, JSON.stringify(session.metadata));
|
|
1640
|
+
this.sessionsCache.set(session.id, session);
|
|
1641
|
+
this.messagesCache.set(session.id, []);
|
|
1642
|
+
this.checkpointsCache.set(session.id, []);
|
|
1643
|
+
return session;
|
|
1644
|
+
}
|
|
1645
|
+
async get(id) {
|
|
1646
|
+
await this.initialize();
|
|
1647
|
+
const cached = this.sessionsCache.get(id);
|
|
1648
|
+
if (cached)
|
|
1649
|
+
return cached;
|
|
1650
|
+
const row = this.db.prepare("SELECT * FROM session WHERE id = ?").get(id);
|
|
1651
|
+
if (!row)
|
|
1652
|
+
return;
|
|
1653
|
+
const session = this.rowToSession(row);
|
|
1654
|
+
this.sessionsCache.set(session.id, session);
|
|
1655
|
+
return session;
|
|
1656
|
+
}
|
|
1657
|
+
async list(options) {
|
|
1658
|
+
await this.initialize();
|
|
1659
|
+
let sql = "SELECT * FROM session";
|
|
1660
|
+
const params = [];
|
|
1661
|
+
const conditions = [];
|
|
1662
|
+
if (options?.filter?.metadata) {
|
|
1663
|
+
for (const [key, value] of Object.entries(options.filter.metadata)) {
|
|
1664
|
+
conditions.push(`json_extract(metadata, '$.${key}') = ?`);
|
|
1665
|
+
params.push(JSON.stringify(value));
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
if (options?.filter?.startTime) {
|
|
1669
|
+
conditions.push("created_at >= ?");
|
|
1670
|
+
params.push(options.filter.startTime);
|
|
1671
|
+
}
|
|
1672
|
+
if (options?.filter?.endTime) {
|
|
1673
|
+
conditions.push("created_at <= ?");
|
|
1674
|
+
params.push(options.filter.endTime);
|
|
1675
|
+
}
|
|
1676
|
+
if (conditions.length > 0) {
|
|
1677
|
+
sql += " WHERE " + conditions.join(" AND ");
|
|
1678
|
+
}
|
|
1679
|
+
const sortField = options?.sort?.field ?? "updatedAt";
|
|
1680
|
+
const sortOrder = options?.sort?.order ?? "desc";
|
|
1681
|
+
const orderColumn = sortField === "title" ? "title" : sortField === "createdAt" ? "created_at" : "updated_at";
|
|
1682
|
+
sql += ` ORDER BY ${orderColumn} ${sortOrder.toUpperCase()}`;
|
|
1683
|
+
const offset = options?.offset ?? 0;
|
|
1684
|
+
const limit = options?.limit ?? 100;
|
|
1685
|
+
sql += " LIMIT ? OFFSET ?";
|
|
1686
|
+
params.push(limit, offset);
|
|
1687
|
+
const rows = this.db.prepare(sql).all(...params);
|
|
1688
|
+
return rows.map((row) => this.rowToSession(row));
|
|
1689
|
+
}
|
|
1690
|
+
async getCount() {
|
|
1691
|
+
await this.initialize();
|
|
1692
|
+
const result = this.db.prepare("SELECT COUNT(*) as count FROM session").get();
|
|
1693
|
+
return result.count;
|
|
1694
|
+
}
|
|
1695
|
+
async update(id, updates) {
|
|
1696
|
+
await this.initialize();
|
|
1697
|
+
const session = await this.get(id);
|
|
1698
|
+
if (!session)
|
|
1699
|
+
return false;
|
|
1700
|
+
if (updates.title !== undefined) {
|
|
1701
|
+
session.title = updates.title;
|
|
1702
|
+
}
|
|
1703
|
+
if (updates.metadata !== undefined) {
|
|
1704
|
+
session.metadata = { ...session.metadata, ...updates.metadata };
|
|
1705
|
+
}
|
|
1706
|
+
session.updatedAt = Date.now();
|
|
1707
|
+
const stmt = this.db.prepare(`
|
|
1708
|
+
UPDATE session
|
|
1709
|
+
SET title = ?, metadata = ?, updated_at = ?
|
|
1710
|
+
WHERE id = ?
|
|
1711
|
+
`);
|
|
1712
|
+
stmt.run(session.title, JSON.stringify(session.metadata), session.updatedAt, id);
|
|
1713
|
+
this.sessionsCache.set(id, session);
|
|
1714
|
+
return true;
|
|
1715
|
+
}
|
|
1716
|
+
async delete(id) {
|
|
1717
|
+
await this.initialize();
|
|
1718
|
+
const session = await this.get(id);
|
|
1719
|
+
if (!session)
|
|
1720
|
+
return false;
|
|
1721
|
+
this.db.prepare("DELETE FROM session WHERE id = ?").run(id);
|
|
1722
|
+
this.sessionsCache.delete(id);
|
|
1723
|
+
this.messagesCache.delete(id);
|
|
1724
|
+
this.checkpointsCache.delete(id);
|
|
1725
|
+
return true;
|
|
1726
|
+
}
|
|
1727
|
+
async addMessage(sessionId, message) {
|
|
1728
|
+
await this.initialize();
|
|
1729
|
+
const session = await this.get(sessionId);
|
|
1730
|
+
if (!session) {
|
|
1731
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
1732
|
+
}
|
|
1733
|
+
const now = Date.now();
|
|
1734
|
+
const msg = {
|
|
1735
|
+
id: generateMessageId2(),
|
|
1736
|
+
sessionID: sessionId,
|
|
1737
|
+
role: message.role,
|
|
1738
|
+
content: message.content,
|
|
1739
|
+
timestamp: now,
|
|
1740
|
+
parts: message.parts,
|
|
1741
|
+
metadata: message.metadata
|
|
1742
|
+
};
|
|
1743
|
+
const stmt = this.db.prepare(`
|
|
1744
|
+
INSERT INTO message (id, session_id, role, content, timestamp, parts, metadata)
|
|
1745
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1746
|
+
`);
|
|
1747
|
+
stmt.run(msg.id, msg.sessionID, msg.role, msg.content, msg.timestamp, msg.parts ? JSON.stringify(msg.parts) : null, msg.metadata ? JSON.stringify(msg.metadata) : null);
|
|
1748
|
+
const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
|
|
1749
|
+
session.messageCount = countResult?.count || 0;
|
|
1750
|
+
session.updatedAt = now;
|
|
1751
|
+
session.metadata = {
|
|
1752
|
+
...session.metadata,
|
|
1753
|
+
messageCount: session.messageCount
|
|
1754
|
+
};
|
|
1755
|
+
this.db.prepare(`
|
|
1756
|
+
UPDATE session SET message_count = ?, metadata = ?, updated_at = ? WHERE id = ?
|
|
1757
|
+
`).run(session.messageCount, JSON.stringify(session.metadata), session.updatedAt, sessionId);
|
|
1758
|
+
const messages = this.messagesCache.get(sessionId) ?? [];
|
|
1759
|
+
messages.push(msg);
|
|
1760
|
+
this.messagesCache.set(sessionId, messages);
|
|
1761
|
+
this.sessionsCache.set(sessionId, session);
|
|
1762
|
+
return msg.id;
|
|
1763
|
+
}
|
|
1764
|
+
async getMessages(sessionId, offset = 0, limit = 50, options) {
|
|
1765
|
+
await this.initialize();
|
|
1766
|
+
let sql = "SELECT * FROM message WHERE session_id = ?";
|
|
1767
|
+
let countSql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
|
|
1768
|
+
const params = [sessionId];
|
|
1769
|
+
const countParams = [sessionId];
|
|
1770
|
+
if (!options?.includeArchived) {
|
|
1771
|
+
sql += " AND is_archived = 0";
|
|
1772
|
+
countSql += " AND is_archived = 0";
|
|
1773
|
+
}
|
|
1774
|
+
if (options?.fromCheckpointId) {
|
|
1775
|
+
sql += " AND timestamp >= (SELECT MIN(timestamp) FROM message WHERE session_id = ? AND json_extract(metadata, '$.checkpointId') = ?)";
|
|
1776
|
+
params.push(sessionId, options.fromCheckpointId);
|
|
1777
|
+
}
|
|
1778
|
+
let actualOffset = offset;
|
|
1779
|
+
if (offset < 0) {
|
|
1780
|
+
const totalResult = this.db.prepare(countSql).get(...countParams);
|
|
1781
|
+
const total = totalResult?.count || 0;
|
|
1782
|
+
actualOffset = Math.max(0, total + offset * limit);
|
|
1783
|
+
}
|
|
1784
|
+
if (options?.reverse) {
|
|
1785
|
+
sql += " ORDER BY timestamp DESC";
|
|
1786
|
+
} else {
|
|
1787
|
+
sql += " ORDER BY timestamp ASC";
|
|
1788
|
+
}
|
|
1789
|
+
sql += " LIMIT ? OFFSET ?";
|
|
1790
|
+
params.push(limit, actualOffset);
|
|
1791
|
+
const rows = this.db.prepare(sql).all(...params);
|
|
1792
|
+
return rows.map((row) => this.rowToMessage(row));
|
|
1793
|
+
}
|
|
1794
|
+
async getMessageCount(sessionId, includeArchived = false) {
|
|
1795
|
+
await this.initialize();
|
|
1796
|
+
let sql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
|
|
1797
|
+
if (!includeArchived) {
|
|
1798
|
+
sql += " AND is_archived = 0";
|
|
1799
|
+
}
|
|
1800
|
+
const result = this.db.prepare(sql).get(sessionId);
|
|
1801
|
+
return result?.count || 0;
|
|
1802
|
+
}
|
|
1803
|
+
async getMessageIndexes(sessionId, role) {
|
|
1804
|
+
await this.initialize();
|
|
1805
|
+
const sql = `
|
|
1806
|
+
SELECT idx FROM (
|
|
1807
|
+
SELECT
|
|
1808
|
+
ROW_NUMBER() OVER (ORDER BY timestamp ASC) - 1 as idx,
|
|
1809
|
+
role
|
|
1810
|
+
FROM message
|
|
1811
|
+
WHERE session_id = ? AND is_archived = 0
|
|
1812
|
+
) ranked
|
|
1813
|
+
WHERE role = ?
|
|
1814
|
+
`;
|
|
1815
|
+
const rows = this.db.prepare(sql).all(sessionId, role);
|
|
1816
|
+
return rows.map((row) => row.idx);
|
|
1817
|
+
}
|
|
1818
|
+
async saveCheckpoint(sessionId, checkpoint) {
|
|
1819
|
+
await this.initialize();
|
|
1820
|
+
const session = await this.get(sessionId);
|
|
1821
|
+
if (!session) {
|
|
1822
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
1823
|
+
}
|
|
1824
|
+
const cps = this.checkpointsCache.get(sessionId) ?? [];
|
|
1825
|
+
cps.push(checkpoint);
|
|
1826
|
+
this.checkpointsCache.set(sessionId, cps);
|
|
1827
|
+
const meta = session.metadata || {};
|
|
1828
|
+
const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
|
|
1829
|
+
checkpointsMeta.checkpoints.push({
|
|
1830
|
+
id: checkpoint.id,
|
|
1831
|
+
messageIndex: checkpoint.messageIndex,
|
|
1832
|
+
title: checkpoint.title,
|
|
1833
|
+
createdAt: checkpoint.createdAt,
|
|
1834
|
+
type: checkpoint.type
|
|
1835
|
+
});
|
|
1836
|
+
checkpointsMeta.latestCheckpointId = checkpoint.id;
|
|
1837
|
+
meta.checkpoints = checkpointsMeta;
|
|
1838
|
+
if (!meta.checkpointDetails) {
|
|
1839
|
+
meta.checkpointDetails = {};
|
|
1840
|
+
}
|
|
1841
|
+
meta.checkpointDetails[checkpoint.id] = checkpoint;
|
|
1842
|
+
session.metadata = meta;
|
|
1843
|
+
session.updatedAt = Date.now();
|
|
1844
|
+
const stmt = this.db.prepare(`
|
|
1845
|
+
UPDATE session SET metadata = ?, updated_at = ? WHERE id = ?
|
|
1846
|
+
`);
|
|
1847
|
+
stmt.run(JSON.stringify(session.metadata), session.updatedAt, sessionId);
|
|
1848
|
+
this.sessionsCache.set(sessionId, session);
|
|
1849
|
+
}
|
|
1850
|
+
async getCheckpoints(sessionId) {
|
|
1851
|
+
await this.initialize();
|
|
1852
|
+
const session = await this.get(sessionId);
|
|
1853
|
+
if (!session)
|
|
1854
|
+
return [];
|
|
1855
|
+
const meta = session.metadata;
|
|
1856
|
+
const checkpointDetails = meta?.checkpointDetails;
|
|
1857
|
+
if (!checkpointDetails)
|
|
1858
|
+
return [];
|
|
1859
|
+
return Object.values(checkpointDetails);
|
|
1860
|
+
}
|
|
1861
|
+
async getCheckpoint(sessionId, checkpointId) {
|
|
1862
|
+
await this.initialize();
|
|
1863
|
+
const checkpoints = await this.getCheckpoints(sessionId);
|
|
1864
|
+
return checkpoints.find((cp) => cp.id === checkpointId);
|
|
1865
|
+
}
|
|
1866
|
+
async deleteCheckpoint(sessionId, checkpointId) {
|
|
1867
|
+
await this.initialize();
|
|
1868
|
+
const session = await this.get(sessionId);
|
|
1869
|
+
if (!session)
|
|
1870
|
+
return false;
|
|
1871
|
+
const checkpoints = this.checkpointsCache.get(sessionId) ?? [];
|
|
1872
|
+
const index = checkpoints.findIndex((cp) => cp.id === checkpointId);
|
|
1873
|
+
if (index === -1)
|
|
1874
|
+
return false;
|
|
1875
|
+
checkpoints.splice(index, 1);
|
|
1876
|
+
this.checkpointsCache.set(sessionId, checkpoints);
|
|
1877
|
+
this.db.prepare(`
|
|
1878
|
+
UPDATE message SET is_archived = 0, archived_at = NULL, checkpoint_id = NULL
|
|
1879
|
+
WHERE session_id = ? AND checkpoint_id = ?
|
|
1880
|
+
`).run(sessionId, checkpointId);
|
|
1881
|
+
const meta = session.metadata || {};
|
|
1882
|
+
const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
|
|
1883
|
+
checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
|
|
1884
|
+
checkpointsMeta.latestCheckpointId = checkpoints[checkpoints.length - 1]?.id;
|
|
1885
|
+
if (meta.checkpointDetails) {
|
|
1886
|
+
delete meta.checkpointDetails[checkpointId];
|
|
1887
|
+
}
|
|
1888
|
+
session.metadata = meta;
|
|
1889
|
+
const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
|
|
1890
|
+
session.messageCount = countResult?.count || 0;
|
|
1891
|
+
session.updatedAt = Date.now();
|
|
1892
|
+
this.db.prepare(`
|
|
1893
|
+
UPDATE session SET metadata = ?, message_count = ?, updated_at = ? WHERE id = ?
|
|
1894
|
+
`).run(JSON.stringify(session.metadata), session.messageCount, session.updatedAt, sessionId);
|
|
1895
|
+
this.sessionsCache.set(sessionId, session);
|
|
1896
|
+
return true;
|
|
1897
|
+
}
|
|
1898
|
+
async archiveMessages(sessionId, checkpointId, beforeIndex) {
|
|
1899
|
+
await this.initialize();
|
|
1900
|
+
const session = await this.get(sessionId);
|
|
1901
|
+
if (!session)
|
|
1902
|
+
return 0;
|
|
1903
|
+
const now = Date.now();
|
|
1904
|
+
const result = this.db.prepare(`
|
|
1905
|
+
UPDATE message
|
|
1906
|
+
SET is_archived = 1, archived_at = ?, checkpoint_id = ?
|
|
1907
|
+
WHERE session_id = ? AND id IN (
|
|
1908
|
+
SELECT id FROM message WHERE session_id = ? AND is_archived = 0
|
|
1909
|
+
ORDER BY timestamp ASC LIMIT ?
|
|
1910
|
+
)
|
|
1911
|
+
`).run(now, checkpointId, sessionId, sessionId, beforeIndex);
|
|
1912
|
+
const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
|
|
1913
|
+
session.messageCount = countResult?.count || 0;
|
|
1914
|
+
session.updatedAt = now;
|
|
1915
|
+
this.db.prepare(`
|
|
1916
|
+
UPDATE session SET message_count = ?, updated_at = ? WHERE id = ?
|
|
1917
|
+
`).run(session.messageCount, session.updatedAt, sessionId);
|
|
1918
|
+
this.sessionsCache.set(sessionId, session);
|
|
1919
|
+
this.messagesCache.delete(sessionId);
|
|
1920
|
+
return result.changes;
|
|
1921
|
+
}
|
|
1922
|
+
async getActiveMessages(sessionId, offset = 0, limit = 50) {
|
|
1923
|
+
return this.getMessages(sessionId, offset, limit, { includeArchived: false });
|
|
1924
|
+
}
|
|
1925
|
+
async searchMessages(options) {
|
|
1926
|
+
await this.initialize();
|
|
1927
|
+
const matches = [];
|
|
1928
|
+
const {
|
|
1929
|
+
query,
|
|
1930
|
+
sessionId,
|
|
1931
|
+
limit = 10,
|
|
1932
|
+
beforeTime,
|
|
1933
|
+
afterTime,
|
|
1934
|
+
includeArchived = false
|
|
1935
|
+
} = options;
|
|
1936
|
+
let sql = "SELECT * FROM message WHERE 1=1";
|
|
1937
|
+
const params = [];
|
|
1938
|
+
if (sessionId) {
|
|
1939
|
+
sql += " AND session_id = ?";
|
|
1940
|
+
params.push(sessionId);
|
|
1941
|
+
}
|
|
1942
|
+
if (!includeArchived) {
|
|
1943
|
+
sql += " AND is_archived = 0";
|
|
1944
|
+
}
|
|
1945
|
+
if (beforeTime) {
|
|
1946
|
+
sql += " AND timestamp <= ?";
|
|
1947
|
+
params.push(beforeTime);
|
|
1948
|
+
}
|
|
1949
|
+
if (afterTime) {
|
|
1950
|
+
sql += " AND timestamp >= ?";
|
|
1951
|
+
params.push(afterTime);
|
|
1952
|
+
}
|
|
1953
|
+
sql += " ORDER BY timestamp DESC";
|
|
1954
|
+
sql += " LIMIT ?";
|
|
1955
|
+
params.push(limit * 10);
|
|
1956
|
+
const rows = this.db.prepare(sql).all(...params);
|
|
1957
|
+
const queryTerms = this.parseQuery(query);
|
|
1958
|
+
const lowerQuery = query.toLowerCase();
|
|
1959
|
+
for (const row of rows) {
|
|
1960
|
+
const content = row.content.toLowerCase();
|
|
1961
|
+
let matchesQuery = true;
|
|
1962
|
+
for (const term of queryTerms.excluded) {
|
|
1963
|
+
if (content.includes(term.toLowerCase())) {
|
|
1964
|
+
matchesQuery = false;
|
|
1965
|
+
break;
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
if (matchesQuery && queryTerms.required.length > 0) {
|
|
1969
|
+
for (const term of queryTerms.required) {
|
|
1970
|
+
if (!content.includes(term.toLowerCase())) {
|
|
1971
|
+
matchesQuery = false;
|
|
1972
|
+
break;
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
if (!matchesQuery && lowerQuery && content.includes(lowerQuery)) {
|
|
1977
|
+
matchesQuery = true;
|
|
1978
|
+
}
|
|
1979
|
+
if (matchesQuery) {
|
|
1980
|
+
matches.push({
|
|
1981
|
+
messageId: row.id,
|
|
1982
|
+
sessionId: row.session_id,
|
|
1983
|
+
role: row.role,
|
|
1984
|
+
content: row.content,
|
|
1985
|
+
timestamp: row.timestamp
|
|
1986
|
+
});
|
|
1987
|
+
if (matches.length >= limit)
|
|
1988
|
+
break;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
return matches;
|
|
1992
|
+
}
|
|
1993
|
+
parseQuery(query) {
|
|
1994
|
+
const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
|
|
1995
|
+
const required = [];
|
|
1996
|
+
const excluded = [];
|
|
1997
|
+
for (const term of terms) {
|
|
1998
|
+
if (term.startsWith("-") || term.toUpperCase().startsWith("NOT ")) {
|
|
1999
|
+
excluded.push(term.replace(/^-|^NOT /i, ""));
|
|
2000
|
+
} else {
|
|
2001
|
+
required.push(term);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
return { required, excluded };
|
|
2005
|
+
}
|
|
2006
|
+
async close() {
|
|
2007
|
+
if (this.db) {
|
|
2008
|
+
this.db.close();
|
|
2009
|
+
this.db = null;
|
|
2010
|
+
}
|
|
2011
|
+
this.sessionsCache.clear();
|
|
2012
|
+
this.messagesCache.clear();
|
|
2013
|
+
this.checkpointsCache.clear();
|
|
2014
|
+
this.initialized = false;
|
|
2015
|
+
}
|
|
2016
|
+
rowToSession(row) {
|
|
2017
|
+
return {
|
|
2018
|
+
id: row.id,
|
|
2019
|
+
title: row.title,
|
|
2020
|
+
directory: row.directory,
|
|
2021
|
+
parentID: row.parent_id,
|
|
2022
|
+
createdAt: row.created_at,
|
|
2023
|
+
updatedAt: row.updated_at,
|
|
2024
|
+
messageCount: row.message_count,
|
|
2025
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : undefined
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
rowToMessage(row) {
|
|
2029
|
+
const rawMessage = {
|
|
2030
|
+
id: row.id,
|
|
2031
|
+
sessionID: row.session_id,
|
|
2032
|
+
role: row.role,
|
|
2033
|
+
content: row.content,
|
|
2034
|
+
timestamp: row.timestamp,
|
|
2035
|
+
parts: row.parts ? JSON.parse(row.parts) : undefined,
|
|
2036
|
+
isArchived: row.is_archived === 1,
|
|
2037
|
+
archivedAt: row.archived_at || undefined,
|
|
2038
|
+
checkpointId: row.checkpoint_id || undefined,
|
|
2039
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : undefined
|
|
2040
|
+
};
|
|
2041
|
+
return this.messageConverter.migrateMessage(rawMessage);
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
export {
|
|
2045
|
+
getDefaultSessionDbPath,
|
|
2046
|
+
getDefaultDataDir,
|
|
2047
|
+
SQLiteSessionStore,
|
|
2048
|
+
MemorySessionStore
|
|
2049
|
+
};
|