bunnyquery 1.19.0 → 1.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -2741,12 +3015,38 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2741
3015
  } else if (!grp.finished && grp.driver === "worker" && !liveIndexChecked && !liveIndexKeys[grp.key]) {
2742
3016
  grp.resolving = true;
2743
3017
  grp.resolvingReason = "status";
3018
+ var openRun = opts && opts.runStubs && (grp.path && opts.runStubs[grp.path] || opts.runStubs[grp.key]);
3019
+ var runNow = opts && opts.liveIndexRunningKeys;
3020
+ if (opts && opts.liveIndexRunningChecked && openRun && openRun.status === "working" && runNow && !runNow[grp.key] && !(grp.path && runNow[grp.path]) && !(grp.name && runNow[grp.name])) {
3021
+ grp.resolving = false;
3022
+ grp.resolvingReason = void 0;
3023
+ grp.queued = true;
3024
+ }
2744
3025
  } else {
2745
3026
  grp.resolving = false;
2746
3027
  }
2747
3028
  var runningNow = opts && opts.liveIndexRunningKeys;
2748
- if (runningNow && !grp.finished && !grp.resolving && grp.status === "active" && (liveIndexKeys[grp.key] || grp.path && liveIndexKeys[grp.path]) && !runningNow[grp.key] && !(grp.path && runningNow[grp.path]) && !(grp.name && runningNow[grp.name])) {
2749
- grp.queued = true;
3029
+ if (runningNow && !grp.finished && !grp.resolving && grp.status === "active" && !runningNow[grp.key] && !(grp.path && runningNow[grp.path]) && !(grp.name && runningNow[grp.name])) {
3030
+ var otherRunning = false;
3031
+ if (opts && opts.liveIndexRunningChecked) {
3032
+ for (var rk in runningNow) {
3033
+ if (runningNow[rk] && rk !== grp.key && rk !== grp.path && rk !== grp.name) {
3034
+ otherRunning = true;
3035
+ break;
3036
+ }
3037
+ }
3038
+ }
3039
+ var openRun2 = opts && opts.runStubs && (grp.path && opts.runStubs[grp.path] || opts.runStubs[grp.key]);
3040
+ var waitingOpenRun = !!(opts && opts.liveIndexRunningChecked && openRun2 && openRun2.status === "working");
3041
+ var startedRun = false;
3042
+ for (var mi = 0; mi < grp.members.length; mi++) {
3043
+ var mm = grp.members[mi].msg;
3044
+ if (mm && mm.role === "assistant" && !mm.isPending && !mm.isPendingInProcess && !mm.isPendingQueued) {
3045
+ startedRun = true;
3046
+ break;
3047
+ }
3048
+ }
3049
+ if (!startedRun && (liveIndexKeys[grp.key] || grp.path && liveIndexKeys[grp.path] || otherRunning || waitingOpenRun)) grp.queued = true;
2750
3050
  }
2751
3051
  }
2752
3052
  var superseded = {};
@@ -2773,6 +3073,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2773
3073
  }
2774
3074
  var now = opts && typeof opts.now === "number" ? opts.now : Date.now();
2775
3075
  var runningKeys = opts && opts.liveIndexRunningKeys;
3076
+ var runningChecked = !!(opts && opts.liveIndexRunningChecked);
2776
3077
  var stubClearedAt = opts && typeof opts.stubClearedAt === "number" && opts.stubClearedAt > 0 ? opts.stubClearedAt : 0;
2777
3078
  for (var sp in runStubs) {
2778
3079
  var rec = runStubs[sp];
@@ -2799,6 +3100,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2799
3100
  var st = "active";
2800
3101
  var fin = false;
2801
3102
  var res = false;
3103
+ var waitingStub = false;
2802
3104
  var reason;
2803
3105
  if (!live) {
2804
3106
  if (rec.status === "done" || doneKeys[sp] || doneKeys[canonIndexKey(sp)] || doneKeys[fname] || doneKeys[canonIndexKey(fname)]) {
@@ -2816,6 +3118,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2816
3118
  } else if (typeof rec.started === "number" && now - rec.started > RUN_RECORD_WORKING_STALE_MS) {
2817
3119
  st = "error";
2818
3120
  fin = true;
3121
+ } else if (runningChecked && rec.status === "working") {
3122
+ waitingStub = true;
2819
3123
  } else {
2820
3124
  res = true;
2821
3125
  reason = "status";
@@ -2849,7 +3153,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2849
3153
  resolving: res,
2850
3154
  resolvingReason: reason,
2851
3155
  stub: true,
2852
- queued: live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3156
+ queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
2853
3157
  stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0)
2854
3158
  };
2855
3159
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
@@ -3024,133 +3328,6 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3024
3328
  return { lead, name, tail, text: lead + (name ? " " + name : "") + tail };
3025
3329
  }
