bunnyquery 1.21.0 → 1.21.4

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
@@ -220,6 +220,9 @@
220
220
  function windowedIndexingEnabled() {
221
221
  return _config?.windowedIndexing === true;
222
222
  }
223
+ function workerIndexEndingsEnabled() {
224
+ return _config?.workerIndexEndings === true;
225
+ }
223
226
  function statusPushEnabled() {
224
227
  return _config?.statusPush === true && typeof _config?.onRequestStatus === "function";
225
228
  }
@@ -998,8 +1001,8 @@ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rul
998
1001
  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.
999
1002
  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.`;
1000
1003
  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.`;
1001
- 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.
1002
- 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.`;
1004
+ const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): when the user NAMED a file (its file name; a document title, a quote or a code they mention is NOT a file name: searchText finds those inside the files), first find its storage path by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used, then find the page with searchText and that path. A spreadsheet's sheets are page text too: a hit names its sheet and rows, and the row itself is a record (its unique_id is the hit's row_id_prefix plus the row number); a spreadsheet indexed before 2026-11-25 has no page text, so read its rows instead (readFileContent, or its records). When they did not name a file, your FIRST call is searchText without a path: no table list, no file lookup before it. Never list or look up files (getUniqueId on "src::") to find out whether a document, quote or title exists before searching: searchText's hits name the file, and a search that finds nothing says what it could not cover. Either way follow searchText's description 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"), or for a hit with "sheet" THE FILE AND THE SHEET ("quote.xlsx, sheet \uCD1D\uAD04"), never a sheet page's number; never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name. In a long file (a manual, a book), when a search of the whole file gives too many hits or none that fit, call getFileOutline 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.
1005
+ 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 (for a sheet hit, the rows: by its row_id_prefix, never readFileContent on a sheet page) 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.`;
1003
1006
  const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
1004
1007
  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.`;
1005
1008
  let systemPrompt = `
@@ -1008,7 +1011,7 @@ Scope: Only answer questions about this project and its data. Do not answer ques
1008
1011
  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.
1009
1012
  ${groundingRules}
1010
1013
  ${webRule}
1011
- 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).
1014
+ FINDING THE DATA: the database is the way in, for every kind of file. A question about what the documents SAY (a procedure, a passage, a definition, how to fix or do something), or one that names a code, a number or a phrase to find (a quote no., a part no., a name), starts with searchText (DOCUMENTS below), not with getTables: the sheets of spreadsheets are in page text too. searchText finds WHICH file, sheet and row holds a value; a total, count or list over rows is still computed from the full row set (NUMBERS FROM A SPREADSHEET below). Everything else (numbers, rows, records, lists, counts, files) follows 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).
1012
1015
  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.
1013
1016
  ${documentRules}
1014
1017
  ${accessGroupRule}
@@ -1058,13 +1061,13 @@ Project description: """${serviceDescription}"""`;
1058
1061
  const { projectId, serviceName, serviceDescription } = params;
1059
1062
  const accessGroup = params.accessGroup === "public" || params.accessGroup === "private" ? params.accessGroup : "authorized";
1060
1063
  let systemPrompt = `You are a background indexing agent for project ${projectId}.
1061
- - 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.
1064
+ - 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. Any other image file (.tif, .tiff, .bmp, .heic) is attached only when the message shows an image of it (the server attaches a converted copy when it can); when none is attached, index it from its metadata and never guess its contents.
1062
1065
  - 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.
1063
1066
  - 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.
1064
1067
  - 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.
1065
1068
  - 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).
