@ai-setting/roy-agent-core 1.4.12 → 1.4.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/packages/core/src/config/index.js +32 -0
  2. package/dist/packages/core/src/env/agent/index.js +24 -0
  3. package/dist/packages/core/src/env/commands/index.js +14 -0
  4. package/dist/packages/core/src/env/debug/formatters/index.js +11 -0
  5. package/dist/packages/core/src/env/debug/index.js +26 -0
  6. package/dist/packages/core/src/env/hook/index.js +29 -0
  7. package/dist/packages/core/src/env/index.js +81 -0
  8. package/dist/packages/core/src/env/llm/index.js +40 -0
  9. package/dist/packages/core/src/env/log-trace/index.js +83 -0
  10. package/dist/packages/core/src/env/mcp/index.js +39 -0
  11. package/dist/packages/core/src/env/mcp/tool/index.js +14 -0
  12. package/dist/packages/core/src/env/memory/built-in/index.js +11 -0
  13. package/dist/packages/core/src/env/memory/index.js +56 -0
  14. package/dist/packages/core/src/env/memory/plugin/index.js +36 -0
  15. package/dist/packages/core/src/env/prompt/index.js +20 -0
  16. package/dist/packages/core/src/env/session/index.js +25 -0
  17. package/dist/packages/core/src/env/session/storage/index.js +18 -0
  18. package/dist/packages/core/src/env/skill/index.js +34 -0
  19. package/dist/packages/core/src/env/skill/tool/index.js +9 -0
  20. package/dist/packages/core/src/env/task/delegate/index.js +18 -0
  21. package/dist/packages/core/src/env/task/hooks/index.js +7 -0
  22. package/dist/packages/core/src/env/task/index.js +30 -0
  23. package/dist/packages/core/src/env/task/plugins/index.js +23 -0
  24. package/dist/packages/core/src/env/task/storage/index.js +14 -0
  25. package/dist/packages/core/src/env/task/tools/index.js +17 -0
  26. package/dist/packages/core/src/env/task/tools/operation/index.js +15 -0
  27. package/dist/packages/core/src/env/tool/built-in/index.js +25 -0
  28. package/dist/packages/core/src/env/tool/index.js +39 -0
  29. package/dist/packages/core/src/env/workflow/decorators/index.js +27 -0
  30. package/dist/packages/core/src/env/workflow/engine/index.js +28 -0
  31. package/dist/packages/core/src/env/workflow/index.js +132 -0
  32. package/dist/packages/core/src/env/workflow/nodes/index.js +19 -0
  33. package/dist/packages/core/src/env/workflow/service/index.js +13 -0
  34. package/dist/packages/core/src/env/workflow/storage/index.js +27 -0
  35. package/dist/packages/core/src/env/workflow/tools/index.js +159 -0
  36. package/dist/packages/core/src/env/workflow/types/index.js +94 -0
  37. package/dist/packages/core/src/env/workflow/utils/index.js +637 -0
  38. package/dist/packages/core/src/index.js +398 -0
  39. package/dist/shared/@ai-setting/roy-agent-core-04fm8177.js +393 -0
  40. package/dist/shared/@ai-setting/roy-agent-core-04qgbjbe.js +172 -0
  41. package/dist/shared/@ai-setting/roy-agent-core-084qqd7t.js +11 -0
  42. package/dist/shared/@ai-setting/roy-agent-core-0gekht4e.js +1130 -0
  43. package/dist/shared/@ai-setting/roy-agent-core-0hdry23r.js +419 -0
  44. package/dist/shared/@ai-setting/roy-agent-core-0sgn3de4.js +102 -0
  45. package/dist/{env/task/tools/index.js → shared/@ai-setting/roy-agent-core-12x57kf1.js} +1 -59
  46. package/dist/shared/@ai-setting/roy-agent-core-1f3xrrm6.js +393 -0
  47. package/dist/shared/@ai-setting/roy-agent-core-1k28kg7h.js +368 -0
  48. package/dist/shared/@ai-setting/roy-agent-core-1z1zv5g8.js +258 -0
  49. package/dist/shared/@ai-setting/roy-agent-core-2hqxnaf3.js +851 -0
  50. package/dist/shared/@ai-setting/roy-agent-core-3dfq8awb.js +587 -0
  51. package/dist/shared/@ai-setting/roy-agent-core-3takar0s.js +93 -0
  52. package/dist/shared/@ai-setting/roy-agent-core-3tnb2005.js +117 -0
  53. package/dist/shared/@ai-setting/roy-agent-core-4vmcvkav.js +14 -0
  54. package/dist/shared/@ai-setting/roy-agent-core-4ws8atva.js +107 -0
  55. package/dist/{env/workflow/nodes/index.js → shared/@ai-setting/roy-agent-core-5fbp24se.js} +8 -55
  56. package/dist/shared/@ai-setting/roy-agent-core-5my94ywp.js +66 -0
  57. package/dist/shared/@ai-setting/roy-agent-core-6j0zcmwk.js +2146 -0
  58. package/dist/shared/@ai-setting/roy-agent-core-6w4pmxc7.js +266 -0
  59. package/dist/shared/@ai-setting/roy-agent-core-7vrk3add.js +10 -0
  60. package/dist/shared/@ai-setting/roy-agent-core-8dvbn7tw.js +64 -0
  61. package/dist/{env/memory/built-in/index.js → shared/@ai-setting/roy-agent-core-8mbmrwzs.js} +22 -76
  62. package/dist/shared/@ai-setting/roy-agent-core-8wzz66qe.js +620 -0
  63. package/dist/shared/@ai-setting/roy-agent-core-9ykq91jc.js +762 -0
  64. package/dist/shared/@ai-setting/roy-agent-core-dde19zke.js +1305 -0
  65. package/dist/shared/@ai-setting/roy-agent-core-f7g67gce.js +913 -0
  66. package/dist/{env/workflow/types/index.js → shared/@ai-setting/roy-agent-core-fq5mtxsy.js} +16 -154
  67. package/dist/{env/task/hooks/index.js → shared/@ai-setting/roy-agent-core-fs0mn2jk.js} +3 -18
  68. package/dist/{config/index.js → shared/@ai-setting/roy-agent-core-fvd9g6k8.js} +140 -605
  69. package/dist/shared/@ai-setting/roy-agent-core-gv1hrn3x.js +378 -0
  70. package/dist/{env/task/tools/operation/index.js → shared/@ai-setting/roy-agent-core-gy0wp5h7.js} +1 -58
  71. package/dist/shared/@ai-setting/roy-agent-core-hyza1gm7.js +15 -0
  72. package/dist/shared/@ai-setting/roy-agent-core-j8zx62zr.js +154 -0
  73. package/dist/shared/@ai-setting/roy-agent-core-jb2exr0d.js +442 -0
  74. package/dist/shared/@ai-setting/roy-agent-core-jv3b7v9w.js +57 -0
  75. package/dist/shared/@ai-setting/roy-agent-core-k1rxf9ya.js +513 -0
  76. package/dist/shared/@ai-setting/roy-agent-core-kydc9nwb.js +60 -0
  77. package/dist/shared/@ai-setting/roy-agent-core-m2x48hw6.js +97 -0
  78. package/dist/shared/@ai-setting/roy-agent-core-m6y668cc.js +377 -0
  79. package/dist/shared/@ai-setting/roy-agent-core-nczzf0ms.js +15 -0
  80. package/dist/shared/@ai-setting/roy-agent-core-nfj6knp5.js +36 -0
  81. package/dist/shared/@ai-setting/roy-agent-core-ntrp979d.js +204 -0
  82. package/dist/shared/@ai-setting/roy-agent-core-pd7g8z5v.js +1387 -0
  83. package/dist/shared/@ai-setting/roy-agent-core-pzk1syce.js +14 -0
  84. package/dist/shared/@ai-setting/roy-agent-core-q50tg9m2.js +862 -0
  85. package/dist/shared/@ai-setting/roy-agent-core-qg9tcaph.js +11 -0
  86. package/dist/shared/@ai-setting/roy-agent-core-qhyerewk.js +20 -0
  87. package/dist/shared/@ai-setting/roy-agent-core-qxybm159.js +82 -0
  88. package/dist/shared/@ai-setting/roy-agent-core-rh9dpkpw.js +549 -0
  89. package/dist/shared/@ai-setting/roy-agent-core-rr9p1g43.js +205 -0
  90. package/dist/{env/workflow/decorators/index.js → shared/@ai-setting/roy-agent-core-sbzvpfn7.js} +8 -173
  91. package/dist/shared/@ai-setting/roy-agent-core-t22nqt4d.js +788 -0
  92. package/dist/shared/@ai-setting/roy-agent-core-tkr5ynkh.js +200 -0
  93. package/dist/shared/@ai-setting/roy-agent-core-v4aabsf0.js +303 -0
  94. package/dist/{env/hook/index.js → shared/@ai-setting/roy-agent-core-w75rafhy.js} +3 -74
  95. package/dist/{env/debug/formatters/index.js → shared/@ai-setting/roy-agent-core-w76hqkmg.js} +11 -66
  96. package/dist/shared/@ai-setting/roy-agent-core-yfbgwes2.js +408 -0
  97. package/dist/shared/@ai-setting/roy-agent-core-yn761yve.js +299 -0
  98. package/dist/shared/@ai-setting/roy-agent-core-yrzmn4m1.js +492 -0
  99. package/dist/{env/workflow/service/index.js → shared/@ai-setting/roy-agent-core-yt8wdh2w.js} +1 -57
  100. package/package.json +3 -2
  101. package/dist/env/agent/index.js +0 -3035
  102. package/dist/env/commands/index.js +0 -1685
  103. package/dist/env/debug/index.js +0 -2300
  104. package/dist/env/index.js +0 -12591
  105. package/dist/env/llm/index.js +0 -2736
  106. package/dist/env/log-trace/index.js +0 -1779
  107. package/dist/env/mcp/index.js +0 -2173
  108. package/dist/env/mcp/tool/index.js +0 -1149
  109. package/dist/env/memory/index.js +0 -2171
  110. package/dist/env/memory/plugin/index.js +0 -1263
  111. package/dist/env/prompt/index.js +0 -2107
  112. package/dist/env/session/index.js +0 -3594
  113. package/dist/env/session/storage/index.js +0 -2049
  114. package/dist/env/skill/index.js +0 -1635
  115. package/dist/env/skill/tool/index.js +0 -114
  116. package/dist/env/task/delegate/index.js +0 -1844
  117. package/dist/env/task/index.js +0 -3578
  118. package/dist/env/task/plugins/index.js +0 -1626
  119. package/dist/env/task/storage/index.js +0 -1464
  120. package/dist/env/tool/built-in/index.js +0 -1151
  121. package/dist/env/tool/index.js +0 -2284
  122. package/dist/env/workflow/engine/index.js +0 -4391
  123. package/dist/env/workflow/index.js +0 -6214
  124. package/dist/env/workflow/storage/index.js +0 -1236
  125. package/dist/env/workflow/tools/index.js +0 -1081
  126. package/dist/env/workflow/utils/index.js +0 -1631
  127. package/dist/index.js +0 -22778
