@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,1464 @@
|
|
|
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/task/storage/sqlite-task-store.ts
|
|
850
|
+
init_logger();
|
|
851
|
+
import { join as join2 } from "path";
|
|
852
|
+
var logger = createLogger("task:store");
|
|
853
|
+
function getDefaultDataDir() {
|
|
854
|
+
const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
|
|
855
|
+
return join2(home, ".local", "share");
|
|
856
|
+
}
|
|
857
|
+
function getDefaultTaskDbPath() {
|
|
858
|
+
return join2(getDefaultDataDir(), "roy-agent", "tasks.db");
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
class SQLiteTaskStore {
|
|
862
|
+
db = null;
|
|
863
|
+
dbPath;
|
|
864
|
+
initialized = false;
|
|
865
|
+
tasksCache = new Map;
|
|
866
|
+
operationsCache = new Map;
|
|
867
|
+
constructor(dbPath) {
|
|
868
|
+
this.dbPath = dbPath || getDefaultTaskDbPath();
|
|
869
|
+
}
|
|
870
|
+
async initialize() {
|
|
871
|
+
if (this.initialized)
|
|
872
|
+
return;
|
|
873
|
+
const { Database } = __require("bun:sqlite");
|
|
874
|
+
if (this.dbPath !== ":memory:") {
|
|
875
|
+
const fs = __require("fs");
|
|
876
|
+
const path = __require("path");
|
|
877
|
+
const dir = path.dirname(this.dbPath);
|
|
878
|
+
if (!fs.existsSync(dir)) {
|
|
879
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
this.db = new Database(this.dbPath);
|
|
883
|
+
this.db.run(`
|
|
884
|
+
CREATE TABLE IF NOT EXISTS task (
|
|
885
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
886
|
+
title TEXT NOT NULL,
|
|
887
|
+
description TEXT DEFAULT '',
|
|
888
|
+
status TEXT DEFAULT 'todo',
|
|
889
|
+
priority TEXT DEFAULT 'medium',
|
|
890
|
+
progress INTEGER DEFAULT 0,
|
|
891
|
+
current_status TEXT DEFAULT '',
|
|
892
|
+
goals_and_expected_deliverables TEXT DEFAULT '',
|
|
893
|
+
parent_task_id INTEGER,
|
|
894
|
+
created_at INTEGER NOT NULL,
|
|
895
|
+
updated_at INTEGER NOT NULL,
|
|
896
|
+
due_date TEXT,
|
|
897
|
+
tags TEXT
|
|
898
|
+
)
|
|
899
|
+
`);
|
|
900
|
+
this.db.run(`
|
|
901
|
+
CREATE TABLE IF NOT EXISTS task_operation (
|
|
902
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
903
|
+
task_id INTEGER NOT NULL,
|
|
904
|
+
session_id TEXT NOT NULL,
|
|
905
|
+
action_type TEXT NOT NULL,
|
|
906
|
+
action_title TEXT NOT NULL,
|
|
907
|
+
action_description TEXT DEFAULT '',
|
|
908
|
+
timestamp INTEGER NOT NULL,
|
|
909
|
+
md_path TEXT,
|
|
910
|
+
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE
|
|
911
|
+
)
|
|
912
|
+
`);
|
|
913
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_task_id ON task_operation(task_id)");
|
|
914
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_session_id ON task_operation(session_id)");
|
|
915
|
+
this.db.run(`
|
|
916
|
+
CREATE TABLE IF NOT EXISTS task_tag (
|
|
917
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
918
|
+
name TEXT NOT NULL UNIQUE,
|
|
919
|
+
created_at INTEGER NOT NULL,
|
|
920
|
+
task_count INTEGER DEFAULT 0
|
|
921
|
+
)
|
|
922
|
+
`);
|
|
923
|
+
this.db.run(`
|
|
924
|
+
CREATE TABLE IF NOT EXISTS task_tag_relation (
|
|
925
|
+
task_id INTEGER NOT NULL,
|
|
926
|
+
tag_id INTEGER NOT NULL,
|
|
927
|
+
created_at INTEGER NOT NULL,
|
|
928
|
+
PRIMARY KEY (task_id, tag_id),
|
|
929
|
+
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
930
|
+
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
931
|
+
)
|
|
932
|
+
`);
|
|
933
|
+
this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)");
|
|
934
|
+
this.initialized = true;
|
|
935
|
+
logger.info(`TaskStore initialized at ${this.dbPath}`);
|
|
936
|
+
}
|
|
937
|
+
async createTask(options) {
|
|
938
|
+
await this.initialize();
|
|
939
|
+
const now = Date.now();
|
|
940
|
+
const stmt = this.db.prepare(`
|
|
941
|
+
INSERT INTO task (title, description, priority, parent_task_id,
|
|
942
|
+
goals_and_expected_deliverables, due_date, tags, status,
|
|
943
|
+
current_status, created_at, updated_at)
|
|
944
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?)
|
|
945
|
+
`);
|
|
946
|
+
const result = stmt.run(options.title, options.description || "", options.priority || "medium", options.parent_task_id || null, options.goals_and_expected_deliverables || "", options.due_date || null, options.tags ? JSON.stringify(options.tags) : null, now, now);
|
|
947
|
+
const task = await this.getTask(result.lastInsertRowid);
|
|
948
|
+
if (task) {
|
|
949
|
+
this.tasksCache.set(task.id, task);
|
|
950
|
+
return task;
|
|
951
|
+
}
|
|
952
|
+
throw new Error("Failed to create task");
|
|
953
|
+
}
|
|
954
|
+
async getTask(id) {
|
|
955
|
+
await this.initialize();
|
|
956
|
+
if (this.tasksCache.has(id)) {
|
|
957
|
+
return this.tasksCache.get(id);
|
|
958
|
+
}
|
|
959
|
+
const stmt = this.db.prepare("SELECT * FROM task WHERE id = ?");
|
|
960
|
+
const row = stmt.get(id);
|
|
961
|
+
if (!row)
|
|
962
|
+
return;
|
|
963
|
+
const task = this.rowToTask(row);
|
|
964
|
+
this.tasksCache.set(id, task);
|
|
965
|
+
return task;
|
|
966
|
+
}
|
|
967
|
+
async updateTask(id, options) {
|
|
968
|
+
await this.initialize();
|
|
969
|
+
const task = await this.getTask(id);
|
|
970
|
+
if (!task)
|
|
971
|
+
return;
|
|
972
|
+
const updates = [];
|
|
973
|
+
const values = [];
|
|
974
|
+
if (options.title !== undefined) {
|
|
975
|
+
updates.push("title = ?");
|
|
976
|
+
values.push(options.title);
|
|
977
|
+
}
|
|
978
|
+
if (options.description !== undefined) {
|
|
979
|
+
updates.push("description = ?");
|
|
980
|
+
values.push(options.description);
|
|
981
|
+
}
|
|
982
|
+
if (options.status !== undefined) {
|
|
983
|
+
updates.push("status = ?");
|
|
984
|
+
values.push(options.status);
|
|
985
|
+
}
|
|
986
|
+
if (options.priority !== undefined) {
|
|
987
|
+
updates.push("priority = ?");
|
|
988
|
+
values.push(options.priority);
|
|
989
|
+
}
|
|
990
|
+
if (options.progress !== undefined) {
|
|
991
|
+
updates.push("progress = ?");
|
|
992
|
+
values.push(options.progress);
|
|
993
|
+
}
|
|
994
|
+
if (options.current_status !== undefined) {
|
|
995
|
+
updates.push("current_status = ?");
|
|
996
|
+
values.push(options.current_status);
|
|
997
|
+
}
|
|
998
|
+
if (options.goals_and_expected_deliverables !== undefined) {
|
|
999
|
+
updates.push("goals_and_expected_deliverables = ?");
|
|
1000
|
+
values.push(options.goals_and_expected_deliverables);
|
|
1001
|
+
}
|
|
1002
|
+
if (options.due_date !== undefined) {
|
|
1003
|
+
updates.push("due_date = ?");
|
|
1004
|
+
values.push(options.due_date);
|
|
1005
|
+
}
|
|
1006
|
+
if (options.tags !== undefined) {
|
|
1007
|
+
updates.push("tags = ?");
|
|
1008
|
+
values.push(JSON.stringify(options.tags));
|
|
1009
|
+
}
|
|
1010
|
+
if (updates.length === 0)
|
|
1011
|
+
return task;
|
|
1012
|
+
updates.push("updated_at = ?");
|
|
1013
|
+
values.push(Date.now());
|
|
1014
|
+
values.push(id);
|
|
1015
|
+
const stmt = this.db.prepare(`UPDATE task SET ${updates.join(", ")} WHERE id = ?`);
|
|
1016
|
+
stmt.run(...values);
|
|
1017
|
+
this.tasksCache.delete(id);
|
|
1018
|
+
return this.getTask(id);
|
|
1019
|
+
}
|
|
1020
|
+
async deleteTask(id) {
|
|
1021
|
+
await this.initialize();
|
|
1022
|
+
const stmt = this.db.prepare("DELETE FROM task WHERE id = ?");
|
|
1023
|
+
const result = stmt.run(id);
|
|
1024
|
+
if (result.changes > 0) {
|
|
1025
|
+
this.tasksCache.delete(id);
|
|
1026
|
+
this.operationsCache.delete(id);
|
|
1027
|
+
}
|
|
1028
|
+
return result.changes > 0;
|
|
1029
|
+
}
|
|
1030
|
+
async listTasks(options) {
|
|
1031
|
+
await this.initialize();
|
|
1032
|
+
let sql = "SELECT * FROM task WHERE 1=1";
|
|
1033
|
+
const params = [];
|
|
1034
|
+
if (options?.status) {
|
|
1035
|
+
sql += " AND status = ?";
|
|
1036
|
+
params.push(options.status);
|
|
1037
|
+
}
|
|
1038
|
+
if (options?.priority) {
|
|
1039
|
+
sql += " AND priority = ?";
|
|
1040
|
+
params.push(options.priority);
|
|
1041
|
+
}
|
|
1042
|
+
if (options?.parent_task_id !== undefined) {
|
|
1043
|
+
sql += " AND parent_task_id = ?";
|
|
1044
|
+
params.push(options.parent_task_id);
|
|
1045
|
+
}
|
|
1046
|
+
sql += " ORDER BY updated_at DESC";
|
|
1047
|
+
if (options?.limit) {
|
|
1048
|
+
sql += " LIMIT ?";
|
|
1049
|
+
params.push(options.limit);
|
|
1050
|
+
}
|
|
1051
|
+
if (options?.offset) {
|
|
1052
|
+
sql += " OFFSET ?";
|
|
1053
|
+
params.push(options.offset);
|
|
1054
|
+
}
|
|
1055
|
+
const stmt = this.db.prepare(sql);
|
|
1056
|
+
const rows = stmt.all(...params);
|
|
1057
|
+
return rows.map((row) => {
|
|
1058
|
+
const task = this.rowToTask(row);
|
|
1059
|
+
this.tasksCache.set(task.id, task);
|
|
1060
|
+
return task;
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
async createOperation(options) {
|
|
1064
|
+
await this.initialize();
|
|
1065
|
+
const now = Date.now();
|
|
1066
|
+
const stmt = this.db.prepare(`
|
|
1067
|
+
INSERT INTO task_operation (task_id, session_id, action_type, action_title,
|
|
1068
|
+
action_description, timestamp, md_path)
|
|
1069
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1070
|
+
`);
|
|
1071
|
+
const result = stmt.run(options.taskId, options.sessionId, options.actionType, options.actionTitle, options.actionDescription || "", now, options.mdPath || null);
|
|
1072
|
+
this.operationsCache.delete(options.taskId);
|
|
1073
|
+
const operation = await this.getOperation(result.lastInsertRowid);
|
|
1074
|
+
if (!operation) {
|
|
1075
|
+
throw new Error("Failed to create operation");
|
|
1076
|
+
}
|
|
1077
|
+
return operation;
|
|
1078
|
+
}
|
|
1079
|
+
async getOperation(id) {
|
|
1080
|
+
await this.initialize();
|
|
1081
|
+
const stmt = this.db.prepare("SELECT * FROM task_operation WHERE id = ?");
|
|
1082
|
+
const row = stmt.get(id);
|
|
1083
|
+
if (!row)
|
|
1084
|
+
return;
|
|
1085
|
+
return this.rowToOperation(row);
|
|
1086
|
+
}
|
|
1087
|
+
async updateOperation(id, updates) {
|
|
1088
|
+
await this.initialize();
|
|
1089
|
+
const op = await this.getOperation(id);
|
|
1090
|
+
if (!op)
|
|
1091
|
+
return;
|
|
1092
|
+
const setClauses = [];
|
|
1093
|
+
const values = [];
|
|
1094
|
+
if (updates.actionTitle !== undefined) {
|
|
1095
|
+
setClauses.push("action_title = ?");
|
|
1096
|
+
values.push(updates.actionTitle);
|
|
1097
|
+
}
|
|
1098
|
+
if (updates.actionDescription !== undefined) {
|
|
1099
|
+
setClauses.push("action_description = ?");
|
|
1100
|
+
values.push(updates.actionDescription);
|
|
1101
|
+
}
|
|
1102
|
+
if (setClauses.length === 0)
|
|
1103
|
+
return op;
|
|
1104
|
+
const stmt = this.db.prepare(`UPDATE task_operation SET ${setClauses.join(", ")} WHERE id = ?`);
|
|
1105
|
+
stmt.run(...values, id);
|
|
1106
|
+
this.operationsCache.delete(op.taskId);
|
|
1107
|
+
return this.getOperation(id);
|
|
1108
|
+
}
|
|
1109
|
+
async deleteOperation(id) {
|
|
1110
|
+
await this.initialize();
|
|
1111
|
+
const op = await this.getOperation(id);
|
|
1112
|
+
if (!op)
|
|
1113
|
+
return false;
|
|
1114
|
+
const stmt = this.db.prepare("DELETE FROM task_operation WHERE id = ?");
|
|
1115
|
+
const result = stmt.run(id);
|
|
1116
|
+
if (result.changes > 0) {
|
|
1117
|
+
this.operationsCache.delete(op.taskId);
|
|
1118
|
+
}
|
|
1119
|
+
return result.changes > 0;
|
|
1120
|
+
}
|
|
1121
|
+
async listOperations(options) {
|
|
1122
|
+
await this.initialize();
|
|
1123
|
+
const cacheKey = options.taskId;
|
|
1124
|
+
if (!this.operationsCache.has(cacheKey)) {
|
|
1125
|
+
const stmt = this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC");
|
|
1126
|
+
const rows = stmt.all(options.taskId);
|
|
1127
|
+
this.operationsCache.set(cacheKey, rows.map((row) => this.rowToOperation(row)));
|
|
1128
|
+
}
|
|
1129
|
+
let ops = this.operationsCache.get(cacheKey);
|
|
1130
|
+
if (options.actionType) {
|
|
1131
|
+
ops = ops.filter((op) => op.actionType === options.actionType);
|
|
1132
|
+
}
|
|
1133
|
+
const offset = options.offset || 0;
|
|
1134
|
+
const limit = options.limit || 20;
|
|
1135
|
+
return ops.slice(offset, offset + limit);
|
|
1136
|
+
}
|
|
1137
|
+
rowToTask(row) {
|
|
1138
|
+
return {
|
|
1139
|
+
id: row.id,
|
|
1140
|
+
title: row.title,
|
|
1141
|
+
description: row.description,
|
|
1142
|
+
status: row.status,
|
|
1143
|
+
priority: row.priority,
|
|
1144
|
+
progress: row.progress,
|
|
1145
|
+
current_status: row.current_status,
|
|
1146
|
+
goals_and_expected_deliverables: row.goals_and_expected_deliverables,
|
|
1147
|
+
parent_task_id: row.parent_task_id || undefined,
|
|
1148
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
1149
|
+
updatedAt: new Date(row.updated_at).toISOString(),
|
|
1150
|
+
due_date: row.due_date || undefined,
|
|
1151
|
+
tags: row.tags ? JSON.parse(row.tags) : undefined
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
rowToOperation(row) {
|
|
1155
|
+
return {
|
|
1156
|
+
id: row.id,
|
|
1157
|
+
taskId: row.task_id,
|
|
1158
|
+
sessionId: row.session_id,
|
|
1159
|
+
actionType: row.action_type,
|
|
1160
|
+
actionTitle: row.action_title,
|
|
1161
|
+
actionDescription: row.action_description,
|
|
1162
|
+
timestamp: new Date(row.timestamp).toISOString(),
|
|
1163
|
+
mdPath: row.md_path || undefined
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
async createTag(name) {
|
|
1167
|
+
await this.initialize();
|
|
1168
|
+
const now = Date.now();
|
|
1169
|
+
const existing = await this.getTagByName(name);
|
|
1170
|
+
if (existing) {
|
|
1171
|
+
return existing;
|
|
1172
|
+
}
|
|
1173
|
+
const stmt = this.db.prepare(`
|
|
1174
|
+
INSERT INTO task_tag (name, created_at, task_count)
|
|
1175
|
+
VALUES (?, ?, 0)
|
|
1176
|
+
`);
|
|
1177
|
+
const result = stmt.run(name, now);
|
|
1178
|
+
return {
|
|
1179
|
+
id: result.lastInsertRowid,
|
|
1180
|
+
name,
|
|
1181
|
+
createdAt: new Date(now).toISOString(),
|
|
1182
|
+
taskCount: 0
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
async getTag(id) {
|
|
1186
|
+
await this.initialize();
|
|
1187
|
+
const stmt = this.db.prepare("SELECT * FROM task_tag WHERE id = ?");
|
|
1188
|
+
const row = stmt.get(id);
|
|
1189
|
+
if (!row)
|
|
1190
|
+
return;
|
|
1191
|
+
return this.rowToTag(row);
|
|
1192
|
+
}
|
|
1193
|
+
async getTagByName(name) {
|
|
1194
|
+
await this.initialize();
|
|
1195
|
+
const stmt = this.db.prepare("SELECT * FROM task_tag WHERE name = ?");
|
|
1196
|
+
const row = stmt.get(name);
|
|
1197
|
+
if (!row)
|
|
1198
|
+
return;
|
|
1199
|
+
return this.rowToTag(row);
|
|
1200
|
+
}
|
|
1201
|
+
async listTags(options) {
|
|
1202
|
+
await this.initialize();
|
|
1203
|
+
let sql = "SELECT * FROM task_tag";
|
|
1204
|
+
const params = [];
|
|
1205
|
+
const orderBy = options?.orderBy || "count";
|
|
1206
|
+
if (orderBy === "count") {
|
|
1207
|
+
sql += " ORDER BY task_count DESC";
|
|
1208
|
+
} else if (orderBy === "name") {
|
|
1209
|
+
sql += " ORDER BY name ASC";
|
|
1210
|
+
} else {
|
|
1211
|
+
sql += " ORDER BY created_at DESC";
|
|
1212
|
+
}
|
|
1213
|
+
if (options?.limit) {
|
|
1214
|
+
sql += " LIMIT ?";
|
|
1215
|
+
params.push(options.limit);
|
|
1216
|
+
}
|
|
1217
|
+
if (options?.offset) {
|
|
1218
|
+
sql += " OFFSET ?";
|
|
1219
|
+
params.push(options.offset);
|
|
1220
|
+
}
|
|
1221
|
+
const stmt = this.db.prepare(sql);
|
|
1222
|
+
const rows = stmt.all(...params);
|
|
1223
|
+
return rows.map((row) => this.rowToTag(row));
|
|
1224
|
+
}
|
|
1225
|
+
async searchTags(options) {
|
|
1226
|
+
await this.initialize();
|
|
1227
|
+
const sql = `
|
|
1228
|
+
SELECT * FROM task_tag
|
|
1229
|
+
WHERE name LIKE ?
|
|
1230
|
+
ORDER BY task_count DESC
|
|
1231
|
+
LIMIT ?
|
|
1232
|
+
`;
|
|
1233
|
+
const stmt = this.db.prepare(sql);
|
|
1234
|
+
const rows = stmt.all(`%${options.query}%`, options.limit || 20);
|
|
1235
|
+
return rows.map((row) => this.rowToTag(row));
|
|
1236
|
+
}
|
|
1237
|
+
async deleteTag(id) {
|
|
1238
|
+
await this.initialize();
|
|
1239
|
+
const stmt = this.db.prepare("DELETE FROM task_tag WHERE id = ?");
|
|
1240
|
+
const result = stmt.run(id);
|
|
1241
|
+
return result.changes > 0;
|
|
1242
|
+
}
|
|
1243
|
+
async addTagsToTask(taskId, tagIds) {
|
|
1244
|
+
await this.initialize();
|
|
1245
|
+
const now = Date.now();
|
|
1246
|
+
const stmt = this.db.prepare(`
|
|
1247
|
+
INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
|
|
1248
|
+
VALUES (?, ?, ?)
|
|
1249
|
+
`);
|
|
1250
|
+
for (const tagId of tagIds) {
|
|
1251
|
+
stmt.run(taskId, tagId, now);
|
|
1252
|
+
this.db.run(`
|
|
1253
|
+
UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
|
|
1254
|
+
`, tagId);
|
|
1255
|
+
}
|
|
1256
|
+
await this.syncTaskTagsJson(taskId);
|
|
1257
|
+
}
|
|
1258
|
+
async removeTagsFromTask(taskId, tagIds) {
|
|
1259
|
+
await this.initialize();
|
|
1260
|
+
const stmt = this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");
|
|
1261
|
+
for (const tagId of tagIds) {
|
|
1262
|
+
stmt.run(taskId, tagId);
|
|
1263
|
+
this.db.run(`
|
|
1264
|
+
UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
|
|
1265
|
+
`, tagId);
|
|
1266
|
+
}
|
|
1267
|
+
await this.syncTaskTagsJson(taskId);
|
|
1268
|
+
}
|
|
1269
|
+
async getTagsForTask(taskId) {
|
|
1270
|
+
await this.initialize();
|
|
1271
|
+
const sql = `
|
|
1272
|
+
SELECT t.* FROM task_tag t
|
|
1273
|
+
INNER JOIN task_tag_relation r ON t.id = r.tag_id
|
|
1274
|
+
WHERE r.task_id = ?
|
|
1275
|
+
ORDER BY t.name ASC
|
|
1276
|
+
`;
|
|
1277
|
+
const stmt = this.db.prepare(sql);
|
|
1278
|
+
const rows = stmt.all(taskId);
|
|
1279
|
+
return rows.map((row) => this.rowToTag(row));
|
|
1280
|
+
}
|
|
1281
|
+
async getTaskIdsByTags(tagNames) {
|
|
1282
|
+
await this.initialize();
|
|
1283
|
+
if (tagNames.length === 0)
|
|
1284
|
+
return [];
|
|
1285
|
+
const placeholders = tagNames.map(() => "?").join(", ");
|
|
1286
|
+
const sql = `
|
|
1287
|
+
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
1288
|
+
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
1289
|
+
WHERE t.name IN (${placeholders})
|
|
1290
|
+
`;
|
|
1291
|
+
const stmt = this.db.prepare(sql);
|
|
1292
|
+
const rows = stmt.all(...tagNames);
|
|
1293
|
+
return rows.map((row) => row.task_id);
|
|
1294
|
+
}
|
|
1295
|
+
async updateTaskTags(taskId, tagNames) {
|
|
1296
|
+
await this.initialize();
|
|
1297
|
+
const currentTags = await this.getTagsForTask(taskId);
|
|
1298
|
+
if (currentTags.length > 0) {
|
|
1299
|
+
await this.removeTagsFromTask(taskId, currentTags.map((t) => t.id));
|
|
1300
|
+
}
|
|
1301
|
+
const tagIds = [];
|
|
1302
|
+
for (const name of tagNames) {
|
|
1303
|
+
let tag = await this.getTagByName(name);
|
|
1304
|
+
if (!tag) {
|
|
1305
|
+
tag = await this.createTag(name);
|
|
1306
|
+
}
|
|
1307
|
+
tagIds.push(tag.id);
|
|
1308
|
+
}
|
|
1309
|
+
if (tagIds.length > 0) {
|
|
1310
|
+
await this.addTagsToTask(taskId, tagIds);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
async searchTasksByKeywords(keywords, options = {}) {
|
|
1314
|
+
await this.initialize();
|
|
1315
|
+
if (!keywords || keywords.length === 0) {
|
|
1316
|
+
return [];
|
|
1317
|
+
}
|
|
1318
|
+
const { limit = 20, excludeTaskId } = options;
|
|
1319
|
+
const tasks = new Map;
|
|
1320
|
+
let taskSql = "SELECT * FROM task WHERE 1=1";
|
|
1321
|
+
const taskParams = [];
|
|
1322
|
+
if (excludeTaskId) {
|
|
1323
|
+
taskSql += " AND id != ?";
|
|
1324
|
+
taskParams.push(excludeTaskId);
|
|
1325
|
+
}
|
|
1326
|
+
taskSql += " ORDER BY updated_at DESC LIMIT ?";
|
|
1327
|
+
taskParams.push(limit * 2);
|
|
1328
|
+
const taskRows = this.db.prepare(taskSql).all(...taskParams);
|
|
1329
|
+
for (const row of taskRows) {
|
|
1330
|
+
const task = this.rowToTask(row);
|
|
1331
|
+
let matchCount = 0;
|
|
1332
|
+
if (task.title) {
|
|
1333
|
+
const lowerTitle = task.title.toLowerCase();
|
|
1334
|
+
for (const keyword of keywords) {
|
|
1335
|
+
if (lowerTitle.includes(keyword.toLowerCase())) {
|
|
1336
|
+
matchCount++;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
if (task.tags && Array.isArray(task.tags)) {
|
|
1341
|
+
for (const keyword of keywords) {
|
|
1342
|
+
const lowerKeyword = keyword.toLowerCase();
|
|
1343
|
+
if (task.tags.some((tag) => tag.toLowerCase().includes(lowerKeyword))) {
|
|
1344
|
+
matchCount += 2;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
if (task.description) {
|
|
1349
|
+
const lowerDesc = task.description.toLowerCase();
|
|
1350
|
+
for (const keyword of keywords) {
|
|
1351
|
+
if (lowerDesc.includes(keyword.toLowerCase())) {
|
|
1352
|
+
matchCount++;
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
if (task.goals_and_expected_deliverables) {
|
|
1357
|
+
const lowerGoals = task.goals_and_expected_deliverables.toLowerCase();
|
|
1358
|
+
for (const keyword of keywords) {
|
|
1359
|
+
if (lowerGoals.includes(keyword.toLowerCase())) {
|
|
1360
|
+
matchCount++;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (matchCount > 0) {
|
|
1365
|
+
tasks.set(task.id, { task, matchCount });
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const allOps = this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();
|
|
1369
|
+
for (const opRow of allOps) {
|
|
1370
|
+
const opSql = `
|
|
1371
|
+
SELECT * FROM task_operation
|
|
1372
|
+
WHERE task_id = ?
|
|
1373
|
+
AND (action_title LIKE ? OR action_description LIKE ?)
|
|
1374
|
+
LIMIT 10
|
|
1375
|
+
`;
|
|
1376
|
+
for (const keyword of keywords) {
|
|
1377
|
+
const pattern = `%${keyword}%`;
|
|
1378
|
+
const ops = this.db.prepare(opSql).all(opRow.task_id, pattern, pattern);
|
|
1379
|
+
if (ops.length > 0) {
|
|
1380
|
+
const taskRow = this.db.prepare("SELECT * FROM task WHERE id = ?").get(opRow.task_id);
|
|
1381
|
+
if (taskRow) {
|
|
1382
|
+
const task = this.rowToTask(taskRow);
|
|
1383
|
+
if (excludeTaskId && task.id === excludeTaskId)
|
|
1384
|
+
continue;
|
|
1385
|
+
const existing = tasks.get(task.id);
|
|
1386
|
+
if (existing) {
|
|
1387
|
+
existing.matchCount += 2;
|
|
1388
|
+
} else {
|
|
1389
|
+
tasks.set(task.id, { task, matchCount: 2 });
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
const results = Array.from(tasks.values()).sort((a, b) => b.matchCount - a.matchCount).slice(0, limit).map((item) => item.task);
|
|
1396
|
+
return results;
|
|
1397
|
+
}
|
|
1398
|
+
async findSimilarTasksByKeywords(keywords, options = {}) {
|
|
1399
|
+
const mergedOptions = { ...options, limit: options.limit ?? 5 };
|
|
1400
|
+
return this.searchTasksByKeywords(keywords, mergedOptions);
|
|
1401
|
+
}
|
|
1402
|
+
async findSimilarTasks(taskId, limit = 5) {
|
|
1403
|
+
await this.initialize();
|
|
1404
|
+
const taskTags = await this.getTagsForTask(taskId);
|
|
1405
|
+
if (taskTags.length === 0) {
|
|
1406
|
+
return [];
|
|
1407
|
+
}
|
|
1408
|
+
const tagIds = taskTags.map((t) => t.id);
|
|
1409
|
+
const placeholders = tagIds.map(() => "?").join(", ");
|
|
1410
|
+
const sql = `
|
|
1411
|
+
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
1412
|
+
FROM task t
|
|
1413
|
+
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
1414
|
+
INNER JOIN task_tag_relation r2 ON t.id = r2.task_id
|
|
1415
|
+
WHERE r.tag_id IN (${placeholders})
|
|
1416
|
+
AND t.id != ?
|
|
1417
|
+
GROUP BY t.id
|
|
1418
|
+
ORDER BY match_count DESC, t.updated_at DESC
|
|
1419
|
+
LIMIT ?
|
|
1420
|
+
`;
|
|
1421
|
+
const stmt = this.db.prepare(sql);
|
|
1422
|
+
const rows = stmt.all(...tagIds, taskId, limit);
|
|
1423
|
+
return rows.map((row) => this.rowToTask(row));
|
|
1424
|
+
}
|
|
1425
|
+
async searchTasks(query, limit = 20) {
|
|
1426
|
+
await this.initialize();
|
|
1427
|
+
const sql = `
|
|
1428
|
+
SELECT * FROM task
|
|
1429
|
+
WHERE title LIKE ? OR description LIKE ?
|
|
1430
|
+
ORDER BY updated_at DESC
|
|
1431
|
+
LIMIT ?
|
|
1432
|
+
`;
|
|
1433
|
+
const stmt = this.db.prepare(sql);
|
|
1434
|
+
const rows = stmt.all(`%${query}%`, `%${query}%`, limit);
|
|
1435
|
+
return rows.map((row) => this.rowToTask(row));
|
|
1436
|
+
}
|
|
1437
|
+
rowToTag(row) {
|
|
1438
|
+
return {
|
|
1439
|
+
id: row.id,
|
|
1440
|
+
name: row.name,
|
|
1441
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
1442
|
+
taskCount: row.task_count
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
async syncTaskTagsJson(taskId) {
|
|
1446
|
+
const tags = await this.getTagsForTask(taskId);
|
|
1447
|
+
const tagNames = tags.map((t) => t.name);
|
|
1448
|
+
const stmt = this.db.prepare("UPDATE task SET tags = ? WHERE id = ?");
|
|
1449
|
+
stmt.run(tagNames.length > 0 ? JSON.stringify(tagNames) : null, taskId);
|
|
1450
|
+
this.tasksCache.delete(taskId);
|
|
1451
|
+
}
|
|
1452
|
+
async close() {
|
|
1453
|
+
if (this.db) {
|
|
1454
|
+
this.db.close();
|
|
1455
|
+
this.db = null;
|
|
1456
|
+
this.initialized = false;
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
export {
|
|
1461
|
+
getDefaultTaskDbPath,
|
|
1462
|
+
getDefaultDataDir,
|
|
1463
|
+
SQLiteTaskStore
|
|
1464
|
+
};
|