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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunnyquery",
3
- "version": "1.21.7",
3
+ "version": "1.21.13",
4
4
  "description": "Embeddable BunnyQuery AI chat widget + its framework-agnostic chat engine",
5
5
  "main": "bunnyquery.js",
6
6
  "exports": {
@@ -474,6 +474,13 @@ export interface ChatHost {
474
474
  * usual"; the engine's findDuplicateUpload is the ready-made implementation.
475
475
  */
476
476
  findDuplicateUpload?(file: { name: string; size: number }): Promise<{ storagePath: string } | null> | { storagePath: string } | null;
477
+ /**
478
+ * Optional. Every linked copy of the project, read fresh (one shared index for
479
+ * identical files; the engine's listLinkedCopies is the ready-made implementation).
480
+ * With it, an Overwrite of an ORIGINAL sends its copies again afterwards (the oldest
481
+ * becomes the new original, the others link to it). Missing or null: nothing is sent.
482
+ */
483
+ findLinkedCopies?(): Promise<Map<string, { original: string; claim?: string; linkedAt?: number; owner?: string | null }> | null>;
477
484
  /** Map a relative path to the consumer's db storage key (e.g. uid-prefixed). */
478
485
  storagePathFor(relPath: string): string;
479
486
  getMimeType(name: string): string | null;
@@ -0,0 +1,448 @@
1
+ /**
2
+ * ONE SHARED INDEX FOR IDENTICAL FILES: the clients' half (owner, 2026-11-26).
3
+ *
4
+ * Files whose stored bytes are the same (same md5 and size, same kind of file) are indexed
5
+ * ONCE. The first one is the ORIGINAL; every later one is a LINKED COPY: the worker links it
6
+ * to the original's index on the server with no AI call (the MCP's content-dedup.js). This
7
+ * module is what both clients (the dashboard and the widget) share about that:
8
+ *
9
+ * - reading a file's copy status off the markers they already sweep (done::, run::) and
10
+ * the live claim ids (one prefix listing of "cas::"),
11
+ * - the words a copy is shown with (Files page chips, the chat's indexing row),
12
+ * - which copies to send again when an original goes away (promotion),
13
+ * - the owner's "Find identical files" calls.
14
+ *
15
+ * THE RECORDS (written by the MCP, read here; see content-dedup.js for the full contract):
16
+ * done::<copy> __INDEXING__ "authorized", tag "bq_linked", data { source, linked: true,
17
+ * alias_of: <original>, alias_claim: "cas::<scope>::<key>", content_key,
18
+ * completed_at, records_written: 0, copy_group, copy_owner }
19
+ * run::<copy> data { status: 'done', linked: true, alias_of, alias_claim, finished }
20
+ * cas::<scope>::<key> the claim, in the original's access group, referencing
21
+ * src::<original>. Deleting or resetting the original removes it, so a
22
+ * linked copy whose alias_claim is not among the live claim ids has lost its
23
+ * original (removed outside the clients, or not promoted yet).
24
+ *
25
+ * Pure apart from the three reads and two route calls at the bottom, which take the skapi
26
+ * instance (or go through the host's forwardRequest) like the rest of the engine.
27
+ */
28
+ import { chatEngineConfig, resolveForwardRequest } from './config';
29
+ import { formatIndexDuration } from './time';
30
+
31
+ /** Tag on every linked copy's done:: marker. */
32
+ export const LINKED_COPY_TAG = 'bq_linked';
33
+ /** unique_id prefix of the content claims. */
34
+ export const CONTENT_CLAIM_PREFIX = 'cas::';
35
+
36
+ /** What a linked copy's done:: (or run::) record says about its link. */
37
+ export type LinkedMarker = {
38
+ /** Storage path of the original whose index this copy shares. */
39
+ original: string;
40
+ /** The claim id the link was made under ("cas::<scope>::<key>"), when recorded. */
41
+ claim?: string;
42
+ /** When the link was written (ms), when recorded. */
43
+ linkedAt?: number;
44
+ /** The copy's own access group, when recorded. */
45
+ group?: string | number | null;
46
+ /** The copy's uploader, when recorded. */
47
+ owner?: string | null;
48
+ /** The content key the copy was linked under, when recorded. */
49
+ contentKey?: string;
50
+ };
51
+
52
+ /** The link a done:: or run:: record's `data` describes, or null when it is not a linked copy's. */
53
+ export function linkedMarkerOf(data: any): LinkedMarker | null {
54
+ if (!data || typeof data !== 'object' || data.linked !== true) return null;
55
+ var original = typeof data.alias_of === 'string' ? data.alias_of : '';
56
+ if (!original) return null;
57
+ var at = Number(data.completed_at || data.finished || data.linked_at);
58
+ return {
59
+ original: original,
60
+ claim: typeof data.alias_claim === 'string' && data.alias_claim ? data.alias_claim : undefined,
61
+ linkedAt: isFinite(at) && at > 0 ? at : undefined,
62
+ group: data.copy_group !== undefined ? data.copy_group : undefined,
63
+ owner: typeof data.copy_owner === 'string' ? data.copy_owner : undefined,
64
+ contentKey: typeof data.content_key === 'string' && data.content_key ? data.content_key : undefined,
65
+ };
66
+ }
67
+
68
+ /** The last segment of a storage path. */
69
+ export function fileNameOf(path: string): string {
70
+ var s = String(path || '');
71
+ var at = s.lastIndexOf('/');
72
+ return at === -1 ? s : s.slice(at + 1);
73
+ }
74
+
75
+ export type CopyStatusKind = 'linked' | 'waiting' | 'original_failed' | 'original_removed';
76
+
77
+ export type CopyStatus = {
78
+ kind: CopyStatusKind;
79
+ /** Storage path of the original. */
80
+ original: string;
81
+ /** The chip's text. */
82
+ label: string;
83
+ /** The chip's tooltip. */
84
+ title: string;
85
+ /** True for the two states in which the copy has no index anyone can search (red). */
86
+ broken: boolean;
87
+ };
88
+
89
+ /** What the original's own markers say, for copyStatusOf. */
90
+ export type OriginalState = {
91
+ /** The original has a done:: marker of its own (not a linked one). */
92
+ done?: boolean;
93
+ /** Its newest run:: record's status, when there is one. */
94
+ run?: string;
95
+ /** The content key its own done:: marker records (the MCP writes it when the original
96
+ * finishes), when known. Different from the copy's: the original now holds other content. */
97
+ contentKey?: string;
98
+ };
99
+
100
+ /**
101
+ * A linked copy's status for the Files page and the widget:
102
+ * 'original_removed' its claim id is not among the live claims (the original was deleted,
103
+ * or reset and not indexed again), or the original has no markers left;
104
+ * 'original_failed' the original's newest run ended in an error or was cancelled;
105
+ * 'waiting' the original is still being indexed;
106
+ * 'linked' the original is indexed: search and totals count the content once.
107
+ * `liveClaims` is the set of live "cas::" ids (listContentClaims), or null when it could not
108
+ * be read: then the claim is not used as evidence either way.
109
+ */
110
+ export function copyStatusOf(marker: LinkedMarker, original?: OriginalState | null, liveClaims?: Set<string> | null): CopyStatus {
111
+ var name = fileNameOf(marker.original);
112
+ var mk = function (kind: CopyStatusKind, label: string, title: string, broken: boolean): CopyStatus {
113
+ return { kind: kind, original: marker.original, label: label, title: title, broken: broken };
114
+ };
115
+ var o = original || {};
116
+ var claimGone = !!(liveClaims && marker.claim && !liveClaims.has(marker.claim));
117
+ // The original finished with OTHER content (overwritten, and this copy was not sent again:
118
+ // another user's copy, or an overwrite outside the BunnyQuery clients). Its claim id may be
119
+ // live again under a new original of the old content, so the claim alone cannot tell.
120
+ if (o.done && o.contentKey && marker.contentKey && o.contentKey !== marker.contentKey && o.run !== 'working') {
121
+ return mk('original_removed', 'Original removed or failed',
122
+ 'Linked to "' + name + '", which now holds other content. Reindex this file to index it on its own.', true);
123
+ }
124
+ if (claimGone && !(o.run === 'working')) {
125
+ return mk('original_removed', 'Original removed or failed',
126
+ 'Linked to "' + name + '", which is no longer indexed. Reindex this file to index it on its own.', true);
127
+ }
128
+ if (o.run === 'error' || o.run === 'cancelled') {
129
+ return mk('original_failed', 'Original removed or failed',
130
+ 'Linked to "' + name + '", whose indexing did not finish. Reindex this file to index it on its own.', true);
131
+ }
132
+ if (o.run === 'working' && !o.done) {
133
+ return mk('waiting', 'Waiting for ' + name,
134
+ 'Same content as "' + name + '", which is still being indexed. This file shares its index when it finishes.', false);
135
+ }
136
+ if (!o.done && o.run !== 'done' && liveClaims && !marker.claim) {
137
+ // an old marker without a claim id and an original with no markers at all
138
+ return mk('original_removed', 'Original removed or failed',
139
+ 'Linked to "' + name + '", which is no longer indexed. Reindex this file to index it on its own.', true);
140
+ }
141
+ return mk('linked', 'Indexed via ' + name,
142
+ 'Same content as "' + name + '"; search and totals count it once.', false);
143
+ }
144
+
145
+ /** "1 copy" / "3 copies": the chip on an original. */
146
+ export function copyCountLabel(n: number): string {
147
+ return n === 1 ? '1 copy' : n + ' copies';
148
+ }
149
+
150
+ /** The tooltip of an original's copy chip, naming the copies. */
151
+ export function copyCountTitle(copies: string[]): string {
152
+ var list = copies.slice(0, 10).map(function (p) { return '/' + p; }).join('\n');
153
+ var more = copies.length > 10 ? '\n...and ' + (copies.length - 10) + ' more' : '';
154
+ return 'The same content is also stored as:\n' + list + more + '\nThey share this file\'s index; search and totals count it once.';
155
+ }
156
+
157
+ /** Copies per original, oldest link first: Map(original path -> copy paths). */
158
+ export function copiesByOriginal(linked: Map<string, LinkedMarker> | { [path: string]: LinkedMarker }): Map<string, string[]> {
159
+ var entries: [string, LinkedMarker][] = linked instanceof Map
160
+ ? Array.from(linked.entries())
161
+ : Object.keys(linked).map(function (k) { return [k, (linked as any)[k]] as [string, LinkedMarker]; });
162
+ entries.sort(function (a, b) {
163
+ return (a[1].linkedAt || 0) - (b[1].linkedAt || 0) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
164
+ });
165
+ var out = new Map<string, string[]>();
166
+ for (var i = 0; i < entries.length; i++) {
167
+ var o = entries[i][1].original;
168
+ if (!out.has(o)) out.set(o, []);
169
+ (out.get(o) as string[]).push(entries[i][0]);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /**
175
+ * A short duration for a link ("0.4 s", "1.9 s", "12 s", then formatIndexDuration's words).
176
+ * A link takes about a second, so the whole-second helper would print nothing for it.
177
+ */
178
+ export function formatLinkDuration(ms?: number): string {
179
+ if (typeof ms !== 'number' || !isFinite(ms) || ms < 0) return '';
180
+ if (ms < 10000) return (Math.max(ms, 100) / 1000).toFixed(1) + ' s';
181
+ return formatIndexDuration(ms);
182
+ }
183
+
184
+ /** The chat indexing row's line for a linked copy: "Same content as A: linked in 0.4 s, no AI used". */
185
+ export function linkedRowLabel(original: string, ms?: number): string {
186
+ var took = formatLinkDuration(ms);
187
+ return 'Same content as ' + fileNameOf(original) + ': linked' + (took ? ' in ' + took : '') + ', no AI used';
188
+ }
189
+
190
+ /**
191
+ * A linked pass's answer, as the worker writes it ("[skapi] Same content as "A.tif": linked
192
+ * to its index in 1.9 s, no AI used. ..."), read back: { original (the file NAME it gives),
193
+ * ms }, or null for any other text.
194
+ */
195
+ export function parseLinkedReply(text: any): { original: string; ms?: number } | null {
196
+ if (typeof text !== 'string' || text.indexOf('[skapi] Same content as "') === -1) return null;
197
+ var m = /\[skapi\] Same content as "([^"]+)": linked to its index(?: in ([0-9]+(?:\.[0-9]+)?) s)?/.exec(text);
198
+ if (!m) return null;
199
+ var secs = m[2] !== undefined ? Number(m[2]) : NaN;
200
+ return { original: m[1], ms: isFinite(secs) ? Math.round(secs * 1000) : undefined };
201
+ }
202
+
203
+ // ------------------------------------------------------------------- promotion
204
+
205
+ /** Who sends the copies again: the signed-in user, and whether they own the project. */
206
+ export type PromotionActor = { userId?: string | null; isProjectOwner?: boolean };
207
+
208
+ /**
209
+ * The linked copies `actor` may send to indexing again (review 2026-11-26): every copy for the
210
+ * project owner, otherwise only the copies the actor uploaded (the marker's copy_owner). Another
211
+ * user's copy is never re-indexed from this user's session: it would read that user's file
212
+ * (perhaps a private one) and write its index under this user's records and upload group. A copy
213
+ * left out keeps its link; once the original holds other content the server answers it as having
214
+ * no index, the Files page shows it red ("Original removed or failed") and its Reindex fixes it.
215
+ */
216
+ export function promotableCopies(
217
+ linked: Map<string, LinkedMarker> | { [path: string]: LinkedMarker },
218
+ actor: PromotionActor,
219
+ ): Map<string, LinkedMarker> {
220
+ var entries: [string, LinkedMarker][] = linked instanceof Map
221
+ ? Array.from(linked.entries())
222
+ : Object.keys(linked).map(function (k) { return [k, (linked as any)[k]] as [string, LinkedMarker]; });
223
+ var out = new Map<string, LinkedMarker>();
224
+ for (var i = 0; i < entries.length; i++) {
225
+ var m = entries[i][1];
226
+ if (actor.isProjectOwner || (!!actor.userId && !!m && m.owner === actor.userId)) out.set(entries[i][0], m);
227
+ }
228
+ return out;
229
+ }
230
+
231
+ /**
232
+ * The copies to send again when originals go away (a delete, a folder delete, an Overwrite
233
+ * of an original), per original, oldest first. The first copy of each list becomes the new
234
+ * original (one real AI run, sent with the share flag so it claims the content); the others
235
+ * are sent after it and link to it. Copies that are themselves being removed are left out, and
236
+ * with `actor`, the copies that user may not re-index (promotableCopies).
237
+ * `removed`: the storage paths going away; `removedFolders`: folder paths whose whole
238
+ * content goes away.
239
+ */
240
+ export function copiesToPromote(
241
+ linked: Map<string, LinkedMarker> | { [path: string]: LinkedMarker },
242
+ removed: string[],
243
+ removedFolders?: string[],
244
+ actor?: PromotionActor | null,
245
+ ): { original: string; copies: string[] }[] {
246
+ if (actor) linked = promotableCopies(linked, actor);
247
+ var gone = new Set<string>(removed || []);
248
+ var folders = (removedFolders || []).filter(Boolean).map(function (f) { return f.replace(/\/+$/, '') + '/'; });
249
+ var isGone = function (p: string): boolean {
250
+ if (gone.has(p)) return true;
251
+ for (var i = 0; i < folders.length; i++) if (p.indexOf(folders[i]) === 0) return true;
252
+ return false;
253
+ };
254
+ var out: { original: string; copies: string[] }[] = [];
255
+ copiesByOriginal(linked).forEach(function (copies, original) {
256
+ if (!isGone(original)) return;
257
+ var keep = copies.filter(function (c) { return !isGone(c); });
258
+ if (keep.length) out.push({ original: original, copies: keep });
259
+ });
260
+ return out;
261
+ }
262
+
263
+ // ------------------------------------------------------------------------ reads
264
+
265
+ function listOf(res: any): any[] {
266
+ return (res && Array.isArray(res.list)) ? res.list : [];
267
+ }
268
+
269
+ /**
270
+ * The live content claim ids of a project ("cas::..."), from one prefix listing of unique
271
+ * ids (open to every signed-in caller, whatever group the claim is in), or null when it
272
+ * could not be read or was cut off (then absence proves nothing).
273
+ */
274
+ export async function listContentClaims(skapi: any, service: string, maxPages = 5): Promise<Set<string> | null> {
275
+ if (!skapi || typeof skapi.getUniqueId !== 'function' || !service) return null;
276
+ try {
277
+ var out = new Set<string>();
278
+ var fetchMore = false;
279
+ for (var page = 0; page < maxPages; page++) {
280
+ var res: any = await skapi.getUniqueId(
281
+ { service: service, unique_id: CONTENT_CLAIM_PREFIX, condition: 'gte' },
282
+ { limit: 1000, fetchMore: fetchMore },
283
+ );
284
+ var list = listOf(res);
285
+ for (var i = 0; i < list.length; i++) {
286
+ var id = typeof list[i] === 'string' ? list[i] : (list[i] && list[i].unique_id);
287
+ if (typeof id === 'string' && id.indexOf(CONTENT_CLAIM_PREFIX) === 0) out.add(id);
288
+ }
289
+ if (!res || res.endOfList !== false) return out;
290
+ fetchMore = true;
291
+ }
292
+ return null;
293
+ } catch (err: any) {
294
+ var msg = String((err && (err.code || err.message)) || err || '');
295
+ if (/NOT_EXISTS|not exist/i.test(msg)) return new Set<string>();
296
+ return null;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Every linked copy of a project, fresh: Map(copy path -> LinkedMarker), from the done::
302
+ * markers tagged "bq_linked". Null when it could not be read. Used before a delete or an
303
+ * Overwrite, where a 30-second-old sweep could miss a copy linked a moment ago.
304
+ */
305
+ export async function listLinkedCopies(skapi: any, service: string, maxPages = 10): Promise<Map<string, LinkedMarker> | null> {
306
+ if (!skapi || typeof skapi.getRecords !== 'function' || !service) return null;
307
+ var out = new Map<string, LinkedMarker>();
308
+ try {
309
+ var fetchMore = false;
310
+ for (var page = 0; page < maxPages; page++) {
311
+ var res: any = await skapi.getRecords(
312
+ { service: service, table: { name: '__INDEXING__', access_group: 'authorized' }, tag: LINKED_COPY_TAG },
313
+ { limit: 1000, fetchMore: fetchMore },
314
+ );
315
+ var list = listOf(res);
316
+ for (var i = 0; i < list.length; i++) {
317
+ var r = list[i] || {};
318
+ var uid = String(r.unique_id || '');
319
+ if (uid.indexOf('done::') !== 0) continue;
320
+ var mk = linkedMarkerOf(r.data);
321
+ if (mk) out.set(uid.slice(6), mk);
322
+ }
323
+ if (!res || res.endOfList !== false) return out;
324
+ fetchMore = true;
325
+ }
326
+ return out;
327
+ } catch (err: any) {
328
+ var msg = String((err && (err.code || err.message)) || err || '');
329
+ if (/NOT_EXISTS|not exist/i.test(msg)) return out;
330
+ return null;
331
+ }
332
+ }
333
+
334
+ // ------------------------------------------------- "Find identical files" (owner)
335
+
336
+ export type IdenticalFileEntry = { path: string; group?: any; uploader?: string | null; indexed?: boolean; indexed_at?: number | null };
337
+ export type IdenticalGroup = { content_key: string; original: IdenticalFileEntry; copies: IdenticalFileEntry[] };
338
+ export type IdenticalScan = { complete: boolean; scanned: number; total: number; groups: IdenticalGroup[]; skipped?: { path: string; reason: string }[] };
339
+
340
+ function bodyOf(res: any): any {
341
+ if (typeof res === 'string') {
342
+ try { return JSON.parse(res); } catch (_) { return res; }
343
+ }
344
+ return res;
345
+ }
346
+
347
+ function errorText(err: any): string {
348
+ var b = err && (err.body || err.data || err.response);
349
+ var bb = bodyOf(b);
350
+ if (bb && typeof bb === 'object') {
351
+ if (typeof bb.reason === 'string') return bb.reason;
352
+ if (typeof bb.message === 'string') return bb.message;
353
+ }
354
+ if (typeof bb === 'string' && bb) return bb;
355
+ return String((err && err.message) || err || 'The request failed.');
356
+ }
357
+
358
+ async function callMcpRoute(route: string, args: { service: string; owner?: string }, data: any): Promise<any> {
359
+ var base = String(chatEngineConfig().mcpBaseUrl || '').replace(/\/+$/, '');
360
+ if (!base) throw new Error('No BunnyQuery server is configured.');
361
+ var res = await resolveForwardRequest()({
362
+ service: args.service,
363
+ ...(args.owner ? { owner: args.owner } : {}),
364
+ url: base + route,
365
+ method: 'POST',
366
+ headers: { 'content-type': 'application/json', Authorization: 'Bearer $ACCESS_TOKEN' },
367
+ data: Object.assign({ project_id: args.service }, data),
368
+ });
369
+ return bodyOf(res);
370
+ }
371
+
372
+ /**
373
+ * The owner's scan for identical files that are indexed separately (MCP
374
+ * /internal/identical-files). Calls again while the server says it is not complete (each
375
+ * call keeps what the last one read), up to `maxCalls`. `onProgress` hears each answer.
376
+ * Rejects with the server's words when it refuses (not the owner, no session).
377
+ */
378
+ export async function findIdenticalFiles(
379
+ args: { service: string; owner?: string; maxCalls?: number; budgetS?: number; onProgress?: (scan: IdenticalScan) => void },
380
+ ): Promise<IdenticalScan> {
381
+ var calls = Math.max(1, args.maxCalls || 12);
382
+ var last: IdenticalScan | null = null;
383
+ for (var i = 0; i < calls; i++) {
384
+ var body: any;
385
+ try {
386
+ // a short budget per call: the relay ends a request after about 29 s, and what one
387
+ // call read is kept on the server for the next
388
+ body = await callMcpRoute('/internal/identical-files', args, { budget_s: args.budgetS || 8 });
389
+ } catch (err) {
390
+ var msg = errorText(err);
391
+ // timed out at the relay: the server kept what it read, so ask again
392
+ if (/timed? ?out|timeout|504/i.test(msg) && i < calls - 1) continue;
393
+ throw new Error(msg);
394
+ }
395
+ if (!body || typeof body !== 'object' || !Array.isArray(body.groups)) {
396
+ throw new Error(typeof body === 'string' && body ? body : 'The server did not answer the scan.');
397
+ }
398
+ last = { complete: !!body.complete, scanned: Number(body.scanned) || 0, total: Number(body.total) || 0, groups: body.groups, skipped: body.skipped };
399
+ if (args.onProgress) args.onProgress(last);
400
+ if (last.complete) return last;
401
+ }
402
+ return last as IdenticalScan;
403
+ }
404
+
405
+ /**
406
+ * Link one copy to an original the owner confirmed (MCP /internal/identical-link, no AI):
407
+ * the copy's own index is removed and it shares the original's. Resolves to the server's
408
+ * answer ({ linked: true, ... }) or { linked: false, reason } when it was refused. Never
409
+ * rejects.
410
+ */
411
+ export async function linkIdenticalFile(
412
+ args: { service: string; owner?: string; copy: string; original: string },
413
+ ): Promise<{ linked: boolean; reason?: string; [k: string]: any }> {
414
+ // A merge can outlast the request relay (about 29 s: the copy's own index is removed
415
+ // first). The server finishes it anyway, and the route is idempotent (an already linked
416
+ // copy answers linked: true at once), so a timed-out call is asked again.
417
+ var last = '';
418
+ for (var attempt = 0; attempt < 4; attempt++) {
419
+ try {
420
+ var body = await callMcpRoute('/internal/identical-link', args, { copy: args.copy, original: args.original });
421
+ if (body && typeof body === 'object' && typeof body.linked === 'boolean') return body;
422
+ return { linked: false, reason: typeof body === 'string' && body ? body : 'unexpected answer' };
423
+ } catch (err) {
424
+ last = errorText(err);
425
+ if (!/timed? ?out|timeout|504/i.test(last)) return { linked: false, reason: last };
426
+ await new Promise(function (r) { setTimeout(r, 8000); });
427
+ }
428
+ }
429
+ return { linked: false, reason: last || 'timed out' };
430
+ }
431
+
432
+ /** Plain words for identical-link's refusal reasons. */
433
+ export function identicalLinkReasonText(reason?: string): string {
434
+ switch (reason) {
435
+ case 'not_identical': return 'the two files no longer have the same content';
436
+ case 'original_not_indexed': return 'the original is not indexed';
437
+ case 'original_is_a_copy': return 'the original is itself a linked copy';
438
+ case 'less_open_original': return 'the original can be read by fewer people than the copy';
439
+ case 'private_original': return 'the original is private';
440
+ case 'private_copy': return 'the copy is another user\'s private file: it shares the index once that user indexes it again';
441
+ case 'content_claimed_by_another_file': return 'another file already holds this content\'s index';
442
+ case 'not_readable': return 'one of the files could not be read from storage';
443
+ case 'different_kind': return 'the files are of different kinds';
444
+ case 'no_file_record': return 'one of the files has no index record';
445
+ case 'unshared_access_group': return 'the file\'s access group cannot share an index';
446
+ default: return reason || 'refused';
447
+ }
448
+ }
@@ -265,6 +265,7 @@ export {
265
265
  buildChatDisplayList,
266
266
  parseIndexingLabel,
267
267
  indexGroupDurationLabel,
268
+ indexGroupLinkedLabel,
268
269
  runRecordDurationMs,
269
270
  type DisplayEntry,
270
271
  type IndexingGroup,
@@ -315,6 +316,7 @@ export {
315
316
  // response extraction
316
317
  extractClaudeText,
317
318
  extractOpenAIText,
319
+ providerDocument,
318
320
  // content transforms
319
321
  transformContentWithImages,
320
322
  transformContentWithOpenAIImages,
@@ -366,6 +368,12 @@ export {
366
368
  normalizeSkipDuplicateFiles,
367
369
  skipDuplicateFilesFrom,
368
370
  projectSkipDuplicateFiles,
371
+ // one shared index for identical files (same record, its own key, on by default)
372
+ SHARE_IDENTICAL_FILES_KEY,
373
+ DEFAULT_SHARE_IDENTICAL_FILES,
374
+ normalizeShareIdenticalFiles,
375
+ shareIdenticalFilesFrom,
376
+ projectShareIdenticalFiles,
369
377
  // chat answer mode (same record, its own `answer_mode` key, standard by default)
370
378
  ANSWER_MODES,
371
379
  DEFAULT_ANSWER_MODE,
@@ -402,3 +410,36 @@ export {
402
410
  type ProjectSettingsReader,
403
411
  type AnswerMode,
404
412
  } from './project_settings';
413
+
414
+ // One shared index for identical files (identical.ts): a linked copy's status and words,
415
+ // which copies to send again when an original goes away, and the owner's "Find identical
416
+ // files" calls. Both clients render from these, so the Files page, agent.vue and the
417
+ // widget say the same thing.
418
+ export {
419
+ LINKED_COPY_TAG,
420
+ CONTENT_CLAIM_PREFIX,
421
+ linkedMarkerOf,
422
+ fileNameOf,
423
+ copyStatusOf,
424
+ copyCountLabel,
425
+ copyCountTitle,
426
+ copiesByOriginal,
427
+ formatLinkDuration,
428
+ linkedRowLabel,
429
+ parseLinkedReply,
430
+ copiesToPromote,
431
+ promotableCopies,
432
+ listContentClaims,
433
+ listLinkedCopies,
434
+ findIdenticalFiles,
435
+ linkIdenticalFile,
436
+ identicalLinkReasonText,
437
+ type LinkedMarker,
438
+ type PromotionActor,
439
+ type CopyStatus,
440
+ type CopyStatusKind,
441
+ type OriginalState,
442
+ type IdenticalFileEntry,
443
+ type IdenticalGroup,
444
+ type IdenticalScan,
445
+ } from './identical';
@@ -68,6 +68,7 @@ import { isPagedReadFile, isImageVisionFile } from './office';
68
68
  import { windowedIndexingEnabled } from './config';
69
69
  import { MAX_INDEXING_RESUME_PASSES } from './requests';
70
70
  import { messageTimeMs, formatIndexDuration } from './time';
71
+ import { parseLinkedReply, linkedRowLabel } from './identical';
71
72
 
72
73
  export type IndexingGroupStatus = 'active' | 'done' | 'error' | 'cancelled';
73
74
 
@@ -229,6 +230,12 @@ export type IndexingGroup = {
229
230
  * it through indexGroupDurationLabel, which also holds it back from any row that is
230
231
  * not a finished 'done'. */
231
232
  durationMs?: number;
233
+ /** This run LINKED the file to an already indexed file with the same content (one
234
+ * shared index for identical files, identical.ts): no AI ran and the file has no
235
+ * rows or pages of its own. `original` is the original's storage path when the run::
236
+ * record named it, else the file name the linked pass's answer gave; `ms` how long
237
+ * the link took. Read it through indexGroupLinkedLabel. */
238
+ linked?: { original: string; ms?: number };
232
239
  };
233
240
 
234
241
  export type DisplayEntry =
@@ -318,6 +325,13 @@ export type RunStubInfo = {
318
325
  /** Chat that owns this run. Absent on records minted before it was
319
326
  * stamped; see BuildDisplayListOptions.stubPlatform. */
320
327
  platform?: 'claude' | 'openai';
328
+ /** The run linked the file to an identical file's index (identical.ts): the record's
329
+ * `linked: true` and the original's storage path (`alias_of`). */
330
+ linked?: boolean;
331
+ alias_of?: string;
332
+ /** How long the link itself took on the server (ms); the record's started..finished
333
+ * span also holds the time the pass waited in the queue, so it is not used. */
334
+ link_ms?: number;
321
335
  };
322
336
 
323
337
  /** Canonical form of an indexing key for COMPARISON only (never for storage).
@@ -544,6 +558,16 @@ export function indexGroupDurationLabel(group?: IndexingGroup | null): string {
544
558
  return formatIndexDuration(group.durationMs);
545
559
  }
546
560
 
561
+ /**
562
+ * A linked copy's row line ("Same content as A.tif: linked in 0.4 s, no AI used"), or ''
563
+ * for any other row. Shared so agent.vue and the widget print the same text in the same
564
+ * place (they show it instead of the pass count and duration).
565
+ */
566
+ export function indexGroupLinkedLabel(group?: IndexingGroup | null): string {
567
+ if (!group || !group.linked || group.status !== 'done') return '';
568
+ return linkedRowLabel(group.linked.original, group.linked.ms);
569
+ }
570
+
547
571
  export function buildChatDisplayList(
548
572
  messages: ChatMessage[],
549
573
  opts?: BuildDisplayListOptions,
@@ -876,6 +900,17 @@ export function buildChatDisplayList(
876
900
  var vm = grp.members[vi];
877
901
  if (vm.msg._indexComplete) sawComplete = true;
878
902
  if (!isHiddenPass(vm.msg)) grp.visibleMembers.push(vm);
903
+ // A pass the worker LINKED to an identical file's index answers in a fixed
904
+ // form (identical.ts parseLinkedReply): no AI ran, and nothing follows it.
905
+ if (vm.msg.role === 'assistant' && !vm.msg.isError && !grp.linked) {
906
+ var linkedReply = parseLinkedReply(vm.msg.content);
907
+ if (linkedReply) grp.linked = linkedReply;
908
+ }
909
+ }
910
+ if (grp.linked && grp.status !== 'active' && grp.status !== 'cancelled') {
911
+ // the link IS the end of the run, whoever would have driven it
912
+ grp.status = 'done';
913
+ sawComplete = true;
879
914
  }
880
915
  // Mirrors ChatSession.maybeResumeIndexing's own routing, which is what makes
881
916
  // the answer match who will actually dispatch the next pass.
@@ -923,7 +958,7 @@ export function buildChatDisplayList(
923
958
  // deterministic completion), it answers without any queue round
924
959
  // trip. Gated on the queue NOT claiming the file live, so a
925
960
  // re-index whose marker-cascade delete lagged still shows yellow.
926
- grp.finished = !newestRunOfKey[order[oi]] ||
961
+ grp.finished = !newestRunOfKey[order[oi]] || !!grp.linked ||
927
962
  (!!doneKeys[grp.key] && !liveIndexKeys[grp.key]) ||
928
963
  (liveIndexChecked && !liveIndexKeys[grp.key]);
929
964
  }
@@ -1199,6 +1234,8 @@ export function buildChatDisplayList(
1199
1234
  ? 'Indexing did not finish.' : undefined),
1200
1235
  // The stub IS the record, so a 'done' record's span is this run's.
1201
1236
  durationMs: st === 'done' ? runRecordDurationMs(rec) : undefined,
1237
+ linked: st === 'done' && rec.linked && rec.alias_of
1238
+ ? { original: rec.alias_of, ms: typeof rec.link_ms === 'number' ? rec.link_ms : undefined } : undefined,
1202
1239
  };
1203
1240
  // A record with no `started` cannot be placed in the conversation.
1204
1241
  // Infinity sorts it to the END (nearest the newest turns) instead of
@@ -1241,6 +1278,10 @@ export function buildChatDisplayList(
1241
1278
  stubList.push({ started: trec.started, group: tg });
1242
1279
  overlayRunRecordVerdict(tg, trec, liveIndexKeys);
1243
1280
  tg.durationMs = runRecordGroupDurationMs(tg, trec);
1281
+ // the record names the original by its storage path; the answer only by name
1282
+ if (trec.linked && trec.alias_of && trec.status === 'done') {
1283
+ tg.linked = { original: trec.alias_of, ms: tg.linked && tg.linked.ms !== undefined ? tg.linked.ms : (typeof trec.link_ms === 'number' ? trec.link_ms : undefined) };
1284
+ }
1244
1285
  }
1245
1286
  }
1246
1287
  stubList.sort(function (a, b) { return a.started - b.started; });
@@ -32,6 +32,8 @@ export type FileUrlDirective = {
32
32
  path: string;
33
33
  /** The exact baked url string in the request body to replace with a fresh one. */
34
34
  url: string;
35
+ /** Indexing first pass only: link to an indexed file with the same bytes (see requests.ts). */
36
+ share_identical?: boolean;
35
37
  };
36
38
 
37
39
  // Files whose text the worker extracts SERVER-SIDE and inlines for indexing,