bunnyquery 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.mjs CHANGED
@@ -43,6 +43,134 @@ async function parseAttachmentContent(file, name, mime) {
43
43
  return text;
44
44
  }
45
45
 
46
+ // src/engine/project_settings.ts
47
+ var UPLOAD_ACCESS_GROUPS = ["public", "authorized", "private"];
48
+ var DEFAULT_UPLOAD_ACCESS_GROUP = "authorized";
49
+ var PROJECT_SETTINGS_TABLE = "__SETTINGS__";
50
+ var PROJECT_SETTINGS_UNIQUE_ID = "bq::settings";
51
+ var PROJECT_SETTINGS_ACCESS_GROUP = "public";
52
+ var UPLOAD_ACCESS_LABELS = {
53
+ public: "Public",
54
+ authorized: "Signed in users",
55
+ private: "Only me"
56
+ };
57
+ var UPLOAD_ACCESS_HINTS = {
58
+ public: "Anyone can ask about this file, including visitors who are not logged in.",
59
+ authorized: "Only users signed in to this project can ask about this file.",
60
+ private: "Only you can ask about this file."
61
+ };
62
+ var UPLOAD_ACCESS_OPTIONS = UPLOAD_ACCESS_GROUPS.map((value) => ({
63
+ value,
64
+ label: UPLOAD_ACCESS_LABELS[value],
65
+ hint: UPLOAD_ACCESS_HINTS[value]
66
+ }));
67
+ var DEFAULT_WEB_ACCESS = false;
68
+ function normalizeWebAccess(value) {
69
+ return value === true;
70
+ }
71
+ function webAccessFrom(data) {
72
+ return data ? normalizeWebAccess(data.web_access) : DEFAULT_WEB_ACCESS;
73
+ }
74
+ var CHAT_GREETING_MAX_LENGTH = 400;
75
+ function normalizeChatGreeting(value) {
76
+ if (typeof value !== "string") return "";
77
+ const trimmed = value.replace(/\r\n?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
78
+ return trimmed.slice(0, CHAT_GREETING_MAX_LENGTH);
79
+ }
80
+ function chatGreetingFrom(data) {
81
+ return normalizeChatGreeting(data?.chat_greeting);
82
+ }
83
+ function normalizeUploadAccessGroup(value) {
84
+ return UPLOAD_ACCESS_GROUPS.indexOf(value) === -1 ? DEFAULT_UPLOAD_ACCESS_GROUP : value;
85
+ }
86
+ function normalizeProjectAccessSetting(value) {
87
+ if (value === "ask") return "ask";
88
+ return UPLOAD_ACCESS_GROUPS.indexOf(value) === -1 ? null : value;
89
+ }
90
+ function accessSettingFrom(data) {
91
+ return normalizeProjectAccessSetting(data?.upload_access_group);
92
+ }
93
+ function uploadAccessGroupFrom(data) {
94
+ const v = accessSettingFrom(data);
95
+ return v && v !== "ask" ? v : DEFAULT_UPLOAD_ACCESS_GROUP;
96
+ }
97
+ function asksUploadAccessFrom(data) {
98
+ return accessSettingFrom(data) === "ask";
99
+ }
100
+ var reader = null;
101
+ var cache = /* @__PURE__ */ new Map();
102
+ function configureProjectSettings(fn) {
103
+ reader = fn;
104
+ }
105
+ function entry(service) {
106
+ let e = cache.get(service);
107
+ if (!e) {
108
+ e = { data: null, settled: false, inflight: null };
109
+ cache.set(service, e);
110
+ }
111
+ return e;
112
+ }
113
+ function loadProjectSettings(service) {
114
+ if (!service) return Promise.resolve(null);
115
+ const e = entry(service);
116
+ if (e.settled) return Promise.resolve(e.data);
117
+ if (e.inflight) return e.inflight;
118
+ if (!reader) return Promise.resolve(null);
119
+ const run = reader(service).then((data) => data && typeof data === "object" ? data : null).catch(() => null).then((data) => {
120
+ const cur = entry(service);
121
+ if (cur.inflight === run) {
122
+ cur.data = data;
123
+ cur.settled = true;
124
+ cur.inflight = null;
125
+ }
126
+ return data;
127
+ });
128
+ e.inflight = run;
129
+ return run;
130
+ }
131
+ function primeProjectSettings(service) {
132
+ void loadProjectSettings(service);
133
+ }
134
+ function readyProjectSettings(service) {
135
+ return loadProjectSettings(service);
136
+ }
137
+ function cachedProjectSettings(service) {
138
+ const e = cache.get(service);
139
+ return e && e.settled ? e.data : null;
140
+ }
141
+ function projectSettingsSettled(service) {
142
+ const e = cache.get(service);
143
+ return !!e && e.settled;
144
+ }
145
+ function projectAccessSetting(service) {
146
+ return accessSettingFrom(cachedProjectSettings(service));
147
+ }
148
+ function projectUploadAccessGroup(service) {
149
+ return uploadAccessGroupFrom(cachedProjectSettings(service));
150
+ }
151
+ function projectAsksUploadAccess(service) {
152
+ return asksUploadAccessFrom(cachedProjectSettings(service));
153
+ }
154
+ function projectChatGreeting(service) {
155
+ return chatGreetingFrom(cachedProjectSettings(service));
156
+ }
157
+ function projectWebAccess(service) {
158
+ return webAccessFrom(cachedProjectSettings(service));
159
+ }
160
+ function setProjectSettings(service, data) {
161
+ if (!service) return;
162
+ cache.set(service, { data: data || null, settled: true, inflight: null });
163
+ }
164
+ function patchProjectSettings(service, patch) {
165
+ if (!service) return;
166
+ const cur = cachedProjectSettings(service) || {};
167
+ setProjectSettings(service, Object.assign({}, cur, patch));
168
+ }
169
+ function clearProjectSettings(service) {
170
+ if (service) cache.delete(service);
171
+ else cache.clear();
172
+ }
173
+
46
174
  // src/engine/config.ts
47
175
  var _config = null;
48
176
  function configureChatEngine(config) {
@@ -108,6 +236,17 @@ function liveStreamingRealtimeEnabled() {
108
236
  function liveStreamingEnabled() {
109
237
  return _config?.liveStreaming === true;
110
238
  }
239
+ function webAccessEnabled(service) {
240
+ const opt = _config ? _config.webAccess : void 0;
241
+ if (typeof opt === "boolean") return opt;
242
+ return webAccessFrom(service ? cachedProjectSettings(service) : null);
243
+ }
244
+ function resolveWebAccess(service) {
245
+ const opt = _config ? _config.webAccess : void 0;
246
+ if (typeof opt === "boolean") return Promise.resolve(opt);
247
+ if (!service) return Promise.resolve(false);
248
+ return loadProjectSettings(service).then(webAccessFrom, () => false);
249
+ }
111
250
  function streamRecoveryEnabled() {
112
251
  if (!_config) return false;
113
252
  if (_config.streamRecovery === false) return false;
@@ -355,12 +494,14 @@ function groupAttachmentFailures(attachments) {
355
494
  // src/engine/prompts/chat_system_prompt.ts
356
495
  function buildChatSystemPrompt(params) {
357
496
  const { projectId, serviceName, serviceDescription, greeting, canUpload, client } = params;
497
+ const webAccess = params.webAccess === true;
358
498
  const g = params.indexAccessGroup;
359
499
  const indexGroupLiteral = typeof g === "number" ? String(g) : g === "public" || g === "private" || g === "authorized" || g === "admin" ? `"${g}"` : '"authorized"';
360
500
  const groundingRules = `ANSWER ONLY FROM THE DATA. Every fact you state about this project's data - a name, a number, a date, a status, what a document says, whether something exists - must come from one of four places: a tool result returned in THIS conversation, a file or image attached to it (including one you read through its attachment link), the project description at the end of this prompt, or what the user told you themselves in this chat. Your general knowledge, the open internet and a plausible guess are NOT sources. Never use them to answer a question about the user's data, to fill a gap in it, or to complete a record that came back partial. A value that is not in what you retrieved is unknown: say it is not in the data instead of supplying a likely one.
361
501
  WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rules require and nothing answers the question, tell the user plainly, in their language, that this project's data does not contain it, and say what you searched (the tables, files or terms) so they can tell missing data from a missed search. Do not answer from memory instead, and do not turn a missing answer into a general explanation of the topic. Offer what would let you answer it: ${canUpload === false ? `another name or file to look under, or asking the project's owner to add it` : `the document to upload, or another name or file to look under`}.
362
502
  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.
363
503
  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.`;
504
+ const documentRules = `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 with getUniqueId using unique_id "src::" and condition "gte" (narrow it by the name the user used). THEN FIND THE PAGE: call searchText with the file's path and the words the user asked about; it returns the file, the page and the matching excerpt. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"); never present a paraphrase as a quote. If searchText answers no_page_text, the file was indexed before page text existed: read it with readFileContent instead, paging with the cursor until END OF FILE, and cite the file. When searchText and the file's records come back empty over files that HAVE page text, say that the data does not have it and name the files and the terms you searched. Never fill the gap from your general knowledge, and never from the web${webAccess ? ` without saying so. 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. This is the one exception to the four sources named above.` : `: this chat has no web tool.`}`;
364
505
  let systemPrompt = `
365
506
  You are a dedicated assistant for the project ID: "${projectId}".
366
507
  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.
@@ -369,13 +510,14 @@ ${groundingRules}
369
510
  NUMBERS FROM A SPREADSHEET: use queryGrid, never mental arithmetic over records. A total, a count, an average, a "how many mention X", a "which one is biggest" - all of those are computed server-side over EVERY row of the file and come back with the sheet, the row count and the row numbers they were made from. Records are a SAMPLE, and a sample added up is a confident wrong number. Quote the row count and the sheet alongside the figure so the reader can check it.
370
511
  CALL queryGrid describe FIRST, before any figure. Workbooks routinely state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that each re-total it, plus a summary sheet whose bottom row is the file total. Those look like four different answers and are one. describe names which sheets restate which, and which rows are totals. Pick ONE sheet, say which you picked, and never add figures across a sheet and its summary. If the reply carries a warning about restatement, repeat it to the user.
371
512
  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.
513
+ ${documentRules}
372
514
  Complete answers over stored data: The database holds one record per spreadsheet row, and each uploaded file becomes many records. 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. An index or tag filter matches inside ONE table only and requires table_name: on getRecords, an index or tag sent with table_name but no access_group is auto-filled with access_group "authorized", but THIS project indexes at access_group ${indexGroupLiteral}, so pass access_group ${indexGroupLiteral} EXPLICITLY on EVERY query that names a table_name here, index or tag or plain - the auto-fill would search a group this project's data is not in and come back empty, and leaving access_group off a plain table query does NOT mean "all groups": unless you are the project's owner the server reads a table with no group as access_group 0 (public only), 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 scoped query comes back empty, retry it across the other groups (0, 1, "private") before concluding there is nothing, while an index or tag WITHOUT table_name FAILS with an error instead of answering, 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; access_group WITHOUT table_name fails with '"table" is required'; table_name on its own returns that whole table across all access groups ONLY for the project's owner, and only its access_group 0 records for any other user, so name the group whenever you name a table. 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. 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", "\uC5C6\uC5B4?", "\uD558\uB098\uB3C4 \uC5C6\uB098?"), you MUST read the COMPLETE matching set before answering. Query with fetch_all set to true, or page through getToolResponsePage until pagination.complete is true, across EVERY table and EVERY relevant file. A single default query returns only the first page (about 50 records). That is a SAMPLE. Never treat it as the whole dataset. 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.
373
515
  Never assert absence from a partial read. Do not say "there is no X", "none", "not found", or "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4" until a complete scan has come back empty. If you have not finished scanning every relevant table and file, keep querying instead of guessing. A confident "no" that later turns out wrong is worse than telling the user you are still checking.
374
516
  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". Server-side index filters match only exact values, leading prefixes, or trailing suffixes, and tag filters only EXACT whole-tag values - never a partial or 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.
375
517
  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.
376
518
  - 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.
377
519
  - 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>" - one call, every table, every access group. 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 and page it with the cursor. 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.
378
- - 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.
520
+ ${webAccess ? `- 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.` : `- 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).`}
379
521
  Stored files and readFileContent: for a file ALREADY in this project's storage, its pages and rows were read at upload time and saved as records, so the database is your best source. Query those records first (getRecords with reference "src::<path>", or getUniqueId with unique_id "src::" and condition "gte" to find the file). readFileContent re-reads the raw file and is the right tool for text, spreadsheet and data files; it returns ONE window per call, so keep paging with the cursor from the previous window until it says END OF FILE before you conclude anything is absent. Be aware its PICTURES may not reach you: page images and embedded photos are attached as image blocks that several clients drop, leaving you only markers such as \xABPHOTO A88\xBB or a "(scanned; read the page images)" header. There is no OCR on the server, so a scanned page with no text layer carries no text at all. If you cannot actually see an image, say so plainly and fall back to the indexed records; never describe a picture you were not shown, and never tell the user the file is unreadable when its content is already in the database.
380
522
  File links: When you find a record whose unique_id starts with "src::", the part after "src::" is the file's storage path or original URL. Always present it as a markdown link so the user can access it. Strip the "src::" prefix - do NOT show it. Format: [filename](db:path/to/file) for storage paths, or [filename](https://...) for external URLs. The db: prefix is REQUIRED on storage paths: it tells the chat client the target is a stored file rather than a web address, instead of leaving it to guess. Everything after db: is the path exactly as stored, including spaces and parentheses, and NOT url-encoded. Storage-path links render as clickable buttons in this chat client that fetch 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.
381
523
  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"), query the database using getUniqueId with unique_id "src::" and condition "gte" (or getRecords by table) to find all indexed file records; every file extracted out of a document has one too, in table "__MEDIA__" (access_group "authorized"). Present each result as a markdown link as described above. Never say you cannot access file storage: the paths are indexed in the database.
@@ -1074,6 +1216,224 @@ function truncateLabelForDisplay(label) {
1074
1216
  return "\u2026" + label.slice(label.length - (LINK_LABEL_MAX_DISPLAY_CHARS - 1));
1075
1217
  }
1076
1218
 
1219
+ // src/engine/retrieval_memory.ts
1220
+ var RETRIEVAL_NOTES_MAX = 6;
1221
+ var RETRIEVAL_NOTES_TOKEN_BUDGET = 1200;
1222
+ var RETRIEVAL_NOTE_MAX_ITEMS = 8;
1223
+ var RETRIEVAL_NOTE_MAX_CHARS = 600;
1224
+ var RETRIEVAL_NOTE_PREFIX = "[Retrieval note, not shown to the user";
1225
+ var FILE_KEYS = ["path", "storage_path", "storagePath", "file", "file_path", "filePath"];
1226
+ var TABLE_KEYS = ["table_name", "tableName"];
1227
+ var GROUP_KEYS = ["access_group", "accessGroup"];
1228
+ var SRC_PREFIX = "src::";
1229
+ var RESULT_WALK_MAX_NODES = 400;
1230
+ var RESULT_WALK_MAX_DEPTH = 5;
1231
+ function isWebToolName(name) {
1232
+ return typeof name === "string" && /^web_(search|fetch)/.test(name);
1233
+ }
1234
+ function pushUnique(list, value) {
1235
+ if (typeof value !== "string") return;
1236
+ var v = value.trim();
1237
+ if (!v || list.indexOf(v) !== -1 || list.length >= RETRIEVAL_NOTE_MAX_ITEMS) return;
1238
+ list.push(v);
1239
+ }
1240
+ function pushGroup(list, value) {
1241
+ if (typeof value === "number" && isFinite(value)) pushUnique(list, String(value));
1242
+ else pushUnique(list, value);
1243
+ }
1244
+ function pushHit(list, path, page) {
1245
+ if (typeof path !== "string" || !path.trim()) return;
1246
+ var n = typeof page === "number" ? page : Number(page);
1247
+ if (!isFinite(n) || n <= 0) return;
1248
+ n = Math.floor(n);
1249
+ for (var i = 0; i < list.length; i++) {
1250
+ if (list[i].path === path && list[i].page === n) return;
1251
+ }
1252
+ if (list.length >= RETRIEVAL_NOTE_MAX_ITEMS) return;
1253
+ list.push({ path: path.trim(), page: n });
1254
+ }
1255
+ function pathFromSrcId(value) {
1256
+ if (typeof value !== "string") return null;
1257
+ if (value.indexOf(SRC_PREFIX) !== 0) return null;
1258
+ var rest = value.slice(SRC_PREFIX.length).trim();
1259
+ return rest ? rest : null;
1260
+ }
1261
+ function parseJsonLoose(value) {
1262
+ if (typeof value !== "string") return value;
1263
+ var t = value.trim();
1264
+ if (!t || t[0] !== "{" && t[0] !== "[") return null;
1265
+ try {
1266
+ return JSON.parse(t);
1267
+ } catch (e) {
1268
+ return null;
1269
+ }
1270
+ }
1271
+ function readArguments(note, args) {
1272
+ if (!args || typeof args !== "object") return;
1273
+ var i;
1274
+ for (i = 0; i < FILE_KEYS.length; i++) pushUnique(note.files, args[FILE_KEYS[i]]);
1275
+ for (i = 0; i < TABLE_KEYS.length; i++) pushUnique(note.tables, args[TABLE_KEYS[i]]);
1276
+ for (i = 0; i < GROUP_KEYS.length; i++) pushGroup(note.accessGroups, args[GROUP_KEYS[i]]);
1277
+ if (typeof args.table === "string") pushUnique(note.tables, args.table);
1278
+ else if (args.table && typeof args.table === "object") {
1279
+ pushUnique(note.tables, args.table.name);
1280
+ pushGroup(note.accessGroups, args.table.access_group);
1281
+ }
1282
+ var ref = pathFromSrcId(args.reference);
1283
+ if (ref) pushUnique(note.files, ref);
1284
+ var uid = pathFromSrcId(args.unique_id);
1285
+ if (uid) pushUnique(note.files, uid);
1286
+ }
1287
+ function readHits(note, result) {
1288
+ var parsed = parseJsonLoose(result);
1289
+ if (!parsed || typeof parsed !== "object") return;
1290
+ var visited = 0;
1291
+ var walk = function(node, depth) {
1292
+ if (!node || typeof node !== "object" || depth > RESULT_WALK_MAX_DEPTH) return;
1293
+ if (++visited > RESULT_WALK_MAX_NODES) return;
1294
+ if (Array.isArray(node)) {
1295
+ for (var i = 0; i < node.length && visited <= RESULT_WALK_MAX_NODES; i++) walk(node[i], depth + 1);
1296
+ return;
1297
+ }
1298
+ if (typeof node.path === "string" && node.page !== void 0) {
1299
+ pushHit(note.hits, node.path, node.page);
1300
+ }
1301
+ for (var k in node) {
1302
+ if (!Object.prototype.hasOwnProperty.call(node, k)) continue;
1303
+ var v = node[k];
1304
+ if (v && typeof v === "object") walk(v, depth + 1);
1305
+ }
1306
+ };
1307
+ walk(parsed, 0);
1308
+ }
1309
+ function claudeResultText(block) {
1310
+ var c = block && block.content;
1311
+ if (typeof c === "string") return c;
1312
+ if (Array.isArray(c)) {
1313
+ return c.map(function(part) {
1314
+ return part && typeof part.text === "string" ? part.text : "";
1315
+ }).join("\n");
1316
+ }
1317
+ return "";
1318
+ }
1319
+ function emptyNote(source) {
1320
+ return { files: [], tables: [], accessGroups: [], hits: [], tools: [], web: false, source };
1321
+ }
1322
+ function noteHasContent(note) {
1323
+ return note.files.length > 0 || note.tables.length > 0 || note.accessGroups.length > 0 || note.hits.length > 0 || note.tools.length > 0 || note.web;
1324
+ }
1325
+ function noteFromToolBlocks(body) {
1326
+ if (!body || typeof body !== "object") return null;
1327
+ var note = emptyNote("tools");
1328
+ var sawTool = false;
1329
+ var i;
1330
+ var content = body.content;
1331
+ if (Array.isArray(content)) {
1332
+ var callNames = {};
1333
+ for (i = 0; i < content.length; i++) {
1334
+ var block = content[i];
1335
+ if (!block || typeof block !== "object") continue;
1336
+ var type = block.type;
1337
+ if (type === "mcp_tool_use" || type === "tool_use") {
1338
+ sawTool = true;
1339
+ pushUnique(note.tools, block.name);
1340
+ if (typeof block.id === "string" && typeof block.name === "string") callNames[block.id] = block.name;
1341
+ readArguments(note, block.input);
1342
+ } else if (type === "server_tool_use" || type === "web_search_tool_use") {
1343
+ sawTool = true;
1344
+ if (isWebToolName(block.name) || type === "web_search_tool_use") note.web = true;
1345
+ pushUnique(note.tools, block.name || type);
1346
+ } else if (type === "mcp_tool_result" || type === "tool_result") {
1347
+ sawTool = true;
1348
+ var name = typeof block.tool_use_id === "string" ? callNames[block.tool_use_id] : void 0;
1349
+ if (!block.is_error && (name === void 0 || name === "searchText")) readHits(note, claudeResultText(block));
1350
+ } else if (type === "web_search_tool_result" || type === "web_fetch_tool_result") {
1351
+ sawTool = true;
1352
+ note.web = true;
1353
+ }
1354
+ }
1355
+ }
1356
+ var output = body.output;
1357
+ if (Array.isArray(output)) {
1358
+ for (i = 0; i < output.length; i++) {
1359
+ var item = output[i];
1360
+ if (!item || typeof item !== "object") continue;
1361
+ var kind = typeof item.type === "string" ? item.type : "";
1362
+ if (kind === "mcp_call" || kind === "function_call") {
1363
+ sawTool = true;
1364
+ pushUnique(note.tools, item.name);
1365
+ readArguments(note, parseJsonLoose(item.arguments) || item.arguments);
1366
+ if (!item.error && item.name === "searchText") readHits(note, item.output);
1367
+ } else if (kind.indexOf("web_search") === 0 || kind.indexOf("web_fetch") === 0) {
1368
+ sawTool = true;
1369
+ note.web = true;
1370
+ pushUnique(note.tools, kind);
1371
+ }
1372
+ }
1373
+ }
1374
+ return sawTool ? note : null;
1375
+ }
1376
+ function retrievalNoteFromText(text) {
1377
+ if (typeof text !== "string" || !text) return null;
1378
+ var note = emptyNote("answer");
1379
+ var link = /\]\(db:([^)\s"]+)/g;
1380
+ var m;
1381
+ while ((m = link.exec(text)) !== null) pushUnique(note.files, m[1]);
1382
+ var src = /src::([^\s"'`<>)\]]+)/g;
1383
+ while ((m = src.exec(text)) !== null) {
1384
+ pushUnique(note.files, m[1].replace(/[.,;:!?]+$/, ""));
1385
+ }
1386
+ return noteHasContent(note) ? note : null;
1387
+ }
1388
+ function extractRetrievalNote(body, answerText) {
1389
+ var fromTools = noteFromToolBlocks(body);
1390
+ var fromText = retrievalNoteFromText(answerText);
1391
+ if (!fromTools) {
1392
+ if (fromText) return fromText;
1393
+ return providerBodyWasRead(body) ? emptyNote("body") : null;
1394
+ }
1395
+ if (fromText) {
1396
+ for (var i = 0; i < fromText.files.length; i++) pushUnique(fromTools.files, fromText.files[i]);
1397
+ }
1398
+ return noteHasContent(fromTools) ? fromTools : emptyNote("body");
1399
+ }
1400
+ function providerBodyWasRead(body) {
1401
+ if (!body || typeof body !== "object") return false;
1402
+ return Array.isArray(body.content) || Array.isArray(body.output);
1403
+ }
1404
+ function isRetrievalNote(value) {
1405
+ return !!value && typeof value === "object" && Array.isArray(value.files) && Array.isArray(value.tables) && Array.isArray(value.accessGroups) && Array.isArray(value.hits) && Array.isArray(value.tools);
1406
+ }
1407
+ function formatRetrievalNote(note) {
1408
+ if (!note || !noteHasContent(note)) return "";
1409
+ var parts = [];
1410
+ if (note.files.length) parts.push("files " + note.files.join(", "));
1411
+ if (note.tables.length) parts.push("tables " + note.tables.join(", "));
1412
+ if (note.accessGroups.length) parts.push("access_group " + note.accessGroups.join(", "));
1413
+ if (note.hits.length) {
1414
+ var byFile = {};
1415
+ var order = [];
1416
+ for (var i = 0; i < note.hits.length; i++) {
1417
+ var h = note.hits[i];
1418
+ if (!byFile[h.path]) {
1419
+ byFile[h.path] = [];
1420
+ order.push(h.path);
1421
+ }
1422
+ byFile[h.path].push(h.page);
1423
+ }
1424
+ parts.push("searchText hits " + order.map(function(p) {
1425
+ return p + " p" + byFile[p].join(", p");
1426
+ }).join("; "));
1427
+ }
1428
+ if (note.tools.length) parts.push("tools " + note.tools.join(", "));
1429
+ if (note.web) parts.push("web tool used");
1430
+ var line = RETRIEVAL_NOTE_PREFIX + ": this turn used " + parts.join(" | ") + "]";
1431
+ if (line.length > RETRIEVAL_NOTE_MAX_CHARS) {
1432
+ line = line.slice(0, RETRIEVAL_NOTE_MAX_CHARS - 4) + "...]";
1433
+ }
1434
+ return line;
1435
+ }
1436
+
1077
1437
  // src/engine/budget.ts
1078
1438
  var CONTEXT_WINDOW_DEFAULT = { claude: 2e5, openai: 128e3 };
1079
1439
  var CONTEXT_WINDOW_BY_MODEL = {
@@ -1245,6 +1605,23 @@ function stripFileBlocksFromHistory(content) {
1245
1605
  if (!content) return content;
1246
1606
  return content.replace(/```([^\n`]+?\.[^\s.`]+)\n[\s\S]*?```/g, "[file previously attached: $1]");
1247
1607
  }
1608
+ function applyRetrievalNotes(messages, latestIndex) {
1609
+ var out = messages.slice();
1610
+ var used = 0, tokens = 0;
1611
+ for (var i = messages.length - 1; i >= 0; i--) {
1612
+ if (used >= RETRIEVAL_NOTES_MAX) break;
1613
+ var m = messages[i];
1614
+ if (i === latestIndex || !m || m.role !== "assistant" || !isRetrievalNote(m._retrieval)) continue;
1615
+ var line = formatRetrievalNote(m._retrieval);
1616
+ if (!line) continue;
1617
+ var cost = estimateTextTokens(line) + 2;
1618
+ if (tokens + cost > RETRIEVAL_NOTES_TOKEN_BUDGET) break;
1619
+ tokens += cost;
1620
+ used++;
1621
+ out[i] = Object.assign({}, m, { content: (m.content || "") + "\n\n" + line });
1622
+ }
1623
+ return { messages: out, notesUsed: used, noteTokens: tokens };
1624
+ }
1248
1625
  function buildBoundedChatMessages(options) {
1249
1626
  var contextBasedBudget = contextBasedBudgetFor(options.platform, options.model, options.projectId);
1250
1627
  var availableInputBudget = getInputTokenBudget(options.platform, options.model, options.projectId);
@@ -1260,6 +1637,7 @@ function buildBoundedChatMessages(options) {
1260
1637
  );
1261
1638
  var windowed = options.history.slice(-maxHistoryMessages);
1262
1639
  var latestIndex = windowed.length - 1;
1640
+ if (options.retrievalNotes !== false) windowed = applyRetrievalNotes(windowed, latestIndex).messages;
1263
1641
  var trimmed = windowed.map(function(m, i2) {
1264
1642
  if (i2 === latestIndex) return m;
1265
1643
  var stripped = stripFileBlocksFromHistory(m.content);
@@ -1283,6 +1661,105 @@ function buildBoundedChatMessages(options) {
1283
1661
  };
1284
1662
  }
1285
1663
 
1664
+ // src/engine/citations.ts
1665
+ var DATA_TOOL_NAMES = [
1666
+ "getRecords",
1667
+ "queryGrid",
1668
+ "readFileContent",
1669
+ "searchText",
1670
+ "getFileOutline",
1671
+ "getUniqueId",
1672
+ "getTables",
1673
+ "getTags",
1674
+ "getIndexes"
1675
+ ];
1676
+ var NO_DATA_TOOL_MARK = "No project data was read for this answer";
1677
+ function citationFileName(path) {
1678
+ var segs = String(path || "").split("/");
1679
+ for (var i = segs.length - 1; i >= 0; i--) {
1680
+ if (segs[i]) return segs[i];
1681
+ }
1682
+ return String(path || "");
1683
+ }
1684
+ function citationLabel(path, page) {
1685
+ return citationFileName(path) + (typeof page === "number" && page > 0 ? " p." + page : "");
1686
+ }
1687
+ function isMintablePath(path) {
1688
+ return !!path && !isHttpUrlLike(path);
1689
+ }
1690
+ function citationsFor(note) {
1691
+ if (!isRetrievalNote(note)) return [];
1692
+ var out = [];
1693
+ var hitPaths = [];
1694
+ var byPath = {};
1695
+ var i;
1696
+ for (i = 0; i < note.hits.length; i++) {
1697
+ var h = note.hits[i];
1698
+ if (!h || typeof h.path !== "string" || !isMintablePath(h.path)) continue;
1699
+ var page = typeof h.page === "number" ? h.page : Number(h.page);
1700
+ if (!isFinite(page) || page <= 0) continue;
1701
+ page = Math.floor(page);
1702
+ if (!byPath[h.path]) {
1703
+ byPath[h.path] = [];
1704
+ hitPaths.push(h.path);
1705
+ }
1706
+ if (byPath[h.path].indexOf(page) === -1) byPath[h.path].push(page);
1707
+ }
1708
+ for (i = 0; i < hitPaths.length; i++) {
1709
+ var p = hitPaths[i];
1710
+ var pages = byPath[p].slice().sort(function(a, b) {
1711
+ return a - b;
1712
+ });
1713
+ for (var j = 0; j < pages.length; j++) {
1714
+ out.push({ path: p, page: pages[j], label: citationLabel(p, pages[j]) });
1715
+ }
1716
+ }
1717
+ for (i = 0; i < note.files.length; i++) {
1718
+ var f = note.files[i];
1719
+ if (typeof f !== "string" || !isMintablePath(f)) continue;
1720
+ if (byPath[f]) continue;
1721
+ var dup = false;
1722
+ for (var k = 0; k < out.length; k++) {
1723
+ if (out[k].path === f && out[k].page === void 0) {
1724
+ dup = true;
1725
+ break;
1726
+ }
1727
+ }
1728
+ if (dup) continue;
1729
+ out.push({ path: f, label: citationLabel(f) });
1730
+ }
1731
+ return out;
1732
+ }
1733
+ function isDataToolName(name) {
1734
+ return DATA_TOOL_NAMES.indexOf(name) !== -1;
1735
+ }
1736
+ function answerUsedNoDataTool(note) {
1737
+ if (!isRetrievalNote(note)) return false;
1738
+ if (note.web) return false;
1739
+ for (var i = 0; i < note.tools.length; i++) {
1740
+ if (isDataToolName(note.tools[i])) return false;
1741
+ }
1742
+ return true;
1743
+ }
1744
+ function retrievalNoteOfAnswer(msg) {
1745
+ if (!msg || msg.role !== "assistant") return null;
1746
+ if (msg.isError || msg.isPending || msg.isBackgroundTask || msg._streamPending) return null;
1747
+ return isRetrievalNote(msg._retrieval) ? msg._retrieval : null;
1748
+ }
1749
+ function citationLinkPart(citation, resolveFreshHref) {
1750
+ var expiredHref = buildDisplayExpiredAttachmentHref(citation.path, citation.label);
1751
+ var cached = resolveFreshHref ? resolveFreshHref(expiredHref) : void 0;
1752
+ return {
1753
+ type: "link",
1754
+ label: truncateLabelForDisplay(citation.label),
1755
+ fullLabel: citation.label,
1756
+ href: cached || expiredHref,
1757
+ expired: !cached,
1758
+ expiredHref,
1759
+ remotePath: citation.path
1760
+ };
1761
+ }
1762
+
1286
1763
  // src/engine/download_encoding.ts
1287
1764
  var BOM = "\uFEFF";
1288
1765
  var BOM_EXTS = /* @__PURE__ */ new Set(["csv", "tsv", "tab", "txt", "text", "log"]);
@@ -2217,10 +2694,26 @@ var ANTHROPIC_PROMPT_CACHING_BETA = "prompt-caching-2024-07-31";
2217
2694
  var ANTHROPIC_BETA_HEADER = `${ANTHROPIC_MCP_BETA},${ANTHROPIC_WEB_FETCH_BETA},${ANTHROPIC_PROMPT_CACHING_BETA}`;
2218
2695
  var WEB_FETCH_MAX_USES = 40;
2219
2696
  var WEB_FETCH_MAX_CONTENT_TOKENS = 2e5;
2697
+ var claudeWebFetchTool = () => ({
2698
+ type: "web_fetch_20250910",
2699
+ name: "web_fetch",
2700
+ max_uses: WEB_FETCH_MAX_USES,
2701
+ citations: { enabled: true },
2702
+ max_content_tokens: WEB_FETCH_MAX_CONTENT_TOKENS
2703
+ });
2220
2704
  var OPENAI_RESPONSES_API_URL = "https://api.openai.com/v1/responses";
2221
2705
  var OPENAI_MODELS_API_URL = "https://api.openai.com/v1/models";
2222
2706
  var DEFAULT_OPENAI_IMAGE_DETAIL = "auto";
2223
2707
  var OPENAI_WEB_SEARCH_EXTERNAL_WEB_ACCESS = true;
2708
+ var openaiWebSearchTool = () => ({
2709
+ type: "web_search",
2710
+ external_web_access: OPENAI_WEB_SEARCH_EXTERNAL_WEB_ACCESS
2711
+ });
2712
+ var webToolsForChat = (platform, webAccess) => {
2713
+ if (webAccess !== true) return [];
2714
+ if (platform === "claude") return [claudeWebFetchTool()];
2715
+ return [openaiWebSearchTool()] ;
2716
+ };
2224
2717
  var MCP_NAME = "BunnyQuery";
2225
2718
  var DEFAULT_CLAUDE_MODEL = "claude-sonnet-5";
2226
2719
  var DEFAULT_OPENAI_MODEL = "gpt-5.6-luna";
@@ -2236,6 +2729,7 @@ function withMcpParams(base, params) {
2236
2729
  }
2237
2730
  var mcpContextParam = (platform, model) => getModelContextWindow(platform, model);
2238
2731
  var mcpIndexingUrl = (platform = "openai", model) => withMcpParams(mcpUrl(), { profile: "index", ctx: mcpContextParam(platform, model) });
2732
+ var mcpChatUrl = (endpointUrl, platform, model) => withMcpParams(endpointUrl, { profile: "chat", ctx: mcpContextParam(platform, model) });
2239
2733
  function mcpEndpointFor(anonymous, publicProjectId, service) {
2240
2734
  if (!anonymous) return { url: mcpUrl(), token: "$ACCESS_TOKEN" };
2241
2735
  const project = publicProjectId || service;
@@ -2421,8 +2915,10 @@ async function callClaudeWithMcp({
2421
2915
  system,
2422
2916
  mcpServer,
2423
2917
  extractContent,
2424
- fileUrls
2918
+ fileUrls,
2919
+ webAccess
2425
2920
  }) {
2921
+ const web = typeof webAccess === "boolean" ? webAccess : await resolveWebAccess(service);
2426
2922
  const mcpServerDefinition = {
2427
2923
  type: "url",
2428
2924
  name: mcpServer.name,
@@ -2481,13 +2977,10 @@ async function callClaudeWithMcp({
2481
2977
  ...mcpServer.defaultConfig ? { default_config: mcpServer.defaultConfig } : {},
2482
2978
  ...mcpServer.configs ? { configs: mcpServer.configs } : {}
2483
2979
  },
2484
- {
2485
- type: "web_fetch_20250910",
2486
- name: "web_fetch",
2487
- max_uses: WEB_FETCH_MAX_USES,
2488
- citations: { enabled: true },
2489
- max_content_tokens: WEB_FETCH_MAX_CONTENT_TOKENS
2490
- }
2980
+ // `web_fetch` rides here only when the project's web switch is on. The
2981
+ // beta header above is left as it is: it only makes the tool TYPE
2982
+ // available, and a request that does not list the tool cannot use it.
2983
+ ...webToolsForChat("claude", web)
2491
2984
  ]
2492
2985
  }
2493
2986
  });
@@ -2507,9 +3000,7 @@ async function callClaudeWithPublicMcp(prompt, service, owner, messages, system,
2507
3000
  fileUrls,
2508
3001
  mcpServer: {
2509
3002
  name: MCP_NAME,
2510
- url: withMcpParams(endpoint.url, {
2511
- ctx: mcpContextParam("claude", model || DEFAULT_CLAUDE_MODEL)
2512
- }),
3003
+ url: mcpChatUrl(endpoint.url, "claude", model || DEFAULT_CLAUDE_MODEL),
2513
3004
  // Omitted entirely for an anonymous turn; the `if (mcpServer.authorizationToken)`
2514
3005
  // guard below drops the key rather than sending an empty one.
2515
3006
  authorizationToken: endpoint.token
@@ -2519,6 +3010,7 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
2519
3010
  const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
2520
3011
  const resolvedModel = model || DEFAULT_OPENAI_MODEL;
2521
3012
  const imageDetail = getOpenAIImageDetail(resolvedModel);
3013
+ const web = await resolveWebAccess(service);
2522
3014
  const messageList = messages && messages.length ? prepareOpenAIMessages(messages, imageDetail) : [
2523
3015
  {
2524
3016
  role: "user",
@@ -2564,19 +3056,15 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
2564
3056
  {
2565
3057
  type: "mcp",
2566
3058
  server_label: MCP_NAME,
2567
- server_url: withMcpParams(endpoint.url, { ctx: mcpContextParam("openai", resolvedModel) }),
3059
+ server_url: mcpChatUrl(endpoint.url, "openai", resolvedModel),
2568
3060
  require_approval: "never",
2569
3061
  // No `headers` at all for an anonymous turn: `Bearer ` with an
2570
3062
  // empty token is a credential the MCP server rejects, and the
2571
3063
  // project-scoped endpoint needs none.
2572
3064
  ...endpoint.token ? { headers: { Authorization: "Bearer " + endpoint.token } } : {}
2573
3065
  },
2574
- ...[
2575
- {
2576
- type: "web_search",
2577
- external_web_access: OPENAI_WEB_SEARCH_EXTERNAL_WEB_ACCESS
2578
- }
2579
- ]
3066
+ // `web_search` rides here only when the project's web switch is on.
3067
+ ...webToolsForChat("openai", web)
2580
3068
  ]
2581
3069
  }
2582
3070
  });
@@ -2724,12 +3212,9 @@ async function notifyAgentSaveAttachment(info) {
2724
3212
  require_approval: "never",
2725
3213
  headers: { Authorization: "Bearer $ACCESS_TOKEN" }
2726
3214
  },
2727
- ...[
2728
- {
2729
- type: "web_search",
2730
- external_web_access: OPENAI_WEB_SEARCH_EXTERNAL_WEB_ACCESS
2731
- }
2732
- ]
3215
+ // UNCONDITIONAL, unlike a chat turn: the project's web switch
3216
+ // governs answers, not indexing. Kept exactly as it was.
3217
+ ...[openaiWebSearchTool()]
2733
3218
  ]
2734
3219
  }
2735
3220
  }));
@@ -2782,13 +3267,9 @@ async function notifyAgentSaveAttachment(info) {
2782
3267
  type: "mcp_toolset",
2783
3268
  mcp_server_name: MCP_NAME
2784
3269
  },
2785
- {
2786
- type: "web_fetch_20250910",
2787
- name: "web_fetch",
2788
- max_uses: WEB_FETCH_MAX_USES,
2789
- citations: { enabled: true },
2790
- max_content_tokens: WEB_FETCH_MAX_CONTENT_TOKENS
2791
- }
3270
+ // UNCONDITIONAL, unlike a chat turn: the project's web switch governs
3271
+ // answers, not indexing. Kept exactly as it was.
3272
+ claudeWebFetchTool()
2792
3273
  ]
2793
3274
  }
2794
3275
  }));
@@ -3327,6 +3808,10 @@ function mapHistoryListToMessages(list, platform, opts) {
3327
3808
  if (item._fromBgChain) okm._fromBgChain = true;
3328
3809
  if (item._isBgTask) okm.isBackgroundTask = true;
3329
3810
  if (isCompact) okm._compact = true;
3811
+ if (!item._isBgTask && !isCompact) {
3812
+ var note = extractRetrievalNote(response, assistantText);
3813
+ if (note) okm._retrieval = note;
3814
+ }
3330
3815
  if (serverItemId !== void 0) okm._serverItemId = serverItemId;
3331
3816
  if (replyTs !== void 0) okm._ts = replyTs;
3332
3817
  if (indexFile && isFinite(executedTs) && executedTs > 0) okm._tsStart = executedTs;
@@ -5022,6 +5507,10 @@ var ChatSession = class {
5022
5507
  return;
5023
5508
  }
5024
5509
  var reply = isErr ? { role: "assistant", content: getErrorMessage(body), isError: true, _serverItemId: itemId } : { role: "assistant", content: text, _serverItemId: itemId };
5510
+ if (!isErr) {
5511
+ var rNote = extractRetrievalNote(body, text);
5512
+ if (rNote) reply._retrieval = rNote;
5513
+ }
5025
5514
  if (ownerKey && this.getHistoryCacheKey() !== ownerKey) {
5026
5515
  this._applyReplyToCache(ownerKey, reply, itemId);
5027
5516
  } else {
@@ -5430,7 +5919,7 @@ var ChatSession = class {
5430
5919
  if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
5431
5920
  var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
5432
5921
  answer = (answer || "").trim();
5433
- return { content: answer || "No text response received from AI provider.", isError: false };
5922
+ return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer) };
5434
5923
  }).catch(function(err) {
5435
5924
  return { content: getErrorMessage(err), isError: true };
5436
5925
  }).then(function(result) {
@@ -5442,6 +5931,7 @@ var ChatSession = class {
5442
5931
  }
5443
5932
  var reply = { role: "assistant", content: result.content, isError: result.isError };
5444
5933
  if (dispatchItemId) reply._serverItemId = dispatchItemId;
5934
+ if (result.retrieval) reply._retrieval = result.retrieval;
5445
5935
  self._applyReplyToCache(params.key, reply, dispatchItemId);
5446
5936
  return result;
5447
5937
  });
@@ -6105,6 +6595,10 @@ var ChatSession = class {
6105
6595
  }
6106
6596
  if (ownerKey && this.getHistoryCacheKey() !== ownerKey) {
6107
6597
  var offReply = isErrorResponseBody(response) ? { role: "assistant", content: getErrorMessage(response), isError: true } : { role: "assistant", content: ((platform === "openai" ? extractOpenAIText(response) : extractClaudeText(response)) || "").trim() || "No text response received from AI provider." };
6598
+ if (!offReply.isError) {
6599
+ var offNote = extractRetrievalNote(response, offReply.content);
6600
+ if (offNote) offReply._retrieval = offNote;
6601
+ }
6108
6602
  this._applyReplyToCache(ownerKey, offReply, serverId);
6109
6603
  if (serverId) this.cancelledServerIds.delete(serverId);
6110
6604
  return;
@@ -6126,6 +6620,7 @@ var ChatSession = class {
6126
6620
  } else {
6127
6621
  var answer = platform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
6128
6622
  answer = (answer || "").trim() || "No text response received from AI provider.";
6623
+ var qNote = extractRetrievalNote(response, answer);
6129
6624
  var lid = this._newLocalId();
6130
6625
  if (targetIdx >= 0 && this.state.messages[targetIdx] && this.state.messages[targetIdx].isPending) {
6131
6626
  var qPainted = this._paintedTextAt(targetIdx);
@@ -6133,16 +6628,21 @@ var ChatSession = class {
6133
6628
  var qSettled = { role: "assistant", content: qPainted, _localId: lid };
6134
6629
  if (prevQ._serverItemId) qSettled._serverItemId = prevQ._serverItemId;
6135
6630
  if (prevQ._ownerKey) qSettled._ownerKey = prevQ._ownerKey;
6631
+ if (qNote) qSettled._retrieval = qNote;
6136
6632
  this.state.messages[targetIdx] = qSettled;
6137
6633
  this.host.notify();
6138
6634
  this.enqueueTypewrite(targetIdx, answer, lid, qPainted);
6139
6635
  } else if (targetIdx >= 0) {
6140
- this.state.messages.splice(targetIdx, 0, { role: "assistant", content: "", _localId: lid });
6636
+ var qInsert = { role: "assistant", content: "", _localId: lid };
6637
+ if (qNote) qInsert._retrieval = qNote;
6638
+ this.state.messages.splice(targetIdx, 0, qInsert);
6141
6639
  this.host.notify();
6142
6640
  this.enqueueTypewrite(targetIdx, answer, lid);
6143
6641
  } else {
6144
6642
  var aiIdx = this.state.messages.length;
6145
- this.state.messages.push({ role: "assistant", content: "", _localId: lid });
6643
+ var qAppend = { role: "assistant", content: "", _localId: lid };
6644
+ if (qNote) qAppend._retrieval = qNote;
6645
+ this.state.messages.push(qAppend);
6146
6646
  this.host.notify();
6147
6647
  this.enqueueTypewrite(aiIdx, answer, lid);
6148
6648
  }
@@ -6732,6 +7232,7 @@ var ChatSession = class {
6732
7232
  var settled = { role: "assistant", content: painted, isPending: false, _localId: lid };
6733
7233
  if (prevSettled._serverItemId) settled._serverItemId = prevSettled._serverItemId;
6734
7234
  if (prevSettled._ownerKey) settled._ownerKey = prevSettled._ownerKey;
7235
+ if (latest._retrieval) settled._retrieval = latest._retrieval;
6735
7236
  this.state.messages[pendingIdx] = settled;
6736
7237
  this._removeStrayPendingAssistants();
6737
7238
  this.host.notify();
@@ -6952,6 +7453,7 @@ var ChatSession = class {
6952
7453
  var isErr = isErrorResponseBody(response);
6953
7454
  var answer = isErr ? getErrorMessage(response) : ((platform === "openai" ? extractOpenAIText(response) : extractClaudeText(response)) || "").trim();
6954
7455
  var reportedComplete = !isErr && !!answer && answer.indexOf(INDEXING_COMPLETE_MARKER) !== -1;
7456
+ var hNote = isErr ? null : extractRetrievalNote(response, answer);
6955
7457
  var stripMarker = function(t) {
6956
7458
  return reportedComplete ? t.split(INDEXING_COMPLETE_MARKER).join("").trim() : t;
6957
7459
  };
@@ -6977,7 +7479,9 @@ var ChatSession = class {
6977
7479
  }
6978
7480
  var hPainted = this._paintedTextAt(idx);
6979
7481
  var lid = this._newLocalId();
6980
- this.state.messages[idx] = { role: "assistant", content: hPainted, _localId: lid, _serverItemId: itemId };
7482
+ var hReply = { role: "assistant", content: hPainted, _localId: lid, _serverItemId: itemId };
7483
+ if (hNote) hReply._retrieval = hNote;
7484
+ this.state.messages[idx] = hReply;
6981
7485
  this.host.notify();
6982
7486
  this.enqueueTypewrite(idx, text, lid, hPainted);
6983
7487
  this.updateHistoryCache();
@@ -7011,6 +7515,7 @@ var ChatSession = class {
7011
7515
  }
7012
7516
  var lid2 = this._newLocalId();
7013
7517
  var reply = { role: "assistant", content: "", _localId: lid2, _serverItemId: itemId };
7518
+ if (hNote) reply._retrieval = hNote;
7014
7519
  this.state.messages.splice(userIdx + 1, 0, reply);
7015
7520
  this.host.notify();
7016
7521
  this.enqueueTypewrite(userIdx + 1, text2, lid2);
@@ -8675,124 +9180,6 @@ function buildChatDisplayList(messages, opts) {
8675
9180
  return out;
8676
9181
  }
8677
9182
 
8678
- // src/engine/project_settings.ts
8679
- var UPLOAD_ACCESS_GROUPS = ["public", "authorized", "private"];
8680
- var DEFAULT_UPLOAD_ACCESS_GROUP = "authorized";
8681
- var PROJECT_SETTINGS_TABLE = "__SETTINGS__";
8682
- var PROJECT_SETTINGS_UNIQUE_ID = "bq::settings";
8683
- var PROJECT_SETTINGS_ACCESS_GROUP = "public";
8684
- var UPLOAD_ACCESS_LABELS = {
8685
- public: "Public",
8686
- authorized: "Signed in users",
8687
- private: "Only me"
8688
- };
8689
- var UPLOAD_ACCESS_HINTS = {
8690
- public: "Anyone can ask about this file, including visitors who are not logged in.",
8691
- authorized: "Only users signed in to this project can ask about this file.",
8692
- private: "Only you can ask about this file."
8693
- };
8694
- var UPLOAD_ACCESS_OPTIONS = UPLOAD_ACCESS_GROUPS.map((value) => ({
8695
- value,
8696
- label: UPLOAD_ACCESS_LABELS[value],
8697
- hint: UPLOAD_ACCESS_HINTS[value]
8698
- }));
8699
- var CHAT_GREETING_MAX_LENGTH = 400;
8700
- function normalizeChatGreeting(value) {
8701
- if (typeof value !== "string") return "";
8702
- const trimmed = value.replace(/\r\n?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
8703
- return trimmed.slice(0, CHAT_GREETING_MAX_LENGTH);
8704
- }
8705
- function chatGreetingFrom(data) {
8706
- return normalizeChatGreeting(data?.chat_greeting);
8707
- }
8708
- function normalizeUploadAccessGroup(value) {
8709
- return UPLOAD_ACCESS_GROUPS.indexOf(value) === -1 ? DEFAULT_UPLOAD_ACCESS_GROUP : value;
8710
- }
8711
- function normalizeProjectAccessSetting(value) {
8712
- if (value === "ask") return "ask";
8713
- return UPLOAD_ACCESS_GROUPS.indexOf(value) === -1 ? null : value;
8714
- }
8715
- function accessSettingFrom(data) {
8716
- return normalizeProjectAccessSetting(data?.upload_access_group);
8717
- }
8718
- function uploadAccessGroupFrom(data) {
8719
- const v = accessSettingFrom(data);
8720
- return v && v !== "ask" ? v : DEFAULT_UPLOAD_ACCESS_GROUP;
8721
- }
8722
- function asksUploadAccessFrom(data) {
8723
- return accessSettingFrom(data) === "ask";
8724
- }
8725
- var reader = null;
8726
- var cache = /* @__PURE__ */ new Map();
8727
- function configureProjectSettings(fn) {
8728
- reader = fn;
8729
- }
8730
- function entry(service) {
8731
- let e = cache.get(service);
8732
- if (!e) {
8733
- e = { data: null, settled: false, inflight: null };
8734
- cache.set(service, e);
8735
- }
8736
- return e;
8737
- }
8738
- function loadProjectSettings(service) {
8739
- if (!service) return Promise.resolve(null);
8740
- const e = entry(service);
8741
- if (e.settled) return Promise.resolve(e.data);
8742
- if (e.inflight) return e.inflight;
8743
- if (!reader) return Promise.resolve(null);
8744
- const run = reader(service).then((data) => data && typeof data === "object" ? data : null).catch(() => null).then((data) => {
8745
- const cur = entry(service);
8746
- if (cur.inflight === run) {
8747
- cur.data = data;
8748
- cur.settled = true;
8749
- cur.inflight = null;
8750
- }
8751
- return data;
8752
- });
8753
- e.inflight = run;
8754
- return run;
8755
- }
8756
- function primeProjectSettings(service) {
8757
- void loadProjectSettings(service);
8758
- }
8759
- function readyProjectSettings(service) {
8760
- return loadProjectSettings(service);
8761
- }
8762
- function cachedProjectSettings(service) {
8763
- const e = cache.get(service);
8764
- return e && e.settled ? e.data : null;
8765
- }
8766
- function projectSettingsSettled(service) {
8767
- const e = cache.get(service);
8768
- return !!e && e.settled;
8769
- }
8770
- function projectAccessSetting(service) {
8771
- return accessSettingFrom(cachedProjectSettings(service));
8772
- }
8773
- function projectUploadAccessGroup(service) {
8774
- return uploadAccessGroupFrom(cachedProjectSettings(service));
8775
- }
8776
- function projectAsksUploadAccess(service) {
8777
- return asksUploadAccessFrom(cachedProjectSettings(service));
8778
- }
8779
- function projectChatGreeting(service) {
8780
- return chatGreetingFrom(cachedProjectSettings(service));
8781
- }
8782
- function setProjectSettings(service, data) {
8783
- if (!service) return;
8784
- cache.set(service, { data: data || null, settled: true, inflight: null });
8785
- }
8786
- function patchProjectSettings(service, patch) {
8787
- if (!service) return;
8788
- const cur = cachedProjectSettings(service) || {};
8789
- setProjectSettings(service, Object.assign({}, cur, patch));
8790
- }
8791
- function clearProjectSettings(service) {
8792
- if (service) cache.delete(service);
8793
- else cache.clear();
8794
- }
8795
-
8796
- export { BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_UPLOAD_ACCESS_GROUP, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, OUTPUT_TOKEN_RESERVE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, applyEncodingDeclaration, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEngineConfig, chatGreetingFrom, chatStreamWiring, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, formatChatTimestamp, formatDuration, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectUploadAccessGroup, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resolveImagePreviewUrl, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow };
9183
+ export { BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resolveImagePreviewUrl, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
8797
9184
  //# sourceMappingURL=engine.mjs.map
8798
9185
  //# sourceMappingURL=engine.mjs.map