bunnyquery 1.19.1 → 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/bunnyquery.js CHANGED
@@ -68,6 +68,13 @@
68
68
  function skipDuplicateFilesFrom(data) {
69
69
  return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
70
70
  }
71
+ var DEFAULT_ANSWER_MODE = "standard";
72
+ function normalizeAnswerMode(value) {
73
+ return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
74
+ }
75
+ function answerModeFrom(data) {
76
+ return normalizeAnswerMode(data ? data.answer_mode : void 0);
77
+ }
71
78
  var CHAT_GREETING_MAX_LENGTH = 400;
72
79
  function normalizeChatGreeting(value) {
73
80
  if (typeof value !== "string") return "";
@@ -213,6 +220,10 @@
213
220
  if (!service) return Promise.resolve(underCeiling(webAccessFrom(null), opt, override));
214
221
  return loadProjectSettings(service).then(webAccessFrom, () => false).then((setting) => underCeiling(setting, opt, override));
215
222
  }
223
+ function resolveAnswerMode(service) {
224
+ if (!service) return Promise.resolve(answerModeFrom(null));
225
+ return loadProjectSettings(service).then(answerModeFrom, () => answerModeFrom(null));
226
+ }
216
227
  function resolveSkipDuplicateFiles(service) {
217
228
  const opt = _config ? _config.skipDuplicateFiles : void 0;
218
229
  if (!service) return Promise.resolve(underCeiling(skipDuplicateFilesFrom(null), opt));
@@ -765,38 +776,44 @@ Extracted content of attached office files (read inline below; do NOT fetch thei
765
776
  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`}.
766
777
  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.
767
778
  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.`;
768
- 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; condition "lte" with the file name alone finds it in any folder). 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. When the user did not name a file ("find a file that contains X"), call searchText WITHOUT path: it narrows by itself. It first searches every file whose name matches: while quick_complete is false, keep its hits and call again with next_cursor without answering yet. When quick_complete is true, give the quick results, then ALWAYS ask the user once whether they want all files searched too, since they may be looking for something else, and only if they say yes call searchText again with cursor = full_scan_cursor (it leaves out the files already searched). With no quick match it searches every other file itself: follow next_cursor until search_complete is true, and once its hits answer the question, answer and ask the user before reading the rest. 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.`}`;
779
+ const webRule = webAccess ? `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.` : `This chat has no web tool: the web is never a source here.`;
780
+ 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 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.`;
781
+ const groupIsAuthorized = indexGroupLiteral === '"authorized"' || indexGroupLiteral === "1";
782
+ const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
783
+ const accessGroupRule = `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 ? `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.` : `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 ? "" : `, 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'.`;
769
784
  let systemPrompt = `
770
785
  You are a dedicated assistant for the project ID: "${projectId}".
771
786
  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.
772
787
  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.
773
788
  ${groundingRules}
789
+ ${webRule}
774
790
  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.
775
- FINDING THE DATA: the database is the way in, for every kind of file. Step 1, getTables (one page). ONLY when the list runs past that page (end_of_list false), search the table names with the words the user used, BOTH ways: condition "gte" (begins with) and condition "lte" (ends with), instead of listing them all. When the list is complete, never search table names: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Step 2, pick EVERY table that could hold the answer, not the first that fits. Step 3, in each of those tables, getIndexes and getTags (one page each, never fetch_all) to learn the exact index names and tag values; when that page does not show the name or the list runs past it, search both ways with the user's words: getTags with table_name and condition "gte", and again with "lte"; getIndexes with order {by: "index_name", value: <the words>, condition: "gte"} and again with "lte". Name and tag lists can be millions of characters long and are never read whole. Never call getTags with neither table_name nor tag: that lists every tag of every table. Step 4, getRecords in that table and group with the selector that matched: an index (string values take "gte" for begins with and "lte" for ends with), one exact tag, or no selector for the whole table, always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>". TAGS are stored lowercase without spaces or punctuation, plus one tag per word: search a tag as one word ("leak") or as the joined phrase ("oilleak"); the server also normalizes the tag you send. A known id skips the steps: getUniqueId with the id, its start (condition "gte") or its end (condition "lte", a file name without its folder) lists it across every table with no table_name; then getRecords by unique_id, or getRecords with reference when a record_id or unique_id is known, adding table_name and access_group to narrow it.
776
- NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set (fetch_all true, or page until pagination.complete is true), keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
791
+ 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.
792
+ 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.
777
793
  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.
778
794
  ${documentRules}
779
- 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.
780
- 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.
781
- 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.
795
+ 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.
796
+ ${accessGroupRule}
797
+ 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 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 "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4" 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.
798
+ 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.
782
799
  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.
783
800
  - 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.
784
- - 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.
801
+ - 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.
785
802
  ${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).`}
