bunnyquery 1.19.2 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bunnyquery.js CHANGED
@@ -199,6 +199,17 @@
199
199
  function windowedIndexingEnabled() {
200
200
  return _config?.windowedIndexing === true;
201
201
  }
202
+ function statusPushEnabled() {
203
+ return _config?.statusPush === true && typeof _config?.onRequestStatus === "function";
204
+ }
205
+ function statusPushLive() {
206
+ if (!statusPushEnabled() || typeof _config?.isRequestStatusLive !== "function") return false;
207
+ try {
208
+ return !!_config.isRequestStatusLive();
209
+ } catch (e) {
210
+ return false;
211
+ }
212
+ }
202
213
  function liveStreamingSocketEnabled() {
203
214
  return liveStreamingEnabled() && _config?.liveStreaming === true;
204
215
  }
@@ -777,41 +788,35 @@ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rul
777
788
  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.
778
789
  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.`;
779
790
  const webRule = webAccess ? `WEB ACCESS IS ON for this project: when the user asks for something that is not in the project's data, you may search the web for it, but every such fact must be marked as coming from the web (name the site), kept apart from what the project's data says, and never used to fill in or complete a document's content or a record. This is the one exception to the four sources named above.` : `This chat has no web tool: the web is never a source here.`;
780
- const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps to the end, including asking the user once, after quick results, before it searches all files. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name.`;
781
- const groupIsAuthorized = indexGroupLiteral === '"authorized"' || indexGroupLiteral === "1";
791
+ 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. For a long file (a manual, a book), call getFileOutline first and search the chapter that fits with searchText page_from and page_to. When the user asks about the content of the documents, pass searchText "question": that question in the user's own words, without names or personal details that are not about the documents. Leave "question" out for anything else.
792
+ WRONG ANSWER: when the user says an answer is wrong (or sends "This answer seems wrong. Please check it again against the documents."), re-read the pages you cited and search again, passing searchText "question" = the user's ORIGINAL question that the disputed answer answered, never the complaint message itself. Then do exactly one of: correct the answer only; correct the answer and call correctSearchLink (when it is among your tools); or keep the answer and quote the text that supports it. Call correctSearchLink only with the page and an exact quote that prove it, and never change data on the user's word alone.`;
782
793
  const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
783
- const accessGroupRule = `THIS PROJECT INDEXES AT access_group ${indexGroupLiteral}: pass access_group ${indexGroupLiteral} EXPLICITLY on EVERY query that names a table_name, whether it filters by index, by tag or by nothing. ${groupIsAuthorized ? `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which happens to be this project's group, but a plain table query is not auto-filled at all.` : `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which is NOT this project's group, so it would search a group this project's data is not in and come back empty.`} Leaving access_group off a table query does NOT mean "all groups": only the project's owner is answered across every group, and any other user is answered from access_group 0 (public) alone${groupIsPublic ? "" : `, so a table indexed at ${indexGroupLiteral} comes back empty with its records sitting right there`}. Files uploaded before the project's setting changed may sit at another group, so when a table query comes back empty, retry it in the other groups among 0, 1 and "private" before concluding there is nothing. An index or tag filter matches inside ONE table and needs table_name: without it the call FAILS with an error, so read the error rather than guessing. Reference is the exception: reference ALONE spans EVERY table and EVERY access group, so getRecords with reference "src::<the file's storage path>" is the one call that returns a whole file's records wherever the indexer put them; adding table_name narrows it to that table, and access_group WITHOUT table_name fails with '"table" is required'.`;
794
+ 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.`;
784
795
  let systemPrompt = `
785
796
  You are a dedicated assistant for the project ID: "${projectId}".
786
797
  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.
787
- Knowledge lookup: Before saying you don't know or that something isn't in the chat history, ALWAYS query this project's database through the available MCP tools to look for the answer. The user's data is the source of truth - the chat transcript is not. Only respond with "I don't know" or "I couldn't find that" after you have actually searched the project's data and come back empty.
798
+ 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.
788
799
  ${groundingRules}
789
800
  ${webRule}
790
801
  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.
791
- FINDING THE DATA: the database is the way in, for every kind of file. Follow the search path in getTables' description, with one exception for this project: when getTables' one page is the whole list (end_of_list true), skip its table-name search even when no name fits: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Pick EVERY table that could hold the answer, not the first that fits. Read getIndexes and getTags one page each, never with fetch_all: name and tag lists can be millions of characters long and are never read whole, so when the name is not on that page, search for it with the user's words as their descriptions say. Never call getTags with neither table_name nor tag: that lists every tag of every table. Then getRecords in that table and group with the selector that matched (an index, one exact tag, or none for the whole table), always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>". Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder). TAGS are stored lowercase without spaces or punctuation, plus one tag per word: search a tag as one word ("leak") or as the joined phrase ("oilleak"); the server also normalizes the tag you send.
792
- NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set, keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
793
- A FILE TOTAL IS NOT A ROW'S TOTAL. The biggest number on a summary sheet is the whole file, not the thing that was asked about. Before quoting any figure, check it is scoped to what the question named: filter by the column that identifies it and report how many rows matched.
802
+ 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).
803
+ 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.
794
804
  ${documentRules}
