bunnyquery 1.21.0 → 1.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.d.mts CHANGED
@@ -492,6 +492,16 @@ interface ChatEngineConfig {
492
492
  * until the worker is deployed, then flip it per environment.
493
493
  */
494
494
  windowedIndexing?: boolean;
495
+ /**
496
+ * The worker writes the ending (done:: and run::) of a file read in ONE pass (an image,
497
+ * or any file not rendered, windowed or paged), as it does for paged chains: the engine
498
+ * then no longer marks such a run "Indexing stopped ... (the page was closed)" when no
499
+ * page here kept its chain. The engine always sends the request flag (index_end); this
500
+ * switch only stops the client-side "lost" verdict. Turn it on only once every region's
501
+ * worker and polling-recovery Lambda carry the 2026-11-25 change: with an older worker
502
+ * a page closed mid-pass would leave the run 'working'. Off unless true.
503
+ */
504
+ workerIndexEndings?: boolean;
495
505
  /**
496
506
  * Mint the durable "indexing finished" marker record ("done::<path>",
497
507
  * reference "src::<path>", table __INDEXING__ — same shape the backend
@@ -617,8 +627,8 @@ interface ChatEngineConfig {
617
627
  * `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
618
628
  * (four sequential requests, about 0.6 s before the model starts).
619
629
  *
620
- * OFF unless set to `true`. Leave it off until one real OpenAI chat on a dev project
621
- * has answered with it on: an account that refuses the item fails one turn, after
630
+ * OFF unless set to `true` (the widget and bunnyquery.com set it; verified on a live
631
+ * OpenAI chat 2026-11-25). An account that refuses the item fails one turn, after
622
632
  * which reuse stays off for that project in this browser. Costs when on: each
623
633
  * reused turn's request body, and so its stored history row, is about 31 to 34 KB
624
634
  * larger (the tool list), which also comes back with every history page.
@@ -1375,6 +1385,13 @@ type BuildIndexingUserMessageOptions = {
1375
1385
  * message instructs the agent to page through EVERY window and datafy each.
1376
1386
  */
1377
1387
  pagedRead?: boolean;
1388
+ /**
1389
+ * An IMAGE file (2026-11-25). 'attached': the engine attaches it to this message as an
1390
+ * image block (jpg/jpeg/png/gif/webp, the ones its image-URL pattern matches). 'maybe': a
1391
+ * format the providers do not take (tif/tiff/bmp/heic); a newer worker attaches a
1392
+ * converted copy, an older one attaches nothing, so the message never claims a picture.
1393
+ */
1394
+ imageFile?: 'attached' | 'maybe';
1378
1395
  };
1379
1396
  /**
1380
1397
  * The access group to write this file's records at. One place, so the user
@@ -1630,9 +1647,11 @@ declare function isTransportFailure(err: any): boolean;
1630
1647
  * the chat gets. A host that never attaches `_retrieval` sees byte-identical
1631
1648
  * requests to today.
1632
1649
  */
1650
+ /** sheet: the hit was on a spreadsheet's sheet page (MCP 2026-11-25), whose page number means nothing to a reader. */
1633
1651
  type RetrievalHit = {
1634
1652
  path: string;
1635
1653
  page: number;
1654
+ sheet?: string;
1636
1655
  };
