bunnyquery 1.21.4 → 1.21.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.mjs CHANGED
@@ -78,6 +78,14 @@ function normalizeSkipDuplicateFiles(value) {
78
78
  function skipDuplicateFilesFrom(data) {
79
79
  return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
80
80
  }
81
+ var SHARE_IDENTICAL_FILES_KEY = "share_identical_files";
82
+ var DEFAULT_SHARE_IDENTICAL_FILES = true;
83
+ function normalizeShareIdenticalFiles(value) {
84
+ return value !== false;
85
+ }
86
+ function shareIdenticalFilesFrom(data) {
87
+ return data ? normalizeShareIdenticalFiles(data.share_identical_files) : DEFAULT_SHARE_IDENTICAL_FILES;
88
+ }
81
89
  var ANSWER_MODES = ["standard", "fast", "thorough"];
82
90
  var DEFAULT_ANSWER_MODE = "standard";
83
91
  var ANSWER_MODE_SETTING_LABEL = "Answer mode";
@@ -191,6 +199,9 @@ function projectWebAccess(service) {
191
199
  function projectSkipDuplicateFiles(service) {
192
200
  return skipDuplicateFilesFrom(cachedProjectSettings(service));
193
201
  }
202
+ function projectShareIdenticalFiles(service) {
203
+ return shareIdenticalFilesFrom(cachedProjectSettings(service));
204
+ }
194
205
  function projectAnswerMode(service) {
195
206
  return answerModeFrom(cachedProjectSettings(service));
196
207
  }
@@ -1061,10 +1072,12 @@ function buildChatSystemPrompt(params) {
1061
1072
  const webAccess = params.webAccess === true;
1062
1073
  const g = params.indexAccessGroup;
1063
1074
  const indexGroupLiteral = typeof g === "number" ? String(g) : g === "public" || g === "private" || g === "authorized" || g === "admin" ? `"${g}"` : '"authorized"';
1075
+ const reindexHint = canUpload === false ? `asking the project's owner to re-index that file` : client === "console" ? `re-indexing that file (select it on the Files page and choose Reindex)` : `re-indexing that file (attach the same file again and choose to reindex it)`;
1064
1076
  const groundingRules = `ANSWER ONLY FROM THE DATA. Every fact you state about this project's data - a name, a number, a date, a status, what a document says, whether something exists - must come from one of four places: a tool result returned in THIS conversation, a file or image attached to it (including one you read through its attachment link), the project description at the end of this prompt, or what the user told you themselves in this chat. Your general knowledge, the open internet and a plausible guess are NOT sources. Never use them to answer a question about the user's data, to fill a gap in it, or to complete a record that came back partial. A value that is not in what you retrieved is unknown: say it is not in the data instead of supplying a likely one.
1065
1077
  WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rules require and nothing answers the question, tell the user plainly, in their language, that this project's data does not contain it, and say what you searched (the tables, files or terms) so they can tell missing data from a missed search. Do not answer from memory instead, and do not turn a missing answer into a general explanation of the topic. Offer what would let you answer it: ${canUpload === false ? `another name or file to look under, or asking the project's owner to add it` : `the document to upload, or another name or file to look under`}.
1078
+ A CODE, NUMBER OR PHRASE THAT searchText DID NOT FIND: when it answers search_complete with no hit, and what its message says was NOT searched has been checked as it says (the skipped_without_page_text files; the records ONLY when the value could be a spreadsheet cell or a row, and then with ONE filtered getRecords on that value, never by paging through a whole table), keep the answer short. The text read from photos, scans and other images IS in the page text searchText covered, so a code, serial or phrase asked about a photo needs no records read: say plainly that it was not found, name what was searched (the file, and its pages when you searched only some of them, or files_searched files and total_pages_searched pages), and when a recently uploaded file or a photo should hold it, suggest ${reindexHint}, since small or handwritten characters can be misread at indexing. Never present a different file as the match, and never guess the value.
1066
1079
  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.
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.`;
1080
+ These 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.`;
1068
1081
  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.`;
1069
1082
  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
1083
  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.`;
@@ -1081,6 +1094,7 @@ NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and n
1081
1094
  ${documentRules}
1082
1095
  ${accessGroupRule}
1083
1096
  COMPLETE ANSWERS: ONE file is routinely SPLIT ACROSS SEVERAL TABLES (a summary row in one, its page or row content in another, its extracted pictures in "__MEDIA__"), so for anything not scoped to a single file run the query in EVERY table that could hold the answer and combine the results. For any request that counts, sums, totals, lists every match, compares across records, finds which one, or asks whether something is present or ABSENT (for example "how many", "total spent", "which card", "is there any", "\uC5C6\uC5B4?", "\uD558\uB098\uB3C4 \uC5C6\uB098?"), read the COMPLETE matching set across every such table and file before answering. Never assert absence ("there is no X", "none", "not found", "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4") until a complete scan has come back empty: a confident "no" that later turns out wrong is worse than telling the user you are still checking. If you answered from one table and then find another holds more, re-run the sweep and give the complete answer instead of only apologising.
1097
+ LINKED COPIES: files with the same content are indexed once. A file a tool reports as a linked copy (linked_copy, or listed in a hit's also_at) has no rows or pages of its own: its content is the original's, stored and tagged under the original's name. Cite the original file and say that the copy is the same file; never count the two as two documents.
1084
1098
  Embedded values: a search term is often stored inside a larger string (a merchant "BAKSA" as "DNH*BAKSA#4070277042", a card as "5860****5173"), which no index or tag filter matches. When the value may be embedded, fetch the full set with fetch_all and match the substring yourself.
1085
1099
  File attachments: an "Attached files:" section with markdown links in a user message points at short-lived signed URLs in this project's storage. Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY in the message as image blocks: look at them directly. Every other attached file (office documents such as .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, PDFs, email (.eml), text/data/code files such as .csv/.tsv/.json/.xml/.txt/.md) is ALREADY INDEXED: it was read end to end when it was uploaded, before this message reached you, so answer from its records (reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS). Some turns instead carry the file text between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers: read that block directly; a "[skapi: ...]" note inside it means that file could not be extracted. ${webAccess ? `Never web_fetch an attachment link (the picture is already in the message, everything else is in the database); a file the user gives as an outside web address may be fetched under the web rule above.` : `This chat has no web tool: never try to download or fetch an attachment link.`}
1086
1100
  Stored files: a file already in this project's storage was read end to end at upload time, so its records come first. For its exact wording find the page with searchText (DOCUMENTS); readFileContent re-reads the raw file (an older file without page text, a data file), and you read it to the end before concluding anything is absent there. If its pictures do not reach you, say so plainly and fall back to the indexed records; never call a file unreadable when its content is in the database.
@@ -1133,7 +1147,7 @@ function buildIndexingSystemPrompt(params) {
1133
1147
  - 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.
1134
1148
  - 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).
1135
1149
  - 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).
1150
+ - 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). ALSO set "text_regions" on that record: a list of up to 4 boxes [left, top, right, bottom], each a fraction from 0 to 1 of the image AS IT IS SHOWN TO YOU (not turned upright), drawn tightly around a label, plate or handwritten area whose characters matter (a serial number, a part number, a tag id); [] when there is none. Where a label names a value (a form field, a plate line), write the value right after its label in "printed_text" or "handwritten_text", as "<label>: <value>" (the label's own words, then the characters written beside it), so the label and its value are found together.
1137
1151
  - 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.
1138
1152
  - 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.
1139
1153
  - 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.
@@ -1210,7 +1224,7 @@ Read this file with the readFileContent tool, using the storage path above - do
1210
1224
  return head + `- temporary URL: ${attachment.url}
1211
1225
  ` + (options.imageFile === "attached" ? `
1212
1226
  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.`;
1227
+ 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". Write each label's value right after its label, as "<label>: <value>" (the label's own words, then the characters written beside it), reading small and handwritten characters closely; use [?] only for a character that is truly unreadable, and never put a guessed character in its place. Then set "text_rotation", "text_legibility" and "text_regions" on the file's "src::" record, and only then describe what the image shows. "text_regions" is a list of up to 4 boxes [left, top, right, bottom], each a fraction from 0 to 1 of the image exactly as it is shown to you here (not turned upright), drawn tightly around a label, plate or handwritten area whose characters matter (a serial number, a part number, a tag); [] when there is none.`;
1214
1228
  }
1215
1229
  return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
1216
1230
  }
@@ -2891,12 +2905,14 @@ async function notifyAgentSaveAttachment(info) {
2891
2905
  const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
2892
2906
  const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : void 0;
2893
2907
  const fileUrlDetail = imageFile && platform === "openai" ? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL) : void 0;
2908
+ const shareIdentical = !continuing && info.shareIdentical !== false && (info.shareIdentical === true || projectShareIdenticalFiles(service));
2894
2909
  const skapiFileUrls = attachment.url && attachment.storagePath ? {
2895
2910
  _skapi_file_urls: [{
2896
2911
  path: attachment.storagePath,
2897
2912
  url: attachment.url,
2898
2913
  ...singlePass ? { index_end: true } : {},
2899
- ...fileUrlDetail ? { detail: fileUrlDetail } : {}
2914
+ ...fileUrlDetail ? { detail: fileUrlDetail } : {},
2915
+ ...shareIdentical ? { share_identical: true } : {}
2900
2916
  }]
2901
2917
  } : {};
2902
2918
  const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : windowedRead && windowPlaceholder ? buildIndexingWindowMessage(attachment, windowPlaceholder, false) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
@@ -3023,13 +3039,26 @@ async function notifyAgentSaveAttachment(info) {
3023
3039
  }
3024
3040
  }));