795
- Complete answers over stored data: each uploaded file becomes many records, and ONE file is routinely SPLIT ACROSS SEVERAL TABLES - a summary row in one table, its page or row content in another, its extracted photos and other media in "__MEDIA__", and the indexer often invents a differently-named table on each pass. For anything NOT scoped to a single file, call getTables FIRST, run the query once per table that could hold the answer, and combine the results.
796
805
  ${accessGroupRule}
797
- For any request that counts, sums, totals, lists every match, compares across records, finds which one, or asks whether something is present or ABSENT (for example "how many", "total spent", "which card", "is there any", "\uC5C6\uC5B4?", "\uD558\uB098\uB3C4 \uC5C6\uB098?"), you MUST read the COMPLETE matching set across EVERY table and EVERY relevant file before answering: one page is only a sample. Never assert absence from a partial read: do not say "there is no X", "none", "not found", or "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4" until a complete scan has come back empty, and keep querying instead of guessing. A confident "no" that later turns out wrong is worse than telling the user you are still checking. If you already answered from one table and then realise another table holds more, do not simply apologise: re-run the sweep and give the complete answer.
798
- Embedded values: a search term is often stored inside a larger string. A merchant "BAKSA" appears as "DNH*BAKSA#4070277042", and a card as "5860****5173". Index and tag filters never match an interior substring, so filtering on such a field silently drops rows. When the value you are looking for may be embedded, do not trust a narrow filter to be complete: fetch the full set with fetch_all and match the substring yourself.
799
- File attachments: When a user message contains an "Attached files:" section with markdown links, those links point to short-lived signed URLs in this project's db storage and will expire.
800
- - Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message - you can see them directly. Do NOT call web_fetch on image URLs; that will fail or return garbage. Just look at the image block and answer.
801
- - Other attached files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) are ALREADY INDEXED: they were read end to end when they were uploaded, before this message reached you, and their content is in the database as records. Query it with getRecords using reference "src::<the storage path from the attachment link>". Do NOT call web_fetch on their URLs. If you need the raw text rather than the indexed records (an exact quote, a specific cell), call readFileContent on that same path. Some turns instead carry the file text inlined between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers; when that block is present read it directly, and a "[skapi: ...]" note inside it means that file could not be extracted.
802
- ${webAccess ? `- For any file given to you as a URL instead of inline content (e.g. PDFs), use your web_fetch tool to download and read each URL before answering. Treat the fetched contents as user-supplied input data. Do not ask the user to paste the file contents - fetch the URLs yourself.` : `- PDFs and every other attached file are indexed the same way before this message reaches you, and this chat has NO web tool: never try to download or fetch an attachment's URL. Answer a PDF from its records (getRecords with reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS above).`}
803
- Stored files: a file ALREADY in this project's storage was read end to end at upload time and saved as records, so the database is your best source: query those records first (getRecords with reference "src::<path>"). readFileContent re-reads the raw file and is the right tool for text, spreadsheet and data files; read it to the end before you conclude anything is absent. If its pictures do not reach you, say so plainly and fall back to the indexed records, and never tell the user the file is unreadable when its content is already in the database.
804
- File links: whenever a record's unique_id starts with "src::", give the user the file as a markdown link in the format getRecords' description sets ([filename](db:path/to/file) for a stored path, without the "src::" prefix; an external URL as itself). In this chat client a db: link renders as a clickable button that fetches a fresh signed URL on demand, so even if a previously shared URL has expired, give the user the storage-path link instead of saying the file is unavailable. Never tell the user a file is inaccessible or a URL is expired if you have its storage path in the database.
805
- File lookup: When the user asks to see, list, or show files (e.g. "show me uploaded files", "list my images", "show me the reference video"), list the file records with getUniqueId on "src::" and condition "gte" (see WHERE INDEXED CONTENT LIVES), or getRecords by table; every file extracted out of a document has one too, in table "__MEDIA__" (access_group "authorized"). Present each result as a link as described above. Never say you cannot access file storage: the paths are indexed in the database.
806
- Showing images: "show me the photo", "\uBCF4\uC5EC\uC918", "display it" is a request for the file's LINK, nothing more. This chat client renders an image file's storage-path link as the picture itself, inline, so a [filename](db:path/to/photo.jpg) link IS the image on screen. Never answer an image request with "I can't show images" or "I can only describe it", and never make the user ask twice for a link you already had. If you have the path, give the link and let the client paint it. The same is true of any file the user asks to see: the link is the answer. Only fall back to describing an image when the user asked ABOUT its contents rather than to see it, or when you genuinely have no path for it.
806
+ 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.
807
+ 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.
808
+ 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.`}
809
+ 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.
810
+ 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.
811
+ 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.
812
+ 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.
807
813
  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.
808
- Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
814
+ 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.
809
815
  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.
810
- The reliable query is getRecords with reference "src::<the document's storage path>". Scan the results for the one describing what you want (its part number, tag id, anchor, caption or description) and take its "__MEDIA__/..." value. Never let a table guess be the reason you report a file as missing.
816
+ 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.
811
817
  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.
812
818
  So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
813
- IF THAT RECORD HAS NO PATH, JOIN ON LOCATION - this needs nothing to have been enriched. Every media record carries data.anchor (the cell or page it was embedded at), plus data.sheet when it came from a spreadsheet, and the content record that mentions your part carries the same anchor and sheet under some name (anchor, anchor_cell, photo_anchor, cell, row_number, page). So: read the anchor and sheet off the content record, query getRecords with reference "src::<the document>", and take the media record whose data.anchor, data.also_at or tags match the anchor, using data.sheet too when both records carry one. Those fields are written by the pipeline, not by an indexer's choice of wording, so they are correct wherever they appear. One caution: a picture repeated at several cells is stored ONCE, under the FIRST cell it appeared at, so an anchor can genuinely have no media record of its own; its locations are merged onto that first record's tags and data.also_at. Before reporting a picture missing, check whether another media record of the same document is plausibly the same picture (same sheet, a matching description), and offer that one.
814
- THIS IS NOT ONLY ABOUT SPREADSHEET PHOTOS. Treat "show me the diagram in that deck" or "the picture in that PDF" exactly like a photo request: query for the media record, never reconstruct a filename.
819
+ 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.
815
820
  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.
816
821
  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:
817
822
  \`\`\`filename.csv
@@ -820,10 +825,10 @@ Carrots,55,$38.50
820
825
  Mushrooms,41,$73.80
821
826
  Zucchini,29,$43.50
822
827
  \`\`\`
823
- 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.`;
828
+ Any format works the same way: \`\`\`my-data.json, \`\`\`index.html, \`\`\`sample.txt.`;
824
829
  systemPrompt += `
825
830
  About BunnyQuery (this app - questions about it are in scope):
826
- 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.
831
+ 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.
827
832
  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.`}