1637
1656
  type RetrievalNote = {
1638
1657
  /** Storage paths (the part after "src::") the turn read, queried or linked. */
@@ -6181,6 +6200,11 @@ declare class ChatSession {
6181
6200
  * worker-driven file (the worker writes its endings), another user's run (their chain is
6182
6201
  * in their browser), or a run whose next pass is being looked for.
6183
6202
  */
6203
+ /** Files the last queue look listed pending or running, settled bubbles included. */
6204
+ private _rawListedIndexKeys;
6205
+ /** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
6206
+ private _lostLooks;
6207
+ private _lostKey;
6184
6208
  private _flipIfChainLost;
6185
6209
  /** A file run the queue says is live, or that this page has a pass queued for. */
6186
6210
  private _fileRunLive;
package/dist/engine.d.ts CHANGED
@@ -492,6 +492,16 @@ interface ChatEngineConfig {
492
492
  * until the worker is deployed, then flip it per environment.
493
493
  */
494
494
  windowedIndexing?: boolean;
495
+ /**
496
+ * The worker writes the ending (done:: and run::) of a file read in ONE pass (an image,
497
+ * or any file not rendered, windowed or paged), as it does for paged chains: the engine
498
+ * then no longer marks such a run "Indexing stopped ... (the page was closed)" when no
499
+ * page here kept its chain. The engine always sends the request flag (index_end); this
500
+ * switch only stops the client-side "lost" verdict. Turn it on only once every region's
501
+ * worker and polling-recovery Lambda carry the 2026-11-25 change: with an older worker
502
+ * a page closed mid-pass would leave the run 'working'. Off unless true.
503
+ */
504
+ workerIndexEndings?: boolean;
495
505
  /**
496
506
  * Mint the durable "indexing finished" marker record ("done::<path>",
497
507
  * reference "src::<path>", table __INDEXING__ — same shape the backend
@@ -617,8 +627,8 @@ interface ChatEngineConfig {
617
627
  * `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
618
628
  * (four sequential requests, about 0.6 s before the model starts).
619
629
  *
620
- * OFF unless set to `true`. Leave it off until one real OpenAI chat on a dev project
621
- * has answered with it on: an account that refuses the item fails one turn, after
630
+ * OFF unless set to `true` (the widget and bunnyquery.com set it; verified on a live
631
+ * OpenAI chat 2026-11-25). An account that refuses the item fails one turn, after
622
632
  * which reuse stays off for that project in this browser. Costs when on: each
623
633
  * reused turn's request body, and so its stored history row, is about 31 to 34 KB
624
634
  * larger (the tool list), which also comes back with every history page.
@@ -1375,6 +1385,13 @@ type BuildIndexingUserMessageOptions = {
1375
1385
  * message instructs the agent to page through EVERY window and datafy each.
1376
1386
  */
1377
1387
  pagedRead?: boolean;
1388
+ /**
1389
+ * An IMAGE file (2026-11-25). 'attached': the engine attaches it to this message as an
1390
+ * image block (jpg/jpeg/png/gif/webp, the ones its image-URL pattern matches). 'maybe': a
1391
+ * format the providers do not take (tif/tiff/bmp/heic); a newer worker attaches a
1392
+ * converted copy, an older one attaches nothing, so the message never claims a picture.
1393
+ */
1394
+ imageFile?: 'attached' | 'maybe';
1378
1395
  };
1379
1396
  /**
1380
1397
  * The access group to write this file's records at. One place, so the user
@@ -1630,9 +1647,11 @@ declare function isTransportFailure(err: any): boolean;
1630
1647
  * the chat gets. A host that never attaches `_retrieval` sees byte-identical
1631
1648
  * requests to today.
1632
1649
  */
1650
+ /** sheet: the hit was on a spreadsheet's sheet page (MCP 2026-11-25), whose page number means nothing to a reader. */
1633
1651
  type RetrievalHit = {
1634
1652
  path: string;
1635
1653
  page: number;
1654
+ sheet?: string;
1636
1655
  };
1637
1656
  type RetrievalNote = {
1638
1657
  /** Storage paths (the part after "src::") the turn read, queried or linked. */
@@ -6181,6 +6200,11 @@ declare class ChatSession {
6181
6200
  * worker-driven file (the worker writes its endings), another user's run (their chain is
6182
6201
  * in their browser), or a run whose next pass is being looked for.
6183
6202
  */
6203
+ /** Files the last queue look listed pending or running, settled bubbles included. */
6204
+ private _rawListedIndexKeys;
6205
+ /** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
6206
+ private _lostLooks;
6207
+ private _lostKey;
6184
6208
  private _flipIfChainLost;
6185
6209
  /** A file run the queue says is live, or that this page has a pass queued for. */
6186
6210
  private _fileRunLive;
package/dist/engine.mjs CHANGED
@@ -276,6 +276,9 @@ function crefSupported() {
276
276
  function windowedIndexingEnabled() {
277
277
  return _config?.windowedIndexing === true;
278
278
  }
279
+ function workerIndexEndingsEnabled() {
280
+ return _config?.workerIndexEndings === true;
281
+ }
279
282
  function statusPushEnabled() {
280
283
  return _config?.statusPush === true && typeof _config?.onRequestStatus === "function";
281
284
  }
@@ -1063,8 +1066,8 @@ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rul
1063
1066
  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.
1064
1067
  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.`;
1065
1068
  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.`;
1066
- 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.
1067
- 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.`;
1069
+ 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.
1070
+ 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.`;
1068
1071
  const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
1069
1072
  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.`;
1070
1073
  let systemPrompt = `
@@ -1073,7 +1076,7 @@ Scope: Only answer questions about this project and its data. Do not answer ques
1073
1076
  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.
1074
1077
  ${groundingRules}
1075
1078
  ${webRule}
1076
- 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).
1079
+ 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).
1077
1080
  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.
1078
1081
  ${documentRules}
1079
1082
  ${accessGroupRule}
@@ -1124,13 +1127,13 @@ function buildIndexingSystemPrompt(params) {
1124
1127
  const { projectId, serviceName, serviceDescription } = params;
1125
1128
  const accessGroup = params.accessGroup === "public" || params.accessGroup === "private" ? params.accessGroup : "authorized";
1126
1129
  let systemPrompt = `You are a background indexing agent for project ${projectId}.
1127
- - 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.
1130
+ - 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.
1128
1131
  - 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.
1129
1132
  - 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.
1130
1133
  - 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.
1131
1134
  - 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).
1132
- - 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.
1133
- - 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).
1135
+ - 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.
1136
+ - 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).
1134
1137
  - 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.
1135
1138
  - 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.
1136
1139
  - 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.
@@ -1202,6 +1205,12 @@ ${options.inlineContentPlaceholder}
1202
1205
  return head + `
1203
1206
  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 ? `
1204
1207
  (A temporary URL is provided ONLY as a fallback if readFileContent fails: ${attachment.url})` : "");
1208
+ }
1209
+ if (options?.imageFile) {
1210
+ return head + `- temporary URL: ${attachment.url}
1211
+ ` + (options.imageFile === "attached" ? `
1212
+ This is an IMAGE file, attached to this message as an image: read it there, not from the URL. ` : `
1213
+ 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.`;
1205
1214
  }
1206
1215
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
1207
1216
  }
