@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.
- package/README.en.md +2 -2
- package/README.md +2 -2
- package/dist/agent/channel-runner.js +2 -0
- package/dist/agent/maintenance-context.js +21 -2
- package/dist/agent/turn/turn-context.js +10 -6
- package/dist/config/settings.d.ts +0 -2
- package/dist/config/settings.js +0 -2
- package/dist/config/tools.d.ts +8 -2
- package/dist/config/tools.js +35 -19
- package/dist/memory/anchors.d.ts +5 -0
- package/dist/memory/anchors.js +49 -0
- package/dist/memory/boundary-work.d.ts +1 -0
- package/dist/memory/boundary-work.js +1 -0
- package/dist/memory/commands.js +23 -6
- package/dist/memory/index-budget.d.ts +16 -0
- package/dist/memory/index-budget.js +24 -2
- package/dist/memory/journal.d.ts +7 -12
- package/dist/memory/journal.js +9 -41
- package/dist/memory/lifecycle.d.ts +1 -0
- package/dist/memory/lifecycle.js +2 -0
- package/dist/memory/reflect-job.d.ts +1 -0
- package/dist/memory/reflect-job.js +1 -0
- package/dist/memory/reflect.d.ts +10 -0
- package/dist/memory/reflect.js +103 -20
- package/dist/memory/render.d.ts +4 -1
- package/dist/memory/render.js +6 -4
- package/dist/memory/review-log.d.ts +2 -2
- package/dist/memory/scheduler.d.ts +7 -0
- package/dist/memory/scheduler.js +70 -3
- package/dist/memory/search-index-db.d.ts +15 -0
- package/dist/memory/search-index-db.js +247 -0
- package/dist/memory/search-index-files.d.ts +11 -0
- package/dist/memory/search-index-files.js +26 -0
- package/dist/memory/search-index-notes.d.ts +11 -0
- package/dist/memory/search-index-notes.js +155 -0
- package/dist/memory/search-index-sync.d.ts +19 -0
- package/dist/memory/search-index-sync.js +267 -0
- package/dist/memory/search-terms.d.ts +12 -0
- package/dist/memory/search-terms.js +185 -0
- package/dist/memory/search.d.ts +8 -28
- package/dist/memory/search.js +18 -278
- package/dist/memory/session-corpus.d.ts +15 -26
- package/dist/memory/session-corpus.js +120 -327
- package/dist/memory/session-search.d.ts +5 -3
- package/dist/memory/session-search.js +119 -171
- package/dist/memory/sidecar-worker.d.ts +2 -0
- package/dist/memory/sidecar-worker.js +25 -1
- package/dist/memory/store.d.ts +4 -0
- package/dist/memory/store.js +22 -1
- package/dist/memory/task-archive-digest.d.ts +61 -0
- package/dist/memory/task-archive-digest.js +366 -0
- package/dist/models/provider-login.d.ts +1 -1
- package/dist/models/provider-login.js +1 -1
- package/dist/playbooks/memory-operations.md +2 -2
- package/dist/shared/text-utils.d.ts +0 -1
- package/dist/shared/text-utils.js +0 -1
- package/dist/subagents/runs.d.ts +1 -1
- package/dist/subagents/task-envelope.js +6 -8
- package/dist/tools/memory-manage.d.ts +1 -0
- package/dist/tools/memory-manage.js +9 -23
- package/dist/tools/registry.js +2 -0
- package/dist/tools/session-search.d.ts +1 -0
- package/dist/tools/session-search.js +12 -6
- package/dist/tools/web-search.d.ts +13 -7
- package/dist/tools/web-search.js +62 -19
- package/dist/web/client.d.ts +2 -0
- package/dist/web/client.js +7 -3
- package/dist/web/config.d.ts +17 -4
- package/dist/web/config.js +42 -4
- package/dist/web/format.d.ts +2 -1
- package/dist/web/format.js +7 -3
- package/dist/web/search-providers.d.ts +15 -8
- package/dist/web/search-providers.js +208 -139
- package/dist/web/search.d.ts +13 -3
- package/dist/web/search.js +86 -40
- package/package.json +1 -1
- package/dist/memory/chinese-words.d.ts +0 -1
- package/dist/memory/chinese-words.js +0 -273
|
@@ -1,43 +1,21 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
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
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
|
|
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
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
|
113
|
-
if (!isRecord(value))
|
|
80
|
+
export function parseTranscriptLine(source, value) {
|
|
81
|
+
if (!isRecord(value))
|
|
114
82
|
return null;
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
|
162
|
-
if (!
|
|
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
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
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
|
-
|
|
199
|
-
|
|
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
|
-
|
|
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
|
-
|
|
268
|
-
|
|
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
|
-
|
|
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
|
|
322
|
-
|
|
323
|
-
|
|
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
|
-
|
|
352
|
-
|
|
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
|
|
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>;
|