828
833
  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.${""}${`
829
834
  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.` }`;
@@ -844,9 +849,9 @@ Project description: """${serviceDescription}"""`;
844
849
  const { projectId, serviceName, serviceDescription } = params;
845
850
  const accessGroup = params.accessGroup === "public" || params.accessGroup === "private" ? params.accessGroup : "authorized";
846
851
  let systemPrompt = `You are a background indexing agent for project ${projectId}.
847
- - 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.
852
+ - 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.
848
853
  - 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.
849
- - 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.)
854
+ - 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.
850
855
  - 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.
851
856
  - 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).
852
857
  - 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.
@@ -854,15 +859,15 @@ Project description: """${serviceDescription}"""`;
854
859
  - 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.
855
860
  - 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.
856
861
  - 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.
857
- - 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.
862
+ - 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.
858
863
  - 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.
859
864
  - 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.
860
865
  - 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.
861
866
  - 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.
862
- - 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.
867
+ - 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.
863
868
  - 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.
864
869
  - 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.
865
- - 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.
870
+ - 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.
866
871
  - 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.
867
872
  - 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.
868
873
  - 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.
@@ -920,7 +925,7 @@ ${options.inlineContentPlaceholder}
920
925
  }
921
926
  if (options?.pagedRead) {
922
927
  return head + `
923
- 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 ? `
928
+ 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 ? `
924
929
  (A temporary URL is provided ONLY as a fallback if readFileContent fails: ${attachment.url})` : "");
925
930
  }
926
931
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
@@ -962,7 +967,7 @@ Records for the earlier pages are ALREADY saved (they reference "${src}"). The N
962
967
  return `
963
968
  ${placeholder}
964
969
 
965
- 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.
970
+ 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).
966
971
 
967
972
  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.
968
973
 
@@ -987,7 +992,7 @@ ${placeholder}
987
992
 
988
993
  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.
989
994
 
990
- 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.
995
+ 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.
991
996
 
992
997
  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.`;
993
998
  }