1066
- - 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.
1067
- - IMAGE FILES uploaded as the file itself: if ANY readable character appears ANYWHERE in the image (a label, a stamp, a sign in the background) it counts as an image WITH text - transcribe it per the rule above, and also capture the layout (what appears where) and every entity named. Only a truly text-free image gets description first: a one-line caption, then the objects present with their attributes (type, color, count, condition, position). Either way, save what you extract onto the file's "src::" record with updateRecords, TAG every entity and identifier visible, and INDEX the one number the image offers (a measured value, an amount, a count).
1069
+ - 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", "serial_no", "tag_id" and "date". Every identifier you read (a serial number, a part number, a tag id, a model code) ALSO goes into "printed_text" or "handwritten_text", exactly as it appears, because those two fields are the image's searchable text. Text can appear at ANY angle (sideways, upside down, mirrored, along a curve): read it in its own orientation, and never call text unreadable only because it is turned. When it is upside down or sideways, watch the look-alikes (6 and 9, 0 and O, 1 and I, Latin and Cyrillic letters of the same shape). 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.5[?][?]" beats nothing. Write [?] for each character that is genuinely unreadable and copy handwriting character for character - do NOT invent a character, 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.
1070
+ - IMAGE FILES uploaded as the file itself: if ANY readable character appears ANYWHERE in the image (a label, a stamp, a sign in the background) it counts as an image WITH text - transcribe it per the rule above, and also capture the layout (what appears where) and every entity named. Only a truly text-free image gets description first: a one-line caption, then the objects present with their attributes (type, color, count, condition, position). Either way, save what you extract onto the file's "src::" record with updateRecords, TAG every entity and identifier visible, and INDEX the one number the image offers (a measured value, an amount, a count). On that same record ALSO set "text_rotation" and "text_legibility". "text_rotation" is the CLOCKWISE turn, 0, 90, 180 or 270, that would make the image's main text upright AS THE IMAGE IS SHOWN TO YOU: 0 when it already reads normally; 180 when it is upside down; 90 when its lines run from bottom to top (the tops of the letters face left); 270 when its lines run from top to bottom (the tops of the letters face right). "text_legibility" is "clear", "partial" or "unreadable" ("none" when there is no text).
1068
1071
  - 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.
1069
1072
  - 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.
1070
1073
  - 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.
@@ -1136,6 +1139,12 @@ ${options.inlineContentPlaceholder}
1136
1139
  return head + `
1137
1140
  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 ? `
1138
1141
  (A temporary URL is provided ONLY as a fallback if readFileContent fails: ${attachment.url})` : "");
1142
+ }
1143
+ if (options?.imageFile) {
1144
+ return head + `- temporary URL: ${attachment.url}
1145
+ ` + (options.imageFile === "attached" ? `
1146
+ This is an IMAGE file, attached to this message as an image: read it there, not from the URL. ` : `
1147
+ This is an IMAGE file in a format the AI cannot take directly. When an image of it is attached to this message (the server converts it when it can), read it there; when none is attached, index the file from its metadata only and do not guess its contents. `) + `Transcribe every character FIRST, at whatever angle the text is: "printed_text", "handwritten_text", and "part_no" / "serial_no" / "tag_id", with every identifier also written inside "printed_text" or "handwritten_text". Then set "text_rotation" and "text_legibility" on the file's "src::" record, and only then describe what the image shows.`;
1139
1148
  }
1140
1149
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
1141
1150
  }
@@ -1717,16 +1726,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1717
1726
  if (typeof value === "number" && isFinite(value)) pushUnique(list, String(value));
1718
1727
  else pushUnique(list, value);
1719
1728
  }
1720
- function pushHit(list, path, page) {
1729
+ function pushHit(list, path, page, sheet) {
1721
1730
  if (typeof path !== "string" || !path.trim()) return;
1722
1731
  var n = typeof page === "number" ? page : Number(page);
1723
1732
  if (!isFinite(n) || n <= 0) return;
1724
1733
  n = Math.floor(n);
1734
+ var sh = typeof sheet === "string" && sheet.trim() ? sheet.trim() : "";
1725
1735
  for (var i = 0; i < list.length; i++) {
1726
- if (list[i].path === path && list[i].page === n) return;
1736
+ if (sh ? list[i].path === path && list[i].sheet === sh : list[i].path === path && list[i].page === n) return;
1727
1737
  }
1728
1738
  if (list.length >= RETRIEVAL_NOTE_MAX_ITEMS) return;
1729
- list.push({ path: path.trim(), page: n });
1739
+ var hit = { path: path.trim(), page: n };
1740
+ if (sh) hit.sheet = sh;
1741
+ list.push(hit);
1730
1742
  }
1731
1743
  function pathFromSrcId(value) {
1732
1744
  if (typeof value !== "string") return null;
@@ -1773,7 +1785,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1773
1785
  return;
1774
1786
  }
1775
1787
  if (typeof node.path === "string" && node.page !== void 0) {
1776
- pushHit(note.hits, node.path, node.page);
1788
+ pushHit(note.hits, node.path, node.page, node.sheet);
1777
1789
  }
1778
1790
  for (var k in node) {
1779
1791
  if (!Object.prototype.hasOwnProperty.call(node, k)) continue;
@@ -1902,8 +1914,16 @@ Index the REMAINING windows - one record per row/item, looking at any page image
1902
1914
  }
1903
1915
  byFile[h.path].push(h.page);
1904
1916
  }
