bunnyquery 1.15.0 → 1.15.2

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.cjs CHANGED
@@ -73,6 +73,13 @@ function normalizeWebAccess(value) {
73
73
  function webAccessFrom(data) {
74
74
  return data ? normalizeWebAccess(data.web_access) : DEFAULT_WEB_ACCESS;
75
75
  }
76
+ var DEFAULT_SKIP_DUPLICATE_FILES = true;
77
+ function normalizeSkipDuplicateFiles(value) {
78
+ return value !== false;
79
+ }
80
+ function skipDuplicateFilesFrom(data) {
81
+ return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
82
+ }
76
83
  var CHAT_GREETING_MAX_LENGTH = 400;
77
84
  function normalizeChatGreeting(value) {
78
85
  if (typeof value !== "string") return "";
@@ -159,6 +166,9 @@ function projectChatGreeting(service) {
159
166
  function projectWebAccess(service) {
160
167
  return webAccessFrom(cachedProjectSettings(service));
161
168
  }
169
+ function projectSkipDuplicateFiles(service) {
170
+ return skipDuplicateFilesFrom(cachedProjectSettings(service));
171
+ }
162
172
  function setProjectSettings(service, data) {
163
173
  if (!service) return;
164
174
  cache.set(service, { data: data || null, settled: true, inflight: null });
@@ -238,16 +248,29 @@ function liveStreamingRealtimeEnabled() {
238
248
  function liveStreamingEnabled() {
239
249
  return _config?.liveStreaming === true;
240
250
  }
251
+ function underCeiling(projectSetting, option, override) {
252
+ if (!projectSetting) return false;
253
+ if (option === false) return false;
254
+ if (override === false) return false;
255
+ return true;
256
+ }
241
257
  function webAccessEnabled(service) {
242
258
  const opt = _config ? _config.webAccess : void 0;
243
- if (typeof opt === "boolean") return opt;
244
- return webAccessFrom(service ? cachedProjectSettings(service) : null);
259
+ return underCeiling(webAccessFrom(service ? cachedProjectSettings(service) : null), opt);
245
260
  }
246
- function resolveWebAccess(service) {
261
+ function resolveWebAccess(service, override) {
247
262
  const opt = _config ? _config.webAccess : void 0;
248
- if (typeof opt === "boolean") return Promise.resolve(opt);
249
- if (!service) return Promise.resolve(false);
250
- return loadProjectSettings(service).then(webAccessFrom, () => false);
263
+ if (!service) return Promise.resolve(underCeiling(webAccessFrom(null), opt, override));
264
+ return loadProjectSettings(service).then(webAccessFrom, () => false).then((setting) => underCeiling(setting, opt, override));
265
+ }
266
+ function skipDuplicateFilesEnabled(service) {
267
+ const opt = _config ? _config.skipDuplicateFiles : void 0;
268
+ return underCeiling(skipDuplicateFilesFrom(service ? cachedProjectSettings(service) : null), opt);
269
+ }
270
+ function resolveSkipDuplicateFiles(service) {
271
+ const opt = _config ? _config.skipDuplicateFiles : void 0;
272
+ if (!service) return Promise.resolve(underCeiling(skipDuplicateFilesFrom(null), opt));
273
+ return loadProjectSettings(service).then(skipDuplicateFilesFrom, () => skipDuplicateFilesFrom(null)).then((setting) => underCeiling(setting, opt));
251
274
  }
252
275
  function streamRecoveryEnabled() {
253
276
  if (!_config) return false;
@@ -263,6 +286,54 @@ function pollOpt() {
263
286
  return p === void 0 ? {} : { poll: p };
264
287
  }
265
288
 
289
+ // src/engine/duplicates.ts
290
+ var DUPLICATE_LOOKUP_MAX_CANDIDATES = 25;
291
+ var SRC_PREFIX = "src::";
292
+ function isDuplicateCandidateId(uniqueId, name) {
293
+ if (typeof uniqueId !== "string" || !name) return false;
294
+ if (uniqueId.indexOf(SRC_PREFIX) !== 0) return false;
295
+ if (uniqueId === SRC_PREFIX + name) return true;
296
+ const tail = "/" + name;
297
+ return uniqueId.length > SRC_PREFIX.length + tail.length && uniqueId.slice(-tail.length) === tail;
298
+ }
299
+ function listOf(res) {
300
+ if (!res) return [];
301
+ if (Array.isArray(res)) return res;
302
+ return Array.isArray(res.list) ? res.list : [];
303
+ }
304
+ async function findDuplicateUpload(skapi, file, userId, opts) {
305
+ try {
306
+ if (!skapi || typeof skapi.getUniqueId !== "function" || typeof skapi.getRecords !== "function") return null;
307
+ const name = file && typeof file.name === "string" ? file.name : "";
308
+ const size = file && typeof file.size === "number" ? file.size : NaN;
309
+ if (!name || !(size >= 0) || !userId) return null;
310
+ const service = opts && opts.service ? { service: opts.service } : {};
311
+ const found = listOf(await skapi.getUniqueId(Object.assign({ unique_id: name, condition: "<=" }, service)));
312
+ const ids = [];
313
+ for (const item of found) {
314
+ const id = item && typeof item === "object" ? item.unique_id : item;
315
+ if (isDuplicateCandidateId(id, name) && ids.indexOf(id) === -1) ids.push(id);
316
+ if (ids.length >= DUPLICATE_LOOKUP_MAX_CANDIDATES) break;
317
+ }
318
+ for (const uniqueId of ids) {
319
+ let record = null;
320
+ try {
321
+ record = listOf(await skapi.getRecords(Object.assign({ unique_id: uniqueId }, service)))[0] || null;
322
+ } catch {
323
+ continue;
324
+ }
325
+ if (!record || typeof record !== "object") continue;
326
+ const data = record.data && typeof record.data === "object" ? record.data : null;
327
+ if (!data || data.size_bytes !== size) continue;
328
+ if (record.user_id !== userId) continue;
329
+ return { storagePath: uniqueId.slice(SRC_PREFIX.length), uniqueId, record };
330
+ }
331
+ return null;
332
+ } catch {
333
+ return null;
334
+ }
335
+ }
336
+
266
337
  // src/engine/office.ts
267
338
  var OFFICE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
268
339
  "doc",
@@ -675,6 +746,10 @@ function buildRenderMeta(attachment) {
675
746
  ` : "") + `- access group (use this for EVERY record you write for this file): ${indexingAccessGroup(attachment)}
676
747
  `;
677
748
  }
749
+ var PAGE_TEXT_TABLE = "page_texts";
750
+ var PAGE_TEXT_RULE = `PAGE TEXT for pages WITHOUT a text layer: for EVERY page whose label (its first label, when the page is split into strips) carries NO "Embedded text layer" block, ALSO post exactly ONE record in table "${PAGE_TEXT_TABLE}" with data {"page": <its document page number from the label, 1-based>, "page_text": "<the page's complete text exactly as printed, verbatim, in reading order, nothing summarised or left out>"}, reference "src::" + the storage path above, in addition to the records above. A page WITH an embedded text layer gets NO such record: its text is already stored.
751
+
752
+ `;
678
753
  function buildRenderDatafy(placeholder) {
679
754
  return `
680
755
  ${placeholder}
@@ -685,7 +760,7 @@ Each image is preceded by a label giving its DOCUMENT PAGE number. That label is
685
760
 
686
761
  Transcribe COMPLETELY, not representatively. A table with twenty rows gets twenty records, not a sample of the first few - if a page has more rows than you can save comfortably, still save them all rather than summarising. Where a page carries an embedded text layer it is quoted above that page's image: it is the exact text and should be preferred over reading the pixels, with the image used for layout, tables, stamps and handwriting.
687
762
 
688
- Save records for THIS window of pages only, then stop and report what you saved. Do NOT try to read the rest of the file and do NOT worry about the pages after this window: if any remain, the next window is rendered and sent to you automatically. Report only the pages you were actually shown - never imply you have seen the whole document.`;
763
+ ` + PAGE_TEXT_RULE + `Save records for THIS window of pages only, then stop and report what you saved. Do NOT try to read the rest of the file and do NOT worry about the pages after this window: if any remain, the next window is rendered and sent to you automatically. Report only the pages you were actually shown - never imply you have seen the whole document.`;
689
764
  }
690
765
  function buildIndexingWindowMessage(attachment, placeholder, isContinuation, positionLabel) {
691
766
  const src = `src::${attachment.storagePath}`;
@@ -1227,7 +1302,7 @@ var RETRIEVAL_NOTE_PREFIX = "[Retrieval note, not shown to the user";
1227
1302
  var FILE_KEYS = ["path", "storage_path", "storagePath", "file", "file_path", "filePath"];
1228
1303
  var TABLE_KEYS = ["table_name", "tableName"];
1229
1304
  var GROUP_KEYS = ["access_group", "accessGroup"];
1230
- var SRC_PREFIX = "src::";
1305
+ var SRC_PREFIX2 = "src::";
1231
1306
  var RESULT_WALK_MAX_NODES = 400;
1232
1307
  var RESULT_WALK_MAX_DEPTH = 5;
1233
1308
  function isWebToolName(name) {
@@ -1256,8 +1331,8 @@ function pushHit(list, path, page) {
1256
1331
  }
1257
1332
  function pathFromSrcId(value) {
1258
1333
  if (typeof value !== "string") return null;
1259
- if (value.indexOf(SRC_PREFIX) !== 0) return null;
1260
- var rest = value.slice(SRC_PREFIX.length).trim();
1334
+ if (value.indexOf(SRC_PREFIX2) !== 0) return null;
1335
+ var rest = value.slice(SRC_PREFIX2.length).trim();
1261
1336
  return rest ? rest : null;
1262
1337
  }
1263
1338
  function parseJsonLoose(value) {
@@ -2926,7 +3001,7 @@ async function callClaudeWithMcp({
2926
3001
  fileUrls,
2927
3002
  webAccess
2928
3003
  }) {
2929
- const web = typeof webAccess === "boolean" ? webAccess : await resolveWebAccess(service);
3004
+ const web = await resolveWebAccess(service, typeof webAccess === "boolean" ? webAccess : void 0);
2930
3005
  const mcpServerDefinition = {
2931
3006
  type: "url",
2932
3007
  name: mcpServer.name,
@@ -4463,6 +4538,9 @@ var ChatSession = class {
4463
4538
  this._liveIndexKey = "";
4464
4539
  this._liveIndexAt = 0;
4465
4540
  this._indexClaims = {};
4541
+ this._bgQueueByFile = null;
4542
+ this._bgQueueStamp = { arr: null, length: 0, first: void 0, last: void 0 };
4543
+ this._bgQueueIndexRebuilds = 0;
4466
4544
  }
4467
4545
  /** What the display layer needs to decide whether a run is finished. `keys` holds
4468
4546
  * every file the server still has indexing work for; `checked` is false until the
@@ -4499,13 +4577,10 @@ var ChatSession = class {
4499
4577
  */
4500
4578
  hasLiveIndexRun(storagePath) {
4501
4579
  if (!storagePath) return false;
4502
- var claimed = this._indexClaims[this._indexClaimKey(storagePath)];
4580
+ var scoped = this._indexClaimKey(storagePath);
4581
+ var claimed = this._indexClaims[scoped];
4503
4582
  if (claimed && nowMs() - claimed < INDEX_DISPATCH_CLAIM_MS) return true;
4504
- var id = this.host.getIdentity();
4505
- for (var i = 0; i < this.bgTaskQueue.length; i++) {
4506
- var e = this.bgTaskQueue[i];
4507
- if (e && e.storagePath === storagePath && e.projectId === id.projectId && e.platform === id.platform) return true;
4508
- }
4583
+ if (this._bgQueueIndex()[scoped] > 0) return true;
4509
4584
  return this.state.messages.some(function(m) {
4510
4585
  if (!m.isBackgroundTask || m.role !== "user" || m.isCancelled) return false;
4511
4586
  if (!(m.isPendingQueued || m.isPendingInProcess || m.isSendingToServer)) return false;
@@ -4518,6 +4593,47 @@ var ChatSession = class {
4518
4593
  var id = this.host.getIdentity();
4519
4594
  return indexScopeKey(id.projectId, id.platform) + "|" + storagePath;
4520
4595
  }
4596
+ /**
4597
+ * bgTaskQueue as a map: scoped path (indexScopeKey(projectId, platform) +
4598
+ * '|' + storagePath, the key the claims and the stops use) -> entries.
4599
+ *
4600
+ * The array stays the source of truth because the engine does not own every
4601
+ * write to it: both hosts hand in their own array (the dashboard a Vue
4602
+ * reactive one it pushes to from the Files page and splices from its
4603
+ * fallback poller), and tests push to it directly. So the map is DERIVED, and
4604
+ * rebuilt when a cheap stamp says the array changed: its identity, its length,
4605
+ * its first and its last entry.
4606
+ *
4607
+ * Why that stamp is exact for this array: every write to bgTaskQueue is either
4608
+ * a push of a NEW entry object or a splice that removes one (nothing inserts
4609
+ * in the middle, replaces in place or re-pushes a removed entry). Under those
4610
+ * two operations, same length plus same last entry means the same contents:
4611
+ * a push changes the last entry unless that same push is removed again, and a
4612
+ * removal changes the length unless a push restores it, which changes the
4613
+ * last entry. The first entry is in the stamp as margin. A rebuild is one
4614
+ * pass over the array, paid once per change instead of once per claim.
4615
+ */
4616
+ _bgQueueIndex() {
4617
+ var q = this.bgTaskQueue;
4618
+ var n = q ? q.length : 0;
4619
+ var first = n ? q[0] : void 0;
4620
+ var last = n ? q[n - 1] : void 0;
4621
+ var st = this._bgQueueStamp;
4622
+ if (this._bgQueueByFile && st.arr === q && st.length === n && st.first === first && st.last === last) {
4623
+ return this._bgQueueByFile;
4624
+ }
4625
+ var idx = {};
4626
+ for (var i = 0; i < n; i++) {
4627
+ var e = q[i];
4628
+ if (!e || !e.storagePath) continue;
4629
+ var k = indexScopeKey(e.projectId, e.platform) + "|" + e.storagePath;
4630
+ idx[k] = (idx[k] || 0) + 1;
4631
+ }
4632
+ this._bgQueueByFile = idx;
4633
+ this._bgQueueStamp = { arr: q, length: n, first, last };
4634
+ this._bgQueueIndexRebuilds++;
4635
+ return idx;
4636
+ }
4521
4637
  /**
4522
4638
  * Take this file's indexing slot, or report that someone already has it.
4523
4639
  *
@@ -8515,11 +8631,26 @@ var ChatSession = class {
8515
8631
  if (!total) return Promise.reject(new Error("Empty attachment"));
8516
8632
  var urls = [];
8517
8633
  var anyIndexFailed = false;
8634
+ var reusedCount = 0;
8635
+ att.reused = false;
8518
8636
  var chain = Promise.resolve();
8637
+ var findDuplicate = function(member) {
8638
+ if (typeof self.host.findDuplicateUpload !== "function") return Promise.resolve(null);
8639
+ var storedName = String(member.storagePath || "").split("/").filter(Boolean).pop() || member.file.name;
8640
+ return resolveSkipDuplicateFiles(id.projectId).then(function(on) {
8641
+ if (!on) return null;
8642
+ return Promise.resolve(self.host.findDuplicateUpload({ name: storedName, size: member.file.size })).then(function(hit) {
8643
+ return hit && typeof hit.storagePath === "string" && hit.storagePath ? hit.storagePath : null;
8644
+ });
8645
+ }).catch(function() {
8646
+ return null;
8647
+ });
8648
+ };
8519
8649
  members.forEach(function(member, idx) {
8520
8650
  chain = chain.then(function() {
8521
8651
  var hadExists = false;
8522
8652
  var skipped = false;
8653
+ var duplicateOf = null;
8523
8654
  var existedBefore = false;
8524
8655
  var onProg = function(p) {
8525
8656
  if (p && p.total) {
@@ -8538,7 +8669,14 @@ var ChatSession = class {
8538
8669
  }
8539
8670
  });
8540
8671
  };
8541
- return doMemberUpload(true).catch(function(err) {
8672
+ return findDuplicate(member).then(function(dup) {
8673
+ if (dup) {
8674
+ duplicateOf = dup;
8675
+ console.log("[chat-engine] skipping an upload the user already has:", member.storagePath, "->", dup);
8676
+ return;
8677
+ }
8678
+ return doMemberUpload(true);
8679
+ }).catch(function(err) {
8542
8680
  var code = err && (err.code || err.body && err.body.code);
8543
8681
  var msg = err && (err.message || err.body && err.body.message || (typeof err === "string" ? err : ""));
8544
8682
  var isExists = code === "EXISTS" || msg && /exist/i.test(msg);
@@ -8558,9 +8696,20 @@ var ChatSession = class {
8558
8696
  });
8559
8697
  }).then(function() {
8560
8698
  if (skipped) return;
8561
- return self.host.getTemporaryUrl(member.storagePath);
8699
+ return self.host.getTemporaryUrl(duplicateOf || member.storagePath);
8562
8700
  }).then(function(url) {
8563
8701
  if (skipped) return;
8702
+ if (duplicateOf) {
8703
+ urls.push({ name: member.relPath, url, storagePath: duplicateOf });
8704
+ reusedCount += 1;
8705
+ if (att.kind !== "folder") {
8706
+ att.uploadedUrl = url;
8707
+ att.storagePath = duplicateOf;
8708
+ att.reused = true;
8709
+ } else att.reusedCount = reusedCount;
8710
+ self.host.renderAttachmentChips();
8711
+ return;
8712
+ }
8564
8713
  urls.push({ name: member.relPath, url, storagePath: member.storagePath });
8565
8714
  if (att.kind !== "folder") {
8566
8715
  att.uploadedUrl = url;
@@ -9201,8 +9350,10 @@ exports.DATA_TOOL_NAMES = DATA_TOOL_NAMES;
9201
9350
  exports.DEFAULT_CLAUDE_MODEL = DEFAULT_CLAUDE_MODEL;
9202
9351
  exports.DEFAULT_CONTEXT_WINDOW = DEFAULT_CONTEXT_WINDOW;
9203
9352
  exports.DEFAULT_OPENAI_MODEL = DEFAULT_OPENAI_MODEL;
9353
+ exports.DEFAULT_SKIP_DUPLICATE_FILES = DEFAULT_SKIP_DUPLICATE_FILES;
9204
9354
  exports.DEFAULT_UPLOAD_ACCESS_GROUP = DEFAULT_UPLOAD_ACCESS_GROUP;
9205
9355
  exports.DEFAULT_WEB_ACCESS = DEFAULT_WEB_ACCESS;
9356
+ exports.DUPLICATE_LOOKUP_MAX_CANDIDATES = DUPLICATE_LOOKUP_MAX_CANDIDATES;
9206
9357
  exports.EMPTY_INDEXING_REPLY = EMPTY_INDEXING_REPLY;
9207
9358
  exports.EXPIRED_ATTACHMENT_URL_HOST = EXPIRED_ATTACHMENT_URL_HOST;
9208
9359
  exports.EXPIRED_ATTACHMENT_URL_ORIGIN = EXPIRED_ATTACHMENT_URL_ORIGIN;
@@ -9234,6 +9385,7 @@ exports.MIN_INPUT_TOKEN_BUDGET = MIN_INPUT_TOKEN_BUDGET;
9234
9385
  exports.MIN_PER_REQUEST_INPUT_CAP = MIN_PER_REQUEST_INPUT_CAP;
9235
9386
  exports.NO_DATA_TOOL_MARK = NO_DATA_TOOL_MARK;
9236
9387
  exports.OUTPUT_TOKEN_RESERVE = OUTPUT_TOKEN_RESERVE;
9388
+ exports.PAGE_TEXT_TABLE = PAGE_TEXT_TABLE;
9237
9389
  exports.POLL_INTERVAL = POLL_INTERVAL;
9238
9390
  exports.PRESIGN_SAFETY_MARGIN_MS = PRESIGN_SAFETY_MARGIN_MS;
9239
9391
  exports.PREVIEWABLE_IMAGE_CONTENT_TYPES = PREVIEWABLE_IMAGE_CONTENT_TYPES;
@@ -9322,6 +9474,7 @@ exports.fetchLiveIndexingKeys = fetchLiveIndexingKeys;
9322
9474
  exports.fillHistoryViewport = fillHistoryViewport;
9323
9475
  exports.filterListByClearHorizon = filterListByClearHorizon;
9324
9476
  exports.findAttachmentParser = findAttachmentParser;
9477
+ exports.findDuplicateUpload = findDuplicateUpload;
9325
9478
  exports.formatChatTimestamp = formatChatTimestamp;
9326
9479
  exports.formatDuration = formatDuration;
9327
9480
  exports.formatRetrievalNote = formatRetrievalNote;
@@ -9346,6 +9499,7 @@ exports.isAuthExpiredError = isAuthExpiredError;
9346
9499
  exports.isBgIndexingQueue = isBgIndexingQueue;
9347
9500
  exports.isCsrStatusEnvelope = isCsrStatusEnvelope;
9348
9501
  exports.isDataToolName = isDataToolName;
9502
+ exports.isDuplicateCandidateId = isDuplicateCandidateId;
9349
9503
  exports.isErrorResponseBody = isErrorResponseBody;
9350
9504
  exports.isHttpUrlLike = isHttpUrlLike;
9351
9505
  exports.isImageVisionFile = isImageVisionFile;
@@ -9379,6 +9533,7 @@ exports.normalizeAttachmentPathCandidate = normalizeAttachmentPathCandidate;
9379
9533
  exports.normalizeChatGreeting = normalizeChatGreeting;
9380
9534
  exports.normalizeExt = normalizeExt;
9381
9535
  exports.normalizeProjectAccessSetting = normalizeProjectAccessSetting;
9536
+ exports.normalizeSkipDuplicateFiles = normalizeSkipDuplicateFiles;
9382
9537
  exports.normalizeTextContent = normalizeTextContent;
9383
9538
  exports.normalizeTrailingInlineToken = normalizeTrailingInlineToken;
9384
9539
  exports.normalizeUploadAccessGroup = normalizeUploadAccessGroup;
@@ -9401,6 +9556,7 @@ exports.projectAccessSetting = projectAccessSetting;
9401
9556
  exports.projectAsksUploadAccess = projectAsksUploadAccess;
9402
9557
  exports.projectChatGreeting = projectChatGreeting;
9403
9558
  exports.projectSettingsSettled = projectSettingsSettled;
9559
+ exports.projectSkipDuplicateFiles = projectSkipDuplicateFiles;
9404
9560
  exports.projectUploadAccessGroup = projectUploadAccessGroup;
9405
9561
  exports.projectWebAccess = projectWebAccess;
9406
9562
  exports.providerBodyWasRead = providerBodyWasRead;
@@ -9412,6 +9568,7 @@ exports.renderInlineLinkHtml = renderInlineLinkHtml;
9412
9568
  exports.repairUrlEntities = repairUrlEntities;
9413
9569
  exports.repairUrlWhitespace = repairUrlWhitespace;
9414
9570
  exports.resolveImagePreviewUrl = resolveImagePreviewUrl;
9571
+ exports.resolveSkipDuplicateFiles = resolveSkipDuplicateFiles;
9415
9572
  exports.resolveWebAccess = resolveWebAccess;
9416
9573
  exports.retrievalNoteFromText = retrievalNoteFromText;
9417
9574
  exports.retrievalNoteOfAnswer = retrievalNoteOfAnswer;
@@ -9422,6 +9579,8 @@ exports.setProjectContextWindow = setProjectContextWindow;
9422
9579
  exports.setProjectSettings = setProjectSettings;
9423
9580
  exports.shouldRescueInFlightMessage = shouldRescueInFlightMessage;
9424
9581
  exports.skapiSupportsStreaming = skapiSupportsStreaming;
9582
+ exports.skipDuplicateFilesEnabled = skipDuplicateFilesEnabled;
9583
+ exports.skipDuplicateFilesFrom = skipDuplicateFilesFrom;
9425
9584
  exports.streamRecoveryEnabled = streamRecoveryEnabled;
9426
9585
  exports.streamRecoveryLabels = streamRecoveryLabels;
9427
9586
  exports.streamRecoveryPhase = streamRecoveryPhase;