3026
3330
 
3027
- // src/engine/errors.ts
3028
- var STATUS_MESSAGE = {
3029
- "408": "The AI provider timed out before it started.",
3030
- "409": "The AI provider rejected the request as conflicting.",
3031
- "413": "The request was too large for the AI provider.",
3032
- "429": "The AI provider is rate limiting requests right now.",
3033
- "500": "The AI provider hit an internal error.",
3034
- "502": "The AI provider is temporarily unreachable.",
3035
- "503": "The AI provider is temporarily unavailable.",
3036
- "504": "The AI provider timed out."
3037
- };
3038
- function isTransientStatus(status) {
3039
- return status === 408 || status === 425 || status === 429 || status >= 500;
3040
- }
3041
- function isCsrStatusEnvelope(res) {
3042
- return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
3043
- }
3044
- function csrEnvelopeError(input) {
3045
- if (!isCsrStatusEnvelope(input)) return void 0;
3046
- if (input.status !== "failed") return void 0;
3047
- return input.error != null ? input.error : { message: "The AI provider request failed." };
3048
- }
3049
- function getErrorMessage(input) {
3050
- var envErr = csrEnvelopeError(input);
3051
- if (envErr !== void 0) input = envErr;
3052
- if (!input) return "Something went wrong.";
3053
- if (typeof input === "string") return input;
3054
- if (input.error && input.error.message) return input.error.message;
3055
- if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
3056
- if (input.body && typeof input.body.message === "string") return input.body.message;
3057
- if (input.message) return input.message;
3058
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
3059
- if (status) {
3060
- var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
3061
- return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
3062
- }
3063
- return "Something went wrong.";
3064
- }
3065
- function isRetriedFailure(input) {
3066
- var envErr = csrEnvelopeError(input);
3067
- if (envErr !== void 0) input = envErr;
3068
- return !!input && typeof input === "object" && input.retried === true;
3069
- }
3070
- function isErrorResponseBody(response) {
3071
- var envErr = csrEnvelopeError(response);
3072
- if (envErr !== void 0) response = envErr;
3073
- if (!response || typeof response !== "object") return envErr !== void 0;
3074
- if (typeof response.status_code === "number" && response.status_code >= 400) return true;
3075
- if (response.type === "error") return true;
3076
- if (response.error && (response.error.message || response.error.type)) return true;
3077
- var body = response.body;
3078
- if (body && typeof body === "object") {
3079
- if (body.type === "error") return true;
3080
- if (body.error && (body.error.message || body.error.type)) return true;
3081
- }
3082
- if (typeof response.message === "string" && response.message.length) {
3083
- var hasClaude = Array.isArray(response.content);
3084
- var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
3085
- if (!hasClaude && !hasOpenAI) return true;
3086
- }
3087
- return false;
3088
- }
3089
- function isNonRetryableRequestError(input) {
3090
- var envErr = csrEnvelopeError(input);
3091
- if (envErr !== void 0) input = envErr;
3092
- if (!input || typeof input !== "object") return false;
3093
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
3094
- var param = void 0;
3095
- var blobs = [];
3096
- var sources = [input.error, input.body && input.body.error, input.body, input];
3097
- for (var i = 0; i < sources.length; i++) {
3098
- var e = sources[i];
3099
- if (!e) continue;
3100
- if (typeof e === "string") {
3101
- blobs.push(e);
3102
- continue;
3103
- }
3104
- if (typeof e !== "object") continue;
3105
- if (param === void 0 && e.param != null) param = e.param;
3106
- if (typeof e.code === "string") blobs.push(e.code);
3107
- if (typeof e.type === "string") blobs.push(e.type);
3108
- if (typeof e.message === "string") blobs.push(e.message);
3109
- }
3110
- var hay = blobs.join(" | ").toLowerCase();
3111
- if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
3112
- return true;
3113
- }
3114
- var isClientReqStatus = status === 400 || status === 422;
3115
- if (isClientReqStatus && param != null && param !== "") return true;
3116
- if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
3117
- return true;
3118
- }
3119
- return false;
3120
- }
3121
- function isAuthExpiredError(input) {
3122
- var envErr = csrEnvelopeError(input);
3123
- if (envErr !== void 0) input = envErr;
3124
- if (!input) return false;
3125
- var blobs = [];
3126
- var push = function(v) {
3127
- if (typeof v === "string" && v) blobs.push(v);
3128
- };
3129
- if (typeof input === "string") push(input);
3130
- else {
3131
- push(input.message);
3132
- push(input.code);
3133
- if (input.error) {
3134
- push(input.error.message);
3135
- push(input.error.code);
3136
- push(input.error.type);
3137
- }
3138
- if (input.body) {
3139
- push(input.body.message);
3140
- if (input.body.error) {
3141
- push(input.body.error.message);
3142
- push(input.body.error.code);
3143
- push(input.body.error.type);
3144
- }
3145
- }
3146
- if (typeof input.status === "number" && input.status === 401) return true;
3147
- if (typeof input.status_code === "number" && input.status_code === 401) return true;
3148
- }
3149
- var hay = blobs.join(" | ").toLowerCase();
3150
- if (!hay) return false;
3151
- 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;
3152
- }
3153
-
3154
3331
  // src/engine/citations.ts