3025
3041
  }
3042
+ function providerDocument(response) {
3043
+ if (typeof response !== "string") return response;
3044
+ var t = response.trim();
3045
+ if (t.charAt(0) !== "{" || t.charAt(t.length - 1) !== "}") return response;
3046
+ try {
3047
+ var doc = JSON.parse(t);
3048
+ return doc && typeof doc === "object" && !Array.isArray(doc) ? doc : response;
3049
+ } catch (e) {
3050
+ return response;
3051
+ }
3052
+ }
3026
3053
  function extractClaudeText(response) {
3054
+ response = providerDocument(response);
3027
3055
  if (!Array.isArray(response?.content)) {
3028
3056
  return "";
3029
3057
  }
3030
3058
  return response.content.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
3031
3059
  }
3032
3060
  function extractOpenAIText(response) {
3061
+ response = providerDocument(response);
3033
3062
  if (typeof response?.output_text === "string" && response.output_text.length) {
3034
3063
  return response.output_text;
3035
3064
  }
@@ -3201,6 +3230,16 @@ function formatDuration(ms) {
3201
3230
  out.push(s + "s");
3202
3231
  return out.join(" ");
3203
3232
  }
3233
+ function formatIndexDuration(ms) {
3234
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 1e3) return "";
3235
+ var total = Math.floor(ms / 1e3);
3236
+ var h = Math.floor(total / 3600);
3237
+ var m = Math.floor(total % 3600 / 60);
3238
+ var s = total % 60;
3239
+ if (h) return h + " h" + (m ? " " + m + " min" : "");
3240
+ if (m) return m + " min" + (s ? " " + s + " s" : "");
3241
+ return s + " s";
3242
+ }
3204
3243
  function requestIdTimeMs(rid) {
3205
3244
  if (typeof rid !== "string") return 0;
3206
3245
  var stamp = rid.split(":")[0] || "";
@@ -3221,6 +3260,311 @@ function messageTimeMs(m) {
3221
3260
  return typeof m._ts === "number" && m._ts > 0 ? m._ts : 0;
3222
3261
  }
3223
3262
 
3263
+ // src/engine/identical.ts
3264
+ var LINKED_COPY_TAG = "bq_linked";
3265
+ var CONTENT_CLAIM_PREFIX = "cas::";
3266
+ function linkedMarkerOf(data) {
3267
+ if (!data || typeof data !== "object" || data.linked !== true) return null;
3268
+ var original = typeof data.alias_of === "string" ? data.alias_of : "";
3269
+ if (!original) return null;
3270
+ var at = Number(data.completed_at || data.finished || data.linked_at);
3271
+ return {
3272
+ original,
3273
+ claim: typeof data.alias_claim === "string" && data.alias_claim ? data.alias_claim : void 0,
3274
+ linkedAt: isFinite(at) && at > 0 ? at : void 0,
3275
+ group: data.copy_group !== void 0 ? data.copy_group : void 0,
3276
+ owner: typeof data.copy_owner === "string" ? data.copy_owner : void 0,
3277
+ contentKey: typeof data.content_key === "string" && data.content_key ? data.content_key : void 0
3278
+ };
3279
+ }
3280
+ function fileNameOf(path) {
3281
+ var s = String(path || "");
3282
+ var at = s.lastIndexOf("/");
3283
+ return at === -1 ? s : s.slice(at + 1);
3284
+ }
3285
+ function copyStatusOf(marker, original, liveClaims) {
3286
+ var name = fileNameOf(marker.original);
3287
+ var mk = function(kind, label, title, broken) {
3288
+ return { kind, original: marker.original, label, title, broken };
3289
+ };
3290
+ var o = original || {};
3291
+ var claimGone = !!(liveClaims && marker.claim && !liveClaims.has(marker.claim));
3292
+ if (o.done && o.contentKey && marker.contentKey && o.contentKey !== marker.contentKey && o.run !== "working") {
3293
+ return mk(
3294
+ "original_removed",
3295
+ "Original removed or failed",
3296
+ 'Linked to "' + name + '", which now holds other content. Reindex this file to index it on its own.',
3297
+ true
3298
+ );
3299
+ }
3300
+ if (claimGone && !(o.run === "working")) {
3301
+ return mk(
3302
+ "original_removed",
3303
+ "Original removed or failed",
3304
+ 'Linked to "' + name + '", which is no longer indexed. Reindex this file to index it on its own.',
3305
+ true
3306
+ );
3307
+ }
3308
+ if (o.run === "error" || o.run === "cancelled") {
3309
+ return mk(
3310
+ "original_failed",
3311
+ "Original removed or failed",
3312
+ 'Linked to "' + name + '", whose indexing did not finish. Reindex this file to index it on its own.',
3313
+ true
3314
+ );
3315
+ }
3316
+ if (o.run === "working" && !o.done) {
3317
+ return mk(
3318
+ "waiting",
3319
+ "Waiting for " + name,
3320
+ 'Same content as "' + name + '", which is still being indexed. This file shares its index when it finishes.',
3321
+ false
3322
+ );
3323
+ }
3324
+ if (!o.done && o.run !== "done" && liveClaims && !marker.claim) {
3325
+ return mk(
3326
+ "original_removed",
3327
+ "Original removed or failed",
3328
+ 'Linked to "' + name + '", which is no longer indexed. Reindex this file to index it on its own.',
3329
+ true
3330
+ );
3331
+ }
3332
+ return mk(
3333
+ "linked",
3334
+ "Indexed via " + name,
3335
+ 'Same content as "' + name + '"; search and totals count it once.',
3336
+ false
3337
+ );
3338
+ }
3339
+ function copyCountLabel(n) {
3340
+ return n === 1 ? "1 copy" : n + " copies";
3341
+ }
3342
+ function copyCountTitle(copies) {
3343
+ var list = copies.slice(0, 10).map(function(p) {
3344
+ return "/" + p;
3345
+ }).join("\n");
3346
+ var more = copies.length > 10 ? "\n...and " + (copies.length - 10) + " more" : "";
3347
+ return "The same content is also stored as:\n" + list + more + "\nThey share this file's index; search and totals count it once.";
3348
+ }
3349
+ function copiesByOriginal(linked) {
3350
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3351
+ return [k, linked[k]];
3352
+ });
3353
+ entries.sort(function(a, b) {
3354
+ return (a[1].linkedAt || 0) - (b[1].linkedAt || 0) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3355
+ });
3356
+ var out = /* @__PURE__ */ new Map();
3357
+ for (var i = 0; i < entries.length; i++) {
3358
+ var o = entries[i][1].original;
3359
+ if (!out.has(o)) out.set(o, []);
3360
+ out.get(o).push(entries[i][0]);
3361
+ }
3362
+ return out;
3363
+ }
3364
+ function formatLinkDuration(ms) {
3365
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 0) return "";
3366
+ if (ms < 1e4) return (Math.max(ms, 100) / 1e3).toFixed(1) + " s";
3367
+ return formatIndexDuration(ms);
3368
+ }
3369
+ function linkedRowLabel(original, ms) {
3370
+ var took = formatLinkDuration(ms);
3371
+ return "Same content as " + fileNameOf(original) + ": linked" + (took ? " in " + took : "") + ", no AI used";
3372
+ }
3373
+ function parseLinkedReply(text) {
3374
+ if (typeof text !== "string" || text.indexOf('[skapi] Same content as "') === -1) return null;
3375
+ var m = /\[skapi\] Same content as "([^"]+)": linked to its index(?: in ([0-9]+(?:\.[0-9]+)?) s)?/.exec(text);
3376
+ if (!m) return null;
3377
+ var secs = m[2] !== void 0 ? Number(m[2]) : NaN;
3378
+ return { original: m[1], ms: isFinite(secs) ? Math.round(secs * 1e3) : void 0 };
3379
+ }
3380
+ function promotableCopies(linked, actor) {
3381
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3382
+ return [k, linked[k]];
3383
+ });
3384
+ var out = /* @__PURE__ */ new Map();
3385
+ for (var i = 0; i < entries.length; i++) {
3386
+ var m = entries[i][1];
3387
+ if (actor.isProjectOwner || !!actor.userId && !!m && m.owner === actor.userId) out.set(entries[i][0], m);
3388
+ }
3389
+ return out;
3390
+ }
3391
+ function copiesToPromote(linked, removed, removedFolders, actor) {
3392
+ if (actor) linked = promotableCopies(linked, actor);
3393
+ var gone = new Set(removed || []);
3394
+ var folders = (removedFolders || []).filter(Boolean).map(function(f) {
3395
+ return f.replace(/\/+$/, "") + "/";
3396
+ });
3397
+ var isGone = function(p) {
3398
+ if (gone.has(p)) return true;
3399
+ for (var i = 0; i < folders.length; i++) if (p.indexOf(folders[i]) === 0) return true;
3400
+ return false;
3401
+ };
3402
+ var out = [];
3403
+ copiesByOriginal(linked).forEach(function(copies, original) {
3404
+ if (!isGone(original)) return;
3405
+ var keep = copies.filter(function(c) {
3406
+ return !isGone(c);
3407
+ });
3408
+ if (keep.length) out.push({ original, copies: keep });
3409
+ });
3410
+ return out;
3411
+ }
3412
+ function listOf(res) {
3413
+ return res && Array.isArray(res.list) ? res.list : [];
3414
+ }
3415
+ async function listContentClaims(skapi, service, maxPages = 5) {
3416
+ if (!skapi || typeof skapi.getUniqueId !== "function" || !service) return null;
3417
+ try {
3418
+ var out = /* @__PURE__ */ new Set();
3419
+ var fetchMore = false;
3420
+ for (var page = 0; page < maxPages; page++) {
3421
+ var res = await skapi.getUniqueId(
3422
+ { service, unique_id: CONTENT_CLAIM_PREFIX, condition: "gte" },
3423
+ { limit: 1e3, fetchMore }
3424
+ );
3425
+ var list = listOf(res);
3426
+ for (var i = 0; i < list.length; i++) {
3427
+ var id = typeof list[i] === "string" ? list[i] : list[i] && list[i].unique_id;
3428
+ if (typeof id === "string" && id.indexOf(CONTENT_CLAIM_PREFIX) === 0) out.add(id);
3429
+ }
3430
+ if (!res || res.endOfList !== false) return out;
3431
+ fetchMore = true;
3432
+ }
3433
+ return null;
3434
+ } catch (err) {
3435
+ var msg = String(err && (err.code || err.message) || err || "");
3436
+ if (/NOT_EXISTS|not exist/i.test(msg)) return /* @__PURE__ */ new Set();
3437
+ return null;
3438
+ }
3439
+ }
3440
+ async function listLinkedCopies(skapi, service, maxPages = 10) {
3441
+ if (!skapi || typeof skapi.getRecords !== "function" || !service) return null;
3442
+ var out = /* @__PURE__ */ new Map();
3443
+ try {
3444
+ var fetchMore = false;
3445
+ for (var page = 0; page < maxPages; page++) {
3446
+ var res = await skapi.getRecords(
3447
+ { service, table: { name: "__INDEXING__", access_group: "authorized" }, tag: LINKED_COPY_TAG },
3448
+ { limit: 1e3, fetchMore }
3449
+ );
3450
+ var list = listOf(res);
3451
+ for (var i = 0; i < list.length; i++) {
3452
+ var r = list[i] || {};
3453
+ var uid = String(r.unique_id || "");
3454
+ if (uid.indexOf("done::") !== 0) continue;
3455
+ var mk = linkedMarkerOf(r.data);
3456
+ if (mk) out.set(uid.slice(6), mk);
3457
+ }
3458
+ if (!res || res.endOfList !== false) return out;
3459
+ fetchMore = true;
3460
+ }
3461
+ return out;
3462
+ } catch (err) {
3463
+ var msg = String(err && (err.code || err.message) || err || "");
3464
+ if (/NOT_EXISTS|not exist/i.test(msg)) return out;
3465
+ return null;
3466
+ }
3467
+ }
3468
+ function bodyOf(res) {
3469
+ if (typeof res === "string") {
3470
+ try {
3471
+ return JSON.parse(res);
3472
+ } catch (_) {
3473
+ return res;
3474
+ }
3475
+ }
3476
+ return res;
3477
+ }
3478
+ function errorText(err) {
3479
+ var b = err && (err.body || err.data || err.response);
3480
+ var bb = bodyOf(b);
3481
+ if (bb && typeof bb === "object") {
3482
+ if (typeof bb.reason === "string") return bb.reason;
3483
+ if (typeof bb.message === "string") return bb.message;
3484
+ }
3485
+ if (typeof bb === "string" && bb) return bb;
3486
+ return String(err && err.message || err || "The request failed.");
3487
+ }
3488
+ async function callMcpRoute(route, args, data) {
3489
+ var base = String(chatEngineConfig().mcpBaseUrl || "").replace(/\/+$/, "");
3490
+ if (!base) throw new Error("No BunnyQuery server is configured.");
3491
+ var res = await resolveForwardRequest()({
3492
+ service: args.service,
3493
+ ...args.owner ? { owner: args.owner } : {},
3494
+ url: base + route,
3495
+ method: "POST",
3496
+ headers: { "content-type": "application/json", Authorization: "Bearer $ACCESS_TOKEN" },
3497
+ data: Object.assign({ project_id: args.service }, data)
3498
+ });
3499
+ return bodyOf(res);
3500
+ }
3501
+ async function findIdenticalFiles(args) {
3502
+ var calls = Math.max(1, args.maxCalls || 12);
3503
+ var last = null;
3504
+ for (var i = 0; i < calls; i++) {
3505
+ var body;
3506
+ try {
3507
+ body = await callMcpRoute("/internal/identical-files", args, { budget_s: args.budgetS || 8 });
3508
+ } catch (err) {
3509
+ var msg = errorText(err);
3510
+ if (/timed? ?out|timeout|504/i.test(msg) && i < calls - 1) continue;
3511
+ throw new Error(msg);
3512
+ }
3513
+ if (!body || typeof body !== "object" || !Array.isArray(body.groups)) {
3514
+ throw new Error(typeof body === "string" && body ? body : "The server did not answer the scan.");
3515
+ }
3516
+ last = { complete: !!body.complete, scanned: Number(body.scanned) || 0, total: Number(body.total) || 0, groups: body.groups, skipped: body.skipped };
3517
+ if (args.onProgress) args.onProgress(last);
3518
+ if (last.complete) return last;
3519
+ }
3520
+ return last;
3521
+ }
3522
+ async function linkIdenticalFile(args) {
3523
+ var last = "";
3524
+ for (var attempt = 0; attempt < 4; attempt++) {
3525
+ try {
3526
+ var body = await callMcpRoute("/internal/identical-link", args, { copy: args.copy, original: args.original });
3527
+ if (body && typeof body === "object" && typeof body.linked === "boolean") return body;
3528
+ return { linked: false, reason: typeof body === "string" && body ? body : "unexpected answer" };
3529
+ } catch (err) {
3530
+ last = errorText(err);
3531
+ if (!/timed? ?out|timeout|504/i.test(last)) return { linked: false, reason: last };
3532
+ await new Promise(function(r) {
3533
+ setTimeout(r, 8e3);
3534
+ });
3535
+ }
3536
+ }
3537
+ return { linked: false, reason: last || "timed out" };
3538
+ }
3539
+ function identicalLinkReasonText(reason) {
3540
+ switch (reason) {
3541
+ case "not_identical":
3542
+ return "the two files no longer have the same content";
3543
+ case "original_not_indexed":
3544
+ return "the original is not indexed";
3545
+ case "original_is_a_copy":
3546
+ return "the original is itself a linked copy";
3547
+ case "less_open_original":
3548
+ return "the original can be read by fewer people than the copy";
3549
+ case "private_original":
3550
+ return "the original is private";
3551
+ case "private_copy":
3552
+ return "the copy is another user's private file: it shares the index once that user indexes it again";
3553
+ case "content_claimed_by_another_file":
3554
+ return "another file already holds this content's index";
3555
+ case "not_readable":
3556
+ return "one of the files could not be read from storage";
3557
+ case "different_kind":
3558
+ return "the files are of different kinds";
3559
+ case "no_file_record":
3560
+ return "one of the files has no index record";
3561
+ case "unshared_access_group":
3562
+ return "the file's access group cannot share an index";
3563
+ default:
3564
+ return reason || "refused";
3565
+ }
3566
+ }
3567
+
3224
3568
  // src/engine/indexing_groups.ts