@@ -1821,16 +1830,19 @@ function pushGroup(list, value) {
1821
1830
  if (typeof value === "number" && isFinite(value)) pushUnique(list, String(value));
1822
1831
  else pushUnique(list, value);
1823
1832
  }
1824
- function pushHit(list, path, page) {
1833
+ function pushHit(list, path, page, sheet) {
1825
1834
  if (typeof path !== "string" || !path.trim()) return;
1826
1835
  var n = typeof page === "number" ? page : Number(page);
1827
1836
  if (!isFinite(n) || n <= 0) return;
1828
1837
  n = Math.floor(n);
1838
+ var sh = typeof sheet === "string" && sheet.trim() ? sheet.trim() : "";
1829
1839
  for (var i = 0; i < list.length; i++) {
1830
- if (list[i].path === path && list[i].page === n) return;
1840
+ if (sh ? list[i].path === path && list[i].sheet === sh : list[i].path === path && list[i].page === n) return;
1831
1841
  }
1832
1842
  if (list.length >= RETRIEVAL_NOTE_MAX_ITEMS) return;
1833
- list.push({ path: path.trim(), page: n });
1843
+ var hit = { path: path.trim(), page: n };
1844
+ if (sh) hit.sheet = sh;
1845
+ list.push(hit);
1834
1846
  }
1835
1847
  function pathFromSrcId(value) {
1836
1848
  if (typeof value !== "string") return null;
@@ -1877,7 +1889,7 @@ function readHits(note, result) {
1877
1889
  return;
1878
1890
  }
1879
1891
  if (typeof node.path === "string" && node.page !== void 0) {
1880
- pushHit(note.hits, node.path, node.page);
1892
+ pushHit(note.hits, node.path, node.page, node.sheet);
1881
1893
  }
1882
1894
  for (var k in node) {
1883
1895
  if (!Object.prototype.hasOwnProperty.call(node, k)) continue;
@@ -2006,8 +2018,16 @@ function formatRetrievalNote(note) {
2006
2018
  }
2007
2019
  byFile[h.path].push(h.page);
2008
2020
  }
2021
+ var sheetsOf = {};
2022
+ for (var s2 = 0; s2 < note.hits.length; s2++) {
2023
+ var hs = note.hits[s2];
2024
+ if (hs.sheet) {
2025
+ if (!sheetsOf[hs.path]) sheetsOf[hs.path] = [];
2026
+ if (sheetsOf[hs.path].indexOf(hs.sheet) === -1) sheetsOf[hs.path].push(hs.sheet);
2027
+ }
2028
+ }
2009
2029
  parts.push("searchText hits " + order.map(function(p) {
2010
- return p + " p" + byFile[p].join(", p");
2030
+ return sheetsOf[p] ? p + " sheet " + sheetsOf[p].join(", sheet ") : p + " p" + byFile[p].join(", p");
2011
2031
  }).join("; "));
2012
2032
  }
2013
2033
  if (note.tools.length) parts.push("tools " + note.tools.join(", "));
@@ -2422,6 +2442,13 @@ function getVisionProfile(model) {
2422
2442
  return { detail, pagesPerWindow: RENDER_PAGES_PER_WINDOW, tile: 1 };
2423
2443
  }
2424
2444
  var IMAGE_URL_REGEX = /\bhttps?:\/\/[^\s<>"'()\[\]]+?\.(?:jpg|jpeg|png|gif|webp)(?:\?[^\s<>"'()\[\]]*)?/gi;
2445
+ var INDEX_IMAGE_OTHER_EXT = /\.(?:tiff?|bmp|heic|heif)$/i;
2446
+ function indexingImageFile(attachment) {
2447
+ const url = typeof attachment.url === "string" ? attachment.url : "";
2448
+ if (url && new RegExp(IMAGE_URL_REGEX.source, "i").test(url)) return "attached";
2449
+ if (INDEX_IMAGE_OTHER_EXT.test(attachment.name || "") || INDEX_IMAGE_OTHER_EXT.test(attachment.storagePath || "")) return "maybe";
2450
+ return void 0;
2451
+ }
2425
2452
  function transformContentWithImages(content) {
2426
2453
  if (typeof content !== "string" || !content) {
2427
2454
  return content;
@@ -2861,10 +2888,20 @@ async function notifyAgentSaveAttachment(info) {
2861
2888
  save_media: !continuing
2862
2889
  }))
2863
2890
  } : {};
2864
- const skapiFileUrls = attachment.url && attachment.storagePath ? { _skapi_file_urls: [{ path: attachment.storagePath, url: attachment.url }] } : {};
2891
+ const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
2892
+ const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : void 0;
2893
+ const fileUrlDetail = imageFile && platform === "openai" ? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL) : void 0;
2894
+ const skapiFileUrls = attachment.url && attachment.storagePath ? {
2895
+ _skapi_file_urls: [{
2896
+ path: attachment.storagePath,
2897
+ url: attachment.url,
2898
+ ...singlePass ? { index_end: true } : {},
2899
+ ...fileUrlDetail ? { detail: fileUrlDetail } : {}
2900
+ }]
2901
+ } : {};
2865
2902
  const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : windowedRead && windowPlaceholder ? buildIndexingWindowMessage(attachment, windowPlaceholder, false) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