786
- 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.
787
- 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.
788
- 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.
803
+ 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.
804
+ 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.
805
+ 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.
789
806
  Showing images: "show me the photo", "\uBCF4\uC5EC\uC918", "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.
790
807
  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.
791
808
  Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
792
809
  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.
793
- The reliable query is getRecords with reference "src::<the document's storage path>" - one call, every table, every access group. 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.
810
+ 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.
794
811
  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.
795
812
  So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
796
813
  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.
797
- 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. For embedded video, audio or a non-picture attachment there is no extracted file: say so plainly and offer the source document.
814
+ 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.
798
815
  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.
799
- File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile: it writes the rows on the server, keeps them out of your context, and returns a download_url you paste as the link. 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:
816
+ 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:
800
817
  \`\`\`filename.csv
801
818
  item,qty,total
802
819
  Carrots,55,$38.50
@@ -992,6 +1009,133 @@ Records for the earlier windows/pages of this file are ALREADY saved (they refer
992
1009
  Index the REMAINING windows - one record per row/item, looking at any page images or embedded photos - saving as you go until readFileContent reports END OF FILE. A \xABPHOTO <cell>\xBB marker in a window marks an embedded picture whose extracted file already has a record in table "__MEDIA__": find it with getRecords reference "src::" + the storage path above and match the cell against data.anchor or tags (a repeated picture is stored under its first anchor only), then enrich it with updateRecords. Never create a photo record of your own and never construct a path for one. Do NOT re-save windows that are already saved. Set every record's reference to exactly "src::" + the storage path above (no sheet, window or summary suffix added). That file record already exists, so do NOT post it; enrich it with updateRecords. When the ENTIRE file is finally indexed, end your message with the token INDEXING_COMPLETE.`;
993
1010
  }
994
1011
 
1012
+ // src/engine/errors.ts
1013
+ var STATUS_MESSAGE = {
1014
+ "408": "The AI provider timed out before it started.",
1015
+ "409": "The AI provider rejected the request as conflicting.",
1016
+ "413": "The request was too large for the AI provider.",
1017
+ "429": "The AI provider is rate limiting requests right now.",
1018
+ "500": "The AI provider hit an internal error.",
1019
+ "502": "The AI provider is temporarily unreachable.",
1020
+ "503": "The AI provider is temporarily unavailable.",
1021
+ "504": "The AI provider timed out."
1022
+ };
1023
+ function isTransientStatus(status) {
1024
+ return status === 408 || status === 425 || status === 429 || status >= 500;
1025
+ }
1026
+ function isCsrStatusEnvelope(res) {
1027
+ return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
1028
+ }
1029
+ function csrEnvelopeError(input) {
1030
+ if (!isCsrStatusEnvelope(input)) return void 0;
1031
+ if (input.status !== "failed") return void 0;
1032
+ return input.error != null ? input.error : { message: "The AI provider request failed." };
1033
+ }
1034
+ function getErrorMessage(input) {
1035
+ var envErr = csrEnvelopeError(input);
1036
+ if (envErr !== void 0) input = envErr;
1037
+ if (!input) return "Something went wrong.";
1038
+ if (typeof input === "string") return input;
1039
+ if (input.error && input.error.message) return input.error.message;
1040
+ if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
1041
+ if (input.body && typeof input.body.message === "string") return input.body.message;
1042
+ if (input.message) return input.message;
1043
+ var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
1044
+ if (status) {
1045
+ var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
1046
+ return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
1047
+ }
1048
+ return "Something went wrong.";
1049
+ }
1050
+ function isRetriedFailure(input) {
1051
+ var envErr = csrEnvelopeError(input);
1052
+ if (envErr !== void 0) input = envErr;
1053
+ return !!input && typeof input === "object" && input.retried === true;
1054
+ }
1055
+ function isErrorResponseBody(response) {
1056
+ var envErr = csrEnvelopeError(response);
1057
+ if (envErr !== void 0) response = envErr;
1058
+ if (!response || typeof response !== "object") return envErr !== void 0;
1059
+ if (typeof response.status_code === "number" && response.status_code >= 400) return true;
1060
+ if (response.type === "error") return true;
1061
+ if (response.error && (response.error.message || response.error.type)) return true;
1062
+ var body = response.body;
1063
+ if (body && typeof body === "object") {
1064
+ if (body.type === "error") return true;
1065
+ if (body.error && (body.error.message || body.error.type)) return true;
1066
+ }
1067
+ if (typeof response.message === "string" && response.message.length) {
1068
+ var hasClaude = Array.isArray(response.content);
1069
+ var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
1070
+ if (!hasClaude && !hasOpenAI) return true;
1071
+ }
1072
+ return false;
1073
+ }
1074
+ function isNonRetryableRequestError(input) {
1075
+ var envErr = csrEnvelopeError(input);
1076
+ if (envErr !== void 0) input = envErr;
1077
+ if (!input || typeof input !== "object") return false;
1078
+ var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
1079
+ var param = void 0;
1080
+ var blobs = [];
1081
+ var sources = [input.error, input.body && input.body.error, input.body, input];
1082
+ for (var i = 0; i < sources.length; i++) {
1083
+ var e = sources[i];
1084
+ if (!e) continue;
1085
+ if (typeof e === "string") {
1086
+ blobs.push(e);
1087
+ continue;
1088
+ }
1089
+ if (typeof e !== "object") continue;
1090
+ if (param === void 0 && e.param != null) param = e.param;
1091
+ if (typeof e.code === "string") blobs.push(e.code);
1092
+ if (typeof e.type === "string") blobs.push(e.type);
1093
+ if (typeof e.message === "string") blobs.push(e.message);
1094
+ }
1095
+ var hay = blobs.join(" | ").toLowerCase();
1096
+ if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
1097
+ return true;
1098
+ }
1099
+ var isClientReqStatus = status === 400 || status === 422;
1100
+ if (isClientReqStatus && param != null && param !== "") return true;
1101
+ if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
1102
+ return true;
1103
+ }
1104
+ return false;
1105
+ }
1106
+ function isAuthExpiredError(input) {
1107
+ var envErr = csrEnvelopeError(input);
1108
+ if (envErr !== void 0) input = envErr;
1109
+ if (!input) return false;
1110
+ var blobs = [];
1111
+ var push = function(v) {
1112
+ if (typeof v === "string" && v) blobs.push(v);
1113
+ };
1114
+ if (typeof input === "string") push(input);
1115
+ else {
1116
+ push(input.message);
1117
+ push(input.code);
1118
+ if (input.error) {
1119
+ push(input.error.message);
1120
+ push(input.error.code);
1121
+ push(input.error.type);
1122
+ }
1123
+ if (input.body) {
1124
+ push(input.body.message);
1125
+ if (input.body.error) {
1126
+ push(input.body.error.message);
1127
+ push(input.body.error.code);
1128
+ push(input.body.error.type);
1129
+ }
1130
+ }
1131
+ if (typeof input.status === "number" && input.status === 401) return true;
1132
+ if (typeof input.status_code === "number" && input.status_code === 401) return true;
1133
+ }
1134
+ var hay = blobs.join(" | ").toLowerCase();
1135
+ if (!hay) return false;
1136
+ return hay.indexOf("token has expired") !== -1 || hay.indexOf("token is expired") !== -1 || hay.indexOf("expired_token") !== -1 || hay.indexOf("invalid_token") !== -1 || hay.indexOf("unauthorized") !== -1 || hay.indexOf("not authorized") !== -1 || hay.indexOf("invalid_request") !== -1 && hay.indexOf("token") !== -1;
1137
+ }
1138
+
995
1139
  // src/engine/links.ts