3155
3332
  var DATA_TOOL_NAMES = [
3156
3333
  "getRecords",
@@ -5210,6 +5387,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5210
5387
  passPaging: {},
5211
5388
  liveIndexChecked: false,
5212
5389
  liveIndexRunning: {},
5390
+ liveIndexRunningChecked: false,
5391
+ liveIndexSettled: {},
5213
5392
  stoppedIndexIds: {}
5214
5393
  };
5215
5394
  this.bgTaskQueue = [];
@@ -5237,7 +5416,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5237
5416
  * every file the server still has indexing work for; `checked` is false until the
5238
5417
  * first answer for this chat, and false means "we do not know yet". */
5239
5418
  getLiveIndexState() {
5240
- return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {} };
5419
+ return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {}, runningChecked: !!this.state.liveIndexRunningChecked, settled: this.state.liveIndexSettled || {} };
5241
5420
  }
5242
5421
  /** Passes that were on a row when the user stopped it, so the display layer can
5243
5422
  * still tell that this run was stopped once the stop has left no other trace.
@@ -5521,6 +5700,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5521
5700
  var next = {};
5522
5701
  var running = {};
5523
5702
  var truncated = false;
5703
+ var runningTruncated = false;
5524
5704
  var settledIds = {};
5525
5705
  this.state.messages.forEach(function(m) {
5526
5706
  if (!m._serverItemId) return;
@@ -5529,7 +5709,15 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5529
5709
  });
5530
5710
  for (var li = 0; li < lists.length; li++) {
5531
5711
  var list = lists[li] && Array.isArray(lists[li].list) ? lists[li].list : [];
5532
- if (list.length >= WORKER_PASS_ADOPT_LIMIT) truncated = true;
5712
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || lists[li] && lists[li].endOfList === false) {
5713
+ truncated = true;
5714
+ for (var si = 0; si < list.length; si++) {
5715
+ if (list[si] && list[si].status === "running") {
5716
+ runningTruncated = true;
5717
+ break;
5718
+ }
5719
+ }
5720
+ }
5533
5721
  for (var i = 0; i < list.length; i++) {
5534
5722
  var item = list[i];
5535
5723
  if (!item || item.status !== "pending" && item.status !== "running") continue;
@@ -5574,7 +5762,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5574
5762
  }
5575
5763
  }
5576
5764
  this.state.liveIndexKeys = next;
5765
+ if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
5766
+ var settledNow = this.state.liveIndexSettled || {};
5767
+ var settledNext = {};
5768
+ for (var sk in settledNow) if (settledNow[sk] && !next[sk]) settledNext[sk] = true;
5769
+ if (nowChecked) {
5770
+ for (var wk in was) if (was[wk] && !next[wk]) {
5771
+ if (!settledNext[wk]) changed = true;
5772
+ settledNext[wk] = true;
5773
+ }
5774
+ }
5775
+ this.state.liveIndexSettled = settledNext;
5577
5776
  this.state.liveIndexRunning = running;
5777
+ this.state.liveIndexRunningChecked = !runningTruncated;
5578
5778
  this.state.liveIndexChecked = nowChecked;
5579
5779
  this._liveIndexAt = nowMs();
5580
5780
  this._liveIndexKey = this.getHistoryCacheKey();
@@ -5585,6 +5785,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5585
5785
  _resetLiveIndexKeys() {
5586
5786
  this.state.liveIndexKeys = {};
5587
5787
  this.state.liveIndexRunning = {};
5788
+ this.state.liveIndexRunningChecked = false;
5789
+ this.state.liveIndexSettled = {};
5588
5790
  this.state.liveIndexChecked = false;
5589
5791
  this._liveIndexAt = 0;
5590
5792
  this.state.passPaging = {};
@@ -6838,7 +7040,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6838
7040
  * one it was composed for. Falls back to the live read only when a caller
6839
7041
  * omits them.
6840
7042
  */
