bunnyquery 1.21.7 → 1.21.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bunnyquery.js CHANGED
@@ -68,6 +68,13 @@
68
68
  function skipDuplicateFilesFrom(data) {
69
69
  return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
70
70
  }
71
+ var DEFAULT_SHARE_IDENTICAL_FILES = true;
72
+ function normalizeShareIdenticalFiles(value) {
73
+ return value !== false;
74
+ }
75
+ function shareIdenticalFilesFrom(data) {
76
+ return data ? normalizeShareIdenticalFiles(data.share_identical_files) : DEFAULT_SHARE_IDENTICAL_FILES;
77
+ }
71
78
  var DEFAULT_ANSWER_MODE = "standard";
72
79
  function normalizeAnswerMode(value) {
73
80
  return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
@@ -151,6 +158,9 @@
151
158
  function projectChatGreeting(service) {
152
159
  return chatGreetingFrom(cachedProjectSettings(service));
153
160
  }
161
+ function projectShareIdenticalFiles(service) {
162
+ return shareIdenticalFilesFrom(cachedProjectSettings(service));
163
+ }
154
164
 
155
165
  // src/engine/config.ts
156
166
  var _config = null;
@@ -998,8 +1008,9 @@ Extracted content of attached office files (read inline below; do NOT fetch thei
998
1008
  const indexGroupLiteral = typeof g === "number" ? String(g) : g === "public" || g === "private" || g === "authorized" || g === "admin" ? `"${g}"` : '"authorized"';
999
1009
  const reindexHint = canUpload === false ? `asking the project's owner to re-index that file` : `re-indexing that file (attach the same file again and choose to reindex it)`;
1000
1010
  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.
1001
- 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`}.
1002
- 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 when the value could be in a table), keep the answer short: 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.
1011
+ FILES IN ANOTHER LANGUAGE. The files may be written in another language than the question (a Russian or English manual asked about in Korean). When searches in the question's language find nothing, or searchText reports query_language_mismatch, search again with the question's key terms translated into the language the files are written in (their names, titles and earlier hits show it): one or two short queries of the main terms (e.g. "oil leak", "gearbox"), before concluding anything.
1012
+ WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rules require (in the files' language too) 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`}.
1013
+ A CODE, NUMBER OR EXACT QUOTE THAT searchText DID NOT FIND (an identifier or a quote, not a topic or how-to question, which follows FILES IN ANOTHER LANGUAGE first): 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.
1003
1014
  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.
1004
1015
  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.`;
1005
1016
  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.`;
@@ -1018,6 +1029,7 @@ NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and n
1018
1029
  ${documentRules}
1019
1030
  ${accessGroupRule}
1020
1031
  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.
1032
+ 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.
1021
1033
  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.
1022
1034
  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.`}
1023
1035
  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.
@@ -2768,12 +2780,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2768
2780
  const singlePass = !visionFile && !windowedRead && !pagedRead && !continuing;
2769
2781
  const imageFile = singlePass && !parsedContent && !serverExtract ? indexingImageFile(attachment) : void 0;
2770
2782
  const fileUrlDetail = imageFile && platform === "openai" ? getOpenAIImageDetail(info.model || DEFAULT_OPENAI_MODEL) : void 0;
2783
+ const shareIdentical = !continuing && info.shareIdentical !== false && (info.shareIdentical === true || projectShareIdenticalFiles(service));
2771
2784
  const skapiFileUrls = attachment.url && attachment.storagePath ? {
2772
2785
  _skapi_file_urls: [{
2773
2786
  path: attachment.storagePath,
2774
2787
  url: attachment.url,
2775
2788
  ...singlePass ? { index_end: true } : {},
2776
- ...fileUrlDetail ? { detail: fileUrlDetail } : {}
2789
+ ...fileUrlDetail ? { detail: fileUrlDetail } : {},
2790
+ ...shareIdentical ? { share_identical: true } : {}
2777
2791
  }]
2778
2792
  } : {};
2779
2793
  const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : windowedRead && windowPlaceholder ? buildIndexingWindowMessage(attachment, windowPlaceholder, false) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
@@ -2900,13 +2914,26 @@ Index the REMAINING windows - one record per row/item, looking at any page image
2900
2914
  }
2901
2915
  }));
2902
2916
  }
2917
+ function providerDocument(response) {
2918
+ if (typeof response !== "string") return response;
2919
+ var t = response.trim();
2920
+ if (t.charAt(0) !== "{" || t.charAt(t.length - 1) !== "}") return response;
2921
+ try {
2922
+ var doc = JSON.parse(t);
2923
+ return doc && typeof doc === "object" && !Array.isArray(doc) ? doc : response;
2924
+ } catch (e) {
2925
+ return response;
2926
+ }
2927
+ }
2903
2928
  function extractClaudeText(response) {
2929
+ response = providerDocument(response);
2904
2930
  if (!Array.isArray(response?.content)) {
2905
2931
  return "";
2906
2932
  }
2907
2933
  return response.content.filter((block) => block?.type === "text").map((block) => block.text).join("\n");
2908
2934
  }
2909
2935
  function extractOpenAIText(response) {
2936
+ response = providerDocument(response);
2910
2937
  if (typeof response?.output_text === "string" && response.output_text.length) {
2911
2938
  return response.output_text;
2912
2939
  }
@@ -3083,6 +3110,122 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3083
3110
  return typeof m._ts === "number" && m._ts > 0 ? m._ts : 0;
3084
3111
  }
3085
3112
 
3113
+ // src/engine/identical.ts
3114
+ var LINKED_COPY_TAG = "bq_linked";
3115
+ function linkedMarkerOf(data) {
3116
+ if (!data || typeof data !== "object" || data.linked !== true) return null;
3117
+ var original = typeof data.alias_of === "string" ? data.alias_of : "";
3118
+ if (!original) return null;
3119
+ var at = Number(data.completed_at || data.finished || data.linked_at);
3120
+ return {
3121
+ original,
3122
+ claim: typeof data.alias_claim === "string" && data.alias_claim ? data.alias_claim : void 0,
3123
+ linkedAt: isFinite(at) && at > 0 ? at : void 0,
3124
+ group: data.copy_group !== void 0 ? data.copy_group : void 0,
3125
+ owner: typeof data.copy_owner === "string" ? data.copy_owner : void 0,
3126
+ contentKey: typeof data.content_key === "string" && data.content_key ? data.content_key : void 0
3127
+ };
3128
+ }
3129
+ function fileNameOf(path) {
3130
+ var s = String(path || "");
3131
+ var at = s.lastIndexOf("/");
3132
+ return at === -1 ? s : s.slice(at + 1);
3133
+ }
3134
+ function copiesByOriginal(linked) {
3135
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3136
+ return [k, linked[k]];
3137
+ });
3138
+ entries.sort(function(a, b) {
3139
+ return (a[1].linkedAt || 0) - (b[1].linkedAt || 0) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3140
+ });
3141
+ var out = /* @__PURE__ */ new Map();
3142
+ for (var i = 0; i < entries.length; i++) {
3143
+ var o = entries[i][1].original;
3144
+ if (!out.has(o)) out.set(o, []);
3145
+ out.get(o).push(entries[i][0]);
3146
+ }
3147
+ return out;
3148
+ }
3149
+ function formatLinkDuration(ms) {
3150
+ if (typeof ms !== "number" || !isFinite(ms) || ms < 0) return "";
3151
+ if (ms < 1e4) return (Math.max(ms, 100) / 1e3).toFixed(1) + " s";
3152
+ return formatIndexDuration(ms);
3153
+ }
3154
+ function linkedRowLabel(original, ms) {
3155
+ var took = formatLinkDuration(ms);
3156
+ return "Same content as " + fileNameOf(original) + ": linked" + (took ? " in " + took : "") + ", no AI used";
3157
+ }
3158
+ function parseLinkedReply(text) {
3159
+ if (typeof text !== "string" || text.indexOf('[skapi] Same content as "') === -1) return null;
3160
+ var m = /\[skapi\] Same content as "([^"]+)": linked to its index(?: in ([0-9]+(?:\.[0-9]+)?) s)?/.exec(text);
3161
+ if (!m) return null;
3162
+ var secs = m[2] !== void 0 ? Number(m[2]) : NaN;
3163
+ return { original: m[1], ms: isFinite(secs) ? Math.round(secs * 1e3) : void 0 };
3164
+ }
3165
+ function promotableCopies(linked, actor) {
3166
+ var entries = linked instanceof Map ? Array.from(linked.entries()) : Object.keys(linked).map(function(k) {
3167
+ return [k, linked[k]];
3168
+ });
3169
+ var out = /* @__PURE__ */ new Map();
3170
+ for (var i = 0; i < entries.length; i++) {
3171
+ var m = entries[i][1];
3172
+ if (actor.isProjectOwner || !!actor.userId && !!m && m.owner === actor.userId) out.set(entries[i][0], m);
3173
+ }
3174
+ return out;
3175
+ }
3176
+ function copiesToPromote(linked, removed, removedFolders, actor) {
3177
+ if (actor) linked = promotableCopies(linked, actor);
3178
+ var gone = new Set(removed || []);
3179
+ var folders = (removedFolders || []).filter(Boolean).map(function(f) {
3180
+ return f.replace(/\/+$/, "") + "/";
3181
+ });
3182
+ var isGone = function(p) {
3183
+ if (gone.has(p)) return true;
3184
+ for (var i = 0; i < folders.length; i++) if (p.indexOf(folders[i]) === 0) return true;
3185
+ return false;
3186
+ };
3187
+ var out = [];
3188
+ copiesByOriginal(linked).forEach(function(copies, original) {
3189
+ if (!isGone(original)) return;
3190
+ var keep = copies.filter(function(c) {
3191
+ return !isGone(c);
3192
+ });
3193
+ if (keep.length) out.push({ original, copies: keep });
3194
+ });
3195
+ return out;
3196
+ }
3197
+ function listOf(res) {
3198
+ return res && Array.isArray(res.list) ? res.list : [];
3199
+ }
3200
+ async function listLinkedCopies(skapi, service, maxPages = 10) {
3201
+ if (!skapi || typeof skapi.getRecords !== "function" || !service) return null;
3202
+ var out = /* @__PURE__ */ new Map();
3203
+ try {
3204
+ var fetchMore = false;
3205
+ for (var page = 0; page < maxPages; page++) {
3206
+ var res = await skapi.getRecords(
3207
+ { service, table: { name: "__INDEXING__", access_group: "authorized" }, tag: LINKED_COPY_TAG },
3208
+ { limit: 1e3, fetchMore }
3209
+ );
3210
+ var list = listOf(res);
3211
+ for (var i = 0; i < list.length; i++) {
3212
+ var r = list[i] || {};
3213
+ var uid = String(r.unique_id || "");
3214
+ if (uid.indexOf("done::") !== 0) continue;
3215
+ var mk = linkedMarkerOf(r.data);
3216
+ if (mk) out.set(uid.slice(6), mk);
3217
+ }
3218
+ if (!res || res.endOfList !== false) return out;
3219
+ fetchMore = true;
3220
+ }
3221
+ return out;
3222
+ } catch (err) {
3223
+ var msg = String(err && (err.code || err.message) || err || "");
3224
+ if (/NOT_EXISTS|not exist/i.test(msg)) return out;
3225
+ return null;
3226
+ }
3227
+ }
3228
+
3086
3229
  // src/engine/indexing_groups.ts
3087
3230
  function canonIndexKey(s) {
3088
3231
  return typeof s === "string" && s ? s.trim() : "";
@@ -3201,6 +3344,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3201
3344
  if (!group || group.status !== "done" || !group.finished || group.resolving || group.queued) return "";
3202
3345
  return formatIndexDuration(group.durationMs);
3203
3346
  }
3347
+ function indexGroupLinkedLabel(group) {
3348
+ if (!group || !group.linked || group.status !== "done") return "";
3349
+ return linkedRowLabel(group.linked.original, group.linked.ms);
3350
+ }
3204
3351
  function buildChatDisplayList(messages, opts) {
3205
3352
  var list = Array.isArray(messages) ? messages : [];
3206
3353
  var liveIndexKeys = opts && opts.liveIndexKeys || {};
@@ -3396,6 +3543,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3396
3543
  var vm = grp.members[vi];
3397
3544
  if (vm.msg._indexComplete) sawComplete = true;
3398
3545
  if (!isHiddenPass(vm.msg)) grp.visibleMembers.push(vm);
3546
+ if (vm.msg.role === "assistant" && !vm.msg.isError && !grp.linked) {
3547
+ var linkedReply = parseLinkedReply(vm.msg.content);
3548
+ if (linkedReply) grp.linked = linkedReply;
3549
+ }
3550
+ }
3551
+ if (grp.linked && grp.status !== "active" && grp.status !== "cancelled") {
3552
+ grp.status = "done";
3553
+ sawComplete = true;
3399
3554
  }
3400
3555
  grp.driver = !isPagedReadFile(grp.name, grp.mime) ? "single" : isImageVisionFile(grp.name, grp.mime) ? "worker" : windowedIndexing ? "worker" : "client";
3401
3556
  if (grp.status === "active") {
@@ -3407,7 +3562,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3407
3562
  } else if (grp.driver === "client") {
3408
3563
  grp.finished = sawComplete || grp.status === "error" || grp.passCount >= MAX_INDEXING_RESUME_PASSES;
3409
3564
  } else {
3410
- grp.finished = !newestRunOfKey[order[oi]] || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3565
+ grp.finished = !newestRunOfKey[order[oi]] || !!grp.linked || !!doneKeys[grp.key] && !liveIndexKeys[grp.key] || liveIndexChecked && !liveIndexKeys[grp.key];
3411
3566
  }
3412
3567
  if (grp.status !== "done") {
3413
3568
  grp.resolving = false;
@@ -3558,7 +3713,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3558
3713
  queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
3559
3714
  stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0),
3560
3715
  // The stub IS the record, so a 'done' record's span is this run's.
3561
- durationMs: st === "done" ? runRecordDurationMs(rec) : void 0
3716
+ durationMs: st === "done" ? runRecordDurationMs(rec) : void 0,
3717
+ 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
3562
3718
  };
3563
3719
  stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
3564
3720
  }
@@ -3578,6 +3734,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3578
3734
  stubList.push({ started: trec.started, group: tg });
3579
3735
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
3580
3736
  tg.durationMs = runRecordGroupDurationMs(tg, trec);
3737
+ if (trec.linked && trec.alias_of && trec.status === "done") {
3738
+ 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 };
3739
+ }
3581
3740
  }
3582
3741
  }
3583
3742
  stubList.sort(function(a, b) {
@@ -3619,7 +3778,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3619
3778
  const tail = "/" + name;
3620
3779
  return uniqueId.length > SRC_PREFIX2.length + tail.length && uniqueId.slice(-tail.length) === tail;
3621
3780
  }
3622
- function listOf(res) {
3781
+ function listOf2(res) {
3623
3782
  if (!res) return [];
3624
3783
  if (Array.isArray(res)) return res;
3625
3784
  return Array.isArray(res.list) ? res.list : [];
@@ -3636,14 +3795,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3636
3795
  async function storedCopyIndexing(skapi, storagePath, service) {
3637
3796
  const doneId = "done::" + storagePath;
3638
3797
  try {
3639
- const done = listOf(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
3798
+ const done = listOf2(await skapi.getUniqueId(Object.assign({ unique_id: doneId }, service), { fetchMore: false, limit: 1 }));
3640
3799
  if (done.some(function(it) {
3641
3800
  return (it && typeof it === "object" ? it.unique_id : it) === doneId;
3642
3801
  })) return "done";
3643
3802
  } catch {
3644
3803
  }
3645
3804
  try {
3646
- const run = listOf(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
3805
+ const run = listOf2(await skapi.getRecords(Object.assign({ unique_id: "run::" + storagePath }, service)))[0];
3647
3806
  const data = run && run.data && typeof run.data === "object" ? run.data : null;
3648
3807
  if (data && data.status === "working" && typeof data.started === "number" && Date.now() - data.started < RUN_RECORD_WORKING_STALE_MS) return "running";
3649
3808
  } catch {
@@ -3672,7 +3831,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3672
3831
  const size = file && typeof file.size === "number" ? file.size : NaN;
3673
3832
  if (!name || !(size >= 0) || !userId) return null;
3674
3833
  const service = opts && opts.service ? { service: opts.service } : {};
3675
- const found = listOf(await skapi.getUniqueId(
3834
+ const found = listOf2(await skapi.getUniqueId(
3676
3835
  Object.assign({ unique_id: name, condition: "<=" }, service),
3677
3836
  { fetchMore: false, limit: DUPLICATE_LOOKUP_LIMIT }
3678
3837
  ));
@@ -3685,7 +3844,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
3685
3844
  for (const uniqueId of ids) {
3686
3845
  let record = null;
3687
3846
  try {
3688
- record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
3847
+ record = listOf2(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
3689
3848
  } catch {
3690
3849
  continue;
3691
3850
  }
@@ -6179,6 +6338,43 @@ Index the REMAINING windows - one record per row/item, looking at any page image
6179
6338
  return queued;
6180
6339
  });
6181
6340
  }
6341
+ /**
6342
+ * ONE SHARED INDEX FOR IDENTICAL FILES: the linked copies that lose their original when
6343
+ * `removed` files (or every file under `folders`) go away, per original, oldest first
6344
+ * (identical.ts copiesToPromote). Read through host.findLinkedCopies, fresh, and it has
6345
+ * to be read BEFORE the delete or reset: those remove nothing from the copies' markers,
6346
+ * but a later sweep could no longer tell whose copies they were once a new original
6347
+ * exists. Never rejects; [] without the hook or on any failure.
6348
+ */
6349
+ collectLinkedCopies(removed, folders) {
6350
+ if (typeof this.host.findLinkedCopies !== "function") return Promise.resolve([]);
6351
+ var id = this.host.getIdentity();
6352
+ var actor = { userId: id && !id.anonymous ? id.userId : null, isProjectOwner: !!(id && !id.anonymous && id.owner && id.userId === id.owner) };
6353
+ return Promise.resolve(this.host.findLinkedCopies()).then(function(map) {
6354
+ return map ? copiesToPromote(map, removed || [], folders, actor) : [];
6355
+ }).catch(function() {
6356
+ return [];
6357
+ });
6358
+ }
6359
+ /**
6360
+ * Send the copies of a removed or overwritten original again (owner decision
6361
+ * 2026-11-26): each list's oldest copy first, so its first pass claims the content and
6362
+ * is indexed for real (one AI run), then the others, which link to it with no AI call.
6363
+ * The share flag rides on every first pass while the project's switch is on (requests.ts
6364
+ * notifyAgentSaveAttachment). Through reindexStoredFiles, so each copy keeps its access
6365
+ * group and shows as a "Reindexing" row. Resolves to the number of files queued.
6366
+ */
6367
+ promoteLinkedCopies(plan) {
6368
+ var list = [];
6369
+ (plan || []).forEach(function(g) {
6370
+ (g && g.copies || []).forEach(function(c) {
6371
+ if (c) list.push({ storagePath: c });
6372
+ });
6373
+ });
6374
+ if (!list.length) return Promise.resolve(0);
6375
+ console.log("[chat-engine] identical files: sending " + list.length + " linked cop" + (list.length === 1 ? "y" : "ies") + " again, their original is gone:", plan);
6376
+ return this.reindexStoredFiles(list);
6377
+ }
6182
6378
  /**
6183
6379
  * The same question, asked of the SERVER when this page cannot answer it.
6184
6380
  *
@@ -12971,6 +13167,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12971
13167
  att._storedCount = 0;
12972
13168
  att._indexQueuedCount = 0;
12973
13169
  att._indexQueued = false;
13170
+ att._landedNew = [];
12974
13171
  var cancelError = function() {
12975
13172
  var e = new Error(UPLOAD_CANCELLED_MESSAGE);
12976
13173
  e.code = "CANCELLED";
@@ -12998,10 +13195,13 @@ Index the REMAINING windows - one record per row/item, looking at any page image
12998
13195
  checkCancel();
12999
13196
  var hadExists = false;
13000
13197
  var skipped = false;
13198
+ var promotion = null;
13001
13199
  var duplicateOf = null;
13002
13200
  var existedBefore = false;
13003
13201
  var madeRecord = false;
13202
+ var sentAll = false;
13004
13203
  var onProg = function(p) {
13204
+ if (p && p.total && p.loaded >= p.total) sentAll = true;
13005
13205
  if (p && p.total) {
13006
13206
  att.progress = Math.floor((idx + p.loaded / p.total) / total * 100);
13007
13207
  self.host.renderAttachmentChips();
@@ -13009,6 +13209,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13009
13209
  };
13010
13210
  var doMemberUpload = function(checkExistence) {
13011
13211
  checkCancel();
13212
+ sentAll = false;
13012
13213
  return self.host.uploadFile({
13013
13214
  file: member.file,
13014
13215
  storagePath: member.storagePath,
@@ -13030,10 +13231,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13030
13231
  }).then(function(r) {
13031
13232
  att._abort = null;
13032
13233
  att._storedCount = (att._storedCount || 0) + 1;
13234
+ if (checkExistence) att._landedNew.push(member.storagePath);
13033
13235
  return r;
13034
13236
  }, function(err) {
13035
13237
  att._abort = null;
13036
- if (att._cancelled) throw cancelError();
13238
+ if (att._cancelled) {
13239
+ if (checkExistence && sentAll) att._landedNew.push(member.storagePath);
13240
+ throw cancelError();
13241
+ }
13037
13242
  throw err;
13038
13243
  });
13039
13244
  };
@@ -13057,6 +13262,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13057
13262
  return self.host.promptOverwrite(member.file.name).then(function(choice) {
13058
13263
  if (choice === "overwrite") {
13059
13264
  existedBefore = true;
13265
+ promotion = self.collectLinkedCopies([member.storagePath]);
13060
13266
  markImagePreviewStale(self.host.getIdentity().projectId || "default", member.storagePath);
13061
13267
  return doMemberUpload(false);
13062
13268
  }
@@ -13189,6 +13395,9 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13189
13395
  if (alreadyIndexing) return;
13190
13396
  att._indexQueuedCount = (att._indexQueuedCount || 0) + 1;
13191
13397
  if (att.kind !== "folder") att._indexQueued = true;
13398
+ att._landedNew = (att._landedNew || []).filter(function(p) {
13399
+ return p !== member.storagePath;
13400
+ });
13192
13401
  self.host.renderAttachmentChips();
13193
13402
  return self.trackIndexDispatch(notifyAgentSaveAttachment({
13194
13403
  platform: id.platform,
@@ -13230,6 +13439,14 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13230
13439
  });
13231
13440
  self.noteBgQueueChanged();
13232
13441
  self.drainBgTaskQueue();
13442
+ if (promotion) {
13443
+ var plan = promotion;
13444
+ promotion = null;
13445
+ plan.then(function(pl) {
13446
+ return self.promoteLinkedCopies(pl);
13447
+ }).catch(function() {
13448
+ });
13449
+ }
13233
13450
  }
13234
13451
  }, function(e) {
13235
13452
  console.error("[chat-engine] indexing request failed", e);
@@ -13310,6 +13527,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13310
13527
  att.status = "cancelled";
13311
13528
  att._abort = null;
13312
13529
  self.host.renderAttachmentChips();
13530
+ if (typeof att._onCancelSettled === "function") {
13531
+ try {
13532
+ att._onCancelSettled((att._landedNew || []).slice());
13533
+ } catch (e) {
13534
+ }
13535
+ }
13313
13536
  return;
13314
13537
  }
13315
13538
  if (removed || aborted) return;
@@ -13349,8 +13572,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
13349
13572
  // src/index.js
13350
13573
  (function() {
13351
13574
  var MCP_PROD = "https://mcp.skapi.com";
13352
- var MCP_DEV = "https://mcp-dev.broadwayinc.computer";
13353
- var BQ_VERSION = "1.21.7" ;
13575
+ var MCP_DEV = "https://mcp.broadwayinc.computer";
13576
+ var BQ_VERSION = "1.21.13" ;
13354
13577
  var ATTACHMENT_URL_EXPIRES_SECONDS = 600;
13355
13578
  var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
13356
13579
  var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
@@ -15286,6 +15509,12 @@ Index the REMAINING windows - one record per row/item, looking at any page image
15286
15509
  if (!uid) return Promise.resolve(null);
15287
15510
  return findDuplicateUpload(S.skapi, file, uid, { service: S.projectId });
15288
15511
  },
15512
+ // Every linked copy of the project (one shared index for identical files): an
15513
+ // Overwrite of an original sends its copies again (engine collectLinkedCopies).
15514
+ findLinkedCopies: function() {
15515
+ if (!S.skapi || !S.projectId || isAnonymousSession()) return Promise.resolve(null);
15516
+ return listLinkedCopies(S.skapi, S.projectId);
15517
+ },
15289
15518
  storagePathFor: function(relPath) {
15290
15519
  return attachmentStoragePath(relPath);
15291
15520
  },
@@ -16367,14 +16596,19 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16367
16596
  var cancelled = (atts || []).filter(isInFlightUpload);
16368
16597
  if (!cancelled.length) return;
16369
16598
  var ids = {};
16599
+ var notice = { list: cancelled, text: "" };
16370
16600
  cancelled.forEach(function(a) {
16601
+ a._onCancelSettled = function(landed) {
16602
+ discardCancelledUploads(a, landed, notice);
16603
+ };
16371
16604
  if (!session.cancelAttachmentUpload(a)) a._cancelled = true;
16372
16605
  ids[a.id] = true;
16373
16606
  });
16374
16607
  CS.attachments = CS.attachments.filter(function(a) {
16375
16608
  return !ids[a.id];
16376
16609
  });
16377
- CS.attachmentCancelNotice = uploadCancelNotice(cancelled);
16610
+ notice.text = uploadCancelNotice(cancelled);
16611
+ CS.attachmentCancelNotice = notice.text;
16378
16612
  CS.attachmentCapNotice = "";
16379
16613
  CS.visibleAttachmentCount = Infinity;
16380
16614
  recomputeAttachmentWarning();
@@ -16387,23 +16621,105 @@ Index the REMAINING windows - one record per row/item, looking at any page image
16387
16621
  return a.kind === "folder" ? a.name + "/" : a.name;
16388
16622
  });
16389
16623
  var text = list.length === 1 ? "Upload cancelled: " + names[0] + "." : list.length + " uploads cancelled: " + names.slice(0, 3).join(", ") + (names.length > 3 ? " and " + (names.length - 3) + " more." : ".");
16390
- var queued = 0, stored = 0;
16624
+ var queued = 0, checking = 0, removed = 0, kept = 0, reasons = [];
16391
16625
  list.forEach(function(a) {
16392
16626
  var q = a._indexQueuedCount || 0;
16393
16627
  queued += q;
16628
+ var d = a._discard;
16629
+ if (d && d.state === "done") {
16630
+ removed += d.removed;
16631
+ kept += d.kept;
16632
+ if (d.reason && reasons.indexOf(d.reason) === -1) reasons.push(d.reason);
16633
+ return;
16634
+ }
16635
+ if (d && d.state === "pending") {
16636
+ checking += d.count;
16637
+ return;
16638
+ }
16394
16639
  var landed = Math.max(0, (a._storedCount || 0) - q);
16395
16640
  if (!landed && a.status === "uploading" && (a.progress || 0) >= 100) landed = 1;
16396
- stored += landed;
16641
+ checking += landed;
16397
16642
  });
16643
+ var one = list.length === 1 && !queued;
16398
16644
  if (queued) {
16399
16645
  text += " " + queued + (queued === 1 ? " file had" : " files had") + " already gone to indexing; stop " + (queued === 1 ? "it from its row" : "them from their rows") + " in the chat.";
16400
16646
  }
16401
- if (stored) {
16402
- var subject = list.length === 1 && stored === 1 && !queued ? "Its" : stored === 1 ? "One file's" : stored + " files'";
16403
- text += " " + subject + " bytes had already been sent, so " + (stored === 1 ? "it" : "they") + " may stay in storage, but " + (stored === 1 ? "it was" : "they were") + " not indexed or added to the chat.";
16647
+ if (checking) {
16648
+ text += " " + (one && checking === 1 ? "Its" : checking === 1 ? "One file's" : checking + " files'") + " bytes had already been sent; removing " + (checking === 1 ? "it" : "them") + " from storage.";
16649
+ }
16650
+ if (removed) {
16651
+ text += " " + (one && removed === 1 && !kept ? "Its bytes had already reached storage and were removed again." : removed === 1 ? "One file had already reached storage and was removed again." : removed + " files had already reached storage and were removed again.");
16652
+ }
16653
+ if (kept) {
16654
+ text += " " + (one && kept === 1 && !removed ? "It" : kept === 1 ? "One file" : kept + " files") + " had already reached storage and could not be removed, but " + (kept === 1 ? "it was" : "they were") + " not indexed or added to the chat." + (reasons.length ? " " + reasons.join(" ") : "");
16404
16655
  }
16405
16656
  return text;
16406
16657
  }
16658
+ function discardCancelledUploads(att, landed, notice) {
16659
+ var paths = (landed || []).filter(function(p, i, all) {
16660
+ return p && all.indexOf(p) === i;
16661
+ });
16662
+ if (!paths.length) {
16663
+ att._discard = { state: "done", removed: 0, kept: 0, reason: "" };
16664
+ refreshCancelNotice(notice);
16665
+ return;
16666
+ }
16667
+ att._discard = { state: "pending", count: paths.length };
16668
+ refreshCancelNotice(notice);
16669
+ var removed = 0, kept = 0, reason = "";
16670
+ paths.reduce(function(p, storagePath) {
16671
+ return p.then(function() {
16672
+ return discardUploadedFile(storagePath).then(function(out) {
16673
+ if (out.removed) removed += 1;
16674
+ else if (!out.gone) {
16675
+ kept += 1;
16676
+ if (!reason && out.message) reason = out.message.replace(/\s*(It|The file) was not removed\.$/, "");
16677
+ }
16678
+ });
16679
+ });
16680
+ }, Promise.resolve()).then(function() {
16681
+ att._discard = { state: "done", removed, kept, reason };
16682
+ refreshCancelNotice(notice);
16683
+ });
16684
+ }
16685
+ function discardUploadedFile(storagePath) {
16686
+ if (!S.skapi || typeof S.skapi.forwardRequest !== "function" || !S.projectId) {
16687
+ return Promise.resolve({ removed: false, message: "This page cannot reach the BunnyQuery server." });
16688
+ }
16689
+ return Promise.resolve(S.skapi.forwardRequest(null, {
16690
+ service: S.projectId,
16691
+ owner: S.owner || void 0,
16692
+ url: mcpBaseUrl() + "/internal/upload-discard",
16693
+ method: "POST",
16694
+ // "$ACCESS_TOKEN" is filled in by skapi with this user's own token: the
16695
+ // server acts for the user it names and nobody else.
16696
+ headers: { "content-type": "application/json", Authorization: "Bearer $ACCESS_TOKEN" },
16697
+ data: { project_id: S.projectId, path: storagePath }
16698
+ })).then(function(res) {
16699
+ var body = res;
16700
+ if (typeof body === "string") {
16701
+ try {
16702
+ body = JSON.parse(body);
16703
+ } catch (e) {
16704
+ body = { message: body };
16705
+ }
16706
+ }
16707
+ if (!body || typeof body !== "object" || typeof body.removed !== "boolean") {
16708
+ return { removed: false, message: "The server gave no answer about the file." };
16709
+ }
16710
+ return { removed: body.removed, gone: body.gone === true, message: typeof body.message === "string" ? body.message : "" };
16711
+ }, function(err) {
16712
+ var msg = err && (err.message || err.body && err.body.message) || (typeof err === "string" ? err : "");
16713
+ return { removed: false, message: msg ? "The server answered: " + String(msg).slice(0, 200).replace(/\.?$/, ".") : "The server could not be reached." };
16714
+ });
16715
+ }
16716
+ function refreshCancelNotice(notice) {
16717
+ if (!notice || CS.attachmentCancelNotice !== notice.text) return;
16718
+ notice.text = uploadCancelNotice(notice.list);
16719
+ CS.attachmentCancelNotice = notice.text;
16720
+ renderAttachmentChips();
16721
+ scheduleAttachmentOverflowRecompute();
16722
+ }
16407
16723
  function clearAttachments() {
16408
16724
  CS.attachments = CS.attachments.filter(function(a) {
16409
16725
  return !!a._batchId;
@@ -17162,6 +17478,8 @@ Index the REMAINING windows - one record per row/item, looking at any page image
17162
17478
  return indexGroupVerb(group) + " " + nameLabel;
17163
17479
  }
17164
17480
  function indexGroupCount(group) {
17481
+ var linkedLine = indexGroupLinkedLabel(group);
17482
+ if (linkedLine) return linkedLine;
17165
17483
  if (group.stub) return indexGroupDurationLabel(group);
17166
17484
  var prog = group.status === "active" && session && session.pageProgressFor ? session.pageProgressFor(group.path || group.key, group.name) : null;
17167
17485
  var pages = prog ? prog.total ? prog.saved + " of " + prog.total + " pages" : prog.saved + " pages" : "";
@@ -17211,7 +17529,11 @@ Index the REMAINING windows - one record per row/item, looking at any page image
17211
17529
  finished: typeof d.finished === "number" ? d.finished : void 0,
17212
17530
  error: typeof d.error === "string" ? d.error : void 0,
17213
17531
  platform: d.platform === "claude" || d.platform === "openai" ? d.platform : void 0,
17214
- owner: list[i] && typeof list[i].user_id === "string" ? list[i].user_id : void 0
17532
+ owner: list[i] && typeof list[i].user_id === "string" ? list[i].user_id : void 0,
17533
+ // a run LINKED to an identical file's index (engine identical.ts)
17534
+ linked: d.linked === true ? true : void 0,
17535
+ alias_of: d.linked === true && typeof d.alias_of === "string" ? d.alias_of : void 0,
17536
+ link_ms: d.linked === true && typeof d.link_ms === "number" ? d.link_ms : void 0
17215
17537
  };
17216
17538
  }
17217
17539
  }
@@ -17291,7 +17613,10 @@ Index the REMAINING windows - one record per row/item, looking at any page image
17291
17613
  finished: rr.finished,
17292
17614
  error: rr.error,
17293
17615
  platform: rr.platform,
17294
- owner: rr.owner
17616
+ owner: rr.owner,
17617
+ linked: rr.linked,
17618
+ alias_of: rr.alias_of,
17619
+ link_ms: rr.link_ms
17295
17620
  };
17296
17621
  }
17297
17622
  }
@@ -18499,7 +18824,7 @@ Index the REMAINING windows - one record per row/item, looking at any page image
18499
18824
  signup: false,
18500
18825
  // include signup (and thus delete/recover account)
18501
18826
  dev: false,
18502
- // use the MCP dev host (mcp-dev.broadwayinc.computer)
18827
+ // use the MCP dev host (mcp.broadwayinc.computer)
18503
18828
  mcpBaseUrl: null,
18504
18829
  // override the MCP OAuth server base entirely
18505
18830
  googleClientId: null,