996
1140
  var EXPIRED_ATTACHMENT_URL_HOST = "_expired_.url";
997
1141
  var EXPIRED_ATTACHMENT_URL_ORIGIN = "https://" + EXPIRED_ATTACHMENT_URL_HOST;
@@ -1829,12 +1973,41 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1829
1973
  var isOpenAINano = (model) => {
1830
1974
  const normalized = (model).trim().toLowerCase();
1831
1975
  if (!/(^|-)nano(-|$)/.test(normalized)) return false;
1976
+ return openAITakesReasoningEffort(normalized);
1977
+ };
1978
+ var openAITakesReasoningEffort = (model) => {
1979
+ const normalized = (model || DEFAULT_OPENAI_MODEL).trim().toLowerCase();
1832
1980
  const match = normalized.match(/^gpt-(\d+)(?:\.(\d+))?(-[a-z0-9.\-]+)?$/);
1833
1981
  if (!match) return false;
1834
1982
  const major = Number(match[1]);
1835
1983
  const minor = match[2] === void 0 ? null : Number(match[2]);
1836
1984
  return major > 5 || major === 5 && minor !== null && minor >= 4;
1837
1985
  };
1986
+ var claudeTakesEffort = (model) => {
1987
+ const normalized = (model || DEFAULT_CLAUDE_MODEL).trim().toLowerCase().replace(/\[1m\]$/, "");
1988
+ const match = normalized.match(/^claude-([a-z]+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:-\d{8})?$/);
1989
+ if (!match) return false;
1990
+ const family = match[1];
1991
+ if (family === "fable" || family === "mythos") return true;
1992
+ if (match[2] === void 0) return false;
1993
+ const major = Number(match[2]);
1994
+ const minor = match[3] === void 0 ? 0 : Number(match[3]);
1995
+ if (family === "opus") return major > 4 || major === 4 && minor >= 5;
1996
+ if (family === "sonnet") return major > 4 || major === 4 && minor >= 6;
1997
+ if (family === "haiku") return major > 5 || major === 5 && minor >= 5;
1998
+ return false;
1999
+ };
2000
+ var ANSWER_MODE_EFFORT = {
2001
+ standard: null,
2002
+ fast: "low",
2003
+ thorough: "high"
2004
+ };
2005
+ function chatEffortFields(platform, model, mode) {
2006
+ const effort = mode ? ANSWER_MODE_EFFORT[mode] : null;
2007
+ if (!effort) return {};
2008
+ if (platform === "openai") return openAITakesReasoningEffort(model) ? { reasoning: { effort } } : {};
2009
+ return claudeTakesEffort(model) ? { output_config: { effort } } : {};
2010
+ }
1838
2011
  var variantIndexingOptions = (model) => {
1839
2012
  if (!isOpenAINano(model) || !isOldestNano(model)) return {};
1840
2013
  return {
@@ -1971,6 +2144,80 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1971
2144
  var POLL_INTERVAL = 3e3;
1972
2145
  var STREAM_POLL_INTERVAL = 1e3;
1973
2146
  var MAX_CONCURRENT_BG_POLLS = 6;
2147
+ var mcpListToolsCache = /* @__PURE__ */ new Map();
2148
+ var mcpListToolsReuseOff = false;
2149
+ var MCP_LIST_TOOLS_OFF_PREFIX = "bunnyquery:mcp-list-tools-off:";
2150
+ function mcpListToolsOffStored(service) {
2151
+ try {
2152
+ return typeof localStorage !== "undefined" && !!localStorage.getItem(MCP_LIST_TOOLS_OFF_PREFIX + service);
2153
+ } catch (_) {
2154
+ return false;
2155
+ }
2156
+ }
2157
+ function storeMcpListToolsOff(service) {
2158
+ if (!service) return;
2159
+ try {
2160
+ if (typeof localStorage !== "undefined") localStorage.setItem(MCP_LIST_TOOLS_OFF_PREFIX + service, String(Date.now()));
2161
+ } catch (_) {
2162
+ }
2163
+ }
2164
+ var SERVER_PLACEHOLDERS = ["$CLIENT_SECRET", "$ACCESS_TOKEN", "$ID_TOKEN"];
2165
+ function failureText(failure) {
2166
+ const env = csrEnvelopeError(failure);
2167
+ const f = env !== void 0 ? env : failure;
2168
+ if (f == null) return "";
2169
+ if (typeof f === "string") return f.toLowerCase();
2170
+ let text = "";
2171
+ try {
2172
+ text = JSON.stringify(f) || "";
2173
+ } catch (_) {
2174
+ text = "";
2175
+ }
2176
+ if (typeof f.message === "string") text += " " + f.message;
2177
+ return text.toLowerCase();
2178
+ }
2179
+ function failureStatus(failure) {
2180
+ const env = csrEnvelopeError(failure);
2181
+ const f = env !== void 0 ? env : failure;
2182
+ if (!f || typeof f !== "object") return void 0;
2183
+ const v = typeof f.status_code === "number" ? f.status_code : typeof f.status === "number" ? f.status : void 0;
2184
+ return v;
2185
+ }
2186
+ function mcpListToolsKey(serverUrl, anonymous, service, publicProjectId, userId) {
2187
+ return JSON.stringify([serverUrl, anonymous ? "anonymous" : "signed-in", service, publicProjectId || "", userId || ""]);
2188
+ }
2189
+ function rememberMcpListTools(turn, body) {
2190
+ if (!turn || !turn.mcpToolsKey || mcpListToolsReuseOff) return;
2191
+ const output = body && Array.isArray(body.output) ? body.output : null;
2192
+ if (!output) return;
2193
+ for (let i = output.length - 1; i >= 0; i--) {
2194
+ const item = output[i];
2195
+ if (!item || item.type !== "mcp_list_tools" || item.server_label !== MCP_NAME) continue;
2196
+ if (item.error || typeof item.id !== "string" || !item.id || !Array.isArray(item.tools)) continue;
2197
+ let toolsText = "";
2198
+ try {
2199
+ toolsText = JSON.stringify(item.tools);
2200
+ } catch (_) {
2201
+ return;
2202
+ }
2203
+ if (SERVER_PLACEHOLDERS.some((ph) => toolsText.indexOf(ph) !== -1)) return;
2204
+ mcpListToolsCache.set(turn.mcpToolsKey, { type: "mcp_list_tools", id: item.id, server_label: item.server_label, tools: item.tools });
2205
+ return;
2206
+ }
2207
+ }
2208
+ function forgetMcpListToolsOnFailure(turn, failure) {
2209
+ if (!turn || !turn.mcpToolsInjected) return;
2210
+ if (turn.mcpToolsKey) mcpListToolsCache.delete(turn.mcpToolsKey);
2211
+ const text = failureText(failure);
2212
+ const status = failureStatus(failure);
2213
+ const namesItem = text.indexOf("mcp_list_tools") !== -1 || !!turn.mcpToolsItemId && text.indexOf(turn.mcpToolsItemId.toLowerCase()) !== -1;
2214
+ if (namesItem) {
2215
+ mcpListToolsReuseOff = true;
2216
+ storeMcpListToolsOff(turn.mcpToolsService);
2217
+ return;
2218
+ }
2219
+ if (status === 400 || status === 422 || text.indexOf("invalid_request_error") !== -1) mcpListToolsReuseOff = true;
2220
+ }
1974
2221
  async function callClaudeWithMcp({
1975
2222
  prompt,
1976
2223
  messages,
@@ -1986,6 +2233,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1986
2233
  webAccess
1987
2234
  }) {
1988
2235
  const web = await resolveWebAccess(service, typeof webAccess === "boolean" ? webAccess : void 0);
2236
+ const effortFields = chatEffortFields("claude", model, await resolveAnswerMode(service));
1989
2237
  const mcpServerDefinition = {
1990
2238
  type: "url",
1991
2239
  name: mcpServer.name,
@@ -2013,6 +2261,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2013
2261
  data: {
2014
2262
  model,
2015
2263
  max_tokens: maxTokens,
2264
+ // `output_config: {effort}` for a fast or thorough project, nothing otherwise.
2265
+ ...effortFields,
2016
2266
  // Top level beside model/messages/mcp_servers, which is where the
2017
2267
  // Messages API takes it.
2018
2268
  ...stream.body,
@@ -2073,11 +2323,27 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2073
2323
  authorizationToken: endpoint.token
2074
2324
  }});
2075
2325
  }
2076
- async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope) {
2326
+ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope, turn) {
2077
2327
  const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
2078
2328
  const resolvedModel = model || DEFAULT_OPENAI_MODEL;
2079
2329
  const imageDetail = getOpenAIImageDetail(resolvedModel);
2330
+ const serverUrl = mcpChatUrl(endpoint.url, "openai", resolvedModel);
2080
2331
  const web = await resolveWebAccess(service);
2332
+ const effortFields = chatEffortFields("openai", resolvedModel, await resolveAnswerMode(service));
2333
+ let listedTools;
2334
+ if (turn) {
2335
+ turn.mcpToolsKey = void 0;
2336
+ turn.mcpToolsInjected = false;
2337
+ turn.mcpToolsService = void 0;
2338
+ turn.mcpToolsItemId = void 0;
2339
+ if (turn.reuseMcpToolList && !mcpListToolsReuseOff && !mcpListToolsOffStored(service)) {
2340
+ turn.mcpToolsKey = mcpListToolsKey(serverUrl, mcpScope?.anonymous, service, mcpScope?.publicProjectId, turn.userId);
2341
+ turn.mcpToolsService = service;
2342
+ listedTools = mcpListToolsCache.get(turn.mcpToolsKey);
2343
+ turn.mcpToolsInjected = !!listedTools;
2344
+ if (listedTools) turn.mcpToolsItemId = listedTools.id;
2345
+ }
2346
+ }
2081
2347
  const messageList = messages && messages.length ? prepareOpenAIMessages(messages, imageDetail) : [
2082
2348
  {
2083
2349
  role: "user",
@@ -2091,6 +2357,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2091
2357
  content: system
2092
2358
  }
2093
2359
  ] : [],
2360
+ // Right after the system message, exactly as OpenAI returned it, so OpenAI
2361
+ // skips asking the MCP server for its tools again. Absent unless stored.
2362
+ // This item passes through the server's $CLIENT_SECRET / $ACCESS_TOKEN /
2363
+ // $ID_TOKEN substitution; rememberMcpListTools never stores a listing that
2364
+ // contains one of those literals.
2365
+ ...listedTools ? [{ type: listedTools.type, id: listedTools.id, server_label: listedTools.server_label, tools: listedTools.tools }] : [],
2094
2366
  ...messageList.map((m) => ({
2095
2367
  role: m.role,
2096
2368
  content: m.content
@@ -2113,6 +2385,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2113
2385
  data: {
2114
2386
  model: resolvedModel,
2115
2387
  max_output_tokens: getMaxOutputTokens("openai", resolvedModel),
2388
+ // `reasoning: {effort}` for a fast or thorough project, nothing otherwise.
2389
+ ...effortFields,
2116
2390
  // Top level beside model/input/tools, which is where the Responses API
2117
2391
  // takes it.
2118
2392
  ...stream.body,
@@ -2123,7 +2397,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2123
2397
  {
2124
2398
  type: "mcp",
2125
2399
  server_label: MCP_NAME,
2126
- server_url: mcpChatUrl(endpoint.url, "openai", resolvedModel),
2400
+ server_url: serverUrl,
2127
2401
  require_approval: "never",
2128
2402
  // No `headers` at all for an anonymous turn: `Bearer ` with an
2129
2403
  // empty token is a credential the MCP server rejects, and the
@@ -3054,133 +3328,6 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3054
3328
  return { lead, name, tail, text: lead + (name ? " " + name : "") + tail };
3055
3329
  }
3056
3330
 
3057
- // src/engine/errors.ts
3058
- var STATUS_MESSAGE = {
3059
- "408": "The AI provider timed out before it started.",
3060
- "409": "The AI provider rejected the request as conflicting.",
3061
- "413": "The request was too large for the AI provider.",
3062
- "429": "The AI provider is rate limiting requests right now.",
3063
- "500": "The AI provider hit an internal error.",
3064
- "502": "The AI provider is temporarily unreachable.",
3065
- "503": "The AI provider is temporarily unavailable.",
3066
- "504": "The AI provider timed out."
3067
- };
3068
- function isTransientStatus(status) {
3069
- return status === 408 || status === 425 || status === 429 || status >= 500;
3070
- }
3071
- function isCsrStatusEnvelope(res) {
3072
- return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
3073
- }
3074
- function csrEnvelopeError(input) {
3075
- if (!isCsrStatusEnvelope(input)) return void 0;
3076
- if (input.status !== "failed") return void 0;
3077
- return input.error != null ? input.error : { message: "The AI provider request failed." };
3078
- }
3079
- function getErrorMessage(input) {
3080
- var envErr = csrEnvelopeError(input);
3081
- if (envErr !== void 0) input = envErr;
3082
- if (!input) return "Something went wrong.";
3083
- if (typeof input === "string") return input;
3084
- if (input.error && input.error.message) return input.error.message;
3085
- if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
3086
- if (input.body && typeof input.body.message === "string") return input.body.message;
3087
- if (input.message) return input.message;
3088
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
3089
- if (status) {
3090
- var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
3091
- return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
3092
- }
3093
- return "Something went wrong.";
3094
- }
3095
- function isRetriedFailure(input) {
3096
- var envErr = csrEnvelopeError(input);
3097
- if (envErr !== void 0) input = envErr;
3098
- return !!input && typeof input === "object" && input.retried === true;
3099
- }
3100
- function isErrorResponseBody(response) {
3101
- var envErr = csrEnvelopeError(response);
3102
- if (envErr !== void 0) response = envErr;
3103
- if (!response || typeof response !== "object") return envErr !== void 0;
3104
- if (typeof response.status_code === "number" && response.status_code >= 400) return true;
3105
- if (response.type === "error") return true;
3106
- if (response.error && (response.error.message || response.error.type)) return true;
3107
- var body = response.body;
3108
- if (body && typeof body === "object") {
3109
- if (body.type === "error") return true;
3110
- if (body.error && (body.error.message || body.error.type)) return true;
3111
- }
3112
- if (typeof response.message === "string" && response.message.length) {
3113
- var hasClaude = Array.isArray(response.content);
3114
- var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
3115
- if (!hasClaude && !hasOpenAI) return true;
3116
- }
3117
- return false;
3118
- }
3119
- function isNonRetryableRequestError(input) {
3120
- var envErr = csrEnvelopeError(input);
3121
- if (envErr !== void 0) input = envErr;
3122
- if (!input || typeof input !== "object") return false;
3123
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
3124
- var param = void 0;
3125
- var blobs = [];
3126
- var sources = [input.error, input.body && input.body.error, input.body, input];
3127
- for (var i = 0; i < sources.length; i++) {
3128
- var e = sources[i];
3129
- if (!e) continue;
3130
- if (typeof e === "string") {
3131
- blobs.push(e);
3132
- continue;
3133
- }
3134
- if (typeof e !== "object") continue;
3135
- if (param === void 0 && e.param != null) param = e.param;
3136
- if (typeof e.code === "string") blobs.push(e.code);
3137
- if (typeof e.type === "string") blobs.push(e.type);
3138
- if (typeof e.message === "string") blobs.push(e.message);
3139
- }
3140
- var hay = blobs.join(" | ").toLowerCase();
3141
- if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
3142
- return true;
3143
- }
3144
- var isClientReqStatus = status === 400 || status === 422;
3145
- if (isClientReqStatus && param != null && param !== "") return true;
3146
- if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
3147
- return true;
3148
- }
3149
- return false;
3150
- }
3151
- function isAuthExpiredError(input) {
3152
- var envErr = csrEnvelopeError(input);
3153
- if (envErr !== void 0) input = envErr;
3154
- if (!input) return false;
3155
- var blobs = [];
3156
- var push = function(v) {
3157
- if (typeof v === "string" && v) blobs.push(v);
3158
- };
3159
- if (typeof input === "string") push(input);
3160
- else {
3161
- push(input.message);
3162
- push(input.code);
3163
- if (input.error) {
3164
- push(input.error.message);
3165
- push(input.error.code);
3166
- push(input.error.type);
3167
- }
3168
- if (input.body) {
3169
- push(input.body.message);
3170
- if (input.body.error) {
3171
- push(input.body.error.message);
3172
- push(input.body.error.code);
3173
- push(input.body.error.type);
3174
- }
3175
- }
3176
- if (typeof input.status === "number" && input.status === 401) return true;
3177
- if (typeof input.status_code === "number" && input.status_code === 401) return true;
3178
- }
3179
- var hay = blobs.join(" | ").toLowerCase();
3180
- if (!hay) return false;
3181
- return hay.indexOf("token has expired") !== -1 || hay.indexOf("token is expired") !== -1 || hay.indexOf("expired_token") !== -1 || hay.indexOf("invalid_token") !== -1 || hay.indexOf("unauthorized") !== -1 || hay.indexOf("not authorized") !== -1 || hay.indexOf("invalid_request") !== -1 && hay.indexOf("token") !== -1;
3182
- }
3183
-
3184
3331
  // src/engine/citations.ts
3185
3332
  var DATA_TOOL_NAMES = [
3186
3333
  "getRecords",
@@ -6893,7 +7040,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6893
7040
  * one it was composed for. Falls back to the live read only when a caller
6894
7041
  * omits them.
6895
7042
  */
6896
- _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner) {
7043
+ _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner, turn) {
6897
7044
  if (projectId === void 0 || owner === void 0) {
6898
7045
  var id = this.host.getIdentity();
6899
7046
  if (projectId === void 0) projectId = id.projectId;
@@ -6901,14 +7048,49 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6901
7048
  }
6902
7049
  var liveId = this.host.getIdentity();
6903
7050
  var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
6904
- return platform === "openai" ? callOpenAIWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope) : callClaudeWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope);
7051
+ if (turn) turn.userId = liveId.anonymous ? "" : liveId.userId || "";
7052
+ return platform === "openai" ? callOpenAIWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope, turn) : callClaudeWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope);
7053
+ }
7054
+ /**
7055
+ * A fresh per-send record for the request builder (see requests.ts ChatTurnContext).
7056
+ * Chat turns only, and only OpenAI reuses a tool listing: Claude's MCP connector has no
7057
+ * equivalent item, and indexing passes never come through here. Off unless the host
7058
+ * set `reuseMcpToolList: true` in configureChatEngine.
7059
+ */
7060
+ _newChatTurn(platform) {
7061
+ var on = false;
7062
+ try {
7063
+ on = chatEngineConfig().reuseMcpToolList === true;
7064
+ } catch (_) {
7065
+ on = false;
7066
+ }
7067
+ return { reuseMcpToolList: platform === "openai" && on };
7068
+ }
7069
+ /**
7070
+ * What a settled chat turn means for the stored MCP tool listing: a failure drops it
7071
+ * when the turn carried it (forgetMcpListToolsOnFailure decides whether reuse also
7072
+ * stops); a good OpenAI body refreshes it. A stopped poll or a cancelled row says
7073
+ * nothing either way. Applied once per turn: an exception thrown later by a UI
7074
+ * handler on the same chain is not a provider failure.
7075
+ */
7076
+ _settleChatTurnTools(turn, response, failed) {
7077
+ if (!turn || turn.settled) return;
7078
+ turn.settled = true;
7079
+ if (failed || isErrorResponseBody(response)) {
7080
+ forgetMcpListToolsOnFailure(turn, response);
7081
+ return;
7082
+ }
7083
+ if (isPollStopped(response) || this._isCancelledPollResult(response)) return;
7084
+ rememberMcpListTools(turn, response);
6905
7085
  }