3225
3569
  function canonIndexKey(s) {
3226
3570
  return typeof s === "string" && s ? s.trim() : "";
@@ -3299,6 +3643,50 @@ function overlayRunRecordVerdict(grp, rec, liveIndexKeys) {
3299
3643
  grp.resolving = false;
3300
3644
  grp.resolvingReason = void 0;
3301
3645
  }
3646
+ function runRecordDurationMs(rec) {
3647
+ if (!rec || rec.status !== "done") return void 0;
3648
+ var a = rec.started;
3649
+ var b = rec.finished;
3650
+ if (typeof a !== "number" || typeof b !== "number" || !isFinite(a) || !isFinite(b) || b < a) return void 0;
3651
+ return b - a;
3652
+ }
3653
+ var RUN_DURATION_CLOCK_SLACK_MS = 6e4;
3654
+ var RUN_DURATION_SERVER_SLACK_MS = 5e3;
3655
+ function runRecordGroupDurationMs(grp, rec) {
3656
+ if (rec.status !== "done" || !grp.members.length) return void 0;
3657
+ var fin = rec.finished;
3658
+ if (typeof fin !== "number" || !isFinite(fin)) return void 0;
3659
+ var firstTs = messageTimeMs(grp.members[0].msg);
3660
+ var lastTs = messageTimeMs(grp.members[grp.members.length - 1].msg);
3661
+ if (!firstTs || !lastTs) return void 0;
3662
+ if (fin < firstTs || fin < lastTs - RUN_DURATION_SERVER_SLACK_MS) return void 0;
3663
+ var firstPassTs = 0;
3664
+ for (var i = 0; i < grp.members.length; i++) {
3665
+ var m = grp.members[i].msg;
3666
+ if (m.role !== "user") continue;
3667
+ var ref = readFileRef(m);
3668
+ if (ref && !ref.continued) firstPassTs = messageTimeMs(m);
3669
+ break;
3670
+ }
3671
+ var st = typeof rec.started === "number" && isFinite(rec.started) ? rec.started : void 0;
3672
+ var start;
3673
+ if (st !== void 0 && st > firstTs + RUN_DURATION_CLOCK_SLACK_MS) return void 0;
3674
+ if (firstPassTs) {
3675
+ start = st !== void 0 && st >= firstPassTs - RUN_DURATION_CLOCK_SLACK_MS ? st : firstPassTs;
3676
+ } else {
3677
+ if (st === void 0) return void 0;
3678
+ start = st;
3679
+ }
3680
+ return fin >= start ? fin - start : void 0;
3681
+ }
3682
+ function indexGroupDurationLabel(group) {
3683
+ if (!group || group.status !== "done" || !group.finished || group.resolving || group.queued) return "";
3684
+ return formatIndexDuration(group.durationMs);
3685
+ }
3686
+ function indexGroupLinkedLabel(group) {
3687
+ if (!group || !group.linked || group.status !== "done") return "";
3688
+ return linkedRowLabel(group.linked.original, group.linked.ms);
3689
+ }
3302
3690
  function buildChatDisplayList(messages, opts) {
3303
3691
  var list = Array.isArray(messages) ? messages : [];
3304
3692
  var liveIndexKeys = opts && opts.liveIndexKeys || {};
@@ -3494,6 +3882,14 @@ function buildChatDisplayList(messages, opts) {
3494
3882
  var vm = grp.members[vi];
3495
3883
  if (vm.msg._indexComplete) sawComplete = true;
3496
3884
  if (!isHiddenPass(vm.msg)) grp.visibleMembers.push(vm);
3885
+ if (vm.msg.role === "assistant" && !vm.msg.isError && !grp.linked) {
3886
+ var linkedReply = parseLinkedReply(vm.msg.content);
3887
+ if (linkedReply) grp.linked = linkedReply;
3888
+ }
3889
+ }
3890
+ if (grp.linked && grp.status !== "active" && grp.status !== "cancelled") {
3891
+ grp.status = "done";
3892
+ sawComplete = true;
3497
3893
  }
3498
3894
  grp.driver = !isPagedReadFile(grp.name, grp.mime) ? "single" : isImageVisionFile(grp.name, grp.mime) ? "worker" : windowedIndexing ? "worker" : "client";
3499
3895
  if (grp.status === "active") {
@@ -3505,7 +3901,7 @@ function buildChatDisplayList(messages, opts) {
3505
3901
  } else if (grp.driver === "client") {
3506
3902
  grp.finished = sawComplete || grp.status === "error" || grp.passCount >= MAX_INDEXING_RESUME_PASSES;
3507
3903
  } else {
3508
- grp.finished = !newestRunOfKey[order[oi]] || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3904
+ grp.finished = !newestRunOfKey[order[oi]] || !!grp.linked || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3509
3905
  }
3510
3906
  if (grp.status !== "done") {
3511
3907
  grp.resolving = false;
@@ -3654,7 +4050,10 @@ function buildChatDisplayList(messages, opts) {
3654
4050
  resolvingReason: reason,
3655
4051
  stub: true,
3656
4052
  queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3657
- stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0)
4053
+ stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0),
4054
+ // The stub IS the record, so a 'done' record's span is this run's.
4055
+ durationMs: st === "done" ? runRecordDurationMs(rec) : void 0,
4056
+ linked: st === "done" && rec.linked && rec.alias_of ? { original: rec.alias_of, ms: typeof rec.link_ms === "number" ? rec.link_ms : void 0 } : void 0
3658
4057
  };
3659
4058
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
3660
4059
  }
@@ -3673,6 +4072,10 @@ function buildChatDisplayList(messages, opts) {
3673
4072
  tg.runKey = "run:" + (tg.path || tg.key) + "#" + trec.started;
3674
4073
  stubList.push({ started: trec.started, group: tg });
3675
4074
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
4075
+ tg.durationMs = runRecordGroupDurationMs(tg, trec);
4076
+ if (trec.linked && trec.alias_of && trec.status === "done") {
4077
+ tg.linked = { original: trec.alias_of, ms: tg.linked && tg.linked.ms !== void 0 ? tg.linked.ms : typeof trec.link_ms === "number" ? trec.link_ms : void 0 };
4078
+ }
3676
4079
  }
3677
4080
  }
