bunnyquery 1.18.0 → 1.19.0
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.md +22 -16
- package/bunnyquery.css +14 -0
- package/bunnyquery.js +8818 -7335
- package/dist/engine.cjs +8518 -7380
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +458 -193
- package/dist/engine.d.ts +458 -193
- package/dist/engine.mjs +8512 -7381
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +72 -138
- package/src/engine/duplicates.ts +114 -35
- package/src/engine/findings.ts +305 -0
- package/src/engine/history.ts +27 -2
- package/src/engine/host.ts +25 -1
- package/src/engine/index.ts +15 -1
- package/src/engine/indexing_groups.ts +18 -0
- package/src/engine/prompts/chat_system_prompt.ts +2 -1
- package/src/engine/prompts/indexing_system_prompt.ts +2 -2
- package/src/engine/prompts/indexing_user_message.ts +4 -3
- package/src/engine/requests.ts +57 -3
- package/src/engine/retrieval_memory.ts +11 -0
- package/src/engine/session.ts +859 -83
- package/styles/chat.css +14 -0
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved search findings (owner, 2026-11-20): where a hard search found its answer, kept in
|
|
3
|
+
* the project's database so the same question, from anyone, later goes straight to the page.
|
|
4
|
+
*
|
|
5
|
+
* WHAT IS SAVED: the LOCATION, never the answer. One record per file page in table
|
|
6
|
+
* "search_findings", unique_id "find::<path>#p<page>", reference "src::<path>" (so a
|
|
7
|
+
* re-index or a delete of the file removes its findings through the cascade), the file's own
|
|
8
|
+
* access group (a finding is never visible to someone who cannot read the file), and tags:
|
|
9
|
+
* the key words of the question and the search terms that found the page, normalized the way
|
|
10
|
+
* every BunnyQuery tag is (tagForms). The chat reads the page again before answering, so a
|
|
11
|
+
* finding can never replay an outdated answer; it only skips the hunt.
|
|
12
|
+
*
|
|
13
|
+
* WHEN: after a chat turn that needed a real search (FINDING_MIN_TOOL_CALLS or more tool
|
|
14
|
+
* calls) and whose answer links a file that a searchText hit found on a page, or, when the
|
|
15
|
+
* turn read the file with readFileContent instead, the pages its answer cites of that file. Read from the
|
|
16
|
+
* provider body the turn already has, by the engine, so it costs no model step. Nothing is
|
|
17
|
+
* invented: no hit on a linked file, no finding. No page text and no result text is copied.
|
|
18
|
+
*
|
|
19
|
+
* The engine never writes records itself: the host's saveSearchFinding hook does (config.ts).
|
|
20
|
+
*/
|
|
21
|
+
import type { RetrievalNote } from './retrieval_memory';
|
|
22
|
+
|
|
23
|
+
export const FINDINGS_TABLE = 'search_findings';
|
|
24
|
+
export const FINDING_ID_PREFIX = 'find::';
|
|
25
|
+
/** Fewer tool calls than this was not a hard search: nothing is saved. */
|
|
26
|
+
export const FINDING_MIN_TOOL_CALLS = 3;
|
|
27
|
+
/** Findings saved from one turn at most. */
|
|
28
|
+
export const FINDING_MAX_PER_TURN = 3;
|
|
29
|
+
/** Key words taken from the question / from the search terms, each. */
|
|
30
|
+
export const FINDING_MAX_WORDS = 8;
|
|
31
|
+
/** Tags one finding record keeps when later finds add theirs. */
|
|
32
|
+
export const FINDING_MAX_TAGS = 40;
|
|
33
|
+
|
|
34
|
+
// Filler a question is phrased with, which says nothing about where the answer is.
|
|
35
|
+
const STOP_WORDS = new Set([
|
|
36
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'what', 'whats', 'which', 'who', 'where', 'when', 'how', 'why',
|
|
37
|
+
'please', 'tell', 'me', 'show', 'give', 'find', 'can', 'you', 'could', 'would', 'of', 'for', 'to', 'in',
|
|
38
|
+
'on', 'at', 'and', 'or', 'about', 'i', 'my', 'our', 'do', 'does', 'did',
|
|
39
|
+
'좀', '알려줘', '알려주세요', '알려', '줘', '주세요', '뭐야', '뭐예요', '뭔가요', '무엇', '무엇인가요', '어떻게',
|
|
40
|
+
'해줘', '해주세요', '있어', '있나요', '있어요', '어디', '어디야', '말해줘', '찾아줘', '보여줘',
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
// Same rules as the MCP's bq-indexing-shape.js, so a finding's tags match what the chat
|
|
44
|
+
// searches: NFKC, lowercase, no spaces or punctuation, plus each word of 2+ characters.
|
|
45
|
+
const WORD_SPLIT = /[\s\-_/,;|+&]+/u;
|
|
46
|
+
const NOT_KEPT = /[\s\p{P}\p{S}]+/gu;
|
|
47
|
+
|
|
48
|
+
function nfkcLower(text: string): string {
|
|
49
|
+
var s = String(text == null ? '' : text);
|
|
50
|
+
try { s = s.normalize('NFKC'); } catch (e) { /* as is */ }
|
|
51
|
+
return s.toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function normalizeTagText(text: string): string {
|
|
55
|
+
return nfkcLower(text).replace(NOT_KEPT, '');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One phrase -> its stored tags: the joined form plus each word when there are several. */
|
|
59
|
+
export function tagForms(text: string): string[] {
|
|
60
|
+
if (typeof text !== 'string') return [];
|
|
61
|
+
if (text.indexOf('::') !== -1) return [text];
|
|
62
|
+
var joined = normalizeTagText(text);
|
|
63
|
+
if (!joined) return [];
|
|
64
|
+
var words = nfkcLower(text).split(WORD_SPLIT)
|
|
65
|
+
.map(function (w) { return w.replace(NOT_KEPT, ''); })
|
|
66
|
+
.filter(function (w) { return Array.from(w).length >= 2; });
|
|
67
|
+
var out = [joined];
|
|
68
|
+
if (words.length > 1) for (var i = 0; i < words.length; i++) if (words[i] !== joined) out.push(words[i]);
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Korean endings and particles glued to a word ("누유시" = 누유 + 시, "방법을", "조치방법좀"),
|
|
73
|
+
// longest first. A tag only matches whole, so a question saying "누유" missed a finding saved
|
|
74
|
+
// as "누유시" (owner, 2026-11-21): the bare word is kept as well.
|
|
75
|
+
const KO_ENDINGS = ['에서는', '으로는', '에서', '으로', '에게', '까지', '부터', '이나', '이랑', '하고', '처럼',
|
|
76
|
+
'시', '좀', '은', '는', '이', '가', '을', '를', '의', '에', '로', '와', '과', '도', '만', '랑', '나', '요'];
|
|
77
|
+
|
|
78
|
+
/** The word without one trailing Korean ending, or '' when nothing (or too little) would be left. */
|
|
79
|
+
export function koreanStem(word: string): string {
|
|
80
|
+
if (!/[\uac00-\ud7a3]$/.test(word)) return '';
|
|
81
|
+
for (var i = 0; i < KO_ENDINGS.length; i++) {
|
|
82
|
+
var e = KO_ENDINGS[i];
|
|
83
|
+
if (word.length > e.length && word.slice(-e.length) === e) {
|
|
84
|
+
var stem = word.slice(0, -e.length);
|
|
85
|
+
return Array.from(stem).length >= 2 ? stem : '';
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The words of a question or a search term that say WHAT is looked for. */
|
|
92
|
+
export function keyWords(text: string | null | undefined): string[] {
|
|
93
|
+
if (typeof text !== 'string' || !text.trim()) return [];
|
|
94
|
+
var out: string[] = [];
|
|
95
|
+
var parts = nfkcLower(text).split(WORD_SPLIT);
|
|
96
|
+
for (var i = 0; i < parts.length && out.length < FINDING_MAX_WORDS; i++) {
|
|
97
|
+
var w = parts[i].replace(NOT_KEPT, '');
|
|
98
|
+
if (Array.from(w).length < 2 || STOP_WORDS.has(w)) continue;
|
|
99
|
+
var stem = koreanStem(w);
|
|
100
|
+
// "조치방법좀": the filler on the end says nothing, so only the stem is kept.
|
|
101
|
+
if (stem && STOP_WORDS.has(w.slice(stem.length))) w = stem, stem = '';
|
|
102
|
+
if (out.indexOf(w) === -1) out.push(w);
|
|
103
|
+
if (stem && out.indexOf(stem) === -1 && out.length < FINDING_MAX_WORDS) out.push(stem);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Page numbers an answer cites: "37쪽", "37 페이지", "page 37", "pages 37 and 53", "p. 53", "p53". */
|
|
109
|
+
export function citedPages(answer: string): number[] {
|
|
110
|
+
var out: number[] = [];
|
|
111
|
+
if (typeof answer !== 'string' || !answer) return out;
|
|
112
|
+
var add = function (n: string) { var v = Number(n); if (Number.isInteger(v) && v > 0 && v < 100000 && out.indexOf(v) === -1) out.push(v); };
|
|
113
|
+
var m: RegExpExecArray | null;
|
|
114
|
+
// A LIST before the unit counts whole: "37·53쪽", "37, 53쪽", "37 및 53쪽", "37~40쪽".
|
|
115
|
+
var after = /((?:\d{1,5}\s*(?:[·,/~\-–]|및|와|과)\s*)*\d{1,5})\s*(?:쪽|페이지|면)/g;
|
|
116
|
+
while ((m = after.exec(answer))) {
|
|
117
|
+
var nums = m[1].match(/\d{1,5}/g) || [];
|
|
118
|
+
for (var a = 0; a < nums.length; a++) add(nums[a]);
|
|
119
|
+
}
|
|
120
|
+
// And after the word: "page 37", "pages 37 and 53", "pp. 37, 53, 60", "p. 53".
|
|
121
|
+
var before = /\b(?:pages?|pp?\.?)\s*(\d{1,5}(?:\s*(?:,|and|&|-|–)\s*\d{1,5})*)/gi;
|
|
122
|
+
while ((m = before.exec(answer))) {
|
|
123
|
+
var list = m[1].match(/\d{1,5}/g) || [];
|
|
124
|
+
for (var b = 0; b < list.length; b++) add(list[b]);
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function parseJsonLoose(value: unknown): any {
|
|
130
|
+
if (typeof value !== 'string') return value;
|
|
131
|
+
try { return JSON.parse(value); } catch (e) { return null; }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** How many MCP tool calls the turn made, the searchText queries it sent and the files it read with readFileContent. */
|
|
135
|
+
export function toolCallsOf(body: any): { calls: number; queries: string[]; readPaths: string[] } {
|
|
136
|
+
var calls = 0;
|
|
137
|
+
var queries: string[] = [];
|
|
138
|
+
var readPaths: string[] = [];
|
|
139
|
+
var add = function (name: any, args: any) {
|
|
140
|
+
calls += 1;
|
|
141
|
+
if (name === 'searchText' && args && typeof args.query === 'string' && args.query.trim()) queries.push(args.query.trim());
|
|
142
|
+
if (name === 'readFileContent' && args && typeof args.path === 'string' && args.path.trim() && readPaths.indexOf(args.path.trim()) === -1) readPaths.push(args.path.trim());
|
|
143
|
+
};
|
|
144
|
+
if (body && Array.isArray(body.content)) {
|
|
145
|
+
for (var i = 0; i < body.content.length; i++) {
|
|
146
|
+
var b = body.content[i];
|
|
147
|
+
if (b && (b.type === 'mcp_tool_use' || b.type === 'tool_use')) add(b.name, b.input);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (body && Array.isArray(body.output)) {
|
|
151
|
+
for (var j = 0; j < body.output.length; j++) {
|
|
152
|
+
var o = body.output[j];
|
|
153
|
+
if (o && (o.type === 'mcp_call' || o.type === 'function_call')) add(o.name, parseJsonLoose(o.arguments) || o.arguments);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { calls: calls, queries: queries, readPaths: readPaths };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Did a getRecords on the findings table return at least one record in this turn? */
|
|
160
|
+
export function usedAFinding(body: any): boolean {
|
|
161
|
+
var returned = function (out: any): boolean {
|
|
162
|
+
var text = typeof out === 'string' ? out : (out == null ? '' : JSON.stringify(out));
|
|
163
|
+
// The result (or the MCP's envelope around it, whose content is the result as a string)
|
|
164
|
+
// names a record_id only when a record came back.
|
|
165
|
+
return text.indexOf('record_id') !== -1;
|
|
166
|
+
};
|
|
167
|
+
var isFindingsQuery = function (name: any, a: any): boolean {
|
|
168
|
+
return name === 'getRecords' && !!a && (a.table_name === FINDINGS_TABLE || a.table === FINDINGS_TABLE);
|
|
169
|
+
};
|
|
170
|
+
if (body && Array.isArray(body.output)) {
|
|
171
|
+
for (var i = 0; i < body.output.length; i++) {
|
|
172
|
+
var o = body.output[i];
|
|
173
|
+
if (o && (o.type === 'mcp_call' || o.type === 'function_call')
|
|
174
|
+
&& isFindingsQuery(o.name, parseJsonLoose(o.arguments) || o.arguments) && returned(o.output)) return true;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (body && Array.isArray(body.content)) {
|
|
178
|
+
var ids: Record<string, true> = {};
|
|
179
|
+
for (var j = 0; j < body.content.length; j++) {
|
|
180
|
+
var b = body.content[j];
|
|
181
|
+
if (b && (b.type === 'mcp_tool_use' || b.type === 'tool_use') && isFindingsQuery(b.name, b.input) && typeof b.id === 'string') ids[b.id] = true;
|
|
182
|
+
else if (b && (b.type === 'mcp_tool_result' || b.type === 'tool_result') && ids[b.tool_use_id] && !b.is_error && returned(b.content)) return true;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export type SearchFinding = {
|
|
189
|
+
storagePath: string;
|
|
190
|
+
page: number;
|
|
191
|
+
uniqueId: string;
|
|
192
|
+
tags: string[];
|
|
193
|
+
data: {
|
|
194
|
+
path: string;
|
|
195
|
+
page: number;
|
|
196
|
+
question_words: string[];
|
|
197
|
+
search_terms: string[];
|
|
198
|
+
found_at: number;
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The findings one finished chat turn earns, or [] (see the file comment for the rules).
|
|
204
|
+
* `note` is the turn's retrieval note (its searchText hits and the files its answer links).
|
|
205
|
+
*/
|
|
206
|
+
export function findingsForTurn(args: {
|
|
207
|
+
question: string | null | undefined;
|
|
208
|
+
body: any;
|
|
209
|
+
note: RetrievalNote | null | undefined;
|
|
210
|
+
answer: string | null | undefined;
|
|
211
|
+
now?: number;
|
|
212
|
+
}): SearchFinding[] {
|
|
213
|
+
var note = args.note;
|
|
214
|
+
if (!note) return [];
|
|
215
|
+
var tc = toolCallsOf(args.body);
|
|
216
|
+
if (tc.calls < FINDING_MIN_TOOL_CALLS) return [];
|
|
217
|
+
// A turn that answered from a saved finding is not a new one. Every turn LOOKS (the
|
|
218
|
+
// prompt checks findings first), so only a lookup that RETURNED a finding counts.
|
|
219
|
+
if (usedAFinding(args.body)) return [];
|
|
220
|
+
var answer = typeof args.answer === 'string' ? args.answer : '';
|
|
221
|
+
var linked = function (path: string): boolean {
|
|
222
|
+
if (!answer) return false;
|
|
223
|
+
if (answer.indexOf('db:' + path) !== -1) return true;
|
|
224
|
+
var name = path.split('/').pop() || path;
|
|
225
|
+
return answer.indexOf(name) !== -1;
|
|
226
|
+
};
|
|
227
|
+
var questionWords = keyWords(args.question);
|
|
228
|
+
var searchWords: string[] = [];
|
|
229
|
+
for (var q = 0; q < tc.queries.length; q++) {
|
|
230
|
+
var ws = keyWords(tc.queries[q]);
|
|
231
|
+
for (var k = 0; k < ws.length && searchWords.length < FINDING_MAX_WORDS; k++) {
|
|
232
|
+
if (searchWords.indexOf(ws[k]) === -1) searchWords.push(ws[k]);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (!questionWords.length && !searchWords.length) return [];
|
|
236
|
+
var tags: string[] = [];
|
|
237
|
+
var addTags = function (list: string[]) {
|
|
238
|
+
for (var i = 0; i < list.length; i++) {
|
|
239
|
+
var forms = tagForms(list[i]);
|
|
240
|
+
for (var f = 0; f < forms.length; f++) if (tags.indexOf(forms[f]) === -1 && tags.length < FINDING_MAX_TAGS) tags.push(forms[f]);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
addTags(questionWords);
|
|
244
|
+
addTags(searchWords);
|
|
245
|
+
// The pages the ANSWER cites ("37쪽", "page 37", "p. 53"): only those become findings.
|
|
246
|
+
// An answer that names no page keeps only the best hit of a linked file.
|
|
247
|
+
var cited = citedPages(answer);
|
|
248
|
+
var out: SearchFinding[] = [];
|
|
249
|
+
var seen: Record<string, true> = {};
|
|
250
|
+
var make = function (path: string, page: number): SearchFinding {
|
|
251
|
+
return {
|
|
252
|
+
storagePath: path,
|
|
253
|
+
page: page,
|
|
254
|
+
uniqueId: FINDING_ID_PREFIX + path + '#p' + page,
|
|
255
|
+
tags: tags.slice(),
|
|
256
|
+
data: {
|
|
257
|
+
path: path,
|
|
258
|
+
page: page,
|
|
259
|
+
question_words: questionWords,
|
|
260
|
+
search_terms: searchWords,
|
|
261
|
+
found_at: typeof args.now === 'number' ? args.now : Date.now(),
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
};
|
|
265
|
+
var hitsList = Array.isArray(note.hits) ? note.hits : [];
|
|
266
|
+
for (var h = 0; h < hitsList.length && out.length < FINDING_MAX_PER_TURN; h++) {
|
|
267
|
+
var hit = hitsList[h];
|
|
268
|
+
if (!hit || typeof hit.path !== 'string' || !hit.path || typeof hit.page !== 'number') continue;
|
|
269
|
+
if (!linked(hit.path)) continue;
|
|
270
|
+
if (cited.length ? cited.indexOf(hit.page) === -1 : out.length > 0) continue;
|
|
271
|
+
var id = FINDING_ID_PREFIX + hit.path + '#p' + hit.page;
|
|
272
|
+
if (seen[id]) continue;
|
|
273
|
+
seen[id] = true;
|
|
274
|
+
out.push({
|
|
275
|
+
storagePath: hit.path,
|
|
276
|
+
page: hit.page,
|
|
277
|
+
uniqueId: id,
|
|
278
|
+
tags: tags.slice(),
|
|
279
|
+
data: {
|
|
280
|
+
path: hit.path,
|
|
281
|
+
page: hit.page,
|
|
282
|
+
question_words: questionWords,
|
|
283
|
+
search_terms: searchWords,
|
|
284
|
+
found_at: typeof args.now === 'number' ? args.now : Date.now(),
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
// A turn that READ the file (readFileContent) instead of searching it, e.g. a file whose
|
|
289
|
+
// page text was not searchable (owner, 2026-11-21): the pages its answer cites of a file it
|
|
290
|
+
// read and links are where the answer is. Only cited pages: a read covers a window of pages,
|
|
291
|
+
// and without a page number there is no location to save.
|
|
292
|
+
if (!out.length && cited.length) {
|
|
293
|
+
for (var r = 0; r < tc.readPaths.length && out.length < FINDING_MAX_PER_TURN; r++) {
|
|
294
|
+
var rp = tc.readPaths[r];
|
|
295
|
+
if (!linked(rp)) continue;
|
|
296
|
+
for (var c = 0; c < cited.length && out.length < FINDING_MAX_PER_TURN; c++) {
|
|
297
|
+
var rid = FINDING_ID_PREFIX + rp + '#p' + cited[c];
|
|
298
|
+
if (seen[rid]) continue;
|
|
299
|
+
seen[rid] = true;
|
|
300
|
+
out.push(make(rp, cited[c]));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
package/src/engine/history.ts
CHANGED
|
@@ -352,6 +352,14 @@ export async function getSplitChatHistory(
|
|
|
352
352
|
* are non-confidential by construction.
|
|
353
353
|
*/
|
|
354
354
|
scopeSurfaceToQueue?: boolean;
|
|
355
|
+
/**
|
|
356
|
+
* CHATS ONLY (owner, 2026-11-21): fetch the conversation and NOT the background
|
|
357
|
+
* indexing queue. A file's indexing passes are listed from its own pass records when
|
|
358
|
+
* its row is opened (ChatSession.loadRunPasses), and its row comes from the run::
|
|
359
|
+
* record, so the history pager never walks the indexing queue: reaching the first
|
|
360
|
+
* chat message is the end of history.
|
|
361
|
+
*/
|
|
362
|
+
skipBg?: boolean;
|
|
355
363
|
},
|
|
356
364
|
fetchOptions: Record<string, any>,
|
|
357
365
|
/** Test seam: replaces getChatHistory. Not for production callers. */
|
|
@@ -401,6 +409,14 @@ async function _getSplitChatHistoryLocked(
|
|
|
401
409
|
* are non-confidential by construction.
|
|
402
410
|
*/
|
|
403
411
|
scopeSurfaceToQueue?: boolean;
|
|
412
|
+
/**
|
|
413
|
+
* CHATS ONLY (owner, 2026-11-21): fetch the conversation and NOT the background
|
|
414
|
+
* indexing queue. A file's indexing passes are listed from its own pass records when
|
|
415
|
+
* its row is opened (ChatSession.loadRunPasses), and its row comes from the run::
|
|
416
|
+
* record, so the history pager never walks the indexing queue: reaching the first
|
|
417
|
+
* chat message is the end of history.
|
|
418
|
+
*/
|
|
419
|
+
skipBg?: boolean;
|
|
404
420
|
},
|
|
405
421
|
fetchOptions: Record<string, any>,
|
|
406
422
|
releaseLock: () => void,
|
|
@@ -451,6 +467,13 @@ async function _getSplitChatHistoryLocked(
|
|
|
451
467
|
}
|
|
452
468
|
}
|
|
453
469
|
const state = splitHistoryStates[key];
|
|
470
|
+
// CHATS ONLY: the indexing queue counts as walked, so no bg page is ever fetched and the
|
|
471
|
+
// end of history is the end of the conversation (see params.skipBg).
|
|
472
|
+
const skipBg = !!params.skipBg;
|
|
473
|
+
if (skipBg) {
|
|
474
|
+
state.bgEnd = true;
|
|
475
|
+
state.bgBuffer = [];
|
|
476
|
+
}
|
|
454
477
|
|
|
455
478
|
// A held page fetched under the OTHER mode is not this call's page —
|
|
456
479
|
// discard it rather than replay page 1 as an "older" page (or vice versa).
|
|
@@ -491,7 +514,7 @@ async function _getSplitChatHistoryLocked(
|
|
|
491
514
|
// The caller paints the CONVERSATION from this return immediately; the
|
|
492
515
|
// stub fetch happens behind the resolved promise, under the same lock.
|
|
493
516
|
// Anything already buffered ships now (it costs nothing).
|
|
494
|
-
if (fetchOptions && fetchOptions.deferBg && (!state.bgEnd || headRefresh)) {
|
|
517
|
+
if (fetchOptions && fetchOptions.deferBg && !skipBg && (!state.bgEnd || headRefresh)) {
|
|
495
518
|
const surfaceList0 = state.surfaceCarry.length ? state.surfaceCarry.concat(surface.list) : surface.list.slice();
|
|
496
519
|
state.surfaceCarry = [];
|
|
497
520
|
const emitNow: any[] = surfaceList0.concat(state.bgBuffer);
|
|
@@ -575,7 +598,9 @@ async function _getSplitChatHistoryLocked(
|
|
|
575
598
|
const boundary = surface.endOfList ? -Infinity : oldestCreated(surfaceList);
|
|
576
599
|
|
|
577
600
|
// ── bg coverage ─────────────────────────────────────────────────────────
|
|
578
|
-
if (
|
|
601
|
+
if (skipBg) {
|
|
602
|
+
// Chats only: nothing of the indexing queue is read.
|
|
603
|
+
} else if (headRefresh) {
|
|
579
604
|
// Non-deferred head refresh: the same single HEAD page the deferred
|
|
580
605
|
// branch fetches, under the same rules — new settles are caught, the
|
|
581
606
|
// end-knowledge (bgEnd/bgStarted) is left untouched, EXCEPT when a full
|
package/src/engine/host.ts
CHANGED
|
@@ -273,6 +273,15 @@ export interface ChatState {
|
|
|
273
273
|
historyStartKeyHistory: string[];
|
|
274
274
|
historyRequestToken: number;
|
|
275
275
|
gateRefreshToken: number;
|
|
276
|
+
/** Saved pages of each document being indexed, by storage path (owner, 2026-11-20):
|
|
277
|
+
* `saved` of `total` pages, read from the MCP's prog::<path> record by the 10-second
|
|
278
|
+
* queue check (config readIndexProgress). Only files with passes still tracked are
|
|
279
|
+
* refreshed; a row shows it while the file is indexing. */
|
|
280
|
+
indexPageProgress?: { [storagePath: string]: { saved: number; total: number | null; at: number } };
|
|
281
|
+
/** Per-file paging of a run's passes loaded on demand (ChatSession.loadRunPasses), by
|
|
282
|
+
* storage path: every pass id the file has (newest first), how many are on screen,
|
|
283
|
+
* whether a load is in flight, and whether the oldest one is loaded. */
|
|
284
|
+
passPaging?: { [storagePath: string]: { ids: string[]; loaded: number; loading: boolean; done: boolean; error?: string } };
|
|
276
285
|
/** Files the SERVER still has unresolved indexing work for, by the key a
|
|
277
286
|
* collapsed row uses (storage path, else filename). Lives on the state rather
|
|
278
287
|
* than privately so a reactive consumer re-renders when it changes. */
|
|
@@ -281,6 +290,9 @@ export interface ChatState {
|
|
|
281
290
|
* means "we have not found out", which the display layer reads as still
|
|
282
291
|
* working — never as an all-clear. */
|
|
283
292
|
liveIndexChecked: boolean;
|
|
293
|
+
/** The files of liveIndexKeys that have a pass RUNNING, same keys. A live file missing
|
|
294
|
+
* here only has passes waiting: its row says "Queued". */
|
|
295
|
+
liveIndexRunning?: { [fileKey: string]: boolean };
|
|
284
296
|
/** Server item ids of the indexing passes that existed — on the row, or on the
|
|
285
297
|
* bg queue — when the user STOPPED that file. Two readers, one fact:
|
|
286
298
|
* buildChatDisplayList reports the run as stopped when it holds any of them
|
|
@@ -368,7 +380,19 @@ export interface ChatHost {
|
|
|
368
380
|
* reference target that exists. Optional: a host without it keeps the old behaviour, where
|
|
369
381
|
* whichever pass got there first created the record and the others hoped it had.
|
|
370
382
|
*/
|
|
371
|
-
ensureFileIndexRecord?(storagePath: string, meta?: { name?: string; mime?: string; size?: number }): Promise<any>;
|
|
383
|
+
ensureFileIndexRecord?(storagePath: string, meta?: { name?: string; mime?: string; size?: number }, accessGroup?: 'public' | 'authorized' | 'private'): Promise<any>;
|
|
384
|
+
/**
|
|
385
|
+
* The access group a file's EXISTING "src::" record is at, or null when it has
|
|
386
|
+
* none (never indexed). Read by the engine BEFORE it deletes that record for a
|
|
387
|
+
* re-index or an overwrite: re-indexing a file is not a decision about who may
|
|
388
|
+
* read it, so the file keeps its group, and it is then passed to
|
|
389
|
+
* ensureFileIndexRecord as `accessGroup` and used for the indexing prompt
|
|
390
|
+
* instead of asking uploadAccessGroup (which may prompt again, or apply a
|
|
391
|
+
* changed project default and declassify a private file). Optional; a host
|
|
392
|
+
* without it re-decides the group as before. Should reject (not answer null)
|
|
393
|
+
* when the record could not be read, so a read failure never re-classifies.
|
|
394
|
+
*/
|
|
395
|
+
readFileAccessGroup?(storagePath: string): Promise<'public' | 'authorized' | 'private' | null>;
|
|
372
396
|
/**
|
|
373
397
|
* The access group this file's records must be written at: the uploader's
|
|
374
398
|
* choice, which is the project default or a per-upload answer.
|
package/src/engine/index.ts
CHANGED
|
@@ -42,13 +42,25 @@ export {
|
|
|
42
42
|
} from './config';
|
|
43
43
|
|
|
44
44
|
// "Has this user already uploaded this file here?", answered from the `src::` file
|
|
45
|
-
// records. The widget wires it as the host's
|
|
45
|
+
// records and the stored copy's indexing state. The widget wires it as the host's
|
|
46
|
+
// findDuplicateUpload hook, and www's duplicates.ts wraps it; it never throws.
|
|
47
|
+
// Saved search findings: where a hard search found its answer (findings.ts).
|
|
48
|
+
export {
|
|
49
|
+
FINDINGS_TABLE,
|
|
50
|
+
FINDING_ID_PREFIX,
|
|
51
|
+
findingsForTurn,
|
|
52
|
+
keyWords as findingKeyWords,
|
|
53
|
+
type SearchFinding,
|
|
54
|
+
} from './findings';
|
|
46
55
|
export {
|
|
47
56
|
findDuplicateUpload,
|
|
48
57
|
isDuplicateCandidateId,
|
|
49
58
|
DUPLICATE_LOOKUP_MAX_CANDIDATES,
|
|
59
|
+
DUPLICATE_LOOKUP_TIMEOUT_MS,
|
|
60
|
+
DUPLICATE_LOOKUP_LIMIT,
|
|
50
61
|
type DuplicateUploadMatch,
|
|
51
62
|
type DuplicateUploadFile,
|
|
63
|
+
type StoredCopyIndexing,
|
|
52
64
|
} from './duplicates';
|
|
53
65
|
|
|
54
66
|
export {
|
|
@@ -232,6 +244,8 @@ export {
|
|
|
232
244
|
isBgIndexingQueue,
|
|
233
245
|
indexDoneUniqueId,
|
|
234
246
|
runIndexUniqueId,
|
|
247
|
+
resetFileIndexOnServer,
|
|
248
|
+
type IndexResetResult,
|
|
235
249
|
upsertIndexRunRecordSafe,
|
|
236
250
|
type IndexRunStatus,
|
|
237
251
|
type IndexRunPatch,
|
|
@@ -219,6 +219,8 @@ export type IndexingGroup = {
|
|
|
219
219
|
stub?: boolean;
|
|
220
220
|
/** The run:: record's stored error text, for a stub row's meta line. */
|
|
221
221
|
stubError?: string;
|
|
222
|
+
/** A run:: row that is live with no pass running yet: waiting in the queue. */
|
|
223
|
+
queued?: boolean;
|
|
222
224
|
};
|
|
223
225
|
|
|
224
226
|
export type DisplayEntry =
|
|
@@ -243,6 +245,10 @@ export type BuildDisplayListOptions = {
|
|
|
243
245
|
/** Whether `liveIndexKeys` has been answered at least once for this chat. False
|
|
244
246
|
* is "we do not know", and a worker-driven run stays unfinished on it. */
|
|
245
247
|
liveIndexChecked?: boolean;
|
|
248
|
+
/** Files of liveIndexKeys with a pass RUNNING (same keys). A live run:: row whose file
|
|
249
|
+
* is missing here has only waiting passes and is marked `queued`. Absent: unknown, and
|
|
250
|
+
* no row is marked. */
|
|
251
|
+
liveIndexRunningKeys?: { [fileKey: string]: boolean };
|
|
246
252
|
/** Files carrying the durable done:: completion marker (one prefix sweep),
|
|
247
253
|
* keyed like IndexingGroup.key (storage path; the bare-name fallback keys
|
|
248
254
|
* of very old prompts simply never match — they keep the queue inference).
|
|
@@ -885,6 +891,15 @@ export function buildChatDisplayList(
|
|
|
885
891
|
} else {
|
|
886
892
|
grp.resolving = false;
|
|
887
893
|
}
|
|
894
|
+
// Waiting, not working: the queue holds this file's next pass but none of its passes
|
|
895
|
+
// is running (files of one project take turns). Only on the queue's own word, both
|
|
896
|
+
// halves of it: live, and not among the running.
|
|
897
|
+
var runningNow = opts && opts.liveIndexRunningKeys;
|
|
898
|
+
if (runningNow && !grp.finished && !grp.resolving && grp.status === 'active'
|
|
899
|
+
&& (liveIndexKeys[grp.key] || (grp.path && liveIndexKeys[grp.path]))
|
|
900
|
+
&& !runningNow[grp.key] && !(grp.path && runningNow[grp.path]) && !(grp.name && runningNow[grp.name])) {
|
|
901
|
+
grp.queued = true;
|
|
902
|
+
}
|
|
888
903
|
}
|
|
889
904
|
|
|
890
905
|
// --- superseded runs -------------------------------------------------------
|
|
@@ -935,6 +950,7 @@ export function buildChatDisplayList(
|
|
|
935
950
|
else if (cg.key) coveredPaths[canonIndexKey(cg.key)] = true;
|
|
936
951
|
}
|
|
937
952
|
var now = opts && typeof opts.now === 'number' ? opts.now : Date.now();
|
|
953
|
+
var runningKeys = opts && opts.liveIndexRunningKeys;
|
|
938
954
|
var stubClearedAt = (opts && typeof opts.stubClearedAt === 'number' && opts.stubClearedAt > 0)
|
|
939
955
|
? opts.stubClearedAt : 0;
|
|
940
956
|
for (var sp in runStubs) {
|
|
@@ -1046,6 +1062,8 @@ export function buildChatDisplayList(
|
|
|
1046
1062
|
resolving: res,
|
|
1047
1063
|
resolvingReason: reason,
|
|
1048
1064
|
stub: true,
|
|
1065
|
+
queued: live && !!runningKeys
|
|
1066
|
+
&& !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : undefined,
|
|
1049
1067
|
stubError: rec.error || (st === 'error' && !rec.error
|
|
1050
1068
|
? 'Indexing did not finish.' : undefined),
|
|
1051
1069
|
};
|
|
@@ -127,7 +127,8 @@ You are a dedicated assistant for the project ID: "${projectId}".
|
|
|
127
127
|
Scope: Only answer questions about this project and its data. Do not answer questions about other projects or topics unrelated to this project. When the user refers to "my database", "my data", or "my files", treat those as references to this project's database and file storage. The ONE exception is BunnyQuery itself - what this app is, what it can do, and how to use it - which is always in scope: answer it from the "About BunnyQuery" section at the end of this prompt.
|
|
128
128
|
Knowledge lookup: Before saying you don't know or that something isn't in the chat history, ALWAYS query this project's database through the available MCP tools to look for the answer. The user's data is the source of truth - the chat transcript is not. Only respond with "I don't know" or "I couldn't find that" after you have actually searched the project's data and come back empty.
|
|
129
129
|
${groundingRules}
|
|
130
|
-
|
|
130
|
+
SAVED FINDINGS FIRST: where an earlier search found an answer is saved in table "search_findings" (one record per file page; its tags are the key words of the question that led there and of the search terms, stored lowercase without spaces). Before any other search, call getRecords with table_name "search_findings", access_group ${indexGroupLiteral} and tags set to ONE specific key word of the question (a name or a term, in the user's words; when nothing comes back, try one more word, or the word in the documents' language). A finding gives data.path and data.page: read THAT page (searchText with that path and the question's words) and answer from the page itself, quoting and citing it as usual. A finding is only a pointer, never the answer: when its page does not answer the question, or nothing is found, search as below.
|
|
131
|
+
FINDING THE DATA: the database is the way in, for every kind of file. Step 1, getTables (one page). ONLY when the list runs past that page (end_of_list false), search the table names with the words the user used, BOTH ways: condition "gte" (begins with) and condition "lte" (ends with), instead of listing them all. When the list is complete, never search table names: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Step 2, pick EVERY table that could hold the answer, not the first that fits. Step 3, in each of those tables, getIndexes and getTags (one page each, never fetch_all) to learn the exact index names and tag values; when that page does not show the name or the list runs past it, search both ways with the user's words: getTags with table_name and condition "gte", and again with "lte"; getIndexes with order {by: "index_name", value: <the words>, condition: "gte"} and again with "lte". Name and tag lists can be millions of characters long and are never read whole. Never call getTags with neither table_name nor tag: that lists every tag of every table. Step 4, getRecords in that table and group with the selector that matched: an index (string values take "gte" for begins with and "lte" for ends with), one exact tag, or no selector for the whole table, always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>". TAGS are stored lowercase without spaces or punctuation, plus one tag per word: search a tag as one word ("leak") or as the joined phrase ("oilleak"); the server also normalizes the tag you send. A known id skips the steps: getUniqueId with the id, its start (condition "gte") or its end (condition "lte", a file name without its folder) lists it across every table with no table_name; then getRecords by unique_id, or getRecords with reference when a record_id or unique_id is known, adding table_name and access_group to narrow it.
|
|
131
132
|
NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set (fetch_all true, or page until pagination.complete is true), keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
|
|
132
133
|
A FILE TOTAL IS NOT A ROW'S TOTAL. The biggest number on a summary sheet is the whole file, not the thing that was asked about. Before quoting any figure, check it is scoped to what the question named: filter by the column that identifies it and report how many rows matched.
|
|
133
134
|
${documentRules}
|
|
@@ -47,11 +47,11 @@ export function buildIndexingSystemPrompt(params: IndexingSystemPromptParams): s
|
|
|
47
47
|
- ONE RECORD PER GRID ROW, ALWAYS. "Row" means the numbered row of the sheet (R37 is one record), never a visual block, item, section or left/right pair. Sheets that repeat the same columns side by side (an A/B block beside a C/D block, "paired" or "mirrored" layouts) still get ONE record per grid row, holding BOTH sides - suffix the keys to keep them apart (PART_NO_A / PART_NO_B). Collapsing a 16-row window into 2 or 3 "block" records is the single most damaging mistake here: it silently loses most of the cells and makes every later total wrong, because some windows were counted per row and others per block. If a window shows rows R37 to R52, you save records for R37..R52 and the count you report is the number of grid rows you actually wrote.
|
|
48
48
|
- THE FILE NAME AND ITS FOLDERS ARE EVIDENCE ABOUT WHAT THE DATA MEANS, and often the only evidence there is. A grid of bare figures filed under "2026/Q2/royalties" is a quarterly royalty settlement; the same grid under "inspections/KCG-B507" is one aircraft's inspection. Nothing inside the sheet says so. Read the trail in the metadata block and use it: name the period, the entity, the counterparty or the subject in the file record's description, and TAG the records with the meaningful parts of it (the client, the aircraft, the quarter, the site), so a later question about that entity finds this file at all. A folder that is only an id or a date is still worth a tag; a folder like "uploads", "new" or "temp" is not.
|
|
49
49
|
- BUT NEVER INSTEAD OF READING. The path tells you what the data is ABOUT; only the content tells you what it SAYS. Never infer a value, a column meaning, a row count or a total from a name, never let a name override what the cells actually contain, and never derive a TABLE name from a folder or a file name - table names are fixed (see below), and a table named after a folder scatters one kind of record across as many tables as the user has folders. Where the name and the content disagree, the content wins and the disagreement is worth recording.
|
|
50
|
-
- FIXED TABLE NAMES. Never invent a table name for one pass, and never vary the name between passes of the SAME file: that scatters one file's data across tables nobody can enumerate later, so the data is effectively lost even though every save succeeded. Use exactly "spreadsheet_rows" for spreadsheet row records, "book_chapters" for a chapter record, "email_messages" for an email message record (see EMAIL below),
|
|
50
|
+
- FIXED TABLE NAMES. Never invent a table name for one pass, and never vary the name between passes of the SAME file: that scatters one file's data across tables nobody can enumerate later, so the data is effectively lost even though every save succeeded. Use exactly "spreadsheet_rows" for spreadsheet row records, "book_chapters" for a chapter record, "email_messages" for an email message record (see EMAIL below), "file_summaries" for the file-level record (which already exists, so update it and never post it), and "document_entries" for EVERYTHING you take from a document's pages or sections (a PDF, a Word file, slides, a scan, a web page, an attachment's prose): one record per row / table entry / line item / section, with "page" (the DOCUMENT PAGE number, when the content has pages) and "kind" (row, entry, section, figure or note) in its data. Embedded photos and other embedded files get NO table of your choosing: their records already exist in table "__MEDIA__", see EXTRACTED MEDIA below. There is NO other table: content that fits none of the above goes to "document_entries" too. Never choose a table name of your own (inspection_items / item_records / manual_page_entries / pdf_pages are names for what is one table): the passes of one file run side by side and cannot agree on a name, and the server stores a post to any other table in "document_entries" anyway. TAGS are stored normalized by the server (lowercase, no spaces or punctuation, plus one tag per word): write each tag naturally, one concept per tag, and never try to vary its spelling or case.
|
|
51
51
|
- EXTRACTED MEDIA: every PICTURE embedded in an uploaded document (photos, diagrams, chart images) is pulled out and saved as a real permanent file under "__MEDIA__/<the document's storage path>/<name>", and a record for each one ALREADY EXISTS in table "__MEDIA__" with unique_id "src::<that path>", reference "src::<the document>", and its path, anchor and sheet already in data. Do NOT create it - the unique_id is taken and your post is rejected. UPDATE it with updateRecords, addressed by that unique_id, adding what the file actually SHOWS plus TAGS for every identifier visible in it (part numbers, tag ids, item names, serial numbers). An update REPLACES the fields you send, so send the existing tags back with your new ones and keep every field already in data (path, anchor, sheet, source, mime, bytes). ONE FILE, ONE RECORD: never also create a photo record in another table. If the update reports that the record does not exist, create it with that same unique_id, reference and data.path - the path must never be lost. Audio and video clips and non-picture attachments are never saved as separate files (an email's attachment text is read inline instead, see EMAIL below), so never claim a separate file or a "__MEDIA__" record exists for one of those.
|
|
52
52
|
- AUDIO files: transcribe the speech, and capture speakers (named where identifiable), the topics discussed, and timestamps of key moments in the record's data. TAG the language, the audio type (call, meeting, dictation, music), each speaker and every named entity; INDEX the duration in seconds as duration_seconds. VIDEO files: everything audio gets, PLUS transcribe on-screen text verbatim (same transcription discipline as photos) and capture the visual timeline - scene changes and what each scene shows, with timestamps. Same tags as audio plus every entity visible on screen, and INDEX duration_seconds here too. These audio and video rules apply to files UPLOADED AS FILES: the transcript and timeline land on the file's own "src::" record, which already exists. Audio or video embedded inside a document is NOT extracted, so never look for or promise a "__MEDIA__" record for it.
|
|
53
53
|
- EPUB / e-books / long-form books (.epub or any book-length prose, provided inline in reading order with chapter headings preserved): you MUST save ONE record per CHAPTER (or, when chapters are unclear, per major section/topic) in the table "book_chapters" - never collapse the whole book into a single record. INDEX each chapter record on its chapter number (so chapters sort and range-query in order) and include the chapter title among its tags; the record's "data" must capture the chapter title plus its order/number AND a substantive summary of that chapter's content (key events, arguments, characters, places, concepts, terms, notable quotes). Apply AS MANY relevant tags as possible to EVERY chapter record (characters, locations, themes, topics, key concepts, key terms, dates, named entities) so the book is easy to SEARCH and cross-reference later - this is the whole point. ALSO put the book-level facts (title, author, language, overall summary, chapter list / table of contents, genre/subjects) onto the "src::" file record that ALREADY EXISTS in "file_summaries", using updateRecords. Do NOT post a second book-level record, and set every chapter record's reference to exactly "src::" + the storage path. This per-chapter completeness OVERRIDES brevity; human-readable summaries only, never raw/binary bytes.
|
|
54
|
-
- EMAIL (.eml, provided inline with "=== EMAIL ===" / "=== BODY ===" / "=== ATTACHMENT i/N: ..." / "=== FORWARDED MESSAGE k (depth d) ===" headings, which always start at column 0; a body line that merely looks like one is body text): you MUST save ONE record per email MESSAGE in the table "email_messages", and a forwarded message inside it (its own "=== EMAIL ===" block) gets its OWN record. Each record carries subject, from, to, cc, date (the Date line: an ISO string when the layer could parse it, otherwise the raw header text), message_id, in_reply_to, and the body text (quoted earlier replies included). INDEX each record on its date as that string exactly as given, and include the sender address, every recipient address and the subject among its tags. Text under an "=== ATTACHMENT" heading is that attachment's extracted content: datafy it by its own kind (rows into "spreadsheet_rows" for a spreadsheet, one record per section for a document), tag those records with the attachment's filename, and give EVERY record the same "src::" reference as the email. Picture attachments are extracted into "__MEDIA__" like any other embedded picture (their media anchor is quoted on the "[picture ...]" line); other attachments are read inline: their content becomes the records above, but no separate FILE or file record exists for one, so never cite a path for it.
|
|
54
|
+
- EMAIL (.eml, provided inline with "=== EMAIL ===" / "=== BODY ===" / "=== ATTACHMENT i/N: ..." / "=== FORWARDED MESSAGE k (depth d) ===" headings, which always start at column 0; a body line that merely looks like one is body text): you MUST save ONE record per email MESSAGE in the table "email_messages", and a forwarded message inside it (its own "=== EMAIL ===" block) gets its OWN record. Each record carries subject, from, to, cc, date (the Date line: an ISO string when the layer could parse it, otherwise the raw header text), message_id, in_reply_to, and the body text (quoted earlier replies included). INDEX each record on its date as that string exactly as given, and include the sender address, every recipient address and the subject among its tags. Text under an "=== ATTACHMENT" heading is that attachment's extracted content: datafy it by its own kind (rows into "spreadsheet_rows" for a spreadsheet, one record per section in "document_entries" for a document), tag those records with the attachment's filename, and give EVERY record the same "src::" reference as the email. Picture attachments are extracted into "__MEDIA__" like any other embedded picture (their media anchor is quoted on the "[picture ...]" line); other attachments are read inline: their content becomes the records above, but no separate FILE or file record exists for one, so never cite a path for it.
|
|
55
55
|
- URL SOURCES: when the source being indexed is a URL rather than an uploaded file (a temporary or signed URL that merely DELIVERS an uploaded file's bytes is not a URL source; that file keeps its storage-path identity), its identity is "src::" + the FULL URL INCLUDING the query string (the query string often selects the content, so dropping it collapses different pages into one identity). If no record with that unique_id exists, create it; if the slot is already taken, update that record or reference it - never mint a variant id. For a WEB PAGE: extract everything on it, infer the page's primary entity type when it is not obvious (product, listing, article, profile), TAG that entity type plus the entities on the page, and INDEX the ONE number every entity of that type can be compared by (a price for a product, a date for an article). Any OTHER URL (a file behind a link) is downloaded and indexed under whichever per-type rule above matches its content. When the URL's content offers more index points than one record carries, add reference-linked records reachable from its "src::" record.
|
|
56
56
|
- This is a background indexing task: do ALL the MCP saving FIRST, never reply mid-task, and never ask the user questions. Be exhaustive about meaning (and, for tabular data, about every row). SAVE AS YOU GO: persist each window's records before reading the next, so progress is never lost. If the file is so large you cannot finish in one turn, still save everything you have read so far; a follow-up pass will automatically continue from where you stopped. NEVER store raw or encoded file bytes in ANY field: no base64, no data: URIs, no hex or blob dumps. A long opaque non-human-readable string is not data - replace it with a structured description of what it encodes. If base64 or a data: URI is all you have for something, describe it conceptually and never paste it; if nothing human-readable can be extracted at all, OMIT that record rather than saving noise.
|
|
57
57
|
- COMPLETION SIGNAL: only when YOU paged the file yourself with readFileContent and it reported "END OF FILE", with every row/item saved, end your final message with the token INDEXING_COMPLETE on its own line. If more rows remain, do NOT write that token - leaving it out is how the system knows to run another pass to continue. When the file arrives INSIDE this message one window at a time (an embedded window of rows/text, or rendered PDF page images), you are NOT the one who decides it is finished: the system advances the window off the real page/row count and sends the next pass automatically, so save this window, report what you saved, and never imply you have seen the whole file.
|
|
@@ -145,7 +145,7 @@ export function buildIndexingUserMessage(
|
|
|
145
145
|
head +
|
|
146
146
|
`\nRead this file with the readFileContent tool, using the storage path above - do NOT fetch a URL and do NOT rely on a single sample. ` +
|
|
147
147
|
`readFileContent returns the file ONE WINDOW at a time: spreadsheets as coordinate-tagged grid rows (e.g. 'R4 A:E&I NUMBER | B:E1007'), scanned/large PDFs as rendered PAGE IMAGES, and windows may include embedded photos - LOOK at any images and datafy what they show. ` +
|
|
148
|
-
`Page through EVERY window: for each window SAVE records for its rows/items/pages (postRecords, one record per row/item), THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed. ` +
|
|
148
|
+
`Page through EVERY window: for each window SAVE records for its rows/items/pages (postRecords, one record per row/item; spreadsheet rows in "spreadsheet_rows", everything else in "document_entries"), THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed. ` +
|
|
149
149
|
`Do NOT stop after the first window and do NOT just write a summary. Set every record's reference to exactly "src::" + the storage path above; that file record already exists, so enrich it with updateRecords instead of posting it again.` +
|
|
150
150
|
(attachment.url ? `\n(A temporary URL is provided ONLY as a fallback if readFileContent fails: ${attachment.url})` : '')
|
|
151
151
|
);
|
|
@@ -264,7 +264,8 @@ function buildRenderDatafy(placeholder: string): string {
|
|
|
264
264
|
return (
|
|
265
265
|
`\n${placeholder}\n\n` +
|
|
266
266
|
`LOOK at each rendered page image in this message and DATAFY what it shows: for EVERY page ` +
|
|
267
|
-
`call postRecords and save records
|
|
267
|
+
`call postRecords and save records in table "document_entries", with "page" set to the DOCUMENT PAGE number ` +
|
|
268
|
+
`from the page's label - one record per row / table entry / line item visible on the page ` +
|
|
268
269
|
`(or one record for the page if it is prose), capturing every value you can read (OCR the text, read tables ` +
|
|
269
270
|
`cell by cell, describe any photos/diagrams). Set EVERY record's reference to exactly "src::" + the storage path above. That file record ALREADY EXISTS, so do NOT post it, and do NOT give your page records a "src::" unique_id of their own. A record with no reference back to it is an ORPHAN: re-indexing the file deletes the linked records and leaves the orphan behind forever as stale data.\n\n` +
|
|
270
271
|
`Each image is preceded by a label giving its DOCUMENT PAGE number. That label is the page's identity - ` +
|
|
@@ -317,7 +318,7 @@ export function buildIndexingWindowMessage(
|
|
|
317
318
|
where +
|
|
318
319
|
`\n${placeholder}\n\n` +
|
|
319
320
|
`DATAFY this window: call postRecords and save records for everything in it - ONE RECORD PER ROW ` +
|
|
320
|
-
`for tabular data (keyed by the column headers), or one record per section for prose. Capture every ` +
|
|
321
|
+
`for tabular data (keyed by the column headers), or one record per section for prose in table "document_entries". Capture every ` +
|
|
321
322
|
`value you can read. The file-level record ALREADY EXISTS with unique_id "src::" + the storage path above: do NOT post it (a duplicate unique_id is rejected), enrich it with updateRecords, ` +
|
|
322
323
|
`and link every row/section record to it by reference.\n\n` +
|
|
323
324
|
`If this window has PHOTOS attached as images, LOOK at each one and datafy what it actually shows. ` +
|