6906
7086
  dispatchAgentRequest(params) {
6907
7087
  var self = this;
6908
7088
  var dispatchItemId;
7089
+ var turn;
6909
7090
  var sendAndPoll = function() {
7091
+ turn = self._newChatTurn(params.aiPlatform);
6910
7092
  return Promise.resolve(
6911
- self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner)
7093
+ self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner, turn)
6912
7094
  ).then(function(initial) {
6913
7095
  if (initial && initial.poll && (initial.status === "pending" || initial.status === "running")) {
6914
7096
  if (initial.id) {
@@ -6937,12 +7119,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6937
7119
  }
6938
7120
  return response;
6939
7121
  }).then(function(response) {
7122
+ self._settleChatTurnTools(turn, response);
6940
7123
  if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: "", isError: false, cancelled: true };
6941
7124
  if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
6942
7125
  var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
6943
7126
  answer = (answer || "").trim();
6944
7127
  return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
6945
7128
  }).catch(function(err) {
7129
+ self._settleChatTurnTools(turn, err, true);
6946
7130
  return { content: getErrorMessage(err), isError: true };
6947
7131
  }).then(function(result) {
6948
7132
  delete self.pendingAgentRequests[params.key];
@@ -7347,7 +7531,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7347
7531
  this.scrollForDispatch(stageId);
7348
7532
  var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
7349
7533
  var capturedQueuedLid = queuedBubble._localId;
7350
- Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner)).then(function(result) {
7534
+ var queuedTurn = this._newChatTurn(aiPlatform);
7535
+ Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner, queuedTurn)).then(function(result) {
7351
7536
  var sendingIdx = self.getHistoryCacheKey() !== capturedKey ? -1 : self.state.messages.findIndex(function(m) {
7352
7537
  return m.isSendingToServer && (m.isPendingQueued || m.isPendingInProcess) && m.role === "user" && !m._stageId && (m._ownerKey === void 0 || m._ownerKey === capturedKey);
7353
7538
  });
@@ -7368,14 +7553,18 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7368
7553
  });