@@ -1,3594 +0,0 @@
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/search-query-parser.ts
1007
- var exports_search_query_parser = {};
1008
- __export(exports_search_query_parser, {
1009
- parseSearchQuery: () => parseSearchQuery,
1010
- matchesQuery: () => matchesQuery
1011
- });
1012
- function parseSearchQuery(query) {
1013
- const result = {
1014
- required: [],
1015
- excluded: [],
1016
- phrases: []
1017
- };
1018
- if (!query || !query.trim()) {
1019
- return result;
1020
- }
1021
- const phraseRegex = /"([^"]+)"/g;
1022
- let match;
1023
- while ((match = phraseRegex.exec(query)) !== null) {
1024
- result.phrases.push(match[1].toLowerCase());
1025
- }
1026
- query = query.replace(phraseRegex, "");
1027
- query = query.replace(/\s+/g, " ").trim();
1028
- if (!query) {
1029
- return result;
1030
- }
1031
- const parts = [];
1032
- let remaining = query;
1033
- const singleOpRegex = /\s+(AND|OR|NOT)\s+/gi;
1034
- let opMatch;
1035
- while ((opMatch = singleOpRegex.exec(remaining)) !== null) {
1036
- const op = opMatch[1].toUpperCase();
1037
- const beforeText = remaining.slice(0, opMatch.index).trim();
1038
- if (beforeText) {
1039
- parts.push({ text: beforeText, operator: undefined });
1040
- }
1041
- parts.push({ text: op, operator: op });
1042
- remaining = remaining.slice(opMatch.index + opMatch[0].length);
1043
- singleOpRegex.lastIndex = 0;
1044
- }
1045
- if (remaining.trim()) {
1046
- parts.push({ text: remaining.trim(), operator: undefined });
1047
- }
1048
- let currentOperator = "AND";
1049
- for (const part of parts) {
1050
- if (part.operator) {
1051
- currentOperator = part.operator;
1052
- } else {
1053
- const wordRegex = /[\w\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]+/gu;
1054
- const words = part.text.match(wordRegex) || [];
1055
- for (const word of words) {
1056
- const lowerWord = word.toLowerCase();
1057
- if (lowerWord === "and" || lowerWord === "or" || lowerWord === "not") {
1058
- currentOperator = lowerWord.toUpperCase();
1059
- continue;
1060
- }
1061
- if (currentOperator === "NOT") {
1062
- if (!result.excluded.includes(lowerWord)) {
1063
- result.excluded.push(lowerWord);
1064
- }
1065
- } else {
1066
- if (!result.required.includes(lowerWord)) {
1067
- result.required.push(lowerWord);
1068
- }
1069
- }
1070
- currentOperator = "AND";
1071
- }
1072
- }
1073
- }
1074
- return result;
1075
- }
1076
- function matchesQuery(content, query) {
1077
- if (!content) {
1078
- return query.required.length === 0 && query.phrases.length === 0;
1079
- }
1080
- const lowerContent = content.toLowerCase();
1081
- for (const term of query.excluded) {
1082
- if (lowerContent.includes(term.toLowerCase())) {
1083
- return false;
1084
- }
1085
- }
1086
- for (const phrase of query.phrases) {
1087
- if (!lowerContent.includes(phrase)) {
1088
- return false;
1089
- }
1090
- }
1091
- if (query.required.length > 0) {
1092
- for (const term of query.required) {
1093
- if (!lowerContent.includes(term)) {
1094
- return false;
1095
- }
1096
- }
1097
- }
1098
- return true;
1099
- }
1100
-
1101
- // packages/core/src/env/hook/types.ts
1102
- function createHook(meta, fn) {
1103
- return {
1104
- ...meta,
1105
- execute: fn
1106
- };
1107
- }
1108
- function createPriorityHook(name, fn, priority) {
1109
- return createHook({ name, priority }, fn);
1110
- }
1111
- // packages/core/src/env/hook/hook-manager.ts
1112
- class HookManager {
1113
- _hooks = new Map;
1114
- componentName;
1115
- componentVersion;
1116
- defaultPriority;
1117
- constructor(options = {}) {
1118
- this.componentName = options.componentName ?? "unknown";
1119
- this.componentVersion = options.componentVersion ?? "0.0.0";
1120
- this.defaultPriority = options.defaultPriority ?? 0;
1121
- }
1122
- register(hookPoint, hook) {
1123
- const hooks = this.getOrCreateHooks(hookPoint);
1124
- hooks.push(hook);
1125
- }
1126
- registerMany(hookPoint, hooks) {
1127
- const hookList = this.getOrCreateHooks(hookPoint);
1128
- hookList.push(...hooks);
1129
- }
1130
- unregister(hookPoint, name) {
1131
- const hooks = this._hooks.get(hookPoint);
1132
- if (!hooks)
1133
- return false;
1134
- const index = hooks.findIndex((h) => h.name === name);
1135
- if (index === -1)
1136
- return false;
1137
- hooks.splice(index, 1);
1138
- return true;
1139
- }
1140
- unregisterAll(hookPoint) {
1141
- this._hooks.delete(hookPoint);
1142
- }
1143
- async execute(hookPoint, data, metadata = {}) {
1144
- const hooks = this._hooks.get(hookPoint);
1145
- if (!hooks || hooks.length === 0)
1146
- return;
1147
- const sortedHooks = this.sortHooks(hooks);
1148
- const ctx = this.createContext(hookPoint, data, metadata, "before");
1149
- for (const hook of sortedHooks) {
1150
- await this.safeExecute(hook, ctx);
1151
- }
1152
- }
1153
- async executeAndCollect(hookPoint, data, metadata = {}) {
1154
- const hooks = this._hooks.get(hookPoint);
1155
- if (!hooks || hooks.length === 0)
1156
- return [];
1157
- const sortedHooks = this.sortHooks(hooks);
1158
- const ctx = this.createContext(hookPoint, data, metadata, "before");
1159
- const results = [];
1160
- for (const hook of sortedHooks) {
1161
- const result = await this.safeExecuteAndReturn(hook, ctx);
1162
- if (result !== undefined) {
1163
- results.push(result);
1164
- }
1165
- }
1166
- return results;
1167
- }
1168
- count(hookPoint) {
1169
- return this._hooks.get(hookPoint)?.length ?? 0;
1170
- }
1171
- clear() {
1172
- this._hooks.clear();
1173
- }
1174
- getHookPoints() {
1175
- return Array.from(this._hooks.keys());
1176
- }
1177
- hasHooks(hookPoint) {
1178
- return this.count(hookPoint) > 0;
1179
- }
1180
- setComponentInfo(name, version) {
1181
- this.componentName = name;
1182
- this.componentVersion = version;
1183
- }
1184
- get hooks() {
1185
- return this._hooks;
1186
- }
1187
- async executeWithIntervention(hookPoint, data, metadata = {}) {
1188
- const hooks = this._hooks.get(hookPoint);
1189
- if (!hooks || hooks.length === 0) {
1190
- return { stopped: false, results: [] };
1191
- }
1192
- const sortedHooks = this.sortHooks(hooks);
1193
- const ctx = this.createContext(hookPoint, data, metadata, "before");
1194
- const results = [];
1195
- let stopped = false;
1196
- let action;
1197
- for (const hook of sortedHooks) {
1198
- if (stopped)
1199
- break;
1200
- const result = await this.safeExecuteAndReturn(hook, ctx);
1201
- results.push(result);
1202
- if (result && typeof result === "object" && "stopped" in result) {
1203
- const hookResult = result;
1204
- if (hookResult.stopped) {
1205
- stopped = true;
1206
- action = hookResult.action;
1207
- }
1208
- }
1209
- }
1210
- return { stopped, action, results };
1211
- }
1212
- getOrCreateHooks(hookPoint) {
1213
- let hooks = this._hooks.get(hookPoint);
1214
- if (!hooks) {
1215
- hooks = [];
1216
- this._hooks.set(hookPoint, hooks);
1217
- }
1218
- return hooks;
1219
- }
1220
- sortHooks(hooks) {
1221
- return [...hooks].sort((a, b) => {
1222
- const priorityA = a.priority ?? this.defaultPriority;
1223
- const priorityB = b.priority ?? this.defaultPriority;
1224
- return priorityA - priorityB;
1225
- });
1226
- }
1227
- createContext(hookPoint, data, metadata, phase) {
1228
- return {
1229
- component: {
1230
- name: this.componentName,
1231
- version: this.componentVersion
1232
- },
1233
- data,
1234
- metadata,
1235
- phase,
1236
- hookPoint
1237
- };
1238
- }
1239
- async safeExecute(hook, ctx) {
1240
- try {
1241
- await hook.execute(ctx);
1242
- } catch (error) {
1243
- console.error(`Hook "${hook.name}" failed:`, error);
1244
- }
1245
- }
1246
- async safeExecuteAndReturn(hook, ctx) {
1247
- try {
1248
- return await hook.execute(ctx);
1249
- } catch (error) {
1250
- console.error(`Hook "${hook.name}" failed:`, error);
1251
- return;
1252
- }
1253
- }
1254
- }
1255
- // packages/core/src/env/hook/global-hook-manager.ts
1256
- var globalHookManager = new HookManager;
1257
- var AgentHookPoints = {
1258
- BEFORE_START: "agent:before.start",
1259
- BEFORE_LLM: "agent:before.llm",
1260
- AFTER_LLM: "agent:after.llm",
1261
- BEFORE_TOOL: "agent:before.tool",
1262
- AFTER_TOOL: "agent:after.tool",
1263
- ON_ITERATION: "agent:on.iteration",
1264
- ON_THRESHOLD: "agent:on.threshold",
1265
- AFTER_COMPLETE: "agent:after.complete",
1266
- ON_ERROR: "agent:on.error"
1267
- };
1268
- var LLMHookPoints = {
1269
- BEFORE_INVOKE: "llm:before.invoke",
1270
- AFTER_INVOKE: "llm:after.invoke",
1271
- ON_STREAM: "llm:on.stream"
1272
- };
1273
- var ToolHookPoints = {
1274
- BEFORE_EXECUTE: "tool:before.execute",
1275
- AFTER_EXECUTE: "tool:after.execute",
1276
- BEFORE_REGISTER: "tool:before.register",
1277
- AFTER_REGISTER: "tool:after.register",
1278
- ON_ERROR: "tool:on.error"
1279
- };
1280
- var hookPointAliases = {
1281
- "before.tool": "tool:before.execute",
1282
- "after.tool": "tool:after.execute",
1283
- "llm.before-invoke": "llm:before.invoke",
1284
- "llm.after-invoke": "llm:after.invoke",
1285
- "llm.stream": "llm:on.stream"
1286
- };
1287
- function setupAliasHooks() {
1288
- const originalRegister = globalHookManager.register.bind(globalHookManager);
1289
- globalHookManager.register = function(hookPoint, hook) {
1290
- originalRegister(hookPoint, hook);
1291
- const alias = hookPointAliases[hookPoint];
1292
- if (alias) {
1293
- originalRegister(alias, hook);
1294
- }
1295
- };
1296
- }
1297
- setupAliasHooks();
1298
- async function executeAgentHook(hookPoint, data, metadata = {}) {
1299
- await globalHookManager.execute(hookPoint, data, metadata);
1300
- }
1301
- async function executeAgentHookWithIntervention(hookPoint, data, metadata = {}) {
1302
- return globalHookManager.executeWithIntervention(hookPoint, data, metadata);
1303
- }
1304
- async function executeLLMHook(hookPoint, data, metadata = {}) {
1305
- await globalHookManager.execute(hookPoint, data, metadata);
1306
- }
1307
- async function executeToolHook(hookPoint, data, metadata = {}) {
1308
- await globalHookManager.execute(hookPoint, data, metadata);
1309
- }
1310
- // packages/core/src/env/session/session-message-converter.ts
1311
- init_decorator();
1312
- import { randomUUID } from "crypto";
1313
- var DEFAULT_REASONING_BUDGET_TOKENS = 1e4;
1314
-
1315
- class SessionMessageConverter {
1316
- toModelMessage(msg) {
1317
- if (msg.role === "assistant") {
1318
- const content = [];
1319
- for (const part of msg.parts || []) {
1320
- if (part.type === "text") {
1321
- const textPart = part;
1322
- content.push({
1323
- type: "text",
1324
- text: textPart.content,
1325
- ...textPart.synthetic !== undefined && { synthetic: textPart.synthetic }
1326
- });
1327
- } else if (part.type === "reasoning") {
1328
- const reasoningPart = part;
1329
- content.push({
1330
- type: "reasoning",
1331
- text: reasoningPart.content,
1332
- reasoningType: reasoningPart.reasoningType
1333
- });
1334
- } else if (part.type === "tool-call") {
1335
- const toolPart = part;
1336
- let parsedArgs = {};
1337
- if (typeof toolPart.arguments === "string") {
1338
- try {
1339
- parsedArgs = JSON.parse(toolPart.arguments);
1340
- } catch {
1341
- parsedArgs = { _raw: toolPart.arguments };
1342
- }
1343
- } else {
1344
- parsedArgs = toolPart.arguments;
1345
- }
1346
- content.push({
1347
- type: "tool-call",
1348
- toolCallId: toolPart.toolCallId,
1349
- toolName: toolPart.toolName,
1350
- input: parsedArgs
1351
- });
1352
- } else if (part.type === "file") {
1353
- const filePart = part;
1354
- content.push({
1355
- type: "file",
1356
- url: filePart.url,
1357
- mimeType: filePart.mime,
1358
- filename: filePart.filename
1359
- });
1360
- } else if (part.type === "tool-result" || part.type === "checkpoint") {} else {
1361
- console.debug(`[session-message-converter] Skipping unsupported part type in assistant: ${part.type}`);
1362
- }
1363
- }
1364
- if (content.length === 0 && msg.content) {
1365
- return { role: "assistant", content: msg.content };
1366
- }
1367
- return { role: "assistant", content };
1368
- }
1369
- if (msg.role === "tool") {
1370
- const toolPart = msg.parts?.find((p) => p.type === "tool-result");
1371
- return {
1372
- role: "tool",
1373
- content: [{
1374
- type: "tool-result",
1375
- toolCallId: toolPart?.toolCallId || "",
1376
- toolName: toolPart?.toolName || "",
1377
- output: toolPart?.output || msg.content || ""
1378
- }]
1379
- };
1380
- }
1381
- return {
1382
- role: msg.role,
1383
- content: msg.content || ""
1384
- };
1385
- }
1386
- fromModelMessage(aiMsg, options) {
1387
- const parts = [];
1388
- const content = typeof aiMsg.content === "string" || Array.isArray(aiMsg.content) ? aiMsg.content : "";
1389
- let hasToolCallPart = false;
1390
- let hasToolResultPart = false;
1391
- if (typeof content === "string") {
1392
- parts.push({ type: "text", content });
1393
- } else if (Array.isArray(content)) {
1394
- for (const part of content) {
1395
- const p = part;
1396
- if (p.type === "text") {
1397
- parts.push({ type: "text", content: p.text || "" });
1398
- } else if (p.type === "reasoning") {
1399
- parts.push({
1400
- type: "reasoning",
1401
- content: p.text || "",
1402
- reasoningType: p.reasoningType,
1403
- state: "completed"
1404
- });
1405
- } else if (p.type === "tool-call") {
1406
- hasToolCallPart = true;
1407
- parts.push({
1408
- type: "tool-call",
1409
- toolCallId: p.toolCallId,
1410
- toolName: p.toolName,
1411
- arguments: p.input,
1412
- state: "pending"
1413
- });
1414
- } else if (p.type === "tool-result") {
1415
- hasToolResultPart = true;
1416
- parts.push({
1417
- type: "tool-result",
1418
- toolCallId: p.toolCallId,
1419
- toolName: p.toolName,
1420
- output: typeof p.output === "string" ? p.output : JSON.stringify(p.output),
1421
- state: "completed"
1422
- });
1423
- } else if (p.type === "file") {
1424
- parts.push({
1425
- type: "file",
1426
- mime: p.mimeType || "application/octet-stream",
1427
- url: p.url,
1428
- filename: p.filename
1429
- });
1430
- } else {
1431
- console.debug(`[session-message-converter] Unknown part type: ${p.type}`);
1432
- }
1433
- }
1434
- }
1435
- let metadataType;
1436
- if (aiMsg.role === "assistant" && hasToolCallPart) {
1437
- metadataType = "tool_call";
1438
- } else if (aiMsg.role === "tool") {
1439
- metadataType = "tool_result";
1440
- }
1441
- const result = {
1442
- id: options?.messageID || `msg_${randomUUID()}`,
1443
- sessionID: options?.sessionID || "",
1444
- role: aiMsg.role,
1445
- timestamp: Date.now(),
1446
- parts,
1447
- content: typeof content === "string" ? content : ""
1448
- };
1449
- if (metadataType) {
1450
- result.metadata = { type: metadataType };
1451
- }
1452
- return result;
1453
- }
1454
- sessionToHistory(messages) {
1455
- return messages.filter((msg) => !msg.metadata?.isArchived && !msg.isArchived).map((msg) => this.toModelMessage(msg));
1456
- }
1457
- extractProviderOptions(msg) {
1458
- const options = {};
1459
- const reasoningParts = msg.parts?.filter((p) => p.type === "reasoning");
1460
- if (reasoningParts && reasoningParts.length > 0) {
1461
- const firstReasoning = reasoningParts[0];
1462
- if (firstReasoning.reasoningType) {
1463
- options.openai = {
1464
- thinking: {
1465
- type: firstReasoning.reasoningType === "effort" ? "extended" : "core"
1466
- }
1467
- };
1468
- if (firstReasoning.reasoningType === "effort") {
1469
- const budgetTokens = firstReasoning.metadata?.tokenCount || DEFAULT_REASONING_BUDGET_TOKENS;
1470
- options.anthropic = {
1471
- thinking: {
1472
- type: "enabled",
1473
- budgetTokens
1474
- }
1475
- };
1476
- }
1477
- }
1478
- }
1479
- return options;
1480
- }
1481
- migrateMessage(oldMsg) {
1482
- if (oldMsg.parts && oldMsg.parts.length > 0) {
1483
- const firstPart = oldMsg.parts[0];
1484
- if (firstPart && typeof firstPart.type === "string" && firstPart.type.length > 0) {
1485
- return {
1486
- ...oldMsg,
1487
- content: oldMsg.content || ""
1488
- };
1489
- }
1490
- }
1491
- return {
1492
- ...oldMsg,
1493
- content: oldMsg.content || "",
1494
- parts: oldMsg.content ? [{ type: "text", content: oldMsg.content }] : []
1495
- };
1496
- }
1497
- }
1498
- __legacyDecorateClassTS([
1499
- TracedAs("session-message-converter.toModelMessage", { recordParams: true, recordResult: true, log: true })
1500
- ], SessionMessageConverter.prototype, "toModelMessage", null);
1501
- __legacyDecorateClassTS([
1502
- TracedAs("session-message-converter.fromModelMessage", { recordParams: true, recordResult: true, log: true })
1503
- ], SessionMessageConverter.prototype, "fromModelMessage", null);
1504
-
1505
- // packages/core/src/env/session/storage/memory.ts
1506
- import { randomUUID as randomUUID2 } from "crypto";
1507
- function generateSessionId() {
1508
- return `session_${randomUUID2()}`;
1509
- }
1510
- function generateMessageId() {
1511
- return `msg_${randomUUID2()}`;
1512
- }
1513
-
1514
- class MemorySessionStore {
1515
- sessions = new Map;
1516
- messages = new Map;
1517
- checkpoints = new Map;
1518
- messageConverter = new SessionMessageConverter;
1519
- async create(options) {
1520
- const now = Date.now();
1521
- const session = {
1522
- id: options.id ?? generateSessionId(),
1523
- title: options.title ?? "Session",
1524
- directory: options.directory ?? "/tmp",
1525
- parentID: options.parentID,
1526
- createdAt: now,
1527
- updatedAt: now,
1528
- messageCount: 0,
1529
- metadata: {
1530
- ...options.metadata,
1531
- messageCount: 0,
1532
- checkpoints: { checkpoints: [] }
1533
- }
1534
- };
1535
- if (this.sessions.has(session.id)) {
1536
- throw new Error(`Session with ID '${session.id}' already exists`);
1537
- }
1538
- this.sessions.set(session.id, session);
1539
- this.messages.set(session.id, []);
1540
- this.checkpoints.set(session.id, []);
1541
- return session;
1542
- }
1543
- async get(id) {
1544
- return this.sessions.get(id);
1545
- }
1546
- async list(options) {
1547
- let sessions = Array.from(this.sessions.values());
1548
- if (options?.filter?.metadata) {
1549
- sessions = sessions.filter((s) => {
1550
- for (const [key, value] of Object.entries(options.filter.metadata)) {
1551
- if (s.metadata?.[key] !== value)
1552
- return false;
1553
- }
1554
- return true;
1555
- });
1556
- }
1557
- if (options?.filter?.startTime) {
1558
- sessions = sessions.filter((s) => s.createdAt >= options.filter.startTime);
1559
- }
1560
- if (options?.filter?.endTime) {
1561
- sessions = sessions.filter((s) => s.createdAt <= options.filter.endTime);
1562
- }
1563
- const sortField = options?.sort?.field ?? "updatedAt";
1564
- const sortOrder = options?.sort?.order ?? "desc";
1565
- sessions.sort((a, b) => {
1566
- let aVal;
1567
- let bVal;
1568
- if (sortField === "title") {
1569
- aVal = a.title;
1570
- bVal = b.title;
1571
- } else if (sortField === "createdAt") {
1572
- aVal = a.createdAt;
1573
- bVal = b.createdAt;
1574
- } else {
1575
- aVal = a.updatedAt;
1576
- bVal = b.updatedAt;
1577
- }
1578
- if (aVal < bVal)
1579
- return sortOrder === "asc" ? -1 : 1;
1580
- if (aVal > bVal)
1581
- return sortOrder === "asc" ? 1 : -1;
1582
- return 0;
1583
- });
1584
- const offset = options?.offset ?? 0;
1585
- const limit = options?.limit ?? 100;
1586
- return sessions.slice(offset, offset + limit);
1587
- }
1588
- async update(id, updates) {
1589
- const session = this.sessions.get(id);
1590
- if (!session)
1591
- return false;
1592
- if (updates.title !== undefined) {
1593
- session.title = updates.title;
1594
- }
1595
- if (updates.metadata !== undefined) {
1596
- session.metadata = { ...session.metadata, ...updates.metadata };
1597
- }
1598
- session.updatedAt = Date.now();
1599
- return true;
1600
- }
1601
- async delete(id) {
1602
- const deleted = this.sessions.delete(id);
1603
- if (deleted) {
1604
- this.messages.delete(id);
1605
- this.checkpoints.delete(id);
1606
- }
1607
- return deleted;
1608
- }
1609
- async getCount() {
1610
- return this.sessions.size;
1611
- }
1612
- async addMessage(sessionId, message) {
1613
- const session = this.sessions.get(sessionId);
1614
- if (!session) {
1615
- throw new Error(`Session not found: ${sessionId}`);
1616
- }
1617
- const rawMessage = {
1618
- sessionID: sessionId,
1619
- role: message.role,
1620
- content: message.content,
1621
- parts: message.parts,
1622
- metadata: message.metadata
1623
- };
1624
- const msg = this.messageConverter.migrateMessage(rawMessage);
1625
- msg.id = generateMessageId();
1626
- msg.timestamp = Date.now();
1627
- const sessionMessages = this.messages.get(sessionId) ?? [];
1628
- sessionMessages.push(msg);
1629
- this.messages.set(sessionId, sessionMessages);
1630
- session.messageCount = sessionMessages.filter((m) => !m.isArchived).length;
1631
- session.metadata = {
1632
- ...session.metadata,
1633
- messageCount: session.messageCount
1634
- };
1635
- session.updatedAt = Date.now();
1636
- return msg.id;
1637
- }
1638
- async getMessages(sessionId, offset = 0, limit = 50, options) {
1639
- let messages = this.messages.get(sessionId) ?? [];
1640
- if (!options?.includeArchived) {
1641
- messages = messages.filter((m) => !m.isArchived);
1642
- }
1643
- if (options?.fromCheckpointId) {
1644
- const checkpoint = await this.getCheckpoint(sessionId, options.fromCheckpointId);
1645
- if (checkpoint) {
1646
- const checkpointIndex = messages.findIndex((m) => m.metadata?.checkpointId === options.fromCheckpointId);
1647
- if (checkpointIndex >= 0) {
1648
- messages = messages.slice(checkpointIndex);
1649
- }
1650
- }
1651
- }
1652
- let actualOffset = offset;
1653
- if (offset < 0) {
1654
- const total = messages.length;
1655
- actualOffset = Math.max(0, total + offset * limit);
1656
- }
1657
- if (options?.reverse) {
1658
- messages = messages.reverse();
1659
- }
1660
- return messages.slice(actualOffset, actualOffset + limit);
1661
- }
1662
- async getMessageCount(sessionId, includeArchived = false) {
1663
- const messages = this.messages.get(sessionId) ?? [];
1664
- if (includeArchived) {
1665
- return messages.length;
1666
- }
1667
- return messages.filter((m) => !m.isArchived).length;
1668
- }
1669
- async getMessageIndexes(sessionId, role) {
1670
- const messages = this.messages.get(sessionId) ?? [];
1671
- const indexes = [];
1672
- messages.filter((m) => !m.isArchived).forEach((msg, filteredIdx) => {
1673
- if (msg.role === role) {
1674
- indexes.push(filteredIdx);
1675
- }
1676
- });
1677
- return indexes;
1678
- }
1679
- async saveCheckpoint(sessionId, checkpoint) {
1680
- const session = this.sessions.get(sessionId);
1681
- if (!session) {
1682
- throw new Error(`Session not found: ${sessionId}`);
1683
- }
1684
- const cps = this.checkpoints.get(sessionId) ?? [];
1685
- cps.push(checkpoint);
1686
- this.checkpoints.set(sessionId, cps);
1687
- const meta = session.metadata || {};
1688
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
1689
- checkpointsMeta.checkpoints.push({
1690
- id: checkpoint.id,
1691
- messageIndex: checkpoint.messageIndex,
1692
- title: checkpoint.title,
1693
- createdAt: checkpoint.createdAt,
1694
- type: checkpoint.type
1695
- });
1696
- checkpointsMeta.latestCheckpointId = checkpoint.id;
1697
- meta.checkpoints = checkpointsMeta;
1698
- if (!meta.checkpointDetails) {
1699
- meta.checkpointDetails = {};
1700
- }
1701
- meta.checkpointDetails[checkpoint.id] = checkpoint;
1702
- session.metadata = meta;
1703
- session.updatedAt = Date.now();
1704
- }
1705
- async getCheckpoints(sessionId) {
1706
- return this.checkpoints.get(sessionId) ?? [];
1707
- }
1708
- async getCheckpoint(sessionId, checkpointId) {
1709
- const cps = this.checkpoints.get(sessionId) ?? [];
1710
- return cps.find((cp) => cp.id === checkpointId);
1711
- }
1712
- async deleteCheckpoint(sessionId, checkpointId) {
1713
- const session = this.sessions.get(sessionId);
1714
- if (!session)
1715
- return false;
1716
- const cps = this.checkpoints.get(sessionId) ?? [];
1717
- const index = cps.findIndex((cp) => cp.id === checkpointId);
1718
- if (index === -1)
1719
- return false;
1720
- cps.splice(index, 1);
1721
- this.checkpoints.set(sessionId, cps);
1722
- const messages = this.messages.get(sessionId) ?? [];
1723
- for (const msg of messages) {
1724
- if (msg.checkpointId === checkpointId) {
1725
- msg.isArchived = false;
1726
- msg.archivedAt = undefined;
1727
- msg.checkpointId = undefined;
1728
- }
1729
- }
1730
- const meta = session.metadata || {};
1731
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
1732
- checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
1733
- checkpointsMeta.latestCheckpointId = cps[cps.length - 1]?.id;
1734
- if (meta.checkpointDetails) {
1735
- delete meta.checkpointDetails[checkpointId];
1736
- }
1737
- session.metadata = meta;
1738
- session.messageCount = messages.filter((m) => !m.isArchived).length;
1739
- session.updatedAt = Date.now();
1740
- return true;
1741
- }
1742
- async archiveMessages(sessionId, checkpointId, beforeIndex) {
1743
- const session = this.sessions.get(sessionId);
1744
- if (!session)
1745
- return 0;
1746
- const messages = this.messages.get(sessionId) ?? [];
1747
- let archivedCount = 0;
1748
- for (let i = 0;i < beforeIndex; i++) {
1749
- if (!messages[i].isArchived) {
1750
- messages[i].isArchived = true;
1751
- messages[i].archivedAt = Date.now();
1752
- messages[i].checkpointId = checkpointId;
1753
- archivedCount++;
1754
- }
1755
- }
1756
- session.messageCount = messages.filter((m) => !m.isArchived).length;
1757
- session.updatedAt = Date.now();
1758
- return archivedCount;
1759
- }
1760
- async getActiveMessages(sessionId, offset = 0, limit = 50) {
1761
- const messages = this.messages.get(sessionId) ?? [];
1762
- const activeMessages = messages.filter((m) => !m.isArchived);
1763
- return activeMessages.slice(offset, offset + limit);
1764
- }
1765
- async searchMessages(options) {
1766
- const matches = [];
1767
- const {
1768
- query,
1769
- sessionId,
1770
- limit = 10,
1771
- beforeTime,
1772
- afterTime,
1773
- includeArchived = false
1774
- } = options;
1775
- let sessionsToSearch;
1776
- if (sessionId) {
1777
- const session = await this.get(sessionId);
1778
- sessionsToSearch = session ? [session] : [];
1779
- } else {
1780
- sessionsToSearch = Array.from(this.sessions.values());
1781
- }
1782
- const queryTerms = this.parseQuery(query);
1783
- for (const session of sessionsToSearch) {
1784
- if (beforeTime && session.updatedAt > beforeTime)
1785
- continue;
1786
- if (afterTime && session.updatedAt < afterTime)
1787
- continue;
1788
- let messages = this.messages.get(session.id) ?? [];
1789
- if (!includeArchived) {
1790
- messages = messages.filter((m) => !m.isArchived);
1791
- }
1792
- for (const msg of messages) {
1793
- if (beforeTime && msg.timestamp > beforeTime)
1794
- continue;
1795
- if (afterTime && msg.timestamp < afterTime)
1796
- continue;
1797
- const content = msg.content.toLowerCase();
1798
- let matchesQuery = true;
1799
- for (const term of queryTerms.required) {
1800
- if (!content.includes(term.toLowerCase())) {
1801
- matchesQuery = false;
1802
- break;
1803
- }
1804
- }
1805
- for (const term of queryTerms.excluded) {
1806
- if (content.includes(term.toLowerCase())) {
1807
- matchesQuery = false;
1808
- break;
1809
- }
1810
- }
1811
- if (matchesQuery) {
1812
- matches.push({
1813
- messageId: msg.id,
1814
- sessionId: session.id,
1815
- role: msg.role,
1816
- content: msg.content,
1817
- timestamp: msg.timestamp
1818
- });
1819
- if (matches.length >= limit) {
1820
- return matches;
1821
- }
1822
- }
1823
- }
1824
- }
1825
- return matches;
1826
- }
1827
- parseQuery(query) {
1828
- const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
1829
- const required = [];
1830
- const excluded = [];
1831
- for (const term of terms) {
1832
- if (term.startsWith("-") || term.startsWith("NOT ")) {
1833
- excluded.push(term.replace(/^-|^NOT /i, ""));
1834
- } else {
1835
- required.push(term);
1836
- }
1837
- }
1838
- return { required, excluded };
1839
- }
1840
- async close() {
1841
- this.sessions.clear();
1842
- this.messages.clear();
1843
- this.checkpoints.clear();
1844
- }
1845
- }
1846
- // packages/core/src/env/session/storage/sqlite.ts
1847
- import { join as join2 } from "path";
1848
- import { randomUUID as randomUUID3 } from "crypto";
1849
- function generateSessionId2() {
1850
- return `session_${randomUUID3()}`;
1851
- }
1852
- function generateMessageId2() {
1853
- return `msg_${randomUUID3()}`;
1854
- }
1855
- function getDefaultDataDir() {
1856
- const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1857
- return join2(home, ".local", "share");
1858
- }
1859
- function getDefaultSessionDbPath() {
1860
- return join2(getDefaultDataDir(), "roy-agent", "sessions.db");
1861
- }
1862
-
1863
- class SQLiteSessionStore {
1864
- db = null;
1865
- dbPath;
1866
- initialized = false;
1867
- sessionsCache = new Map;
1868
- messagesCache = new Map;
1869
- checkpointsCache = new Map;
1870
- messageConverter = new SessionMessageConverter;
1871
- constructor(dbPath) {
1872
- this.dbPath = dbPath || getDefaultSessionDbPath();
1873
- }
1874
- async initialize() {
1875
- if (this.initialized)
1876
- return;
1877
- const { Database } = __require("bun:sqlite");
1878
- if (this.dbPath !== ":memory:") {
1879
- const fs = __require("fs");
1880
- const path = __require("path");
1881
- const dir = path.dirname(this.dbPath);
1882
- if (!fs.existsSync(dir)) {
1883
- fs.mkdirSync(dir, { recursive: true });
1884
- }
1885
- }
1886
- this.db = new Database(this.dbPath);
1887
- this.db.run(`
1888
- CREATE TABLE IF NOT EXISTS session (
1889
- id TEXT PRIMARY KEY,
1890
- title TEXT NOT NULL,
1891
- directory TEXT NOT NULL,
1892
- parent_id TEXT,
1893
- created_at INTEGER NOT NULL,
1894
- updated_at INTEGER NOT NULL,
1895
- message_count INTEGER DEFAULT 0,
1896
- metadata TEXT
1897
- )
1898
- `);
1899
- this.db.run(`
1900
- CREATE TABLE IF NOT EXISTS message (
1901
- id TEXT PRIMARY KEY,
1902
- session_id TEXT NOT NULL,
1903
- role TEXT NOT NULL,
1904
- content TEXT NOT NULL,
1905
- timestamp INTEGER NOT NULL,
1906
- parts TEXT,
1907
- is_archived INTEGER DEFAULT 0,
1908
- archived_at INTEGER,
1909
- checkpoint_id TEXT,
1910
- metadata TEXT,
1911
- FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE
1912
- )
1913
- `);
1914
- this.db.run("CREATE INDEX IF NOT EXISTS idx_message_session ON message(session_id)");
1915
- this.db.run("CREATE INDEX IF NOT EXISTS idx_message_checkpoint ON message(checkpoint_id)");
1916
- this.initialized = true;
1917
- }
1918
- async create(options) {
1919
- await this.initialize();
1920
- const now = Date.now();
1921
- const session = {
1922
- id: options.id ?? generateSessionId2(),
1923
- title: options.title ?? "Session",
1924
- directory: options.directory ?? "/tmp",
1925
- parentID: options.parentID,
1926
- createdAt: now,
1927
- updatedAt: now,
1928
- messageCount: 0,
1929
- metadata: {
1930
- ...options.metadata,
1931
- messageCount: 0,
1932
- checkpoints: { checkpoints: [] }
1933
- }
1934
- };
1935
- const existing = this.db.prepare("SELECT id FROM session WHERE id = ?").get(session.id);
1936
- if (existing) {
1937
- throw new Error(`Session with ID '${session.id}' already exists`);
1938
- }
1939
- const stmt = this.db.prepare(`
1940
- INSERT INTO session (id, title, directory, parent_id, created_at, updated_at, message_count, metadata)
1941
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1942
- `);
1943
- stmt.run(session.id, session.title, session.directory, session.parentID || null, session.createdAt, session.updatedAt, session.messageCount, JSON.stringify(session.metadata));
1944
- this.sessionsCache.set(session.id, session);
1945
- this.messagesCache.set(session.id, []);
1946
- this.checkpointsCache.set(session.id, []);
1947
- return session;
1948
- }
1949
- async get(id) {
1950
- await this.initialize();
1951
- const cached = this.sessionsCache.get(id);
1952
- if (cached)
1953
- return cached;
1954
- const row = this.db.prepare("SELECT * FROM session WHERE id = ?").get(id);
1955
- if (!row)
1956
- return;
1957
- const session = this.rowToSession(row);
1958
- this.sessionsCache.set(session.id, session);
1959
- return session;
1960
- }
1961
- async list(options) {
1962
- await this.initialize();
1963
- let sql = "SELECT * FROM session";
1964
- const params = [];
1965
- const conditions = [];
1966
- if (options?.filter?.metadata) {
1967
- for (const [key, value] of Object.entries(options.filter.metadata)) {
1968
- conditions.push(`json_extract(metadata, '$.${key}') = ?`);
1969
- params.push(JSON.stringify(value));
1970
- }
1971
- }
1972
- if (options?.filter?.startTime) {
1973
- conditions.push("created_at >= ?");
1974
- params.push(options.filter.startTime);
1975
- }
1976
- if (options?.filter?.endTime) {
1977
- conditions.push("created_at <= ?");
1978
- params.push(options.filter.endTime);
1979
- }
1980
- if (conditions.length > 0) {
1981
- sql += " WHERE " + conditions.join(" AND ");
1982
- }
1983
- const sortField = options?.sort?.field ?? "updatedAt";
1984
- const sortOrder = options?.sort?.order ?? "desc";
1985
- const orderColumn = sortField === "title" ? "title" : sortField === "createdAt" ? "created_at" : "updated_at";
1986
- sql += ` ORDER BY ${orderColumn} ${sortOrder.toUpperCase()}`;
1987
- const offset = options?.offset ?? 0;
1988
- const limit = options?.limit ?? 100;
1989
- sql += " LIMIT ? OFFSET ?";
1990
- params.push(limit, offset);
1991
- const rows = this.db.prepare(sql).all(...params);
1992
- return rows.map((row) => this.rowToSession(row));
1993
- }
1994
- async getCount() {
1995
- await this.initialize();
1996
- const result = this.db.prepare("SELECT COUNT(*) as count FROM session").get();
1997
- return result.count;
1998
- }
1999
- async update(id, updates) {
2000
- await this.initialize();
2001
- const session = await this.get(id);
2002
- if (!session)
2003
- return false;
2004
- if (updates.title !== undefined) {
2005
- session.title = updates.title;
2006
- }
2007
- if (updates.metadata !== undefined) {
2008
- session.metadata = { ...session.metadata, ...updates.metadata };
2009
- }
2010
- session.updatedAt = Date.now();
2011
- const stmt = this.db.prepare(`
2012
- UPDATE session
2013
- SET title = ?, metadata = ?, updated_at = ?
2014
- WHERE id = ?
2015
- `);
2016
- stmt.run(session.title, JSON.stringify(session.metadata), session.updatedAt, id);
2017
- this.sessionsCache.set(id, session);
2018
- return true;
2019
- }
2020
- async delete(id) {
2021
- await this.initialize();
2022
- const session = await this.get(id);
2023
- if (!session)
2024
- return false;
2025
- this.db.prepare("DELETE FROM session WHERE id = ?").run(id);
2026
- this.sessionsCache.delete(id);
2027
- this.messagesCache.delete(id);
2028
- this.checkpointsCache.delete(id);
2029
- return true;
2030
- }
2031
- async addMessage(sessionId, message) {
2032
- await this.initialize();
2033
- const session = await this.get(sessionId);
2034
- if (!session) {
2035
- throw new Error(`Session not found: ${sessionId}`);
2036
- }
2037
- const now = Date.now();
2038
- const msg = {
2039
- id: generateMessageId2(),
2040
- sessionID: sessionId,
2041
- role: message.role,
2042
- content: message.content,
2043
- timestamp: now,
2044
- parts: message.parts,
2045
- metadata: message.metadata
2046
- };
2047
- const stmt = this.db.prepare(`
2048
- INSERT INTO message (id, session_id, role, content, timestamp, parts, metadata)
2049
- VALUES (?, ?, ?, ?, ?, ?, ?)
2050
- `);
2051
- 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);
2052
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
2053
- session.messageCount = countResult?.count || 0;
2054
- session.updatedAt = now;
2055
- session.metadata = {
2056
- ...session.metadata,
2057
- messageCount: session.messageCount
2058
- };
2059
- this.db.prepare(`
2060
- UPDATE session SET message_count = ?, metadata = ?, updated_at = ? WHERE id = ?
2061
- `).run(session.messageCount, JSON.stringify(session.metadata), session.updatedAt, sessionId);
2062
- const messages = this.messagesCache.get(sessionId) ?? [];
2063
- messages.push(msg);
2064
- this.messagesCache.set(sessionId, messages);
2065
- this.sessionsCache.set(sessionId, session);
2066
- return msg.id;
2067
- }
2068
- async getMessages(sessionId, offset = 0, limit = 50, options) {
2069
- await this.initialize();
2070
- let sql = "SELECT * FROM message WHERE session_id = ?";
2071
- let countSql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
2072
- const params = [sessionId];
2073
- const countParams = [sessionId];
2074
- if (!options?.includeArchived) {
2075
- sql += " AND is_archived = 0";
2076
- countSql += " AND is_archived = 0";
2077
- }
2078
- if (options?.fromCheckpointId) {
2079
- sql += " AND timestamp >= (SELECT MIN(timestamp) FROM message WHERE session_id = ? AND json_extract(metadata, '$.checkpointId') = ?)";
2080
- params.push(sessionId, options.fromCheckpointId);
2081
- }
2082
- let actualOffset = offset;
2083
- if (offset < 0) {
2084
- const totalResult = this.db.prepare(countSql).get(...countParams);
2085
- const total = totalResult?.count || 0;
2086
- actualOffset = Math.max(0, total + offset * limit);
2087
- }
2088
- if (options?.reverse) {
2089
- sql += " ORDER BY timestamp DESC";
2090
- } else {
2091
- sql += " ORDER BY timestamp ASC";
2092
- }
2093
- sql += " LIMIT ? OFFSET ?";
2094
- params.push(limit, actualOffset);
2095
- const rows = this.db.prepare(sql).all(...params);
2096
- return rows.map((row) => this.rowToMessage(row));
2097
- }
2098
- async getMessageCount(sessionId, includeArchived = false) {
2099
- await this.initialize();
2100
- let sql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
2101
- if (!includeArchived) {
2102
- sql += " AND is_archived = 0";
2103
- }
2104
- const result = this.db.prepare(sql).get(sessionId);
2105
- return result?.count || 0;
2106
- }
2107
- async getMessageIndexes(sessionId, role) {
2108
- await this.initialize();
2109
- const sql = `
2110
- SELECT idx FROM (
2111
- SELECT
2112
- ROW_NUMBER() OVER (ORDER BY timestamp ASC) - 1 as idx,
2113
- role
2114
- FROM message
2115
- WHERE session_id = ? AND is_archived = 0
2116
- ) ranked
2117
- WHERE role = ?
2118
- `;
2119
- const rows = this.db.prepare(sql).all(sessionId, role);
2120
- return rows.map((row) => row.idx);
2121
- }
2122
- async saveCheckpoint(sessionId, checkpoint) {
2123
- await this.initialize();
2124
- const session = await this.get(sessionId);
2125
- if (!session) {
2126
- throw new Error(`Session not found: ${sessionId}`);
2127
- }
2128
- const cps = this.checkpointsCache.get(sessionId) ?? [];
2129
- cps.push(checkpoint);
2130
- this.checkpointsCache.set(sessionId, cps);
2131
- const meta = session.metadata || {};
2132
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
2133
- checkpointsMeta.checkpoints.push({
2134
- id: checkpoint.id,
2135
- messageIndex: checkpoint.messageIndex,
2136
- title: checkpoint.title,
2137
- createdAt: checkpoint.createdAt,
2138
- type: checkpoint.type
2139
- });
2140
- checkpointsMeta.latestCheckpointId = checkpoint.id;
2141
- meta.checkpoints = checkpointsMeta;
2142
- if (!meta.checkpointDetails) {
2143
- meta.checkpointDetails = {};
2144
- }
2145
- meta.checkpointDetails[checkpoint.id] = checkpoint;
2146
- session.metadata = meta;
2147
- session.updatedAt = Date.now();
2148
- const stmt = this.db.prepare(`
2149
- UPDATE session SET metadata = ?, updated_at = ? WHERE id = ?
2150
- `);
2151
- stmt.run(JSON.stringify(session.metadata), session.updatedAt, sessionId);
2152
- this.sessionsCache.set(sessionId, session);
2153
- }
2154
- async getCheckpoints(sessionId) {
2155
- await this.initialize();
2156
- const session = await this.get(sessionId);
2157
- if (!session)
2158
- return [];
2159
- const meta = session.metadata;
2160
- const checkpointDetails = meta?.checkpointDetails;
2161
- if (!checkpointDetails)
2162
- return [];
2163
- return Object.values(checkpointDetails);
2164
- }
2165
- async getCheckpoint(sessionId, checkpointId) {
2166
- await this.initialize();
2167
- const checkpoints = await this.getCheckpoints(sessionId);
2168
- return checkpoints.find((cp) => cp.id === checkpointId);
2169
- }
2170
- async deleteCheckpoint(sessionId, checkpointId) {
2171
- await this.initialize();
2172
- const session = await this.get(sessionId);
2173
- if (!session)
2174
- return false;
2175
- const checkpoints = this.checkpointsCache.get(sessionId) ?? [];
2176
- const index = checkpoints.findIndex((cp) => cp.id === checkpointId);
2177
- if (index === -1)
2178
- return false;
2179
- checkpoints.splice(index, 1);
2180
- this.checkpointsCache.set(sessionId, checkpoints);
2181
- this.db.prepare(`
2182
- UPDATE message SET is_archived = 0, archived_at = NULL, checkpoint_id = NULL
2183
- WHERE session_id = ? AND checkpoint_id = ?
2184
- `).run(sessionId, checkpointId);
2185
- const meta = session.metadata || {};
2186
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
2187
- checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
2188
- checkpointsMeta.latestCheckpointId = checkpoints[checkpoints.length - 1]?.id;
2189
- if (meta.checkpointDetails) {
2190
- delete meta.checkpointDetails[checkpointId];
2191
- }
2192
- session.metadata = meta;
2193
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
2194
- session.messageCount = countResult?.count || 0;
2195
- session.updatedAt = Date.now();
2196
- this.db.prepare(`
2197
- UPDATE session SET metadata = ?, message_count = ?, updated_at = ? WHERE id = ?
2198
- `).run(JSON.stringify(session.metadata), session.messageCount, session.updatedAt, sessionId);
2199
- this.sessionsCache.set(sessionId, session);
2200
- return true;
2201
- }
2202
- async archiveMessages(sessionId, checkpointId, beforeIndex) {
2203
- await this.initialize();
2204
- const session = await this.get(sessionId);
2205
- if (!session)
2206
- return 0;
2207
- const now = Date.now();
2208
- const result = this.db.prepare(`
2209
- UPDATE message
2210
- SET is_archived = 1, archived_at = ?, checkpoint_id = ?
2211
- WHERE session_id = ? AND id IN (
2212
- SELECT id FROM message WHERE session_id = ? AND is_archived = 0
2213
- ORDER BY timestamp ASC LIMIT ?
2214
- )
2215
- `).run(now, checkpointId, sessionId, sessionId, beforeIndex);
2216
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
2217
- session.messageCount = countResult?.count || 0;
2218
- session.updatedAt = now;
2219
- this.db.prepare(`
2220
- UPDATE session SET message_count = ?, updated_at = ? WHERE id = ?
2221
- `).run(session.messageCount, session.updatedAt, sessionId);
2222
- this.sessionsCache.set(sessionId, session);
2223
- this.messagesCache.delete(sessionId);
2224
- return result.changes;
2225
- }
2226
- async getActiveMessages(sessionId, offset = 0, limit = 50) {
2227
- return this.getMessages(sessionId, offset, limit, { includeArchived: false });
2228
- }
2229
- async searchMessages(options) {
2230
- await this.initialize();
2231
- const matches = [];
2232
- const {
2233
- query,
2234
- sessionId,
2235
- limit = 10,
2236
- beforeTime,
2237
- afterTime,
2238
- includeArchived = false
2239
- } = options;
2240
- let sql = "SELECT * FROM message WHERE 1=1";
2241
- const params = [];
2242
- if (sessionId) {
2243
- sql += " AND session_id = ?";
2244
- params.push(sessionId);
2245
- }
2246
- if (!includeArchived) {
2247
- sql += " AND is_archived = 0";
2248
- }
2249
- if (beforeTime) {
2250
- sql += " AND timestamp <= ?";
2251
- params.push(beforeTime);
2252
- }
2253
- if (afterTime) {
2254
- sql += " AND timestamp >= ?";
2255
- params.push(afterTime);
2256
- }
2257
- sql += " ORDER BY timestamp DESC";
2258
- sql += " LIMIT ?";
2259
- params.push(limit * 10);
2260
- const rows = this.db.prepare(sql).all(...params);
2261
- const queryTerms = this.parseQuery(query);
2262
- const lowerQuery = query.toLowerCase();
2263
- for (const row of rows) {
2264
- const content = row.content.toLowerCase();
2265
- let matchesQuery = true;
2266
- for (const term of queryTerms.excluded) {
2267
- if (content.includes(term.toLowerCase())) {
2268
- matchesQuery = false;
2269
- break;
2270
- }
2271
- }
2272
- if (matchesQuery && queryTerms.required.length > 0) {
2273
- for (const term of queryTerms.required) {
2274
- if (!content.includes(term.toLowerCase())) {
2275
- matchesQuery = false;
2276
- break;
2277
- }
2278
- }
2279
- }
2280
- if (!matchesQuery && lowerQuery && content.includes(lowerQuery)) {
2281
- matchesQuery = true;
2282
- }
2283
- if (matchesQuery) {
2284
- matches.push({
2285
- messageId: row.id,
2286
- sessionId: row.session_id,
2287
- role: row.role,
2288
- content: row.content,
2289
- timestamp: row.timestamp
2290
- });
2291
- if (matches.length >= limit)
2292
- break;
2293
- }
2294
- }
2295
- return matches;
2296
- }
2297
- parseQuery(query) {
2298
- const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
2299
- const required = [];
2300
- const excluded = [];
2301
- for (const term of terms) {
2302
- if (term.startsWith("-") || term.toUpperCase().startsWith("NOT ")) {
2303
- excluded.push(term.replace(/^-|^NOT /i, ""));
2304
- } else {
2305
- required.push(term);
2306
- }
2307
- }
2308
- return { required, excluded };
2309
- }
2310
- async close() {
2311
- if (this.db) {
2312
- this.db.close();
2313
- this.db = null;
2314
- }
2315
- this.sessionsCache.clear();
2316
- this.messagesCache.clear();
2317
- this.checkpointsCache.clear();
2318
- this.initialized = false;
2319
- }
2320
- rowToSession(row) {
2321
- return {
2322
- id: row.id,
2323
- title: row.title,
2324
- directory: row.directory,
2325
- parentID: row.parent_id,
2326
- createdAt: row.created_at,
2327
- updatedAt: row.updated_at,
2328
- messageCount: row.message_count,
2329
- metadata: row.metadata ? JSON.parse(row.metadata) : undefined
2330
- };
2331
- }
2332
- rowToMessage(row) {
2333
- const rawMessage = {
2334
- id: row.id,
2335
- sessionID: row.session_id,
2336
- role: row.role,
2337
- content: row.content,
2338
- timestamp: row.timestamp,
2339
- parts: row.parts ? JSON.parse(row.parts) : undefined,
2340
- isArchived: row.is_archived === 1,
2341
- archivedAt: row.archived_at || undefined,
2342
- checkpointId: row.checkpoint_id || undefined,
2343
- metadata: row.metadata ? JSON.parse(row.metadata) : undefined
2344
- };
2345
- return this.messageConverter.migrateMessage(rawMessage);
2346
- }
2347
- }
2348
- // packages/core/src/env/component.ts
2349
- class BaseComponent {
2350
- _status = "created";
2351
- _enabled = true;
2352
- env;
2353
- hookManager;
2354
- constructor() {
2355
- this.hookManager = new HookManager;
2356
- }
2357
- getStatus() {
2358
- return this._status;
2359
- }
2360
- getConfig() {
2361
- return {
2362
- name: this.name,
2363
- version: this.version,
2364
- enabled: this._enabled,
2365
- env: this.env
2366
- };
2367
- }
2368
- isEnvInitialized() {
2369
- return this._status !== "created";
2370
- }
2371
- setStatus(status) {
2372
- this._status = status;
2373
- }
2374
- getEnv() {
2375
- return this.env;
2376
- }
2377
- async init(config) {
2378
- if (config?.env) {
2379
- this.env = config.env;
2380
- }
2381
- this.setStatus("initializing");
2382
- try {
2383
- if (config?.name)
2384
- Object.defineProperty(this, "name", { value: config.name, writable: false });
2385
- if (config?.version)
2386
- Object.defineProperty(this, "version", { value: config.version, writable: false });
2387
- } catch {}
2388
- if (config?.enabled !== undefined)
2389
- this._enabled = config.enabled;
2390
- this.hookManager.setComponentInfo(this.name, this.version);
2391
- await this.onInit();
2392
- this.setStatus("running");
2393
- }
2394
- async start() {
2395
- if (this._started)
2396
- return;
2397
- this._started = true;
2398
- await this.onStart();
2399
- this.setStatus("running");
2400
- }
2401
- async stop() {
2402
- this.setStatus("stopping");
2403
- this.hookManager.clear();
2404
- await this.onStop();
2405
- this.setStatus("stopped");
2406
- }
2407
- async onInit() {}
2408
- async onStart() {}
2409
- async onStop() {}
2410
- registerHook(hookPoint, hook) {
2411
- this.hookManager.register(hookPoint, hook);
2412
- }
2413
- addHook(hookPoint, name, fn, priority) {
2414
- this.hookManager.register(hookPoint, createHook({ name, priority }, fn));
2415
- }
2416
- removeHook(hookPoint, name) {
2417
- return this.hookManager.unregister(hookPoint, name);
2418
- }
2419
- async executeHooks(hookPoint, data, metadata) {
2420
- await this.hookManager.execute(hookPoint, data, metadata);
2421
- }
2422
- getConfigComponent() {
2423
- return this.env?.getComponent("config");
2424
- }
2425
- getRuntimeConfig(key, defaultValue) {
2426
- const configComponent = this.getConfigComponent();
2427
- if (configComponent) {
2428
- const value = configComponent.get(key);
2429
- if (value !== undefined) {
2430
- return value;
2431
- }
2432
- }
2433
- return defaultValue;
2434
- }
2435
- }
2436
-
2437
- // packages/core/src/env/session/session-component.ts
2438
- init_logger();
2439
-
2440
- // packages/core/src/config/env-key.ts
2441
- function toEnvKey(key, prefix) {
2442
- let keyNormalized = key.replace(/[.-]/g, "_");
2443
- keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/_+/g, "_").toUpperCase();
2444
- if (prefix) {
2445
- const separator = prefix.endsWith("_") ? "" : "_";
2446
- return `${prefix}${separator}${keyNormalized}`;
2447
- }
2448
- return keyNormalized;
2449
- }
2450
- function fromEnvKey(envKey, prefix) {
2451
- if (!prefix) {
2452
- return envKey;
2453
- }
2454
- if (envKey.startsWith(prefix)) {
2455
- const afterPrefix = envKey.slice(prefix.length);
2456
- if (afterPrefix.startsWith("_")) {
2457
- return afterPrefix.slice(1);
2458
- }
2459
- return afterPrefix;
2460
- }
2461
- return envKey;
2462
- }
2463
- function envKeyToConfigKey(envKey, prefix, componentName) {
2464
- const prefixUpper = prefix.toUpperCase();
2465
- if (!envKey.startsWith(prefixUpper)) {
2466
- return;
2467
- }
2468
- const componentUpperNormalized = componentName.replace(/-/g, "_").toUpperCase();
2469
- let keyPart = envKey.slice(prefixUpper.length);
2470
- if (keyPart.startsWith("_")) {
2471
- keyPart = keyPart.slice(1);
2472
- }
2473
- if (!keyPart) {
2474
- return;
2475
- }
2476
- const firstUnderscore = keyPart.indexOf("_");
2477
- let restPart;
2478
- if (firstUnderscore === -1) {
2479
- restPart = keyPart;
2480
- } else {
2481
- const firstPart = keyPart.slice(0, firstUnderscore);
2482
- const remaining = keyPart.slice(firstUnderscore + 1);
2483
- if (firstPart === componentUpperNormalized) {
2484
- restPart = remaining;
2485
- } else {
2486
- restPart = keyPart;
2487
- }
2488
- }
2489
- if (!restPart) {
2490
- return;
2491
- }
2492
- const restPartConverted = restPart.replace(/_/g, ".");
2493
- return `${componentName}.${restPartConverted.toLowerCase()}`;
2494
- }
2495
-
2496
- // packages/core/src/env/session/session-component.ts
2497
- init_decorator();
2498
-
2499
- // packages/core/src/env/agent/summary-agent.ts
2500
- init_logger();
2501
- init_decorator();
2502
- var logger = createLogger("agent:summary");
2503
-
2504
- class SummaryAgent {
2505
- promptComponent;
2506
- llmComponent;
2507
- config;
2508
- constructor(promptComponent, llmComponent, config) {
2509
- this.promptComponent = promptComponent;
2510
- this.llmComponent = llmComponent;
2511
- this.config = {
2512
- type: "summary",
2513
- promptName: "session/compact",
2514
- maxIterations: 1,
2515
- model: undefined,
2516
- ...config
2517
- };
2518
- }
2519
- async generateCompactHint(options) {
2520
- const { messages, sessionContext } = options;
2521
- logger.info("[SummaryAgent] Generating compact hint for session");
2522
- const formattedMessages = this.formatMessages(messages);
2523
- const systemPrompt = this.getHintGenerationSystemPrompt();
2524
- const userPrompt = this.buildHintGenerationUserPrompt(formattedMessages, sessionContext);
2525
- let response;
2526
- try {
2527
- response = await this.llmComponent.invoke({
2528
- messages: [
2529
- { role: "system", content: systemPrompt },
2530
- { role: "user", content: userPrompt }
2531
- ],
2532
- skipThresholdCheck: true
2533
- });
2534
- } catch (error) {
2535
- logger.error(`[SummaryAgent] Hint generation LLM invoke failed: ${error}`);
2536
- throw new Error(`LLM invoke failed: ${error}`);
2537
- }
2538
- const responseContent = response.output?.content || response.content || "";
2539
- const hint = this.parseHintResponse(responseContent);
2540
- logger.info("[SummaryAgent] Compact hint generated", { hint: hint.substring(0, 100) });
2541
- return {
2542
- hint,
2543
- rawResponse: responseContent
2544
- };
2545
- }
2546
- async run(options) {
2547
- const { messages, userContext, outputFormat, scenarioHint } = options;
2548
- logger.info("[SummaryAgent] Starting checkpoint generation", {
2549
- hasScenarioHint: !!scenarioHint
2550
- });
2551
- const formattedMessages = this.formatMessages(messages);
2552
- const systemPrompt = this.getSystemPrompt(scenarioHint);
2553
- const userPrompt = this.buildUserPrompt(formattedMessages, userContext);
2554
- let response;
2555
- try {
2556
- response = await this.llmComponent.invoke({
2557
- messages: [
2558
- { role: "system", content: systemPrompt },
2559
- { role: "user", content: userPrompt }
2560
- ],
2561
- model: this.config.model,
2562
- skipThresholdCheck: true
2563
- });
2564
- } catch (error) {
2565
- logger.error(`[SummaryAgent] LLM invoke failed: ${error}`);
2566
- throw new Error(`LLM invoke failed: ${error}`);
2567
- }
2568
- const responseContent = response.output?.content || response.content || "";
2569
- if (outputFormat === "json") {
2570
- const result = this.parseJsonResponse(responseContent);
2571
- logger.info(`[SummaryAgent] Checkpoint generated: "${result.title}"`);
2572
- return {
2573
- title: result.title || "Untitled Checkpoint",
2574
- processKeyPoints: result.processKeyPoints || [],
2575
- currentState: result.currentState || "",
2576
- nextSteps: result.nextSteps || [],
2577
- userIntents: result.userIntents || [],
2578
- rawResponse: responseContent
2579
- };
2580
- }
2581
- throw new Error(`Unsupported output format: ${outputFormat}`);
2582
- }
2583
- getSystemPrompt(scenarioHint) {
2584
- let prompt = `You are a professional session analyst assistant. Your task is to extract key information from a conversation and generate a structured checkpoint.
2585
-
2586
- A checkpoint captures the progress and state of a session at a point in time. It should contain:
2587
-
2588
- 1. **Process Key Points**: The key steps, discoveries, or decisions made during this part of the conversation
2589
- 2. **Current State**: The current progress and status at the end of the conversation
2590
- 3. **Next Steps**: Follow-up items and what needs to be done next
2591
- 4. **User Intents**: The underlying goals and intentions of the user (what they want to accomplish)
2592
-
2593
- Be concise and accurate. Avoid redundancy. Each section should be appropriately sized - not too long.`;
2594
- if (scenarioHint && scenarioHint.trim()) {
2595
- prompt += `
2596
-
2597
- ## Scenario Context
2598
-
2599
- ${scenarioHint.trim()}`;
2600
- }
2601
- return prompt;
2602
- }
2603
- getHintGenerationSystemPrompt() {
2604
- return `You are a compact guidance prompt engineer. Your task is to analyze a conversation and generate a "compact guidance prompt" that will instruct the checkpoint generator on what information to extract and preserve during session compression.
2605
-
2606
- **Purpose**: The guidance prompt will be used by the checkpoint generator to understand:
2607
- 1. What work is currently in progress
2608
- 2. What progress has been made
2609
- 3. What information MUST be preserved during compression (this is critical for task continuation)
2610
- 4. What information should be the focus of extraction
2611
-
2612
- **Key Principle**: The preserved information should enable seamless task continuation. If critical details are lost during compression, the user will have to re-explain context when continuing this work later.
2613
-
2614
- **Output Format**: A structured guidance prompt (3-4 sentences) covering:
2615
- 1. Current work type and what the user is trying to accomplish
2616
- 2. Current progress and key achievements
2617
- 3. CRITICAL information that MUST be preserved (decisions, findings, remaining issues)
2618
- 4. What the checkpoint generator should focus on when extracting information
2619
-
2620
- **Example good outputs**:
2621
- 1. "Bug investigation: User is debugging LSP diagnostics not updating after file edits. Progress: identified root cause (getDiagnostics needs to read latest file content and trigger didChange notification), implemented fix, CI verified. CRITICAL to preserve: the fix implementation details (file path, code changes), that 2 agent-node-integration tests still fail due to test assertion timing issue (expects 'running' but completes in ~78ms) - this is unrelated to LSP work. Focus extraction on: root cause analysis, fix implementation, known remaining test issues."
2622
- 2. "Feature development: User is implementing JWT authentication for auth-service. Progress: designed auth flow, implemented token refresh logic, middleware partially done. CRITICAL to preserve: auth flow decisions (token storage, refresh strategy), completed middleware components, modules pending implementation. Focus extraction on: architectural decisions, completed components, pending work."
2623
- 3. "Refactoring: User is migrating data layer to repository pattern. Progress: migrated UserRepository and OrderRepository, 3 more pending. CRITICAL to preserve: pattern decisions (interface definitions, dependency injection approach), completed repositories, modules pending migration. Focus extraction on: pattern implementation details, completed vs pending modules."`;
2624
- }
2625
- buildHintGenerationUserPrompt(messages, sessionContext) {
2626
- let prompt = `Analyze the following conversation and generate a compact guidance prompt for checkpoint generation.
2627
-
2628
- ## Your Task
2629
- Generate a structured guidance prompt (3-4 sentences) that will help the checkpoint generator understand:
2630
- 1. What work is currently in progress
2631
- 2. What progress has been made
2632
- 3. What information MUST be preserved during compression (critical for task continuation)
2633
- 4. What the checkpoint generator should focus on when extracting information
2634
-
2635
- `;
2636
- if (sessionContext) {
2637
- const ctxLines = ["## Session Context"];
2638
- if (sessionContext.activeTaskTitle) {
2639
- ctxLines.push(`- Active Task: ${sessionContext.activeTaskTitle}`);
2640
- }
2641
- if (sessionContext.workingDirectory) {
2642
- ctxLines.push(`- Working Directory: ${sessionContext.workingDirectory}`);
2643
- }
2644
- if (sessionContext.recentActions && sessionContext.recentActions.length > 0) {
2645
- ctxLines.push(`- Recent Actions: ${sessionContext.recentActions.slice(-3).join(" \u2192 ")}`);
2646
- }
2647
- if (ctxLines.length > 1) {
2648
- prompt += ctxLines.join(`
2649
- `) + `
2650
-
2651
- `;
2652
- }
2653
- }
2654
- prompt += `## Conversation to Analyze
2655
-
2656
- ${messages}
2657
-
2658
- `;
2659
- prompt += `---
2660
-
2661
- `;
2662
- prompt += `## Output Format
2663
-
2664
- `;
2665
- prompt += `Generate a structured guidance prompt covering:
2666
- `;
2667
- prompt += `1. Current work type and what the user is trying to accomplish
2668
- `;
2669
- prompt += `2. Current progress and key achievements
2670
- `;
2671
- prompt += `3. CRITICAL information that MUST be preserved (decisions, findings, remaining issues)
2672
- `;
2673
- prompt += `4. What to focus on during extraction
2674
-
2675
- `;
2676
- prompt += `Wrap the output in a JSON object with a \`guidance_prompt\` key:
2677
-
2678
- `;
2679
- prompt += `\`\`\`json
2680
- `;
2681
- prompt += `{
2682
- `;
2683
- prompt += ` "guidance_prompt": "Work type: ... Progress: ... CRITICAL to preserve: ... Focus extraction on: ..."
2684
- `;
2685
- prompt += `}
2686
- `;
2687
- prompt += `\`\`\`
2688
-
2689
- `;
2690
- prompt += `IMPORTANT: The preserved information should enable seamless task continuation. If critical details are lost, the user will need to re-explain context when continuing this work.`;
2691
- return prompt;
2692
- }
2693
- buildUserPrompt(messages, userContext) {
2694
- let prompt = `Please analyze the following conversation and generate a checkpoint:
2695
-
2696
- `;
2697
- if (userContext && userContext !== "\u65E0\u989D\u5916\u4E0A\u4E0B\u6587") {
2698
- prompt += `## Context
2699
- ${userContext}
2700
-
2701
- `;
2702
- }
2703
- prompt += `## Conversation Content
2704
-
2705
- ${messages}
2706
-
2707
- `;
2708
- prompt += `---
2709
-
2710
- `;
2711
- prompt += `## Output Format
2712
-
2713
- Please output in the following JSON format:
2714
-
2715
- \`\`\`json
2716
- {
2717
- "title": "Brief checkpoint title (max 30 characters)",
2718
- "processKeyPoints": [
2719
- "Point 1: Description of key discovery or decision",
2720
- "Point 2: Description of important step or conclusion",
2721
- "Point 3: ..."
2722
- ],
2723
- "currentState": "Current state description explaining progress and status (50-100 characters)",
2724
- "nextSteps": [
2725
- "Next follow-up item 1",
2726
- "Next follow-up item 2"
2727
- ],
2728
- "userIntents": [
2729
- "User intent 1: what the user wants to accomplish",
2730
- "User intent 2: another goal or request",
2731
- "User intent 3: ..."
2732
- ]
2733
- }
2734
- \`\`\`
2735
-
2736
- `;
2737
- prompt += `## Intent Extraction Guidelines
2738
-
2739
- `;
2740
- prompt += `- Extract user intents from the ENTIRE conversation flow (both user and assistant messages)
2741
- `;
2742
- prompt += `- Focus on what the user WANTS to accomplish, not just what was discussed
2743
- `;
2744
- prompt += `- Include both explicit requests and inferred goals
2745
- `;
2746
- prompt += `- Aim for 2-5 intents, prioritize the most important ones
2747
- `;
2748
- prompt += `- Be concise and specific in intent descriptions
2749
- `;
2750
- prompt += `- Examples: "Fix authentication bug", "Optimize database performance", "Add unit tests for auth module"
2751
-
2752
- `;
2753
- prompt += `Make sure the JSON output is valid and can be parsed.`;
2754
- return prompt;
2755
- }
2756
- formatMessages(messages) {
2757
- return messages.map((m, i) => `[${i}] ${m.role}: ${m.content}`).join(`
2758
-
2759
- `);
2760
- }
2761
- parseJsonResponse(content) {
2762
- const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) || content.match(/```\s*([\s\S]*?)\s*```/) || [null, content];
2763
- const jsonStr = jsonMatch[1] || content;
2764
- try {
2765
- return JSON.parse(jsonStr.trim());
2766
- } catch {
2767
- const fixed = jsonStr.replace(/,\s*}/g, "}").replace(/,\s*]/g, "]").replace(/'/g, '"').trim();
2768
- try {
2769
- return JSON.parse(fixed);
2770
- } catch (e) {
2771
- logger.error(`[SummaryAgent] Failed to parse JSON: ${content}`);
2772
- throw new Error(`Failed to parse checkpoint JSON: ${e}`);
2773
- }
2774
- }
2775
- }
2776
- parseHintResponse(content) {
2777
- return parseCompactHintResponse(content);
2778
- }
2779
- }
2780
- __legacyDecorateClassTS([
2781
- TracedAs("summary-agent.generateCompactHint")
2782
- ], SummaryAgent.prototype, "generateCompactHint", null);
2783
- __legacyDecorateClassTS([
2784
- TracedAs("summary-agent.run", { recordParams: true, recordResult: true })
2785
- ], SummaryAgent.prototype, "run", null);
2786
- __legacyDecorateClassTS([
2787
- TracedAs("summary-agent.getHintGenerationSystemPrompt")
2788
- ], SummaryAgent.prototype, "getHintGenerationSystemPrompt", null);
2789
- __legacyDecorateClassTS([
2790
- TracedAs("summary-agent.buildHintGenerationUserPrompt")
2791
- ], SummaryAgent.prototype, "buildHintGenerationUserPrompt", null);
2792
- __legacyDecorateClassTS([
2793
- TracedAs("summary-agent.parseHintResponse")
2794
- ], SummaryAgent.prototype, "parseHintResponse", null);
2795
- function parseCompactHintResponse(content) {
2796
- const jsonResult = extractGuidanceFromJson(content);
2797
- if (jsonResult !== null) {
2798
- const trimmed = jsonResult.trim();
2799
- if (!trimmed) {
2800
- return "[Hint extraction failed]";
2801
- }
2802
- if (trimmed.length > 500) {
2803
- return trimmed.substring(0, 500) + "...";
2804
- }
2805
- return trimmed;
2806
- }
2807
- let text = content.replace(/```json\s*([\s\S]*?)\s*```/g, "$1").replace(/```markdown\s*([\s\S]*?)\s*```/g, "$1").replace(/```\s*([\s\S]*?)\s*```/g, "$1").trim();
2808
- if (!text) {
2809
- return "[Hint extraction failed]";
2810
- }
2811
- if (text.length > 500) {
2812
- return text.substring(0, 500) + "...";
2813
- }
2814
- return text;
2815
- }
2816
- function extractGuidanceFromJson(content) {
2817
- const jsonBlockMatch = content.match(/```json\s*([\s\S]*?)\s*```/);
2818
- if (jsonBlockMatch) {
2819
- const parsed2 = tryParseJson(jsonBlockMatch[1]);
2820
- const guidancePrompt2 = parsed2?.guidance_prompt;
2821
- if (typeof guidancePrompt2 === "string") {
2822
- return guidancePrompt2;
2823
- }
2824
- }
2825
- const plainBlockMatch = content.match(/```\s*([\s\S]*?)\s*```/);
2826
- if (plainBlockMatch) {
2827
- const parsed2 = tryParseJson(plainBlockMatch[1]);
2828
- const guidancePrompt2 = parsed2?.guidance_prompt;
2829
- if (typeof guidancePrompt2 === "string") {
2830
- return guidancePrompt2;
2831
- }
2832
- }
2833
- const jsonMatch = content.match(/\{[\s\S]*"guidance_prompt"[\s\S]*\}/);
2834
- if (jsonMatch) {
2835
- const parsed2 = tryParseJson(jsonMatch[0]);
2836
- const guidancePrompt2 = parsed2?.guidance_prompt;
2837
- if (typeof guidancePrompt2 === "string") {
2838
- return guidancePrompt2;
2839
- }
2840
- }
2841
- const parsed = tryParseJson(content.trim());
2842
- const guidancePrompt = parsed?.guidance_prompt;
2843
- if (typeof guidancePrompt === "string") {
2844
- return guidancePrompt;
2845
- }
2846
- return null;
2847
- }
2848
- function tryParseJson(str) {
2849
- if (!str || !str.trim()) {
2850
- return null;
2851
- }
2852
- try {
2853
- return JSON.parse(str.trim());
2854
- } catch {
2855
- try {
2856
- const fixed = str.replace(/,\s*}/g, "}").replace(/,\s*]/g, "]").trim();
2857
- return JSON.parse(fixed);
2858
- } catch {
2859
- return null;
2860
- }
2861
- }
2862
- }
2863
-
2864
- // packages/core/src/env/session/session-config-registration.ts
2865
- var SESSION_DEFAULTS = {
2866
- "session.defaultDirectory": "/tmp",
2867
- "session.defaultTitleTemplate": "Session - {date}",
2868
- "session.maxMessages": 100,
2869
- "session.compactionThreshold": 80,
2870
- "session.autoCompact": true,
2871
- "session.storage.type": "sqlite",
2872
- "session.storage.dbPath": undefined,
2873
- "session.checkpoint.enabled": false,
2874
- "session.contextLimit": 1e5,
2875
- "session.maxSessions": 100
2876
- };
2877
- var SESSION_CONFIG_REGISTRATION = {
2878
- name: "session",
2879
- sources: [
2880
- { type: "env", envPrefix: "SESSION", priority: 20, watch: false }
2881
- ],
2882
- keys: [
2883
- { key: "session.defaultDirectory", sources: ["env", "file"] },
2884
- { key: "session.defaultTitleTemplate", sources: ["env", "file"] },
2885
- { key: "session.maxMessages", sources: ["env", "file"] },
2886
- { key: "session.compactionThreshold", sources: ["env", "file"] },
2887
- { key: "session.autoCompact", sources: ["env", "file"] },
2888
- { key: "session.storage.type", sources: ["env", "file"] },
2889
- { key: "session.storage.dbPath", sources: ["env", "file"] },
2890
- { key: "session.checkpoint.enabled", sources: ["env", "file"] },
2891
- { key: "session.contextLimit", sources: ["env", "file"] },
2892
- { key: "session.maxSessions", sources: ["env", "file"] }
2893
- ]
2894
- };
2895
-
2896
- // packages/core/src/env/session/session-component.ts
2897
- import path from "path";
2898
- var logger2 = createLogger("session");
2899
-
2900
- class SessionComponent extends BaseComponent {
2901
- name = "session";
2902
- version = "1.1.0";
2903
- config;
2904
- store;
2905
- activeSessionId;
2906
- hooksConfig = {};
2907
- configComponent;
2908
- configWatcher;
2909
- summaryAgent;
2910
- promptComponent;
2911
- llmComponent;
2912
- constructor() {
2913
- super();
2914
- }
2915
- async init(config) {
2916
- await super.init(config);
2917
- const options = config?.options;
2918
- if (!options?.configComponent) {
2919
- throw new Error("ConfigComponent is required for SessionComponent initialization");
2920
- }
2921
- this.configComponent = options.configComponent;
2922
- await this.registerConfig(options);
2923
- const storageConfig = this.config?.storage;
2924
- if (storageConfig?.type === "sqlite") {
2925
- this.store = new SQLiteSessionStore(storageConfig.dbPath);
2926
- logger2.info(`[SessionComponent] Using SQLite storage: ${storageConfig.dbPath || "default path"}`);
2927
- } else {
2928
- this.store = new MemorySessionStore;
2929
- logger2.info("[SessionComponent] Using memory storage");
2930
- }
2931
- this.setStatus("running");
2932
- logger2.info("[SessionComponent] Initialized");
2933
- }
2934
- getDefaultSessionDbPath() {
2935
- const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
2936
- return path.join(home, ".local", "share", "roy-agent", "sessions.db");
2937
- }
2938
- async registerConfig(options) {
2939
- const configComponent = options.configComponent;
2940
- if (!configComponent)
2941
- return;
2942
- const { configPath, envPrefix, config } = options;
2943
- const prefix = envPrefix !== undefined ? envPrefix : "SESSION";
2944
- configComponent.registerComponent(SESSION_CONFIG_REGISTRATION);
2945
- if (configPath) {
2946
- configComponent.registerSource({
2947
- type: "file",
2948
- relativePath: configPath,
2949
- optional: true,
2950
- watch: false
2951
- });
2952
- }
2953
- configComponent.registerSource({
2954
- type: "env",
2955
- envPrefix: prefix,
2956
- priority: 20,
2957
- watch: false
2958
- });
2959
- await configComponent.load("session");
2960
- for (const envKey of Object.keys(process.env)) {
2961
- const configKey = envKeyToConfigKey(envKey, prefix, "session");
2962
- if (!configKey)
2963
- continue;
2964
- const value = process.env[envKey];
2965
- if (value !== undefined) {
2966
- await configComponent.set(configKey, value);
2967
- }
2968
- }
2969
- for (const [key, value] of Object.entries(SESSION_DEFAULTS)) {
2970
- if (configComponent.get(key) === undefined) {
2971
- await configComponent.set(key, value);
2972
- }
2973
- }
2974
- if (configComponent.get("session.storage.dbPath") === undefined) {
2975
- await configComponent.set("session.storage.dbPath", this.getDefaultSessionDbPath());
2976
- }
2977
- if (config) {
2978
- const flatConfig = this.flattenConfig(config);
2979
- for (const [key, value] of Object.entries(flatConfig)) {
2980
- await configComponent.set(key, value);
2981
- }
2982
- }
2983
- this.registerConfigWatcher(configComponent);
2984
- this.config = this.buildConfig(configComponent);
2985
- }
2986
- buildConfig(configComponent) {
2987
- return {
2988
- defaultDirectory: configComponent.get("session.defaultDirectory"),
2989
- defaultTitleTemplate: configComponent.get("session.defaultTitleTemplate"),
2990
- maxMessages: configComponent.get("session.maxMessages"),
2991
- compactionThreshold: configComponent.get("session.compactionThreshold"),
2992
- autoCompact: configComponent.get("session.autoCompact"),
2993
- storage: {
2994
- type: configComponent.get("session.storage.type"),
2995
- dbPath: configComponent.get("session.storage.dbPath")
2996
- }
2997
- };
2998
- }
2999
- flattenConfig(obj, prefix = "session") {
3000
- const result = {};
3001
- for (const [key, value] of Object.entries(obj)) {
3002
- const fullKey = `${prefix}.${key}`;
3003
- if (value && typeof value === "object" && !Array.isArray(value)) {
3004
- Object.assign(result, this.flattenConfig(value, fullKey));
3005
- } else {
3006
- result[fullKey] = value;
3007
- }
3008
- }
3009
- return result;
3010
- }
3011
- registerConfigWatcher(configComponent) {
3012
- if (typeof configComponent.watch !== "function") {
3013
- return;
3014
- }
3015
- this.configWatcher = configComponent.watch("session.*", (event) => {
3016
- this.onConfigChange(event);
3017
- });
3018
- }
3019
- onConfigChange(event) {
3020
- logger2.info(`Session config changed: ${event.key}`, {
3021
- oldValue: event.oldValue,
3022
- newValue: event.newValue
3023
- });
3024
- }
3025
- async onStart() {
3026
- logger2.info("[SessionComponent] Started");
3027
- }
3028
- async onStop() {
3029
- this.configWatcher?.();
3030
- this.configWatcher = undefined;
3031
- await this.store?.close();
3032
- this.store = undefined;
3033
- this.setStatus("stopped");
3034
- logger2.info("[SessionComponent] Stopped");
3035
- }
3036
- async create(options = {}) {
3037
- await this.executeBeforeHooks("create", { options });
3038
- const title = options.title ?? this.generateTitle();
3039
- const session = await this.store.create({
3040
- ...options,
3041
- title
3042
- });
3043
- logger2.info(`[SessionComponent] Created session: ${session.id}`, { title });
3044
- await this.executeAfterHooks("create", { session, options });
3045
- return session;
3046
- }
3047
- async get(id) {
3048
- await this.executeBeforeHooks("session.get", { id });
3049
- const session = await this.store?.get(id);
3050
- await this.executeAfterHooks("session.get", { session });
3051
- return session;
3052
- }
3053
- async getSession(id) {
3054
- const session = await this.get(id);
3055
- if (!session) {
3056
- return null;
3057
- }
3058
- const messages = await this.getMessages(id);
3059
- return {
3060
- sessionId: session.id,
3061
- title: session.title || "Untitled",
3062
- messages: messages.map((m) => ({
3063
- role: m.role,
3064
- content: m.content,
3065
- timestamp: m.timestamp
3066
- }))
3067
- };
3068
- }
3069
- async searchSessions(query, options) {
3070
- const limit = options?.limit ?? 20;
3071
- if (options?.session_id) {
3072
- const session = await this.get(options.session_id);
3073
- if (session) {
3074
- const messages = await this.getMessages(options.session_id);
3075
- const lastMessage = messages[messages.length - 1];
3076
- return [{
3077
- sessionId: session.id,
3078
- title: session.title || "Untitled",
3079
- preview: lastMessage?.content?.substring(0, 200) || "",
3080
- timestamp: session.updatedAt || session.createdAt
3081
- }];
3082
- }
3083
- return [];
3084
- }
3085
- const sessions = await this.list({ limit });
3086
- const results = [];
3087
- for (const session of sessions) {
3088
- if (results.length >= limit)
3089
- break;
3090
- const messages = await this.getMessages(session.id);
3091
- const lastMessage = messages[messages.length - 1];
3092
- const preview = lastMessage?.content?.substring(0, 200) || "";
3093
- if (query) {
3094
- const lowerQuery = query.toLowerCase();
3095
- const titleMatch = (session.title || "").toLowerCase().includes(lowerQuery);
3096
- const previewMatch = preview.toLowerCase().includes(lowerQuery);
3097
- if (!titleMatch && !previewMatch) {
3098
- continue;
3099
- }
3100
- }
3101
- results.push({
3102
- sessionId: session.id,
3103
- title: session.title || "Untitled",
3104
- preview,
3105
- timestamp: session.updatedAt || session.createdAt
3106
- });
3107
- }
3108
- return results;
3109
- }
3110
- async list(options) {
3111
- await this.executeBeforeHooks("session.list", { options });
3112
- const sessions = await this.store?.list(options) ?? [];
3113
- await this.executeAfterHooks("session.list", { sessions });
3114
- return sessions;
3115
- }
3116
- async getCount() {
3117
- return await this.store?.getCount() ?? 0;
3118
- }
3119
- async update(id, updates) {
3120
- await this.executeBeforeHooks("session.update", { id, updates });
3121
- const success = await this.store?.update(id, updates);
3122
- if (success) {
3123
- logger2.info(`[SessionComponent] Updated session: ${id}`, { updates });
3124
- await this.executeAfterHooks("session.update", { id, updates });
3125
- }
3126
- return success ?? false;
3127
- }
3128
- async delete(id) {
3129
- await this.executeBeforeHooks("session.delete", { id });
3130
- const success = await this.store?.delete(id);
3131
- if (success) {
3132
- if (this.activeSessionId === id) {
3133
- this.activeSessionId = undefined;
3134
- }
3135
- logger2.info(`[SessionComponent] Deleted session: ${id}`);
3136
- await this.executeAfterHooks("session.delete", { id });
3137
- }
3138
- return success ?? false;
3139
- }
3140
- getActiveSession() {
3141
- if (!this.activeSessionId)
3142
- return;
3143
- return;
3144
- }
3145
- getActiveSessionId() {
3146
- return this.activeSessionId;
3147
- }
3148
- async setActiveSession(id) {
3149
- const session = await this.store?.get(id);
3150
- if (!session)
3151
- return false;
3152
- this.activeSessionId = id;
3153
- logger2.info(`[SessionComponent] Active session set: ${id}`);
3154
- return true;
3155
- }
3156
- async addMessage(sessionId, message) {
3157
- const contentPreview = typeof message.content === "string" ? message.content.substring(0, 100) : JSON.stringify(message.content).substring(0, 100);
3158
- logger2.info(`[SessionComponent.addMessage] sessionId=${sessionId}, role=${message.role}, content="${contentPreview}"`);
3159
- try {
3160
- const messageId = await this.store?.addMessage(sessionId, message);
3161
- logger2.info(`[SessionComponent.addMessage] Success: messageId=${messageId}`);
3162
- return messageId;
3163
- } catch (error) {
3164
- logger2.error(`[SessionComponent] Failed to add message: ${error}`);
3165
- return;
3166
- }
3167
- }
3168
- async getMessages(sessionId, options) {
3169
- const messages = await this.store?.getMessages(sessionId, options?.offset, options?.limit);
3170
- return messages ?? [];
3171
- }
3172
- async getMessageCount(sessionId, includeArchived) {
3173
- return this.store?.getMessageCount(sessionId, includeArchived) ?? 0;
3174
- }
3175
- async getMessageIndexes(sessionId, role) {
3176
- return this.store?.getMessageIndexes(sessionId, role) ?? [];
3177
- }
3178
- async executeBeforeHooks(operation, context) {
3179
- const hookKey = `before.session.${operation}`;
3180
- const hooks = this.hooksConfig[hookKey] ?? [];
3181
- const hookContext = context;
3182
- for (const hook of hooks) {
3183
- if (hook.before) {
3184
- await hook.before(hookContext);
3185
- }
3186
- }
3187
- const options = context.options;
3188
- if (options?.hooks) {
3189
- const hookArray = options.hooks[hookKey] ?? [];
3190
- for (const hook of hookArray) {
3191
- if (hook.before) {
3192
- await hook.before(hookContext);
3193
- }
3194
- }
3195
- }
3196
- }
3197
- async executeAfterHooks(operation, context) {
3198
- const hookKey = `after.session.${operation}`;
3199
- const hooks = this.hooksConfig[hookKey] ?? [];
3200
- const hookContext = context;
3201
- for (const hook of hooks) {
3202
- if (hook.after) {
3203
- await hook.after(hookContext);
3204
- }
3205
- }
3206
- const options = context.options;
3207
- if (options?.hooks) {
3208
- const hookArray = options.hooks[hookKey] ?? [];
3209
- for (const hook of hookArray) {
3210
- if (hook.after) {
3211
- await hook.after(hookContext);
3212
- }
3213
- }
3214
- }
3215
- }
3216
- generateTitle() {
3217
- const template = this.config?.defaultTitleTemplate ?? "Session - {date}";
3218
- const date = new Date().toISOString().replace("T", " ").substring(0, 19);
3219
- return template.replace("{date}", date);
3220
- }
3221
- setSummaryComponents(promptComponent, llmComponent) {
3222
- this.promptComponent = promptComponent;
3223
- this.llmComponent = llmComponent;
3224
- this.summaryAgent = new SummaryAgent(promptComponent, llmComponent);
3225
- }
3226
- ensureSummaryAgent() {
3227
- if (!this.summaryAgent) {
3228
- if (!this.promptComponent || !this.llmComponent) {
3229
- throw new Error("SummaryAgent components not initialized. Call setSummaryComponents() first.");
3230
- }
3231
- this.summaryAgent = new SummaryAgent(this.promptComponent, this.llmComponent);
3232
- }
3233
- }
3234
- async generateCompactHint(sessionId) {
3235
- const session = await this.get(sessionId);
3236
- if (!session) {
3237
- throw new Error(`Session not found: ${sessionId}`);
3238
- }
3239
- const latestCheckpoint = this.getLatestCheckpoint(session);
3240
- const startIndex = latestCheckpoint?.messageIndex ?? 0;
3241
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3242
- const messages = await this.store.getMessages(sessionId, startIndex, MAX_SAFE_MESSAGES, { includeArchived: false });
3243
- if (messages.length < 3) {
3244
- logger2.warn("[SessionComponent] Not enough messages for hint generation");
3245
- return "";
3246
- }
3247
- this.ensureSummaryAgent();
3248
- const result = await this.summaryAgent.generateCompactHint({
3249
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
3250
- sessionContext: {}
3251
- });
3252
- logger2.info("[SessionComponent] Compact hint generated", {
3253
- sessionId,
3254
- hintLength: result.hint.length
3255
- });
3256
- return result.hint;
3257
- }
3258
- async compact(sessionId, options) {
3259
- const session = await this.get(sessionId);
3260
- if (!session) {
3261
- throw new Error(`Session not found: ${sessionId}`);
3262
- }
3263
- const latestCheckpoint = this.getLatestCheckpoint(session);
3264
- const startIndex = latestCheckpoint?.messageIndex ?? 0;
3265
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3266
- const messages = await this.store.getMessages(sessionId, startIndex, MAX_SAFE_MESSAGES, { includeArchived: false });
3267
- if (messages.length < 3) {
3268
- throw new Error("Not enough messages to compact (minimum 3 required)");
3269
- }
3270
- const recentMessages = this.extractRecentMessages(messages, 2);
3271
- this.ensureSummaryAgent();
3272
- await this.executeBeforeHooks("compact", { session, options });
3273
- const summaryResult = await this.summaryAgent.run({
3274
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
3275
- userContext: options?.summary,
3276
- outputFormat: "json",
3277
- scenarioHint: options?.scenarioHint
3278
- });
3279
- const checkpointId = `cp_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 8)}`;
3280
- const checkpoint = {
3281
- id: checkpointId,
3282
- messageIndex: startIndex,
3283
- title: summaryResult.title,
3284
- summary: [
3285
- `Process: ${summaryResult.processKeyPoints.join("; ")}`,
3286
- `State: ${summaryResult.currentState}`
3287
- ].join(`
3288
- `),
3289
- processKeyPoints: summaryResult.processKeyPoints,
3290
- currentState: summaryResult.currentState,
3291
- nextSteps: summaryResult.nextSteps,
3292
- userIntents: summaryResult.userIntents,
3293
- messageCountBefore: messages.length,
3294
- createdAt: Date.now(),
3295
- type: "compact",
3296
- recentMessages
3297
- };
3298
- await this.store.saveCheckpoint(sessionId, checkpoint);
3299
- await this.store.archiveMessages(sessionId, checkpointId, messages.length);
3300
- const checkpointMessage = this.createCheckpointMessage(checkpoint);
3301
- await this.store.addMessage(sessionId, checkpointMessage);
3302
- const updatedSession = await this.get(sessionId);
3303
- const remainingMessageCount = updatedSession?.messageCount ?? 0;
3304
- const checkpointCount = updatedSession?.metadata?.checkpoints?.checkpoints?.length ?? 0;
3305
- logger2.info(`[SessionComponent] Compacted session: ${sessionId}`, {
3306
- checkpointId,
3307
- archivedCount: messages.length,
3308
- remainingCount: remainingMessageCount,
3309
- hasScenarioHint: !!options?.scenarioHint,
3310
- recentMessagesCount: recentMessages.length
3311
- });
3312
- await this.executeAfterHooks("compact", { session, checkpoint, options });
3313
- return {
3314
- checkpoint,
3315
- deletedMessageCount: messages.length,
3316
- remainingMessageCount,
3317
- checkpointCount
3318
- };
3319
- }
3320
- extractRecentMessages(messages, turnCount = 2) {
3321
- const recentMessages = [];
3322
- let turnsExtracted = 0;
3323
- let i = messages.length - 1;
3324
- while (i >= 0 && turnsExtracted < turnCount) {
3325
- const msg = messages[i];
3326
- if (msg.metadata?.isCheckpoint) {
3327
- i--;
3328
- continue;
3329
- }
3330
- const hasToolParts = msg.parts?.some((p) => p.type === "tool-call" || p.type === "tool-result");
3331
- if (msg.role === "assistant" && !hasToolParts && msg.content.trim()) {
3332
- recentMessages.unshift({
3333
- role: "assistant",
3334
- content: msg.content
3335
- });
3336
- let j = i - 1;
3337
- while (j >= 0) {
3338
- const prevMsg = messages[j];
3339
- if (prevMsg.metadata?.isCheckpoint) {
3340
- j--;
3341
- continue;
3342
- }
3343
- if (prevMsg.role === "user") {
3344
- recentMessages.unshift({
3345
- role: "user",
3346
- content: prevMsg.content
3347
- });
3348
- turnsExtracted++;
3349
- break;
3350
- }
3351
- j--;
3352
- }
3353
- i = j;
3354
- } else {
3355
- i--;
3356
- }
3357
- }
3358
- logger2.debug("[SessionComponent] Extracted recent messages", {
3359
- turnCount,
3360
- messagesExtracted: recentMessages.length
3361
- });
3362
- return recentMessages;
3363
- }
3364
- async previewCompact(sessionId) {
3365
- const session = await this.get(sessionId);
3366
- if (!session) {
3367
- throw new Error(`Session not found: ${sessionId}`);
3368
- }
3369
- const latestCheckpoint = this.getLatestCheckpoint(session);
3370
- const startIndex = latestCheckpoint?.messageIndex ?? 0;
3371
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3372
- const messages = await this.store.getMessages(sessionId, startIndex, MAX_SAFE_MESSAGES, { includeArchived: false });
3373
- const estimatedTokens = messages.reduce((sum, m) => sum + m.content.length * 0.25, 0);
3374
- return {
3375
- messageCountToCompact: messages.length,
3376
- estimatedCheckpointTokens: Math.round(estimatedTokens * 0.1),
3377
- wouldTrigger: messages.length >= (this.config?.maxMessages ?? 50)
3378
- };
3379
- }
3380
- async getCheckpoints(sessionId) {
3381
- return await this.store.getCheckpoints(sessionId);
3382
- }
3383
- async getCheckpoint(sessionId, checkpointId) {
3384
- return await this.store.getCheckpoint(sessionId, checkpointId);
3385
- }
3386
- async deleteCheckpoint(sessionId, checkpointId) {
3387
- await this.executeBeforeHooks("deleteCheckpoint", { sessionId, checkpointId });
3388
- const success = await this.store.deleteCheckpoint(sessionId, checkpointId);
3389
- if (success) {
3390
- logger2.info(`[SessionComponent] Deleted checkpoint: ${checkpointId}`);
3391
- await this.executeAfterHooks("deleteCheckpoint", { sessionId, checkpointId });
3392
- }
3393
- return success;
3394
- }
3395
- async getContext(sessionId, options) {
3396
- const session = await this.get(sessionId);
3397
- if (!session) {
3398
- throw new Error(`Session not found`);
3399
- }
3400
- let contextMessages = [];
3401
- let startCheckpoint;
3402
- if (options?.fullHistory) {
3403
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3404
- contextMessages = await this.store.getMessages(sessionId, 0, MAX_SAFE_MESSAGES, {
3405
- includeArchived: true
3406
- });
3407
- } else {
3408
- const latestCheckpointId = session.metadata?.checkpoints?.latestCheckpointId;
3409
- if (latestCheckpointId) {
3410
- startCheckpoint = await this.store.getCheckpoint(sessionId, latestCheckpointId);
3411
- if (startCheckpoint) {
3412
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3413
- contextMessages = await this.store.getMessages(sessionId, startCheckpoint.messageIndex, MAX_SAFE_MESSAGES, { includeArchived: false });
3414
- }
3415
- }
3416
- if (contextMessages.length === 0) {
3417
- const MAX_SAFE_MESSAGES = Number.MAX_SAFE_INTEGER;
3418
- contextMessages = await this.store.getMessages(sessionId, 0, MAX_SAFE_MESSAGES, {
3419
- includeArchived: false
3420
- });
3421
- }
3422
- }
3423
- if (options?.minUserMessages && options.minUserMessages > 0) {
3424
- const userIndexes = [];
3425
- for (let i = 0;i < contextMessages.length; i++) {
3426
- if (contextMessages[i].role === "user") {
3427
- userIndexes.push(i);
3428
- }
3429
- }
3430
- if (userIndexes.length > options.minUserMessages) {
3431
- const targetIndex = userIndexes[userIndexes.length - options.minUserMessages];
3432
- contextMessages = contextMessages.slice(targetIndex);
3433
- }
3434
- }
3435
- if (options?.messageLimit) {
3436
- contextMessages = contextMessages.slice(-options.messageLimit);
3437
- }
3438
- const checkpoints = contextMessages.filter((m) => m.metadata?.isCheckpoint).map((m) => m.metadata.checkpointMeta);
3439
- const estimatedTokens = contextMessages.reduce((sum, m) => sum + m.content.length * 0.25, 0);
3440
- return {
3441
- session,
3442
- checkpoints,
3443
- startCheckpoint: startCheckpoint ?? checkpoints[checkpoints.length - 1],
3444
- messages: contextMessages,
3445
- totalMessageCount: contextMessages.length,
3446
- activeMessageCount: contextMessages.filter((m) => !m.isArchived).length,
3447
- archivedMessageCount: contextMessages.filter((m) => m.isArchived).length,
3448
- estimatedTokens: Math.round(estimatedTokens)
3449
- };
3450
- }
3451
- async shouldCompact(sessionId) {
3452
- const session = await this.get(sessionId);
3453
- if (!session)
3454
- return false;
3455
- const preview = await this.previewCompact(sessionId);
3456
- return preview.wouldTrigger;
3457
- }
3458
- async searchMessages(options) {
3459
- const {
3460
- query,
3461
- sessionId,
3462
- limit = 10,
3463
- maxResults = 100,
3464
- beforeTime,
3465
- afterTime,
3466
- includeArchived = false,
3467
- includeContext = false,
3468
- contextLines = 2
3469
- } = options;
3470
- if (!this.store) {
3471
- return [];
3472
- }
3473
- let sessions;
3474
- if (sessionId) {
3475
- const session = await this.get(sessionId);
3476
- sessions = session ? [session] : [];
3477
- } else {
3478
- sessions = await this.list({ limit: 1000 });
3479
- }
3480
- const results = [];
3481
- let totalMatches = 0;
3482
- for (const session of sessions) {
3483
- if (beforeTime && session.updatedAt > beforeTime)
3484
- continue;
3485
- if (afterTime && session.updatedAt < afterTime)
3486
- continue;
3487
- const messages = await this.store.getMessages(session.id, 0, 1000, { includeArchived });
3488
- const queryTerms = parseSearchQuery(query);
3489
- const matches = [];
3490
- for (const msg of messages) {
3491
- if (beforeTime && msg.timestamp > beforeTime)
3492
- continue;
3493
- if (afterTime && msg.timestamp < afterTime)
3494
- continue;
3495
- if (matchesQuery(msg.content, queryTerms)) {
3496
- const match = {
3497
- messageId: msg.id,
3498
- sessionId: session.id,
3499
- role: msg.role,
3500
- content: msg.content,
3501
- timestamp: msg.timestamp
3502
- };
3503
- if (includeContext) {
3504
- const msgIndex = messages.indexOf(msg);
3505
- const beforeMsgs = messages.slice(Math.max(0, msgIndex - contextLines), msgIndex);
3506
- const afterMsgs = messages.slice(msgIndex + 1, msgIndex + 1 + contextLines);
3507
- match.contextBefore = beforeMsgs.map((m) => m.content).join(`
3508
- `);
3509
- match.contextAfter = afterMsgs.map((m) => m.content).join(`
3510
- `);
3511
- }
3512
- matches.push(match);
3513
- if (matches.length >= limit)
3514
- break;
3515
- }
3516
- }
3517
- if (matches.length > 0) {
3518
- results.push({
3519
- sessionId: session.id,
3520
- sessionTitle: session.title,
3521
- sessionDirectory: session.directory,
3522
- updatedAt: session.updatedAt,
3523
- messageCount: session.messageCount,
3524
- matches
3525
- });
3526
- totalMatches += matches.length;
3527
- if (totalMatches >= maxResults)
3528
- break;
3529
- }
3530
- }
3531
- return results;
3532
- }
3533
- getLatestCheckpoint(session) {
3534
- const latestId = session.metadata?.checkpoints?.latestCheckpointId;
3535
- if (!latestId)
3536
- return;
3537
- return session.metadata?.checkpointDetails?.[latestId];
3538
- }
3539
- createCheckpointMessage(checkpoint) {
3540
- const lines = [
3541
- `# Checkpoint: ${checkpoint.title}`,
3542
- "",
3543
- "## Process Key Points",
3544
- ...checkpoint.processKeyPoints.map((p, i) => `${i + 1}. ${p}`),
3545
- "",
3546
- "## Current State",
3547
- checkpoint.currentState,
3548
- ""
3549
- ];
3550
- if (checkpoint.nextSteps?.length) {
3551
- lines.push("## Next Steps");
3552
- checkpoint.nextSteps.forEach((s, i) => lines.push(`${i + 1}. ${s}`));
3553
- lines.push("");
3554
- }
3555
- lines.push("## Messages Compacted");
3556
- lines.push(`${checkpoint.messageCountBefore} messages compacted at ${new Date(checkpoint.createdAt).toISOString()}`);
3557
- const content = lines.join(`
3558
- `);
3559
- return {
3560
- role: "user",
3561
- content,
3562
- parts: [{
3563
- type: "checkpoint",
3564
- checkpointId: checkpoint.id,
3565
- content,
3566
- title: checkpoint.title,
3567
- processKeyPoints: checkpoint.processKeyPoints,
3568
- currentState: checkpoint.currentState,
3569
- nextSteps: checkpoint.nextSteps,
3570
- messageCountBefore: checkpoint.messageCountBefore,
3571
- createdAt: checkpoint.createdAt
3572
- }],
3573
- metadata: {
3574
- isCheckpoint: true,
3575
- checkpointId: checkpoint.id,
3576
- checkpointMeta: checkpoint
3577
- }
3578
- };
3579
- }
3580
- }
3581
- __legacyDecorateClassTS([
3582
- TracedAs("session.generateCompactHint")
3583
- ], SessionComponent.prototype, "generateCompactHint", null);
3584
- __legacyDecorateClassTS([
3585
- TracedAs("session.compact", { recordParams: true, recordResult: true })
3586
- ], SessionComponent.prototype, "compact", null);
3587
- __legacyDecorateClassTS([
3588
- TracedAs("session.extractRecentMessages")
3589
- ], SessionComponent.prototype, "extractRecentMessages", null);
3590
- export {
3591
- SessionMessageConverter,
3592
- SessionComponent,
3593
- MemorySessionStore
3594
- };