bunnyquery 1.19.0 → 1.19.2
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 +31 -0
- package/bunnyquery.css +15 -0
- package/bunnyquery.js +521 -173
- package/dist/engine.cjs +501 -193
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +5188 -5051
- package/dist/engine.d.ts +5188 -5051
- package/dist/engine.mjs +491 -194
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +27 -1
- package/src/engine/host.ts +6 -0
- package/src/engine/index.ts +19 -0
- package/src/engine/indexing_groups.ts +46 -4
- package/src/engine/project_settings.ts +71 -0
- package/src/engine/prompts/chat_system_prompt.ts +77 -24
- package/src/engine/requests.ts +249 -4
- package/src/engine/session.ts +138 -20
- package/src/widget.css +15 -0
package/package.json
CHANGED
package/src/engine/config.ts
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
import { type AttachmentParser, registerAttachmentParser } from './attachment_parsers';
|
|
23
|
-
import { cachedProjectSettings, loadProjectSettings, webAccessFrom, skipDuplicateFilesFrom } from './project_settings';
|
|
23
|
+
import { cachedProjectSettings, loadProjectSettings, webAccessFrom, skipDuplicateFilesFrom, answerModeFrom, type AnswerMode } from './project_settings';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* One report about a turn that is streaming, as handed to `onLiveStreamUpdate`.
|
|
@@ -232,6 +232,20 @@ export interface ChatEngineConfig {
|
|
|
232
232
|
* them; `true` or unset follows the project. See duplicates.ts for the check.
|
|
233
233
|
*/
|
|
234
234
|
skipDuplicateFiles?: boolean;
|
|
235
|
+
/**
|
|
236
|
+
* Reuse the MCP tool listing OpenAI returned on an earlier CHAT turn of this page
|
|
237
|
+
* (OpenAI only). With it, the next chat request carries OpenAI's own
|
|
238
|
+
* `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
|
|
239
|
+
* (four sequential requests, about 0.6 s before the model starts).
|
|
240
|
+
*
|
|
241
|
+
* OFF unless set to `true`. Leave it off until one real OpenAI chat on a dev project
|
|
242
|
+
* has answered with it on: an account that refuses the item fails one turn, after
|
|
243
|
+
* which reuse stays off for that project in this browser. Costs when on: each
|
|
244
|
+
* reused turn's request body, and so its stored history row, is about 31 to 34 KB
|
|
245
|
+
* larger (the tool list), which also comes back with every history page.
|
|
246
|
+
* Claude turns and indexing passes never use it. See requests.ts ChatTurnContext.
|
|
247
|
+
*/
|
|
248
|
+
reuseMcpToolList?: boolean;
|
|
235
249
|
/**
|
|
236
250
|
* skapi.forwardRequestFinalize, bound to the consumer's skapi instance.
|
|
237
251
|
* Stores the version of a streamed turn that history should keep (the engine
|
|
@@ -486,6 +500,18 @@ export function resolveWebAccess(service?: string, override?: boolean): Promise<
|
|
|
486
500
|
.then((setting) => underCeiling(setting, opt, override));
|
|
487
501
|
}
|
|
488
502
|
|
|
503
|
+
/**
|
|
504
|
+
* The project's answer mode for a chat turn, awaiting its settings record so the
|
|
505
|
+
* first turn after a page load reads the stored value (same reason as
|
|
506
|
+
* resolveWebAccess). Never rejects: a failed or impossible read settles as
|
|
507
|
+
* 'standard', which adds nothing to the request. There is no host option: the
|
|
508
|
+
* mode is the project owner's choice. See project_settings.ts AnswerMode.
|
|
509
|
+
*/
|
|
510
|
+
export function resolveAnswerMode(service?: string): Promise<AnswerMode> {
|
|
511
|
+
if (!service) return Promise.resolve(answerModeFrom(null));
|
|
512
|
+
return loadProjectSettings(service).then(answerModeFrom, () => answerModeFrom(null));
|
|
513
|
+
}
|
|
514
|
+
|
|
489
515
|
/**
|
|
490
516
|
* The skip-duplicates switch for an upload, SYNCHRONOUSLY: the project's cached
|
|
491
517
|
* `skip_duplicate_files` setting (on unless the owner turned it off), restricted
|
package/src/engine/host.ts
CHANGED
|
@@ -293,6 +293,12 @@ export interface ChatState {
|
|
|
293
293
|
/** The files of liveIndexKeys that have a pass RUNNING, same keys. A live file missing
|
|
294
294
|
* here only has passes waiting: its row says "Queued". */
|
|
295
295
|
liveIndexRunning?: { [fileKey: string]: boolean };
|
|
296
|
+
/** The running half of the last look came back whole (see liveIndexRunning), even when
|
|
297
|
+
* the pending half did not: a file with an open run that is not running is waiting. */
|
|
298
|
+
liveIndexRunningChecked?: boolean;
|
|
299
|
+
/** Files a complete look saw leave the queue, kept until they are live again (same keys
|
|
300
|
+
* as liveIndexKeys). The display reads them like done:: markers. */
|
|
301
|
+
liveIndexSettled?: { [fileKey: string]: boolean };
|
|
296
302
|
/** Server item ids of the indexing passes that existed — on the row, or on the
|
|
297
303
|
* bg queue — when the user STOPPED that file. Two readers, one fact:
|
|
298
304
|
* buildChatDisplayList reports the run as stopped when it holds any of them
|
package/src/engine/index.ts
CHANGED
|
@@ -34,6 +34,10 @@ export {
|
|
|
34
34
|
// template; the awaiting form is what the request builders use.
|
|
35
35
|
webAccessEnabled,
|
|
36
36
|
resolveWebAccess,
|
|
37
|
+
// The project's chat answer mode ('standard' | 'fast' | 'thorough'), awaited the
|
|
38
|
+
// same way. What the request builders read; exported for a host that wants to
|
|
39
|
+
// show the mode a turn will use.
|
|
40
|
+
resolveAnswerMode,
|
|
37
41
|
// Same ceiling rule for the upload path's skip-duplicates switch: the project's
|
|
38
42
|
// `skip_duplicate_files` setting (on by default), restricted by a host's
|
|
39
43
|
// `skipDuplicateFiles: false`.
|
|
@@ -261,6 +265,10 @@ export {
|
|
|
261
265
|
callClaudeWithMcp,
|
|
262
266
|
callClaudeWithPublicMcp,
|
|
263
267
|
callOpenAIWithPublicMcp,
|
|
268
|
+
// The answer mode's request fields for one provider and model: {} for 'standard'
|
|
269
|
+
// and for a model that does not take effort, else reasoning / output_config.
|
|
270
|
+
chatEffortFields,
|
|
271
|
+
type ChatTurnContext,
|
|
264
272
|
notifyAgentSaveAttachment,
|
|
265
273
|
listClaudeModels,
|
|
266
274
|
listOpenAIModels,
|
|
@@ -320,6 +328,16 @@ export {
|
|
|
320
328
|
normalizeSkipDuplicateFiles,
|
|
321
329
|
skipDuplicateFilesFrom,
|
|
322
330
|
projectSkipDuplicateFiles,
|
|
331
|
+
// chat answer mode (same record, its own `answer_mode` key, standard by default)
|
|
332
|
+
ANSWER_MODES,
|
|
333
|
+
DEFAULT_ANSWER_MODE,
|
|
334
|
+
ANSWER_MODE_SETTING_LABEL,
|
|
335
|
+
ANSWER_MODE_LABELS,
|
|
336
|
+
ANSWER_MODE_HINTS,
|
|
337
|
+
ANSWER_MODE_OPTIONS,
|
|
338
|
+
normalizeAnswerMode,
|
|
339
|
+
answerModeFrom,
|
|
340
|
+
projectAnswerMode,
|
|
323
341
|
// pure readers over a settings `data` object
|
|
324
342
|
normalizeUploadAccessGroup,
|
|
325
343
|
normalizeProjectAccessSetting,
|
|
@@ -344,4 +362,5 @@ export {
|
|
|
344
362
|
type ProjectAccessSetting,
|
|
345
363
|
type ProjectSettingsData,
|
|
346
364
|
type ProjectSettingsReader,
|
|
365
|
+
type AnswerMode,
|
|
347
366
|
} from './project_settings';
|
|
@@ -249,6 +249,11 @@ export type BuildDisplayListOptions = {
|
|
|
249
249
|
* is missing here has only waiting passes and is marked `queued`. Absent: unknown, and
|
|
250
250
|
* no row is marked. */
|
|
251
251
|
liveIndexRunningKeys?: { [fileKey: string]: boolean };
|
|
252
|
+
/** The running half of the queue look is complete (liveIndexRunningChecked). With the
|
|
253
|
+
* pending half cut off (liveIndexChecked false), a file whose run:: record is still
|
|
254
|
+
* 'working' and that is not running is waiting: its row says "Queued" instead of
|
|
255
|
+
* "Fetching status" until the queue is small enough to list whole. */
|
|
256
|
+
liveIndexRunningChecked?: boolean;
|
|
252
257
|
/** Files carrying the durable done:: completion marker (one prefix sweep),
|
|
253
258
|
* keyed like IndexingGroup.key (storage path; the bare-name fallback keys
|
|
254
259
|
* of very old prompts simply never match — they keep the queue inference).
|
|
@@ -888,6 +893,16 @@ export function buildChatDisplayList(
|
|
|
888
893
|
// thing here that is actually known.
|
|
889
894
|
grp.resolving = true;
|
|
890
895
|
grp.resolvingReason = 'status';
|
|
896
|
+
// Same reading as a run:: row's: the running half is whole and this file is
|
|
897
|
+
// not in it, while its run record says the run is open, so it is waiting.
|
|
898
|
+
var openRun = opts && opts.runStubs && ((grp.path && opts.runStubs[grp.path]) || opts.runStubs[grp.key]);
|
|
899
|
+
var runNow = opts && opts.liveIndexRunningKeys;
|
|
900
|
+
if (opts && opts.liveIndexRunningChecked && openRun && openRun.status === 'working' && runNow
|
|
901
|
+
&& !runNow[grp.key] && !(grp.path && runNow[grp.path]) && !(grp.name && runNow[grp.name])) {
|
|
902
|
+
grp.resolving = false;
|
|
903
|
+
grp.resolvingReason = undefined;
|
|
904
|
+
grp.queued = true;
|
|
905
|
+
}
|
|
891
906
|
} else {
|
|
892
907
|
grp.resolving = false;
|
|
893
908
|
}
|
|
@@ -896,9 +911,30 @@ export function buildChatDisplayList(
|
|
|
896
911
|
// halves of it: live, and not among the running.
|
|
897
912
|
var runningNow = opts && opts.liveIndexRunningKeys;
|
|
898
913
|
if (runningNow && !grp.finished && !grp.resolving && grp.status === 'active'
|
|
899
|
-
&& (liveIndexKeys[grp.key] || (grp.path && liveIndexKeys[grp.path]))
|
|
900
914
|
&& !runningNow[grp.key] && !(grp.path && runningNow[grp.path]) && !(grp.name && runningNow[grp.name])) {
|
|
901
|
-
|
|
915
|
+
// A file sent a moment ago is not in the last look yet, and the engine guesses
|
|
916
|
+
// its first pass is running. One project's files index one at a time, so when
|
|
917
|
+
// the look shows ANOTHER file running, this one is waiting whatever the guess.
|
|
918
|
+
var otherRunning = false;
|
|
919
|
+
if (opts && opts.liveIndexRunningChecked) {
|
|
920
|
+
for (var rk in runningNow) {
|
|
921
|
+
if (runningNow[rk] && rk !== grp.key && rk !== grp.path && rk !== grp.name) { otherRunning = true; break; }
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
// And a file whose run is open (its run:: record) that the WHOLE running list does
|
|
925
|
+
// not hold: it is waiting, even when the pending list was cut off before it.
|
|
926
|
+
var openRun2 = opts && opts.runStubs && ((grp.path && opts.runStubs[grp.path]) || opts.runStubs[grp.key]);
|
|
927
|
+
var waitingOpenRun = !!(opts && opts.liveIndexRunningChecked && openRun2 && openRun2.status === 'working');
|
|
928
|
+
// Only before the run has done anything: a file with a FINISHED pass is mid-run.
|
|
929
|
+
// Between two of its own passes it is briefly not running, and the look can still
|
|
930
|
+
// hold the pass that just ended; calling that "Queued" next to its saved pages read
|
|
931
|
+
// as going backwards.
|
|
932
|
+
var startedRun = false;
|
|
933
|
+
for (var mi = 0; mi < grp.members.length; mi++) {
|
|
934
|
+
var mm = grp.members[mi].msg;
|
|
935
|
+
if (mm && mm.role === 'assistant' && !mm.isPending && !mm.isPendingInProcess && !mm.isPendingQueued) { startedRun = true; break; }
|
|
936
|
+
}
|
|
937
|
+
if (!startedRun && (liveIndexKeys[grp.key] || (grp.path && liveIndexKeys[grp.path]) || otherRunning || waitingOpenRun)) grp.queued = true;
|
|
902
938
|
}
|
|
903
939
|
}
|
|
904
940
|
|
|
@@ -951,6 +987,7 @@ export function buildChatDisplayList(
|
|
|
951
987
|
}
|
|
952
988
|
var now = opts && typeof opts.now === 'number' ? opts.now : Date.now();
|
|
953
989
|
var runningKeys = opts && opts.liveIndexRunningKeys;
|
|
990
|
+
var runningChecked = !!(opts && opts.liveIndexRunningChecked);
|
|
954
991
|
var stubClearedAt = (opts && typeof opts.stubClearedAt === 'number' && opts.stubClearedAt > 0)
|
|
955
992
|
? opts.stubClearedAt : 0;
|
|
956
993
|
for (var sp in runStubs) {
|
|
@@ -1005,6 +1042,7 @@ export function buildChatDisplayList(
|
|
|
1005
1042
|
var st: IndexingGroupStatus = 'active';
|
|
1006
1043
|
var fin = false;
|
|
1007
1044
|
var res = false;
|
|
1045
|
+
var waitingStub = false;
|
|
1008
1046
|
var reason: 'history' | 'status' | undefined;
|
|
1009
1047
|
if (!live) {
|
|
1010
1048
|
// A done:: marker from the same sweep is as terminal as the record's
|
|
@@ -1026,6 +1064,10 @@ export function buildChatDisplayList(
|
|
|
1026
1064
|
// Older than any real run and still unconfirmed: a dead claim, not
|
|
1027
1065
|
// an open question. Same horizon the files page applies.
|
|
1028
1066
|
st = 'error'; fin = true;
|
|
1067
|
+
} else if (runningChecked && rec.status === 'working') {
|
|
1068
|
+
// The pending half was cut off, the running half was not, and this
|
|
1069
|
+
// file is not running: it is waiting behind the files that are.
|
|
1070
|
+
waitingStub = true;
|
|
1029
1071
|
} else {
|
|
1030
1072
|
// Genuinely unanswered — the queue reply is one round trip away
|
|
1031
1073
|
// and this self-heals the moment it lands.
|
|
@@ -1062,8 +1104,8 @@ export function buildChatDisplayList(
|
|
|
1062
1104
|
resolving: res,
|
|
1063
1105
|
resolvingReason: reason,
|
|
1064
1106
|
stub: true,
|
|
1065
|
-
queued: live && !!runningKeys
|
|
1066
|
-
&& !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : undefined,
|
|
1107
|
+
queued: waitingStub || (live && !!runningKeys
|
|
1108
|
+
&& !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname]) ? true : undefined,
|
|
1067
1109
|
stubError: rec.error || (st === 'error' && !rec.error
|
|
1068
1110
|
? 'Indexing did not finish.' : undefined),
|
|
1069
1111
|
};
|
|
@@ -97,6 +97,7 @@ export type ProjectSettingsData = {
|
|
|
97
97
|
chat_greeting?: unknown;
|
|
98
98
|
web_access?: unknown;
|
|
99
99
|
skip_duplicate_files?: unknown;
|
|
100
|
+
answer_mode?: unknown;
|
|
100
101
|
[key: string]: unknown;
|
|
101
102
|
};
|
|
102
103
|
|
|
@@ -160,6 +161,66 @@ export function skipDuplicateFilesFrom(data: ProjectSettingsData | null | undefi
|
|
|
160
161
|
return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
|
|
161
162
|
}
|
|
162
163
|
|
|
164
|
+
/**
|
|
165
|
+
* How much the model thinks before a CHAT answer. Same record, its own
|
|
166
|
+
* `answer_mode` key. Optional, and absent on almost every project.
|
|
167
|
+
*
|
|
168
|
+
* 'standard' the provider's own default. NOTHING is added to the request: a
|
|
169
|
+
* project that never opens the setting sends byte for byte the
|
|
170
|
+
* request it sent before the setting existed.
|
|
171
|
+
* 'fast' effort "low": fewer reasoning tokens and fewer tool round trips,
|
|
172
|
+
* so a simple question comes back sooner.
|
|
173
|
+
* 'thorough' effort "high": more reasoning before the answer, for questions
|
|
174
|
+
* that need several reads to get right.
|
|
175
|
+
*
|
|
176
|
+
* Only the literal 'fast' or 'thorough' changes anything. This record is public
|
|
177
|
+
* and a client must never act on a value it did not write, so every other value
|
|
178
|
+
* (absent, a typo, a number) reads as 'standard'.
|
|
179
|
+
*
|
|
180
|
+
* Applied where the chat request is built (config.ts resolveAnswerMode, then
|
|
181
|
+
* requests.ts chatEffortFields): OpenAI `reasoning.effort` and Claude
|
|
182
|
+
* `output_config.effort`, and only on models known to accept the field. A model
|
|
183
|
+
* that does not is sent no field at all, as if the mode were 'standard'.
|
|
184
|
+
* Indexing passes never read this setting.
|
|
185
|
+
*/
|
|
186
|
+
export type AnswerMode = 'standard' | 'fast' | 'thorough';
|
|
187
|
+
|
|
188
|
+
export const ANSWER_MODES: AnswerMode[] = ['standard', 'fast', 'thorough'];
|
|
189
|
+
|
|
190
|
+
export const DEFAULT_ANSWER_MODE: AnswerMode = 'standard';
|
|
191
|
+
|
|
192
|
+
/** The setting's own name, for a settings page heading or row label. */
|
|
193
|
+
export const ANSWER_MODE_SETTING_LABEL = 'Answer mode';
|
|
194
|
+
|
|
195
|
+
export const ANSWER_MODE_LABELS: Record<AnswerMode, string> = {
|
|
196
|
+
standard: 'Standard',
|
|
197
|
+
fast: 'Fast',
|
|
198
|
+
thorough: 'Thorough',
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
export const ANSWER_MODE_HINTS: Record<AnswerMode, string> = {
|
|
202
|
+
standard: 'The AI model decides how long to think. This is the default.',
|
|
203
|
+
fast: 'Shorter thinking for quicker answers. Best for simple questions.',
|
|
204
|
+
thorough: 'Longer thinking before answering. Slower, and uses more tokens.',
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** Menu option list, in the order it should be shown. */
|
|
208
|
+
export const ANSWER_MODE_OPTIONS = ANSWER_MODES.map((value) => ({
|
|
209
|
+
value,
|
|
210
|
+
label: ANSWER_MODE_LABELS[value],
|
|
211
|
+
hint: ANSWER_MODE_HINTS[value],
|
|
212
|
+
}));
|
|
213
|
+
|
|
214
|
+
/** Narrow a stored value to a mode: only 'fast' and 'thorough' are not standard. */
|
|
215
|
+
export function normalizeAnswerMode(value: any): AnswerMode {
|
|
216
|
+
return value === 'fast' || value === 'thorough' ? value : DEFAULT_ANSWER_MODE;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The mode held in a settings-record `data`, 'standard' when unset. */
|
|
220
|
+
export function answerModeFrom(data: ProjectSettingsData | null | undefined): AnswerMode {
|
|
221
|
+
return normalizeAnswerMode(data ? data.answer_mode : undefined);
|
|
222
|
+
}
|
|
223
|
+
|
|
163
224
|
/**
|
|
164
225
|
* Longest custom opening line the dashboard will store.
|
|
165
226
|
*
|
|
@@ -395,6 +456,16 @@ export function projectSkipDuplicateFiles(service: string): boolean {
|
|
|
395
456
|
return skipDuplicateFilesFrom(cachedProjectSettings(service));
|
|
396
457
|
}
|
|
397
458
|
|
|
459
|
+
/**
|
|
460
|
+
* Sync convenience: the project's answer mode, 'standard' until the fetch
|
|
461
|
+
* settles or when the project never set it. The request builders use the
|
|
462
|
+
* awaiting form (config.ts resolveAnswerMode) so the first turn after a page
|
|
463
|
+
* load reads the stored value.
|
|
464
|
+
*/
|
|
465
|
+
export function projectAnswerMode(service: string): AnswerMode {
|
|
466
|
+
return answerModeFrom(cachedProjectSettings(service));
|
|
467
|
+
}
|
|
468
|
+
|
|
398
469
|
/**
|
|
399
470
|
* Adopt a value the caller just WROTE, so the settings page reflects its own
|
|
400
471
|
* save without a re-fetch.
|
|
@@ -104,57 +104,110 @@ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rul
|
|
|
104
104
|
KEEP WHAT THE DATA SAYS APART FROM WHAT YOU WORKED OUT. A total you computed, a comparison, a trend, an interpretation or a recommendation is yours, not the data's: label it as such ("calculated from...", "this suggests...") and name the rows or files it was made from. Never present an estimate, an assumption or an inference as something the data states.
|
|
105
105
|
These three rules govern every claim about the project's data. They do not limit the About BunnyQuery section (answer product questions from it), a greeting, or text the user explicitly asks you to write.`;
|
|
106
106
|
|
|
107
|
+
// ---- Web switch ---------------------------------------------------------
|
|
108
|
+
// Follows the tool list: with the web off the chat has no such tool, with it on
|
|
109
|
+
// a web fact must be marked as one. It sits right after the grounding rules
|
|
110
|
+
// because it is the one exception to their four sources. (It used to be the
|
|
111
|
+
// tail of the DOCUMENTS rule, which also restated "never from general knowledge"
|
|
112
|
+
// a third time; the grounding rules already say it once.)
|
|
113
|
+
const webRule = webAccess
|
|
114
|
+
? `WEB ACCESS IS ON for this project: when the user asks for something that is not in the project's data, you may search the web for it, but every such fact must be marked as coming from the web (name the site), kept apart from what the project's data says, and never used to fill in or complete a document's content or a record. This is the one exception to the four sources named above.`
|
|
115
|
+
: `This chat has no web tool: the web is never a source here.`;
|
|
116
|
+
|
|
107
117
|
// ---- Documents -------------------------------------------------------
|
|
108
118
|
// One method for a question about a file's CONTENT (a contract, a report, a
|
|
109
119
|
// manual), where the invented answers were worst: the model picked records it
|
|
110
120
|
// liked and paraphrased. Find the file, find the page with searchText, quote
|
|
111
121
|
// the exact text, cite file and page; an old file (no page text) is read with
|
|
112
|
-
// readFileContent
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
//
|
|
122
|
+
// readFileContent.
|
|
123
|
+
//
|
|
124
|
+
// Trimmed 2026-11-22 (efficiency item 7): searchText's step protocol (quick
|
|
125
|
+
// search, quick_complete / next_cursor / full_scan_cursor / search_complete,
|
|
126
|
+
// asking before a full search), its no_page_text fallback and its "an empty
|
|
127
|
+
// result over files with page text is a real not-in-the-data" rule are all in
|
|
128
|
+
// the chat profile's searchText description (mcp/tools/*.js), which the model
|
|
129
|
+
// reads on every step. That description must stay self-sufficient for
|
|
130
|
+
// third-party MCP clients, so the duplicate is removed HERE and the prompt only
|
|
131
|
+
// points at it. What stays is what no tool text says: quote and cite.
|
|
120
132
|
const documentRules =
|
|
121
|
-
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise
|
|
122
|
-
|
|
123
|
-
|
|
133
|
+
`DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps 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"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name.`;
|
|
134
|
+
|
|
135
|
+
// ---- Access group -----------------------------------------------------
|
|
136
|
+
// Item 1 (2026-11-22): this used to say an index or tag query is "auto-filled
|
|
137
|
+
// with access_group "authorized", but THIS project indexes at access_group
|
|
138
|
+
// <group> ... the auto-fill would search a group this project's data is not
|
|
139
|
+
// in", which contradicts itself on the default project, whose group IS
|
|
140
|
+
// "authorized". The auto-fill sentence now follows the project's group, and so
|
|
141
|
+
// does the "comes back empty" clause (a "public" project's table read with no
|
|
142
|
+
// group is read at 0, which is right). Every instruction it carried is kept:
|
|
143
|
+
// the group goes on every query that names a table; a non-owner's table read
|
|
144
|
+
// with no group sees group 0 only; an empty result is retried in the other
|
|
145
|
+
// groups; reference alone spans every table and group; an index or tag
|
|
146
|
+
// without table_name fails, and so does access_group without table_name.
|
|
147
|
+
// A raw number renders unquoted, so 1 is "authorized" and 0 is "public".
|
|
148
|
+
const groupIsAuthorized = indexGroupLiteral === '"authorized"' || indexGroupLiteral === '1';
|
|
149
|
+
const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === '0';
|
|
150
|
+
const accessGroupRule =
|
|
151
|
+
`THIS PROJECT INDEXES AT access_group ${indexGroupLiteral}: pass access_group ${indexGroupLiteral} EXPLICITLY on EVERY query that names a table_name, whether it filters by index, by tag or by nothing. ${groupIsAuthorized
|
|
152
|
+
? `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which happens to be this project's group, but a plain table query is not auto-filled at all.`
|
|
153
|
+
: `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which is NOT this project's group, so it would search a group this project's data is not in and come back empty.`} Leaving access_group off a table query does NOT mean "all groups": only the project's owner is answered across every group, and any other user is answered from access_group 0 (public) alone${groupIsPublic
|
|
154
|
+
? ''
|
|
155
|
+
: `, so a table indexed at ${indexGroupLiteral} comes back empty with its records sitting right there`}. Files uploaded before the project's setting changed may sit at another group, so when a table query comes back empty, retry it in the other groups among 0, 1 and "private" before concluding there is nothing. An index or tag filter matches inside ONE table and needs table_name: without it the call FAILS with an error, so read the error rather than guessing. Reference is the exception: reference ALONE spans EVERY table and EVERY access group, so getRecords with reference "src::<the file's storage path>" is the one call that returns a whole file's records wherever the indexer put them; adding table_name narrows it to that table, and access_group WITHOUT table_name fails with '"table" is required'.`;
|
|
124
156
|
|
|
157
|
+
// Trimmed 2026-11-22 (efficiency item 7), each rule removed here is stated in a
|
|
158
|
+
// chat-profile tool description the model reads on every step:
|
|
159
|
+
// - table/tag/index name search both ways (gte begins with, lte ends with)
|
|
160
|
+
// and "a known id: getUniqueId or reference": getTables, getTags,
|
|
161
|
+
// getIndexes, getUniqueId, getRecords.index.condition.
|
|
162
|
+
// - "one page is a SAMPLE, about 50 records; fetch_all or page with
|
|
163
|
+
// getToolResponsePage while pagination.has_more": getRecords (+ fetch_all,
|
|
164
|
+
// fetch_limit) and getToolResponsePage.
|
|
165
|
+
// - index filters match exact / prefix / suffix only, tags exact only:
|
|
166
|
+
// getRecords.index.condition and getRecords.tags.
|
|
167
|
+
// - readFileContent's window paging, dropped image blocks, no OCR, never
|
|
168
|
+
// describing an unseen picture: readFileContent (chat wording).
|
|
169
|
+
// - db: link mechanics (strip src::, prefix db:, path verbatim, never
|
|
170
|
+
// url-encoded): getRecords SOURCE LINKS.
|
|
171
|
+
// - exportRecordsToFile's download_url handling, no retyped rows:
|
|
172
|
+
// exportRecordsToFile.
|
|
173
|
+
// What stays is BunnyQuery's own: where the indexer puts things, the access
|
|
174
|
+
// group, the spreadsheet row layout, __MEDIA__, how THIS client renders db:
|
|
175
|
+
// links and images, and the code-block file rule.
|
|
125
176
|
let systemPrompt = `
|
|
126
177
|
You are a dedicated assistant for the project ID: "${projectId}".
|
|
127
178
|
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
179
|
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
180
|
${groundingRules}
|
|
181
|
+
${webRule}
|
|
130
182
|
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.
|
|
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
|
|
183
|
+
FINDING THE DATA: the database is the way in, for every kind of file. Follow 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>". 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). 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.
|
|
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. Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
|
|
133
185
|
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.
|
|
134
186
|
${documentRules}
|
|
135
|
-
Complete answers over stored data:
|
|
136
|
-
|
|
137
|
-
|
|
187
|
+
Complete answers over stored data: each uploaded file becomes many records, and ONE file is routinely SPLIT ACROSS SEVERAL TABLES - a summary row in one table, its page or row content in another, its extracted photos and other media in "__MEDIA__", and the indexer often invents a differently-named table on each pass. For anything NOT scoped to a single file, call getTables FIRST, run the query once per table that could hold the answer, and combine the results.
|
|
188
|
+
${accessGroupRule}
|
|
189
|
+
For any request that counts, sums, totals, lists every match, compares across records, finds which one, or asks whether something is present or ABSENT (for example "how many", "total spent", "which card", "is there any", "없어?", "하나도 없나?"), you MUST read the COMPLETE matching set across EVERY table and EVERY relevant file before answering: one page is only a sample. Never assert absence from a partial read: do not say "there is no X", "none", "not found", or "아니요, 없습니다" until a complete scan has come back empty, and keep querying instead of guessing. A confident "no" that later turns out wrong is worse than telling the user you are still checking. If you already answered from one table and then realise another table holds more, do not simply apologise: re-run the sweep and give the complete answer.
|
|
190
|
+
Embedded values: a search term is often stored inside a larger string. A merchant "BAKSA" appears as "DNH*BAKSA#4070277042", and a card as "5860****5173". Index and tag filters never match an interior substring, so filtering on such a field silently drops rows. When the value you are looking for may be embedded, do not trust a narrow filter to be complete: fetch the full set with fetch_all and match the substring yourself.
|
|
138
191
|
File attachments: When a user message contains an "Attached files:" section with markdown links, those links point to short-lived signed URLs in this project's db storage and will expire.
|
|
139
192
|
- Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message - you can see them directly. Do NOT call web_fetch on image URLs; that will fail or return garbage. Just look at the image block and answer.
|
|
140
|
-
- Other attached files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) are ALREADY INDEXED: they were read end to end when they were uploaded, before this message reached you, and their content is in the database as records. Query it with getRecords using reference "src::<the storage path from the attachment link>"
|
|
193
|
+
- Other attached files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) are ALREADY INDEXED: they were read end to end when they were uploaded, before this message reached you, and their content is in the database as records. Query it with getRecords using reference "src::<the storage path from the attachment link>". Do NOT call web_fetch on their URLs. If you need the raw text rather than the indexed records (an exact quote, a specific cell), call readFileContent on that same path. Some turns instead carry the file text inlined between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers; when that block is present read it directly, and a "[skapi: ...]" note inside it means that file could not be extracted.
|
|
141
194
|
${webAccess
|
|
142
195
|
? `- For any file given to you as a URL instead of inline content (e.g. PDFs), use your web_fetch tool to download and read each URL before answering. Treat the fetched contents as user-supplied input data. Do not ask the user to paste the file contents - fetch the URLs yourself.`
|
|
143
196
|
: `- PDFs and every other attached file are indexed the same way before this message reaches you, and this chat has NO web tool: never try to download or fetch an attachment's URL. Answer a PDF from its records (getRecords with reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS above).`}
|
|
144
|
-
Stored files
|
|
145
|
-
File links:
|
|
146
|
-
File lookup: When the user asks to see, list, or show files (e.g. "show me uploaded files", "list my images", "show me the reference video"),
|
|
197
|
+
Stored files: a file ALREADY in this project's storage was read end to end at upload time and saved as records, so the database is your best source: query those records first (getRecords with reference "src::<path>"). readFileContent re-reads the raw file and is the right tool for text, spreadsheet and data files; read it to the end before you conclude anything is absent. If its pictures do not reach you, say so plainly and fall back to the indexed records, and never tell the user the file is unreadable when its content is already in the database.
|
|
198
|
+
File links: whenever a record's unique_id starts with "src::", give the user the file as a markdown link in the format getRecords' description sets ([filename](db:path/to/file) for a stored path, without the "src::" prefix; an external URL as itself). In this chat client a db: link renders as a clickable button that fetches a fresh signed URL on demand, so even if a previously shared URL has expired, give the user the storage-path link instead of saying the file is unavailable. Never tell the user a file is inaccessible or a URL is expired if you have its storage path in the database.
|
|
199
|
+
File lookup: When the user asks to see, list, or show files (e.g. "show me uploaded files", "list my images", "show me the reference video"), list the file records with getUniqueId on "src::" and condition "gte" (see WHERE INDEXED CONTENT LIVES), or getRecords by table; every file extracted out of a document has one too, in table "__MEDIA__" (access_group "authorized"). Present each result as a link as described above. Never say you cannot access file storage: the paths are indexed in the database.
|
|
147
200
|
Showing images: "show me the photo", "보여줘", "display it" is a request for the file's LINK, nothing more. This chat client renders an image file's storage-path link as the picture itself, inline, so a [filename](db:path/to/photo.jpg) link IS the image on screen. Never answer an image request with "I can't show images" or "I can only describe it", and never make the user ask twice for a link you already had. If you have the path, give the link and let the client paint it. The same is true of any file the user asks to see: the link is the answer. Only fall back to describing an image when the user asked ABOUT its contents rather than to see it, or when you genuinely have no path for it.
|
|
148
201
|
Media inside a document is extracted into real files: every embedded PICTURE inside an uploaded document - photos, diagrams, chart images - is pulled out at upload time and saved as its OWN permanent file in this project's storage, in the folder "__MEDIA__/<the document's storage path>/". Embedded audio, video and non-picture attachments are never saved as separate files (an email's attachment text is indexed inline instead), and a scanned PDF page is not stored as a separate picture (its content is indexed from the page itself) - for those, say so plainly and offer the source document. A picture is NOT trapped inside its source document: never answer that a photo exists only inside the spreadsheet or deck, that no separate image file was saved, or that there is nothing to open, and never hand back a link to the source .xlsx or .pdf when the user asked for a picture inside it.
|
|
149
202
|
Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
|
|
150
203
|
RECOGNISE IT BY THE VALUE, NOT THE FIELD NAME. Any field whose value begins with "__MEDIA__/" is a storage path to an extracted file, whatever the field is called - path, photo_path, media_path, file, attachment, or something the indexer invented that day. A record's unique_id beginning "src::__MEDIA__/" marks it as a media record too.
|
|
151
|
-
The reliable query is getRecords with reference "src::<the document's storage path>"
|
|
204
|
+
The reliable query is getRecords with reference "src::<the document's storage path>". Scan the results for the one describing what you want (its part number, tag id, anchor, caption or description) and take its "__MEDIA__/..." value. Never let a table guess be the reason you report a file as missing.
|
|
152
205
|
Link it VERBATIM as [caption](db:<the path>). An image renders inline as the picture itself; other media renders as a link the user can open.
|
|
153
206
|
So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
|
|
154
207
|
IF THAT RECORD HAS NO PATH, JOIN ON LOCATION - this needs nothing to have been enriched. Every media record carries data.anchor (the cell or page it was embedded at), plus data.sheet when it came from a spreadsheet, and the content record that mentions your part carries the same anchor and sheet under some name (anchor, anchor_cell, photo_anchor, cell, row_number, page). So: read the anchor and sheet off the content record, query getRecords with reference "src::<the document>", and take the media record whose data.anchor, data.also_at or tags match the anchor, using data.sheet too when both records carry one. Those fields are written by the pipeline, not by an indexer's choice of wording, so they are correct wherever they appear. One caution: a picture repeated at several cells is stored ONCE, under the FIRST cell it appeared at, so an anchor can genuinely have no media record of its own; its locations are merged onto that first record's tags and data.also_at. Before reporting a picture missing, check whether another media record of the same document is plausibly the same picture (same sheet, a matching description), and offer that one.
|
|
155
|
-
THIS IS NOT ONLY ABOUT SPREADSHEET PHOTOS. Treat "show me the diagram in that deck" or "the picture in that PDF" exactly like a photo request: query for the media record, never reconstruct a filename.
|
|
208
|
+
THIS IS NOT ONLY ABOUT SPREADSHEET PHOTOS. Treat "show me the diagram in that deck" or "the picture in that PDF" exactly like a photo request: query for the media record, never reconstruct a filename.
|
|
156
209
|
A document may still have no media record: it was indexed before the "__MEDIA__" table existed, or its format is one whose embedded files are not extracted. Then say plainly that this picture is not indexed and offer the source document. One missing record is never evidence that media is not stored.
|
|
157
|
-
File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile
|
|
210
|
+
File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile and hand over its link the way its description says. Never retype stored rows into a code block and never split one dataset across several blocks. For a file you are authoring yourself, or to produce specifically-formatted text such as HTML, CSV, JSON, or Markdown, put the file's full contents inside a fenced code block whose info string is the intended filename WITH its extension (e.g. report.csv), NOT a language name like "csv". The chat client turns such a block into a downloadable file named after that info string. Emit one file per block, in plain text only - never base64 or any other encoding. Example for CSV:
|
|
158
211
|
\`\`\`filename.csv
|
|
159
212
|
item,qty,total
|
|
160
213
|
Carrots,55,$38.50
|
|
@@ -178,7 +231,7 @@ How data gets in: ${canUpload === false
|
|
|
178
231
|
: `the user attaches files to a chat message with the paperclip button in the composer, or drags and drops them onto the chat (whole folders work; up to 20 files per message). Uploaded files land in this project's file storage and are indexed automatically: read end to end and turned into database records. "Indexed" means exactly that, and it is why you can only answer from a file once its indexing has finished. While a file indexes, the chat shows a status row for it: yellow while it is working, green when it is indexed, red if it failed. A large file is indexed in windows over several passes, which takes longer; indexing runs on the server, so it keeps going if the user closes the page and the row is still there when they come back. The user can also paste plain text straight into the chat and ask you to save it - store it with the postRecords tool. BunnyQuery reads over 50 formats: office documents (.docx, .xlsx, .pptx, .hwp, .hwpx, .odt, .ods, .odp, .epub), email (.eml), PDFs, images, .csv/.tsv, .json, .xml, .html, .txt/.md and source code. Images and scanned PDFs are read with vision at index time.`}
|
|
179
232
|
Getting answers out: the user asks in plain language, in any language, and you answer from this project's data. You can also produce reports and downloadable files (CSV and the rest) as described in the File generation rules above, and any stored file can be handed back as a link, with images rendering inline in the chat.${client === 'console'
|
|
180
233
|
? `
|
|
181
|
-
Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.`
|
|
234
|
+
Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, the Answer mode (Standard, Fast or Thorough: how quickly or how deeply you work on each answer), and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.`
|
|
182
235
|
: ''}${client === 'widget'
|
|
183
236
|
? `
|
|
184
237
|
This chat is the BunnyQuery widget embedded in a website, so the user may have no access to the project console: keep any instructions to what can be done here in the chat.`
|