1917
+ var sheetsOf = {};
1918
+ for (var s2 = 0; s2 < note.hits.length; s2++) {
1919
+ var hs = note.hits[s2];
1920
+ if (hs.sheet) {
1921
+ if (!sheetsOf[hs.path]) sheetsOf[hs.path] = [];
1922
+ if (sheetsOf[hs.path].indexOf(hs.sheet) === -1) sheetsOf[hs.path].push(hs.sheet);
1923
+ }
1924
+ }
1905
1925
  parts.push("searchText hits " + order.map(function(p) {
1906
- return p + " p" + byFile[p].join(", p");
1926
+ return sheetsOf[p] ? p + " sheet " + sheetsOf[p].join(", sheet ") : p + " p" + byFile[p].join(", p");
1907
1927
  }).join("; "));
1908
1928
  }
1909
1929
  if (note.tools.length) parts.push("tools " + note.tools.join(", "));
@@ -2297,6 +2317,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2297
2317
  return { detail, pagesPerWindow: RENDER_PAGES_PER_WINDOW, tile: 1 };
2298
2318
  }
2299
2319
  var IMAGE_URL_REGEX = /\bhttps?:\/\/[^\s<>"'()\[\]]+?\.(?:jpg|jpeg|png|gif|webp)(?:\?[^\s<>"'()\[\]]*)?/gi;
2320
+ var INDEX_IMAGE_OTHER_EXT = /\.(?:tiff?|bmp|heic|heif)$/i;
2321
+ function indexingImageFile(attachment) {
2322
+ const url = typeof attachment.url === "string" ? attachment.url : "";
2323
+ if (url && new RegExp(IMAGE_URL_REGEX.source, "i").test(url)) return "attached";
2324
+ if (INDEX_IMAGE_OTHER_EXT.test(attachment.name || "") || INDEX_IMAGE_OTHER_EXT.test(attachment.storagePath || "")) return "maybe";
2325
+ return void 0;
2326
+ }
2300
2327
  function transformContentWithImages(content) {
2301
2328
  if (typeof content !== "string" || !content) {
2302
2329
  return content;
@@ -2736,10 +2763,20 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2736
2763
  save_media: !continuing
2737
2764
  }))
2738
2765
  } : {};
2739
- const skapiFileUrls = attachment.url && attachment.storagePath ? { _skapi_file_urls: [{ path: attachment.storagePath, url: attachment.url }] } : {};
2766
+ const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
2767
+ const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : void 0;
2768
+ const fileUrlDetail = imageFile && platform === "openai" ? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL) : void 0;
2769
+ const skapiFileUrls = attachment.url && attachment.storagePath ? {
2770
+ _skapi_file_urls: [{
2771
+ path: attachment.storagePath,
2772
+ url: attachment.url,
2773
+ ...singlePass ? { index_end: true } : {},
2774
+ ...fileUrlDetail ? { detail: fileUrlDetail } : {}
2775
+ }]
2776
+ } : {};
2740
2777
  const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : windowedRead && windowPlaceholder ? buildIndexingWindowMessage(attachment, windowPlaceholder, false) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
2741
2778
  attachment,