6841
- _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner) {
7043
+ _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner, turn) {
6842
7044
  if (projectId === void 0 || owner === void 0) {
6843
7045
  var id = this.host.getIdentity();
6844
7046
  if (projectId === void 0) projectId = id.projectId;
@@ -6846,14 +7048,49 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6846
7048
  }
6847
7049
  var liveId = this.host.getIdentity();
6848
7050
  var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
6849
- 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);
6850
7085
  }
6851
7086
  dispatchAgentRequest(params) {
6852
7087
  var self = this;
6853
7088
  var dispatchItemId;
7089
+ var turn;
6854
7090
  var sendAndPoll = function() {
7091
+ turn = self._newChatTurn(params.aiPlatform);
6855
7092
  return Promise.resolve(
6856
- 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)
6857
7094
  ).then(function(initial) {
6858
7095
  if (initial && initial.poll && (initial.status === "pending" || initial.status === "running")) {
6859
7096
  if (initial.id) {
@@ -6882,12 +7119,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6882
7119
  }
6883
7120
  return response;
6884
7121
  }).then(function(response) {
7122
+ self._settleChatTurnTools(turn, response);
6885
7123
  if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: "", isError: false, cancelled: true };
6886
7124
  if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
6887
7125
  var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
6888
7126
  answer = (answer || "").trim();
6889
7127
  return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
6890
7128
  }).catch(function(err) {
7129
+ self._settleChatTurnTools(turn, err, true);
6891
7130
  return { content: getErrorMessage(err), isError: true };
6892
7131
  }).then(function(result) {
6893
7132
  delete self.pendingAgentRequests[params.key];
@@ -7292,7 +7531,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7292
7531
  this.scrollForDispatch(stageId);
7293
7532
  var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
7294
7533
  var capturedQueuedLid = queuedBubble._localId;
7295
- 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) {
7296
7536
  var sendingIdx = self.getHistoryCacheKey() !== capturedKey ? -1 : self.state.messages.findIndex(function(m) {
7297
7537
  return m.isSendingToServer && (m.isPendingQueued || m.isPendingInProcess) && m.role === "user" && !m._stageId && (m._ownerKey === void 0 || m._ownerKey === capturedKey);
7298
7538
  });
@@ -7313,14 +7553,18 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7313
7553
  });
7314
7554
  if (serverId) self._trackPoll(serverId, "fg", qp);
7315
7555
  return qp.then(function(res) {
7556
+ self._settleChatTurnTools(queuedTurn, res);
7316
7557
  if (isPollStopped(res)) return;
7317
7558
  return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey);
7318
7559
  }).catch(function(err) {
7560
+ self._settleChatTurnTools(queuedTurn, err, true);
7319
7561
  return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey);
7320
7562
  });
7321
7563
  }
7564
+ self._settleChatTurnTools(queuedTurn, result);
7322
7565
  return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
7323
7566
  }).catch(function(err) {
7567
+ self._settleChatTurnTools(queuedTurn, err, true);
7324
7568
  return self.onQueuedSendError(capturedComposed, err, void 0, capturedKey);
7325
7569
  });
7326
7570
  return;
@@ -7341,8 +7585,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7341
7585
  this.updateHistoryCache();
7342
7586
  this.state.sending = true;
7343
7587
  this.scrollForDispatch(stageId);