2866
2903
  attachment,
2867
- parsedContent ? { inlineContent: parsedContent } : placeholder ? { inlineContentPlaceholder: placeholder } : pagedRead ? { pagedRead: true } : void 0
2904
+ parsedContent ? { inlineContent: parsedContent } : placeholder ? { inlineContentPlaceholder: placeholder } : pagedRead ? { pagedRead: true } : imageFile ? { imageFile } : void 0
2868
2905
  );
2869
2906
  const systemPrompt = buildIndexingSystemPrompt({
2870
2907
  // The model copies this id verbatim into project_id tool calls, so it must be
@@ -3769,10 +3806,20 @@ function citationsFor(note) {
3769
3806
  var out = [];
3770
3807
  var hitPaths = [];
3771
3808
  var byPath = {};
3809
+ var sheetsByPath = {};
3772
3810
  var i;
3773
3811
  for (i = 0; i < note.hits.length; i++) {
3774
3812
  var h = note.hits[i];
3775
3813
  if (!h || typeof h.path !== "string" || !isMintablePath(h.path)) continue;
3814
+ if (typeof h.sheet === "string" && h.sheet) {
3815
+ if (!byPath[h.path]) {
3816
+ byPath[h.path] = [];
3817
+ hitPaths.push(h.path);
3818
+ }
3819
+ if (!sheetsByPath[h.path]) sheetsByPath[h.path] = [];
3820
+ if (sheetsByPath[h.path].indexOf(h.sheet) === -1) sheetsByPath[h.path].push(h.sheet);
3821
+ continue;
3822
+ }
3776
3823
  var page = typeof h.page === "number" ? h.page : Number(h.page);
3777
3824
  if (!isFinite(page) || page <= 0) continue;
3778
3825
  page = Math.floor(page);
@@ -3784,6 +3831,10 @@ function citationsFor(note) {
3784
3831
  }
3785
3832
  for (i = 0; i < hitPaths.length; i++) {
3786
3833
  var p = hitPaths[i];
3834
+ var sheets = sheetsByPath[p] || [];
3835
+ for (var sj = 0; sj < sheets.length; sj++) {
3836
+ out.push({ path: p, label: citationFileName(p) + " \xB7 " + sheets[sj] });
3837
+ }
3787
3838
  var pages = byPath[p].slice().sort(function(a, b) {
3788
3839
  return a - b;
3789
3840
  });
@@ -5872,6 +5923,18 @@ var _ChatSession = class _ChatSession {
5872
5923
  /** Pages watching a project's background indexing queue (watchIndexQueue). */
5873
5924
  this._iqWatches = [];
5874
5925
  this._chainsRestored = false;
5926
+ /**
5927
+ * A run closed idle (a complete queue look found no pass of it) whose record still says
5928
+ * 'working': when it is THIS user's run of a client-driven file and no browser tab here
5929
+ * keeps its chain (a reload, a discarded tab, or a browser without localStorage lost
5930
+ * it), nothing will ever send its next pass, so run:: says CHAIN_LOST_TEXT. Never for a
5931
+ * worker-driven file (the worker writes its endings), another user's run (their chain is
5932
+ * in their browser), or a run whose next pass is being looked for.
5933
+ */
5934
+ /** Files the last queue look listed pending or running, settled bubbles included. */
5935
+ this._rawListedIndexKeys = {};
5936
+ /** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
5937
+ this._lostLooks = {};
5875
5938
  /**
5876
5939
  * Pick up indexing passes the WORKER minted, which no client ever dispatched.
5877
5940
  *
@@ -6267,6 +6330,7 @@ var _ChatSession = class _ChatSession {
6267
6330
  _recordLiveIndexKeys(lists) {
6268
6331
  var next = {};
6269
6332
  var running = {};
6333
+ var rawListed = {};
6270
6334
  var truncated = false;
6271
6335
  var runningTruncated = false;
6272
6336
  var settledIds = {};
@@ -6289,6 +6353,11 @@ var _ChatSession = class _ChatSession {
6289
6353
  for (var i = 0; i < list.length; i++) {
6290
6354
  var item = list[i];
6291
6355
  if (!item || item.status !== "pending" && item.status !== "running") continue;
6356
+ var rawRef = parseIndexingRequestText(listedRequestText(item));
6357
+ if (rawRef) {
6358
+ if (rawRef.path) rawListed[rawRef.path] = true;
6359
+ if (rawRef.name) rawListed[rawRef.name] = true;
6360
+ }
6292
6361
  if (item.id && settledIds[item.id]) continue;
6293
6362
  var text = listedRequestText(item);
6294
6363
  if (!isIndexingRequestText(text)) continue;
@@ -6330,6 +6399,7 @@ var _ChatSession = class _ChatSession {
6330
6399
  }
6331
6400
  }
6332
6401
  this.state.liveIndexKeys = next;
6402
+ this._rawListedIndexKeys = rawListed;
6333
6403
  if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
6334
6404
  var settledNow = this.state.liveIndexSettled || {};
6335
6405
  var settledNext = {};
@@ -10152,33 +10222,40 @@ var _ChatSession = class _ChatSession {
10152
10222
  else if (!Object.keys(self._openMap()).length && !self._viewMounted()) self._stopStatusPush();
10153
10223
  });
10154
10224
  }
10155
- /**
10156
- * A run closed idle (a complete queue look found no pass of it) whose record still says
10157
- * 'working': when it is THIS user's run of a client-driven file and no browser tab here
10158
- * keeps its chain (a reload, a discarded tab, or a browser without localStorage lost
10159
- * it), nothing will ever send its next pass, so run:: says CHAIN_LOST_TEXT. Never for a
10160
- * worker-driven file (the worker writes its endings), another user's run (their chain is
10161
- * in their browser), or a run whose next pass is being looked for.
10162
- */
10225
+ _lostKey(run) {
10226
+ return run.projectId + "\0" + run.storagePath + "\0" + run.since;
10227
+ }
10163
10228
  _flipIfChainLost(run) {
10164
10229
  var self = this;
10165
- if (!run.owner) return;
10230
+ if (!run.owner) return false;
10231
+ var raw = this._rawListedIndexKeys || {};
10232
+ if (raw[run.storagePath] || run.filename && raw[run.filename]) {
10233
+ delete this._lostLooks[this._lostKey(run)];
10234
+ return true;
10235
+ }
10236
+ var lk = this._lostKey(run);
10237
+ if (!this._lostLooks[lk]) {
10238
+ this._lostLooks[lk] = 1;
10239
+ return true;
10240
+ }
10241
+ delete this._lostLooks[lk];
10166
10242
  var live = null;
10167
10243
  try {
10168
10244
  live = this.host.getIdentity();
10169
10245
  } catch (e2) {
10170
10246
  live = null;
10171
10247
  }
10172
- if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return;
10248
+ if (!live || !live.userId || live.userId !== run.owner || live.projectId !== run.projectId) return false;
10173
10249
  var name = run.filename || run.storagePath.split("/").pop() || run.storagePath;
10174
- if (this._isWorkerDrivenIndexing(name, void 0)) return;
10175
- if (this._chainKept(run.projectId, run.storagePath)) return;
10250
+ if (this._isWorkerDrivenIndexing(name, void 0)) return false;
10251
+ if (workerIndexEndingsEnabled() && !isPagedReadFile(name, void 0)) return false;
10252
+ if (this._chainKept(run.projectId, run.storagePath)) return false;
10176
10253
  for (var q = 0; q < this.bgTaskQueue.length; q++) {
10177
10254
  var e = this.bgTaskQueue[q];
10178
- if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return;
10255
+ if (e && e.projectId === run.projectId && e.storagePath === run.storagePath) return false;
10179
10256
  }
10180
10257
  if (this._recPending) for (var c in this._recPending) {
10181
- if (this._recPending[c].kind === "indexing" && this._recPending[c].projectId === run.projectId) return;
10258
+ if (this._recPending[c].kind === "indexing" && this._recPending[c].projectId === run.projectId) return false;
10182
10259
  }
10183
10260
  var projectId = run.projectId, path = run.storagePath;
10184
10261
  runSettleSideEffect(projectId, bgIndexingQueueName(live.userId, projectId), "lost:" + projectId + ":" + path + ":" + run.since, function() {
@@ -10191,6 +10268,7 @@ var _ChatSession = class _ChatSession {
10191
10268
  }
10192
10269
  });
10193
10270
  });
10271
+ return false;
10194
10272
  }
10195
10273
  /** A file run the queue says is live, or that this page has a pass queued for. */
10196
10274
  _fileRunLive(run) {
@@ -10222,8 +10300,8 @@ var _ChatSession = class _ChatSession {
10222
10300
  var closed = [];
10223
10301
  for (var k in runs) {
10224
10302
  if (runs[k].projectId !== projectId || this._fileRunLive(runs[k])) continue;
10303
+ if (this._flipIfChainLost(runs[k])) continue;
10225
10304
  closed.push(runs[k].storagePath);
10226
- this._flipIfChainLost(runs[k]);
10227
10305
  delete runs[k];
10228
10306
  if (!this._fileRunsIdle) this._fileRunsIdle = {};
10229
10307
  this._fileRunsIdle[k] = true;