@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3

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 (78) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/dist/agent/channel-runner.js +2 -0
  4. package/dist/agent/maintenance-context.js +21 -2
  5. package/dist/agent/turn/turn-context.js +10 -6
  6. package/dist/config/settings.d.ts +0 -2
  7. package/dist/config/settings.js +0 -2
  8. package/dist/config/tools.d.ts +8 -2
  9. package/dist/config/tools.js +35 -19
  10. package/dist/memory/anchors.d.ts +5 -0
  11. package/dist/memory/anchors.js +49 -0
  12. package/dist/memory/boundary-work.d.ts +1 -0
  13. package/dist/memory/boundary-work.js +1 -0
  14. package/dist/memory/commands.js +23 -6
  15. package/dist/memory/index-budget.d.ts +16 -0
  16. package/dist/memory/index-budget.js +24 -2
  17. package/dist/memory/journal.d.ts +7 -12
  18. package/dist/memory/journal.js +9 -41
  19. package/dist/memory/lifecycle.d.ts +1 -0
  20. package/dist/memory/lifecycle.js +2 -0
  21. package/dist/memory/reflect-job.d.ts +1 -0
  22. package/dist/memory/reflect-job.js +1 -0
  23. package/dist/memory/reflect.d.ts +10 -0
  24. package/dist/memory/reflect.js +103 -20
  25. package/dist/memory/render.d.ts +4 -1
  26. package/dist/memory/render.js +6 -4
  27. package/dist/memory/review-log.d.ts +2 -2
  28. package/dist/memory/scheduler.d.ts +7 -0
  29. package/dist/memory/scheduler.js +70 -3
  30. package/dist/memory/search-index-db.d.ts +15 -0
  31. package/dist/memory/search-index-db.js +247 -0
  32. package/dist/memory/search-index-files.d.ts +11 -0
  33. package/dist/memory/search-index-files.js +26 -0
  34. package/dist/memory/search-index-notes.d.ts +11 -0
  35. package/dist/memory/search-index-notes.js +155 -0
  36. package/dist/memory/search-index-sync.d.ts +19 -0
  37. package/dist/memory/search-index-sync.js +267 -0
  38. package/dist/memory/search-terms.d.ts +12 -0
  39. package/dist/memory/search-terms.js +185 -0
  40. package/dist/memory/search.d.ts +8 -28
  41. package/dist/memory/search.js +18 -278
  42. package/dist/memory/session-corpus.d.ts +15 -26
  43. package/dist/memory/session-corpus.js +120 -327
  44. package/dist/memory/session-search.d.ts +5 -3
  45. package/dist/memory/session-search.js +119 -171
  46. package/dist/memory/sidecar-worker.d.ts +2 -0
  47. package/dist/memory/sidecar-worker.js +25 -1
  48. package/dist/memory/store.d.ts +4 -0
  49. package/dist/memory/store.js +22 -1
  50. package/dist/memory/task-archive-digest.d.ts +61 -0
  51. package/dist/memory/task-archive-digest.js +366 -0
  52. package/dist/models/provider-login.d.ts +1 -1
  53. package/dist/models/provider-login.js +1 -1
  54. package/dist/playbooks/memory-operations.md +2 -2
  55. package/dist/shared/text-utils.d.ts +0 -1
  56. package/dist/shared/text-utils.js +0 -1
  57. package/dist/subagents/runs.d.ts +1 -1
  58. package/dist/subagents/task-envelope.js +6 -8
  59. package/dist/tools/memory-manage.d.ts +1 -0
  60. package/dist/tools/memory-manage.js +9 -23
  61. package/dist/tools/registry.js +2 -0
  62. package/dist/tools/session-search.d.ts +1 -0
  63. package/dist/tools/session-search.js +12 -6
  64. package/dist/tools/web-search.d.ts +13 -7
  65. package/dist/tools/web-search.js +62 -19
  66. package/dist/web/client.d.ts +2 -0
  67. package/dist/web/client.js +7 -3
  68. package/dist/web/config.d.ts +17 -4
  69. package/dist/web/config.js +42 -4
  70. package/dist/web/format.d.ts +2 -1
  71. package/dist/web/format.js +7 -3
  72. package/dist/web/search-providers.d.ts +15 -8
  73. package/dist/web/search-providers.js +208 -139
  74. package/dist/web/search.d.ts +13 -3
  75. package/dist/web/search.js +86 -40
  76. package/package.json +1 -1
  77. package/dist/memory/chinese-words.d.ts +0 -1
  78. package/dist/memory/chinese-words.js +0 -273