@@ -2523,6 +2528,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2523
2528
  service,
2524
2529
  owner,
2525
2530
  ...pollOpt(),
2531
+ // Status push for this pass and the continuations the worker queues from it
2532
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2533
+ ...statusPushEnabled() ? { notify: true } : {},
2526
2534
  url: OPENAI_RESPONSES_API_URL,
2527
2535
  method: "POST",
2528
2536
  headers: {
@@ -2567,6 +2575,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2567
2575
  service,
2568
2576
  owner,
2569
2577
  ...pollOpt(),
2578
+ // Status push for this pass and the continuations the worker queues from it
2579
+ // (see ChatEngineConfig.statusPush). Absent unless the host turned it on.
2580
+ ...statusPushEnabled() ? { notify: true } : {},
2570
2581
  url: ANTHROPIC_MESSAGES_API_URL,
2571
2582
  method: "POST",
2572
2583
  headers: {
@@ -5129,6 +5140,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5129
5140
  var WORKER_PASS_ADOPT_ATTEMPTS = [0, 2e3, 6e3];
5130
5141
  var RECENT_INDEX_PASS_EVIDENCE_MS = 10 * 60 * 1e3;
5131
5142
  var ADOPT_TICK_MS = 10 * 1e3;
5143
+ var STATUS_PUSH_ADOPT_TICK_MS = 60 * 1e3;
5144
+ var CATCH_UP_MIN_GAP_MS = 2e3;
5145
+ var RETURN_WATCH_MS = 15 * 1e3;
5146
+ var RETURN_WATCH_SLEEP_GAP_MS = 45 * 1e3;
5147
+ var STATUS_NUDGE_MIN_GAP_MS = 2e3;
5132
5148
  var EARLY_PROBE_SCHEDULE_MS = [400, 900, 1700];
5133
5149
  var INDEXING_DRAIN_BUSY_POLL_MS = 8e3;
5134
5150
  var INDEXING_DRAIN_CONFIRM_POLL_MS = 3e3;
@@ -5270,6 +5286,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5270
5286
  }
5271
5287
  return Math.floor(v / 2 / 1e6);
5272
5288
  }
5289
+ var WRONG_ANSWER_MESSAGE = "This answer seems wrong. Please check it again against the documents.";
5290
+ var WRONG_ANSWER_LABEL = "Wrong answer?";
5291
+ function canReportWrongAnswer(msg) {
5292
+ var note = retrievalNoteOfAnswer(msg);
5293
+ return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5294
+ }
5273
5295
  var _ChatSession = class _ChatSession {
5274
5296
  constructor(host) {
5275
5297
  // --- live streaming ----------------------------------------------------
@@ -5319,6 +5341,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5319
5341
  // bubble can never silently revert to its 200-char head.
5320
5342
  this._hydratedBodies = {};
5321
5343
  this._hydratingItems = {};
5344
+ /** The button's label and the message it sends, read off the session so the
5345
+ * clients need no extra import. */
5346
+ this.wrongAnswerLabel = WRONG_ANSWER_LABEL;
5347
+ this.wrongAnswerMessage = WRONG_ANSWER_MESSAGE;
5322
5348
  this.typewriterQueue = Promise.resolve();
5323
5349
  /**
5324
5350
  * Pick up indexing passes the WORKER minted, which no client ever dispatched.
@@ -5355,6 +5381,27 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5355
5381
  * a reload starts without it and asks once, as before. */
5356
5382
  this._idleVerdictAt = {};
5357
5383
  this._adoptTickTimer = null;
5384
+ /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5385
+ * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5386
+ * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5387
+ // ── RETURN CATCH-UP + REQUEST STATUS PUSH (owner, 2026-11-23) ──────────────
5388
+ // The rule: when the user comes back to the chat (the tab shown again, the computer
5389
+ // awake again, the network or the websocket back), the chat is re-read from the
5390
+ // server, so nothing that happened while they were away is missing. The re-read is
5391
+ // loadHistory's own first-page refresh, the one every mount runs: it keeps older pages
5392
+ // the user loaded, keeps a send still in flight, never lets an empty answer replace a
5393
+ // known one, re-attaches polls to whatever is still waiting, and reads back a streamed
5394
+ // answer nobody finalized. Status frames (statusPush) only make things faster; they
5395
+ // never decide anything on screen.
5396
+ this._catchUpAt = 0;
5397
+ this._catchUpTimer = null;
5398
+ this._returnWatchTimer = null;
5399
+ this._returnWatchAt = 0;
5400
+ this._returnListeners = false;
5401
+ this._statusUnsub = null;
5402
+ this._statusNudgeTimer = null;
5403
+ this._statusNudgeAt = 0;
5404
+ this._statusSeenConnect = false;
5358
5405
  /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
5359
5406
  * live. Complete means both lists came back shorter than their limit, so a tracked pass
5360
5407
  * missing from it really has left the queue. */
@@ -5399,6 +5446,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5399
5446
  this.historyItemPolls = /* @__PURE__ */ new Map();
5400
5447
  this._pauseReasons = /* @__PURE__ */ new Set();
5401
5448
  this._resuming = false;
5449
+ this._wrongReported = {};
5402
5450
  this._lidSeq = 0;
5403
5451
  this._stageSeq = 0;
5404
5452
  this._uploadBatches = 0;
@@ -6793,8 +6841,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6793
6841
  this._resuming = true;
6794
6842
  return Promise.resolve().then(function() {
6795
6843
  self.drainBgTaskQueue();
6796
- if (self.needsHistoryRefetch()) return self.loadHistory(false, self.state.gateRefreshToken);
6797
- self.refreshLiveIndexState();
6844
+ return self.catchUpHistory();
6798
6845
  }).catch(function(e) {
6799
6846
  console.error("[chat-engine] resume polling failed", e);
6800
6847
  }).then(function() {
@@ -8025,6 +8072,54 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8025
8072
  }
8026
8073
  });
8027
8074
  }
