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