@@ -1,43 +1,21 @@
1
- import { readdir, stat } from "node:fs/promises";
2
- import { basename, join } from "node:path";
1
+ import { basename, join, relative, sep } from "node:path";
3
2
  import { getConversationsDir, SUBAGENT_RUNS_LOG_FILENAME } from "../desk/paths.js";
4
- import { isNodeError, readOptionalTextFile } from "../shared/os.js";
5
3
  import { isRecord } from "../shared/type-guards.js";
6
- /**
7
- * Ceiling on how much of one message is kept for *matching*. The old code clipped each message to
8
- * the small display window at ingest, so a keyword in the middle of a long message was gone from
9
- * the corpus entirely and widening the query could never bring it back. This is deliberately much
10
- * larger than the display window; a single pathological message still cannot blow out memory.
11
- */
12
- export const SESSION_SCAN_MAX_CHARS = 20_000;
13
- const DEFAULT_MAX_CHARS_PER_DOCUMENT = 4_000;
14
- const DEFAULT_MAX_DOCUMENTS_TOTAL = 5_000;
15
- const IGNORED_JSONL_FILES = new Set([
16
- "context.jsonl",
17
- "log.jsonl",
18
- "log.jsonl.1",
19
- SUBAGENT_RUNS_LOG_FILENAME,
20
- "memory-review.jsonl",
21
- ]);
22
- function parseJsonLine(line) {
23
- const trimmed = line.trim();
24
- if (!trimmed) {
25
- return null;
26
- }
27
- try {
28
- return JSON.parse(trimmed);
29
- }
30
- catch {
31
- return null;
32
- }
33
- }
4
+ import { listIndexSourceEntries } from "./search-index-files.js";
5
+ import { redactSecrets } from "./secret-redaction.js";
6
+ import { stripInjectedMemoryContext } from "./transcript.js";
7
+ const MAX_DOC_CHARS = 200_000;
8
+ const IGNORED_JSONL_FILES = new Set([SUBAGENT_RUNS_LOG_FILENAME, "memory-review.jsonl"]);
9
+ const ISO_PREFIX = String.raw `\[\d{4}-\d{2}-\d{2}[^\]\r\n]{0,30}\]`;
10
+ const SPEAKER_PREFIX = String.raw `\[([^\]\r\n]{1,64})\]:`;
11
+ const ATTRIBUTION = new RegExp(`^(?:\\s*(${ISO_PREFIX})[ \t]*)?(?:${SPEAKER_PREFIX}[ \t]*)?`);
34
12
  function normalizeRole(value) {
35
- if (value === "user" || value === "assistant" || value === "tool" || value === "system") {
13
+ if (value === "user" || value === "assistant" || value === "tool" || value === "system")
36
14
  return value;
37
- }
38
- if (value === "bot") {
15
+ if (value === "bot")
39
16
  return "assistant";
40
- }
17
+ if (value === "toolResult")
18
+ return "tool";
41
19
  return "unknown";
42
20
  }