3678
4081
  stubList.sort(function(a, b) {
@@ -3714,7 +4117,7 @@ function isDuplicateCandidateId(uniqueId, name) {
3714
4117
  const tail = "/" + name;
3715
4118
  return uniqueId.length > SRC_PREFIX2.length + tail.length && uniqueId.slice(-tail.length) === tail;
3716
4119
  }
3717
- function listOf(res) {
4120
+ function listOf2(res) {
3718
4121
  if (!res) return [];
3719
4122
  if (Array.isArray(res)) return res;
3720
4123
  return Array.isArray(res.list) ? res.list : [];
@@ -3731,14 +4134,14 @@ function nfc(text) {
3731
4134
  async function storedCopyIndexing(skapi, storagePath, service) {
3732
4135
  const doneId = "done::" + storagePath;
3733
4136
  try {
3734
- const done = listOf(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
4137
+ const done = listOf2(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
3735
4138
  if (done.some(function(it) {
3736
4139
  return (it && typeof it === "object" ? it.unique_id : it) === doneId;
3737
4140
  })) return "done";
3738
4141
  } catch {
3739
4142
  }
3740
4143
  try {
3741
- const run = listOf(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
4144
+ const run = listOf2(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
3742
4145
  const data = run && run.data && typeof run.data === "object" ? run.data : null;
3743
4146
  if (data && data.status === "working" && typeof data.started === "number" && Date.now() - data.started < RUN_RECORD_WORKING_STALE_MS) return "running";
3744
4147
  } catch {
@@ -3767,7 +4170,7 @@ async function lookupDuplicate(skapi, file, userId, opts) {
3767
4170
  const size = file && typeof file.size === "number" ? file.size : NaN;
3768
4171
  if (!name || !(size >= 0) || !userId) return null;
3769
4172
  const service = opts && opts.service ? { service: opts.service } : {};
3770
- const found = listOf(await skapi.getUniqueId(
4173
+ const found = listOf2(await skapi.getUniqueId(
3771
4174
  Object.assign({ unique_id: name, condition: "<=" }, service),
3772
4175
  { fetchMore: false, limit: DUPLICATE_LOOKUP_LIMIT }
3773
4176
  ));
@@ -3780,7 +4183,7 @@ async function lookupDuplicate(skapi, file, userId, opts) {
3780
4183
  for (const uniqueId of ids) {
3781
4184
  let record = null;
3782
4185
  try {
3783
- record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
4186
+ record = listOf2(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
3784
4187
  } catch {
3785
4188
  continue;
3786
4189
  }
@@ -4111,6 +4514,22 @@ var IMAGE_PREVIEWS_PER_MESSAGE = 8;
4111
4514
  var INLINE_LINK_GLYPH = "\u2197";
4112
4515
  var INLINE_LINK_UNAVAILABLE_GLYPH = "\u2715";
4113
4516
  var INLINE_LINK_UNAVAILABLE_SUFFIX = " (unavailable)";
4517
+ var FIT_LABEL_TAIL_CHARS = 8;
4518
+ function splitLabelForFit(name) {
4519
+ var chars = Array.from(String(name == null ? "" : name));
4520
+ var dot = -1;
4521
+ for (var i = chars.length - 1; i > 0; i--) {
4522
+ if (chars[i] === ".") {
4523
+ dot = i;
4524
+ break;
4525
+ }
4526
+ if (chars[i] === " " || chars[i] === "/" || chars.length - i > 10) break;
4527
+ }
4528
+ var extStart = dot > 0 && dot < chars.length - 1 ? dot : chars.length;
4529
+ var tailStart = Math.max(0, extStart - FIT_LABEL_TAIL_CHARS);
4530
+ if (tailStart < 4) return { stem: chars.join(""), tail: "" };
4531
+ return { stem: chars.slice(0, tailStart).join(""), tail: chars.slice(tailStart).join("") };
4532
+ }
4114
4533
  function renderInlineLinkHtml(link, opts) {
4115
4534
  var o = opts || {};
4116
4535
  var unavailable = !!o.unavailable;
@@ -4123,7 +4542,16 @@ function renderInlineLinkHtml(link, opts) {
4123
4542
  if (unavailable) cls.push("is-unavailable");
4124
4543
  if (preview) cls.push("is-image-preview");
4125
4544
  var glyphHtml = '<span class="bq-link-glyph" translate="no">' + (unavailable ? INLINE_LINK_UNAVAILABLE_GLYPH : INLINE_LINK_GLYPH) + "</span>";
4126
- var labelHtml = glyphHtml + escapeInlineHtml(link.label + (unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : ""));
4545
+ var stateSuffix = unavailable ? INLINE_LINK_UNAVAILABLE_SUFFIX : refreshing ? " (fetching...)" : "";
4546
+ var fit = !!o.fitLabel && !preview;
4547
+ if (fit) cls.push("bq-link-fit");
4548
+ var labelHtml;
4549
+ if (fit) {
4550
+ var split = splitLabelForFit(full);
4551
+ labelHtml = glyphHtml + '<span class="bq-link-stem">' + escapeInlineHtml(split.stem) + "</span>" + (split.tail ? '<span class="bq-link-tail">' + escapeInlineHtml(split.tail) + "</span>" : "") + (stateSuffix ? '<span class="bq-link-tail">' + escapeInlineHtml(stateSuffix) + "</span>" : "");
4552
+ } else {
4553
+ labelHtml = glyphHtml + escapeInlineHtml(link.label + stateSuffix);
4554
+ }
4127
4555
  var attrs = ['class="' + cls.join(" ") + '"'];
4128
4556
  if (unavailable) attrs.push('aria-disabled="true"', 'data-bq-unavailable="1"');
4129
4557
  else attrs.push('href="' + escapeInlineHtml(link.href) + '"', 'target="_blank"', 'rel="noopener noreferrer"');
@@ -5851,6 +6279,10 @@ function canReportWrongAnswer(msg) {
5851
6279
  var note = retrievalNoteOfAnswer(msg);
5852
6280
  return !!note && !answerUsedNoDataTool(note) && !msg.isCancelled;
5853
6281
  }
6282
+ var UPLOAD_CANCELLED_MESSAGE = "Upload cancelled";
6283
+ function isUploadCancelledError(err) {
6284
+ return !!err && (err.code === "CANCELLED" || err.message === UPLOAD_CANCELLED_MESSAGE);
6285
+ }
5854
6286
  var _ChatSession = class _ChatSession {
5855
6287
  constructor(host) {
5856
6288
  // --- live streaming ----------------------------------------------------
@@ -6272,6 +6704,43 @@ var _ChatSession = class _ChatSession {
6272
6704
  return queued;
6273
6705
  });
6274
6706
  }
6707
+ /**
6708
+ * ONE SHARED INDEX FOR IDENTICAL FILES: the linked copies that lose their original when
6709
+ * `removed` files (or every file under `folders`) go away, per original, oldest first
6710
+ * (identical.ts copiesToPromote). Read through host.findLinkedCopies, fresh, and it has
6711
+ * to be read BEFORE the delete or reset: those remove nothing from the copies' markers,
6712
+ * but a later sweep could no longer tell whose copies they were once a new original
6713
+ * exists. Never rejects; [] without the hook or on any failure.
6714
+ */
6715
+ collectLinkedCopies(removed, folders) {
6716
+ if (typeof this.host.findLinkedCopies !== "function") return Promise.resolve([]);
6717
+ var id = this.host.getIdentity();
6718
+ var actor = { userId: id && !id.anonymous ? id.userId : null, isProjectOwner: !!(id && !id.anonymous && id.owner && id.userId === id.owner) };
6719
+ return Promise.resolve(this.host.findLinkedCopies()).then(function(map) {
6720
+ return map ? copiesToPromote(map, removed || [], folders, actor) : [];
6721
+ }).catch(function() {
6722
+ return [];
6723
+ });
6724
+ }
6725
+ /**
6726
+ * Send the copies of a removed or overwritten original again (owner decision
6727
+ * 2026-11-26): each list's oldest copy first, so its first pass claims the content and
6728
+ * is indexed for real (one AI run), then the others, which link to it with no AI call.
6729
+ * The share flag rides on every first pass while the project's switch is on (requests.ts
6730
+ * notifyAgentSaveAttachment). Through reindexStoredFiles, so each copy keeps its access
6731
+ * group and shows as a "Reindexing" row. Resolves to the number of files queued.
6732
+ */
6733
+ promoteLinkedCopies(plan) {
6734
+ var list = [];
6735
+ (plan || []).forEach(function(g) {
6736
+ (g && g.copies || []).forEach(function(c) {
6737
+ if (c) list.push({ storagePath: c });
6738
+ });
6739
+ });
6740
+ if (!list.length) return Promise.resolve(0);
6741
+ console.log("[chat-engine] identical files: sending " + list.length + " linked cop" + (list.length === 1 ? "y" : "ies") + " again, their original is gone:", plan);
6742
+ return this.reindexStoredFiles(list);
6743
+ }
6275
6744
  /**
6276
6745
  * The same question, asked of the SERVER when this page cannot answer it.
6277
6746
  *
@@ -13016,6 +13485,29 @@ var _ChatSession = class _ChatSession {
13016
13485
  });
13017
13486
  }
13018
13487
  // --- attachment upload orchestration ---------------------------------
13488
+ /**
13489
+ * The user cancelled this chip's upload (the widget's per-chip x or "Cancel all
13490
+ * uploads"). Stops the bytes now when they are moving (the host's abort), and
13491
+ * leaves a flag every later step of uploadSingleAttachment checks, so a cancel
13492
+ * that lands between steps (the get-signed-url round trip before the bytes, or
13493
+ * the src:: record and the indexing request after them) still stops the file
13494
+ * from being indexed and from being attached to the chat turn. A member whose
13495
+ * indexing request has already gone out is past cancelling: it shows as an
13496
+ * indexing row with its own Stop. Returns false for a chip that is not being
13497
+ * uploaded by this session any more.
13498
+ */
13499
+ cancelAttachmentUpload(att) {
13500
+ if (!att || att._cancelled) return false;
13501
+ if (att.status !== "uploading" && !att._batchId) return false;
13502
+ att._cancelled = true;
13503
+ if (typeof att._abort === "function") {
13504
+ try {
13505
+ att._abort();
13506
+ } catch (e) {
13507
+ }
13508
+ }
13509
+ return true;
13510
+ }
13019
13511
  // Upload one attachment (a file = 1 member, a folder = N) to db storage and
13020
13512
  // queue indexing per member. The bytes I/O + chip rendering go through host
13021
13513
  // hooks; the overwrite/reindex flow, status lifecycle, and indexing live here.
@@ -13038,6 +13530,18 @@ var _ChatSession = class _ChatSession {
13038
13530
  var anyIndexFailed = false;
13039
13531
  var reusedCount = 0;
13040
13532
  att.reused = false;
13533
+ att._storedCount = 0;
13534
+ att._indexQueuedCount = 0;
13535
+ att._indexQueued = false;
13536
+ att._landedNew = [];
13537
+ var cancelError = function() {
13538
+ var e = new Error(UPLOAD_CANCELLED_MESSAGE);
13539
+ e.code = "CANCELLED";
13540
+ return e;
13541
+ };
13542
+ var checkCancel = function() {
13543
+ if (att._cancelled) throw cancelError();
13544
+ };
13041
13545
  delete att.duplicates;
13042
13546
  var chain = Promise.resolve();
13043
13547
  var findDuplicate = function(member) {
@@ -13054,25 +13558,54 @@ var _ChatSession = class _ChatSession {
13054
13558
  };
13055
13559
  members.forEach(function(member, idx) {
13056
13560
  chain = chain.then(function() {
13561
+ checkCancel();
13057
13562
  var hadExists = false;
13058
13563
  var skipped = false;
13564
+ var promotion = null;
13059
13565
  var duplicateOf = null;
13060
13566
  var existedBefore = false;
13567
+ var madeRecord = false;
13568
+ var sentAll = false;
13061
13569
  var onProg = function(p) {
13570
+ if (p && p.total && p.loaded >= p.total) sentAll = true;
13062
13571
  if (p && p.total) {
13063
13572
  att.progress = Math.floor((idx + p.loaded / p.total) / total * 100);
13064
13573
  self.host.renderAttachmentChips();
13065
13574
  }
13066
13575
  };
13067
13576
  var doMemberUpload = function(checkExistence) {
13577
+ checkCancel();
13578
+ sentAll = false;
13068
13579
  return self.host.uploadFile({
13069
13580
  file: member.file,
13070
13581
  storagePath: member.storagePath,
13071
13582
  checkExistence,
13072
13583
  onProgress: onProg,
13584
+ // The host hands its abort over just before the bytes start. A
13585
+ // cancel made during the get-signed-url round trip had nothing to
13586
+ // abort yet, so it is applied here, before anything is sent: a
13587
+ // storage POST that never completes leaves no object behind.
13073
13588
  setAbort: function(abort) {
13074
13589
  att._abort = abort;
13590
+ if (att._cancelled) {
13591
+ try {
13592
+ abort();
13593
+ } catch (e) {
13594
+ }
13595
+ }
13075
13596
  }
13597
+ }).then(function(r) {
13598
+ att._abort = null;
13599
+ att._storedCount = (att._storedCount || 0) + 1;
13600
+ if (checkExistence) att._landedNew.push(member.storagePath);
13601
+ return r;
13602
+ }, function(err) {
13603
+ att._abort = null;
13604
+ if (att._cancelled) {
13605
+ if (checkExistence && sentAll) att._landedNew.push(member.storagePath);
13606
+ throw cancelError();
13607
+ }
13608
+ throw err;
13076
13609
  });
13077
13610
  };
13078
13611
  if (isIndexRetry) {
@@ -13095,6 +13628,7 @@ var _ChatSession = class _ChatSession {
13095
13628
  return self.host.promptOverwrite(member.file.name).then(function(choice) {
13096
13629
  if (choice === "overwrite") {
13097
13630
  existedBefore = true;
13631
+ promotion = self.collectLinkedCopies([member.storagePath]);
13098
13632
  markImagePreviewStale(self.host.getIdentity().projectId || "default", member.storagePath);
13099
13633
  return doMemberUpload(false);
13100
13634
  }
@@ -13106,12 +13640,14 @@ var _ChatSession = class _ChatSession {
13106
13640
  existedBefore = true;
13107
13641
  });
13108
13642
  }).then(function() {
13643
+ checkCancel();
13109
13644
  if (skipped) return;
13110
13645
  return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
13111
13646
  var ecode = err && (err.code || err.body && err.body.code);
13112
13647
  var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
13113
13648
  var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
13114
13649
  if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
13650
+ madeRecord = !existedBefore;
13115
13651
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13116
13652
  name: member.file.name,
13117
13653
  mime: member.file.type || self.host.getMimeType(member.file.name),
@@ -13121,6 +13657,13 @@ var _ChatSession = class _ChatSession {
13121
13657
  });
13122
13658
  });
13123
13659
  }).then(function(url) {
13660
+ if (att._cancelled) {
13661
+ var dropEarly = madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13662
+ }) : Promise.resolve();
13663
+ return dropEarly.then(function() {
13664
+ throw cancelError();
13665
+ });
13666
+ }
13124
13667
  if (skipped) return;
13125
13668
  if (duplicateOf) {
13126
13669
  urls.push({ name: member.relPath, url, storagePath: duplicateOf });
@@ -13149,13 +13692,14 @@ var _ChatSession = class _ChatSession {
13149
13692
  var mime = member.file.type || self.host.getMimeType(member.file.name);
13150
13693
  var alreadyIndexing = false;
13151
13694
  var existingGroup = null;
13695
+ var clearedOld = false;
13152
13696
  var preIndex = self.claimIndexRun(member.storagePath).then(function(claimed) {
13153
13697
  alreadyIndexing = !claimed;
13154
13698
  if (alreadyIndexing) {
13155
13699
  console.log("[chat-engine] skipping a duplicate index request for", member.storagePath);
13156
13700
  return;
13157
13701
  }
13158
- if (!existedBefore) return;
13702
+ if (!existedBefore || att._cancelled) return;
13159
13703
  var readGroup = typeof self.host.readFileAccessGroup === "function" ? Promise.resolve(self.host.readFileAccessGroup(member.storagePath)).then(function(g) {
13160
13704
  existingGroup = g || null;
13161
13705
  }, function(err) {
@@ -13163,7 +13707,9 @@ var _ChatSession = class _ChatSession {
13163
13707
  throw err;
13164
13708
  }) : Promise.resolve();
13165
13709
  return readGroup.then(function() {
13710
+ if (att._cancelled) return;
13166
13711
  if (typeof self.host.deleteExistingFileRecord === "function") {
13712
+ clearedOld = true;
13167
13713
  return Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13168
13714
  });
13169
13715
  }
@@ -13171,7 +13717,9 @@ var _ChatSession = class _ChatSession {
13171
13717
  });
13172
13718
  preIndex = preIndex.then(function() {
13173
13719
  if (alreadyIndexing) return;
13720
+ if (att._cancelled && !clearedOld) return;
13174
13721
  if (typeof self.host.ensureFileIndexRecord !== "function") return;
13722
+ if (!existedBefore) madeRecord = true;
13175
13723
  return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
13176
13724
  name: member.file.name,
13177
13725
  mime: mime || void 0,
@@ -13192,10 +13740,31 @@ var _ChatSession = class _ChatSession {
13192
13740
  }).catch(function() {
13193
13741
  });
13194
13742
  });
13743
+ var abandonIfCancelled = function() {
13744
+ if (!att._cancelled) return;
13745
+ if (!alreadyIndexing) self.releaseIndexRun(member.storagePath);
13746
+ var drop = !existedBefore && !alreadyIndexing && madeRecord && typeof self.host.deleteExistingFileRecord === "function" ? Promise.resolve(self.host.deleteExistingFileRecord(member.storagePath)).catch(function() {
13747
+ }) : Promise.resolve();
13748
+ return drop.then(function() {
13749
+ throw cancelError();
13750
+ });
13751
+ };
13195
13752
  return preIndex.then(function() {
13753
+ return abandonIfCancelled();
13754
+ }).then(function() {
13196
13755
  return parseAttachmentContent(member.file, member.file.name, mime || void 0);
13756
+ }).then(function(parsedContent) {
13757
+ return Promise.resolve(abandonIfCancelled()).then(function() {
13758
+ return parsedContent;
13759
+ });
13197
13760
  }).then(function(parsedContent) {
13198
13761
  if (alreadyIndexing) return;
13762
+ att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
13763
+ if (att.kind !== "folder") att._indexQueued = true;
13764
+ att._landedNew = (att._landedNew || []).filter(function(p) {
13765
+ return p !== member.storagePath;
13766
+ });
13767
+ self.host.renderAttachmentChips();
13199
13768
  return self.trackIndexDispatch(notifyAgentSaveAttachment({
13200
13769
  platform: id.platform,
13201
13770
  model: id.model,
@@ -13236,6 +13805,14 @@ var _ChatSession = class _ChatSession {
13236
13805
  });
13237
13806
  self.noteBgQueueChanged();
13238
13807
  self.drainBgTaskQueue();
13808
+ if (promotion) {
13809
+ var plan = promotion;
13810
+ promotion = null;
13811
+ plan.then(function(pl) {
13812
+ return self.promoteLinkedCopies(pl);
13813
+ }).catch(function() {
13814
+ });
13815
+ }
13239
13816
  }
13240
13817
  }, function(e) {
13241
13818
  console.error("[chat-engine] indexing request failed", e);
@@ -13251,6 +13828,7 @@ var _ChatSession = class _ChatSession {
13251
13828
  });
13252
13829
  });
13253
13830
  return chain.then(function() {
13831
+ checkCancel();
13254
13832
  att._abort = null;
13255
13833
  att.progress = 100;
13256
13834
  if (att.kind === "folder") att.uploadedUrls = urls.map(function(u) {
@@ -13311,12 +13889,26 @@ var _ChatSession = class _ChatSession {
13311
13889
  return a.id === att.id;
13312
13890
  });
13313
13891
  var aborted = err && (err.message === "Aborted" || err === "Aborted");
13892
+ if (att._cancelled || isUploadCancelledError(err)) {
13893
+ att.status = "cancelled";
13894
+ att._abort = null;
13895
+ self.host.renderAttachmentChips();
13896
+ if (typeof att._onCancelSettled === "function") {
13897
+ try {
13898
+ att._onCancelSettled((att._landedNew || []).slice());
13899
+ } catch (e) {
13900
+ }
13901
+ }
13902
+ return;
13903
+ }
13314
13904
  if (removed || aborted) return;
13315
13905
  att.status = "error";
13316
13906
  att.errorMessage = "File upload has failed";
13317
13907
  att.errorCode = err && (err.code || err.body && err.body.code) || "";
13318
13908
  att.errorDetail = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
13319
13909
  self.host.renderAttachmentChips();
13910
+ }).then(function() {
13911
+ att._settledBatch = att._batchId || true;
13320
13912
  });
13321
13913
  });
13322
13914
  });
@@ -13343,6 +13935,6 @@ var _ChatSession = class _ChatSession {
13343
13935
  _ChatSession.RUN_PASS_PAGE = 10;
13344
13936
  var ChatSession = _ChatSession;
13345
13937
 
13346
- export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, LOOK_DEADLINE_MS, LOOK_FAST_MS, LOOK_SLOW_MS, LOOK_STALE_MS, LookScheduler, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NOT_SENT_TEXT, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, REQUEST_GONE_TEXT, REQUEST_UNREACHABLE_TEXT, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLiveTextIntoRunningRow, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, crefSupported, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isNotExistsError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isReturnTrigger, isServerExtractable, isServiceDbAttachmentHref, isTransportFailure, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, listedRequestText, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, messageTimeMs, mintCacheBustStamp, needsBomForExt, newClientRef, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, reconcilerReadsEnabled, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, requestIdTimeMs, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, runSettleSideEffect, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, sideEffectDone, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, statusPushEnabled, statusPushLive, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
13938
+ export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTENT_CLAIM_PREFIX, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SHARE_IDENTICAL_FILES, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINKED_COPY_TAG, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, LOOK_DEADLINE_MS, LOOK_FAST_MS, LOOK_SLOW_MS, LOOK_STALE_MS, LookScheduler, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NOT_SENT_TEXT, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, REQUEST_GONE_TEXT, REQUEST_UNREACHABLE_TEXT, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, SHARE_IDENTICAL_FILES_KEY, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, UPLOAD_CANCELLED_MESSAGE, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLiveTextIntoRunningRow, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, copiesByOriginal, copiesToPromote, copyCountLabel, copyCountTitle, copyStatusOf, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, crefSupported, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fileNameOf, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, findIdenticalFiles, formatChatTimestamp, formatDuration, formatIndexDuration, formatLinkDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, identicalLinkReasonText, indexDoneUniqueId, indexGroupDurationLabel, indexGroupLinkedLabel, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isNotExistsError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isReturnTrigger, isServerExtractable, isServiceDbAttachmentHref, isTransportFailure, isUploadCancelledError, isWindowedReadFile, linkIdenticalFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, linkedMarkerOf, linkedRowLabel, listClaudeModels, listContentClaims, listLinkedCopies, listOpenAIModels, listedRequestText, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, messageTimeMs, mintCacheBustStamp, needsBomForExt, newClientRef, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeShareIdenticalFiles, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, parseLinkedReply, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectShareIdenticalFiles, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, promotableCopies, providerBodyWasRead, providerDocument, readExpiredAttachmentHref, readyProjectSettings, reconcilerReadsEnabled, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, requestIdTimeMs, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, runRecordDurationMs, runSettleSideEffect, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shareIdenticalFilesFrom, shouldRescueInFlightMessage, sideEffectDone, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, splitLabelForFit, statusPushEnabled, statusPushLive, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
13347
13939
  //# sourceMappingURL=engine.mjs.map
13348
13940
  //# sourceMappingURL=engine.mjs.map