7369
7554
  if (serverId) self._trackPoll(serverId, "fg", qp);
7370
7555
  return qp.then(function(res) {
7556
+ self._settleChatTurnTools(queuedTurn, res);
7371
7557
  if (isPollStopped(res)) return;
7372
7558
  return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey);
7373
7559
  }).catch(function(err) {
7560
+ self._settleChatTurnTools(queuedTurn, err, true);
7374
7561
  return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey);
7375
7562
  });
7376
7563
  }
7564
+ self._settleChatTurnTools(queuedTurn, result);
7377
7565
  return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
7378
7566
  }).catch(function(err) {
7567
+ self._settleChatTurnTools(queuedTurn, err, true);
7379
7568
  return self.onQueuedSendError(capturedComposed, err, void 0, capturedKey);
7380
7569
  });
7381
7570
  return;
@@ -7396,8 +7585,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7396
7585
  this.updateHistoryCache();
7397
7586
  this.state.sending = true;
7398
7587
  this.scrollForDispatch(stageId);
7588
+ var immediateUserLid = immediateUser._localId;
7399
7589
  var historyForLlm = this.state.messages.filter(function(m) {
7400
- if (m === immediateUser) return false;
7590
+ if (m === immediateUser || immediateUserLid && m && m._localId === immediateUserLid) return false;
7401
7591
  return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder && !m.isCancelled && !m.isBackgroundTask && !m.isError;
7402
7592
  });