7588
+ var immediateUserLid = immediateUser._localId;
7344
7589
  var historyForLlm = this.state.messages.filter(function(m) {
7345
- if (m === immediateUser) return false;
7590
+ if (m === immediateUser || immediateUserLid && m && m._localId === immediateUserLid) return false;
7346
7591
  return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder && !m.isCancelled && !m.isBackgroundTask && !m.isError;
7347
7592
  });
7348
7593
  historyForLlm.push({ role: "user", content: llmComposed });
@@ -7353,7 +7598,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
7353
7598
  projectId: id.projectId,
7354
7599
  history: historyForLlm
7355
7600
  });
7356
- var immediateUserLid = immediateUser._localId, immediatePlaceholderLid = immediatePlaceholder._localId;
7601
+ var immediatePlaceholderLid = immediatePlaceholder._localId;
7357
7602
  var run = this.dispatchAgentRequest({
7358
7603
  key,
7359
7604
  projectId: id.projectId,
@@ -8953,9 +9198,23 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8953
9198
  });
8954
9199
  }
8955
9200
  /** The page progress to show for a file's row, or null (see _refreshPageProgress). */
8956
- pageProgressFor(storagePath) {
8957
- if (!storagePath || !this.state.indexPageProgress) return null;
8958
- var p = this.state.indexPageProgress[storagePath];
9201
+ pageProgressFor(storagePath, fileName) {
9202
+ var map = this.state.indexPageProgress;
9203
+ if (!map) return null;
9204
+ var p = storagePath ? map[storagePath] : void 0;
9205
+ if (!p && fileName) {
9206
+ var hit = null;
9207
+ for (var k in map) {
9208
+ if (k === fileName || k.slice(-(fileName.length + 1)) === "/" + fileName) {
9209
+ if (hit) {
9210
+ hit = null;
9211
+ break;
9212
+ }
9213
+ hit = k;
9214
+ }
9215
+ }
9216
+ if (hit) p = map[hit];
9217
+ }
8959
9218
  return p ? { saved: p.saved, total: p.total } : null;
8960
9219
  }
8961
9220
  _noteLiveLook(svcId, platform, results) {
@@ -8963,7 +9222,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8963
9222
  var complete = true;
8964
9223
  for (var r = 0; r < results.length; r++) {
8965
9224
  var list = results[r] && Array.isArray(results[r].list) ? results[r].list : [];
8966
- if (list.length >= WORKER_PASS_ADOPT_LIMIT) complete = false;
9225
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || results[r] && results[r].endOfList === false) complete = false;
8967
9226
  for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === "string") ids[list[i].id] = true;
8968
9227
  }
8969
9228
  this._lastLiveLook = complete ? { svcId, platform, at: Date.now(), ids } : null;
@@ -9994,6 +10253,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9994
10253
  uploadSingleAttachment(att, stageId) {
9995
10254
  var self = this;
9996
10255
  var id = this.host.getIdentity();
10256
+ var isIndexRetry = att.status === "indexError";
9997
10257
  att.status = "uploading";
9998
10258
  att.progress = null;
9999
10259
  att.errorMessage = "";
@@ -10046,7 +10306,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10046
10306
  }
10047
10307
  });
10048
10308
  };
