bunnyquery 1.19.1 → 1.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.mjs CHANGED
@@ -78,6 +78,30 @@ function normalizeSkipDuplicateFiles(value) {
78
78
  function skipDuplicateFilesFrom(data) {
79
79
  return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
80
80
  }
81
+ var ANSWER_MODES = ["standard", "fast", "thorough"];
82
+ var DEFAULT_ANSWER_MODE = "standard";
83
+ var ANSWER_MODE_SETTING_LABEL = "Answer mode";
84
+ var ANSWER_MODE_LABELS = {
85
+ standard: "Standard",
86
+ fast: "Fast",
87
+ thorough: "Thorough"
88
+ };
89
+ var ANSWER_MODE_HINTS = {
90
+ standard: "The AI model decides how long to think. This is the default.",
91
+ fast: "Shorter thinking for quicker answers. Best for simple questions.",
92
+ thorough: "Longer thinking before answering. Slower, and uses more tokens."
93
+ };
94
+ var ANSWER_MODE_OPTIONS = ANSWER_MODES.map((value) => ({
95
+ value,
96
+ label: ANSWER_MODE_LABELS[value],
97
+ hint: ANSWER_MODE_HINTS[value]
98
+ }));
99
+ function normalizeAnswerMode(value) {
100
+ return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
101
+ }
102
+ function answerModeFrom(data) {
103
+ return normalizeAnswerMode(data ? data.answer_mode : void 0);
104
+ }
81
105
  var CHAT_GREETING_MAX_LENGTH = 400;
82
106
  function normalizeChatGreeting(value) {
83
107
  if (typeof value !== "string") return "";
@@ -167,6 +191,9 @@ function projectWebAccess(service) {
167
191
  function projectSkipDuplicateFiles(service) {
168
192
  return skipDuplicateFilesFrom(cachedProjectSettings(service));
169
193
  }
194
+ function projectAnswerMode(service) {
195
+ return answerModeFrom(cachedProjectSettings(service));
196
+ }
170
197
  function setProjectSettings(service, data) {
171
198
  if (!service) return;
172
199
  cache.set(service, { data: data || null, settled: true, inflight: null });
@@ -249,6 +276,10 @@ function resolveWebAccess(service, override) {
249
276
  if (!service) return Promise.resolve(underCeiling(webAccessFrom(null), opt, override));
250
277
  return loadProjectSettings(service).then(webAccessFrom, () => false).then((setting) => underCeiling(setting, opt, override));
251
278
  }
279
+ function resolveAnswerMode(service) {
280
+ if (!service) return Promise.resolve(answerModeFrom(null));
281
+ return loadProjectSettings(service).then(answerModeFrom, () => answerModeFrom(null));
282
+ }
252
283
  function skipDuplicateFilesEnabled(service) {
253
284
  const opt = _config ? _config.skipDuplicateFiles : void 0;
254
285
  return underCeiling(skipDuplicateFilesFrom(service ? cachedProjectSettings(service) : null), opt);
@@ -807,51 +838,50 @@ function buildChatSystemPrompt(params) {
807
838
  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`}.
808
839
  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.
809
840
  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.`;
810
- 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.`}`;
841
+ 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.`;
842
+ 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.`;
843
+ const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
844
+ 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, and never rely on a default: a group left off is NOT "all groups", and any user but the project's owner is then answered from access_group 0 (public) alone${groupIsPublic ? "" : `, so a table indexed at ${indexGroupLiteral} would look 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. 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.`;
811
845
  let systemPrompt = `
812
846
  You are a dedicated assistant for the project ID: "${projectId}".
813
847
  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.
814
- 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.
848
+ Knowledge lookup: before saying you don't know, or that something isn't in the chat history, ALWAYS search this project's data with the tools: the project's data lives in its database, not in the earlier messages of this chat.
815
849
  ${groundingRules}
850
+ ${webRule}
816
851
  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.
817
- 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.
818
- 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.
819
- 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.
852
+ 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>" (see the access group rule below); every later mention of a file's records means this call. Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder).
853
+ NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set, keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. A FILE TOTAL IS NOT A ROW'S TOTAL: the biggest number on a summary sheet is the whole file, not the thing asked about, so check every figure is scoped to what the question named (filter by the column that identifies it). Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
820
854
  ${documentRules}
821
- 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.
822
- 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.
823
- 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.
824
- 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.
825
- - 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.
826
- - 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.
827
- ${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).`}
828
- 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.
829
- 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.
830
- 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.
831
- 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.
855
+ ${accessGroupRule}
856
+ COMPLETE ANSWERS: ONE file is routinely SPLIT ACROSS SEVERAL TABLES (a summary row in one, its page or row content in another, its extracted pictures in "__MEDIA__"), so for anything not scoped to a single file run the query in EVERY 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?"), read the COMPLETE matching set across every such table and file before answering. Never assert absence ("there is no X", "none", "not found", "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4") until a complete scan has come back empty: a confident "no" that later turns out wrong is worse than telling the user you are still checking. If you answered from one table and then find another holds more, re-run the sweep and give the complete answer instead of only apologising.
857
+ Embedded values: a search term is often stored inside a larger string (a merchant "BAKSA" as "DNH*BAKSA#4070277042", a card as "5860****5173"), which no index or tag filter matches. When the value may be embedded, fetch the full set with fetch_all and match the substring yourself.
858
+ File attachments: an "Attached files:" section with markdown links in a user message points at short-lived signed URLs in this project's storage. Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY in the message as image blocks: look at them directly. Every other attached file (office documents such as .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, PDFs, email (.eml), text/data/code files such as .csv/.tsv/.json/.xml/.txt/.md) is ALREADY INDEXED: it was read end to end when it was uploaded, before this message reached you, so answer from its records (reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS). Some turns instead carry the file text between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers: read that block directly; a "[skapi: ...]" note inside it means that file could not be extracted. ${webAccess ? `Never web_fetch an attachment link (the picture is already in the message, everything else is in the database); a file the user gives as an outside web address may be fetched under the web rule above.` : `This chat has no web tool: never try to download or fetch an attachment link.`}
859
+ Stored files: a file already in this project's storage was read end to end at upload time, so its records come first. For its exact wording find the page with searchText (DOCUMENTS); readFileContent re-reads the raw file (an older file without page text, a data file), and you read it to the end before concluding anything is absent there. If its pictures do not reach you, say so plainly and fall back to the indexed records; never call a file unreadable when its content is in the database.
860
+ File links: give every "src::" file as a link in the format getRecords' description sets. In this chat client a db: link is a button that fetches a fresh signed URL on demand, so never call a file inaccessible or a URL expired when you have its storage path.
861
+ File lookup: to see, list or show files ("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__" (at its document's access group). Present each as a link. Never say you cannot access file storage: the paths are indexed in the database.
862
+ Showing images: "show me the photo", "\uBCF4\uC5EC\uC918", "display it" asks for the file's LINK: this client renders an image's db: link as the picture itself, inline, so the link IS the image on screen, and the same goes for any file the user asks to see. Never answer 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. Describe an image only when the user asked ABOUT its contents, or when you genuinely have no path for it.
832
863
  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.
833
- Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
864
+ Finding an extracted media file (a photo, or a diagram in a deck or a PDF alike): it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename or guessing a table.
834
865
  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.
835
- 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.
866
+ The reliable query is the document's records (reference "src::<the document's storage path>"). Scan them for the one describing what you want (its part number, tag id, anchor, caption or description) and take its "__MEDIA__/..." value.
836
867
  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.
837
868
  So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
838
- 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.
839
- 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.
869
+ 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, read the document's records again, 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.
840
870
  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.
841
- 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:
871
+ 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:
842
872
  \`\`\`filename.csv
843
873
  item,qty,total
844
874
  Carrots,55,$38.50
845
875
  Mushrooms,41,$73.80
846
876
  Zucchini,29,$43.50
847
877
  \`\`\`
848
- The same pattern applies to any format - name the block after the file you intend: \`\`\`my-data.json, \`\`\`index.html, \`\`\`sample.txt, and so on.`;
878
+ Any format works the same way: \`\`\`my-data.json, \`\`\`index.html, \`\`\`sample.txt.`;
849
879
  systemPrompt += `
850
880
  About BunnyQuery (this app - questions about it are in scope):
851
- You are the assistant inside BunnyQuery, an AI assistant for the user's own business data. Instead of digging through folders, dashboards and files, the user uploads their documents, spreadsheets, images, notes and records, BunnyQuery indexes them into this project's database, and you answer questions, write reports and summarize from THAT data rather than from the open internet. Each project has its own data, its own AI platform (ChatGPT or Claude, powered by the project owner's own API key) and its own base prompt. BunnyQuery is built on Skapi (www.skapi.com), so the same project database is also reachable over MCP from any MCP-compatible AI client (mcp.broadwayinc.computer), and this chat can be embedded in a website as a widget with one script tag. Answer product questions from the facts in this section. If you are asked something about BunnyQuery that is NOT stated here - pricing, plan limits, a roadmap, a feature you cannot see - say you are not certain and point the user at the project owner or the BunnyQuery site, rather than inventing it.
881
+ You are the assistant inside BunnyQuery, an AI assistant for the user's own business data. Instead of digging through folders, dashboards and files, the user uploads their documents, spreadsheets, images, notes and records, BunnyQuery indexes them into this project's database, and you answer questions, write reports and summarize from THAT data rather than from the open internet. Each project has its own data, its own AI platform (ChatGPT or Claude, powered by the project owner's own API key) and its own base prompt. BunnyQuery is built on Skapi (www.skapi.com), so the same project database is also reachable over MCP from any MCP-compatible AI client (mcp.skapi.com), and this chat can be embedded in a website as a widget with one script tag. Answer product questions from the facts in this section. If you are asked something about BunnyQuery that is NOT stated here - pricing, plan limits, a roadmap, a feature you cannot see - say you are not certain and point the user at the project owner or the BunnyQuery site, rather than inventing it.
852
882
  How data gets in: ${canUpload === false ? `this user CANNOT upload in this session (they are not signed in, or the project's database is frozen for non-admins), and the attach affordances are hidden from them. Never instruct them to attach, drag in or upload a file, and never blame a missing answer on them not having uploaded it. Answer from what is already indexed, and when something genuinely is not in the project, say so and suggest asking the project's owner to add it.` : `the user attaches files to a chat message with the paperclip button in the composer, or drags and drops them onto the chat (whole folders work; up to 20 files per message). Uploaded files land in this project's file storage and are indexed automatically: read end to end and turned into database records. "Indexed" means exactly that, and it is why you can only answer from a file once its indexing has finished. While a file indexes, the chat shows a status row for it: yellow while it is working, green when it is indexed, red if it failed. A large file is indexed in windows over several passes, which takes longer; indexing runs on the server, so it keeps going if the user closes the page and the row is still there when they come back. The user can also paste plain text straight into the chat and ask you to save it - store it with the postRecords tool. BunnyQuery reads over 50 formats: office documents (.docx, .xlsx, .pptx, .hwp, .hwpx, .odt, .ods, .odp, .epub), email (.eml), PDFs, images, .csv/.tsv, .json, .xml, .html, .txt/.md and source code. Images and scanned PDFs are read with vision at index time.`}
853
883
  Getting answers out: the user asks in plain language, in any language, and you answer from this project's data. You can also produce reports and downloadable files (CSV and the rest) as described in the File generation rules above, and any stored file can be handed back as a link, with images rendering inline in the chat.${client === "console" ? `
854
- Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.` : ""}${client === "widget" ? `
884
+ Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, the Answer mode (Standard, Fast or Thorough: how quickly or how deeply you work on each answer), and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.` : ""}${client === "widget" ? `
855
885
  This chat is the BunnyQuery widget embedded in a website, so the user may have no access to the project console: keep any instructions to what can be done here in the chat.` : ""}`;
856
886
  if (greeting) {
857
887
  systemPrompt += `
@@ -870,9 +900,9 @@ function buildIndexingSystemPrompt(params) {
870
900
  const { projectId, serviceName, serviceDescription } = params;
871
901
  const accessGroup = params.accessGroup === "public" || params.accessGroup === "private" ? params.accessGroup : "authorized";
872
902
  let systemPrompt = `You are a background indexing agent for project ${projectId}.
873
- - 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.
903
+ - Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message: look at them directly, and never fetch an image URL.
874
904
  - Most 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) have ALREADY been extracted on the server and included inline in the user message between the "BEGIN FILE CONTENT" / "END FILE CONTENT" markers - read that directly. If the inline content is a "[skapi: ...]" note, the file could not be extracted - index it from its metadata only.
875
- - BIG SPREADSHEETS / TEXT: the inline content may be only the FIRST part of a large file (it can end with a truncation or "more remains" note). UNLESS this message already embeds a window of the file (in which case the message tells you not to call readFileContent, and you must not), read big spreadsheets and big text/data files WITH THE readFileContent TOOL: it returns the file ONE WINDOW at a time (spreadsheets as coordinate-tagged grid rows, text as a range of characters). Pass the file's storage path. After each window: datafy it into records and SAVE them, THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed - never stop after the first window. (Do NOT call readFileContent on a PDF - see the next line.)
905
+ - BIG SPREADSHEETS / TEXT: the inline content may be only the FIRST part of a large file (it can end with a truncation or "more remains" note). UNLESS this message already embeds a window of the file (in which case the message tells you not to call readFileContent, and you must not), read big spreadsheets and big text/data files WITH THE readFileContent TOOL: it returns the file ONE WINDOW at a time (spreadsheets as coordinate-tagged grid rows, text as a range of characters). Pass the file's storage path. After each window: datafy it into records and SAVE them, THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed - never stop after the first window.
876
906
  - PDFs (scanned or not): you do NOT read a PDF with a tool or a URL. Its pages are RENDERED and embedded directly in the user message as IMAGE blocks, a WINDOW of pages at a time. LOOK at the embedded page images and datafy every one. The note beside them tells you whether MORE pages remain: if so, save this window's records and stop (a follow-up pass shows the next window automatically); only when the note says it was the LAST window is the PDF fully seen. Do NOT call readFileContent or web_fetch for a PDF.
877
907
  - VISION: when the message (a readFileContent window, an embedded PDF page, or an inline attachment) includes IMAGES - scanned/rendered PDF pages, or photos embedded in a spreadsheet next to a row/block - LOOK at them and capture what they show as record data (the reading/values in a scanned table, the part/defect/condition visible in a photo). The image IS part of the data; correlate each photo with its labelled block ("PHOTO A3" markers tie a photo to that grid row).
878
908
  - TRANSCRIBE, DO NOT DESCRIBE. When an image contains ANY text - a label, tag, stamp, form field, serial/part number, handwriting - your FIRST job is to read the characters out and store them VERBATIM, not to describe the scene. A record saying "a red inspection tag with handwritten markings" is worthless: it is unsearchable and every such photo produces the same sentence. Put the characters you can actually read into these EXACT fields, not variations of them: "printed_text" (the pre-printed wording), "handwritten_text" (what a person wrote by hand), and, when you can resolve one, "part_no", "tag_id" and "date". Same reason as the fixed table names: a field called photo_text in one pass and visible_text_notes in the next cannot be queried together. Read PARTIAL values rather than skipping: "500.7402.52__" beats nothing. Only when a character is genuinely unreadable, leave that field null or mark the unreadable span - do NOT invent it, and do NOT replace the whole transcription with a description of what the object looks like. A scene description is a nice extra AFTER the text, never instead of it.
@@ -880,15 +910,15 @@ function buildIndexingSystemPrompt(params) {
880
910
  - Whatever the file type, this file's identity is "src::" + its storage path (the "storage path" metadata line) - never the inline content or a temporary URL. That record ALREADY EXISTS: the upload pipeline creates it in table "file_summaries" (access group "${accessGroup}") before indexing starts, so posting it again is rejected as a duplicate unique_id. Reference it from every record you write, and add what you learn to it with updateRecords. If that update unexpectedly reports the record does not exist, post it yourself ONCE with that exact "src::" unique_id (table "file_summaries", access group "${accessGroup}") and carry on; this is the ONE exception to the do-NOT-post-the-file-record rules elsewhere in these instructions, because the source identity must never be dropped just because an update failed.
881
911
  - ACCESS GROUP (hard rule): every record you write for this file - the file record, per-row records, chapters, summaries, intermediates - MUST be posted with access group "${accessGroup}". Pass it explicitly on every postRecords call; do not leave it out and do not vary it between passes of the same file. An access group is part of a record's table key, so records saved under a different group than the file are in a different table and will not come back with the rest of it: a "public" file whose rows were saved as "authorized" is one an anonymous visitor can see the name of and none of the contents of, and a re-index cannot find the strays to clean them up. The one exception is the EXTRACTED MEDIA records in "__MEDIA__", which the pipeline creates for you - leave their group alone and only enrich them.
882
912
  - REACHABILITY (hard rule): every record you write while indexing this file MUST be reachable from the file's "src::<storage path>" record by following reference - either reference that record directly, or reference something that already reaches it. A record with no reference, or one pointing outside this file's chain, is an ORPHAN: deleting or re-indexing the file removes the reachable records and leaves the orphan behind forever, where it keeps turning up in later answers as stale data. If you create an intermediate record that OTHER records reference (a page record that rows hang off, a sheet or section record), set source.can_remove_referencing_records to true on it; the delete cascade passes a delete through a record only when that record carries the flag OR a unique_id starting "src::" (the file record cascades because its unique_id starts with "src::"; the intermediates you create carry no "src::" id, so they need the flag), and it cascades ONE LEVEL AT A TIME, so EVERY intermediate record in a chain needs its own marker - an unmarked link stops the cascade there and everything below it survives as orphans. When in doubt, reference the file record directly and keep the chain flat.
883
- - TABULAR data (any spreadsheet - .csv/.tsv/.xlsx/.xls/.ods, or sheet-like rows): UNLESS the message tells you the server has ALREADY saved this spreadsheet's rows as records (in which case you must NOT write row records and must NOT call readFileContent for it; your only job is the file-level summary it describes), you MUST save EVERY data row as its own record (ONE record per row) with that row's actual column values in the record's "data", keyed by the header names, in a table named EXACTLY "spreadsheet_rows". Do NOT summarize, sample only a few rows, or save just file metadata - index the whole sheet, window by window, until it ends. Make MULTIPLE postRecords calls in batches (e.g. 30-50 rows per call) rather than one oversized call. This per-row completeness OVERRIDES brevity. The file-level "src::" record ALREADY EXISTS - the upload pipeline creates it before indexing starts - so do NOT create it. Link EVERY per-row record to it via reference (set each row record's reference to exactly "src::" + the storage path, with NO sheet/window/summary suffix added; the row records themselves do NOT carry a src:: unique_id). Enrich that same record with sheet name(s), column headers and total row count via updateRecords rather than posting another one. The per-row records AND this reference linkage are BOTH mandatory: the linkage is what lets the whole sheet be found and cleaned up together when the file is re-indexed. INDEX each row record on the row's most useful NUMERIC column (named by its header) so rows sort and range-query; when the row has no numeric column, index the grid row number instead. TAG each row record with the sheet name, the file name, and the row's categorical values (a status, a category, a type) - tags are how rows are filtered without scanning the table.
913
+ - TABULAR data (any spreadsheet - .csv/.tsv/.xlsx/.xls/.ods, or sheet-like rows): UNLESS the message tells you the server has ALREADY saved this spreadsheet's rows as records (in which case you must NOT write row records and must NOT call readFileContent for it; your only job is the file-level summary it describes), you MUST save EVERY data row as its own record (ONE record per row) with that row's actual column values in the record's "data", keyed by the header names, in a table named EXACTLY "spreadsheet_rows". Do NOT summarize, sample only a few rows, or save just file metadata - index the whole sheet, window by window, until it ends. Make MULTIPLE postRecords calls in batches (e.g. 30-50 rows per call) rather than one oversized call. This per-row completeness OVERRIDES brevity. Set each row record's reference to exactly "src::" + the storage path, with NO sheet/window/summary suffix (the rows carry no "src::" unique_id of their own), and add the sheet name(s), column headers and total row count to that file record with updateRecords. INDEX each row record on the row's most useful NUMERIC column (named by its header) so rows sort and range-query; when the row has no numeric column, index the grid row number instead. TAG each row record with the sheet name, the file name, and the row's categorical values (a status, a category, a type) - tags are how rows are filtered without scanning the table.
884
914
  - WINDOW TAG. The message that shows you a window of a file names a tag of the form "win::" followed by a short code, and tells you to put it on every record you save from that window. Do it, on EVERY record, alongside the record's other tags. It is how the server removes exactly that window's records if the window ever has to be sent to you again, so that a retry never doubles what is stored. Never invent one, never reuse one from another window, and never leave it off.
885
915
  - ONE RECORD PER GRID ROW, ALWAYS. "Row" means the numbered row of the sheet (R37 is one record), never a visual block, item, section or left/right pair. Sheets that repeat the same columns side by side (an A/B block beside a C/D block, "paired" or "mirrored" layouts) still get ONE record per grid row, holding BOTH sides - suffix the keys to keep them apart (PART_NO_A / PART_NO_B). Collapsing a 16-row window into 2 or 3 "block" records is the single most damaging mistake here: it silently loses most of the cells and makes every later total wrong, because some windows were counted per row and others per block. If a window shows rows R37 to R52, you save records for R37..R52 and the count you report is the number of grid rows you actually wrote.
886
916
  - THE FILE NAME AND ITS FOLDERS ARE EVIDENCE ABOUT WHAT THE DATA MEANS, and often the only evidence there is. A grid of bare figures filed under "2026/Q2/royalties" is a quarterly royalty settlement; the same grid under "inspections/KCG-B507" is one aircraft's inspection. Nothing inside the sheet says so. Read the trail in the metadata block and use it: name the period, the entity, the counterparty or the subject in the file record's description, and TAG the records with the meaningful parts of it (the client, the aircraft, the quarter, the site), so a later question about that entity finds this file at all. A folder that is only an id or a date is still worth a tag; a folder like "uploads", "new" or "temp" is not.
887
917
  - BUT NEVER INSTEAD OF READING. The path tells you what the data is ABOUT; only the content tells you what it SAYS. Never infer a value, a column meaning, a row count or a total from a name, never let a name override what the cells actually contain, and never derive a TABLE name from a folder or a file name - table names are fixed (see below), and a table named after a folder scatters one kind of record across as many tables as the user has folders. Where the name and the content disagree, the content wins and the disagreement is worth recording.
888
- - FIXED TABLE NAMES. Never invent a table name for one pass, and never vary the name between passes of the SAME file: that scatters one file's data across tables nobody can enumerate later, so the data is effectively lost even though every save succeeded. Use exactly "spreadsheet_rows" for spreadsheet row records, "book_chapters" for a chapter record, "email_messages" for an email message record (see EMAIL below), "file_summaries" for the file-level record (which already exists, so update it and never post it), and "document_entries" for EVERYTHING you take from a document's pages or sections (a PDF, a Word file, slides, a scan, a web page, an attachment's prose): one record per row / table entry / line item / section, with "page" (the DOCUMENT PAGE number, when the content has pages) and "kind" (row, entry, section, figure or note) in its data. Embedded photos and other embedded files get NO table of your choosing: their records already exist in table "__MEDIA__", see EXTRACTED MEDIA below. There is NO other table: content that fits none of the above goes to "document_entries" too. Never choose a table name of your own (inspection_items / item_records / manual_page_entries / pdf_pages are names for what is one table): the passes of one file run side by side and cannot agree on a name, and the server stores a post to any other table in "document_entries" anyway. TAGS are stored normalized by the server (lowercase, no spaces or punctuation, plus one tag per word): write each tag naturally, one concept per tag, and never try to vary its spelling or case.
918
+ - FIXED TABLE NAMES. Use exactly "spreadsheet_rows" for spreadsheet row records, "book_chapters" for a chapter record, "email_messages" for an email message record (see EMAIL below), "file_summaries" for the file-level record (it already exists, see above), and "document_entries" for EVERYTHING you take from a document's pages or sections (a PDF, a Word file, slides, a scan, a web page, an attachment's prose): one record per row / table entry / line item / section, with "page" (the DOCUMENT PAGE number, when the content has pages) and "kind" (row, entry, section, figure or note) in its data. Embedded photos and other embedded files get NO table of your choosing: their records already exist in table "__MEDIA__", see EXTRACTED MEDIA below. There is NO other table: content that fits none of the above goes to "document_entries" too. Never choose a table name of your own, and never vary one between passes (inspection_items / item_records / manual_page_entries / pdf_pages are names for what is one table): the passes of one file run side by side and cannot agree on a name, a scattered file cannot be found again, and the server stores a post to any other table in "document_entries" anyway. TAGS are stored normalized by the server (lowercase, no spaces or punctuation, plus one tag per word): write each tag naturally, one concept per tag, and never try to vary its spelling or case.
889
919
  - EXTRACTED MEDIA: every PICTURE embedded in an uploaded document (photos, diagrams, chart images) is pulled out and saved as a real permanent file under "__MEDIA__/<the document's storage path>/<name>", and a record for each one ALREADY EXISTS in table "__MEDIA__" with unique_id "src::<that path>", reference "src::<the document>", and its path, anchor and sheet already in data. Do NOT create it - the unique_id is taken and your post is rejected. UPDATE it with updateRecords, addressed by that unique_id, adding what the file actually SHOWS plus TAGS for every identifier visible in it (part numbers, tag ids, item names, serial numbers). An update REPLACES the fields you send, so send the existing tags back with your new ones and keep every field already in data (path, anchor, sheet, source, mime, bytes). ONE FILE, ONE RECORD: never also create a photo record in another table. If the update reports that the record does not exist, create it with that same unique_id, reference and data.path - the path must never be lost. Audio and video clips and non-picture attachments are never saved as separate files (an email's attachment text is read inline instead, see EMAIL below), so never claim a separate file or a "__MEDIA__" record exists for one of those.
890
920
  - AUDIO files: transcribe the speech, and capture speakers (named where identifiable), the topics discussed, and timestamps of key moments in the record's data. TAG the language, the audio type (call, meeting, dictation, music), each speaker and every named entity; INDEX the duration in seconds as duration_seconds. VIDEO files: everything audio gets, PLUS transcribe on-screen text verbatim (same transcription discipline as photos) and capture the visual timeline - scene changes and what each scene shows, with timestamps. Same tags as audio plus every entity visible on screen, and INDEX duration_seconds here too. These audio and video rules apply to files UPLOADED AS FILES: the transcript and timeline land on the file's own "src::" record, which already exists. Audio or video embedded inside a document is NOT extracted, so never look for or promise a "__MEDIA__" record for it.
891
- - EPUB / e-books / long-form books (.epub or any book-length prose, provided inline in reading order with chapter headings preserved): you MUST save ONE record per CHAPTER (or, when chapters are unclear, per major section/topic) in the table "book_chapters" - never collapse the whole book into a single record. INDEX each chapter record on its chapter number (so chapters sort and range-query in order) and include the chapter title among its tags; the record's "data" must capture the chapter title plus its order/number AND a substantive summary of that chapter's content (key events, arguments, characters, places, concepts, terms, notable quotes). Apply AS MANY relevant tags as possible to EVERY chapter record (characters, locations, themes, topics, key concepts, key terms, dates, named entities) so the book is easy to SEARCH and cross-reference later - this is the whole point. ALSO put the book-level facts (title, author, language, overall summary, chapter list / table of contents, genre/subjects) onto the "src::" file record that ALREADY EXISTS in "file_summaries", using updateRecords. Do NOT post a second book-level record, and set every chapter record's reference to exactly "src::" + the storage path. This per-chapter completeness OVERRIDES brevity; human-readable summaries only, never raw/binary bytes.
921
+ - EPUB / e-books / long-form books (.epub or any book-length prose, provided inline in reading order with chapter headings preserved): you MUST save ONE record per CHAPTER (or, when chapters are unclear, per major section/topic) in the table "book_chapters" - never collapse the whole book into a single record. INDEX each chapter record on its chapter number (so chapters sort and range-query in order) and include the chapter title among its tags; the record's "data" must capture the chapter title plus its order/number AND a substantive summary of that chapter's content (key events, arguments, characters, places, concepts, terms, notable quotes). Apply AS MANY relevant tags as possible to EVERY chapter record (characters, locations, themes, topics, key concepts, key terms, dates, named entities) so the book is easy to SEARCH and cross-reference later - this is the whole point. ALSO put the book-level facts (title, author, language, overall summary, chapter list / table of contents, genre/subjects) onto the file's "src::" record with updateRecords (never a second book-level record), and reference it from every chapter record. This per-chapter completeness OVERRIDES brevity; human-readable summaries only, never raw/binary bytes.
892
922
  - EMAIL (.eml, provided inline with "=== EMAIL ===" / "=== BODY ===" / "=== ATTACHMENT i/N: ..." / "=== FORWARDED MESSAGE k (depth d) ===" headings, which always start at column 0; a body line that merely looks like one is body text): you MUST save ONE record per email MESSAGE in the table "email_messages", and a forwarded message inside it (its own "=== EMAIL ===" block) gets its OWN record. Each record carries subject, from, to, cc, date (the Date line: an ISO string when the layer could parse it, otherwise the raw header text), message_id, in_reply_to, and the body text (quoted earlier replies included). INDEX each record on its date as that string exactly as given, and include the sender address, every recipient address and the subject among its tags. Text under an "=== ATTACHMENT" heading is that attachment's extracted content: datafy it by its own kind (rows into "spreadsheet_rows" for a spreadsheet, one record per section in "document_entries" for a document), tag those records with the attachment's filename, and give EVERY record the same "src::" reference as the email. Picture attachments are extracted into "__MEDIA__" like any other embedded picture (their media anchor is quoted on the "[picture ...]" line); other attachments are read inline: their content becomes the records above, but no separate FILE or file record exists for one, so never cite a path for it.
893
923
  - URL SOURCES: when the source being indexed is a URL rather than an uploaded file (a temporary or signed URL that merely DELIVERS an uploaded file's bytes is not a URL source; that file keeps its storage-path identity), its identity is "src::" + the FULL URL INCLUDING the query string (the query string often selects the content, so dropping it collapses different pages into one identity). If no record with that unique_id exists, create it; if the slot is already taken, update that record or reference it - never mint a variant id. For a WEB PAGE: extract everything on it, infer the page's primary entity type when it is not obvious (product, listing, article, profile), TAG that entity type plus the entities on the page, and INDEX the ONE number every entity of that type can be compared by (a price for a product, a date for an article). Any OTHER URL (a file behind a link) is downloaded and indexed under whichever per-type rule above matches its content. When the URL's content offers more index points than one record carries, add reference-linked records reachable from its "src::" record.
894
924
  - This is a background indexing task: do ALL the MCP saving FIRST, never reply mid-task, and never ask the user questions. Be exhaustive about meaning (and, for tabular data, about every row). SAVE AS YOU GO: persist each window's records before reading the next, so progress is never lost. If the file is so large you cannot finish in one turn, still save everything you have read so far; a follow-up pass will automatically continue from where you stopped. NEVER store raw or encoded file bytes in ANY field: no base64, no data: URIs, no hex or blob dumps. A long opaque non-human-readable string is not data - replace it with a structured description of what it encodes. If base64 or a data: URI is all you have for something, describe it conceptually and never paste it; if nothing human-readable can be extracted at all, OMIT that record rather than saving noise.
@@ -946,7 +976,7 @@ ${options.inlineContentPlaceholder}
946
976
  }
947
977
  if (options?.pagedRead) {
948
978
  return head + `
949
- Read this file with the readFileContent tool, using the storage path above - do NOT fetch a URL and do NOT rely on a single sample. readFileContent returns the file ONE WINDOW at a time: spreadsheets as coordinate-tagged grid rows (e.g. 'R4 A:E&I NUMBER | B:E1007'), scanned/large PDFs as rendered PAGE IMAGES, and windows may include embedded photos - LOOK at any images and datafy what they show. Page through EVERY window: for each window SAVE records for its rows/items/pages (postRecords, one record per row/item; spreadsheet rows in "spreadsheet_rows", everything else in "document_entries"), THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed. Do NOT stop after the first window and do NOT just write a summary. Set every record's reference to exactly "src::" + the storage path above; that file record already exists, so enrich it with updateRecords instead of posting it again.` + (attachment.url ? `
979
+ Read this file with the readFileContent tool, using the storage path above - do NOT fetch a URL and do NOT rely on a single sample. readFileContent returns the file ONE WINDOW at a time: spreadsheets as coordinate-tagged grid rows (e.g. 'R4 A:E&I NUMBER | B:E1007'), text as a character range, and windows may include embedded photos - LOOK at any images and datafy what they show. Page through EVERY window: for each window SAVE records for its rows/items/pages (postRecords, one record per row/item; spreadsheet rows in "spreadsheet_rows", everything else in "document_entries"), THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed. Do NOT stop after the first window and do NOT just write a summary. Set every record's reference to exactly "src::" + the storage path above; that file record already exists, so enrich it with updateRecords instead of posting it again.` + (attachment.url ? `
950
980
  (A temporary URL is provided ONLY as a fallback if readFileContent fails: ${attachment.url})` : "");
951
981
  }
952
982
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
@@ -988,7 +1018,7 @@ function buildRenderDatafy(placeholder) {
988
1018
  return `
989
1019
  ${placeholder}
990
1020
 
991
- LOOK at each rendered page image in this message and DATAFY what it shows: for EVERY page call postRecords and save records in table "document_entries", with "page" set to the DOCUMENT PAGE number from the page's label - one record per row / table entry / line item visible on the page (or one record for the page if it is prose), capturing every value you can read (OCR the text, read tables cell by cell, describe any photos/diagrams). Set EVERY record's reference to exactly "src::" + the storage path above. That file record ALREADY EXISTS, so do NOT post it, and do NOT give your page records a "src::" unique_id of their own. A record with no reference back to it is an ORPHAN: re-indexing the file deletes the linked records and leaves the orphan behind forever as stale data.
1021
+ LOOK at each rendered page image in this message and DATAFY what it shows: for EVERY page call postRecords and save records in table "document_entries", with "page" set to the DOCUMENT PAGE number from the page's label - one record per row / table entry / line item visible on the page (or one record for the page if it is prose), capturing every value you can read (OCR the text, read tables cell by cell, transcribe the text in photos/diagrams before describing them). Set EVERY record's reference to exactly "src::" + the storage path above (that file record already exists: never post it, and give your page records no "src::" unique_id of their own).
992
1022
 
993
1023
  Each image is preceded by a label giving its DOCUMENT PAGE number. That label is the page's identity - use it, and ignore any page number PRINTED on the document itself (a scan often restarts its own numbering per section, so a footer reading "PAGE 4 OF 8" routinely disagrees with the real position). Whether a page is one you have already saved is stated in the note above the images - decide from that, never from a printed page number.
994
1024
 
@@ -1013,7 +1043,7 @@ ${placeholder}
1013
1043
 
1014
1044
  DATAFY this window: call postRecords and save records for everything in it - ONE RECORD PER ROW for tabular data (keyed by the column headers), or one record per section for prose in table "document_entries". Capture every value you can read. The file-level record ALREADY EXISTS with unique_id "src::" + the storage path above: do NOT post it (a duplicate unique_id is rejected), enrich it with updateRecords, and link every row/section record to it by reference.
1015
1045
 
1016
- If this window has PHOTOS attached as images, LOOK at each one and datafy what it actually shows. A \xABPHOTO ...\xBB marker in the grid text ties a picture to its row and comes in two forms. \xABPHOTO A88 -> __MEDIA__/...\xBB means the picture at cell A88 is saved as a permanent file at exactly that storage path, and its record in table "__MEDIA__" has unique_id "src::" + that path: UPDATE that record with updateRecords, adding what the picture SHOWS and TAGS for every identifier visible in it (part numbers, tag ids, item names, serial numbers). Do NOT create a duplicate and do NOT add a second photo record in another table: one file, one record. If that update reports the record does not exist, create it ONCE with that same unique_id, reference "src::" + the storage path above, table "__MEDIA__", access group "authorized", and data carrying the path - the path must never be lost. A bare \xABPHOTO A88\xBB marker with no arrow is a picture with no stored path of its own in this window: usually a repeat stored under an earlier anchor, or one too small to keep. NEVER construct a storage path or unique_id for it: find its record, if any, with getRecords reference "src::" + the storage path above, matching the cell against data.anchor or tags, and enrich what you find. The row record stays about its row's cells. Never report that photo contents could not be extracted when images are attached here.
1046
+ If this window has PHOTOS attached as images, LOOK at each one and datafy what it actually shows. A \xABPHOTO ...\xBB marker in the grid text ties a picture to its row and comes in two forms. \xABPHOTO A88 -> __MEDIA__/...\xBB means the picture at cell A88 is saved as a permanent file at exactly that storage path, and its record in table "__MEDIA__" has unique_id "src::" + that path: UPDATE that record with updateRecords, adding what the picture SHOWS and TAGS for every identifier visible in it (part numbers, tag ids, item names, serial numbers). Do NOT create a duplicate and do NOT add a second photo record in another table: one file, one record. If that update reports the record does not exist, create it ONCE with that same unique_id, reference "src::" + the storage path above, table "__MEDIA__", access group "${indexingAccessGroup(attachment)}", and data carrying the path - the path must never be lost. A bare \xABPHOTO A88\xBB marker with no arrow is a picture with no stored path of its own in this window: usually a repeat stored under an earlier anchor, or one too small to keep. NEVER construct a storage path or unique_id for it: find its record, if any, with getRecords reference "src::" + the storage path above, matching the cell against data.anchor or tags, and enrich what you find. The row record stays about its row's cells. Never report that photo contents could not be extracted when images are attached here.
1017
1047
 
1018
1048
  Save records for THIS window only, then stop and report what you saved. Do NOT try to read the rest of the file, and do NOT call readFileContent - if more remains, the next window is read and sent to you automatically. Report only what you were actually shown, and never imply you have seen the whole file when the note beside the window says more remains.`;
1019
1049
  }
@@ -1035,6 +1065,165 @@ Records for the earlier windows/pages of this file are ALREADY saved (they refer
1035
1065
  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.`;
1036
1066
  }
1037
1067
 
1068
+ // src/engine/errors.ts
1069
+ var STATUS_MESSAGE = {
1070
+ "408": "The AI provider timed out before it started.",
1071
+ "409": "The AI provider rejected the request as conflicting.",
1072
+ "413": "The request was too large for the AI provider.",
1073
+ "429": "The AI provider is rate limiting requests right now.",
1074
+ "500": "The AI provider hit an internal error.",
1075
+ "502": "The AI provider is temporarily unreachable.",
1076
+ "503": "The AI provider is temporarily unavailable.",
1077
+ "504": "The AI provider timed out."
1078
+ };
1079
+ function isTransientStatus(status) {
1080
+ return status === 408 || status === 425 || status === 429 || status >= 500;
1081
+ }
1082
+ function isCsrStatusEnvelope(res) {
1083
+ return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
1084
+ }
1085
+ function csrEnvelopeError(input) {
1086
+ if (!isCsrStatusEnvelope(input)) return void 0;
1087
+ if (input.status !== "failed") return void 0;
1088
+ return input.error != null ? input.error : { message: "The AI provider request failed." };
1089
+ }
1090
+ function getErrorMessage(input) {
1091
+ var envErr = csrEnvelopeError(input);
1092
+ if (envErr !== void 0) input = envErr;
1093
+ if (!input) return "Something went wrong.";
1094
+ if (typeof input === "string") return input;
1095
+ if (input.error && input.error.message) return input.error.message;
1096
+ if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
1097
+ if (input.body && typeof input.body.message === "string") return input.body.message;
1098
+ if (input.message) return input.message;
1099
+ var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
1100
+ if (status) {
1101
+ var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
1102
+ return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
1103
+ }
1104
+ return "Something went wrong.";
1105
+ }
1106
+ function isRetriedFailure(input) {
1107
+ var envErr = csrEnvelopeError(input);
1108
+ if (envErr !== void 0) input = envErr;
1109
+ return !!input && typeof input === "object" && input.retried === true;
1110
+ }
1111
+ function isErrorResponseBody(response) {
1112
+ var envErr = csrEnvelopeError(response);
1113
+ if (envErr !== void 0) response = envErr;
1114
+ if (!response || typeof response !== "object") return envErr !== void 0;
1115
+ if (typeof response.status_code === "number" && response.status_code >= 400) return true;
1116
+ if (response.type === "error") return true;
1117
+ if (response.error && (response.error.message || response.error.type)) return true;
1118
+ var body = response.body;
1119
+ if (body && typeof body === "object") {
1120
+ if (body.type === "error") return true;
1121
+ if (body.error && (body.error.message || body.error.type)) return true;
1122
+ }
1123
+ if (typeof response.message === "string" && response.message.length) {
1124
+ var hasClaude = Array.isArray(response.content);
1125
+ var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
1126
+ if (!hasClaude && !hasOpenAI) return true;
1127
+ }
1128
+ return false;
1129
+ }
1130
+ function isNonRetryableRequestError(input) {
1131
+ var envErr = csrEnvelopeError(input);
1132
+ if (envErr !== void 0) input = envErr;
1133
+ if (!input || typeof input !== "object") return false;
1134
+ var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
1135
+ var param = void 0;
1136
+ var blobs = [];
1137
+ var sources = [input.error, input.body && input.body.error, input.body, input];
1138
+ for (var i = 0; i < sources.length; i++) {
1139
+ var e = sources[i];
1140
+ if (!e) continue;
1141
+ if (typeof e === "string") {
1142
+ blobs.push(e);
1143
+ continue;
1144
+ }
1145
+ if (typeof e !== "object") continue;
1146
+ if (param === void 0 && e.param != null) param = e.param;
1147
+ if (typeof e.code === "string") blobs.push(e.code);
1148
+ if (typeof e.type === "string") blobs.push(e.type);
1149
+ if (typeof e.message === "string") blobs.push(e.message);
1150
+ }
1151
+ var hay = blobs.join(" | ").toLowerCase();
1152
+ if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
1153
+ return true;
1154
+ }
1155
+ var isClientReqStatus = status === 400 || status === 422;
1156
+ if (isClientReqStatus && param != null && param !== "") return true;
1157
+ if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
1158
+ return true;
1159
+ }
1160
+ return false;
1161
+ }
1162
+ function isAuthExpiredError(input) {
1163
+ var envErr = csrEnvelopeError(input);
1164
+ if (envErr !== void 0) input = envErr;
1165
+ if (!input) return false;
1166
+ var blobs = [];
1167
+ var push = function(v) {
1168
+ if (typeof v === "string" && v) blobs.push(v);
1169
+ };
1170
+ if (typeof input === "string") push(input);
1171
+ else {
1172
+ push(input.message);
1173
+ push(input.code);
1174
+ if (input.error) {
1175
+ push(input.error.message);
1176
+ push(input.error.code);
1177
+ push(input.error.type);
1178
+ }
1179
+ if (input.body) {
1180
+ push(input.body.message);
1181
+ if (input.body.error) {
1182
+ push(input.body.error.message);
1183
+ push(input.body.error.code);
1184
+ push(input.body.error.type);
1185
+ }
1186
+ }
1187
+ if (typeof input.status === "number" && input.status === 401) return true;
1188
+ if (typeof input.status_code === "number" && input.status_code === 401) return true;
1189
+ }
1190
+ var hay = blobs.join(" | ").toLowerCase();
1191
+ if (!hay) return false;
1192
+ 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;
1193
+ }
1194
+ function isProviderApiKeyError(input) {
1195
+ var envErr = csrEnvelopeError(input);
1196
+ if (envErr !== void 0) input = envErr;
1197
+ if (!input) return false;
1198
+ var blobs = [];
1199
+ var push = function(v) {
1200
+ if (typeof v === "string" && v) blobs.push(v);
1201
+ };
1202
+ if (typeof input === "string") push(input);
1203
+ else {
1204
+ push(input.message);
1205
+ push(input.code);
1206
+ push(input.type);
1207
+ if (input.error) {
1208
+ push(input.error.message);
1209
+ push(input.error.code);
1210
+ push(input.error.type);
1211
+ }
1212
+ if (input.body) {
1213
+ push(input.body.message);
1214
+ push(input.body.type);
1215
+ if (input.body.error) {
1216
+ push(input.body.error.message);
1217
+ push(input.body.error.code);
1218
+ push(input.body.error.type);
1219
+ }
1220
+ }
1221
+ }
1222
+ var hay = blobs.join(" | ").toLowerCase();
1223
+ if (!hay) return false;
1224
+ return hay.indexOf("authentication_error") !== -1 || hay.indexOf("invalid_api_key") !== -1 || hay.indexOf("invalid x-api-key") !== -1 || hay.indexOf("incorrect api key") !== -1 || hay.indexOf("invalid api key") !== -1 || hay.indexOf("no api key provided") !== -1;
1225
+ }
1226
+
1038
1227
  // src/engine/links.ts
1039
1228
  var EXPIRED_ATTACHMENT_URL_HOST = "_expired_.url";
1040
1229
  var EXPIRED_ATTACHMENT_URL_ORIGIN = "https://" + EXPIRED_ATTACHMENT_URL_HOST;
@@ -1899,12 +2088,41 @@ var OLDEST_NANO_REASONING_EFFORT = "high";
1899
2088
  var isOpenAINano = (model) => {
1900
2089
  const normalized = (model).trim().toLowerCase();
1901
2090
  if (!/(^|-)nano(-|$)/.test(normalized)) return false;
2091
+ return openAITakesReasoningEffort(normalized);
2092
+ };
2093
+ var openAITakesReasoningEffort = (model) => {
2094
+ const normalized = (model || DEFAULT_OPENAI_MODEL).trim().toLowerCase();
1902
2095
  const match = normalized.match(/^gpt-(\d+)(?:\.(\d+))?(-[a-z0-9.\-]+)?$/);
1903
2096
  if (!match) return false;
1904
2097
  const major = Number(match[1]);
1905
2098
  const minor = match[2] === void 0 ? null : Number(match[2]);
1906
2099
  return major > 5 || major === 5 && minor !== null && minor >= 4;
1907
2100
  };
2101
+ var claudeTakesEffort = (model) => {
2102
+ const normalized = (model || DEFAULT_CLAUDE_MODEL).trim().toLowerCase().replace(/\[1m\]$/, "");
2103
+ const match = normalized.match(/^claude-([a-z]+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:-\d{8})?$/);
2104
+ if (!match) return false;
2105
+ const family = match[1];
2106
+ if (family === "fable" || family === "mythos") return true;
2107
+ if (match[2] === void 0) return false;
2108
+ const major = Number(match[2]);
2109
+ const minor = match[3] === void 0 ? 0 : Number(match[3]);
2110
+ if (family === "opus") return major > 4 || major === 4 && minor >= 5;
2111
+ if (family === "sonnet") return major > 4 || major === 4 && minor >= 6;
2112
+ if (family === "haiku") return major > 5 || major === 5 && minor >= 5;
2113
+ return false;
2114
+ };
2115
+ var ANSWER_MODE_EFFORT = {
2116
+ standard: null,
2117
+ fast: "low",
2118
+ thorough: "high"
2119
+ };
2120
+ function chatEffortFields(platform, model, mode) {
2121
+ const effort = mode ? ANSWER_MODE_EFFORT[mode] : null;
2122
+ if (!effort) return {};
2123
+ if (platform === "openai") return openAITakesReasoningEffort(model) ? { reasoning: { effort } } : {};
2124
+ return claudeTakesEffort(model) ? { output_config: { effort } } : {};
2125
+ }
1908
2126
  var variantIndexingOptions = (model) => {
1909
2127
  if (!isOpenAINano(model) || !isOldestNano(model)) return {};
1910
2128
  return {
@@ -2041,6 +2259,80 @@ function applyHistoryCacheBreakpoint(messages) {
2041
2259
  var POLL_INTERVAL = 3e3;
2042
2260
  var STREAM_POLL_INTERVAL = 1e3;
2043
2261
  var MAX_CONCURRENT_BG_POLLS = 6;
2262
+ var mcpListToolsCache = /* @__PURE__ */ new Map();
2263
+ var mcpListToolsReuseOff = false;
2264
+ var MCP_LIST_TOOLS_OFF_PREFIX = "bunnyquery:mcp-list-tools-off:";
2265
+ function mcpListToolsOffStored(service) {
2266
+ try {
2267
+ return typeof localStorage !== "undefined" && !!localStorage.getItem(MCP_LIST_TOOLS_OFF_PREFIX + service);
2268
+ } catch (_) {
2269
+ return false;
2270
+ }
2271
+ }
2272
+ function storeMcpListToolsOff(service) {
2273
+ if (!service) return;
2274
+ try {
2275
+ if (typeof localStorage !== "undefined") localStorage.setItem(MCP_LIST_TOOLS_OFF_PREFIX + service, String(Date.now()));
2276
+ } catch (_) {
2277
+ }
2278
+ }
2279
+ var SERVER_PLACEHOLDERS = ["$CLIENT_SECRET", "$ACCESS_TOKEN", "$ID_TOKEN"];
2280
+ function failureText(failure) {
2281
+ const env = csrEnvelopeError(failure);
2282
+ const f = env !== void 0 ? env : failure;
2283
+ if (f == null) return "";
2284
+ if (typeof f === "string") return f.toLowerCase();
2285
+ let text = "";
2286
+ try {
2287
+ text = JSON.stringify(f) || "";
2288
+ } catch (_) {
2289
+ text = "";
2290
+ }
2291
+ if (typeof f.message === "string") text += " " + f.message;
2292
+ return text.toLowerCase();
2293
+ }
2294
+ function failureStatus(failure) {
2295
+ const env = csrEnvelopeError(failure);
2296
+ const f = env !== void 0 ? env : failure;
2297
+ if (!f || typeof f !== "object") return void 0;
2298
+ const v = typeof f.status_code === "number" ? f.status_code : typeof f.status === "number" ? f.status : void 0;
2299
+ return v;
2300
+ }
2301
+ function mcpListToolsKey(serverUrl, anonymous, service, publicProjectId, userId) {
2302
+ return JSON.stringify([serverUrl, anonymous ? "anonymous" : "signed-in", service, publicProjectId || "", userId || ""]);
2303
+ }
2304
+ function rememberMcpListTools(turn, body) {
2305
+ if (!turn || !turn.mcpToolsKey || mcpListToolsReuseOff) return;
2306
+ const output = body && Array.isArray(body.output) ? body.output : null;
2307
+ if (!output) return;
2308
+ for (let i = output.length - 1; i >= 0; i--) {
2309
+ const item = output[i];
2310
+ if (!item || item.type !== "mcp_list_tools" || item.server_label !== MCP_NAME) continue;
2311
+ if (item.error || typeof item.id !== "string" || !item.id || !Array.isArray(item.tools)) continue;
2312
+ let toolsText = "";
2313
+ try {
2314
+ toolsText = JSON.stringify(item.tools);
2315
+ } catch (_) {
2316
+ return;
2317
+ }
2318
+ if (SERVER_PLACEHOLDERS.some((ph) => toolsText.indexOf(ph) !== -1)) return;
2319
+ mcpListToolsCache.set(turn.mcpToolsKey, { type: "mcp_list_tools", id: item.id, server_label: item.server_label, tools: item.tools });
2320
+ return;
2321
+ }
2322
+ }
2323
+ function forgetMcpListToolsOnFailure(turn, failure) {
2324
+ if (!turn || !turn.mcpToolsInjected) return;
2325
+ if (turn.mcpToolsKey) mcpListToolsCache.delete(turn.mcpToolsKey);
2326
+ const text = failureText(failure);
2327
+ const status = failureStatus(failure);
2328
+ const namesItem = text.indexOf("mcp_list_tools") !== -1 || !!turn.mcpToolsItemId && text.indexOf(turn.mcpToolsItemId.toLowerCase()) !== -1;
2329
+ if (namesItem) {
2330
+ mcpListToolsReuseOff = true;
2331
+ storeMcpListToolsOff(turn.mcpToolsService);
2332
+ return;
2333
+ }
2334
+ if (status === 400 || status === 422 || text.indexOf("invalid_request_error") !== -1) mcpListToolsReuseOff = true;
2335
+ }
2044
2336
  async function callClaudeWithMcp({
2045
2337
  prompt,
2046
2338
  messages,
@@ -2056,6 +2348,7 @@ async function callClaudeWithMcp({
2056
2348
  webAccess
2057
2349
  }) {
2058
2350
  const web = await resolveWebAccess(service, typeof webAccess === "boolean" ? webAccess : void 0);
2351
+ const effortFields = chatEffortFields("claude", model, await resolveAnswerMode(service));
2059
2352
  const mcpServerDefinition = {
2060
2353
  type: "url",
2061
2354
  name: mcpServer.name,
@@ -2083,6 +2376,8 @@ async function callClaudeWithMcp({
2083
2376
  data: {
2084
2377
  model,
2085
2378
  max_tokens: maxTokens,
2379
+ // `output_config: {effort}` for a fast or thorough project, nothing otherwise.
2380
+ ...effortFields,
2086
2381
  // Top level beside model/messages/mcp_servers, which is where the
2087
2382
  // Messages API takes it.
2088
2383
  ...stream.body,
@@ -2143,11 +2438,27 @@ async function callClaudeWithPublicMcp(prompt, service, owner, messages, system,
2143
2438
  authorizationToken: endpoint.token
2144
2439
  }});
2145
2440
  }
2146
- async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope) {
2441
+ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope, turn) {
2147
2442
  const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
2148
2443
  const resolvedModel = model || DEFAULT_OPENAI_MODEL;
2149
2444
  const imageDetail = getOpenAIImageDetail(resolvedModel);
2445
+ const serverUrl = mcpChatUrl(endpoint.url, "openai", resolvedModel);
2150
2446
  const web = await resolveWebAccess(service);
2447
+ const effortFields = chatEffortFields("openai", resolvedModel, await resolveAnswerMode(service));
2448
+ let listedTools;
2449
+ if (turn) {
2450
+ turn.mcpToolsKey = void 0;
2451
+ turn.mcpToolsInjected = false;
2452
+ turn.mcpToolsService = void 0;
2453
+ turn.mcpToolsItemId = void 0;
2454
+ if (turn.reuseMcpToolList && !mcpListToolsReuseOff && !mcpListToolsOffStored(service)) {
2455
+ turn.mcpToolsKey = mcpListToolsKey(serverUrl, mcpScope?.anonymous, service, mcpScope?.publicProjectId, turn.userId);
2456
+ turn.mcpToolsService = service;
2457
+ listedTools = mcpListToolsCache.get(turn.mcpToolsKey);
2458
+ turn.mcpToolsInjected = !!listedTools;
2459
+ if (listedTools) turn.mcpToolsItemId = listedTools.id;
2460
+ }
2461
+ }
2151
2462
  const messageList = messages && messages.length ? prepareOpenAIMessages(messages, imageDetail) : [
2152
2463
  {
2153
2464
  role: "user",
@@ -2161,6 +2472,12 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
2161
2472
  content: system
2162
2473
  }
2163
2474
  ] : [],
2475
+ // Right after the system message, exactly as OpenAI returned it, so OpenAI
2476
+ // skips asking the MCP server for its tools again. Absent unless stored.
2477
+ // This item passes through the server's $CLIENT_SECRET / $ACCESS_TOKEN /
2478
+ // $ID_TOKEN substitution; rememberMcpListTools never stores a listing that
2479
+ // contains one of those literals.
2480
+ ...listedTools ? [{ type: listedTools.type, id: listedTools.id, server_label: listedTools.server_label, tools: listedTools.tools }] : [],
2164
2481
  ...messageList.map((m) => ({
2165
2482
  role: m.role,
2166
2483
  content: m.content
@@ -2183,6 +2500,8 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
2183
2500
  data: {
2184
2501
  model: resolvedModel,
2185
2502
  max_output_tokens: getMaxOutputTokens("openai", resolvedModel),
2503
+ // `reasoning: {effort}` for a fast or thorough project, nothing otherwise.
2504
+ ...effortFields,
2186
2505
  // Top level beside model/input/tools, which is where the Responses API
2187
2506
  // takes it.
2188
2507
  ...stream.body,
@@ -2193,7 +2512,7 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
2193
2512
  {
2194
2513
  type: "mcp",
2195
2514
  server_label: MCP_NAME,
2196
- server_url: mcpChatUrl(endpoint.url, "openai", resolvedModel),
2515
+ server_url: serverUrl,
2197
2516
  require_approval: "never",
2198
2517
  // No `headers` at all for an anonymous turn: `Bearer ` with an
2199
2518
  // empty token is a credential the MCP server rejects, and the
@@ -3149,165 +3468,6 @@ function buildChatGreeting(params) {
3149
3468
  return { lead, name, tail, text: lead + (name ? " " + name : "") + tail };
3150
3469
  }
3151
3470
 
3152
- // src/engine/errors.ts
3153
- var STATUS_MESSAGE = {
3154
- "408": "The AI provider timed out before it started.",
3155
- "409": "The AI provider rejected the request as conflicting.",
3156
- "413": "The request was too large for the AI provider.",
3157
- "429": "The AI provider is rate limiting requests right now.",
3158
- "500": "The AI provider hit an internal error.",
3159
- "502": "The AI provider is temporarily unreachable.",
3160
- "503": "The AI provider is temporarily unavailable.",
3161
- "504": "The AI provider timed out."
3162
- };
3163
- function isTransientStatus(status) {
3164
- return status === 408 || status === 425 || status === 429 || status >= 500;
3165
- }
3166
- function isCsrStatusEnvelope(res) {
3167
- return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
3168
- }
3169
- function csrEnvelopeError(input) {
3170
- if (!isCsrStatusEnvelope(input)) return void 0;
3171
- if (input.status !== "failed") return void 0;
3172
- return input.error != null ? input.error : { message: "The AI provider request failed." };
3173
- }
3174
- function getErrorMessage(input) {
3175
- var envErr = csrEnvelopeError(input);
3176
- if (envErr !== void 0) input = envErr;
3177
- if (!input) return "Something went wrong.";
3178
- if (typeof input === "string") return input;
3179
- if (input.error && input.error.message) return input.error.message;
3180
- if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
3181
- if (input.body && typeof input.body.message === "string") return input.body.message;
3182
- if (input.message) return input.message;
3183
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
3184
- if (status) {
3185
- var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
3186
- return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
3187
- }
3188
- return "Something went wrong.";
3189
- }
3190
- function isRetriedFailure(input) {
3191
- var envErr = csrEnvelopeError(input);
3192
- if (envErr !== void 0) input = envErr;
3193
- return !!input && typeof input === "object" && input.retried === true;
3194
- }
3195
- function isErrorResponseBody(response) {
3196
- var envErr = csrEnvelopeError(response);
3197
- if (envErr !== void 0) response = envErr;
3198
- if (!response || typeof response !== "object") return envErr !== void 0;
3199
- if (typeof response.status_code === "number" && response.status_code >= 400) return true;
3200
- if (response.type === "error") return true;
3201
- if (response.error && (response.error.message || response.error.type)) return true;
3202
- var body = response.body;
3203
- if (body && typeof body === "object") {
3204
- if (body.type === "error") return true;
3205
- if (body.error && (body.error.message || body.error.type)) return true;
3206
- }
3207
- if (typeof response.message === "string" && response.message.length) {
3208
- var hasClaude = Array.isArray(response.content);
3209
- var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
3210
- if (!hasClaude && !hasOpenAI) return true;
3211
- }
3212
- return false;
3213
- }
3214
- function isNonRetryableRequestError(input) {
3215
- var envErr = csrEnvelopeError(input);
3216
- if (envErr !== void 0) input = envErr;
3217
- if (!input || typeof input !== "object") return false;
3218
- var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
3219
- var param = void 0;
3220
- var blobs = [];
3221
- var sources = [input.error, input.body && input.body.error, input.body, input];
3222
- for (var i = 0; i < sources.length; i++) {
3223
- var e = sources[i];
3224
- if (!e) continue;
3225
- if (typeof e === "string") {
3226
- blobs.push(e);
3227
- continue;
3228
- }
3229
- if (typeof e !== "object") continue;
3230
- if (param === void 0 && e.param != null) param = e.param;
3231
- if (typeof e.code === "string") blobs.push(e.code);
3232
- if (typeof e.type === "string") blobs.push(e.type);
3233
- if (typeof e.message === "string") blobs.push(e.message);
3234
- }
3235
- var hay = blobs.join(" | ").toLowerCase();
3236
- if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
3237
- return true;
3238
- }
3239
- var isClientReqStatus = status === 400 || status === 422;
3240
- if (isClientReqStatus && param != null && param !== "") return true;
3241
- if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
3242
- return true;
3243
- }
3244
- return false;
3245
- }
3246
- function isAuthExpiredError(input) {
3247
- var envErr = csrEnvelopeError(input);
3248
- if (envErr !== void 0) input = envErr;
3249
- if (!input) return false;
3250
- var blobs = [];
3251
- var push = function(v) {
3252
- if (typeof v === "string" && v) blobs.push(v);
3253
- };
3254
- if (typeof input === "string") push(input);
3255
- else {
3256
- push(input.message);
3257
- push(input.code);
3258
- if (input.error) {
3259
- push(input.error.message);
3260
- push(input.error.code);
3261
- push(input.error.type);
3262
- }
3263
- if (input.body) {
3264
- push(input.body.message);
3265
- if (input.body.error) {
3266
- push(input.body.error.message);
3267
- push(input.body.error.code);
3268
- push(input.body.error.type);
3269
- }
3270
- }
3271
- if (typeof input.status === "number" && input.status === 401) return true;
3272
- if (typeof input.status_code === "number" && input.status_code === 401) return true;
3273
- }
3274
- var hay = blobs.join(" | ").toLowerCase();
3275
- if (!hay) return false;
3276
- 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;
3277
- }
3278
- function isProviderApiKeyError(input) {
3279
- var envErr = csrEnvelopeError(input);
3280
- if (envErr !== void 0) input = envErr;
3281
- if (!input) return false;
3282
- var blobs = [];
3283
- var push = function(v) {
3284
- if (typeof v === "string" && v) blobs.push(v);
3285
- };
3286
- if (typeof input === "string") push(input);
3287
- else {
3288
- push(input.message);
3289
- push(input.code);
3290
- push(input.type);
3291
- if (input.error) {
3292
- push(input.error.message);
3293
- push(input.error.code);
3294
- push(input.error.type);
3295
- }
3296
- if (input.body) {
3297
- push(input.body.message);
3298
- push(input.body.type);
3299
- if (input.body.error) {
3300
- push(input.body.error.message);
3301
- push(input.body.error.code);
3302
- push(input.body.error.type);
3303
- }
3304
- }
3305
- }
3306
- var hay = blobs.join(" | ").toLowerCase();
3307
- if (!hay) return false;
3308
- return hay.indexOf("authentication_error") !== -1 || hay.indexOf("invalid_api_key") !== -1 || hay.indexOf("invalid x-api-key") !== -1 || hay.indexOf("incorrect api key") !== -1 || hay.indexOf("invalid api key") !== -1 || hay.indexOf("no api key provided") !== -1;
3309
- }
3310
-
3311
3471
  // src/engine/citations.ts
3312
3472
  var DATA_TOOL_NAMES = [
3313
3473
  "getRecords",
@@ -7072,7 +7232,7 @@ var _ChatSession = class _ChatSession {
7072
7232
  * one it was composed for. Falls back to the live read only when a caller
7073
7233
  * omits them.
7074
7234
  */
7075
- _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner) {
7235
+ _callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner, turn) {
7076
7236
  if (projectId === void 0 || owner === void 0) {
7077
7237
  var id = this.host.getIdentity();
7078
7238
  if (projectId === void 0) projectId = id.projectId;
@@ -7080,14 +7240,49 @@ var _ChatSession = class _ChatSession {
7080
7240
  }
7081
7241
  var liveId = this.host.getIdentity();
7082
7242
  var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
7083
- 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);
7243
+ if (turn) turn.userId = liveId.anonymous ? "" : liveId.userId || "";
7244
+ 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);
7245
+ }
7246
+ /**
7247
+ * A fresh per-send record for the request builder (see requests.ts ChatTurnContext).
7248
+ * Chat turns only, and only OpenAI reuses a tool listing: Claude's MCP connector has no
7249
+ * equivalent item, and indexing passes never come through here. Off unless the host
7250
+ * set `reuseMcpToolList: true` in configureChatEngine.
7251
+ */
7252
+ _newChatTurn(platform) {
7253
+ var on = false;
7254
+ try {
7255
+ on = chatEngineConfig().reuseMcpToolList === true;
7256
+ } catch (_) {
7257
+ on = false;
7258
+ }
7259
+ return { reuseMcpToolList: platform === "openai" && on };
7260
+ }
7261
+ /**
7262
+ * What a settled chat turn means for the stored MCP tool listing: a failure drops it
7263
+ * when the turn carried it (forgetMcpListToolsOnFailure decides whether reuse also
7264
+ * stops); a good OpenAI body refreshes it. A stopped poll or a cancelled row says
7265
+ * nothing either way. Applied once per turn: an exception thrown later by a UI
7266
+ * handler on the same chain is not a provider failure.
7267
+ */
7268
+ _settleChatTurnTools(turn, response, failed) {
7269
+ if (!turn || turn.settled) return;
7270
+ turn.settled = true;
7271
+ if (failed || isErrorResponseBody(response)) {
7272
+ forgetMcpListToolsOnFailure(turn, response);
7273
+ return;
7274
+ }
7275
+ if (isPollStopped(response) || this._isCancelledPollResult(response)) return;
7276
+ rememberMcpListTools(turn, response);
7084
7277
  }
7085
7278
  dispatchAgentRequest(params) {
7086
7279
  var self = this;
7087
7280
  var dispatchItemId;
7281
+ var turn;
7088
7282
  var sendAndPoll = function() {
7283
+ turn = self._newChatTurn(params.aiPlatform);
7089
7284
  return Promise.resolve(
7090
- self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner)
7285
+ self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner, turn)
7091
7286
  ).then(function(initial) {
7092
7287
  if (initial && initial.poll && (initial.status === "pending" || initial.status === "running")) {
7093
7288
  if (initial.id) {
@@ -7116,12 +7311,14 @@ var _ChatSession = class _ChatSession {
7116
7311
  }
7117
7312
  return response;
7118
7313
  }).then(function(response) {
7314
+ self._settleChatTurnTools(turn, response);
7119
7315
  if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: "", isError: false, cancelled: true };
7120
7316
  if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
7121
7317
  var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
7122
7318
  answer = (answer || "").trim();
7123
7319
  return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
7124
7320
  }).catch(function(err) {
7321
+ self._settleChatTurnTools(turn, err, true);
7125
7322
  return { content: getErrorMessage(err), isError: true };
7126
7323
  }).then(function(result) {
7127
7324
  delete self.pendingAgentRequests[params.key];
@@ -7526,7 +7723,8 @@ var _ChatSession = class _ChatSession {
7526
7723
  this.scrollForDispatch(stageId);
7527
7724
  var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
7528
7725
  var capturedQueuedLid = queuedBubble._localId;
7529
- Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner)).then(function(result) {
7726
+ var queuedTurn = this._newChatTurn(aiPlatform);
7727
+ Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner, queuedTurn)).then(function(result) {
7530
7728
  var sendingIdx = self.getHistoryCacheKey() !== capturedKey ? -1 : self.state.messages.findIndex(function(m) {
7531
7729
  return m.isSendingToServer && (m.isPendingQueued || m.isPendingInProcess) && m.role === "user" && !m._stageId && (m._ownerKey === void 0 || m._ownerKey === capturedKey);
7532
7730
  });
@@ -7547,14 +7745,18 @@ var _ChatSession = class _ChatSession {
7547
7745
  });
7548
7746
  if (serverId) self._trackPoll(serverId, "fg", qp);
7549
7747
  return qp.then(function(res) {
7748
+ self._settleChatTurnTools(queuedTurn, res);
7550
7749
  if (isPollStopped(res)) return;
7551
7750
  return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey);
7552
7751
  }).catch(function(err) {
7752
+ self._settleChatTurnTools(queuedTurn, err, true);
7553
7753
  return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey);
7554
7754
  });
7555
7755
  }
7756
+ self._settleChatTurnTools(queuedTurn, result);
7556
7757
  return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
7557
7758
  }).catch(function(err) {
7759
+ self._settleChatTurnTools(queuedTurn, err, true);
7558
7760
  return self.onQueuedSendError(capturedComposed, err, void 0, capturedKey);
7559
7761
  });
7560
7762
  return;
@@ -7575,8 +7777,9 @@ var _ChatSession = class _ChatSession {
7575
7777
  this.updateHistoryCache();
7576
7778
  this.state.sending = true;
7577
7779
  this.scrollForDispatch(stageId);
7780
+ var immediateUserLid = immediateUser._localId;
7578
7781
  var historyForLlm = this.state.messages.filter(function(m) {
7579
- if (m === immediateUser) return false;
7782
+ if (m === immediateUser || immediateUserLid && m && m._localId === immediateUserLid) return false;
7580
7783
  return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder && !m.isCancelled && !m.isBackgroundTask && !m.isError;
7581
7784
  });
7582
7785
  historyForLlm.push({ role: "user", content: llmComposed });
@@ -7587,7 +7790,7 @@ var _ChatSession = class _ChatSession {
7587
7790
  projectId: id.projectId,
7588
7791
  history: historyForLlm
7589
7792
  });
7590
- var immediateUserLid = immediateUser._localId, immediatePlaceholderLid = immediatePlaceholder._localId;
7793
+ var immediatePlaceholderLid = immediatePlaceholder._localId;
7591
7794
  var run = this.dispatchAgentRequest({
7592
7795
  key,
7593
7796
  projectId: id.projectId,
@@ -10560,6 +10763,6 @@ var _ChatSession = class _ChatSession {
10560
10763
  _ChatSession.RUN_PASS_PAGE = 10;
10561
10764
  var ChatSession = _ChatSession;
10562
10765
 
10563
- export { BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, FINDINGS_TABLE, FINDING_ID_PREFIX, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, keyWords as findingKeyWords, findingsForTurn, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
10766
+ export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, FINDINGS_TABLE, FINDING_ID_PREFIX, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, keyWords as findingKeyWords, findingsForTurn, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
10564
10767
  //# sourceMappingURL=engine.mjs.map
10565
10768
  //# sourceMappingURL=engine.mjs.map