8075
+ /**
8076
+ * Does this bubble get the "Wrong answer?" button: the free function's gate,
8077
+ * and only on the latest answer, because the message it sends names no answer
8078
+ * and the model reads it right after the last one. An answer already reported
8079
+ * keeps its (disabled) button after the complaint turn lands below it.
8080
+ */
8081
+ canReportWrongAnswer(msg) {
8082
+ if (!canReportWrongAnswer(msg)) return false;
8083
+ return this.wrongAnswerReported(msg) || this._isLatestAnswer(msg);
8084
+ }
8085
+ /** True when no chat turn follows `msg` in state.messages. Indexing rows and
8086
+ * cancelled turns do not count (neither reaches the model's history). Matched
8087
+ * by identity or by item id, since agent.vue hands in reactive proxies. */
8088
+ _isLatestAnswer(msg) {
8089
+ var list = this.state.messages || [];
8090
+ var sid = msg._serverItemId, lid = msg._localId;
8091
+ for (var i = list.length - 1; i >= 0; i--) {
8092
+ var m = list[i];
8093
+ if (!m) continue;
8094
+ if (m === msg || m.role === "assistant" && (sid && m._serverItemId === sid || lid && m._localId === lid)) return true;
8095
+ if (m.isBackgroundTask || m.isCancelled) continue;
8096
+ return false;
8097
+ }
8098
+ return false;
8099
+ }
8100
+ /** True once this answer's "Wrong answer?" was sent (one click per answer). */
8101
+ wrongAnswerReported(msg) {
8102
+ if (!msg) return false;
8103
+ if (msg._wrongReported) return true;
8104
+ var key = msg._serverItemId || msg._localId;
8105
+ return !!key && !!this._wrongReported[key];
8106
+ }
8107
+ /**
8108
+ * The "Wrong answer?" button: sends WRONG_ANSWER_MESSAGE as an ordinary visible
8109
+ * user turn through dispatchComposedMessage, so it reads the same after a reload
8110
+ * and both clients behave alike. The answer is marked first, so the button goes
8111
+ * disabled at once. False when the bubble does not qualify or was already used.
8112
+ * `pinned` is the caller's usual pinned identity and prompt (agent.vue pins them).
8113
+ */
8114
+ reportWrongAnswer(msg, pinned) {
8115
+ if (this.wrongAnswerReported(msg) || !this.canReportWrongAnswer(msg)) return false;
8116
+ msg._wrongReported = true;
8117
+ var key = msg._serverItemId || msg._localId;
8118
+ if (key) this._wrongReported[key] = true;
8119
+ this.host.notify();
8120
+ this.dispatchComposedMessage(WRONG_ANSWER_MESSAGE, false, void 0, void 0, void 0, pinned);
8121
+ return true;
8122
+ }
8028
8123
  /**
8029
8124
  * Stop waiting for the reply to the chat turn that is running now, and move on.
8030
8125
  *
@@ -8865,9 +8960,153 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8865
8960
  });
8866
8961
  return found;
8867
8962
  }
8868
- /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
8869
- * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
8870
- * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
8963
+ /**
8964
+ * Re-read the chat from the server now (see the rule above). Safe to call from any
8965
+ * number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
8966
+ * once, at the end of the gap. Nothing happens while no chat view is mounted (the
8967
+ * mount loads the chat anyway) or while background polling is paused (the tab is
8968
+ * hidden: showing it calls this again).
8969
+ */
8970
+ catchUpHistory() {
8971
+ var self = this;
8972
+ var id = this.host.getIdentity();
8973
+ if (!id.projectId || id.platform === "none") return Promise.resolve();
8974
+ if (!this.host.isViewMounted || !this.host.isViewMounted() || this.isPollingPaused()) return Promise.resolve();
8975
+ this._ensureReturnWatch();
8976
+ var wait = this._catchUpAt + CATCH_UP_MIN_GAP_MS - Date.now();
8977
+ if (wait > 0) {
8978
+ if (!this._catchUpTimer) {
8979
+ this._catchUpTimer = setTimeout(function() {
8980
+ self._catchUpTimer = null;
8981
+ self.catchUpHistory();
8982
+ }, wait);
8983
+ }
8984
+ return Promise.resolve();
8985
+ }
8986
+ this._catchUpAt = Date.now();
8987
+ return this.loadHistory(false, this.state.gateRefreshToken).catch(function(e) {
8988
+ console.error("[chat-engine] catch-up failed", e);
8989
+ });
8990
+ }
8991
+ /**
8992
+ * Watch for the moments the user comes back without the tab being hidden first: the
8993
+ * computer waking from sleep (the timer finds a gap far longer than its interval),
8994
+ * the network coming back, a page restored from the back-forward cache. Also starts
8995
+ * the status push listener. Runs while a chat view is mounted and stops itself when
8996
+ * none is.
8997
+ */
8998
+ _ensureReturnWatch() {
8999
+ var self = this;
9000
+ if (typeof window === "undefined") return;
9001
+ if (!this._returnListeners) {
9002
+ this._returnListeners = true;
9003
+ var onBack = function() {
9004
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9005
+ self.catchUpHistory();
9006
+ };
9007
+ window.addEventListener("online", onBack);
9008
+ window.addEventListener("pageshow", function(ev) {
9009
+ if (ev && ev.persisted) onBack();
9010
+ });
9011
+ }
9012
+ this._startStatusPush();
9013
+ if (this._returnWatchTimer) return;
9014
+ this._returnWatchAt = Date.now();
9015
+ var look = function() {
9016
+ self._returnWatchTimer = null;
9017
+ if (!self.host.isViewMounted || !self.host.isViewMounted()) {
9018
+ self._stopStatusPush();
9019
+ return;
9020
+ }
9021
+ var now = Date.now();
9022
+ var gap = now - self._returnWatchAt;
9023
+ self._returnWatchAt = now;
9024
+ if (gap > RETURN_WATCH_SLEEP_GAP_MS && (typeof document === "undefined" || document.visibilityState !== "hidden")) {
9025
+ self.catchUpHistory();
9026
+ }
9027
+ self._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9028
+ };
9029
+ this._returnWatchTimer = setTimeout(look, RETURN_WATCH_MS);
9030
+ }
9031
+ /** Listen to request status frames while a chat view is mounted (statusPush on). */
9032
+ _startStatusPush() {
9033
+ if (this._statusUnsub || !statusPushEnabled()) return;
9034
+ var self = this;
9035
+ this._statusSeenConnect = false;
9036
+ try {
9037
+ var unsub = chatEngineConfig().onRequestStatus(function(ev) {
9038
+ self._onRequestStatus(ev);
9039
+ });
9040
+ this._statusUnsub = typeof unsub === "function" ? unsub : function() {
9041
+ };
9042
+ } catch (e) {
9043
+ this._statusUnsub = null;
9044
+ }
9045
+ }
9046
+ _stopStatusPush() {
9047
+ var unsub = this._statusUnsub;
9048
+ this._statusUnsub = null;
9049
+ if (this._statusNudgeTimer) {
9050
+ clearTimeout(this._statusNudgeTimer);
9051
+ this._statusNudgeTimer = null;
9052
+ }
9053
+ if (unsub) {
9054
+ try {
9055
+ unsub();
9056
+ } catch (e) {
9057
+ }
9058
+ }
9059
+ }
9060
+ /**
9061
+ * One status frame event. 'connected' (first connection, and every reconnect after a
9062
+ * drop, a sleep or the planned renewal) catches up, because frames sent while the
9063
+ * socket was down are lost. A status change of an indexing pass this page does not
9064
+ * poll runs the queue check now instead of at its next heartbeat; a pass that IS polled
9065
+ * was already woken by skapi-js itself. Chat turns are left to their own polls.
9066
+ */
9067
+ _onRequestStatus(ev) {
9068
+ if (!ev || !this.host.isViewMounted()) return;
9069
+ if (ev.type === "connected") {
9070
+ if (!this._statusSeenConnect) {
9071
+ this._statusSeenConnect = true;
9072
+ return;
9073
+ }
9074
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
9075
+ this.catchUpHistory();
9076
+ return;
9077
+ }
9078
+ if (ev.type !== "status" || typeof ev.id !== "string") return;
9079
+ if (!ev.queue || !isBgIndexingQueue(ev.queue)) return;
9080
+ if (this.historyItemPolls.has(ev.id)) return;
9081
+ var tracked = false;
9082
+ for (var i = 0; i < this.bgTaskQueue.length; i++) {
9083
+ var e = this.bgTaskQueue[i];
9084
+ if (e && e.id === ev.id) {
9085
+ tracked = !e.byListing;
9086
+ break;
9087
+ }
9088
+ }
9089
+ if (tracked) return;
9090
+ this._nudgeQueueCheck();
9091
+ }
9092
+ /** Run the queue check (adopt, settle by listing, page progress) now, at most once per
9093
+ * STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
9094
+ _nudgeQueueCheck() {
9095
+ var self = this;
9096
+ if (this._statusNudgeTimer) return;
9097
+ var wait = Math.max(0, this._statusNudgeAt + STATUS_NUDGE_MIN_GAP_MS - Date.now());
9098
+ this._statusNudgeTimer = setTimeout(function() {
9099
+ self._statusNudgeTimer = null;
9100
+ self._statusNudgeAt = Date.now();
9101
+ var id = self.host.getIdentity();
9102
+ if (!id.projectId || id.platform !== "claude" && id.platform !== "openai") return;
9103
+ if (self.isPollingPaused() || !self.host.isViewMounted()) return;
9104
+ self._adoptWorkerIndexingPasses(0, false, true);
9105
+ self._settleByListing();
9106
+ self._refreshPageProgress();
9107
+ self._ensureAdoptTick();
9108
+ }, wait);
9109
+ }
8871
9110
  _ensureAdoptTick() {
8872
9111
  if (this._adoptTickTimer) return;
8873
9112
  var self = this;
@@ -8888,7 +9127,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
8888
9127
  self._settleByListing();
8889
9128
  self._refreshPageProgress();
8890
9129
  self._ensureAdoptTick();
8891
- }, ADOPT_TICK_MS);
9130
+ }, statusPushLive() ? STATUS_PUSH_ADOPT_TICK_MS : ADOPT_TICK_MS);
8892
9131
  }
8893
9132
  /**
8894
9133
  * Follow an indexing pass found in a loaded history page through the queue check
@@ -9504,6 +9743,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9504
9743
  var id = this.host.getIdentity();
9505
9744
  var svcId = id.projectId, plat = id.platform;
9506
9745
  if (!svcId || plat === "none" || !this.host.isViewMounted()) return;
9746
+ this._ensureReturnWatch();
9507
9747
  this._applyIndexCancellations();
9508
9748
  this._sweepCancelledIndexing();
9509
9749
  this._ensureAdoptTick();
@@ -9572,6 +9812,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9572
9812
  var executedAt;
9573
9813
  var bp = entry2.poll({
9574
9814
  latency: POLL_INTERVAL,
9815
+ // Status push (statusPushEnabled): a pass adopted from a listing is polled
9816
+ // slowly while frames arrive, like one this page dispatched. A dispatch
9817
+ // reply's poll decides that from the server's acknowledgement and
9818
+ // ignores this key.
9819
+ notify: statusPushEnabled(),
9575
9820
  onResponse: function(_res, meta) {
9576
9821
  if (meta && typeof meta.executed === "number" && meta.executed > 0) executedAt = meta.executed;
9577
9822
  }
@@ -10220,7 +10465,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10220
10465
  }
10221
10466
  }
10222
10467
  };
10223
- var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10468
+ var pp = isBg ? item.poll(Object.assign({ latency: POLL_INTERVAL, notify: statusPushEnabled() }, pollOpts)) : self._fgPollWithEarlyProbe(item, capturedId, pollOpts, {
10224
10469
  platform,
10225
10470
  projectId,
10226
10471
  owner,
@@ -10573,9 +10818,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10573
10818
 
10574
10819
  // src/index.js
10575
10820
  (function() {
10576
- var MCP_PROD = "https://mcp.broadwayinc.computer";
10821
+ var MCP_PROD = "https://mcp.skapi.com";
10577
10822
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
10578
- var BQ_VERSION = "1.19.2" ;
10823
+ var BQ_VERSION = "1.20.0" ;
10579
10824
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
10580
10825
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
10581
10826
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -14169,6 +14414,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
14169
14414
  bubble.appendChild(citeRow);
14170
14415
  }
14171
14416
  if (answerUsedNoDataTool(citeNote)) bubble.appendChild(h("span", { class: "bq-no-source-note", text: NO_DATA_TOOL_MARK }));
14417
+ if (session.canReportWrongAnswer(msg)) {
14418
+ var wrongSent = session.wrongAnswerReported(msg);
14419
+ var wrongBtn = h("button", { class: "bq-wrong-answer-btn", type: "button", text: session.wrongAnswerLabel });
14420
+ if (wrongSent) wrongBtn.disabled = true;
14421
+ else wrongBtn.addEventListener("click", function(e) {
14422
+ e.stopPropagation();
14423
+ wrongBtn.disabled = true;
14424
+ readyProjectSettings(S.projectId).then(function() {
14425
+ session.reportWrongAnswer(msg);
14426
+ });
14427
+ });
14428
+ bubble.appendChild(wrongBtn);
14429
+ }
14172
14430
  }
14173
14431
  if (msg.isUploadingAttachments) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Uploading files...)" }));
14174
14432
  else if (msg.isAwaitingIndexing) bubble.appendChild(h("span", { class: "bq-pending-note", text: "(Indexing files...)" }));
@@ -15305,6 +15563,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15305
15563
  { class: "bq-modal-desc" },
15306
15564
  "A file named \u201C" + filename + "\u201D already exists. Skip it, keep the existing file and just reindex it, or overwrite it completely?"
15307
15565
  ),
15566
+ h("p", { class: "bq-modal-desc", text: "Re-indexing also removes everything search has learned about this file from people's questions and corrections." }),
15308
15567
  applyLabel,
15309
15568
  h(
15310
15569
  "div",
@@ -15374,7 +15633,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15374
15633
  )
15375
15634
  )
15376
15635
  ));
15377
- body.push(h("p", { class: "bq-modal-desc", text: 'To index the stored copies again, choose Reindex. To upload such files again instead, turn off "Skip duplicate files" in the project settings.' }));
15636
+ body.push(h("p", { class: "bq-modal-desc", text: `To index the stored copies again, choose Reindex. Re-indexing also removes everything search has learned about this file from people's questions and corrections. To upload such files again instead, turn off "Skip duplicate files" in the project settings.` }));
15378
15637
  reindexBtn = h("button", { class: "btn", type: "button", onclick: function() {
15379
15638
  if (reindexing) return;
15380
15639
  reindexing = true;
@@ -15605,7 +15864,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15605
15864
  // skapi-js can (see canStream in init) and buffers, with a warning, when it
15606
15865
  // cannot. Before 1.16.0 this key meant "stream at all" and the socket was
15607
15866
  // `liveStreamingRealtime`; that name is now ignored.
15608
- liveStreaming: false
15867
+ liveStreaming: false,
15868
+ // Request STATUS PUSH (engine ChatEngineConfig.statusPush): indexing passes are
15869
+ // dispatched with `notify`, their polls slow down to a heartbeat while status
15870
+ // frames arrive on skapi's websocket, and the chat catches up when the socket
15871
+ // comes back. OFF unless the embedder asks, for the same reason as
15872
+ // `liveStreaming`: it keeps a websocket open on the host page's skapi instance.
15873
+ // Needs skapi-js 2.5.0 or newer on the page; an older one leaves it off.
15874
+ statusPush: false
15609
15875
  }, opts || {});
15610
15876
  S.mountEl = mountEl;
15611
15877
  clear(mountEl);
@@ -15742,7 +16008,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15742
16008
  // canStream. What the embedder chooses is the socket: `liveStreaming` here
15743
16009
  // is the engine's socket-delivery key. ANDed with canStream so a page whose
15744
16010
  // SDK cannot stream never asks for a socket on a buffered reply.
15745
- liveStreaming: canStream && S.opts.liveStreaming === true
16011
+ liveStreaming: canStream && S.opts.liveStreaming === true,
16012
+ // ---- request status push (mirrored in agent.vue's ai_agent.ts) ----
16013
+ // Only an explicit true, and only when the page's skapi-js has the hooks
16014
+ // (2.5.0 or newer); the engine then does nothing different without them.
16015
+ statusPush: S.opts.statusPush === true && !!S.skapi && typeof S.skapi.onRequestStatus === "function",
16016
+ onRequestStatus: S.skapi && typeof S.skapi.onRequestStatus === "function" ? S.skapi.onRequestStatus.bind(S.skapi) : void 0,
16017
+ isRequestStatusLive: S.skapi && typeof S.skapi.isRequestStatusLive === "function" ? S.skapi.isRequestStatusLive.bind(S.skapi) : void 0
15746
16018
  // The transport: dispatch and history, plus the finalize hook that stores
15747
16019
  // a streamed turn's kept version and the chunk reader that is the second
15748
16020
  // half of the durability guarantee. The two optional hooks are handed