bunnyquery 1.20.1 → 1.21.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.md +67 -10
- package/bunnyquery.css +49 -0
- package/bunnyquery.js +3907 -1555
- package/dist/engine.cjs +3822 -1497
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +1478 -701
- package/dist/engine.d.ts +1478 -701
- package/dist/engine.mjs +3805 -1494
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/citations.ts +12 -0
- package/src/engine/config.ts +91 -15
- package/src/engine/errors.ts +38 -0
- package/src/engine/history.ts +71 -11
- package/src/engine/host.ts +51 -4
- package/src/engine/index.ts +38 -9
- package/src/engine/prompts/chat_system_prompt.ts +3 -3
- package/src/engine/prompts/indexing_system_prompt.ts +3 -3
- package/src/engine/prompts/indexing_user_message.ts +20 -0
- package/src/engine/reconciler.ts +594 -0
- package/src/engine/requests.ts +97 -11
- package/src/engine/retrieval_memory.ts +21 -6
- package/src/engine/session.ts +3600 -1433
- package/src/widget.css +34 -0
- package/styles/chat.css +15 -0
- package/src/engine/findings.ts +0 -305
package/package.json
CHANGED
package/src/engine/citations.ts
CHANGED
|
@@ -74,10 +74,18 @@ export function citationsFor(note: RetrievalNote | null | undefined): Citation[]
|
|
|
74
74
|
var out: Citation[] = [];
|
|
75
75
|
var hitPaths: string[] = [];
|
|
76
76
|
var byPath: Record<string, number[]> = {};
|
|
77
|
+
// spreadsheet hits: one chip per sheet, "file · sheet", no page (a sheet page is no place to open)
|
|
78
|
+
var sheetsByPath: Record<string, string[]> = {};
|
|
77
79
|
var i: number;
|
|
78
80
|
for (i = 0; i < note.hits.length; i++) {
|
|
79
81
|
var h: RetrievalHit = note.hits[i];
|
|
80
82
|
if (!h || typeof h.path !== 'string' || !isMintablePath(h.path)) continue;
|
|
83
|
+
if (typeof h.sheet === 'string' && h.sheet) {
|
|
84
|
+
if (!byPath[h.path]) { byPath[h.path] = []; hitPaths.push(h.path); }
|
|
85
|
+
if (!sheetsByPath[h.path]) sheetsByPath[h.path] = [];
|
|
86
|
+
if (sheetsByPath[h.path].indexOf(h.sheet) === -1) sheetsByPath[h.path].push(h.sheet);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
81
89
|
var page = typeof h.page === 'number' ? h.page : Number(h.page);
|
|
82
90
|
if (!isFinite(page) || page <= 0) continue;
|
|
83
91
|
page = Math.floor(page);
|
|
@@ -86,6 +94,10 @@ export function citationsFor(note: RetrievalNote | null | undefined): Citation[]
|
|
|
86
94
|
}
|
|
87
95
|
for (i = 0; i < hitPaths.length; i++) {
|
|
88
96
|
var p = hitPaths[i];
|
|
97
|
+
var sheets = sheetsByPath[p] || [];
|
|
98
|
+
for (var sj = 0; sj < sheets.length; sj++) {
|
|
99
|
+
out.push({ path: p, label: citationFileName(p) + ' · ' + sheets[sj] });
|
|
100
|
+
}
|
|
89
101
|
var pages = byPath[p].slice().sort(function (a, b) { return a - b; });
|
|
90
102
|
for (var j = 0; j < pages.length; j++) {
|
|
91
103
|
out.push({ path: p, page: pages[j], label: citationLabel(p, pages[j]) });
|
package/src/engine/config.ts
CHANGED
|
@@ -72,7 +72,7 @@ export interface LiveStreamUpdate {
|
|
|
72
72
|
type ForwardRequestFinalizeFn = (
|
|
73
73
|
requestId: string,
|
|
74
74
|
data: any,
|
|
75
|
-
options: { url: string; method: string; service?: string; owner?: string },
|
|
75
|
+
options: { url: string; method: string; service?: string; owner?: string; ifAbsent?: boolean },
|
|
76
76
|
) => Promise<any>;
|
|
77
77
|
|
|
78
78
|
/** The chunk read-back call, identical under its new and its deprecated key. */
|
|
@@ -141,6 +141,16 @@ export interface ChatEngineConfig {
|
|
|
141
141
|
* until the worker is deployed, then flip it per environment.
|
|
142
142
|
*/
|
|
143
143
|
windowedIndexing?: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* The worker writes the ending (done:: and run::) of a file read in ONE pass (an image,
|
|
146
|
+
* or any file not rendered, windowed or paged), as it does for paged chains: the engine
|
|
147
|
+
* then no longer marks such a run "Indexing stopped ... (the page was closed)" when no
|
|
148
|
+
* page here kept its chain. The engine always sends the request flag (index_end); this
|
|
149
|
+
* switch only stops the client-side "lost" verdict. Turn it on only once every region's
|
|
150
|
+
* worker and polling-recovery Lambda carry the 2026-11-25 change: with an older worker
|
|
151
|
+
* a page closed mid-pass would leave the run 'working'. Off unless true.
|
|
152
|
+
*/
|
|
153
|
+
workerIndexEndings?: boolean;
|
|
144
154
|
/**
|
|
145
155
|
* Mint the durable "indexing finished" marker record ("done::<path>",
|
|
146
156
|
* reference "src::<path>", table __INDEXING__ — same shape the backend
|
|
@@ -151,8 +161,10 @@ export interface ChatEngineConfig {
|
|
|
151
161
|
* only ever inferred here); the worker writes their marker itself.
|
|
152
162
|
* Must be best-effort: tolerate the marker already existing and never
|
|
153
163
|
* throw. Optional so older consumers keep the pre-marker inference.
|
|
164
|
+
* May return a promise that rejects when the write failed (not for "already
|
|
165
|
+
* there"): the engine then writes it again, a few times, with backoff.
|
|
154
166
|
*/
|
|
155
|
-
mintIndexDoneMarker?: (info: { service: string; storagePath: string }) => void
|
|
167
|
+
mintIndexDoneMarker?: (info: { service: string; storagePath: string }) => void | Promise<unknown>;
|
|
156
168
|
/**
|
|
157
169
|
* Create-or-update the per-file indexing RUN record ("run::<path>",
|
|
158
170
|
* reference "src::<path>", table __INDEXING__). The record is the durable
|
|
@@ -166,7 +178,9 @@ export interface ChatEngineConfig {
|
|
|
166
178
|
* overwrite a terminal status (done/error/cancelled) — a late create from
|
|
167
179
|
* a slow enqueue must not resurrect a run another writer already closed.
|
|
168
180
|
* Must be best-effort and never throw. Optional: without it the engine
|
|
169
|
-
* behaves exactly as before (legacy scan/probe path).
|
|
181
|
+
* behaves exactly as before (legacy scan/probe path). May return a promise
|
|
182
|
+
* that rejects when the write failed: the engine then writes it again, a few
|
|
183
|
+
* times, with backoff.
|
|
170
184
|
*/
|
|
171
185
|
upsertIndexRunRecord?: (info: {
|
|
172
186
|
service: string;
|
|
@@ -179,7 +193,7 @@ export interface ChatEngineConfig {
|
|
|
179
193
|
error?: string;
|
|
180
194
|
queue?: string;
|
|
181
195
|
};
|
|
182
|
-
}) => void
|
|
196
|
+
}) => void | Promise<unknown>;
|
|
183
197
|
/**
|
|
184
198
|
* Deliver each relayed chunk over skapi's WEBSOCKET as well, so text lands as it
|
|
185
199
|
* is relayed instead of on the next poll tick. Off unless a host asks.
|
|
@@ -259,8 +273,8 @@ export interface ChatEngineConfig {
|
|
|
259
273
|
* `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
|
|
260
274
|
* (four sequential requests, about 0.6 s before the model starts).
|
|
261
275
|
*
|
|
262
|
-
* OFF unless set to `true
|
|
263
|
-
*
|
|
276
|
+
* OFF unless set to `true` (the widget and bunnyquery.com set it; verified on a live
|
|
277
|
+
* OpenAI chat 2026-11-25). An account that refuses the item fails one turn, after
|
|
264
278
|
* which reuse stays off for that project in this browser. Costs when on: each
|
|
265
279
|
* reused turn's request body, and so its stored history row, is about 31 to 34 KB
|
|
266
280
|
* larger (the tool list), which also comes back with every history page.
|
|
@@ -346,15 +360,6 @@ export interface ChatEngineConfig {
|
|
|
346
360
|
* Asked by the 10-second queue check for files still being indexed.
|
|
347
361
|
*/
|
|
348
362
|
readIndexProgress?: (service: string, storagePath: string) => Promise<{ pages_saved?: number; pages_total?: number | null } | null>;
|
|
349
|
-
/**
|
|
350
|
-
* Save one search finding (findings.ts): where a hard search found its answer, as a
|
|
351
|
-
* record in table "search_findings" with the given unique_id, tags and data, reference
|
|
352
|
-
* "src::<storagePath>" and the ACCESS GROUP OF THAT FILE (read it; skip the save when
|
|
353
|
-
* the file has no record). When the unique_id is taken, add the new tags to the existing
|
|
354
|
-
* record instead. Best effort: never throw into the engine. Optional: without it nothing
|
|
355
|
-
* is saved.
|
|
356
|
-
*/
|
|
357
|
-
saveSearchFinding?: (finding: import('./findings').SearchFinding & { service: string; owner?: string }) => Promise<any> | void;
|
|
358
363
|
/**
|
|
359
364
|
* The request ids of one file's indexing passes: the unique ids "pass::<storagePath>#<id>"
|
|
360
365
|
* the worker writes as each pass starts (getUniqueId, prefix "pass::<storagePath>#", every
|
|
@@ -363,6 +368,34 @@ export interface ChatEngineConfig {
|
|
|
363
368
|
* (ChatSession.loadRunPasses). Without it the history pages the indexing queue as before.
|
|
364
369
|
*/
|
|
365
370
|
listIndexPasses?: (service: string, storagePath: string) => Promise<string[]>;
|
|
371
|
+
/**
|
|
372
|
+
* THE RECONCILER'S READS (reconciler plan, section 3; skapi-js 2.7.0 or newer). All
|
|
373
|
+
* three are optional, and a host hands over only what its skapi-js has: with
|
|
374
|
+
* `forwardRequestStatus` AND `forwardRequestRead` the engine follows every waiting
|
|
375
|
+
* item with one batch read per look (ChatSession's reconciler) instead of one poll
|
|
376
|
+
* per request; without them it keeps today's polls, and its looks re-attach a
|
|
377
|
+
* failed poll through the old by-id read (csrHistoryItemLookup).
|
|
378
|
+
*
|
|
379
|
+
* skapi.forwardRequestStatus(requests, { service, owner, deadline, fresh, signal }):
|
|
380
|
+
* the status of up to 100 requests per call, no bodies.
|
|
381
|
+
*/
|
|
382
|
+
forwardRequestStatus?: (requests: any[], opts?: any) => Promise<{ list: any[]; [key: string]: any }>;
|
|
383
|
+
/** skapi.forwardRequestRead({ id, url, method, since, service, owner, deadline, fresh,
|
|
384
|
+
* signal }): one request as an envelope that always carries its status, with a
|
|
385
|
+
* streamed turn's chunks after `since`. Read once per item that just turned terminal. */
|
|
386
|
+
forwardRequestRead?: (params: any) => Promise<any>;
|
|
387
|
+
/** skapi.forwardRequestQueueCounters(queues, { service, owner, deadline, fresh,
|
|
388
|
+
* signal }): the tiny counter rows of up to 20 queues. Read on every look; the
|
|
389
|
+
* requests themselves are read only when a counter moved, on a trigger, or once a
|
|
390
|
+
* minute. Optional even with the two above: without it every look reads statuses. */
|
|
391
|
+
forwardRequestQueueCounters?: (queues: string[], opts?: any) => Promise<{ queues: { [name: string]: any } }>;
|
|
392
|
+
/**
|
|
393
|
+
* Ask the host to refresh what it shows of a project's records, because indexing
|
|
394
|
+
* work of that project just settled and none is left in this page's queue. A data
|
|
395
|
+
* hook: called with no chat view mounted too (the files page, the records page), and
|
|
396
|
+
* only in the tab that holds the project's settle lock. Optional; never throws.
|
|
397
|
+
*/
|
|
398
|
+
refreshRecords?: (projectId: string) => void;
|
|
366
399
|
}
|
|
367
400
|
|
|
368
401
|
let _config: ChatEngineConfig | null = null;
|
|
@@ -453,11 +486,54 @@ export function resolveForwardRequestStream(): ForwardRequestStreamFn | undefine
|
|
|
453
486
|
return typeof cfg.forwardRequestStream === 'function' ? cfg.forwardRequestStream : undefined;
|
|
454
487
|
}
|
|
455
488
|
|
|
489
|
+
/** skapi.forwardRequestStatus, or undefined (an skapi-js older than 2.7.0). Never throws. */
|
|
490
|
+
export function resolveForwardRequestStatus(): ((requests: any[], opts?: any) => Promise<any>) | undefined {
|
|
491
|
+
if (!_config || typeof _config.forwardRequestStatus !== 'function') return undefined;
|
|
492
|
+
const cfg = _config;
|
|
493
|
+
return (requests: any[], opts?: any) => cfg.forwardRequestStatus!.call(cfg, requests, opts);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** skapi.forwardRequestRead, or undefined. Never throws. */
|
|
497
|
+
export function resolveForwardRequestRead(): ((params: any) => Promise<any>) | undefined {
|
|
498
|
+
if (!_config || typeof _config.forwardRequestRead !== 'function') return undefined;
|
|
499
|
+
const cfg = _config;
|
|
500
|
+
return (params: any) => cfg.forwardRequestRead!.call(cfg, params);
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** skapi.forwardRequestQueueCounters, or undefined. Never throws. */
|
|
504
|
+
export function resolveForwardRequestQueueCounters(): ((queues: string[], opts?: any) => Promise<any>) | undefined {
|
|
505
|
+
if (!_config || typeof _config.forwardRequestQueueCounters !== 'function') return undefined;
|
|
506
|
+
const cfg = _config;
|
|
507
|
+
return (queues: string[], opts?: any) => cfg.forwardRequestQueueCounters!.call(cfg, queues, opts);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* The host handed over the reconciler's two reads (batch status and envelope read), so
|
|
512
|
+
* the engine follows waiting items with batch reads instead of one poll each. False on
|
|
513
|
+
* an older skapi-js: the engine then keeps today's polls (see forwardRequestStatus).
|
|
514
|
+
*/
|
|
515
|
+
export function reconcilerReadsEnabled(): boolean {
|
|
516
|
+
return !!resolveForwardRequestStatus() && !!resolveForwardRequestRead();
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* A send may carry a client reference (`cref`). Only with the reconciler's reads: the
|
|
521
|
+
* same skapi-js (2.7.0) brought both, and an older one drops the key anyway, so a send
|
|
522
|
+
* whose ack was lost could never be matched by it.
|
|
523
|
+
*/
|
|
524
|
+
export function crefSupported(): boolean {
|
|
525
|
+
return reconcilerReadsEnabled();
|
|
526
|
+
}
|
|
527
|
+
|
|
456
528
|
/** True when the consumer has opted in to server-driven windowed indexing. */
|
|
457
529
|
export function windowedIndexingEnabled(): boolean {
|
|
458
530
|
return _config?.windowedIndexing === true;
|
|
459
531
|
}
|
|
460
532
|
|
|
533
|
+
export function workerIndexEndingsEnabled(): boolean {
|
|
534
|
+
return _config?.workerIndexEndings === true;
|
|
535
|
+
}
|
|
536
|
+
|
|
461
537
|
/** True when the consumer has opted in to live streaming of chat turns. */
|
|
462
538
|
/** Socket delivery of the stream: the host asked (`liveStreaming`) AND the turn streams. */
|
|
463
539
|
/** Request status push is on: the host asked for it and handed over onRequestStatus. */
|
package/src/engine/errors.ts
CHANGED
|
@@ -278,3 +278,41 @@ export function isProviderApiKeyError(input: any): boolean {
|
|
|
278
278
|
hay.indexOf('invalid api key') !== -1 ||
|
|
279
279
|
hay.indexOf('no api key provided') !== -1;
|
|
280
280
|
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The server's own "that request is gone" answer to a read of it (the row was removed:
|
|
284
|
+
* cancelled while queued, or cleaned up). A fact about the request, unlike every
|
|
285
|
+
* failure isTransportFailure covers.
|
|
286
|
+
*/
|
|
287
|
+
export function isNotExistsError(err: any): boolean {
|
|
288
|
+
return !!err && typeof err === 'object' && (err.code === 'NOT_EXISTS' || (!!err.body && err.body.code === 'NOT_EXISTS'));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Codes skapi-js gives a request that failed ON THE WAY rather than because the server
|
|
292
|
+
// said no (2.7.0 types them; older builds reject with bare strings, matched below).
|
|
293
|
+
var TRANSPORT_FAILURE_CODES = ['NETWORK_ERROR', 'TIMEOUT', 'RATE_LIMITED', 'TOO_MANY_REQUESTS', 'SERVER_ERROR', 'ABORTED', 'TOKEN_REFRESH_FAILED'];
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* True when a READ of a request failed on the way: no network, no answer in time, rate
|
|
297
|
+
* limited, a server fault (5xx), an aborted read. Such a failure says nothing about the
|
|
298
|
+
* request itself, which may be running or already answered, so a caller must never
|
|
299
|
+
* turn it into an error bubble or a failed run record (reconciler plan, section 3 item 4).
|
|
300
|
+
*/
|
|
301
|
+
export function isTransportFailure(err: any): boolean {
|
|
302
|
+
if (err === undefined || err === null) return true;
|
|
303
|
+
if (typeof err === 'string') {
|
|
304
|
+
var s = err.toLowerCase();
|
|
305
|
+
return s.indexOf('network') !== -1 || s.indexOf('abort') !== -1 || s.indexOf('too many') !== -1 ||
|
|
306
|
+
s.indexOf('timeout') !== -1 || s.indexOf('timed out') !== -1 || s.indexOf('no response for') !== -1;
|
|
307
|
+
}
|
|
308
|
+
if (typeof err !== 'object') return false;
|
|
309
|
+
if (typeof TypeError !== 'undefined' && err instanceof TypeError) return true; // fetch() on the way
|
|
310
|
+
var code = err.code !== undefined && err.code !== null ? String(err.code) : '';
|
|
311
|
+
if (TRANSPORT_FAILURE_CODES.indexOf(code) !== -1) return true;
|
|
312
|
+
if (code === '429' || /^5\d\d$/.test(code)) return true;
|
|
313
|
+
var status = typeof err.status === 'number' ? err.status : (typeof err.statusCode === 'number' ? err.statusCode : 0);
|
|
314
|
+
if (status === 429 || status >= 500) return true;
|
|
315
|
+
var msg = typeof err.message === 'string' ? err.message.toLowerCase() : '';
|
|
316
|
+
return msg.indexOf('network error') !== -1 || msg.indexOf('failed to fetch') !== -1 ||
|
|
317
|
+
msg.indexOf('no response for') !== -1 || msg.indexOf('timed out') !== -1 || msg === 'aborted';
|
|
318
|
+
}
|
package/src/engine/history.ts
CHANGED
|
@@ -43,6 +43,14 @@ export function extractLastUserTextFromRequest(requestBody: any): string {
|
|
|
43
43
|
return '';
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** The last user text of a listed row: the compact stub's `request_text` when the
|
|
47
|
+
* listing was compact (the body never left the server), else read from the full
|
|
48
|
+
* request echo (a backend without compact stubs). */
|
|
49
|
+
export function listedRequestText(item: any): string {
|
|
50
|
+
if (item && typeof item.request_text === 'string') return item.request_text;
|
|
51
|
+
return extractLastUserTextFromRequest(item && item.request_body);
|
|
52
|
+
}
|
|
53
|
+
|
|
46
54
|
/** The two openings an indexing prompt can have. A bg-queue item that starts with
|
|
47
55
|
* neither is an ordinary chat that happened to be routed onto that queue. */
|
|
48
56
|
export function isIndexingRequestText(userText: any): boolean {
|
|
@@ -129,8 +137,11 @@ export function probeBgQueue(
|
|
|
129
137
|
}
|
|
130
138
|
const inflight = bgProbeInflight[key];
|
|
131
139
|
if (inflight) return inflight;
|
|
140
|
+
// compact + queue_exact: the indexing rows come back as label stubs (no request echo,
|
|
141
|
+
// which can be hundreds of KB per row) from exactly this queue's range. Every reader of
|
|
142
|
+
// this answer takes the text through listedRequestText. Older backends ignore both.
|
|
132
143
|
const p = Promise.resolve(getChatHistory(
|
|
133
|
-
{ service: params.service, owner: params.owner, platform: params.platform, queue: params.queue, status: params.status },
|
|
144
|
+
{ service: params.service, owner: params.owner, platform: params.platform, queue: params.queue, status: params.status, compact: true, queue_exact: true },
|
|
134
145
|
{ limit: params.limit, fetchMore: false },
|
|
135
146
|
)).then(function (result: any) {
|
|
136
147
|
const entry: BgProbeEntry = { result: result, at: Date.now() };
|
|
@@ -167,21 +178,28 @@ export async function fetchLiveIndexingKeys(params: {
|
|
|
167
178
|
platform: 'claude' | 'openai';
|
|
168
179
|
/** Same value the dispatch used - see bgIndexingQueueName. */
|
|
169
180
|
userId?: string;
|
|
181
|
+
}, opts?: {
|
|
182
|
+
/** Reuse a shared answer up to this old (default BG_PROBE_TTL_MS); 0 always asks. */
|
|
183
|
+
maxAgeMs?: number;
|
|
170
184
|
}): Promise<{ keys: Set<string>; checked: boolean; at: number }> {
|
|
171
185
|
const queue = bgIndexingQueueName(params.userId, params.service);
|
|
172
186
|
const base = { service: params.service, owner: params.owner, platform: params.platform, queue };
|
|
187
|
+
const maxAgeMs = opts && typeof opts.maxAgeMs === 'number' ? opts.maxAgeMs : BG_PROBE_TTL_MS;
|
|
173
188
|
const [pending, running] = await Promise.all([
|
|
174
|
-
probeBgQueue({ ...base, status: 'pending', limit: LIVE_INDEX_PROBE_LIMIT }, { maxAgeMs
|
|
175
|
-
probeBgQueue({ ...base, status: 'running', limit: LIVE_INDEX_PROBE_LIMIT }, { maxAgeMs
|
|
189
|
+
probeBgQueue({ ...base, status: 'pending', limit: LIVE_INDEX_PROBE_LIMIT }, { maxAgeMs }),
|
|
190
|
+
probeBgQueue({ ...base, status: 'running', limit: LIVE_INDEX_PROBE_LIMIT }, { maxAgeMs }),
|
|
176
191
|
]);
|
|
177
192
|
const keys = new Set<string>();
|
|
178
193
|
let truncated = false;
|
|
179
194
|
for (const entry of [pending, running]) {
|
|
180
195
|
const res = entry.result;
|
|
181
196
|
const list: any[] = (res && Array.isArray((res as any).list)) ? (res as any).list : [];
|
|
182
|
-
|
|
197
|
+
// Cut off when the page came back full OR the server says more exist: the queue
|
|
198
|
+
// filters run after the range read, so a short page can still have a cursor, and
|
|
199
|
+
// reading it as whole would show files as idle while passes remain.
|
|
200
|
+
if (list.length >= LIVE_INDEX_PROBE_LIMIT || (res && (res as any).endOfList === false)) truncated = true;
|
|
183
201
|
for (const item of list) {
|
|
184
|
-
const text =
|
|
202
|
+
const text = listedRequestText(item);
|
|
185
203
|
if (!text || !isIndexingRequestText(text)) continue;
|
|
186
204
|
const ref = parseIndexingRequestText(text);
|
|
187
205
|
if (!ref) continue;
|
|
@@ -989,6 +1007,14 @@ export function mapHistoryListToMessages(list: any[], platform: 'claude' | 'open
|
|
|
989
1007
|
export function adoptLocalAnswerIntoPage(incoming: ChatMessage, local: ChatMessage): boolean {
|
|
990
1008
|
if (!incoming || !local || !incoming._streamPending) return false;
|
|
991
1009
|
if (incoming.role !== 'assistant' || local.role !== 'assistant') return false;
|
|
1010
|
+
// AN ERROR BUBBLE IS NEVER THE ANSWER. It is this client's account of a read or a
|
|
1011
|
+
// send that went wrong ("Network error", "No response for 60 seconds."), written
|
|
1012
|
+
// by THIS client and never by the model. Adopted, it became the turn's answer for
|
|
1013
|
+
// good: the marker came off (so the real answer, still in the chunk store, was
|
|
1014
|
+
// never read back), the error flag did not come across (so it rendered as a
|
|
1015
|
+
// normal reply), and the model was handed it as its own words in every later
|
|
1016
|
+
// turn. The row's unknown answer stays unknown and the recovery reads it back.
|
|
1017
|
+
if (local.isError) return false;
|
|
992
1018
|
var hasText = typeof local.content === 'string' && local.content.length > 0;
|
|
993
1019
|
var isLive = !!(local.isPending || local._streaming);
|
|
994
1020
|
if (!hasText && !isLive) return false;
|
|
@@ -1009,6 +1035,32 @@ export function adoptLocalAnswerIntoPage(incoming: ChatMessage, local: ChatMessa
|
|
|
1009
1035
|
return true;
|
|
1010
1036
|
}
|
|
1011
1037
|
|
|
1038
|
+
/**
|
|
1039
|
+
* Keep the LIVE TEXT of a turn the page still shows as running. Mutates `incoming`;
|
|
1040
|
+
* true when it took anything.
|
|
1041
|
+
*
|
|
1042
|
+
* A running row maps to an empty "Thinking..." placeholder (the row has no body
|
|
1043
|
+
* yet), so a first-page refetch landing while an answer streams replaced the bubble
|
|
1044
|
+
* the reader was watching with an empty one. The painter only paints when the text
|
|
1045
|
+
* GROWS past what it already painted, so the bubble then sat on "Thinking..." until
|
|
1046
|
+
* a larger chunk arrived and jumped back, or, with every chunk already delivered,
|
|
1047
|
+
* stayed blank until the settle retyped the whole answer. The local copy is the same
|
|
1048
|
+
* turn (same server id), so its text and its live state come across; the settle
|
|
1049
|
+
* still replaces the text with the authoritative answer.
|
|
1050
|
+
*/
|
|
1051
|
+
export function adoptLiveTextIntoRunningRow(incoming: ChatMessage, local: ChatMessage): boolean {
|
|
1052
|
+
if (!incoming || !local) return false;
|
|
1053
|
+
if (incoming.role !== 'assistant' || local.role !== 'assistant') return false;
|
|
1054
|
+
if (!incoming.isPending || incoming.isBackgroundTask || incoming._streamPending) return false;
|
|
1055
|
+
if (local.isError || !(local.isPending || local._streaming)) return false;
|
|
1056
|
+
if (typeof local.content !== 'string' || !local.content) return false;
|
|
1057
|
+
if (typeof incoming.content === 'string' && incoming.content.length >= local.content.length) return false;
|
|
1058
|
+
incoming.content = local.content;
|
|
1059
|
+
if (local._localId !== undefined) incoming._localId = local._localId;
|
|
1060
|
+
if (local._streaming) incoming._streaming = true;
|
|
1061
|
+
return true;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1012
1064
|
/* ---- rescuing in-flight bubbles across a first-page refetch ---------------
|
|
1013
1065
|
*
|
|
1014
1066
|
* A first-page fetch REPLACES the message list, and the list may hold bubbles the
|
|
@@ -1068,19 +1120,27 @@ export function shouldRescueInFlightMessage(m: ChatMessage, ctx: RescueDecisionC
|
|
|
1068
1120
|
// the painter finds THAT one on its next paint (about a second later), and rescuing
|
|
1069
1121
|
// as well would put the same turn on screen twice.
|
|
1070
1122
|
if (m._streaming && !m._serverItemId) return true;
|
|
1123
|
+
// A send whose ack was lost while the reconciler looks for its row by cref, or one that
|
|
1124
|
+
// says "Not sent. Retry?" (reconciler plan, section 3 item 9). It has no server id, so
|
|
1125
|
+
// no page can carry a copy of it: it is kept, or its bubbles (and the Retry) vanish.
|
|
1126
|
+
if (!m._serverItemId && (m._unconfirmed || m._notSent)) return true;
|
|
1071
1127
|
if (!m._serverItemId && ctx.pageHasPendingAssistant) return false;
|
|
1072
1128
|
// In flight by its own flags, id or no id. The immediate-send pair is stamped
|
|
1073
1129
|
// with its server id as soon as the dispatch reports one, and that id is there
|
|
1074
1130
|
// to let the check above recognise the server's copy — not to disqualify the
|
|
1075
1131
|
// bubble from being kept when there is no such copy.
|
|
1076
1132
|
if (m.isSendingToServer || m.isPendingQueued || m.isPendingInProcess || m.isPending) return true;
|
|
1077
|
-
// An immediate-send user bubble carries no flags of its own
|
|
1078
|
-
//
|
|
1079
|
-
//
|
|
1080
|
-
|
|
1133
|
+
// An immediate-send user bubble carries no flags of its own; what identifies it
|
|
1134
|
+
// is its own unanswered placeholder directly below it. Before the ack that pair
|
|
1135
|
+
// has no server id and state.sending says a send is in flight. AFTER the ack
|
|
1136
|
+
// (state.sending clears there now, reconciler plan section 3 item 6) both carry
|
|
1137
|
+
// the turn's id, and the shared id is the proof: a user bubble whose placeholder
|
|
1138
|
+
// below names the same request is that request's question.
|
|
1139
|
+
if (m.role === 'user') {
|
|
1081
1140
|
var next = ctx.next;
|
|
1082
|
-
if (!next || next.isBackgroundTask || !next.isPending) return false;
|
|
1083
|
-
|
|
1141
|
+
if (!next || next.isBackgroundTask || !next.isPending || next.role !== 'assistant') return false;
|
|
1142
|
+
if (ctx.sending && (next._serverItemId === undefined || next._serverItemId === m._serverItemId)) return true;
|
|
1143
|
+
return !!m._serverItemId && next._serverItemId === m._serverItemId;
|
|
1084
1144
|
}
|
|
1085
1145
|
return false;
|
|
1086
1146
|
}
|
package/src/engine/host.ts
CHANGED
|
@@ -144,10 +144,10 @@ export interface ChatMessage {
|
|
|
144
144
|
/** PROTOCOL + PRESENTATIONAL: this bubble is being painted from a LIVE stream.
|
|
145
145
|
*
|
|
146
146
|
* It sits alongside `isPending`, never instead of it. The bubble is still the
|
|
147
|
-
* turn's "Thinking..." placeholder as far as every
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
147
|
+
* turn's "Thinking..." placeholder as far as every settle is concerned (the apply
|
|
148
|
+
* funnel, ChatSession.applyTerminal, finds a turn's waiting bubble by its server id
|
|
149
|
+
* AND isPending), and clearing that flag to mean "it has text now" would make the
|
|
150
|
+
* turn read as already answered, so its real answer would be refused.
|
|
151
151
|
* What this adds is the one thing those mechanisms do not care about and the VIEW
|
|
152
152
|
* does: `content` is already worth rendering, so draw the text instead of the
|
|
153
153
|
* spinner.
|
|
@@ -253,6 +253,16 @@ export interface ChatMessage {
|
|
|
253
253
|
// ChatSession singleton, so without this a bubble is unattributable and an
|
|
254
254
|
// in-flight turn from project A gets rescued/cached into project B.
|
|
255
255
|
_ownerKey?: string;
|
|
256
|
+
/** The client reference the turn was sent with (reconciler plan, section 3 item 9). On
|
|
257
|
+
* the user bubble of a send; a send whose ack was lost is matched to its row by it. */
|
|
258
|
+
_cref?: string;
|
|
259
|
+
/** A send whose POST got no answer while the reconciler looks for its row by `_cref`:
|
|
260
|
+
* kept through history merges until its row is found or it is "Not sent". */
|
|
261
|
+
_unconfirmed?: boolean;
|
|
262
|
+
/** A send whose POST got no answer and whose row the server never showed: the reply
|
|
263
|
+
* bubble says "Not sent. Retry?" and ChatSession.retryNotSent(msg) sends it again.
|
|
264
|
+
* Never retried on its own. */
|
|
265
|
+
_notSent?: boolean;
|
|
256
266
|
}
|
|
257
267
|
|
|
258
268
|
export interface ChatState {
|
|
@@ -309,6 +319,28 @@ export interface ChatState {
|
|
|
309
319
|
* liveIndexKeys, so a reactive consumer re-renders the moment a stop is
|
|
310
320
|
* recorded — a stop with nothing left to cancel changes no message at all. */
|
|
311
321
|
stoppedIndexIds: { [serverItemId: string]: boolean };
|
|
322
|
+
/** The reconciler's last look failed on the way (network, timeout, 429, 5xx) and it is
|
|
323
|
+
* trying again with backoff. Nothing on screen was changed by the failure; a view may
|
|
324
|
+
* show a small "Reconnecting..." note while this is true. */
|
|
325
|
+
reconnecting?: boolean;
|
|
326
|
+
/** The reconciler's reads are refused for want of a sign-in. Looks resume on the next
|
|
327
|
+
* sign-in (ChatSession.noteSignedIn); a view may say "Sign in to see the latest
|
|
328
|
+
* answers" while this is true. */
|
|
329
|
+
signInNeeded?: boolean;
|
|
330
|
+
/** The background indexing queue of a project as the reconciler last read it, for a
|
|
331
|
+
* page that shows indexing state with or without a chat view (the dashboard's files
|
|
332
|
+
* page), by project id. Filled while someone watches it (ChatSession.watchIndexQueue).
|
|
333
|
+
* `keys` holds the storage paths and file names with a pass waiting or running;
|
|
334
|
+
* `checked` is false when the read came back cut off (absence then proves nothing);
|
|
335
|
+
* `at` is when the read ran (a re-served read keeps its time, so two different `at`
|
|
336
|
+
* values are two independent looks). */
|
|
337
|
+
indexQueues?: { [projectId: string]: IndexQueueSnapshot };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export interface IndexQueueSnapshot {
|
|
341
|
+
keys: { [fileKey: string]: true };
|
|
342
|
+
checked: boolean;
|
|
343
|
+
at: number;
|
|
312
344
|
}
|
|
313
345
|
|
|
314
346
|
export interface ChatHost {
|
|
@@ -357,6 +389,21 @@ export interface ChatHost {
|
|
|
357
389
|
formatIndexingLabel(name: string, mime?: string, size?: number | null, storagePath?: string, reindex?: boolean, continued?: boolean): string;
|
|
358
390
|
/** drainBgTaskQueue is a no-op until the chat view is mounted. */
|
|
359
391
|
isViewMounted(): boolean;
|
|
392
|
+
/**
|
|
393
|
+
* Optional. Read the run:: records of these files again (reconciler plan, section 3
|
|
394
|
+
* item 1). The engine follows a file whose record says 'working' (syncFileRuns) until
|
|
395
|
+
* the record says it ended or a complete look at the queue finds no pass of it, and
|
|
396
|
+
* asks for this every 30 seconds meanwhile, while the file is not seen live. The host
|
|
397
|
+
* re-reads its records and hands the 'working' paths back through syncFileRuns.
|
|
398
|
+
*/
|
|
399
|
+
recheckFileRuns?(projectId: string, storagePaths: string[]): void;
|
|
400
|
+
/**
|
|
401
|
+
* Optional. A provider answer (or a provider error) just settled a request of this
|
|
402
|
+
* project, whichever path read it (a poll, a look, a stream). The host may judge the
|
|
403
|
+
* project's API key from it (web-bunnyquery's "Your API key is invalid"). Called once
|
|
404
|
+
* per request, after the bubble is written.
|
|
405
|
+
*/
|
|
406
|
+
onProviderAnswer?(projectId: string, platform: 'claude' | 'openai', result: any): void;
|
|
360
407
|
|
|
361
408
|
/** Clear-horizon timestamp (localStorage, per service#platform) — view-owned. */
|
|
362
409
|
getClearedAt(): number;
|
package/src/engine/index.ts
CHANGED
|
@@ -47,19 +47,33 @@ export {
|
|
|
47
47
|
// and whether status messages are arriving right now.
|
|
48
48
|
statusPushEnabled,
|
|
49
49
|
statusPushLive,
|
|
50
|
+
// The reconciler's reads (skapi-js 2.7.0): whether the host handed over the batch
|
|
51
|
+
// status and envelope reads (then items are followed by looks, not one poll each),
|
|
52
|
+
// and whether a send may carry a client reference.
|
|
53
|
+
reconcilerReadsEnabled,
|
|
54
|
+
crefSupported,
|
|
50
55
|
} from './config';
|
|
51
56
|
|
|
57
|
+
// The reconciler's clock (one timer chain per page) and the cross-tab settle lock. The
|
|
58
|
+
// session drives them; exported for diagnostics and for a host's own side effects.
|
|
59
|
+
export {
|
|
60
|
+
LookScheduler,
|
|
61
|
+
LOOK_DEADLINE_MS,
|
|
62
|
+
LOOK_FAST_MS,
|
|
63
|
+
LOOK_SLOW_MS,
|
|
64
|
+
LOOK_STALE_MS,
|
|
65
|
+
isReturnTrigger,
|
|
66
|
+
runSettleSideEffect,
|
|
67
|
+
sideEffectDone,
|
|
68
|
+
newClientRef,
|
|
69
|
+
type LookTrigger,
|
|
70
|
+
type LookRequest,
|
|
71
|
+
type LookOutcome,
|
|
72
|
+
} from './reconciler';
|
|
73
|
+
|
|
52
74
|
// "Has this user already uploaded this file here?", answered from the `src::` file
|
|
53
75
|
// records and the stored copy's indexing state. The widget wires it as the host's
|
|
54
76
|
// findDuplicateUpload hook, and www's duplicates.ts wraps it; it never throws.
|
|
55
|
-
// Saved search findings: where a hard search found its answer (findings.ts).
|
|
56
|
-
export {
|
|
57
|
-
FINDINGS_TABLE,
|
|
58
|
-
FINDING_ID_PREFIX,
|
|
59
|
-
findingsForTurn,
|
|
60
|
-
keyWords as findingKeyWords,
|
|
61
|
-
type SearchFinding,
|
|
62
|
-
} from './findings';
|
|
63
77
|
export {
|
|
64
78
|
findDuplicateUpload,
|
|
65
79
|
isDuplicateCandidateId,
|
|
@@ -117,6 +131,8 @@ export {
|
|
|
117
131
|
// was answered twice before, one of the two one level too shallow, which is how
|
|
118
132
|
// a wrong API key on a streamed turn reported "No text response received".
|
|
119
133
|
isCsrStatusEnvelope, csrEnvelopeError,
|
|
134
|
+
// A read that failed on the way vs the server's own "that request is gone".
|
|
135
|
+
isTransportFailure, isNotExistsError,
|
|
120
136
|
} from './errors';
|
|
121
137
|
export * from './budget';
|
|
122
138
|
// Retrieval memory: the per-turn note of what a chat turn read, queried or
|
|
@@ -142,6 +158,7 @@ export {
|
|
|
142
158
|
filterListByClearHorizon,
|
|
143
159
|
normalizeTextContent,
|
|
144
160
|
extractLastUserTextFromRequest,
|
|
161
|
+
listedRequestText,
|
|
145
162
|
mapHistoryListToMessages,
|
|
146
163
|
// The indexing-prompt reader. Exported because the prompt is the only record
|
|
147
164
|
// of what a pass is about, so anything that meets a pass without a bubble
|
|
@@ -159,6 +176,9 @@ export {
|
|
|
159
176
|
// unknown answer is not an empty one. Shared for the same reason the rescue
|
|
160
177
|
// rule is: a client mapper that forks it erases answers off the screen.
|
|
161
178
|
adoptLocalAnswerIntoPage,
|
|
179
|
+
// The same rule for a turn the page still shows as RUNNING: the live text the
|
|
180
|
+
// reader is watching is kept instead of being blanked until the next chunk.
|
|
181
|
+
adoptLiveTextIntoRunningRow,
|
|
162
182
|
// One bounded look at the bg-indexing queue: which files still have a live
|
|
163
183
|
// pass. The dbfile browser's "indexed" badge uses this so a file only goes
|
|
164
184
|
// green once the run is confirmed over, not when its src:: record appears.
|
|
@@ -224,8 +244,17 @@ export {
|
|
|
224
244
|
ChatSession, liveSafePrefix, typewriterResumeIndex, mayKeepStreamedAnswer,
|
|
225
245
|
streamRecoveryPhase, streamRecoveryLabels,
|
|
226
246
|
type StreamDispatchContext,
|
|
247
|
+
// The one apply funnel's types: the identity an open item is pinned to, and what
|
|
248
|
+
// a caller hands applyTerminal / onPollFailure.
|
|
249
|
+
type OpenItem, type OpenItemInit, type TerminalContext,
|
|
250
|
+
// What the reconciler writes: a send whose row never appeared ("Not sent. Retry?",
|
|
251
|
+
// ChatSession.retryNotSent) and a turn whose row is gone.
|
|
252
|
+
NOT_SENT_TEXT, REQUEST_GONE_TEXT, REQUEST_UNREACHABLE_TEXT,
|
|
253
|
+
// A page that draws indexing state from the queue, with or without a chat view
|
|
254
|
+
// (ChatSession.watchIndexQueue; the answer is in state.indexQueues).
|
|
255
|
+
type IndexQueueIdentity, type IndexQueueWatchOptions, type IndexQueueWatchHandle,
|
|
227
256
|
} from './session';
|
|
228
|
-
export type { ChatHost, ChatIdentity, ChatState, ChatMessage, IndexingFileRef, PinnedDispatchContext } from './host';
|
|
257
|
+
export type { ChatHost, ChatIdentity, ChatState, ChatMessage, IndexingFileRef, PinnedDispatchContext, IndexQueueSnapshot } from './host';
|
|
229
258
|
|
|
230
259
|
// Display transform: collapse a file's many background-indexing turns into one
|
|
231
260
|
// row, wherever they sit in the conversation. Shared so both chatboxes match.
|
|
@@ -138,8 +138,8 @@ These three rules govern every claim about the project's data. They do not limit
|
|
|
138
138
|
// triggers: check again, then one of three outcomes, and a learned link
|
|
139
139
|
// changes only on proof (correctSearchLink with page and exact quote).
|
|
140
140
|
const documentRules =
|
|
141
|
-
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of):
|
|
142
|
-
WRONG ANSWER: when the user says an answer is wrong (or sends "This answer seems wrong. Please check it again against the documents."), re-read the pages you cited and search again, passing searchText "question" = the user's ORIGINAL question that the disputed answer answered, never the complaint message itself. Then do exactly one of: correct the answer only; correct the answer and call correctSearchLink (when it is among your tools); or keep the answer and quote the text that supports it. Call correctSearchLink only with the page and an exact quote that prove it, and never change data on the user's word alone.`;
|
|
141
|
+
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): when the user NAMED a file (its file name; a document title, a quote or a code they mention is NOT a file name: searchText finds those inside the files), first find its storage path by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used, then find the page with searchText and that path. A spreadsheet's sheets are page text too: a hit names its sheet and rows, and the row itself is a record (its unique_id is the hit's row_id_prefix plus the row number); a spreadsheet indexed before 2026-11-25 has no page text, so read its rows instead (readFileContent, or its records). When they did not name a file, your FIRST call is searchText without a path: no table list, no file lookup before it. Never list or look up files (getUniqueId on "src::") to find out whether a document, quote or title exists before searching: searchText's hits name the file, and a search that finds nothing says what it could not cover. Either way follow searchText's description to the end, including asking the user once, after quick results, before it searches all files. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"), or for a hit with "sheet" THE FILE AND THE SHEET ("quote.xlsx, sheet 총괄"), never a sheet page's number; never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name. In a long file (a manual, a book), when a search of the whole file gives too many hits or none that fit, call getFileOutline and search the chapter that fits with searchText page_from and page_to. When the user asks about the content of the documents, pass searchText "question": that question in the user's own words, without names or personal details that are not about the documents. Leave "question" out for anything else.
|
|
142
|
+
WRONG ANSWER: when the user says an answer is wrong (or sends "This answer seems wrong. Please check it again against the documents."), re-read the pages you cited (for a sheet hit, the rows: by its row_id_prefix, never readFileContent on a sheet page) and search again, passing searchText "question" = the user's ORIGINAL question that the disputed answer answered, never the complaint message itself. Then do exactly one of: correct the answer only; correct the answer and call correctSearchLink (when it is among your tools); or keep the answer and quote the text that supports it. Call correctSearchLink only with the page and an exact quote that prove it, and never change data on the user's word alone.`;
|
|
143
143
|
|
|
144
144
|
// ---- Access group -----------------------------------------------------
|
|
145
145
|
// Trimmed 2026-11-23: the server's default-filling (an index or tag query auto-filled with
|
|
@@ -180,7 +180,7 @@ Scope: Only answer questions about this project and its data. Do not answer ques
|
|
|
180
180
|
Knowledge lookup: before saying you don't know, or that something isn't in the chat history, ALWAYS search this project's data with the tools: the project's data lives in its database, not in the earlier messages of this chat.
|
|
181
181
|
${groundingRules}
|
|
182
182
|
${webRule}
|
|
183
|
-
FINDING THE DATA: the database is the way in, for every kind of file.
|
|
183
|
+
FINDING THE DATA: the database is the way in, for every kind of file. A question about what the documents SAY (a procedure, a passage, a definition, how to fix or do something), or one that names a code, a number or a phrase to find (a quote no., a part no., a name), starts with searchText (DOCUMENTS below), not with getTables: the sheets of spreadsheets are in page text too. searchText finds WHICH file, sheet and row holds a value; a total, count or list over rows is still computed from the full row set (NUMBERS FROM A SPREADSHEET below). Everything else (numbers, rows, records, lists, counts, files) follows the search path in getTables' description, with one exception for this project: when getTables' one page is the whole list (end_of_list true), skip its table-name search even when no name fits: 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). Pick EVERY table that could hold the answer, not the first that fits. Read getIndexes and getTags one page each, never with fetch_all: name and tag lists can be millions of characters long and are never read whole, so when the name is not on that page, search for it with the user's words as their descriptions say. Never call getTags with neither table_name nor tag: that lists every tag of every table. Then getRecords in that table and group with the selector that matched (an index, one exact tag, or none 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>" (see the access group rule below); every later mention of a file's records means this call. Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder).
|
|
184
184
|
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, 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. A FILE TOTAL IS NOT A ROW'S TOTAL: the biggest number on a summary sheet is the whole file, not the thing asked about, so check every figure is scoped to what the question named (filter by the column that identifies it). Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
|
|
185
185
|
${documentRules}
|
|
186
186
|
${accessGroupRule}
|