2742
- parsedContent ? { inlineContent: parsedContent } : placeholder ? { inlineContentPlaceholder: placeholder } : pagedRead ? { pagedRead: true } : void 0
2779
+ parsedContent ? { inlineContent: parsedContent } : placeholder ? { inlineContentPlaceholder: placeholder } : pagedRead ? { pagedRead: true } : imageFile ? { imageFile } : void 0
2743
2780
  );
2744
2781
  const systemPrompt = buildIndexingSystemPrompt({
2745
2782
  // The model copies this id verbatim into project_id tool calls, so it must be
@@ -2983,6 +3020,57 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2983
3020
  return `[POST]${url.toLowerCase()}#${service}:${itemId}`;
2984
3021
  }
2985
3022
 
3023
+ // src/engine/time.ts
3024
+ function wallClockNow() {
3025
+ return Date.now();
3026
+ }
3027
+ function formatChatTimestamp(ms) {
3028
+ if (typeof ms !== "number" || !isFinite(ms) || ms <= 0) return "";
3029
+ try {
3030
+ return new Date(ms).toLocaleString(void 0, {
3031
+ year: "numeric",
3032
+ month: "short",
3033
+ day: "numeric",
3034
+ hour: "numeric",
3035
+ minute: "2-digit",
3036
+ second: "2-digit"
3037
+ });
3038
+ } catch (e) {
3039
+ return "";
3040
+ }
3041
+ }
3042
+ function formatDuration(ms) {
3043
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
3044
+ var total = Math.floor(ms / 1e3);
3045
+ var h = Math.floor(total / 3600);
3046
+ var m = Math.floor(total % 3600 / 60);
3047
+ var s = total % 60;
3048
+ var out = [];
3049
+ if (h) out.push(h + "h");
3050
+ if (m) out.push(m + "m");
3051
+ out.push(s + "s");
3052
+ return out.join(" ");
3053
+ }
3054
+ function requestIdTimeMs(rid) {
3055
+ if (typeof rid !== "string") return 0;
3056
+ var stamp = rid.split(":")[0] || "";
3057
+ if (stamp.length !== 13) return 0;
3058
+ var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
3059
+ var v = 0;
3060
+ for (var i = 0; i < stamp.length; i++) {
3061
+ var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
3062
+ if (d < 0) return 0;
3063
+ v = v * 32 + d;
3064
+ }
3065
+ return Math.floor(v / 2 / 1e6);
3066
+ }
3067
+ function messageTimeMs(m) {
3068
+ if (!m) return 0;
3069
+ var r = typeof m._serverItemId === "string" ? requestIdTimeMs(m._serverItemId) : 0;
3070
+ if (r > 0) return r;
3071
+ return typeof m._ts === "number" && m._ts > 0 ? m._ts : 0;
3072
+ }
3073
+
2986
3074
  // src/engine/indexing_groups.ts
2987
3075
  function canonIndexKey(s) {
2988
3076
  return typeof s === "string" && s ? s.trim() : "";
@@ -3093,8 +3181,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3093
3181
  var alreadySeen = !!(msg._serverItemId && runByItemId[msg._serverItemId]);
3094
3182
  var openId = openRunOfKey[key];
3095
3183
  var notLater = false;
3096
- if (openId && typeof msg._ts === "number" && typeof newestTsOfRun[openId] === "number") {
3097
- notLater = msg._ts <= newestTsOfRun[openId];
3184
+ var msgTime = messageTimeMs(msg);
3185
+ if (openId && msgTime > 0 && typeof newestTsOfRun[openId] === "number") {
3186
+ notLater = msgTime <= newestTsOfRun[openId];
3098
3187
  }
3099
3188
  if (!ref.continued && !alreadySeen && !notLater && openRunOfKey[key]) delete openRunOfKey[key];
3100
3189
  runId = openRunOfKey[key];
@@ -3108,9 +3197,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3108
3197
  runId = runOfIndex[i - 1];
3109
3198
  }
3110
3199
  if (!runId) continue;
3111
- if (typeof msg._ts === "number") {
3200
+ var memberTime = messageTimeMs(msg);
3201
+ if (memberTime > 0) {
3112
3202
  var prevTs = newestTsOfRun[runId];
3113
- if (typeof prevTs !== "number" || msg._ts > prevTs) newestTsOfRun[runId] = msg._ts;
3203
+ if (typeof prevTs !== "number" || memberTime > prevTs) newestTsOfRun[runId] = memberTime;
3114
3204
  }
3115
3205
  var g = groups[runId];
3116
3206
  if (!g) {
@@ -3619,10 +3709,20 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3619
3709
  var out = [];
3620
3710
  var hitPaths = [];
3621
3711
  var byPath = {};
3712
+ var sheetsByPath = {};
3622
3713
  var i;
3623
3714
  for (i = 0; i < note.hits.length; i++) {
3624
3715
  var h = note.hits[i];
3625
3716
  if (!h || typeof h.path !== "string" || !isMintablePath(h.path)) continue;
3717
+ if (typeof h.sheet === "string" && h.sheet) {
3718
+ if (!byPath[h.path]) {
3719
+ byPath[h.path] = [];
3720
+ hitPaths.push(h.path);
3721
+ }
3722
+ if (!sheetsByPath[h.path]) sheetsByPath[h.path] = [];
3723
+ if (sheetsByPath[h.path].indexOf(h.sheet) === -1) sheetsByPath[h.path].push(h.sheet);
3724
+ continue;
3725
+ }
3626
3726
  var page = typeof h.page === "number" ? h.page : Number(h.page);
3627
3727
  if (!isFinite(page) || page <= 0) continue;
3628
3728
  page = Math.floor(page);
@@ -3634,6 +3734,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3634
3734
  }
3635
3735
  for (i = 0; i < hitPaths.length; i++) {
3636
3736
  var p = hitPaths[i];
3737
+ var sheets = sheetsByPath[p] || [];
3738
+ for (var sj = 0; sj < sheets.length; sj++) {
3739
+ out.push({ path: p, label: citationFileName(p) + " \xB7 " + sheets[sj] });
3740
+ }
3637
3741
  var pages = byPath[p].slice().sort(function(a, b) {
3638
3742
  return a - b;
3639
3743
  });
@@ -4001,38 +4105,6 @@ Index the REMAINING windows - one record per row/item, looking at any page image
4001
4105
  return closest.call(img, PREVIEW_LAYOUT_BOX_SELECTOR) || img;
4002
4106
  }
4003
4107
 
4004
- // src/engine/time.ts
4005
- function wallClockNow() {
4006
- return Date.now();
4007
- }
4008
- function formatChatTimestamp(ms) {
4009
- if (typeof ms !== "number" || !isFinite(ms) || ms <= 0) return "";
4010
- try {
4011
- return new Date(ms).toLocaleString(void 0, {
4012
- year: "numeric",
4013
- month: "short",
4014
- day: "numeric",
4015
- hour: "numeric",
4016
- minute: "2-digit",
4017
- second: "2-digit"
4018
- });
4019
- } catch (e) {
4020
- return "";
4021
- }
4022
- }
4023
- function formatDuration(ms) {
4024
- if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
4025
- var total = Math.floor(ms / 1e3);
4026
- var h = Math.floor(total / 3600);
4027
- var m = Math.floor(total % 3600 / 60);
4028
- var s = total % 60;
4029
- var out = [];
4030
- if (h) out.push(h + "h");
4031
- if (m) out.push(m + "m");
4032
- out.push(s + "s");
4033
- return out.join(" ");
4034
- }
4035
-
4036
4108
  // src/engine/ai_agent.ts
4037
4109
  function normalizePlatform(raw) {
4038
4110
  var p = (raw || "").trim().toLowerCase();
@@ -5596,19 +5668,6 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5596
5668
  }
5597
5669
  var LIVE_PAINT_MIN_MS = 250;
5598
5670
  var LIVE_TYPE_MAX_STEP = 1200;
5599
- function requestIdTimeMs(rid) {
5600
- if (typeof rid !== "string") return 0;
5601
- var stamp = rid.split(":")[0] || "";
5602
- if (stamp.length !== 13) return 0;
5603
- var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
5604
- var v = 0;
5605
- for (var i = 0; i < stamp.length; i++) {
5606
- var d = alphabet.indexOf(stamp.charAt(i).toUpperCase());
5607
- if (d < 0) return 0;
5608
- v = v * 32 + d;
5609
- }
5610
- return Math.floor(v / 2 / 1e6);
5611
- }
5612
5671
  var WRONG_ANSWER_MESSAGE = "This answer seems wrong. Please check it again against the documents.";
5613
5672
  var WRONG_ANSWER_LABEL = "Wrong answer?";
5614
5673
  function canReportWrongAnswer(msg) {
@@ -5695,6 +5754,18 @@ Index the REMAINING windows - one record per row/item, looking at any page image
5695
5754
  /** Pages watching a project's background indexing queue (watchIndexQueue). */
5696
5755
  this._iqWatches = [];
5697
5756
  this._chainsRestored = false;
5757
+ /**
5758
+ * A run closed idle (a complete queue look found no pass of it) whose record still says
5759
+ * 'working': when it is THIS user's run of a client-driven file and no browser tab here
5760
+ * keeps its chain (a reload, a discarded tab, or a browser without localStorage lost
5761
+ * it), nothing will ever send its next pass, so run:: says CHAIN_LOST_TEXT. Never for a
5762
+ * worker-driven file (the worker writes its endings), another user's run (their chain is
5763
+ * in their browser), or a run whose next pass is being looked for.
5764
+ */
5765
+ /** Files the last queue look listed pending or running, settled bubbles included. */
5766
+ this._rawListedIndexKeys = {};
5767
+ /** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
5768
+ this._lostLooks = {};
5698
5769
  /**
5699
5770
  * Pick up indexing passes the WORKER minted, which no client ever dispatched.
5700
5771
  *
@@ -6090,6 +6161,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6090
6161
  _recordLiveIndexKeys(lists) {
6091
6162
  var next = {};
6092
6163
  var running = {};
6164
+ var rawListed = {};
6093
6165
  var truncated = false;
6094
6166
  var runningTruncated = false;
6095
6167
  var settledIds = {};
@@ -6112,6 +6184,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6112
6184
  for (var i = 0; i < list.length; i++) {
6113
6185
  var item = list[i];
6114
6186
  if (!item || item.status !== "pending" && item.status !== "running") continue;
6187
+ var rawRef = parseIndexingRequestText(listedRequestText(item));
6188
+ if (rawRef) {
6189
+ if (rawRef.path) rawListed[rawRef.path] = true;
6190
+ if (rawRef.name) rawListed[rawRef.name] = true;
6191
+ }
6115
6192
  if (item.id && settledIds[item.id]) continue;
6116
6193
  var text = listedRequestText(item);
6117
6194
  if (!isIndexingRequestText(text)) continue;
@@ -6153,6 +6230,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6153
6230
  }
6154
6231
  }
6155
6232
  this.state.liveIndexKeys = next;
6233
+ this._rawListedIndexKeys = rawListed;
6156
6234
  if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
6157
6235
  var settledNow = this.state.liveIndexSettled || {};
6158
6236
  var settledNext = {};
@@ -9975,33 +10053,40 @@ Index the REMAINING windows - one record per row/item, looking at any page image
9975
10053
  else if (!Object.keys(self._openMap()).length && !self._viewMounted()) self._stopStatusPush();
9976
10054
  });
9977
10055
  }
9978
- /**
9979
- * A run closed idle (a complete queue look found no pass of it) whose record still says
9980
- * 'working': when it is THIS user's run of a client-driven file and no browser tab here
9981
- * keeps its chain (a reload, a discarded tab, or a browser without localStorage lost
9982
- * it), nothing will ever send its next pass, so run:: says CHAIN_LOST_TEXT. Never for a
9983
- * worker-driven file (the worker writes its endings), another user's run (their chain is
9984
- * in their browser), or a run whose next pass is being looked for.
9985
- */
10056
+ _lostKey(run) {
10057
+ return run.projectId + "\0" + run.storagePath + "\0" + run.since;
10058
+ }
9986
10059
  _flipIfChainLost(run) {
9987
10060
  var self = this;
9988
- if (!run.owner) return;
10061
+ if (!run.owner) return false;
10062
+ var raw = this._rawListedIndexKeys || {};
10063
+ if (raw[run.storagePath] || run.filename && raw[run.filename]) {
10064
+ delete this._lostLooks[this._lostKey(run)];
10065
+ return true;
10066
+ }
10067
+ var lk = this._lostKey(run);
10068
+ if (!this._lostLooks[lk]) {
10069
+ this._lostLooks[lk] = 1;
10070
+ return true;
10071
+ }
10072
+ delete this._lostLooks[lk];
9989
10073
  var live = null;
9990
10074
  try {
9991
10075
  live = this.host.getIdentity();
9992
10076
  } catch (e2) {
9993
10077
  live = null;
9994
10078
  }
9995
- if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return;
10079
+ if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return false;
9996
10080
  var name = run.filename || run.storagePath.split("/").pop() || run.storagePath;
9997
- if (this._isWorkerDrivenIndexing(name, void 0)) return;
9998
- if (this._chainKept(run.projectId, run.storagePath)) return;
10081
+ if (this._isWorkerDrivenIndexing(name, void 0)) return false;
10082
+ if (workerIndexEndingsEnabled() && !isPagedReadFile(name, void 0)) return false;
10083
+ if (this._chainKept(run.projectId, run.storagePath)) return false;
9999
10084
  for (var q = 0; q < this.bgTaskQueue.length; q++) {
10000
10085
  var e = this.bgTaskQueue[q];
10001
- if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return;
10086
+ if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return false;
10002
10087
  }
10003
10088
  if (this._recPending) for (var c in this._recPending) {
10004
- if (this._recPending[c].kind === "indexing" && this._recPending[c].projectId === run.projectId) return;
10089
+ if (this._recPending[c].kind === "indexing" && this._recPending[c].projectId === run.projectId) return false;
10005
10090
  }
10006
10091
  var projectId = run.projectId, path = run.storagePath;
10007
10092
  runSettleSideEffect(projectId, bgIndexingQueueName(live.userId, projectId), "lost:" + projectId + ":" + path + ":" + run.since, function() {
@@ -10014,6 +10099,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10014
10099
  }
10015
10100
  });
10016
10101
  });
10102
+ return false;
10017
10103
  }
10018
10104
  /** A file run the queue says is live, or that this page has a pass queued for. */
10019
10105
  _fileRunLive(run) {
@@ -10045,8 +10131,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
10045
10131
  var closed = [];
10046
10132
  for (var k in runs) {
10047
10133
  if (runs[k].projectId !== projectId || this._fileRunLive(runs[k])) continue;
10134
+ if (this._flipIfChainLost(runs[k])) continue;
10048
10135
  closed.push(runs[k].storagePath);
10049
- this._flipIfChainLost(runs[k]);
10050
10136
  delete runs[k];
10051
10137
  if (!this._fileRunsIdle) this._fileRunsIdle = {};
10052
10138
  this._fileRunsIdle[k] = true;
@@ -11509,15 +11595,18 @@ Index the REMAINING windows - one record per row/item, looking at any page image
11509
11595
  self.updateHistoryCache();
11510
11596
  });
11511
11597
  }
11512
- /** Insert bubbles before the first message that is newer than them (by `_ts`); messages
11513
- * without a time are skipped over, and the end of the list takes them otherwise. */
11598
+ /** Insert bubbles before the first message that is newer than them; messages whose time
11599
+ * is unknown are skipped over, and the end of the list takes them otherwise. A message's
11600
+ * time is its `_ts`, else (2026-11-25) the time in its request id: a live worker pass
11601
+ * adopted from the queue carries no `_ts`, and a file's older passes loaded by opening its
11602
+ * row (loadRunPasses) used to land AFTER it, which split one run into two rows. */
11514
11603
  _insertByTime(bubbles) {
11515
- var at = bubbles[0] && bubbles[0]._ts;
11604
+ var at = messageTimeMs(bubbles[0]);
11516
11605
  var idx = this.state.messages.length;
11517
- if (typeof at === "number") {
11606
+ if (at > 0) {
11518
11607
  for (var i = 0; i < this.state.messages.length; i++) {
11519
- var t = this.state.messages[i] && this.state.messages[i]._ts;
11520
- if (typeof t === "number" && t > at) {
11608
+ var t = messageTimeMs(this.state.messages[i]);
11609
+ if (t > 0 && t > at) {
11521
11610
  idx = i;
11522
11611
  break;
11523
11612
  }
@@ -13081,7 +13170,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13081
13170
  (function() {
13082
13171
  var MCP_PROD = "https://mcp.skapi.com";
13083
13172
  var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
13084
- var BQ_VERSION = "1.21.0" ;
13173
+ var BQ_VERSION = "1.21.4" ;
13085
13174
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
13086
13175
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
13087
13176
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -18135,12 +18224,16 @@ Index the REMAINING windows - one record per row/item, looking at any page image
18135
18224
  // a project that turned it off.
18136
18225
  skipDuplicateFiles: null,
18137
18226
  // Reuse the MCP tool listing OpenAI returned on an earlier chat turn, so
18138
- // OpenAI skips fetching it again (about 0.6 s per turn). Off unless true.
18139
- // See the engine's configureChatEngine `reuseMcpToolList`.
18140
- reuseMcpToolList: false,
18227
+ // OpenAI skips fetching it again (about 0.6 s per turn). On unless false
18228
+ // (verified live on dev 2026-11-25). See configureChatEngine `reuseMcpToolList`.
18229
+ reuseMcpToolList: true,
18141
18230
  // Server-driven windowed indexing; read at configureChatEngine time.
18142
18231
  // Listed here so the defaults object is the full opt surface.
18143
18232
  windowedIndexing: true,
18233
+ // The worker writes the ending of a file read in one pass (an image); see the
18234
+ // engine's configureChatEngine `workerIndexEndings`. Opt-in until every region's
18235
+ // worker carries it.
18236
+ workerIndexEndings: false,
18144
18237
  // Deliver the streamed reply over skapi's WEBSOCKET as well as the poll.
18145
18238
  // OFF unless the embedder asks, because this widget runs on someone else's
18146
18239
  // page with someone else's skapi instance: skapi's joinRealtime REPLACES
@@ -18245,6 +18338,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
18245
18338
  // MAX_INDEXING_RESUME_PASSES, which needs the tab kept open and stops early
18246
18339
  // on a big file. Pass windowedIndexing: false in init opts to opt back out.
18247
18340
  windowedIndexing: S.opts.windowedIndexing !== false,
18341
+ // single-pass files: the worker writes their done:: / run:: (opt-in, see defaults)
18342
+ workerIndexEndings: S.opts.workerIndexEndings === true,
18248
18343
  // Client-side attachment parsers (e.g. an .hwp parser) passed via init opts.
18249
18344
  attachmentParsers: S.opts.attachmentParsers || void 0,
18250
18345
  // Web access for chat answers. Handed over ONLY when the embedder
@@ -18256,8 +18351,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
18256
18351
  // Skip duplicate uploads. Same hand-over rule: only a pinned boolean is
18257
18352
  // passed, and the project's setting is the ceiling the engine applies.
18258
18353
  skipDuplicateFiles: typeof S.opts.skipDuplicateFiles === "boolean" ? S.opts.skipDuplicateFiles : void 0,
18259
- // OpenAI MCP tool-list reuse across chat turns: only an explicit true.
18260
- reuseMcpToolList: S.opts.reuseMcpToolList === true,
18354
+ // OpenAI MCP tool-list reuse across chat turns: on unless an explicit false.
18355
+ reuseMcpToolList: S.opts.reuseMcpToolList !== false,
18261
18356
  // ---- live streaming (mirrored in agent.vue's ai_agent.ts) --------
18262
18357
  // Streaming itself is not passed: the engine streams whenever the two
18263
18358
  // hooks below are handed over, which skapiEngineTransport does only when