7403
7593
  historyForLlm.push({ role: "user", content: llmComposed });
@@ -7408,7 +7598,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7408
7598
  projectId: id.projectId,
7409
7599
  history: historyForLlm
7410
7600
  });
7411
- var immediateUserLid = immediateUser._localId, immediatePlaceholderLid = immediatePlaceholder._localId;
7601
+ var immediatePlaceholderLid = immediatePlaceholder._localId;
7412
7602
  var run = this.dispatchAgentRequest({
7413
7603
  key,
7414
7604
  projectId: id.projectId,
@@ -10385,7 +10575,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10385
10575
  (function() {
10386
10576
  var MCP_PROD = "https://mcp.broadwayinc.computer";
10387
10577
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
10388
- var BQ_VERSION = "1.19.1" ;
10578
+ var BQ_VERSION = "1.19.2" ;
10389
10579
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
10390
10580
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
10391
10581
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -15395,6 +15585,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15395
15585
  // false here restricts below it for this page, true has no effect on
15396
15586
  // a project that turned it off.
15397
15587
  skipDuplicateFiles: null,
15588
+ // Reuse the MCP tool listing OpenAI returned on an earlier chat turn, so
15589
+ // OpenAI skips fetching it again (about 0.6 s per turn). Off unless true.
15590
+ // See the engine's configureChatEngine `reuseMcpToolList`.
15591
+ reuseMcpToolList: false,
15398
15592
  // Server-driven windowed indexing; read at configureChatEngine time.
15399
15593
  // Listed here so the defaults object is the full opt surface.
15400
15594
  windowedIndexing: true,
@@ -15540,6 +15734,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15540
15734
  // Skip duplicate uploads. Same hand-over rule: only a pinned boolean is
15541
15735
  // passed, and the project's setting is the ceiling the engine applies.
15542
15736
  skipDuplicateFiles: typeof S.opts.skipDuplicateFiles === "boolean" ? S.opts.skipDuplicateFiles : void 0,
15737
+ // OpenAI MCP tool-list reuse across chat turns: only an explicit true.
15738
+ reuseMcpToolList: S.opts.reuseMcpToolList === true,
15543
15739
  // ---- live streaming (mirrored in agent.vue's ai_agent.ts) --------
15544
15740
  // Streaming itself is not passed: the engine streams whenever the two
15545
15741
  // hooks below are handed over, which skapiEngineTransport does only when