43
21
  function extractContentText(content) {
@@ -55,9 +33,6 @@ function extractContentText(content) {
55
33
  if (part.type === "text" && typeof part.text === "string") {
56
34
  return part.text;
57
35
  }
58
- if (part.type === "thinking" && typeof part.thinking === "string") {
59
- return part.thinking;
60
- }
61
36
  if (part.type === "toolCall") {
62
37
  const toolName = (typeof part.toolName === "string" && part.toolName) ||
63
38
  (typeof part.name === "string" && part.name) ||
@@ -72,314 +47,132 @@ function extractContentText(content) {
72
47
  .filter(Boolean)
73
48
  .join("\n");
74
49
  }
75
- function extractMessageText(message) {
76
- if (!isRecord(message)) {
77
- return { role: "unknown", text: "" };
78
- }
79
- return {
80
- role: normalizeRole(message.role),
81
- text: extractContentText(message.content),
82
- };
83
- }
84
50
  function getStringField(record, key) {
85
51
  const value = record[key];
86
52
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
87
53
  }
88
- function getNestedRecord(record, key) {
89
- const value = record[key];
90
- return isRecord(value) ? value : null;
91
- }
92
- function createDocument(params) {
93
- // The ingest clip is a fixed, generous scan cap — not the caller's display window. Trimming for
94
- // display happens later, at query time, centered on the match (fix plan §2.5). `params.maxChars`
95
- // is kept in the signature for callers that still pass it but no longer drives the clip.
96
- const raw = params.text.trim();
97
- if (!raw) {
98
- return null;
54
+ function createDocument(role, raw, ts, speaker) {
55
+ let text = raw.trim();
56
+ if (role === "user") {
57
+ text = stripInjectedMemoryContext(text);
58
+ const prefix = ATTRIBUTION.exec(text);
59
+ if (prefix?.[0]) {
60
+ ts = prefix[1]?.slice(1, -1) ?? ts;
61
+ speaker = prefix[2] ?? speaker;
62
+ text = text.slice(prefix[0].length).trim();
63
+ }
99
64
  }
100
- const scanTruncated = raw.length > SESSION_SCAN_MAX_CHARS;
65
+ if (!text)
66
+ return null;
67
+ // Redact before clipping so a boundary cannot turn a secret into an unrecognized fragment.
68
+ text = redactSecrets(text);
69
+ if (role === "tool" && text.length > 4_000)
70
+ text = `${text.slice(0, 3_000)}\n[…]\n${text.slice(-1_000)}`;
71
+ const truncated = text.length > MAX_DOC_CHARS;
101
72
  return {
102
- id: params.id,
103
- source: params.source,
104
- path: params.path,
105
- timestamp: params.timestamp,
106
- role: params.role,
107
- text: scanTruncated ? raw.slice(0, SESSION_SCAN_MAX_CHARS) : raw,
108
- ...(scanTruncated ? { scanTruncated: true } : {}),
109
- sessionId: params.sessionId,
73
+ role,
74
+ text: text.slice(0, MAX_DOC_CHARS),
75
+ truncated,
76
+ speaker: speaker && redactSecrets(speaker),
77
+ ts,
110
78
  };
111
79
  }
112
- function parseSessionEntry(value, path, lineNumber, source, maxChars) {
113
- if (!isRecord(value)) {
80
+ export function parseTranscriptLine(source, value) {
81
+ if (!isRecord(value))
114
82
  return null;
115
- }
116
- const timestamp = getStringField(value, "timestamp") ?? getStringField(value, "date");
117
- const sessionId = getStringField(value, "sessionId") ?? getStringField(value, "branchId");
118
- if (value.type === "message") {
119
- const message = getNestedRecord(value, "message");
120
- if (!message) {
83
+ if (source === "log") {
84
+ if (value.skipContextSync === true)
121
85
  return null;
122
- }
123
- const { role, text } = extractMessageText(message);
124
- return createDocument({
125
- id: `${basename(path)}:${lineNumber}`,
126
- source,
127
- path,
128
- timestamp,
129
- role,
130
- text,
131
- sessionId,
132
- maxChars,
133
- });
134
- }
135
- if ("message" in value && isRecord(value.message)) {
136
- const { role, text } = extractMessageText(value.message);
137
- return createDocument({
138
- id: `${basename(path)}:${lineNumber}`,
139
- source,
140
- path,
141
- timestamp,
142
- role,
143
- text,
144
- sessionId,
145
- maxChars,
146
- });
147
- }
148
- const role = normalizeRole(value.role);
149
- const text = getStringField(value, "text") ?? getStringField(value, "content") ?? "";
150
- return createDocument({
151
- id: `${basename(path)}:${lineNumber}`,
152
- source,
153
- path,
154
- timestamp,
155
- role,
156
- text,
157
- sessionId,
158
- maxChars,
159
- });
86
+ const bot = value.isBot === true;
87
+ return createDocument(bot ? "assistant" : "user", getStringField(value, "text") ?? "", getStringField(value, "date") ?? getStringField(value, "ts"), bot ? undefined : (getStringField(value, "displayName") ?? getStringField(value, "userName")));
88
+ }
89
+ const message = isRecord(value.message) ? value.message : value;
90
+ return createDocument(normalizeRole(message.role), getStringField(message, "text") ?? extractContentText(message.content), getStringField(value, "timestamp") ?? getStringField(value, "date"));
91
+ }
92
+ export function dedupKey(text) {
93
+ return text
94
+ .normalize("NFKC")
95
+ .split("\n")
96
+ .map((line) => line.replace(ATTRIBUTION, ""))
97
+ .join(" ")
98
+ .replace(/\s+/g, " ")
99
+ .trim();
100
+ }
101
+ export async function listDeskTranscriptSources(deskDir) {
102
+ const conversationsDir = getConversationsDir(deskDir);
103
+ const conversations = (await listIndexSourceEntries(conversationsDir)).filter((entry) => entry.isDirectory());
104
+ const archiveDir = join(deskDir, "tasks", "archive");
105
+ const [conversationsFiles, taskFiles] = await Promise.all([
106
+ Promise.all(conversations.map(async ({ name: conversation }) => {
107
+ const dir = join(conversationsDir, conversation);
108
+ const files = [];
109
+ for (const entry of await listIndexSourceEntries(dir)) {
110
+ if (!entry.isFile() || IGNORED_JSONL_FILES.has(entry.name))
111
+ continue;
112
+ const isLog = /^log\.jsonl(?:\.\d+)?$/.test(entry.name);
113
+ if (!isLog && (!entry.name.endsWith(".jsonl") || entry.name.startsWith("log.jsonl")))
114
+ continue;
115
+ const path = join(dir, entry.name);
116
+ files.push({
117
+ path,
118
+ relPath: relative(deskDir, path).split(sep).join("/"),
119
+ conversation,
120
+ kind: isLog ? "log" : "session",
121
+ source: isLog ? "log" : entry.name === "context.jsonl" ? "context" : "session",
122
+ });
123
+ }
124
+ return files;
125
+ })),
126
+ listIndexSourceEntries(archiveDir),
127
+ ]);
128
+ return [
129
+ ...conversationsFiles.flat(),
130
+ ...taskFiles
131
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
132
+ .map(({ name }) => ({
133
+ path: join(archiveDir, name),
134
+ relPath: `tasks/archive/${name}`,
135
+ kind: "task",
136
+ source: "task",
137
+ })),
138
+ ];
160
139
  }
161
- function parseLogEntry(value, path, lineNumber, maxChars) {
162
- if (!isRecord(value)) {
163
- return null;
164
- }
165
- // Command traffic (help/status/tasks/... echoes) is marked skipContextSync at write time
166
- // (runtime/bootstrap.ts) so it never comes back as memory-extraction input.
167
- if (value.skipContextSync === true) {
140
+ export function archivedTaskDoc(mdPath, markdown, logContent, mtimeMs) {
141
+ if (!markdown.trim())
168
142
  return null;
169
- }
170
- const isBot = value.isBot === true;
171
- const text = getStringField(value, "text") ?? "";
172
- const role = isBot ? "assistant" : "user";
173
- const timestamp = getStringField(value, "date") ?? getStringField(value, "ts");
174
- const userName = getStringField(value, "displayName") ?? getStringField(value, "userName");
175
- const prefixedText = userName && !isBot ? `[${userName}] ${text}` : text;
176
- return createDocument({
177
- id: `${basename(path)}:${lineNumber}`,
178
- source: "log",
179
- path,
180
- timestamp,
181
- role,
182
- text: prefixedText,
183
- maxChars,
184
- });
185
- }
186
- async function parseJsonlFile(path, source, maxChars) {
187
- const content = await readOptionalTextFile(path);
188
- if (!content.trim()) {
189
- return [];
190
- }
191
- const docs = [];
192
- const lines = content.split(/\r?\n/);
193
- for (let index = 0; index < lines.length; index++) {
194
- const parsed = parseJsonLine(lines[index] ?? "");
195
- if (parsed === null) {
143
+ const id = basename(mdPath, ".md");
144
+ const logNotes = [];
145
+ let closedAt;
146
+ for (const line of logContent.split(/\r?\n/)) {
147
+ const parsed = parseJsonLine(line);
148
+ if (!isRecord(parsed))
196
149
  continue;
150
+ if (parsed.kind === "report" && typeof parsed.text === "string" && parsed.text.trim()) {
151
+ logNotes.push(`[汇报] ${parsed.text.trim()}`);
197
152
  }
198
- const document = source === "log"
199
- ? parseLogEntry(parsed, path, index + 1, maxChars)
200
- : parseSessionEntry(parsed, path, index + 1, source, maxChars);
201
- if (document) {
202
- docs.push(document);
153
+ else if (parsed.kind === "ask" && typeof parsed.question === "string" && parsed.question.trim()) {
154
+ logNotes.push(`[提问] ${parsed.question.trim()}`);
203
155
  }
204
- }
205
- return docs;
206
- }
207
- async function listConversations(deskDir) {
208
- try {
209
- const entries = await readdir(getConversationsDir(deskDir), { withFileTypes: true });
210
- return entries
211
- .filter((entry) => entry.isDirectory())
212
- .map((entry) => entry.name)
213
- .sort();
214
- }
215
- catch (error) {
216
- if (isNodeError(error) && error.code === "ENOENT") {
217
- return [];
218
- }
219
- throw error;
220
- }
221
- }
222
- async function listSessionJsonlFiles(conversationDirs, maxFiles) {
223
- // Stat in parallel: one round trip per session file, and awaiting them one at a time made the
224
- // corpus build scale with the file count rather than with the slowest stat.
225
- const listed = await Promise.all(conversationDirs.map(async ({ conversation, dir }) => {
226
- try {
227
- return (await readdir(dir))
228
- .filter((name) => name.endsWith(".jsonl") && !IGNORED_JSONL_FILES.has(name))
229
- .map((name) => ({ conversation, path: join(dir, name) }));
230
- }
231
- catch {
232
- return [];
233
- }
234
- }));
235
- const stated = await Promise.all(listed.flat().map(async (entry) => {
236
- try {
237
- const stats = await stat(entry.path);
238
- return stats.isFile() ? { ...entry, mtimeMs: stats.mtimeMs } : null;
239
- }
240
- catch {
241
- return null;
242
- }
243
- }));
244
- return stated
245
- .filter((entry) => entry !== null)
246
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
247
- .slice(0, Math.max(0, maxFiles))
248
- .map(({ conversation, path }) => ({ conversation, path }));
249
- }
250
- async function readArchivedTaskDocuments(deskDir, maxFiles, maxChars) {
251
- const archiveDir = join(deskDir, "tasks", "archive");
252
- let names;
253
- try {
254
- names = (await readdir(archiveDir)).filter((name) => name.endsWith(".md"));
255
- }
256
- catch (error) {
257
- if (isNodeError(error) && error.code === "ENOENT")
258
- return [];
259
- throw error;
260
- }
261
- const stated = await Promise.all(names.map(async (name) => {
262
- const path = join(archiveDir, name);
263
- try {
264
- const stats = await stat(path);
265
- return stats.isFile() ? { name, path, mtimeMs: stats.mtimeMs } : null;
156
+ else if (parsed.kind === "message" && typeof parsed.text === "string" && parsed.text.trim()) {
157
+ logNotes.push(`[用户消息] ${parsed.text.trim()}`);
266
158
  }
267
- catch {
268
- return null;
159
+ else if (parsed.kind === "close" || parsed.kind === "closed") {
160
+ closedAt = getStringField(parsed, "ts") ?? closedAt;
161
+ const outcome = getStringField(parsed, "outcome") ?? "closed";
162
+ const note = getStringField(parsed, "note");
163
+ logNotes.push(`[结项 ${outcome}]${note ? ` ${note}` : ""}`);
269
164
  }
270
- }));
271
- const files = stated
272
- .filter((entry) => entry !== null)
273
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
274
- .slice(0, Math.min(200, Math.max(20, maxFiles * 10)));
275
- const docs = [];
276
- for (const file of files) {
277
- const id = file.name.slice(0, -".md".length);
278
- const markdown = await readOptionalTextFile(file.path);
279
- if (!markdown.trim())
280
- continue;
281
- const logContent = await readOptionalTextFile(join(archiveDir, `${id}.jsonl`));
282
- const logNotes = [];
283
- let closedAt;
284
- for (const line of logContent.split(/\r?\n/)) {
285
- const parsed = parseJsonLine(line);
286
- if (!isRecord(parsed))
287
- continue;
288
- if (parsed.kind === "report" && typeof parsed.text === "string" && parsed.text.trim()) {
289
- logNotes.push(`[汇报] ${parsed.text.trim()}`);
290
- }
291
- else if (parsed.kind === "ask" && typeof parsed.question === "string" && parsed.question.trim()) {
292
- logNotes.push(`[提问] ${parsed.question.trim()}`);
293
- }
294
- else if (parsed.kind === "message" && typeof parsed.text === "string" && parsed.text.trim()) {
295
- logNotes.push(`[用户消息] ${parsed.text.trim()}`);
296
- }
297
- else if (parsed.kind === "close" || parsed.kind === "closed") {
298
- closedAt = getStringField(parsed, "ts") ?? closedAt;
299
- const outcome = getStringField(parsed, "outcome") ?? "closed";
300
- const note = getStringField(parsed, "note");
301
- logNotes.push(`[结项 ${outcome}]${note ? ` ${note}` : ""}`);
302
- }
303
- }
304
- const frontmatterClosedAt = /^closedAt:\s*["']?([^"'\r\n]+)["']?\s*$/m.exec(markdown)?.[1]?.trim();
305
- const timestamp = closedAt ?? frontmatterClosedAt ?? new Date(file.mtimeMs).toISOString();
306
- const combined = logNotes.length > 0 ? `${markdown.trim()}\n\n${logNotes.join("\n")}` : markdown.trim();
307
- const document = createDocument({
308
- id: `tasks/archive/${file.name}`,
309
- source: "task",
310
- path: file.path,
311
- timestamp,
312
- role: "assistant",
313
- text: `[归档任务 ${id}]\n${combined}`,
314
- maxChars,
315
- });
316
- if (document)
317
- docs.push(document);
318
165
  }
319
- return docs.reverse();
166
+ const frontmatterClosedAt = /^closedAt:\s*["']?([^"'\r\n]+)["']?\s*$/m.exec(markdown)?.[1]?.trim();
167
+ const timestamp = closedAt ?? frontmatterClosedAt ?? new Date(mtimeMs).toISOString();
168
+ const combined = logNotes.length > 0 ? `${markdown.trim()}\n\n${logNotes.join("\n")}` : markdown.trim();
169
+ return createDocument("assistant", `[归档任务 ${id}]\n${combined}`, timestamp);
320
170
  }
321
- export async function buildSessionCorpus(options) {
322
- const maxFiles = Math.max(1, Math.floor(options.maxFiles));
323
- const maxChars = options.maxCharsPerDocument ?? DEFAULT_MAX_CHARS_PER_DOCUMENT;
324
- const maxDocuments = options.maxDocumentsTotal ?? DEFAULT_MAX_DOCUMENTS_TOTAL;
325
- const conversationDirs = (await listConversations(options.deskDir)).map((conversation) => ({
326
- conversation,
327
- dir: join(getConversationsDir(options.deskDir), conversation),
328
- }));
329
- const readPlan = [];
330
- for (const { conversation, dir } of conversationDirs) {
331
- readPlan.push({ path: join(dir, "context.jsonl"), source: "context", conversation }, { path: join(dir, "log.jsonl"), source: "log", conversation }, { path: join(dir, "log.jsonl.1"), source: "log", conversation });
332
- }
333
- for (const entry of await listSessionJsonlFiles(conversationDirs, maxFiles)) {
334
- readPlan.push({ ...entry, source: "session" });
335
- }
336
- // Every conversation is read, each keeping at most its newest `maxDocuments`; the total is then
337
- // shared out by `shareBudget`. Stopping in directory order once the total ran over let one
338
- // long-lived channel fill the budget before later channels were read at all (spec 058, D12:
339
- // `session_search` covers the whole desk).
340
- const byConversation = new Map();
341
- for (const item of readPlan) {
342
- let docs = byConversation.get(item.conversation) ?? [];
343
- for (const document of await parseJsonlFile(item.path, item.source, maxChars)) {
344
- // Ids are `<file>:<line>`, and every conversation has its own `context.jsonl`.
345
- docs.push({ ...document, id: `${item.conversation}/${document.id}`, conversation: item.conversation });
346
- }
347
- if (docs.length > maxDocuments * 2)
348
- docs = docs.slice(-maxDocuments);
349
- byConversation.set(item.conversation, docs);
171
+ export function parseJsonLine(line) {
172
+ try {
173
+ return JSON.parse(line);
350
174
  }
351
- const archivedTasks = await readArchivedTaskDocuments(options.deskDir, maxFiles, maxChars);
352
- const groups = [...byConversation.values()];
353
- if (archivedTasks.length > 0)
354
- groups.push(archivedTasks);
355
- return shareBudget(groups.map(deduplicate), maxDocuments);
356
- }
357
- function deduplicate(docs) {
358
- const deduplicated = [];
359
- const seen = new Set();
360
- for (const document of docs) {
361
- const identity = document.timestamp
362
- ? `${document.timestamp}\0${document.role}\0${document.text}`
363
- : `${document.source}\0${document.id}`;
364
- if (seen.has(identity))
365
- continue;
366
- seen.add(identity);
367
- deduplicated.push(document);
175
+ catch {
176
+ return null;
368
177
  }
369
- return deduplicated;
370
- }
371
- /**
372
- * Fair shares of `budget`, smallest conversation first: one that needs less than an equal share
373
- * keeps everything and leaves the rest to the others; a larger one keeps its newest documents.
374
- */
375
- function shareBudget(groups, budget) {
376
- const kept = new Map();
377
- let remaining = budget;
378
- const bySize = [...groups].sort((a, b) => a.length - b.length);
379
- bySize.forEach((group, index) => {
380
- const take = Math.min(group.length, Math.floor(remaining / (bySize.length - index)));
381
- kept.set(group, take === 0 ? [] : group.slice(-take));
382
- remaining -= take;
383
- });
384
- return groups.flatMap((group) => kept.get(group) ?? []);
385
178
  }
@@ -1,19 +1,19 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
2
  import type { ModelRequests } from "../models/requests.js";
3
- import { type SessionSearchRole } from "./session-corpus.js";
3
+ import { type SyncStats } from "./search-index-sync.js";
4
+ import type { SessionSearchRole } from "./session-corpus.js";
4
5
  export interface SearchDeskSessionsRequest {
5
6
  channelId?: string;
6
7
  /** Attributes the optional summarization's spend to the desk. */
7
8
  desk?: string;
8
9
  /** Every conversation in this desk is searched (spec 058, D12). */
9
10
  deskDir: string;
11
+ appHomeDir: string;
10
12
  /** A human name for a conversation directory (the channel's name), for labelling results. */
11
13
  describeConversation?: (conversation: string) => string | undefined;
12
14
  query: string;
13
15
  roleFilter?: string[];
14
16
  limit: number;
15
- maxFiles: number;
16
- maxChunks: number;
17
17
  maxCharsPerChunk: number;
18
18
  summarizeWithModel: boolean;
19
19
  timeoutMs: number;
@@ -27,6 +27,7 @@ export interface SessionSearchResult {
27
27
  conversation?: string;
28
28
  channel?: string;
29
29
  when?: string;
30
+ speaker?: string;
30
31
  role: SessionSearchRole;
31
32
  score: number;
32
33
  summary: string;
@@ -39,5 +40,6 @@ export interface SessionSearchResponse {
39
40
  /** Documents whose text was itself clipped at the scan cap — a keyword past that point is not
40
41
  * findable in this corpus, so "no match" there is not proof it was never said. */
41
42
  partialDocuments: number;
43
+ index: SyncStats;
42
44
  }
43
45
  export declare function searchDeskSessions(request: SearchDeskSessionsRequest): Promise<SessionSearchResponse>;