10049
- return findDuplicate(member).then(function(dup) {
10309
+ if (isIndexRetry) {
10310
+ hadExists = true;
10311
+ existedBefore = true;
10312
+ }
10313
+ return (isIndexRetry ? Promise.resolve(null) : findDuplicate(member)).then(function(dup) {
10314
+ if (isIndexRetry) return;
10050
10315
  if (dup) {
10051
10316
  duplicateOf = dup;
10052
10317
  console.log("[chat-engine] skipping an upload the user already has:", member.storagePath, "->", dup);
@@ -10073,7 +10338,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10073
10338
  });
10074
10339
  }).then(function() {
10075
10340
  if (skipped) return;
10076
- return self.host.getTemporaryUrl(duplicateOf || member.storagePath);
10341
+ return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
10342
+ var ecode = err && (err.code || err.body && err.body.code);
10343
+ var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
10344
+ var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
10345
+ if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
10346
+ return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
10347
+ name: member.file.name,
10348
+ mime: member.file.type || self.host.getMimeType(member.file.name),
10349
+ size: member.file.size
10350
+ })).then(function() {
10351
+ return self.host.getTemporaryUrl(member.storagePath);
10352
+ });
10353
+ });
10077
10354
  }).then(function(url) {
10078
10355
  if (skipped) return;
10079
10356
  if (duplicateOf) {
@@ -10243,7 +10520,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10243
10520
  if (!self.state.attachments.some(function(a) {
10244
10521
  return a.id === att.id;
10245
10522
  })) return;
10246
- if (att.status === "done" || att.status === "indexError") {
10523
+ if (att.status === "done") {
10247
10524
  if (att.kind === "folder" && att.uploadedUrls) {
10248
10525
  att.uploadedUrls.forEach(function(u) {
10249
10526
  collected.push({ name: u.path, url: u.url, storagePath: u.storagePath });
@@ -10298,7 +10575,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10298
10575
  (function() {
10299
10576
  var MCP_PROD = "https://mcp.broadwayinc.computer";
10300
10577
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
10301
- var BQ_VERSION = "1.19.0" ;
10578
+ var BQ_VERSION = "1.19.2" ;
10302
10579
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
10303
10580
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
10304
10581
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -10651,7 +10928,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10651
10928
  return h(
10652
10929
  "div",
10653
10930
  {
10654
- class: "bq-bunny-loader" + (""),
10931
+ class: "bq-bunny-loader" + (overlay ? " bq-bunny-loader--overlay" : ""),
10655
10932
  "aria-hidden": "true",
10656
10933
  translate: "no"
10657
10934
  },
@@ -12553,6 +12830,21 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12553
12830
  }
12554
12831
  });
12555
12832
  }
12833
+ var genDotTick = 0, genDotTimer = null;
12834
+ function startGenDotTicker() {
12835
+ if (genDotTimer) return;
12836
+ genDotTimer = setInterval(function() {
12837
+ var els = CS.typing && CS.messagesBox ? CS.messagesBox.querySelectorAll(".bq-gen-dots") : [];
12838
+ if (!els.length) {
12839
+ clearInterval(genDotTimer);
12840
+ genDotTimer = null;
12841
+ genDotTick = 0;
12842
+ return;
12843
+ }
12844
+ genDotTick = (genDotTick + 1) % 3;
12845
+ for (var i = 0; i < els.length; i++) els[i].textContent = ".".repeat(genDotTick + 1);
12846
+ }, 400);
12847
+ }
12556
12848
  function parseMsgPartsHtml(content, opts) {
12557
12849
  var noPreviews = !!(opts && opts.imagePreviews === false);
12558
12850
  var placeholderHtml = [];
@@ -12573,7 +12865,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12573
12865
  if (CS.typing) {
12574
12866
  var openFence = working.match(/```([^\n`]+?\.[^\s.`]+)\n?/);
12575
12867
  if (openFence && typeof openFence.index === "number") {
12576
- working = working.slice(0, openFence.index) + "\n[generating " + openFence[1] + "\u2026]";
12868
+ working = working.slice(0, openFence.index) + "\n[generating " + openFence[1] + pushPlaceholder('<span class="bq-gen-dots">' + ".".repeat(genDotTick + 1) + "</span>") + "]";
12869
+ startGenDotTicker();
12577
12870
  }
12578
12871
  }
12579
12872
  var codeMasks = [];
@@ -12735,9 +13028,32 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12735
13028
  var fields = signed && signed.fields ? signed.fields : {};
12736
13029
  for (var name in fields) form.append(name, fields[name]);
12737
13030
  form.append("file", file);
12738
- return xhrUploadForm(signed.url, form, onProgress, setAbort);
13031
+ return xhrUploadForm(signed.url, form, onProgress, setAbort).catch(function(err) {
13032
+ if (err && (err === "Aborted" || err.message === "Aborted")) throw err;
13033
+ var sum = summarizeUploadError(err);
13034
+ var e = new Error("Upload failed for " + file.name + (sum.message ? ": " + sum.message : ""));
13035
+ if (sum.code) e.code = sum.code;
13036
+ throw e;
13037
+ });
12739
13038
  });
12740
13039
  }
13040
+ function summarizeUploadError(err) {
13041
+ if (!err) return { code: "", message: "" };
13042
+ if (typeof err === "string") {
13043
+ var c = /<Code>([^<]+)<\/Code>/.exec(err), m = /<Message>([^<]+)<\/Message>/.exec(err);
13044
+ var code = c ? c[1] : "", msg = m ? m[1] : "";
13045
+ if (code || msg) return { code, message: msg || code };
13046
+ return { code: "", message: err.length > 300 ? err.slice(0, 300) : err };
13047
+ }
13048
+ var ecode = err.code || err.body && err.body.code || "";
13049
+ var emsg = err.message || err.body && err.body.message || "";
13050
+ if (ecode || emsg) return { code: ecode, message: emsg };
13051
+ try {
13052
+ return { code: "", message: JSON.stringify(err).slice(0, 300) };
13053
+ } catch (x) {
13054
+ return { code: "", message: String(err) };
13055
+ }
13056
+ }
12741
13057
  var DECORATION_START = /^[<>:"\\|?*]/;
12742
13058
  function deleteFileIndexDecorations(storagePath) {
12743
13059
  if (!S.skapi || typeof S.skapi.getUniqueId !== "function") return Promise.resolve();
@@ -13365,7 +13681,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13365
13681
  if (inputEl) inputEl.value = "";
13366
13682
  }
13367
13683
  function setupDragAndDrop(chatEl) {
13368
- var depth = 0, overlay = null;
13684
+ var depth = 0, overlay = null, preparing = null;
13369
13685
  function showOverlay() {
13370
13686
  if (overlay || S.aiPlatform === "none") return;
13371
13687
  overlay = h(
@@ -13417,7 +13733,20 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13417
13733
  e.preventDefault();
13418
13734
  depth = 0;
13419
13735
  hideOverlay();
13420
- handleDrop(e.dataTransfer);
13736
+ if (preparing) return;
13737
+ preparing = h(
13738
+ "div",
13739
+ { class: "bq-drop-preparing", role: "status", "aria-live": "polite" },
13740
+ bunnyLoader("Preparing files...", false)
13741
+ );
13742
+ chatEl.appendChild(preparing);
13743
+ var done = function() {
13744
+ if (preparing && preparing.parentNode) preparing.parentNode.removeChild(preparing);
13745
+ preparing = null;
13746
+ };
13747
+ Promise.resolve().then(function() {
13748
+ return handleDrop(e.dataTransfer);
13749
+ }).then(done, done);
13421
13750
  });
13422
13751
  }
13423
13752
  function handleDrop(dt) {
@@ -13431,7 +13760,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13431
13760
  var entry2 = it.webkitGetAsEntry ? it.webkitGetAsEntry() : null;
13432
13761
  entries.push(entry2 || it.getAsFile());
13433
13762
  }
13434
- Promise.all(entries.map(function(entry3) {
13763
+ return Promise.all(entries.map(function(entry3) {
13435
13764
  if (!entry3) return Promise.resolve(null);
13436
13765
  if (entry3 instanceof File) return Promise.resolve(newAttachment({ kind: "file", name: entry3.name, file: entry3 }));
13437
13766
  if (entry3.isFile) {
@@ -13595,11 +13924,20 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13595
13924
  anchor.click();
13596
13925
  return;
13597
13926
  }
13927
+ var busy = document.createTextNode(" (fetching...)");
13928
+ anchor.classList.add("is-refreshing");
13929
+ anchor.appendChild(busy);
13930
+ var unbusy = function() {
13931
+ anchor.classList.remove("is-refreshing");
13932
+ if (busy.parentNode) busy.parentNode.removeChild(busy);
13933
+ };
13598
13934
  fetchFreshHrefForExpiredLink(originalHref, anchor.dataset.bqRemotePath).then(function(fresh) {
13935
+ unbusy();
13599
13936
  anchor.href = fresh;
13600
13937
  anchor.dataset.bqExpired = "0";
13601
13938
  anchor.click();
13602
13939
  }).catch(function(err) {
13940
+ unbusy();
13603
13941
  console.error("[bunnyquery] expired link refresh failed", err);
13604
13942
  markLinkUnavailable(linkUnavailableKeyForHref(originalHref));
13605
13943
  if (anchor.dataset.bqRemotePath) markLinkUnavailable(linkUnavailableKeyForPath(anchor.dataset.bqRemotePath));
@@ -13874,7 +14212,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13874
14212
  }
13875
14213
  function indexGroupCount(group) {
13876
14214
  if (group.stub) return "";
13877
- var prog = group.status === "active" && session && session.pageProgressFor ? session.pageProgressFor(group.path) : null;
14215
+ var prog = group.status === "active" && session && session.pageProgressFor ? session.pageProgressFor(group.path || group.key, group.name) : null;
13878
14216
  var pages = prog ? prog.total ? prog.saved + " of " + prog.total + " pages" : prog.saved + " pages" : "";
13879
14217
  var passes = group.passCount <= 1 && !group.mayHaveOlder ? "" : group.passCount + (group.mayHaveOlder ? "+" : "") + " passes";
13880
14218
  return [pages, passes].filter(Boolean).join(" \xB7 ");
@@ -14045,6 +14383,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14045
14383
  liveIndexChecked: liveIndex.checked,
14046
14384
  // Which live files have a pass running: a live row without one says "Queued".
14047
14385
  liveIndexRunningKeys: liveIndex.running,
14386
+ liveIndexRunningChecked: liveIndex.runningChecked,
14048
14387
  // Runs the user stopped. A stop that landed on a RUNNING pass leaves no
14049
14388
  // cancelled bubble behind (that pass finishes and answers normally), so
14050
14389
  // without this the row reports the stop as a finished "Indexed".
@@ -14052,7 +14391,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14052
14391
  // Durable completion markers + run records (one sweep, see above).
14053
14392
  // doneKeys settle worker-run greens without a queue round trip;
14054
14393
  // runStubs paint rows for runs whose passes are not loaded yet.
14055
- doneKeys: fresh ? markerSweep.done : void 0,
14394
+ // Plus the files the queue check saw leave the queue (agent.vue same).
14395
+ doneKeys: Object.assign({}, fresh ? markerSweep.done : {}, liveIndex.settled || {}),
14056
14396
  runStubs: stubs,
14057
14397
  // Records are service-wide and horizon-blind; without this every
14058
14398
  // "Clear chat history" resurrected one row per indexed file.
@@ -14552,6 +14892,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14552
14892
  var moPatch = { status: "done", finished: typeof moLast === "number" ? moLast : Date.now() };
14553
14893
  if (typeof moFirst === "number") moPatch.started = moFirst;
14554
14894
  if (mog.name) moPatch.filename = mog.name;
14895
+ if (S.aiPlatform === "claude" || S.aiPlatform === "openai") moPatch.platform = S.aiPlatform;
14555
14896
  void upsertIndexRunRecordDb(S.projectId, mog.path, moPatch);
14556
14897
  if (morec) morec.status = "done";
14557
14898
  else markerSweep.runs[mog.path] = { status: "done" };
@@ -14731,10 +15072,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14731
15072
  }
14732
15073
  });
14733
15074
  input.addEventListener("keydown", function(e) {
14734
- if (e.key === "Enter" && !e.shiftKey && !composing) {
14735
- e.preventDefault();
14736
- sendMessage();
14737
- }
15075
+ if (e.key !== "Enter" || e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) return;
15076
+ if (composing || e.isComposing || e.keyCode === 229) return;
15077
+ e.preventDefault();
15078
+ sendMessage();
14738
15079
  });
14739
15080
  requestAnimationFrame(function() {
14740
15081
  autoGrowInput(input);
@@ -14799,6 +15140,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14799
15140
  CS.historyStartKeyHistory = Array.isArray(loaded.startKeyHistory) ? loaded.startKeyHistory.slice() : [];
14800
15141
  session.aiChatHistoryCache[cacheKey2] = Object.assign({}, loaded, { messages: restored });
14801
15142
  renderMessages();
15143
+ scrollToBottom();
14802
15144
  }
14803
15145
  if (loaded && !session.needsHistoryRefetch()) {
14804
15146
  session.drainBgTaskQueue();
@@ -15243,6 +15585,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15243
15585
  // false here restricts below it for this page, true has no effect on
15244
15586
  // a project that turned it off.
15245
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,
15246
15592
  // Server-driven windowed indexing; read at configureChatEngine time.
15247
15593
  // Listed here so the defaults object is the full opt surface.
15248
15594
  windowedIndexing: true,
@@ -15388,6 +15734,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15388
15734
  // Skip duplicate uploads. Same hand-over rule: only a pinned boolean is
15389
15735
  // passed, and the project's setting is the ceiling the engine applies.
15390
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,
15391
15739
  // ---- live streaming (mirrored in agent.vue's ai_agent.ts) --------
15392
15740
  // Streaming itself is not passed: the engine streams whenever the two
15393
15741
  // hooks below are handed over, which skapiEngineTransport does only when