bunnyquery 1.20.1 → 1.21.3

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.d.mts CHANGED
@@ -1,149 +1,3 @@
1
- /**
2
- * Retrieval memory: a compact note of what a chat turn RETRIEVED, kept with the
3
- * turn so a follow-up question skips discovery.
4
- *
5
- * THE PROBLEM. The provider runs the tool loop on its side and history keeps
6
- * only the answer text (budget.ts), so on "and what does page 3 say?" the model
7
- * starts from nothing: it looks the file up again, guesses a table and an access
8
- * group again, and routinely lands somewhere else, which is how an answer flips
9
- * between two turns about the same document.
10
- *
11
- * WHAT THE ENGINE CAN SEE. The provider's final body carries the tool loop:
12
- * - Anthropic Messages: content[] blocks `mcp_tool_use` (name, input) and
13
- * `mcp_tool_result` (content), plus `server_tool_use` / `web_*_tool_result`
14
- * for the built-in web tools;
15
- * - OpenAI Responses: output[] items `mcp_call` (name, arguments as a JSON
16
- * string, output as a string) and `web_search_call`.
17
- * The polling worker stores that body on the row (spilling to S3 past 300 KB,
18
- * never truncating), and a streamed turn's assembled body keeps the same blocks
19
- * (sse.ts copies each block's skeleton and its JSON input verbatim), so the
20
- * same reader works live, after a stream and after a reload. When a body has no
21
- * tool blocks at all (a host that strips them, a provider shape this does not
22
- * know), the note falls back to what the ANSWER names: db: file links and src::
23
- * paths. Nothing is ever invented: an empty note is null, not a guess.
24
- *
25
- * WHAT IS KEPT, per turn: files (storage paths), tables, access groups,
26
- * searchText hits as path + page, the tool names, and whether a web tool ran.
27
- * Arguments are read by KEY, never by position, and only the keys the
28
- * BunnyQuery tools use for those four things; a query's filter values, a
29
- * record's data and a tool result's text are never copied, so the note cannot
30
- * leak a page of a document into every later turn.
31
- *
32
- * HOW IT REACHES THE MODEL. buildBoundedChatMessages appends the formatted note
33
- * to the LLM copy of the assistant turn it belongs to (never the displayed
34
- * bubble), for the newest RETRIEVAL_NOTES_MAX turns and within
35
- * RETRIEVAL_NOTES_TOKEN_BUDGET tokens, so the memory is bounded however long
36
- * the chat gets. A host that never attaches `_retrieval` sees byte-identical
37
- * requests to today.
38
- */
39
- type RetrievalHit = {
40
- path: string;
41
- page: number;
42
- };
43
- type RetrievalNote = {
44
- /** Storage paths (the part after "src::") the turn read, queried or linked. */
45
- files: string[];
46
- /** Table names the turn queried. */
47
- tables: string[];
48
- /** Access groups the turn queried at, as written in the call. */
49
- accessGroups: string[];
50
- /** searchText hits: the page a term was found on, per file. */
51
- hits: RetrievalHit[];
52
- /** Tool names, in order of first use. */
53
- tools: string[];
54
- /** A web tool ran in this turn (web_search / web_fetch). */
55
- web: boolean;
56
- /** 'tools' when read off the body's tool blocks; 'answer' when only the
57
- * answer text was available to read. */
58
- source: 'tools' | 'answer' | 'body';
59
- };
60
- /** How many of the newest turns carry their note into the request. */
61
- declare const RETRIEVAL_NOTES_MAX = 6;
62
- /** Ceiling on the estimated tokens all carried notes may add to one request. */
63
- declare const RETRIEVAL_NOTES_TOKEN_BUDGET = 1200;
64
- /** Per-list cap inside one note (files, tables, groups, hits, tools). */
65
- declare const RETRIEVAL_NOTE_MAX_ITEMS = 8;
66
- /** Hard cap on one formatted note. */
67
- declare const RETRIEVAL_NOTE_MAX_CHARS = 600;
68
- /** The marker a carried note opens with; also what keeps it out of the model's own voice. */
69
- declare const RETRIEVAL_NOTE_PREFIX = "[Retrieval note, not shown to the user";
70
- /**
71
- * What an ANSWER names: db: file links ("[name](db:path)") and src:: ids. The
72
- * fallback for a body with no tool blocks, and merged into a tool note too so a
73
- * file the model linked but never queried (it knew the path from history) is
74
- * still remembered.
75
- */
76
- declare function retrievalNoteFromText(text: string | null | undefined): RetrievalNote | null;
77
- /**
78
- * The note for one assistant turn: the body's tool loop when it has one, else
79
- * what the answer names, else null. `answerText` is the extracted answer, read
80
- * for file links in both cases.
81
- */
82
- declare function extractRetrievalNote(body: any, answerText?: string | null): RetrievalNote | null;
83
- /**
84
- * True when `body` is a provider response this module can read: an Anthropic
85
- * Messages body (`content` array) or an OpenAI Responses body (`output` array).
86
- */
87
- declare function providerBodyWasRead(body: any): boolean;
88
- /** True when the value is a note this module produced (or an equivalent shape). */
89
- declare function isRetrievalNote(value: any): value is RetrievalNote;
90
- /**
91
- * One line the model reads. Sections are omitted when empty, the whole thing is
92
- * capped at RETRIEVAL_NOTE_MAX_CHARS, and it opens with RETRIEVAL_NOTE_PREFIX so
93
- * the model can tell it from its own earlier words. Returns '' for an empty note.
94
- */
95
- declare function formatRetrievalNote(note: RetrievalNote | null | undefined): string;
96
-
97
- /**
98
- * Saved search findings (owner, 2026-11-20): where a hard search found its answer, kept in
99
- * the project's database so the same question, from anyone, later goes straight to the page.
100
- *
101
- * WHAT IS SAVED: the LOCATION, never the answer. One record per file page in table
102
- * "search_findings", unique_id "find::<path>#p<page>", reference "src::<path>" (so a
103
- * re-index or a delete of the file removes its findings through the cascade), the file's own
104
- * access group (a finding is never visible to someone who cannot read the file), and tags:
105
- * the key words of the question and the search terms that found the page, normalized the way
106
- * every BunnyQuery tag is (tagForms). The chat reads the page again before answering, so a
107
- * finding can never replay an outdated answer; it only skips the hunt.
108
- *
109
- * WHEN: after a chat turn that needed a real search (FINDING_MIN_TOOL_CALLS or more tool
110
- * calls) and whose answer links a file that a searchText hit found on a page, or, when the
111
- * turn read the file with readFileContent instead, the pages its answer cites of that file. Read from the
112
- * provider body the turn already has, by the engine, so it costs no model step. Nothing is
113
- * invented: no hit on a linked file, no finding. No page text and no result text is copied.
114
- *
115
- * The engine never writes records itself: the host's saveSearchFinding hook does (config.ts).
116
- */
117
-
118
- declare const FINDINGS_TABLE = "search_findings";
119
- declare const FINDING_ID_PREFIX = "find::";
120
- /** The words of a question or a search term that say WHAT is looked for. */
121
- declare function keyWords(text: string | null | undefined): string[];
122
- type SearchFinding = {
123
- storagePath: string;
124
- page: number;
125
- uniqueId: string;
126
- tags: string[];
127
- data: {
128
- path: string;
129
- page: number;
130
- question_words: string[];
131
- search_terms: string[];
132
- found_at: number;
133
- };
134
- };
135
- /**
136
- * The findings one finished chat turn earns, or [] (see the file comment for the rules).
137
- * `note` is the turn's retrieval note (its searchText hits and the files its answer links).
138
- */
139
- declare function findingsForTurn(args: {
140
- question: string | null | undefined;
141
- body: any;
142
- note: RetrievalNote | null | undefined;
143
- answer: string | null | undefined;
144
- now?: number;
145
- }): SearchFinding[];
146
-
147
1
  /**
148
2
  * Client-side attachment-parser plugins.
149
3
  *
@@ -499,6 +353,27 @@ declare function patchProjectSettings(service: string, patch: ProjectSettingsDat
499
353
  */
500
354
  declare function clearProjectSettings(service?: string): void;
501
355
 
356
+ /**
357
+ * Engine configuration / dependency injection.
358
+ *
359
+ * The engine is framework- and transport-agnostic: it never imports a skapi
360
+ * instance or `import.meta.env`. Each consumer calls `configureChatEngine()`
361
+ * once at startup to inject the skapi transport functions, the MCP base URL,
362
+ * and (optionally) the `poll` value to attach to every forwarded request.
363
+ *
364
+ * Why `poll` is configurable: agent.vue uses the npm-bundled skapi-js and OMITS
365
+ * `poll` (its request auto-resolves with the final body), whereas
366
+ * the BunnyQuery widget uses the deployed skapi-js@latest and must pass
367
+ * `poll: 0` to get the early ack + a manual `.poll()` handle (needed for queued-
368
+ * send cancel). So the request builders include `poll` only when it is set.
369
+ *
370
+ * THE TRANSPORT IS THE forwardRequest FAMILY ONLY (owner, 2026-11-20: clientSecretRequest
371
+ * is being deprecated). The old `clientSecretRequest*` keys are no longer read: a host
372
+ * injects `forwardRequest`, `forwardRequestHistory` and, to stream,
373
+ * `forwardRequestFinalize` and `forwardRequestStream`, all from skapi-js 2.1.0 or newer.
374
+ * Every call goes through the resolveForwardRequest* functions below.
375
+ */
376
+
502
377
  /**
503
378
  * One report about a turn that is streaming, as handed to `onLiveStreamUpdate`.
504
379
  *
@@ -553,6 +428,7 @@ type ForwardRequestFinalizeFn = (requestId: string, data: any, options: {
553
428
  method: string;
554
429
  service?: string;
555
430
  owner?: string;
431
+ ifAbsent?: boolean;
556
432
  }) => Promise<any>;
557
433
  /** The chunk read-back call, identical under its new and its deprecated key. */
558
434
  type ForwardRequestStreamFn = (requestId: string, options: {
@@ -616,6 +492,16 @@ interface ChatEngineConfig {
616
492
  * until the worker is deployed, then flip it per environment.
617
493
  */
618
494
  windowedIndexing?: boolean;
495
+ /**
496
+ * The worker writes the ending (done:: and run::) of a file read in ONE pass (an image,
497
+ * or any file not rendered, windowed or paged), as it does for paged chains: the engine
498
+ * then no longer marks such a run "Indexing stopped ... (the page was closed)" when no
499
+ * page here kept its chain. The engine always sends the request flag (index_end); this
500
+ * switch only stops the client-side "lost" verdict. Turn it on only once every region's
501
+ * worker and polling-recovery Lambda carry the 2026-11-25 change: with an older worker
502
+ * a page closed mid-pass would leave the run 'working'. Off unless true.
503
+ */
504
+ workerIndexEndings?: boolean;
619
505
  /**
620
506
  * Mint the durable "indexing finished" marker record ("done::<path>",
621
507
  * reference "src::<path>", table __INDEXING__ — same shape the backend
@@ -626,11 +512,13 @@ interface ChatEngineConfig {
626
512
  * only ever inferred here); the worker writes their marker itself.
627
513
  * Must be best-effort: tolerate the marker already existing and never
628
514
  * throw. Optional so older consumers keep the pre-marker inference.
515
+ * May return a promise that rejects when the write failed (not for "already
516
+ * there"): the engine then writes it again, a few times, with backoff.
629
517
  */
630
518
  mintIndexDoneMarker?: (info: {
631
519
  service: string;
632
520
  storagePath: string;
633
- }) => void;
521
+ }) => void | Promise<unknown>;
634
522
  /**
635
523
  * Create-or-update the per-file indexing RUN record ("run::<path>",
636
524
  * reference "src::<path>", table __INDEXING__). The record is the durable
@@ -644,7 +532,9 @@ interface ChatEngineConfig {
644
532
  * overwrite a terminal status (done/error/cancelled) — a late create from
645
533
  * a slow enqueue must not resurrect a run another writer already closed.
646
534
  * Must be best-effort and never throw. Optional: without it the engine
647
- * behaves exactly as before (legacy scan/probe path).
535
+ * behaves exactly as before (legacy scan/probe path). May return a promise
536
+ * that rejects when the write failed: the engine then writes it again, a few
537
+ * times, with backoff.
648
538
  */
649
539
  upsertIndexRunRecord?: (info: {
650
540
  service: string;
@@ -657,7 +547,7 @@ interface ChatEngineConfig {
657
547
  error?: string;
658
548
  queue?: string;
659
549
  };
660
- }) => void;
550
+ }) => void | Promise<unknown>;
661
551
  /**
662
552
  * Deliver each relayed chunk over skapi's WEBSOCKET as well, so text lands as it
663
553
  * is relayed instead of on the next poll tick. Off unless a host asks.
@@ -737,8 +627,8 @@ interface ChatEngineConfig {
737
627
  * `mcp_list_tools` item and OpenAI skips asking the MCP server for its tools again
738
628
  * (four sequential requests, about 0.6 s before the model starts).
739
629
  *
740
- * OFF unless set to `true`. Leave it off until one real OpenAI chat on a dev project
741
- * has answered with it on: an account that refuses the item fails one turn, after
630
+ * OFF unless set to `true` (the widget and bunnyquery.com set it; verified on a live
631
+ * OpenAI chat 2026-11-25). An account that refuses the item fails one turn, after
742
632
  * which reuse stays off for that project in this browser. Costs when on: each
743
633
  * reused turn's request body, and so its stored history row, is about 31 to 34 KB
744
634
  * larger (the tool list), which also comes back with every history page.
@@ -827,18 +717,6 @@ interface ChatEngineConfig {
827
717
  pages_saved?: number;
828
718
  pages_total?: number | null;
829
719
  } | null>;
830
- /**
831
- * Save one search finding (findings.ts): where a hard search found its answer, as a
832
- * record in table "search_findings" with the given unique_id, tags and data, reference
833
- * "src::<storagePath>" and the ACCESS GROUP OF THAT FILE (read it; skip the save when
834
- * the file has no record). When the unique_id is taken, add the new tags to the existing
835
- * record instead. Best effort: never throw into the engine. Optional: without it nothing
836
- * is saved.
837
- */
838
- saveSearchFinding?: (finding: SearchFinding & {
839
- service: string;
840
- owner?: string;
841
- }) => Promise<any> | void;
842
720
  /**
843
721
  * The request ids of one file's indexing passes: the unique ids "pass::<storagePath>#<id>"
844
722
  * the worker writes as each pass starts (getUniqueId, prefix "pass::<storagePath>#", every
@@ -847,9 +725,56 @@ interface ChatEngineConfig {
847
725
  * (ChatSession.loadRunPasses). Without it the history pages the indexing queue as before.
848
726
  */
849
727
  listIndexPasses?: (service: string, storagePath: string) => Promise<string[]>;
728
+ /**
729
+ * THE RECONCILER'S READS (reconciler plan, section 3; skapi-js 2.7.0 or newer). All
730
+ * three are optional, and a host hands over only what its skapi-js has: with
731
+ * `forwardRequestStatus` AND `forwardRequestRead` the engine follows every waiting
732
+ * item with one batch read per look (ChatSession's reconciler) instead of one poll
733
+ * per request; without them it keeps today's polls, and its looks re-attach a
734
+ * failed poll through the old by-id read (csrHistoryItemLookup).
735
+ *
736
+ * skapi.forwardRequestStatus(requests, { service, owner, deadline, fresh, signal }):
737
+ * the status of up to 100 requests per call, no bodies.
738
+ */
739
+ forwardRequestStatus?: (requests: any[], opts?: any) => Promise<{
740
+ list: any[];
741
+ [key: string]: any;
742
+ }>;
743
+ /** skapi.forwardRequestRead({ id, url, method, since, service, owner, deadline, fresh,
744
+ * signal }): one request as an envelope that always carries its status, with a
745
+ * streamed turn's chunks after `since`. Read once per item that just turned terminal. */
746
+ forwardRequestRead?: (params: any) => Promise<any>;
747
+ /** skapi.forwardRequestQueueCounters(queues, { service, owner, deadline, fresh,
748
+ * signal }): the tiny counter rows of up to 20 queues. Read on every look; the
749
+ * requests themselves are read only when a counter moved, on a trigger, or once a
750
+ * minute. Optional even with the two above: without it every look reads statuses. */
751
+ forwardRequestQueueCounters?: (queues: string[], opts?: any) => Promise<{
752
+ queues: {
753
+ [name: string]: any;
754
+ };
755
+ }>;
756
+ /**
757
+ * Ask the host to refresh what it shows of a project's records, because indexing
758
+ * work of that project just settled and none is left in this page's queue. A data
759
+ * hook: called with no chat view mounted too (the files page, the records page), and
760
+ * only in the tab that holds the project's settle lock. Optional; never throws.
761
+ */
762
+ refreshRecords?: (projectId: string) => void;
850
763
  }
851
764
  declare function configureChatEngine(config: ChatEngineConfig): void;
852
765
  declare function chatEngineConfig(): ChatEngineConfig;
766
+ /**
767
+ * The host handed over the reconciler's two reads (batch status and envelope read), so
768
+ * the engine follows waiting items with batch reads instead of one poll each. False on
769
+ * an older skapi-js: the engine then keeps today's polls (see forwardRequestStatus).
770
+ */
771
+ declare function reconcilerReadsEnabled(): boolean;
772
+ /**
773
+ * A send may carry a client reference (`cref`). Only with the reconciler's reads: the
774
+ * same skapi-js (2.7.0) brought both, and an older one drops the key anyway, so a send
775
+ * whose ack was lost could never be matched by it.
776
+ */
777
+ declare function crefSupported(): boolean;
853
778
  /** True when the consumer has opted in to live streaming of chat turns. */
854
779
  /** Socket delivery of the stream: the host asked (`liveStreaming`) AND the turn streams. */
855
780
  /** Request status push is on: the host asked for it and handed over onRequestStatus. */
@@ -980,6 +905,140 @@ declare function streamRecoveryEnabled(): boolean;
980
905
  */
981
906
  declare function skapiSupportsStreaming(sk: any): boolean;
982
907
 
908
+ /**
909
+ * The reconciler's clock and the cross-tab settle lock (reconciler plan, sections 3 and 4b,
910
+ * BUNNYQUERY_CHAT_RECONCILER_PLAN.md).
911
+ *
912
+ * WHAT LIVES HERE. Only the parts that know nothing about chats: one timer chain per page
913
+ * (LookScheduler), the triggers that pull its next look forward, the deadline and the
914
+ * generation that make a hung look harmless, the backoff after a failed look, and the lock
915
+ * that keeps side effects (a next indexing pass, run::/done:: writes, a finalize, a records
916
+ * refresh) to one tab. What a look actually reads and applies is ChatSession's
917
+ * (_reconcileLook in session.ts), handed in as a hook, so this file is testable on its own
918
+ * and the session keeps its own state private.
919
+ *
920
+ * THE RULES IT ENFORCES (owner, 2026-11-24, plan 4b):
921
+ * 1. One loop. One setTimeout handle for the whole page, whatever the number of waiting
922
+ * requests. Scheduling always clears the previous handle first.
923
+ * 2. Returns never add work. A trigger while a look runs sets ONE follow-up look (the
924
+ * triggers are merged), never a second loop or a second timer. A trigger while no look
925
+ * runs starts the look now.
926
+ * 3. A look that does not finish within LOOK_DEADLINE_MS is over: it counts as failed
927
+ * (nothing on screen changes), its in-flight reads are aborted, and anything its
928
+ * generation returns later is ignored by the session (alive() is false).
929
+ */
930
+ /** How long one look may take in all. */
931
+ declare const LOOK_DEADLINE_MS: number;
932
+ /** The visible cadence while anything is waiting. */
933
+ declare const LOOK_FAST_MS: number;
934
+ /** The visible cadence while request status frames arrive (statusPush), and the hidden
935
+ * cadence while a client-driven indexing chain is open. */
936
+ declare const LOOK_SLOW_MS: number;
937
+ /** Re-read every open item at least this often, whatever the queue counters say. */
938
+ declare const LOOK_STALE_MS: number;
939
+ /** Why a look runs. Several merge into one look. */
940
+ type LookTrigger = 'tick' | 'return' | 'visible' | 'wake' | 'online' | 'pageshow' | 'reconnect' | 'view' | 'frame' | 'unknown' | 'promote' | 'send' | 'signin' | 'add';
941
+ declare function isReturnTrigger(t: string): boolean;
942
+ /** One look as the session sees it. */
943
+ type LookRequest = {
944
+ /** Generation: grows by one per look. */
945
+ gen: number;
946
+ triggers: {
947
+ [k: string]: true;
948
+ };
949
+ /** Any trigger was a return (see RETURN_TRIGGERS). */
950
+ isReturn: boolean;
951
+ /** Aborts every read of this look at its deadline (undefined without AbortController). */
952
+ signal: any;
953
+ /** False once the deadline passed or a newer look started: drop every result. */
954
+ alive: () => boolean;
955
+ /** Milliseconds left before the deadline (at least 1). */
956
+ remaining: () => number;
957
+ };
958
+ /** How a look ended: 'ok' (it read what it needed), 'transient' (a read failed on the way:
959
+ * backoff, nothing changed), 'auth' (the sign-in is gone), 'idle' (nothing to do). */
960
+ type LookOutcome = 'ok' | 'transient' | 'auth' | 'idle';
961
+ interface LookHooks {
962
+ /** Run one look. Never called twice at once. */
963
+ runLook(req: LookRequest): Promise<LookOutcome>;
964
+ /** Is there anything to follow: `visible` = anything at all (the 3 s cadence), `hidden`
965
+ * = something worth a look once a minute while the tab is hidden. */
966
+ work(): {
967
+ visible: boolean;
968
+ hidden: boolean;
969
+ };
970
+ /** Status frames are arriving (statusPush): the visible cadence slows to a minute. */
971
+ pushLive(): boolean;
972
+ /** The reconnecting / sign-in flags changed (for the views). */
973
+ onFlags(flags: {
974
+ reconnecting: boolean;
975
+ signInNeeded: boolean;
976
+ }): void;
977
+ }
978
+ /**
979
+ * The one timer chain. See the file note for the rules.
980
+ */
981
+ declare class LookScheduler {
982
+ private hooks;
983
+ private timer;
984
+ /** When the pending timer should fire, on both clocks (wake detection). */
985
+ private expectPerf;
986
+ private expectWall;
987
+ private running;
988
+ /** Triggers that arrived while a look ran: exactly one more look runs with them. */
989
+ private pending;
990
+ /** Resolvers of trigger() promises, by the look that will serve them. */
991
+ private waitCurrent;
992
+ private waitNext;
993
+ private backoff;
994
+ private listening;
995
+ private stopped;
996
+ gen: number;
997
+ reconnecting: boolean;
998
+ signInNeeded: boolean;
999
+ /** Diagnostics (and the throwaway checks): looks started, timers armed. */
1000
+ looks: number;
1001
+ timersArmed: number;
1002
+ constructor(hooks: LookHooks);
1003
+ /** Pull the next look forward to now. Resolves when the look that serves it ends. */
1004
+ trigger(kind: LookTrigger): Promise<void>;
1005
+ /** Triggers gathered for a look about to start (see trigger). */
1006
+ private starting;
1007
+ private waitStarting;
1008
+ /** Make sure the chain runs at its cadence when there is work. Never adds a timer when
1009
+ * one is armed or a look is running, so calling it from every add is free. */
1010
+ ensure(): void;
1011
+ /** The sign-in came back (or the host says so): looks resume at once. */
1012
+ signedIn(): void;
1013
+ /** Stop the chain (tests, teardown). A later trigger or ensure starts it again. */
1014
+ stop(): void;
1015
+ isRunning(): boolean;
1016
+ private _flags;
1017
+ private _listen;
1018
+ private _start;
1019
+ private _finish;
1020
+ private scheduling;
1021
+ private _scheduleNext;
1022
+ private _arm;
1023
+ }
1024
+ /** Has this side effect run in any tab (within a day)? */
1025
+ declare function sideEffectDone(key: string): boolean;
1026
+ /**
1027
+ * Run `fn` once across the tabs, under the settle lock of (project, queue). `key` names
1028
+ * the side effect (e.g. "resume:<request id>"). Never throws; `fn` may be async.
1029
+ *
1030
+ * Done only when it worked: the side effect is marked in flight (FX_INFLIGHT_MS, so the
1031
+ * other tabs leave it alone) while `fn` runs, and done when `fn` returns, or when the
1032
+ * promise it returns resolves. A throw or a rejected promise clears the mark and `fn` runs
1033
+ * again after a backoff, up to FX_MAX_TRIES times in this tab; a later call with the same
1034
+ * key (the next look, another tab) can still run it after that. A tab that finds it in
1035
+ * flight elsewhere looks again once that mark would have expired, so a tab that died
1036
+ * mid-write does not leave it undone.
1037
+ */
1038
+ declare function runSettleSideEffect(projectId: string, queue: string, key: string, fn: () => any, attempt?: number, tries?: number): void;
1039
+ /** A client reference for one send: 1 to 64 letters, digits, "_" or "-". */
1040
+ declare function newClientRef(): string;
1041
+
983
1042
  /**
984
1043
  * Duplicate-upload detection for chat attachments (reliability plan, owner's
985
1044
  * yes 2026-10-12): "has the signed-in user already uploaded THIS file to this
@@ -1326,6 +1385,13 @@ type BuildIndexingUserMessageOptions = {
1326
1385
  * message instructs the agent to page through EVERY window and datafy each.
1327
1386
  */
1328
1387
  pagedRead?: boolean;
1388
+ /**
1389
+ * An IMAGE file (2026-11-25). 'attached': the engine attaches it to this message as an
1390
+ * image block (jpg/jpeg/png/gif/webp, the ones its image-URL pattern matches). 'maybe': a
1391
+ * format the providers do not take (tif/tiff/bmp/heic); a newer worker attaches a
1392
+ * converted copy, an older one attaches nothing, so the message never claims a picture.
1393
+ */
1394
+ imageFile?: 'attached' | 'maybe';
1329
1395
  };
1330
1396
  /**
1331
1397
  * The access group to write this file's records at. One place, so the user
@@ -1529,6 +1595,117 @@ declare function isAuthExpiredError(input: any): boolean;
1529
1595
  * reduced to by getErrorMessage, because the view usually only keeps the text.
1530
1596
  */
1531
1597
  declare function isProviderApiKeyError(input: any): boolean;
1598
+ /**
1599
+ * The server's own "that request is gone" answer to a read of it (the row was removed:
1600
+ * cancelled while queued, or cleaned up). A fact about the request, unlike every
1601
+ * failure isTransportFailure covers.
1602
+ */
1603
+ declare function isNotExistsError(err: any): boolean;
1604
+ /**
1605
+ * True when a READ of a request failed on the way: no network, no answer in time, rate
1606
+ * limited, a server fault (5xx), an aborted read. Such a failure says nothing about the
1607
+ * request itself, which may be running or already answered, so a caller must never
1608
+ * turn it into an error bubble or a failed run record (reconciler plan, section 3 item 4).
1609
+ */
1610
+ declare function isTransportFailure(err: any): boolean;
1611
+
1612
+ /**
1613
+ * Retrieval memory: a compact note of what a chat turn RETRIEVED, kept with the
1614
+ * turn so a follow-up question skips discovery.
1615
+ *
1616
+ * THE PROBLEM. The provider runs the tool loop on its side and history keeps
1617
+ * only the answer text (budget.ts), so on "and what does page 3 say?" the model
1618
+ * starts from nothing: it looks the file up again, guesses a table and an access
1619
+ * group again, and routinely lands somewhere else, which is how an answer flips
1620
+ * between two turns about the same document.
1621
+ *
1622
+ * WHAT THE ENGINE CAN SEE. The provider's final body carries the tool loop:
1623
+ * - Anthropic Messages: content[] blocks `mcp_tool_use` (name, input) and
1624
+ * `mcp_tool_result` (content), plus `server_tool_use` / `web_*_tool_result`
1625
+ * for the built-in web tools;
1626
+ * - OpenAI Responses: output[] items `mcp_call` (name, arguments as a JSON
1627
+ * string, output as a string) and `web_search_call`.
1628
+ * The polling worker stores that body on the row (spilling to S3 past 300 KB,
1629
+ * never truncating), and a streamed turn's assembled body keeps the same blocks
1630
+ * (sse.ts copies each block's skeleton and its JSON input verbatim), so the
1631
+ * same reader works live, after a stream and after a reload. When a body has no
1632
+ * tool blocks at all (a host that strips them, a provider shape this does not
1633
+ * know), the note falls back to what the ANSWER names: db: file links and src::
1634
+ * paths. Nothing is ever invented: an empty note is null, not a guess.
1635
+ *
1636
+ * WHAT IS KEPT, per turn: files (storage paths), tables, access groups,
1637
+ * searchText hits as path + page, the tool names, and whether a web tool ran.
1638
+ * Arguments are read by KEY, never by position, and only the keys the
1639
+ * BunnyQuery tools use for those four things; a query's filter values, a
1640
+ * record's data and a tool result's text are never copied, so the note cannot
1641
+ * leak a page of a document into every later turn.
1642
+ *
1643
+ * HOW IT REACHES THE MODEL. buildBoundedChatMessages appends the formatted note
1644
+ * to the LLM copy of the assistant turn it belongs to (never the displayed
1645
+ * bubble), for the newest RETRIEVAL_NOTES_MAX turns and within
1646
+ * RETRIEVAL_NOTES_TOKEN_BUDGET tokens, so the memory is bounded however long
1647
+ * the chat gets. A host that never attaches `_retrieval` sees byte-identical
1648
+ * requests to today.
1649
+ */
1650
+ /** sheet: the hit was on a spreadsheet's sheet page (MCP 2026-11-25), whose page number means nothing to a reader. */
1651
+ type RetrievalHit = {
1652
+ path: string;
1653
+ page: number;
1654
+ sheet?: string;
1655
+ };
1656
+ type RetrievalNote = {
1657
+ /** Storage paths (the part after "src::") the turn read, queried or linked. */
1658
+ files: string[];
1659
+ /** Table names the turn queried. */
1660
+ tables: string[];
1661
+ /** Access groups the turn queried at, as written in the call. */
1662
+ accessGroups: string[];
1663
+ /** searchText hits: the page a term was found on, per file. */
1664
+ hits: RetrievalHit[];
1665
+ /** Tool names, in order of first use. */
1666
+ tools: string[];
1667
+ /** A web tool ran in this turn (web_search / web_fetch). */
1668
+ web: boolean;
1669
+ /** 'tools' when read off the body's tool blocks; 'answer' when only the
1670
+ * answer text was available to read. */
1671
+ source: 'tools' | 'answer' | 'body';
1672
+ };
1673
+ /** How many of the newest turns carry their note into the request. */
1674
+ declare const RETRIEVAL_NOTES_MAX = 6;
1675
+ /** Ceiling on the estimated tokens all carried notes may add to one request. */
1676
+ declare const RETRIEVAL_NOTES_TOKEN_BUDGET = 1200;
1677
+ /** Per-list cap inside one note (files, tables, groups, hits, tools). */
1678
+ declare const RETRIEVAL_NOTE_MAX_ITEMS = 8;
1679
+ /** Hard cap on one formatted note. */
1680
+ declare const RETRIEVAL_NOTE_MAX_CHARS = 600;
1681
+ /** The marker a carried note opens with; also what keeps it out of the model's own voice. */
1682
+ declare const RETRIEVAL_NOTE_PREFIX = "[Retrieval note, not shown to the user";
1683
+ /**
1684
+ * What an ANSWER names: db: file links ("[name](db:path)") and src:: ids. The
1685
+ * fallback for a body with no tool blocks, and merged into a tool note too so a
1686
+ * file the model linked but never queried (it knew the path from history) is
1687
+ * still remembered.
1688
+ */
1689
+ declare function retrievalNoteFromText(text: string | null | undefined): RetrievalNote | null;
1690
+ /**
1691
+ * The note for one assistant turn: the body's tool loop when it has one, else
1692
+ * what the answer names, else null. `answerText` is the extracted answer, read
1693
+ * for file links in both cases.
1694
+ */
1695
+ declare function extractRetrievalNote(body: any, answerText?: string | null): RetrievalNote | null;
1696
+ /**
1697
+ * True when `body` is a provider response this module can read: an Anthropic
1698
+ * Messages body (`content` array) or an OpenAI Responses body (`output` array).
1699
+ */
1700
+ declare function providerBodyWasRead(body: any): boolean;
1701
+ /** True when the value is a note this module produced (or an equivalent shape). */
1702
+ declare function isRetrievalNote(value: any): value is RetrievalNote;
1703
+ /**
1704
+ * One line the model reads. Sections are omitted when empty, the whole thing is
1705
+ * capped at RETRIEVAL_NOTE_MAX_CHARS, and it opens with RETRIEVAL_NOTE_PREFIX so
1706
+ * the model can tell it from its own earlier words. Returns '' for an empty note.
1707
+ */
1708
+ declare function formatRetrievalNote(note: RetrievalNote | null | undefined): string;
1532
1709
 
1533
1710
  declare var CONTEXT_WINDOW_DEFAULT: Record<string, number>;
1534
1711
  declare var CONTEXT_WINDOW_BY_MODEL: Record<string, number>;
@@ -2662,402 +2839,8 @@ interface SseParser {
2662
2839
  }
2663
2840
  declare function createSseParser(): SseParser;
2664
2841
 
2665
- declare const MCP_NAME = "BunnyQuery";
2666
- declare const DEFAULT_CLAUDE_MODEL = "claude-haiku-5-5";
2667
- declare const DEFAULT_OPENAI_MODEL = "gpt-6-luna";
2668
2842
  /**
2669
- * THE two `stream` flags of a streamed chat turn, produced together or not at all.
2670
- *
2671
- * There are two of them and they are NOT the same flag:
2672
- *
2673
- * * `transport.stream` is SKAPI's. It tells the polling worker to read the
2674
- * destination's response incrementally and append the raw bytes to the chunk
2675
- * table, and it is never sent on to the destination.
2676
- * * `body.stream` is the DESTINATION's own field, and BunnyQuery is the party
2677
- * that may set it: skapi relays bytes and knows no vendor, so it cannot know
2678
- * that Anthropic Messages and OpenAI Responses both happen to spell it
2679
- * `stream` at the top level of the body.
2680
- *
2681
- * Setting one without the other fails QUIETLY, which is why they are produced by
2682
- * one function from one boolean and returned as one object:
2683
- *
2684
- * * body streams, skapi buffers -> the row stores an SSE TRANSCRIPT where
2685
- * extractClaudeText / extractOpenAIText expect a parsed document, so the turn
2686
- * reads back as an empty answer with nothing in the logs to say why.
2687
- * * skapi streams, the body never asked -> the destination sends one plain
2688
- * document, the relay chops it into chunks, the frame parser finds no framing
2689
- * at all, and the row settles with a status and no body.
2690
- *
2691
- * Two frozen constants rather than a fresh object per call: the pair is a
2692
- * CONSTANT, and an object literal built at each call site is exactly the shape
2693
- * that drifts when someone edits one arm.
2694
- */
2695
- type ChatStreamWiring = {
2696
- /** Spread into the forwardRequest OPTIONS (skapi's relay switch). `realtime`
2697
- * belongs here and never in `body`: it is skapi's, not the destination's. */
2698
- transport: {
2699
- stream?: true;
2700
- realtime?: true;
2701
- };
2702
- /** Spread into `data` (the destination's own switch). */
2703
- body: {
2704
- stream?: true;
2705
- };
2706
- };
2707
- declare function chatStreamWiring(queue?: string): ChatStreamWiring;
2708
- /**
2709
- * The body fields a CHAT turn's answer mode adds, for the one provider and model the turn
2710
- * runs on. An empty object, i.e. nothing at all, for 'standard' (the default) and for any
2711
- * model not known to accept the field, so a project that never set a mode sends the exact
2712
- * request it sent before the setting existed. OpenAI takes `reasoning: {effort}`, Claude
2713
- * takes `output_config: {effort}`. Never used by an indexing pass.
2714
- */
2715
- declare function chatEffortFields(platform: 'claude' | 'openai', model: string | undefined, mode: AnswerMode | undefined): Record<string, any>;
2716
- /** How a given model should be shown a rendered document. */
2717
- type VisionProfile = {
2718
- /** Per-image `detail` (OpenAI only). */
2719
- detail: string;
2720
- /** Pages the worker renders into one window. */
2721
- pagesPerWindow: number;
2722
- /** Horizontal bands per page; 1 renders the whole page as one image. */
2723
- tile: number;
2724
- };
2725
- /**
2726
- * Resolve the render profile for a model.
2727
- *
2728
- * Three tiers, and they fail for different reasons, which is why one set of knobs cannot
2729
- * serve all of them:
2730
- * - full: everything ABOVE gpt-5.4-nano - the base models, mini, and every gpt-5.6
2731
- * including 5.6-nano. These already transcribe dense scans correctly, so they get
2732
- * 'original' detail and are otherwise untouched.
2733
- * - gpt-5.4-nano: also gets 'original', so it sees exactly the SAME pixels as the full
2734
- * tier. Its gap therefore is not resolution, and tiling would do nothing for it. What
2735
- * it lacks is room: a smaller window leaves the same output budget divided between
2736
- * fewer pages.
2737
- * - downsampled (below the 'original' floor: gpt-5.3-nano, gpt-5-nano, gpt-4.1-nano):
2738
- * capped at 'high', which resamples the page onto a 512px grid no matter what DPI it
2739
- * was rendered at. Render resolution is wasted on these entirely; the only way to give
2740
- * them readable text is to make each image cover less of the page, which is `tile`.
2741
- */
2742
- declare function getVisionProfile(model?: string): VisionProfile;
2743
- type ClaudeRole = 'user' | 'assistant';
2744
- type ClaudeMessage = {
2745
- role: ClaudeRole;
2746
- content: string;
2747
- };
2748
- type OpenAIMessage = {
2749
- role: ClaudeRole;
2750
- content: string;
2751
- };
2752
- type ClaudeMcpToolConfig = {
2753
- enabled?: boolean;
2754
- defer_loading?: boolean;
2755
- };
2756
- type ClaudeMcpServerRequest = {
2757
- name: string;
2758
- url: string;
2759
- authorizationToken?: string;
2760
- defaultConfig?: ClaudeMcpToolConfig;
2761
- configs?: Record<string, ClaudeMcpToolConfig>;
2762
- };
2763
- declare function transformContentWithImages(content: string): string | Array<Record<string, any>>;
2764
- declare function transformContentWithOpenAIImages(content: string, detail?: string): string | Array<Record<string, any>>;
2765
- type CallClaudeWithMcpParams = {
2766
- prompt: string;
2767
- messages?: ClaudeMessage[];
2768
- service: string;
2769
- owner: string;
2770
- userId?: string;
2771
- model?: string;
2772
- maxTokens?: number;
2773
- system?: string;
2774
- mcpServer: ClaudeMcpServerRequest;
2775
- extractContent?: ExtractDirective[];
2776
- fileUrls?: FileUrlDirective[];
2777
- onResponse?: (res: any) => void;
2778
- onError?: (err: any) => void;
2779
- /**
2780
- * Attach Claude's `web_fetch` to this turn. A per-call host value under the
2781
- * same ceiling rule as the config option: the project's `web_access` setting
2782
- * is the most a turn can have, and `false` here (or in the config) takes it
2783
- * off. Omitted follows the config option and the project. See config.ts
2784
- * resolveWebAccess.
2785
- */
2786
- webAccess?: boolean;
2787
- };
2788
- declare const POLL_INTERVAL = 3000;
2789
- declare const STREAM_POLL_INTERVAL = 1000;
2790
- declare const MAX_CONCURRENT_BG_POLLS = 6;
2791
- /**
2792
- * What a chat turn hands the OpenAI request builder about itself, and what the builder
2793
- * writes back. Created per turn by ChatSession; a host that calls the builder directly
2794
- * and passes nothing gets exactly the request it always got.
2795
- */
2796
- type ChatTurnContext = {
2797
- /**
2798
- * Reuse the MCP tool listing OpenAI returned on an earlier chat turn (OpenAI only).
2799
- * Every OpenAI turn otherwise starts with OpenAI asking our MCP server for its tools,
2800
- * four sequential requests (server/discover, initialize, notifications/initialized,
2801
- * tools/list), about 0.6 s before the model starts. OpenAI's docs: "As long as the
2802
- * mcp_list_tools item is present in the context of an API request, the API will not
2803
- * fetch a list of tools from the MCP server again at each turn."
2804
- */
2805
- reuseMcpToolList?: boolean;
2806
- /** Who the turn runs as. Part of the listing key: a different user can see a different list. */
2807
- userId?: string;
2808
- /** Written by the builder: the key this turn's listing is stored under. */
2809
- mcpToolsKey?: string;
2810
- /** Written by the builder: true when a stored listing rode in this turn's input. */
2811
- mcpToolsInjected?: boolean;
2812
- /** Written by the builder: the project the listing belongs to (for the per-project off verdict). */
2813
- mcpToolsService?: string;
2814
- /** Written by the builder: the id of the listing that rode in this turn's input. */
2815
- mcpToolsItemId?: string;
2816
- /** Set by ChatSession once the turn's outcome was applied, so a later handler cannot apply it twice. */
2817
- settled?: boolean;
2818
- };
2819
- declare function callClaudeWithMcp({ prompt, messages, service, owner, userId, model, maxTokens, system, mcpServer, extractContent, fileUrls, webAccess, }: CallClaudeWithMcpParams): Promise<any>;
2820
- declare function callClaudeWithPublicMcp(prompt: string, service: string, owner: string, messages?: ClaudeMessage[], system?: string, model?: string, userId?: string, extractContent?: ExtractDirective[], fileUrls?: FileUrlDirective[], onResponse?: (res: any) => void, onError?: (err: any) => void, mcpScope?: {
2821
- anonymous?: boolean;
2822
- publicProjectId?: string;
2823
- }): Promise<any>;
2824
- declare function callOpenAIWithPublicMcp(prompt: string, service: string, owner: string, messages?: OpenAIMessage[], system?: string, model?: string, userId?: string, extractContent?: ExtractDirective[], fileUrls?: FileUrlDirective[], onResponse?: (res: any) => void, onError?: (err: any) => void, mcpScope?: {
2825
- anonymous?: boolean;
2826
- publicProjectId?: string;
2827
- }, turn?: ChatTurnContext): Promise<any>;
2828
- type AttachmentSaveInfo = {
2829
- platform: 'claude' | 'openai';
2830
- model?: string;
2831
- service: string;
2832
- /** The PUBLIC project ID (formatted token, skapi.project_id). Shown to the model; falls back to `service`. */
2833
- publicProjectId?: string;
2834
- owner: string;
2835
- /**
2836
- * Queue base for this indexing pass: "<userId>-bg". REQUIRED, and it must be
2837
- * the SAME value the chat turn uses (ChatSession.dispatchComposedMessage's
2838
- * `id.userId || id.projectId`) — the backend serialises requests that share a
2839
- * queue name and runs different ones IN PARALLEL, so a pass enqueued under a
2840
- * different base does not hold the chat back at all. It was optional once,
2841
- * defaulting to `service`; the chatbox omitted it, and its files were indexed
2842
- * on "<projectId>-bg" while its question ran on "<userId>-bg" — the question
2843
- * was answered from a file nothing had read yet. Pass `userId || projectId`.
2844
- */
2845
- userId: string;
2846
- serviceName?: string;
2847
- serviceDescription?: string;
2848
- attachment: {
2849
- name: string;
2850
- storagePath: string;
2851
- mime?: string;
2852
- size?: number;
2853
- url: string;
2854
- /**
2855
- * Access group this file's records are written at (the uploader's choice,
2856
- * already applied to the "src::" record). Threaded into the indexing
2857
- * prompts so the agent's own records land in the same group; omitted
2858
- * means "authorized", the group everything used before the setting existed.
2859
- */
2860
- accessGroup?: 'public' | 'authorized' | 'private';
2861
- };
2862
- /**
2863
- * Content parsed CLIENT-SIDE by an attachment-parser plugin (e.g. an .hwp
2864
- * parser). When set, it is inlined into the indexing message verbatim and
2865
- * takes precedence over server-side office extraction / web_fetch.
2866
- */
2867
- parsedContent?: string;
2868
- /**
2869
- * True for a RESUME pass: a previous indexing pass could not finish this (large)
2870
- * file, so continue it - always via readFileContent paging, with a "continue"
2871
- * message telling the agent to resume from where the saved records leave off.
2872
- */
2873
- continueIndexing?: boolean;
2874
- /**
2875
- * For an image-vision file (PDF), the 0-based PAGE the render window should start at.
2876
- * The worker renders [renderFrom, renderFrom+RENDER_PAGES_PER_WINDOW) and injects them
2877
- * as image blocks; the resume loop advances this by a window each pass.
2878
- */
2879
- renderFrom?: number;
2880
- };
2881
- declare function notifyAgentSaveAttachment(info: AttachmentSaveInfo): Promise<any>;
2882
- declare function extractClaudeText(response: any): any;
2883
- declare function extractOpenAIText(response: any): any;
2884
- declare function listClaudeModels(service: string, owner: string): Promise<any>;
2885
- declare function listOpenAIModels(service: string, owner: string): Promise<any>;
2886
- declare const BG_INDEXING_QUEUE_SUFFIX = "-bg";
2887
- /**
2888
- * unique_id of the durable "indexing finished" marker record for a stored file.
2889
- *
2890
- * Written by the BACKEND (the polling worker calls the MCP server's
2891
- * /internal/index-complete at the end of an auto_continue chain whose final
2892
- * window reported no more content) and, for completions a client knows
2893
- * deterministically (single-pass settle, client-chain completion token), by the
2894
- * consumer's mintIndexDoneMarker hook — never by the model.
2895
- * The marker record carries `reference: "src::<path>"`, so the reindex flow's
2896
- * delete of the src:: record cascades to it and a re-run starts unmarked.
2897
- *
2898
- * Existence semantics: present = the whole file was read to the end. Absent =
2899
- * unknown (still running, failed partway, indexed before this marker existed,
2900
- * or a single-pass run minted before the client hook existed) - callers must
2901
- * fall back to the live-queue probe (fetchLiveIndexingKeys) before reading
2902
- * absence as anything.
2903
- */
2904
- /** What the MCP's /internal/index-reset answered. */
2905
- type IndexResetResult = {
2906
- path: string;
2907
- /** The access group the old file record had, or null when there was none. */
2908
- access_group: string | number | null;
2909
- removed: number;
2910
- missing: number;
2911
- failed: number;
2912
- decorations: number;
2913
- ambiguous: number;
2914
- ms?: number;
2915
- };
2916
- /**
2917
- * Clear a file's index on the SERVER before a Reindex or an Overwrite (owner,
2918
- * 2026-11-20): the MCP's /internal/index-reset removes the file record (and, through its
2919
- * cascade, everything referencing it), the agent's decorated per-window ids and the
2920
- * done::/run:: markers, in parallel, as the signed-in user. Reached through the host's
2921
- * forwardRequest with "$ACCESS_TOKEN", which skapi fills in with the caller's own token,
2922
- * so no client code ever holds it.
2923
- *
2924
- * Resolves to the server's answer, or null when the call could not be made or answered
2925
- * something else (an older MCP without the route, a timeout): the caller then clears
2926
- * the index itself, as it always did. Never rejects.
2927
- */
2928
- declare function resetFileIndexOnServer(args: {
2929
- service: string;
2930
- owner?: string;
2931
- storagePath: string;
2932
- }): Promise<IndexResetResult | null>;
2933
- declare function indexDoneUniqueId(storagePath: string): string;
2934
- /**
2935
- * unique_id of the per-file indexing RUN record.
2936
- *
2937
- * One record per storage path, newest run wins (a reindex's delete-then-repost
2938
- * of src:: cascade-deletes the old record first, exactly like done::). Minted
2939
- * status='working' by the client the moment it enqueues a run's FIRST pass, and
2940
- * closed (done/error/cancelled) by whichever side observes the ending: the
2941
- * worker via the MCP internal routes for worker-driven chains, the client for
2942
- * deterministic settles, cancels, and dispatch failures. It exists so chat rows
2943
- * and files-page badges can answer "which runs exist and how did they end"
2944
- * from ONE records query instead of scanning bg history.
2945
- *
2946
- * A 'working' record is a claim, not proof: a chain that dies without reaching
2947
- * any error path leaves it dangling, so readers must treat a stale 'working'
2948
- * (old `started`, no live-queue confirmation) as unknown, never as live.
2949
- */
2950
- declare function runIndexUniqueId(storagePath: string): string;
2951
- type IndexRunStatus = 'working' | 'done' | 'error' | 'cancelled';
2952
- type IndexRunPatch = {
2953
- status: IndexRunStatus;
2954
- filename?: string;
2955
- started?: number;
2956
- finished?: number;
2957
- error?: string;
2958
- queue?: string;
2959
- /** Chat that owns this run. A run:: record is keyed by storage path alone,
2960
- * but a chat is per (project, platform) — without this the Claude chat's
2961
- * runs surfaced as rows in the same project's ChatGPT chat, where their
2962
- * passes can never load and the queue probe can never see them. */
2963
- platform?: 'claude' | 'openai';
2964
- };
2965
- /**
2966
- * Fire-and-forget wrapper over the consumer's upsertIndexRunRecord hook.
2967
- * Safe everywhere: missing hook, unconfigured engine, and consumer throws all
2968
- * reduce to a no-op — a run record must never be able to break the run itself.
2969
- */
2970
- declare function upsertIndexRunRecordSafe(service: string, storagePath: string, patch: IndexRunPatch): void;
2971
- /**
2972
- * The one place the background-indexing queue name is spelled out. The backend
2973
- * serialises requests sharing a queue name and runs different names in PARALLEL,
2974
- * so every indexing pass AND the chat turn that must wait behind them have to
2975
- * resolve to the identical string — see AttachmentSaveInfo.userId for what
2976
- * happens when they do not.
2977
- */
2978
- declare function bgIndexingQueueName(userId?: string, service?: string): string;
2979
- /**
2980
- * True when a request belongs to the background-indexing queue.
2981
- *
2982
- * Accepts BOTH shapes this value arrives in: the bare queue name the client sends
2983
- * ("<userId>-bg"), and the server qid that comes back on history/poll responses
2984
- * ("<service>:<queue>|<seq>"). Testing the tail of the raw value only works for the
2985
- * first: a qid ends in "|<seq>", so `endsWith('-bg')` is always false for it — which
2986
- * silently meant history items were NEVER recognised as background tasks.
2987
- */
2988
- declare function isBgIndexingQueue(queueName?: string): boolean;
2989
- type BgTaskEntry = {
2990
- projectId: string;
2991
- platform: 'claude' | 'openai';
2992
- id: string;
2993
- filename: string;
2994
- storagePath?: string;
2995
- isReindex?: boolean;
2996
- mime?: string;
2997
- size?: number;
2998
- status: 'running' | 'pending';
2999
- poll: ((opts: {
3000
- latency: number;
3001
- notify?: boolean;
3002
- onResponse?: (res: any, meta?: {
3003
- executed?: number;
3004
- }) => void;
3005
- }) => Promise<any>) | undefined;
3006
- /** How many CONTINUE passes have already run for this file (resume-across-passes). */
3007
- resumePass?: number;
3008
- /** The STAGED chat turn these files were attached to (ChatSession.stageOutgoingMessage).
3009
- * drainBgTaskQueue inserts this pass's bubble directly ABOVE that turn's bubble, so the
3010
- * collapsed row sits where the reader expects it — right before the message the files
3011
- * came with — from the moment it appears, instead of the turn being moved down past it
3012
- * once everything finishes. Absent for work with no chat turn behind it (the dbfile
3013
- * page, an attachment-only send, a worker-adopted pass), which appends as before. */
3014
- stageId?: string;
3015
- /** Settled from the 10-second queue check instead of its own poll (owner, 2026-11-20).
3016
- * Set by drainBgTaskQueue on every pass when the host has csrHistoryItemLookup, and on
3017
- * adoption for the worker's lanes. Polls on one queue run one at a time in skapi-js, so
3018
- * a pass that finished waited behind every pass ahead of it; see
3019
- * ChatSession._settleByListing. */
3020
- byListing?: boolean;
3021
- /** When this client first tracked the pass (ms). A pass missing from a listing taken
3022
- * BEFORE that proves nothing about it. */
3023
- adoptedAt?: number;
3024
- };
3025
- declare const INDEXING_COMPLETE_MARKER = "INDEXING_COMPLETE";
3026
- declare const EMPTY_INDEXING_REPLY = "Finished reading this file.";
3027
- /**
3028
- * `queue` narrows the fetch to one processing chain; `status` narrows it to items
3029
- * in one state. Passing both is how the client asks "is there still unresolved
3030
- * work on the background-indexing queue?" without pulling a page of chat history
3031
- * (see ChatSession._adoptWorkerIndexingPasses) — the server answers that from a
3032
- * status-keyed index, so the reply carries only the live items, not the bodies of
3033
- * everything already finished.
3034
- */
3035
- declare function getChatHistory(params: {
3036
- service?: string;
3037
- owner?: string;
3038
- platform: 'claude' | 'openai';
3039
- queue?: string;
3040
- status?: 'pending' | 'running' | 'resolved' | 'failed';
3041
- /** Exact-queue listing: without it the qid range is a PREFIX match, so
3042
- * queue "u1" also returns "u1-bg" rows. Requires the updated polling
3043
- * lambda; older backends ignore it (harmless, wider results). */
3044
- queue_exact?: boolean;
3045
- /** Label/marker STUBS instead of full bodies (see the polling lambda).
3046
- * Older backends ignore it and return full items. */
3047
- compact?: boolean;
3048
- /** Drop one queue's rows from an id-prefix listing — how the surface
3049
- * chat is fetched WITHOUT the bg-indexing queue while legacy items on
3050
- * odd queue names survive. Older backends ignore it. */
3051
- queue_exclude?: string;
3052
- }, fetchOptions: Record<string, any>): Promise<any>;
3053
- /** Full server-side id of one history item, for a csr-poll POINT LOOKUP (the
3054
- * single-item path returns the item WITH bodies — how an expanded row fetches
3055
- * the passes a compact listing stubbed out). Mirrors the id the SDK builds:
3056
- * `[METHOD]url#service:` + the item's own `stamp:entropy` id. */
3057
- declare function buildHistoryItemFullId(platform: 'claude' | 'openai', service: string, itemId: string): string;
3058
-
3059
- /**
3060
- * ChatSession host adapter + state types.
2843
+ * ChatSession host adapter + state types.
3061
2844
  *
3062
2845
  * ChatSession is DOM-free and Vue-free; the consumer (bunnyquery widget or the
3063
2846
  * agent.vue chatbox) implements `ChatHost` to bridge identity, rendering, scroll,
@@ -3197,10 +2980,10 @@ interface ChatMessage {
3197
2980
  /** PROTOCOL + PRESENTATIONAL: this bubble is being painted from a LIVE stream.
3198
2981
  *
3199
2982
  * It sits alongside `isPending`, never instead of it. The bubble is still the
3200
- * turn's "Thinking..." placeholder as far as every queue mechanism is concerned
3201
- * (_ownThinkingIndex, resolveQueuedUserBubble, typewriteLatestReply and the
3202
- * stray-pending sweep all find their target by isPending), and clearing that flag
3203
- * to mean "it has text now" would strand the turn's real answer beside an orphan.
2983
+ * turn's "Thinking..." placeholder as far as every settle is concerned (the apply
2984
+ * funnel, ChatSession.applyTerminal, finds a turn's waiting bubble by its server id
2985
+ * AND isPending), and clearing that flag to mean "it has text now" would make the
2986
+ * turn read as already answered, so its real answer would be refused.
3204
2987
  * What this adds is the one thing those mechanisms do not care about and the VIEW
3205
2988
  * does: `content` is already worth rendering, so draw the text instead of the
3206
2989
  * spinner.
@@ -3300,6 +3083,16 @@ interface ChatMessage {
3300
3083
  * never carries it, so neither view needs a second test. */
3301
3084
  _tsStart?: number;
3302
3085
  _ownerKey?: string;
3086
+ /** The client reference the turn was sent with (reconciler plan, section 3 item 9). On
3087
+ * the user bubble of a send; a send whose ack was lost is matched to its row by it. */
3088
+ _cref?: string;
3089
+ /** A send whose POST got no answer while the reconciler looks for its row by `_cref`:
3090
+ * kept through history merges until its row is found or it is "Not sent". */
3091
+ _unconfirmed?: boolean;
3092
+ /** A send whose POST got no answer and whose row the server never showed: the reply
3093
+ * bubble says "Not sent. Retry?" and ChatSession.retryNotSent(msg) sends it again.
3094
+ * Never retried on its own. */
3095
+ _notSent?: boolean;
3303
3096
  }
3304
3097
  interface ChatState {
3305
3098
  messages: ChatMessage[];
@@ -3377,6 +3170,31 @@ interface ChatState {
3377
3170
  stoppedIndexIds: {
3378
3171
  [serverItemId: string]: boolean;
3379
3172
  };
3173
+ /** The reconciler's last look failed on the way (network, timeout, 429, 5xx) and it is
3174
+ * trying again with backoff. Nothing on screen was changed by the failure; a view may
3175
+ * show a small "Reconnecting..." note while this is true. */
3176
+ reconnecting?: boolean;
3177
+ /** The reconciler's reads are refused for want of a sign-in. Looks resume on the next
3178
+ * sign-in (ChatSession.noteSignedIn); a view may say "Sign in to see the latest
3179
+ * answers" while this is true. */
3180
+ signInNeeded?: boolean;
3181
+ /** The background indexing queue of a project as the reconciler last read it, for a
3182
+ * page that shows indexing state with or without a chat view (the dashboard's files
3183
+ * page), by project id. Filled while someone watches it (ChatSession.watchIndexQueue).
3184
+ * `keys` holds the storage paths and file names with a pass waiting or running;
3185
+ * `checked` is false when the read came back cut off (absence then proves nothing);
3186
+ * `at` is when the read ran (a re-served read keeps its time, so two different `at`
3187
+ * values are two independent looks). */
3188
+ indexQueues?: {
3189
+ [projectId: string]: IndexQueueSnapshot;
3190
+ };
3191
+ }
3192
+ interface IndexQueueSnapshot {
3193
+ keys: {
3194
+ [fileKey: string]: true;
3195
+ };
3196
+ checked: boolean;
3197
+ at: number;
3380
3198
  }
3381
3199
  interface ChatHost {
3382
3200
  /** Read live (platform/model/name can change between sends). */
@@ -3426,6 +3244,21 @@ interface ChatHost {
3426
3244
  formatIndexingLabel(name: string, mime?: string, size?: number | null, storagePath?: string, reindex?: boolean, continued?: boolean): string;
3427
3245
  /** drainBgTaskQueue is a no-op until the chat view is mounted. */
3428
3246
  isViewMounted(): boolean;
3247
+ /**
3248
+ * Optional. Read the run:: records of these files again (reconciler plan, section 3
3249
+ * item 1). The engine follows a file whose record says 'working' (syncFileRuns) until
3250
+ * the record says it ended or a complete look at the queue finds no pass of it, and
3251
+ * asks for this every 30 seconds meanwhile, while the file is not seen live. The host
3252
+ * re-reads its records and hands the 'working' paths back through syncFileRuns.
3253
+ */
3254
+ recheckFileRuns?(projectId: string, storagePaths: string[]): void;
3255
+ /**
3256
+ * Optional. A provider answer (or a provider error) just settled a request of this
3257
+ * project, whichever path read it (a poll, a look, a stream). The host may judge the
3258
+ * project's API key from it (web-bunnyquery's "Your API key is invalid"). Called once
3259
+ * per request, after the bubble is written.
3260
+ */
3261
+ onProviderAnswer?(projectId: string, platform: 'claude' | 'openai', result: any): void;
3429
3262
  /** Clear-horizon timestamp (localStorage, per service#platform) — view-owned. */
3430
3263
  getClearedAt(): number;
3431
3264
  uploadFile(args: {
@@ -3493,26 +3326,454 @@ interface ChatHost {
3493
3326
  * the chip says so. Null, a rejection or a missing hook all mean "upload as
3494
3327
  * usual"; the engine's findDuplicateUpload is the ready-made implementation.
3495
3328
  */
3496
- findDuplicateUpload?(file: {
3497
- name: string;
3498
- size: number;
3499
- }): Promise<{
3500
- storagePath: string;
3501
- } | null> | {
3502
- storagePath: string;
3503
- } | null;
3504
- /** Map a relative path to the consumer's db storage key (e.g. uid-prefixed). */
3505
- storagePathFor(relPath: string): string;
3506
- getMimeType(name: string): string | null;
3507
- /** Non-dismissible "file exists" prompt → skip, keep+reindex, or overwrite. */
3508
- promptOverwrite(filename: string): Promise<'overwrite' | 'reindex' | 'skip'>;
3509
- /** Clear the "apply to all" overwrite choice at the start of a batch. */
3510
- resetOverwriteBatch(): void;
3511
- /** Re-render the attachment chip row (progress / status). */
3512
- renderAttachmentChips(): void;
3513
- /** Enable/disable composer controls during an upload batch. */
3514
- updateComposerControls(): void;
3515
- }
3329
+ findDuplicateUpload?(file: {
3330
+ name: string;
3331
+ size: number;
3332
+ }): Promise<{
3333
+ storagePath: string;
3334
+ } | null> | {
3335
+ storagePath: string;
3336
+ } | null;
3337
+ /** Map a relative path to the consumer's db storage key (e.g. uid-prefixed). */
3338
+ storagePathFor(relPath: string): string;
3339
+ getMimeType(name: string): string | null;
3340
+ /** Non-dismissible "file exists" prompt → skip, keep+reindex, or overwrite. */
3341
+ promptOverwrite(filename: string): Promise<'overwrite' | 'reindex' | 'skip'>;
3342
+ /** Clear the "apply to all" overwrite choice at the start of a batch. */
3343
+ resetOverwriteBatch(): void;
3344
+ /** Re-render the attachment chip row (progress / status). */
3345
+ renderAttachmentChips(): void;
3346
+ /** Enable/disable composer controls during an upload batch. */
3347
+ updateComposerControls(): void;
3348
+ }
3349
+
3350
+ declare const MCP_NAME = "BunnyQuery";
3351
+ declare const DEFAULT_CLAUDE_MODEL = "claude-haiku-5-5";
3352
+ declare const DEFAULT_OPENAI_MODEL = "gpt-6-luna";
3353
+ /**
3354
+ * THE two `stream` flags of a streamed chat turn, produced together or not at all.
3355
+ *
3356
+ * There are two of them and they are NOT the same flag:
3357
+ *
3358
+ * * `transport.stream` is SKAPI's. It tells the polling worker to read the
3359
+ * destination's response incrementally and append the raw bytes to the chunk
3360
+ * table, and it is never sent on to the destination.
3361
+ * * `body.stream` is the DESTINATION's own field, and BunnyQuery is the party
3362
+ * that may set it: skapi relays bytes and knows no vendor, so it cannot know
3363
+ * that Anthropic Messages and OpenAI Responses both happen to spell it
3364
+ * `stream` at the top level of the body.
3365
+ *
3366
+ * Setting one without the other fails QUIETLY, which is why they are produced by
3367
+ * one function from one boolean and returned as one object:
3368
+ *
3369
+ * * body streams, skapi buffers -> the row stores an SSE TRANSCRIPT where
3370
+ * extractClaudeText / extractOpenAIText expect a parsed document, so the turn
3371
+ * reads back as an empty answer with nothing in the logs to say why.
3372
+ * * skapi streams, the body never asked -> the destination sends one plain
3373
+ * document, the relay chops it into chunks, the frame parser finds no framing
3374
+ * at all, and the row settles with a status and no body.
3375
+ *
3376
+ * Two frozen constants rather than a fresh object per call: the pair is a
3377
+ * CONSTANT, and an object literal built at each call site is exactly the shape
3378
+ * that drifts when someone edits one arm.
3379
+ */
3380
+ type ChatStreamWiring = {
3381
+ /** Spread into the forwardRequest OPTIONS (skapi's relay switch). `realtime`
3382
+ * belongs here and never in `body`: it is skapi's, not the destination's. */
3383
+ transport: {
3384
+ stream?: true;
3385
+ realtime?: true;
3386
+ };
3387
+ /** Spread into `data` (the destination's own switch). */
3388
+ body: {
3389
+ stream?: true;
3390
+ };
3391
+ };
3392
+ declare function chatStreamWiring(queue?: string): ChatStreamWiring;
3393
+ /**
3394
+ * The body fields a CHAT turn's answer mode adds, for the one provider and model the turn
3395
+ * runs on. An empty object, i.e. nothing at all, for 'standard' (the default) and for any
3396
+ * model not known to accept the field, so a project that never set a mode sends the exact
3397
+ * request it sent before the setting existed. OpenAI takes `reasoning: {effort}`, Claude
3398
+ * takes `output_config: {effort}`. Never used by an indexing pass.
3399
+ */
3400
+ declare function chatEffortFields(platform: 'claude' | 'openai', model: string | undefined, mode: AnswerMode | undefined): Record<string, any>;
3401
+ /** How a given model should be shown a rendered document. */
3402
+ type VisionProfile = {
3403
+ /** Per-image `detail` (OpenAI only). */
3404
+ detail: string;
3405
+ /** Pages the worker renders into one window. */
3406
+ pagesPerWindow: number;
3407
+ /** Horizontal bands per page; 1 renders the whole page as one image. */
3408
+ tile: number;
3409
+ };
3410
+ /**
3411
+ * Resolve the render profile for a model.
3412
+ *
3413
+ * Three tiers, and they fail for different reasons, which is why one set of knobs cannot
3414
+ * serve all of them:
3415
+ * - full: everything ABOVE gpt-5.4-nano - the base models, mini, and every gpt-5.6
3416
+ * including 5.6-nano. These already transcribe dense scans correctly, so they get
3417
+ * 'original' detail and are otherwise untouched.
3418
+ * - gpt-5.4-nano: also gets 'original', so it sees exactly the SAME pixels as the full
3419
+ * tier. Its gap therefore is not resolution, and tiling would do nothing for it. What
3420
+ * it lacks is room: a smaller window leaves the same output budget divided between
3421
+ * fewer pages.
3422
+ * - downsampled (below the 'original' floor: gpt-5.3-nano, gpt-5-nano, gpt-4.1-nano):
3423
+ * capped at 'high', which resamples the page onto a 512px grid no matter what DPI it
3424
+ * was rendered at. Render resolution is wasted on these entirely; the only way to give
3425
+ * them readable text is to make each image cover less of the page, which is `tile`.
3426
+ */
3427
+ declare function getVisionProfile(model?: string): VisionProfile;
3428
+ type ClaudeRole = 'user' | 'assistant';
3429
+ type ClaudeMessage = {
3430
+ role: ClaudeRole;
3431
+ content: string;
3432
+ };
3433
+ type OpenAIMessage = {
3434
+ role: ClaudeRole;
3435
+ content: string;
3436
+ };
3437
+ type ClaudeMcpToolConfig = {
3438
+ enabled?: boolean;
3439
+ defer_loading?: boolean;
3440
+ };
3441
+ type ClaudeMcpServerRequest = {
3442
+ name: string;
3443
+ url: string;
3444
+ authorizationToken?: string;
3445
+ defaultConfig?: ClaudeMcpToolConfig;
3446
+ configs?: Record<string, ClaudeMcpToolConfig>;
3447
+ };
3448
+ declare function transformContentWithImages(content: string): string | Array<Record<string, any>>;
3449
+ declare function transformContentWithOpenAIImages(content: string, detail?: string): string | Array<Record<string, any>>;
3450
+ type CallClaudeWithMcpParams = {
3451
+ prompt: string;
3452
+ messages?: ClaudeMessage[];
3453
+ service: string;
3454
+ owner: string;
3455
+ userId?: string;
3456
+ model?: string;
3457
+ maxTokens?: number;
3458
+ system?: string;
3459
+ mcpServer: ClaudeMcpServerRequest;
3460
+ extractContent?: ExtractDirective[];
3461
+ fileUrls?: FileUrlDirective[];
3462
+ onResponse?: (res: any) => void;
3463
+ onError?: (err: any) => void;
3464
+ /**
3465
+ * Attach Claude's `web_fetch` to this turn. A per-call host value under the
3466
+ * same ceiling rule as the config option: the project's `web_access` setting
3467
+ * is the most a turn can have, and `false` here (or in the config) takes it
3468
+ * off. Omitted follows the config option and the project. See config.ts
3469
+ * resolveWebAccess.
3470
+ */
3471
+ webAccess?: boolean;
3472
+ /** The send's client reference (ChatTurnContext.cref), passed to forwardRequest. */
3473
+ cref?: string;
3474
+ };
3475
+ declare const POLL_INTERVAL = 3000;
3476
+ declare const STREAM_POLL_INTERVAL = 1000;
3477
+ declare const MAX_CONCURRENT_BG_POLLS = 6;
3478
+ /**
3479
+ * What a chat turn hands the OpenAI request builder about itself, and what the builder
3480
+ * writes back. Created per turn by ChatSession; a host that calls the builder directly
3481
+ * and passes nothing gets exactly the request it always got.
3482
+ */
3483
+ type ChatTurnContext = {
3484
+ /**
3485
+ * Reuse the MCP tool listing OpenAI returned on an earlier chat turn (OpenAI only).
3486
+ * Every OpenAI turn otherwise starts with OpenAI asking our MCP server for its tools,
3487
+ * four sequential requests (server/discover, initialize, notifications/initialized,
3488
+ * tools/list), about 0.6 s before the model starts. OpenAI's docs: "As long as the
3489
+ * mcp_list_tools item is present in the context of an API request, the API will not
3490
+ * fetch a list of tools from the MCP server again at each turn."
3491
+ */
3492
+ reuseMcpToolList?: boolean;
3493
+ /** Who the turn runs as. Part of the listing key: a different user can see a different list. */
3494
+ userId?: string;
3495
+ /** Written by the builder: the key this turn's listing is stored under. */
3496
+ mcpToolsKey?: string;
3497
+ /** Written by the builder: true when a stored listing rode in this turn's input. */
3498
+ mcpToolsInjected?: boolean;
3499
+ /** Written by the builder: the project the listing belongs to (for the per-project off verdict). */
3500
+ mcpToolsService?: string;
3501
+ /** Written by the builder: the id of the listing that rode in this turn's input. */
3502
+ mcpToolsItemId?: string;
3503
+ /** Set by ChatSession once the turn's outcome was applied, so a later handler cannot apply it twice. */
3504
+ settled?: boolean;
3505
+ /** The client reference of this send (reconciler plan, section 3 item 9): sent as
3506
+ * forwardRequest's `cref`, so a send whose ack was lost is found by it and never sent
3507
+ * twice. Set by ChatSession only when the host's skapi-js carries it (crefSupported). */
3508
+ cref?: string;
3509
+ };
3510
+ declare function callClaudeWithMcp({ prompt, messages, service, owner, userId, model, maxTokens, system, mcpServer, extractContent, fileUrls, webAccess, cref, }: CallClaudeWithMcpParams): Promise<any>;
3511
+ declare function callClaudeWithPublicMcp(prompt: string, service: string, owner: string, messages?: ClaudeMessage[], system?: string, model?: string, userId?: string, extractContent?: ExtractDirective[], fileUrls?: FileUrlDirective[], onResponse?: (res: any) => void, onError?: (err: any) => void, mcpScope?: {
3512
+ anonymous?: boolean;
3513
+ publicProjectId?: string;
3514
+ }, turn?: ChatTurnContext): Promise<any>;
3515
+ declare function callOpenAIWithPublicMcp(prompt: string, service: string, owner: string, messages?: OpenAIMessage[], system?: string, model?: string, userId?: string, extractContent?: ExtractDirective[], fileUrls?: FileUrlDirective[], onResponse?: (res: any) => void, onError?: (err: any) => void, mcpScope?: {
3516
+ anonymous?: boolean;
3517
+ publicProjectId?: string;
3518
+ }, turn?: ChatTurnContext): Promise<any>;
3519
+ type AttachmentSaveInfo = {
3520
+ platform: 'claude' | 'openai';
3521
+ model?: string;
3522
+ service: string;
3523
+ /** The PUBLIC project ID (formatted token, skapi.project_id). Shown to the model; falls back to `service`. */
3524
+ publicProjectId?: string;
3525
+ owner: string;
3526
+ /**
3527
+ * Queue base for this indexing pass: "<userId>-bg". REQUIRED, and it must be
3528
+ * the SAME value the chat turn uses (ChatSession.dispatchComposedMessage's
3529
+ * `id.userId || id.projectId`) — the backend serialises requests that share a
3530
+ * queue name and runs different ones IN PARALLEL, so a pass enqueued under a
3531
+ * different base does not hold the chat back at all. It was optional once,
3532
+ * defaulting to `service`; the chatbox omitted it, and its files were indexed
3533
+ * on "<projectId>-bg" while its question ran on "<userId>-bg" — the question
3534
+ * was answered from a file nothing had read yet. Pass `userId || projectId`.
3535
+ */
3536
+ userId: string;
3537
+ serviceName?: string;
3538
+ serviceDescription?: string;
3539
+ attachment: {
3540
+ name: string;
3541
+ storagePath: string;
3542
+ mime?: string;
3543
+ size?: number;
3544
+ url: string;
3545
+ /**
3546
+ * Access group this file's records are written at (the uploader's choice,
3547
+ * already applied to the "src::" record). Threaded into the indexing
3548
+ * prompts so the agent's own records land in the same group; omitted
3549
+ * means "authorized", the group everything used before the setting existed.
3550
+ */
3551
+ accessGroup?: 'public' | 'authorized' | 'private';
3552
+ };
3553
+ /**
3554
+ * Content parsed CLIENT-SIDE by an attachment-parser plugin (e.g. an .hwp
3555
+ * parser). When set, it is inlined into the indexing message verbatim and
3556
+ * takes precedence over server-side office extraction / web_fetch.
3557
+ */
3558
+ parsedContent?: string;
3559
+ /**
3560
+ * True for a RESUME pass: a previous indexing pass could not finish this (large)
3561
+ * file, so continue it - always via readFileContent paging, with a "continue"
3562
+ * message telling the agent to resume from where the saved records leave off.
3563
+ */
3564
+ continueIndexing?: boolean;
3565
+ /** The pass's client reference, passed to forwardRequest's `cref`: a pass whose ack was
3566
+ * lost on the way is found by it in the queue listing and never sent twice. */
3567
+ cref?: string;
3568
+ /**
3569
+ * For an image-vision file (PDF), the 0-based PAGE the render window should start at.
3570
+ * The worker renders [renderFrom, renderFrom+RENDER_PAGES_PER_WINDOW) and injects them
3571
+ * as image blocks; the resume loop advances this by a window each pass.
3572
+ */
3573
+ renderFrom?: number;
3574
+ };
3575
+ declare function notifyAgentSaveAttachment(info: AttachmentSaveInfo): Promise<any>;
3576
+ declare function extractClaudeText(response: any): any;
3577
+ declare function extractOpenAIText(response: any): any;
3578
+ declare function listClaudeModels(service: string, owner: string): Promise<any>;
3579
+ declare function listOpenAIModels(service: string, owner: string): Promise<any>;
3580
+ declare const BG_INDEXING_QUEUE_SUFFIX = "-bg";
3581
+ /**
3582
+ * unique_id of the durable "indexing finished" marker record for a stored file.
3583
+ *
3584
+ * Written by the BACKEND (the polling worker calls the MCP server's
3585
+ * /internal/index-complete at the end of an auto_continue chain whose final
3586
+ * window reported no more content) and, for completions a client knows
3587
+ * deterministically (single-pass settle, client-chain completion token), by the
3588
+ * consumer's mintIndexDoneMarker hook — never by the model.
3589
+ * The marker record carries `reference: "src::<path>"`, so the reindex flow's
3590
+ * delete of the src:: record cascades to it and a re-run starts unmarked.
3591
+ *
3592
+ * Existence semantics: present = the whole file was read to the end. Absent =
3593
+ * unknown (still running, failed partway, indexed before this marker existed,
3594
+ * or a single-pass run minted before the client hook existed) - callers must
3595
+ * fall back to the live-queue probe (fetchLiveIndexingKeys) before reading
3596
+ * absence as anything.
3597
+ */
3598
+ /** What the MCP's /internal/index-reset answered. */
3599
+ type IndexResetResult = {
3600
+ path: string;
3601
+ /** The access group the old file record had, or null when there was none. */
3602
+ access_group: string | number | null;
3603
+ removed: number;
3604
+ missing: number;
3605
+ failed: number;
3606
+ decorations: number;
3607
+ ambiguous: number;
3608
+ ms?: number;
3609
+ };
3610
+ /**
3611
+ * Clear a file's index on the SERVER before a Reindex or an Overwrite (owner,
3612
+ * 2026-11-20): the MCP's /internal/index-reset removes the file record (and, through its
3613
+ * cascade, everything referencing it), the agent's decorated per-window ids and the
3614
+ * done::/run:: markers, in parallel, as the signed-in user. Reached through the host's
3615
+ * forwardRequest with "$ACCESS_TOKEN", which skapi fills in with the caller's own token,
3616
+ * so no client code ever holds it.
3617
+ *
3618
+ * Resolves to the server's answer, or null when the call could not be made or answered
3619
+ * something else (an older MCP without the route, a timeout): the caller then clears
3620
+ * the index itself, as it always did. Never rejects.
3621
+ */
3622
+ declare function resetFileIndexOnServer(args: {
3623
+ service: string;
3624
+ owner?: string;
3625
+ storagePath: string;
3626
+ }): Promise<IndexResetResult | null>;
3627
+ declare function indexDoneUniqueId(storagePath: string): string;
3628
+ /**
3629
+ * unique_id of the per-file indexing RUN record.
3630
+ *
3631
+ * One record per storage path, newest run wins (a reindex's delete-then-repost
3632
+ * of src:: cascade-deletes the old record first, exactly like done::). Minted
3633
+ * status='working' by the client the moment it enqueues a run's FIRST pass, and
3634
+ * closed (done/error/cancelled) by whichever side observes the ending: the
3635
+ * worker via the MCP internal routes for worker-driven chains, the client for
3636
+ * deterministic settles, cancels, and dispatch failures. It exists so chat rows
3637
+ * and files-page badges can answer "which runs exist and how did they end"
3638
+ * from ONE records query instead of scanning bg history.
3639
+ *
3640
+ * A 'working' record is a claim, not proof: a chain that dies without reaching
3641
+ * any error path leaves it dangling, so readers must treat a stale 'working'
3642
+ * (old `started`, no live-queue confirmation) as unknown, never as live.
3643
+ */
3644
+ declare function runIndexUniqueId(storagePath: string): string;
3645
+ type IndexRunStatus = 'working' | 'done' | 'error' | 'cancelled';
3646
+ type IndexRunPatch = {
3647
+ status: IndexRunStatus;
3648
+ filename?: string;
3649
+ started?: number;
3650
+ finished?: number;
3651
+ error?: string;
3652
+ queue?: string;
3653
+ /** Chat that owns this run. A run:: record is keyed by storage path alone,
3654
+ * but a chat is per (project, platform) — without this the Claude chat's
3655
+ * runs surfaced as rows in the same project's ChatGPT chat, where their
3656
+ * passes can never load and the queue probe can never see them. */
3657
+ platform?: 'claude' | 'openai';
3658
+ };
3659
+ /**
3660
+ * Wrapper over the consumer's upsertIndexRunRecord hook. Never throws: a run record
3661
+ * must never be able to break the run itself. A missing hook or an unconfigured engine
3662
+ * is a no-op.
3663
+ *
3664
+ * The promise: with `report`, it rejects when the write failed (the hook threw or its
3665
+ * promise rejected), so a caller that retries (the settle lock) can see it; without
3666
+ * `report` it always resolves (fire and forget).
3667
+ */
3668
+ declare function upsertIndexRunRecordSafe(service: string, storagePath: string, patch: IndexRunPatch, opts?: {
3669
+ report?: boolean;
3670
+ }): Promise<void>;
3671
+ /**
3672
+ * The one place the background-indexing queue name is spelled out. The backend
3673
+ * serialises requests sharing a queue name and runs different names in PARALLEL,
3674
+ * so every indexing pass AND the chat turn that must wait behind them have to
3675
+ * resolve to the identical string — see AttachmentSaveInfo.userId for what
3676
+ * happens when they do not.
3677
+ */
3678
+ declare function bgIndexingQueueName(userId?: string, service?: string): string;
3679
+ /**
3680
+ * True when a request belongs to the background-indexing queue.
3681
+ *
3682
+ * Accepts BOTH shapes this value arrives in: the bare queue name the client sends
3683
+ * ("<userId>-bg"), and the server qid that comes back on history/poll responses
3684
+ * ("<service>:<queue>|<seq>"). Testing the tail of the raw value only works for the
3685
+ * first: a qid ends in "|<seq>", so `endsWith('-bg')` is always false for it — which
3686
+ * silently meant history items were NEVER recognised as background tasks.
3687
+ */
3688
+ declare function isBgIndexingQueue(queueName?: string): boolean;
3689
+ type BgTaskEntry = {
3690
+ projectId: string;
3691
+ platform: 'claude' | 'openai';
3692
+ id: string;
3693
+ filename: string;
3694
+ storagePath?: string;
3695
+ isReindex?: boolean;
3696
+ mime?: string;
3697
+ size?: number;
3698
+ status: 'running' | 'pending';
3699
+ poll: ((opts: {
3700
+ latency: number;
3701
+ notify?: boolean;
3702
+ onResponse?: (res: any, meta?: {
3703
+ executed?: number;
3704
+ }) => void;
3705
+ }) => Promise<any>) | undefined;
3706
+ /** How many CONTINUE passes have already run for this file (resume-across-passes). */
3707
+ resumePass?: number;
3708
+ /** The STAGED chat turn these files were attached to (ChatSession.stageOutgoingMessage).
3709
+ * drainBgTaskQueue inserts this pass's bubble directly ABOVE that turn's bubble, so the
3710
+ * collapsed row sits where the reader expects it — right before the message the files
3711
+ * came with — from the moment it appears, instead of the turn being moved down past it
3712
+ * once everything finishes. Absent for work with no chat turn behind it (the dbfile
3713
+ * page, an attachment-only send, a worker-adopted pass), which appends as before. */
3714
+ stageId?: string;
3715
+ /** Settled from the 10-second queue check instead of its own poll (owner, 2026-11-20).
3716
+ * Set by drainBgTaskQueue on every pass when the host has csrHistoryItemLookup, and on
3717
+ * adoption for the worker's lanes. Polls on one queue run one at a time in skapi-js, so
3718
+ * a pass that finished waited behind every pass ahead of it; see
3719
+ * ChatSession._settleByListing. */
3720
+ byListing?: boolean;
3721
+ /** When this client first tracked the pass (ms). A pass missing from a listing taken
3722
+ * BEFORE that proves nothing about it. */
3723
+ adoptedAt?: number;
3724
+ /** The identity this pass was dispatched or adopted under, pinned at that moment
3725
+ * (reconciler plan, section 3 item 1). Its settle, its by-id reads and the next
3726
+ * CONTINUE pass of a client-driven file use this, never the identity live at the
3727
+ * time, which a project or platform switch has moved on. Filled by the engine the
3728
+ * first time it sees the entry when a host pushed it without one. */
3729
+ identity?: ChatIdentity;
3730
+ /** The project owner, pinned with the identity (by-id reads are scoped by it). */
3731
+ owner?: string;
3732
+ /** History cache key of the chat this pass belongs to, pinned with the identity. */
3733
+ ownerKey?: string;
3734
+ };
3735
+ declare const INDEXING_COMPLETE_MARKER = "INDEXING_COMPLETE";
3736
+ declare const EMPTY_INDEXING_REPLY = "Finished reading this file.";
3737
+ /**
3738
+ * `queue` narrows the fetch to one processing chain; `status` narrows it to items
3739
+ * in one state. Passing both is how the client asks "is there still unresolved
3740
+ * work on the background-indexing queue?" without pulling a page of chat history
3741
+ * (see ChatSession._adoptWorkerIndexingPasses) — the server answers that from a
3742
+ * status-keyed index, so the reply carries only the live items, not the bodies of
3743
+ * everything already finished.
3744
+ */
3745
+ declare function getChatHistory(params: {
3746
+ service?: string;
3747
+ owner?: string;
3748
+ platform: 'claude' | 'openai';
3749
+ queue?: string;
3750
+ status?: 'pending' | 'running' | 'resolved' | 'failed';
3751
+ /** Exact-queue listing: without it the qid range is a PREFIX match, so
3752
+ * queue "u1" also returns "u1-bg" rows. Requires the updated polling
3753
+ * lambda; older backends ignore it (harmless, wider results). */
3754
+ queue_exact?: boolean;
3755
+ /** Label/marker STUBS instead of full bodies (see the polling lambda).
3756
+ * Older backends ignore it and return full items. */
3757
+ compact?: boolean;
3758
+ /** Drop one queue's rows from an id-prefix listing — how the surface
3759
+ * chat is fetched WITHOUT the bg-indexing queue while legacy items on
3760
+ * odd queue names survive. Older backends ignore it. */
3761
+ queue_exclude?: string;
3762
+ /** "ids": the light listing (id, status, times, queue, cref; no bodies). skapi-js 2.7.0. */
3763
+ fields?: 'ids';
3764
+ /** Only rows newer than this request id. skapi-js 2.7.0. */
3765
+ after?: string;
3766
+ /** Transport options for a reconciler read (skapi-js 2.7.0): its deadline, an
3767
+ * abort signal, and `fresh` (never join an identical listing in flight). */
3768
+ deadline?: number;
3769
+ signal?: any;
3770
+ fresh?: boolean;
3771
+ }, fetchOptions: Record<string, any>): Promise<any>;
3772
+ /** Full server-side id of one history item, for a csr-poll POINT LOOKUP (the
3773
+ * single-item path returns the item WITH bodies — how an expanded row fetches
3774
+ * the passes a compact listing stubbed out). Mirrors the id the SDK builds:
3775
+ * `[METHOD]url#service:` + the item's own `stamp:entropy` id. */
3776
+ declare function buildHistoryItemFullId(platform: 'claude' | 'openai', service: string, itemId: string): string;
3516
3777
 
3517
3778
  /**
3518
3779
  * History mapping (pure). Moved verbatim from the chatbox. The clear-horizon
@@ -3524,6 +3785,10 @@ interface ChatHost {
3524
3785
  declare function filterListByClearHorizon(list: any[], clearedAt: number): any[];
3525
3786
  declare function normalizeTextContent(content: any): string;
3526
3787
  declare function extractLastUserTextFromRequest(requestBody: any): string;
3788
+ /** The last user text of a listed row: the compact stub's `request_text` when the
3789
+ * listing was compact (the body never left the server), else read from the full
3790
+ * request echo (a backend without compact stubs). */
3791
+ declare function listedRequestText(item: any): string;
3527
3792
  /** The two openings an indexing prompt can have. A bg-queue item that starts with
3528
3793
  * neither is an ordinary chat that happened to be routed onto that queue. */
3529
3794
  declare function isIndexingRequestText(userText: any): boolean;
@@ -3568,6 +3833,9 @@ declare function fetchLiveIndexingKeys(params: {
3568
3833
  platform: 'claude' | 'openai';
3569
3834
  /** Same value the dispatch used - see bgIndexingQueueName. */
3570
3835
  userId?: string;
3836
+ }, opts?: {
3837
+ /** Reuse a shared answer up to this old (default BG_PROBE_TTL_MS); 0 always asks. */
3838
+ maxAgeMs?: number;
3571
3839
  }): Promise<{
3572
3840
  keys: Set<string>;
3573
3841
  checked: boolean;
@@ -3691,6 +3959,20 @@ declare function mapHistoryListToMessages(list: any[], platform: 'claude' | 'ope
3691
3959
  * the settle would drop the real answer on the floor.
3692
3960
  */
3693
3961
  declare function adoptLocalAnswerIntoPage(incoming: ChatMessage, local: ChatMessage): boolean;
3962
+ /**
3963
+ * Keep the LIVE TEXT of a turn the page still shows as running. Mutates `incoming`;
3964
+ * true when it took anything.
3965
+ *
3966
+ * A running row maps to an empty "Thinking..." placeholder (the row has no body
3967
+ * yet), so a first-page refetch landing while an answer streams replaced the bubble
3968
+ * the reader was watching with an empty one. The painter only paints when the text
3969
+ * GROWS past what it already painted, so the bubble then sat on "Thinking..." until
3970
+ * a larger chunk arrived and jumped back, or, with every chunk already delivered,
3971
+ * stayed blank until the settle retyped the whole answer. The local copy is the same
3972
+ * turn (same server id), so its text and its live state come across; the settle
3973
+ * still replaces the text with the authoritative answer.
3974
+ */
3975
+ declare function adoptLiveTextIntoRunningRow(incoming: ChatMessage, local: ChatMessage): boolean;
3694
3976
  interface RescueDecisionContext {
3695
3977
  /** Is this `_serverItemId` in the page that was just fetched? */
3696
3978
  hasServerId: (id: string) => boolean;
@@ -4352,6 +4634,130 @@ type PollHandle = {
4352
4634
  /** Absent on an older skapi-js that cannot stop an attached poll. */
4353
4635
  stop?: () => void;
4354
4636
  };
4637
+ /** Where an item stands, by the server's account. Only ever moves forward. */
4638
+ type OpenItemState = 'queued' | 'running' | 'terminal';
4639
+ /**
4640
+ * An item this page follows (a chat turn or an indexing pass), with the identity it
4641
+ * belongs to PINNED at the moment it was added: the dispatch ack, a history page that
4642
+ * showed it running or waiting, or a background entry the drain adopted. Every settle,
4643
+ * read and follow-up of the item uses this identity, never the one live at the time,
4644
+ * which a project, platform or account switch has moved on.
4645
+ */
4646
+ type OpenItem = {
4647
+ /** History cache key (chatCacheKey) of the chat the item belongs to. */
4648
+ ownerKey: string;
4649
+ projectId: string;
4650
+ owner: string;
4651
+ platform: 'claude' | 'openai';
4652
+ /** The server queue it runs on, when known. */
4653
+ queue?: string;
4654
+ kind: 'chat' | 'indexing';
4655
+ state: OpenItemState;
4656
+ /** Wall clock when this page started following it: "did the reader watch it live". */
4657
+ addedAt: number;
4658
+ /** The send's client reference, when known (reconciler plan, section 3 item 9). */
4659
+ cref?: string;
4660
+ /** An anonymous visitor's item: its row is keyed by the network it was sent from, so
4661
+ * "missing" reads as "no longer reachable from this network". */
4662
+ anonymous?: boolean;
4663
+ /** performance.now() of the last look that read this item's status. 0 = never. */
4664
+ lastConfirmed: number;
4665
+ /** The status the last read gave (pending, running, resolved, ...). */
4666
+ lastStatus?: string;
4667
+ /** The row streams its answer (batch status `stream`). */
4668
+ stream?: boolean;
4669
+ /** When the worker began executing it (a running read's `executed`): the start of the
4670
+ * pass's duration when an older skapi-js's look, not a poll, settles it. */
4671
+ executedAt?: number;
4672
+ /** A look saw it terminal while a live poll or stream still held it: the next look
4673
+ * reads it itself if that reader has not settled it by then. */
4674
+ terminalSeen?: boolean;
4675
+ /** The user id of the identity it was sent under (ChatIdentity.userId), pinned when it
4676
+ * was added. A row is readable only by the caller who made it, so while another
4677
+ * identity is signed in (signed out, another account) the item is left alone: not
4678
+ * read, not settled, never marked "no longer available" (see _recReadable). */
4679
+ uid?: string;
4680
+ /** Envelope reads that answered body_unavailable (stored, not loadable now), and when
4681
+ * the last one was. See _recBodyUnavailable. */
4682
+ unavail?: number;
4683
+ unavailAt?: number;
4684
+ /** A worker-driven indexing pass read as failed without the worker's `retried` mark:
4685
+ * when that was (performance.now()). Read once more before the failure is shown, as
4686
+ * the worker writes the mark only after it queued the window again (plan 3.8). */
4687
+ failedPending?: number;
4688
+ /** That second read is due (a complete queue look came, or the wait ran out). */
4689
+ failedRecheck?: boolean;
4690
+ /** A chat turn sent by this page (dispatchAgentRequest): sends it once more when the
4691
+ * answer a look reads is an expired sign-in (the dispatch poll's one resend). Used once. */
4692
+ resend?: (body: any) => void;
4693
+ /** The send's turn context (dispatchAgentRequest), settled when a look applies its answer. */
4694
+ turn?: ChatTurnContext;
4695
+ };
4696
+ /** What trackOpenItem takes: the identity, plus the state the caller saw. */
4697
+ type OpenItemInit = {
4698
+ ownerKey?: string;
4699
+ projectId?: string;
4700
+ owner?: string;
4701
+ platform?: string;
4702
+ queue?: string;
4703
+ kind?: 'chat' | 'indexing';
4704
+ state?: 'queued' | 'running';
4705
+ cref?: string;
4706
+ anonymous?: boolean;
4707
+ /** The identity's user id it was sent under; the live identity's when left out. */
4708
+ uid?: string;
4709
+ };
4710
+ /** What a caller of applyTerminal / onPollFailure knows about the item. Every field
4711
+ * is optional: the pinned identity of an open item fills the gaps, the live identity
4712
+ * only after that. */
4713
+ type TerminalContext = {
4714
+ ownerKey?: string;
4715
+ projectId?: string;
4716
+ platform?: string;
4717
+ owner?: string;
4718
+ queue?: string;
4719
+ /** Write the text at once, never typed out. */
4720
+ instant?: boolean;
4721
+ /** A corrected answer for a turn already settled (a stream read back in full after
4722
+ * an incomplete live parse): replaces the settled text instead of being refused. */
4723
+ correction?: boolean;
4724
+ };
4725
+ /** Who a page watches the background indexing queue of (see ChatSession.watchIndexQueue). */
4726
+ type IndexQueueIdentity = {
4727
+ projectId: string;
4728
+ owner: string;
4729
+ platform: 'claude' | 'openai';
4730
+ /** The user the queue is named after (the same value the dispatch used). */
4731
+ userId?: string;
4732
+ };
4733
+ /** A page that shows indexing state from the queue (the dashboard's files page). */
4734
+ type IndexQueueWatchOptions = {
4735
+ /** Read live on every look: null while the page cannot ask (no platform, no key). */
4736
+ identity: () => IndexQueueIdentity | null;
4737
+ /** The page needs a second look soon (a green waiting for its confirmation). */
4738
+ wantsConfirm?: () => boolean;
4739
+ /** The page follows runs of its own that the queue cannot show (run:: 'working'
4740
+ * records of other users): recheckRuns is called every FILE_RUN_RECHECK_MS while
4741
+ * this says so and the tab is visible. */
4742
+ runsOpen?: () => boolean;
4743
+ recheckRuns?: () => void;
4744
+ };
4745
+ /** What watchIndexQueue hands back. */
4746
+ type IndexQueueWatchHandle = {
4747
+ /** Stop watching (the page unmounts). */
4748
+ stop(): void;
4749
+ /** A fresh read unless the last one is younger than `maxAgeMs` (default 0). Resolves
4750
+ * once the look that reads it is over (the snapshot is then in state.indexQueues). */
4751
+ refresh(maxAgeMs?: number): Promise<void>;
4752
+ /** Something the page waits on changed (wantsConfirm, runsOpen): the chain runs. */
4753
+ ensure(): void;
4754
+ };
4755
+ /** What a send whose row the server never showed says. */
4756
+ declare var NOT_SENT_TEXT: string;
4757
+ /** What a chat turn whose row is gone says ("missing" on a strongly consistent read). */
4758
+ declare var REQUEST_GONE_TEXT: string;
4759
+ /** The same for an anonymous visitor, whose rows are keyed by the network they were sent from. */
4760
+ declare var REQUEST_UNREACHABLE_TEXT: string;
4355
4761
  /**
4356
4762
  * The prefix of a still-arriving answer that is safe to render as markdown.
4357
4763
  *
@@ -5199,8 +5605,8 @@ declare class ChatSession {
5199
5605
  * history fetch issued in that window returns the turn ALREADY SETTLED, with no
5200
5606
  * pending assistant in it. The rescue then re-appends the local pair below the
5201
5607
  * server's copy (the question, twice), and when the poll finally resolves,
5202
- * typewriteLatestReply writes the answer into the rescued placeholder because it
5203
- * is the only pending assistant left (the answer, twice). updateHistoryCache
5608
+ * the old positional settle wrote the answer into the rescued placeholder because
5609
+ * it was the only pending assistant left (the answer, twice). updateHistoryCache
5204
5610
  * persists the result, so it survives every later visit.
5205
5611
  *
5206
5612
  * Navigating away while waiting and coming back is what lands a fetch in that
@@ -5215,15 +5621,101 @@ declare class ChatSession {
5215
5621
  * above these bubbles while the request is in flight.
5216
5622
  */
5217
5623
  private _stampTurnWithItemId;
5218
- /**
5219
- * Land a resolved reply in the history cache of a chat that is NOT currently
5220
- * visible, without touching state.messages. Mirrors the cache-only path in
5221
- * dispatchAgentRequest: REPLACE the trailing pending "Thinking..." bubble
5222
- * (append only when there is none), and settle the matching pending user
5223
- * bubble, so the cached copy never keeps a stuck "Thinking..." that a later
5224
- * cache-first load would re-render forever.
5225
- */
5226
- private _applyReplyToCache;
5624
+ /** Pinned identity of every item this page follows, by server id. Lazy, like the
5625
+ * stream-recovery bookkeeping, so a session built with Object.create works. */
5626
+ private _openItems?;
5627
+ /** Items whose result was applied (or that were cancelled), for the life of the page. */
5628
+ private _terminalIds?;
5629
+ /** Wall clock of the last time the tab was hidden; 0 = never in this page life. */
5630
+ private _hiddenAt?;
5631
+ private _visibilityWatched?;
5632
+ /** The by-id "is the next queued turn running yet" look (see _checkQueuedRunning). */
5633
+ private _queuedCheckTimer?;
5634
+ private _openMap;
5635
+ private _tomb;
5636
+ /** Remember when the tab was last hidden, for the "watched live" test. */
5637
+ private _watchVisibility;
5638
+ /**
5639
+ * Follow an item, with its identity pinned NOW (the ack, a page showing it running
5640
+ * or waiting, a background entry being adopted). Adding an id already followed
5641
+ * changes nothing but its state, and only forward; a terminal id is never reopened.
5642
+ */
5643
+ trackOpenItem(itemId: string, init: OpenItemInit): void;
5644
+ /** The pinned identity of an item this page follows, or null. */
5645
+ getOpenItem(itemId: string): OpenItem | null;
5646
+ /** True once an item's result was applied (or it was cancelled) in this page. */
5647
+ isItemSettled(itemId: string): boolean;
5648
+ private _closeItem;
5649
+ /** Did the reader watch this turn arrive? Live text was painted into it, or the tab
5650
+ * has stayed visible (with this chat on screen) since the page started following it. */
5651
+ private _watchedLive;
5652
+ /** The identity a settle uses: the caller's, then the pinned one, then the live one. */
5653
+ private _settleIdentity;
5654
+ /**
5655
+ * Apply how an item ended. The ONLY writer of a settled result; see the section note.
5656
+ * `result` is what the server gave back: a provider body, an error body, a cancelled
5657
+ * envelope, or a status envelope (which is not a result and is routed instead).
5658
+ * True when a bubble was written.
5659
+ */
5660
+ applyTerminal(itemId: string, result: any, ctx?: TerminalContext): boolean;
5661
+ /** Hand a settled provider answer to the host (ChatHost.onProviderAnswer), whichever
5662
+ * path read it. Optional, and never in the way of the settle. */
5663
+ private _noteProviderAnswer;
5664
+ /** A bubble of this item that still reads as waiting (a stale page can put one back). */
5665
+ private _hasWaitingBubble;
5666
+ /** The settled copy of a request bubble: its pending and sending flags come off,
5667
+ * everything that places it (file row, queue, chat, time, render key) stays. */
5668
+ private _settledUserCopy;
5669
+ /**
5670
+ * The shared core: settle the item with id `itemId` inside `list`, by id only.
5671
+ * Returns what happened and, for a reply to type out, where and from what.
5672
+ */
5673
+ private _settleInList;
5674
+ private _applyTerminalOnScreen;
5675
+ /** Put the whole text of a reply (found by local id) into a chat's cache copy. */
5676
+ private _patchCachedText;
5677
+ /** The same settle for a chat that is not on screen: made in its history cache,
5678
+ * which is what the next visit renders. Never typed. */
5679
+ private _applyTerminalToCache;
5680
+ /**
5681
+ * A read of an item failed (its poll, or a by-id read). Only the server's own answer
5682
+ * changes the screen: NOT_EXISTS settles the item as cancelled; a failure on the way
5683
+ * (network, timeout, 429, 5xx) or of the sign-in leaves everything as it is, and the
5684
+ * next look settles it; any other refusal is shown on the item, by id.
5685
+ */
5686
+ onPollFailure(itemId: string, err: any, ctx?: TerminalContext): 'cancelled' | 'kept' | 'failed';
5687
+ /**
5688
+ * A streamed turn's row settled 'resolved' with no body: its answer is in the chunk
5689
+ * store. A live stream that is still being fed settles it itself; otherwise the
5690
+ * chunks are read back by id, and the read's apply goes through the funnel.
5691
+ */
5692
+ private _readBackSettledStream;
5693
+ /** The server says the item is running (or waiting): move it forward, never back. */
5694
+ private _noteServerState;
5695
+ /**
5696
+ * Show a queued chat turn as RUNNING, found by its server id, because the server said
5697
+ * so. This replaces the guess that "the next waiting bubble on screen" was the one
5698
+ * the server took next. False when that turn is not waiting on screen.
5699
+ */
5700
+ private _promoteChatItemToRunning;
5701
+ /**
5702
+ * After a chat turn ends, ask the SERVER whether the next queued turn of this chat
5703
+ * runs now, by id: the oldest waiting main-queue turn with a server id is read once
5704
+ * (csrHistoryItemLookup) a few times over a few seconds, and promoted when the row
5705
+ * says running. Bounded and single: a new call restarts the ladder. A host without
5706
+ * the by-id read gets no promotion; the turn shows as answered when its poll settles.
5707
+ */
5708
+ /** The chat `key` is on screen and none of its main-queue turns shows as running
5709
+ * (no "Thinking..." of an ordinary turn): the next settle will not come to ask. */
5710
+ private _noRunningChatTurnOnScreen;
5711
+ private _checkQueuedRunning;
5712
+ /**
5713
+ * Settle a send that has NO server id: its POST failed, or the POST answered with a
5714
+ * body directly. Found by the bubbles' own local ids, never by position.
5715
+ */
5716
+ private _settleLocalTurn;
5717
+ /** A provider body (or error) read as the reply it renders as. */
5718
+ private _replyFromBody;
5227
5719
  /**
5228
5720
  * projectId/owner are passed explicitly by every caller: a request can be
5229
5721
  * dispatched after the user moved to another project, and re-reading the live
@@ -5247,6 +5739,31 @@ declare class ChatSession {
5247
5739
  * handler on the same chain is not a provider failure.
5248
5740
  */
5249
5741
  private _settleChatTurnTools;
5742
+ /**
5743
+ * Send one chat turn and follow it to its end. Two phases (reconciler plan, section 3
5744
+ * item 6):
5745
+ *
5746
+ * ACK. The POST that puts the turn on the server's queue. Only a 401 on THIS request
5747
+ * may refresh the session and send again, once. When it comes back with the server
5748
+ * id the turn is stamped (params.onItemId, matched by local id), pinned as an open
5749
+ * item, and the sending state clears: pendingAgentRequests[key] (an immediate send's
5750
+ * marker) is the ack and nothing longer.
5751
+ *
5752
+ * FOLLOW. The poll on that id. Whatever it ends with goes through applyTerminal or
5753
+ * onPollFailure. A failed READ never sends the turn again: a 401 on a poll tick used
5754
+ * to resend the whole prompt as a new request while the first one kept running.
5755
+ * The one resend left is the server's own FINAL answer saying the turn's
5756
+ * credentials expired (the MCP bearer the turn carried went stale): that turn is
5757
+ * over and failed, so one fresh turn is sent in its place.
5758
+ *
5759
+ * params: key, projectId, owner, aiPlatform, aiModel, systemPrompt, text,
5760
+ * boundedMessages, userId (the queue), extractContent, fileUrls, plus
5761
+ * userLid / placeholderLid the local ids of the turn's bubbles (a send with no
5762
+ * server id is settled through these);
5763
+ * onItemId(itemId) the ack, every time an id is learned;
5764
+ * onAck(itemId?) once, when the POST is over either way;
5765
+ * immediate an immediate send: marks pendingAgentRequests[key].
5766
+ */
5250
5767
  dispatchAgentRequest(params: any): Promise<any>;
5251
5768
  /**
5252
5769
  * Put a turn on screen the INSTANT the user hits Send, before its attachments
@@ -5257,9 +5774,9 @@ declare class ChatSession {
5257
5774
  *
5258
5775
  * Staged bubbles carry _useBgQueue because that is where a turn with
5259
5776
  * attachments ultimately dispatches (behind its own indexing tasks). That flag
5260
- * is also what keeps promoteNextQueuedToRunning / resolveQueuedUserBubble off
5261
- * them: those advance the SERVER queue, and a staged turn has no server
5262
- * request behind it yet.
5777
+ * is also what keeps the queued-turn promotion (_checkQueuedRunning) off them:
5778
+ * it follows the SERVER queue, and a staged turn has no server request behind
5779
+ * it yet.
5263
5780
  *
5264
5781
  * Returns the id to hand back as PinnedDispatchContext.stageId at dispatch.
5265
5782
  */
@@ -5352,42 +5869,24 @@ declare class ChatSession {
5352
5869
  */
5353
5870
  private scrollForDispatch;
5354
5871
  promoteNextBgQueuedToRunning(): void;
5872
+ /**
5873
+ * The next queued chat turn shows "Thinking..." once the SERVER says it runs.
5874
+ *
5875
+ * This used to promote "the first waiting bubble on screen" the moment any turn
5876
+ * ended, which was a guess about the server's queue, and wrong whenever the screen
5877
+ * and the queue disagreed: a turn still running on the server after a failed read,
5878
+ * a cancel in flight, a send whose ack had not come back. Now it asks: the oldest
5879
+ * waiting turn is read by id and promoted when its row says running (see
5880
+ * _checkQueuedRunning). Kept public under its old name for hosts that call it.
5881
+ */
5355
5882
  promoteNextQueuedToRunning(): void;
5356
5883
  /**
5357
- * The "Thinking..." placeholder belonging to the user bubble at `userIdx`, or -1.
5358
- *
5359
- * Every path that creates one puts it IMMEDIATELY after its user bubble
5360
- * (promoteNextQueuedToRunning, the immediate-send pair, applyHistoryItemResolution),
5361
- * so ownership is adjacency — modulo background bubbles, which get spliced in
5362
- * around them. Taking the first pending assistant ANYWHERE below instead was a
5363
- * hijack: a turn sent with attachments never gets a placeholder of its own
5364
- * (promoteNextQueuedToRunning skips _useBgQueue turns) and now keeps the position
5365
- * it was sent in, so an ordinary turn sent while its files indexed sits BELOW it
5366
- * with a placeholder of its own — and the attachment turn's answer was rendered
5367
- * as the answer to that unrelated question.
5368
- */
5369
- private _ownThinkingIndex;
5370
- resolveQueuedUserBubble(serverId?: string): number | undefined;
5371
- insertAtTarget(msg: ChatMessage, targetIdx: number): void;
5372
- /**
5373
- * The server's OWN copy of this turn is already on screen.
5374
- *
5375
- * A first-page fetch can land between the server settling the item and this
5376
- * poll's tick, and now that the local bubbles carry the item id
5377
- * (_stampTurnWithItemId) the rescue correctly drops them and renders the
5378
- * server's settled pair instead. There is then nothing left to resolve: the
5379
- * -1 fallback would push the answer in a SECOND time at the bottom of the list,
5380
- * and the positional fallbacks would hijack some other turn's bubble.
5381
- *
5382
- * The USER bubble counts, not just a settled assistant: an item whose answer is
5383
- * empty produces no assistant bubble at all in the mapper, and that variant
5384
- * would otherwise still bottom-push "No text response received...". While a turn
5385
- * is genuinely live its user bubble is always pending (the queued branch sets
5386
- * isPendingQueued, promoteNextQueuedToRunning sets isPendingInProcess), so this
5387
- * cannot fire early.
5388
- */
5389
- private _turnAlreadyRendered;
5884
+ * A queued send's answer, routed through the funnel by its server id. Kept for hosts
5885
+ * that call it; the engine's own queued path settles through dispatchAgentRequest.
5886
+ * Without a server id there is nothing to settle by, and nothing is written.
5887
+ */
5390
5888
  onQueuedSendResponse(_composed: string, response: any, platform: string, serverId?: string, ownerKey?: string): void;
5889
+ /** A queued send's failed read, routed through onPollFailure by its server id. */
5391
5890
  onQueuedSendError(_composed: string, err: any, serverId?: string, ownerKey?: string): void;
5392
5891
  cancelQueuedMessage(msg: ChatMessage, idx: number): void;
5393
5892
  /** The button's label and the message it sends, read off the session so the
@@ -5432,12 +5931,12 @@ declare class ChatSession {
5432
5931
  * 2. the poll on it is stopped, which settles whichever chain was awaiting it
5433
5932
  * with a stopped result: dispatchAgentRequest's for an immediate send, the
5434
5933
  * queued chain for a promoted turn, the history poll after a reload. Each
5435
- * reads a stopped or cancelled result as "no reply" and releases what it
5436
- * holds (state.sending, pendingAgentRequests, historyItemPolls), which is
5437
- * what lets the next send go out immediately instead of queueing;
5934
+ * reads a stopped result as "no reply" and releases its poll registration
5935
+ * (state.sending and pendingAgentRequests were already released at the ack);
5438
5936
  * 3. the bubbles settle at once, without waiting for that chain: the user
5439
- * bubble takes its cancelled form, the placeholder goes, and the next queued
5440
- * turn, if there is one, is promoted so its own "Thinking" appears.
5937
+ * bubble takes its cancelled form, the placeholder goes, the id is
5938
+ * tombstoned, and the server is asked whether the next queued turn runs now,
5939
+ * so its own "Thinking" appears when it does.
5441
5940
  *
5442
5941
  * What it does NOT do: the provider call already in flight on the worker runs
5443
5942
  * to its end (a streamed one stops within about a second). A message sent
@@ -5466,17 +5965,16 @@ declare class ChatSession {
5466
5965
  *
5467
5966
  * Idempotent on purpose: a cancel this client made settles the bubbles at once,
5468
5967
  * and the chain that was awaiting the poll settles again a moment later when the
5469
- * stop resolves it. The second pass finds nothing to do. Deliberately NOT
5470
- * _removeStrayPendingAssistants: by then the placeholder on screen is the freshly
5471
- * promoted turn's, whose user bubble is pending, and the sweep would take it.
5968
+ * stop resolves it. The second pass finds nothing to do.
5472
5969
  */
5473
5970
  private _settleCancelledTurn;
5474
5971
  /**
5475
5972
  * _settleCancelledTurn for a chat that is not on screen: the same edit, made in
5476
- * its history cache. Matched by id where the cached bubbles carry one; an
5477
- * off-chat send caches its pair before the ack (see dispatchComposedMessage), so
5478
- * the fallback is positional, exactly as _applyReplyToCache's is: the trailing
5479
- * pending placeholder, and the last request bubble still marked in flight.
5973
+ * its history cache, by id only. Every bubble of a turn that can be cancelled
5974
+ * carries its id: an off-chat send's pair is stamped at the ack like any other
5975
+ * (dispatchComposedMessage), and a cancel needs the id to be sent at all. (The
5976
+ * positional fallback this had, "the trailing pending placeholder", could take
5977
+ * another turn's.)
5480
5978
  */
5481
5979
  private _applyCancelToCache;
5482
5980
  /**
@@ -5504,23 +6002,321 @@ declare class ChatSession {
5504
6002
  typewriteIntoIndex(idx: number, fullText: string, localId?: string, paintedText?: string): Promise<void>;
5505
6003
  private typewriterQueue;
5506
6004
  enqueueTypewrite(idx: number, fullText: string, localId?: string, paintedText?: string): Promise<any>;
5507
- typewriteLatestReply(key: string): Promise<any>;
5508
- _removeStrayPendingAssistants(): void;
5509
- /** Index of the USER bubble the message at `idx` belongs to — the nearest one
5510
- * above it, stepping over background bubbles (a file's indexing rows are
5511
- * inserted between turns). -1 when the nearest thing above is not a user turn,
5512
- * which for a placeholder means it is an orphan. */
5513
- private _owningUserIndex;
5514
- /** The bubble at `idx` is the "Thinking…" of a DIFFERENT turn that is still
5515
- * waiting for its answer, so the sweep above must leave it alone. */
5516
- private _isLiveImmediatePlaceholder;
5517
- /** A pending assistant at `idx` is the placeholder OF the turn above it, so a
5518
- * reply may take its slot. Every path that makes one copies the parent's
5519
- * _serverItemId (or neither has one yet), so a mismatch means the slot belongs to
5520
- * some other request and the reply must be spliced in beside it, not on top. */
5521
- private _isOwnPlaceholderOf;
5522
6005
  _clearPendingUserBubble(itemId: string): void;
5523
- resumePendingRequest(token: number): Promise<void>;
6006
+ resumePendingRequest(_token: number): Promise<void>;
6007
+ private _sched?;
6008
+ /** The last counters seen, per "<projectId>|<queue>". */
6009
+ private _recCounters?;
6010
+ /** performance.now() of the last look that read every open item's status. */
6011
+ private _recFullReadAt;
6012
+ /** performance.now() of the last return look's start (see resumePolling). */
6013
+ private _recReturnAt;
6014
+ /** Open items a status frame named since the last look: read by the next one. */
6015
+ private _recFrameIds?;
6016
+ /** Looks that still read statuses after a counter moved: a queued turn starts a moment
6017
+ * after the one ahead of it finishes, and starting moves no counter. */
6018
+ private _recFollowUps;
6019
+ /** The backend refused the counters read (too old): statuses are read every look. */
6020
+ private _recCountersOff;
6021
+ /** The backend refused the batch status read (too old): today's polls instead. */
6022
+ private _recReadsOff;
6023
+ /** Chunks of a terminal streamed turn read so far, by id (a long answer can take more
6024
+ * than one read, and more than one look). */
6025
+ private _recChunks?;
6026
+ /** Sends whose POST got no answer, by cref. */
6027
+ private _recPending?;
6028
+ /** "Not sent. Retry?" replies, by their local id. */
6029
+ private _notSent?;
6030
+ /** Chat turns shown as "could not be loaded", tried again later (_recRetryUnloadable). */
6031
+ private _recUnloadable?;
6032
+ /** A first-page read a look could not run yet (a load in flight, polling paused). */
6033
+ private _recFirstPageOwed;
6034
+ /** performance.now() of the last first-page read a look started. */
6035
+ private _recFirstPageAt;
6036
+ /** gateRefreshToken of the last first-page load started (see loadHistory). */
6037
+ private _recFirstPageToken;
6038
+ /** performance.now() when the last first-page load landed (see loadHistory). */
6039
+ private _recFirstPageDoneAt;
6040
+ /** performance.now() of the last indexing queue check a look ran. */
6041
+ private _recAdoptAt;
6042
+ /** Indexing runs whose run:: record says 'working', by "<projectId>|<path>". */
6043
+ private _fileRuns?;
6044
+ /** Runs a complete queue look found no pass for: not re-opened by the same records. */
6045
+ private _fileRunsIdle?;
6046
+ private _fileRunCheckAt;
6047
+ private _recSyncing;
6048
+ /** Pages watching a project's background indexing queue (watchIndexQueue). */
6049
+ private _iqWatches;
6050
+ private _recNewMode;
6051
+ private _recSched;
6052
+ /** Keep the chain running at its cadence while there is anything to follow. */
6053
+ private _recEnsure;
6054
+ /** A view host may be absent (the dashboard's files page): nothing here may throw then. */
6055
+ private _viewMounted;
6056
+ private _viewNotify;
6057
+ /**
6058
+ * Look at the server now. `trigger` says why (default 'return': the user is back, so
6059
+ * readers restart and the first page is read). Resolves when that look ends. Any
6060
+ * number of calls at once run one look, plus exactly one more for calls that arrive
6061
+ * while it runs.
6062
+ */
6063
+ reconcileNow(trigger?: string): Promise<void>;
6064
+ /** The sign-in is back: looks resume at once (state.signInNeeded clears on success). */
6065
+ noteSignedIn(): void;
6066
+ /** A chat view was (re)opened: a return look (readers, discovery, first page). */
6067
+ noteViewOpened(): void;
6068
+ /** The host changed bgTaskQueue (the files page pushes passes with no chat view):
6069
+ * the new entries join the open set and the chain runs. */
6070
+ noteBgQueueChanged(): void;
6071
+ /**
6072
+ * True when this page's reconciler follows every bgTaskQueue entry itself, with or
6073
+ * without a chat view (the host's skapi-js has the batch reads). A host's own poller of
6074
+ * that queue (web-bunnyquery main.vue's fallback poller) then stands down: two
6075
+ * followers of one pass race to settle it, and the poller's settle skips the next pass
6076
+ * of a file this client drives and its run:: record.
6077
+ */
6078
+ followsBackgroundQueue(): boolean;
6079
+ /** Stop the reconciler's timer (tests, teardown). Any trigger starts it again. */
6080
+ stopReconciler(): void;
6081
+ /** Diagnostics: the open set's size, looks run, timers armed, pending sends. */
6082
+ reconcilerStats(): {
6083
+ open: number;
6084
+ looks: number;
6085
+ timers: number;
6086
+ generation: number;
6087
+ pendingSends: number;
6088
+ fileRuns: number;
6089
+ reconnecting: boolean;
6090
+ signInNeeded: boolean;
6091
+ running: boolean;
6092
+ };
6093
+ /** The bg entry of a pass, by id. */
6094
+ private _bgEntry;
6095
+ /** The queue an indexing pass runs on. */
6096
+ private _bgQueueOf;
6097
+ /**
6098
+ * Every bgTaskQueue entry is an open item, whoever pushed it (the engine, the files
6099
+ * page with no chat view, a host's own code). Its identity is pinned here when the
6100
+ * host pushed it without one, from the identity live now when that is the entry's
6101
+ * project.
6102
+ */
6103
+ private _syncOpenFromBgQueue;
6104
+ private _chains?;
6105
+ /** Passes whose chain ended (see _forgetChain): never kept again. */
6106
+ private _chainEnded?;
6107
+ private _chainsRestored;
6108
+ private _chainStorage;
6109
+ private _chainKey;
6110
+ /** Keep every client-driven pass in bgTaskQueue (the newest pass per file wins). */
6111
+ private _persistChains;
6112
+ /** The chain of this file ended: forget it (only when the kept pass is not newer than
6113
+ * `upToId`, a later run of the same file being newer; without it, whatever is kept). */
6114
+ private _forgetChain;
6115
+ /** Is a chain of this file kept (this page or another tab of this browser)? */
6116
+ private _chainKept;
6117
+ /** Once per page, at its first look: the kept chains go back into bgTaskQueue. */
6118
+ private _restoreChains;
6119
+ /** An open indexing pass whose file this client drives (it sends the next pass). */
6120
+ private _isClientDrivenOpen;
6121
+ /** What the chain has to follow: anything at all (visible cadence), and what is worth
6122
+ * a look once a minute while the tab is hidden (a client-driven chain: without the
6123
+ * browser its next pass is never sent). Never reads the network. */
6124
+ private _recWork;
6125
+ /** How a failed read is taken: 'auth' (the sign-in is gone), 'transient' (on the way),
6126
+ * 'refused' (the server's own no). */
6127
+ private _recErrKind;
6128
+ /** The user id signed in now (ChatIdentity.userId), or null when the host cannot say. */
6129
+ private _recLiveUid;
6130
+ /**
6131
+ * Can the caller signed in now read an item sent under `uid`? A row answers only the
6132
+ * identity that made it: after a sign-out (or with another account) every read of it
6133
+ * would come back "missing" and settle a turn that is fine as "no longer available".
6134
+ * Such an item is left exactly as it is (not read, not counted as work) until its user
6135
+ * is back. An item pinned before the user was known (uid = the project id, the hosts'
6136
+ * fallback) is always read.
6137
+ */
6138
+ private _recReadable;
6139
+ /** The newest server id of a chat known here (on screen, in its cache, or open). */
6140
+ private _recNewestKnownId;
6141
+ /** Put a send's cref on its bubbles (on screen and in the chat's cache). */
6142
+ private _stampCref;
6143
+ /** A send whose POST got no answer: its row is looked for by cref (see dispatchAgentRequest). */
6144
+ private _recAddPendingSend;
6145
+ /** Patch the bubbles of a local turn (by local id), on screen and in its chat's cache. */
6146
+ private _markLocalTurn;
6147
+ /**
6148
+ * Send again a turn that said "Not sent. Retry?". Only ever on the user's click: the
6149
+ * reply bubble goes back to waiting and the same send goes out with a new cref. False
6150
+ * when `msg` is not such a reply (or was retried already).
6151
+ */
6152
+ retryNotSent(msg: ChatMessage): boolean;
6153
+ /** Is a send of this chat in flight right now (see retryNotSent)? */
6154
+ private _chatBusy;
6155
+ /** True for a "Not sent. Retry?" reply that retryNotSent can still send. */
6156
+ canRetryNotSent(msg: ChatMessage): boolean;
6157
+ /**
6158
+ * Follow an indexing run from its run:: 'working' record (reconciler plan, section 3
6159
+ * item 1): the host passes the project's paths whose record says working, after every
6160
+ * read of those records. A run stays open until its record says done/error/cancelled
6161
+ * (it leaves the list), or a complete look at the queue finds no pass of it. While one
6162
+ * is open and not seen live, a look asks the host to read the records again
6163
+ * (host.recheckFileRuns) every FILE_RUN_RECHECK_MS: no fixed number of rounds.
6164
+ */
6165
+ syncFileRuns(projectId: string, workingPaths: string[], info?: {
6166
+ [path: string]: {
6167
+ owner?: string;
6168
+ filename?: string;
6169
+ };
6170
+ }): void;
6171
+ /** The runs of a project this page follows, by storage path. */
6172
+ openFileRuns(projectId: string): string[];
6173
+ /**
6174
+ * Watch a project's background indexing queue, with or without a chat view (the
6175
+ * dashboard's files page draws its "Indexing" and "Indexed" badges from it). The
6176
+ * reconciler's one timer chain reads it (no timer or poll of the page's own):
6177
+ * - at once when the watch starts, on every return (tab shown, wake, online,
6178
+ * reconnect) and when a status frame names the indexing queue;
6179
+ * - every 8 s while the queue holds work or the last read came back cut off (once a
6180
+ * minute while status frames arrive);
6181
+ * - every 2.5 s while the page waits for a second, independent look (wantsConfirm);
6182
+ * - never while the tab is hidden (a refresh() still reads).
6183
+ * The answer lands in state.indexQueues[projectId] (IndexQueueSnapshot). Runs the page
6184
+ * follows itself (runsOpen) get recheckRuns every FILE_RUN_RECHECK_MS from the same
6185
+ * chain. A failed read keeps the last snapshot.
6186
+ */
6187
+ watchIndexQueue(opts: IndexQueueWatchOptions): IndexQueueWatchHandle;
6188
+ /** The last read of a project's indexing queue (see watchIndexQueue), or null. */
6189
+ indexQueueSnapshot(projectId: string): IndexQueueSnapshot | null;
6190
+ private _iqIdentity;
6191
+ /** What the watches give the chain to do (see _recWork). */
6192
+ private _iqWork;
6193
+ /** The watched queues' part of a look: read the ones that are due (see watchIndexQueue). */
6194
+ private _iqLook;
6195
+ /**
6196
+ * A run closed idle (a complete queue look found no pass of it) whose record still says
6197
+ * 'working': when it is THIS user's run of a client-driven file and no browser tab here
6198
+ * keeps its chain (a reload, a discarded tab, or a browser without localStorage lost
6199
+ * it), nothing will ever send its next pass, so run:: says CHAIN_LOST_TEXT. Never for a
6200
+ * worker-driven file (the worker writes its endings), another user's run (their chain is
6201
+ * in their browser), or a run whose next pass is being looked for.
6202
+ */
6203
+ /** Files the last queue look listed pending or running, settled bubbles included. */
6204
+ private _rawListedIndexKeys;
6205
+ /** Runs found idle on one complete look, waiting for a second before "lost" (see below). */
6206
+ private _lostLooks;
6207
+ private _lostKey;
6208
+ private _flipIfChainLost;
6209
+ /** A file run the queue says is live, or that this page has a pass queued for. */
6210
+ private _fileRunLive;
6211
+ /** Ask the host to read the records of open runs that are not seen live. */
6212
+ private _recCheckFileRuns;
6213
+ /** A COMPLETE look at the queue (both listings shorter than their limit) found no pass
6214
+ * for these runs: they are over. The host reads their records one last time. */
6215
+ private _closeIdleFileRuns;
6216
+ /**
6217
+ * Rule 3 of 4b: on every return each live stream reader is stopped (and its in-flight
6218
+ * read aborted) before the look decides anything; a fresh one starts after the look if
6219
+ * the turn still streams. A reader whose poll cannot be stopped (an older skapi-js) is
6220
+ * left alone, and none is added beside it.
6221
+ */
6222
+ private _recStopLiveReaders;
6223
+ /** Start the one reader of a running streamed turn on screen that has none. */
6224
+ private _recStartReaders;
6225
+ private _recAttachReader;
6226
+ /** One look. See the section note. Never throws; never changes the screen on a failure. */
6227
+ private _reconcileLook;
6228
+ private _reconcileChatLook;
6229
+ /**
6230
+ * The look of a host whose skapi-js has no batch reads: today's polls stay, and the
6231
+ * look re-attaches what a failed poll let go of (onPollFailure 'kept', a bg entry whose
6232
+ * read failed): one by-id read each through csrHistoryItemLookup, a few per look.
6233
+ */
6234
+ private _reconcileLookLegacy;
6235
+ /**
6236
+ * The discovery listing: rows of a chat's queue newer than what the page knows, ids and
6237
+ * status only. On a return (the chat on screen), and while a send waits for its row
6238
+ * (its chat). A row carrying a waiting send's cref IS that send: its bubbles get the id
6239
+ * and it is followed like any acked turn. A waiting send no complete listing has shown
6240
+ * twice says "Not sent. Retry?". A live row nothing here knows makes the look read the
6241
+ * first page.
6242
+ */
6243
+ private _recDiscover;
6244
+ private _recApplyDiscovery;
6245
+ /** A waiting send's row was found by its cref: the send was received after all. */
6246
+ private _recMatchPending;
6247
+ /** Two complete listings never showed the send: it did not reach the server. Shown as
6248
+ * "Not sent. Retry?" and never sent again unless the user asks (retryNotSent). */
6249
+ private _recNotSent;
6250
+ /** The first history page, merged (loadHistory's own merge), on a return or when a live
6251
+ * row nothing here knows was seen. Not awaited: the look's own reads decide its outcome,
6252
+ * and the merge applies itself. Owed (run by a later look) while a load is in flight or
6253
+ * polling is paused. */
6254
+ private _recFirstPage;
6255
+ /** The indexing queue check (adoption, page progress, file runs), at its own cadence
6256
+ * inside the one chain. Needs the chat view: what it adopts are rows of that chat. */
6257
+ private _recIndexingCheck;
6258
+ /**
6259
+ * Read the queue counters and, when needed, the status of the open items.
6260
+ *
6261
+ * WHICH ITEMS. A row read costs as much as the conversation it carries, so a look reads
6262
+ * every open item only on a return and at the stale watch (once a minute). Otherwise it
6263
+ * reads only the items whose status can have changed: the ones never confirmed or seen
6264
+ * terminal, the ones a status frame named, and, when a counter moved or something
6265
+ * nudged the look (a settle asking for the next turn, a send), the running items plus
6266
+ * the head of each queue's line (a queue runs its requests in order, so only the first
6267
+ * few waiting ones can have started). A bulk upload's hundreds of waiting passes are
6268
+ * then read once a minute, not on every finish.
6269
+ */
6270
+ private _recReadStatuses;
6271
+ private _recReadGroup;
6272
+ private _recApplyStatuses;
6273
+ /** A pass the server says runs now: its waiting bubble becomes the running one, by id
6274
+ * (replaces promoteNextBgQueuedToRunning's guess). True when a bubble changed. */
6275
+ private _recPromoteBg;
6276
+ /** One item the batch read says is over: let a live reader settle it if it is still
6277
+ * being fed (one look's grace), else read it once and apply it. */
6278
+ private _recSettleTerminal;
6279
+ private _recChunkState;
6280
+ /**
6281
+ * The envelope read of one terminal item. A streamed turn with no stored answer is read
6282
+ * from its cursor (`since`), as many reads as it takes within the look, and is final
6283
+ * only when the cursor reaches `final_seq` (without one, when `more` is false); what is
6284
+ * read so far is kept for the next look when the deadline comes first.
6285
+ */
6286
+ private _recReadEnvelope;
6287
+ /**
6288
+ * An envelope read answered body_unavailable: the answer is stored but could not be
6289
+ * loaded now (an S3 read that failed on the server). Read again at every look for the
6290
+ * first BODY_UNAVAILABLE_BACKOFF_AFTER tries, then only at the stale watch or a return
6291
+ * (_recSettleTerminal). After BODY_UNAVAILABLE_GIVE_UP the turn stops saying
6292
+ * "Thinking..." and shows ANSWER_UNLOADABLE_TEXT; a later read that loads the answer
6293
+ * replaces that text (_recRetryUnloadable). An indexing pass ends with that error.
6294
+ */
6295
+ private _recBodyUnavailable;
6296
+ /**
6297
+ * Chat turns shown as ANSWER_UNLOADABLE_TEXT: one envelope read each at a return or
6298
+ * the stale watch, at most UNLOADABLE_RETRIES times. An answer that loads replaces the
6299
+ * text (a correction); a row that is gone or failed leaves the text as it is.
6300
+ */
6301
+ private _recRetryUnloadable;
6302
+ /** A streamed turn read whole (or given up on): shown at once, finalized only when
6303
+ * whole and keepable, with if_absent so a complete answer another tab stored wins. */
6304
+ private _recApplyStreamed;
6305
+ /** Apply one terminal value (a provider body, a failed or cancelled envelope). */
6306
+ private _recApplyValue;
6307
+ /** An item the server no longer has ("missing" on a strongly consistent read). */
6308
+ private _recApplyMissing;
6309
+ /** After a terminal apply: an item whose bubble is nowhere (no chat view, no cache of
6310
+ * its chat) is closed all the same; the next history load shows the server's state. */
6311
+ private _recAfterApply;
6312
+ /**
6313
+ * Store a streamed answer as the version history keeps (csr-finalize) with if_absent,
6314
+ * in the tab that holds the settle lock. When another tab stored one first ("exists"),
6315
+ * the stored one is read back and shown instead.
6316
+ */
6317
+ private _finalizeAnswer;
6318
+ /** Another tab stored this turn's answer first: show the stored one. */
6319
+ private _readStoredAnswer;
5524
6320
  /** Record how long a background indexing pass took, on the bubble that just
5525
6321
  * settled, so the duration shows immediately instead of waiting for whatever
5526
6322
  * next refetches history.
@@ -5536,18 +6332,10 @@ declare class ChatSession {
5536
6332
  * Indexing passes only: an ordinary turn has no duration to show, and
5537
6333
  * `_tsStart`'s presence is what both views read to decide. */
5538
6334
  private _stampPassDuration;
5539
- handleHistoryItemResolution(itemId: string, response: any, platform: string, executedAt?: number): void;
6335
+ handleHistoryItemResolution(itemId: string, response: any, platform: string, executedAt?: number, ctx?: TerminalContext): void;
5540
6336
  /** The file an already-rendered background pass is about, off its request
5541
6337
  * bubble. Null for an ordinary turn, which is most of them. */
5542
6338
  private _indexRefOfItem;
5543
- /**
5544
- * Settle a turn the server reports as cancelled: the request bubble goes to its
5545
- * cancelled form and the "Thinking..." placeholder goes away. The same shape
5546
- * cancelQueuedMessage produces locally, so a cancel this client made and one it
5547
- * merely found out about render identically — and an indexing pass keeps the
5548
- * markers that hold it in its file's collapsed row.
5549
- */
5550
- private _settleCancelledItem;
5551
6339
  /**
5552
6340
  * A poll that came back saying the request was CANCELLED, rather than with an
5553
6341
  * answer.
@@ -5563,7 +6351,13 @@ declare class ChatSession {
5563
6351
  * another device, or the row being cancelled server-side by the file's own stop.
5564
6352
  */
5565
6353
  private _isCancelledPollResult;
5566
- applyHistoryItemResolution(itemId: string, response: any, platform: string): void;
6354
+ /**
6355
+ * A history-attached poll (the engine's, agent.vue's, the files page's) settled.
6356
+ * Routed through the one funnel, by id: see applyTerminal. `ctx` is the identity the
6357
+ * caller pinned when it attached the poll; the open item's pinned identity fills
6358
+ * whatever it leaves out.
6359
+ */
6360
+ applyHistoryItemResolution(itemId: string, response: any, platform: string, ctx?: TerminalContext): void;
5567
6361
  /** How a bg task maps onto a collapsed row: the row's own key (storage path
5568
6362
  * when known, else the filename), scoped to the chat it belongs to. A storage
5569
6363
  * path is project-relative ("report.xlsx"), and ONE ChatSession serves every
@@ -5644,35 +6438,23 @@ declare class ChatSession {
5644
6438
  * work, so a tab return no longer re-asks for ten minutes after every run. Memory only:
5645
6439
  * a reload starts without it and asks once, as before. */
5646
6440
  private _idleVerdictAt;
5647
- private _adoptTickTimer;
5648
6441
  /** Newest wall-clock `_ts` of any indexing pass on screen, or 0. */
5649
6442
  private _newestIndexPassTs;
5650
6443
  /** Live indexing work THIS page is tracking for the project: a queued or adopted pass,
5651
6444
  * an attached bg poll, or a live key a look recorded. No recency guess. */
5652
6445
  private _hasLocalLiveIndexWork;
5653
- /** Start the ADOPT_TICK_MS follow-up if this page is tracking live indexing work and
5654
- * is visible. Idempotent; each tick re-checks and stops when the work is gone, the tab
5655
- * is hidden (resume restarts it through refreshLiveIndexState) or the view closed. */
5656
- private _catchUpAt;
5657
- private _catchUpTimer;
5658
- private _returnWatchTimer;
5659
- private _returnWatchAt;
5660
- private _returnListeners;
5661
6446
  private _statusUnsub;
5662
- private _statusNudgeTimer;
5663
- private _statusNudgeAt;
5664
6447
  private _statusSeenConnect;
5665
6448
  /**
5666
- * Re-read the chat from the server now (see the rule above). Safe to call from any
5667
- * number of triggers at once: calls within CATCH_UP_MIN_GAP_MS of the last one run
5668
- * once, at the end of the gap. Nothing happens while no chat view is mounted (the
5669
- * mount loads the chat anyway) or while background polling is paused (the tab is
5670
- * hidden: showing it calls this again).
6449
+ * Re-read the chat from the server now (see the rule above). A thin wrapper over the
6450
+ * reconciler's return look: safe to call from any number of triggers at once, runs
6451
+ * with no chat view too (the first page is read only when one is mounted, and owed
6452
+ * while polling is paused), and resolves when that look ends.
5671
6453
  */
5672
6454
  catchUpHistory(): Promise<void>;
5673
6455
  /**
5674
6456
  * Watch for the moments the user comes back without the tab being hidden first: the
5675
- * computer waking from sleep (the timer finds a gap far longer than its interval),
6457
+ * computer waking from sleep (the reconciler's timer finds a gap far longer than asked),
5676
6458
  * the network coming back, a page restored from the back-forward cache. Also starts
5677
6459
  * the status push listener. Runs while a chat view is mounted and stops itself when
5678
6460
  * none is.
@@ -5689,8 +6471,8 @@ declare class ChatSession {
5689
6471
  * was already woken by skapi-js itself. Chat turns are left to their own polls.
5690
6472
  */
5691
6473
  private _onRequestStatus;
5692
- /** Run the queue check (adopt, settle by listing, page progress) now, at most once per
5693
- * STATUS_NUDGE_MIN_GAP_MS, then let the heartbeat carry on. */
6474
+ /** Run the queue check (adopt, settle by listing, page progress) now, through the
6475
+ * reconciler's one chain. */
5694
6476
  private _nudgeQueueCheck;
5695
6477
  private _ensureAdoptTick;
5696
6478
  /** The last COMPLETE running+pending look at this user's bg queue: which pass ids were
@@ -5720,20 +6502,6 @@ declare class ChatSession {
5720
6502
  * the running one, with a "Thinking..." placeholder under it. False when that pass has
5721
6503
  * no waiting bubble (already running, settled, or not on screen). */
5722
6504
  private _promoteBgItemToRunning;
5723
- /** Turns whose findings were already looked at (a turn can settle by more than one path). */
5724
- private _findingsDone;
5725
- /**
5726
- * Save where a hard search found its answer (findings.ts), through the host's
5727
- * saveSearchFinding hook. Never for an indexing pass, never twice for one turn, never
5728
- * throws, never waited on.
5729
- *
5730
- * OFF since 1.20.1 (owner, 2026-11-24): the MCP's searchText now learns which page answered
5731
- * a question by itself (learned links, read first by every search), so the chat no longer
5732
- * reads "search_findings" first (that read cost 7 to 8 s at the start of every turn in
5733
- * production) and nothing is saved here. SAVE_SEARCH_FINDINGS turns it back on.
5734
- */
5735
- static SAVE_SEARCH_FINDINGS: boolean;
5736
- private _saveFindings;
5737
6505
  /**
5738
6506
  * Chats-only history (owner, 2026-11-21): on when the host can list a file's passes
5739
6507
  * (listIndexPasses) and read one by id (csrHistoryItemLookup). The history fetch then
@@ -5844,6 +6612,15 @@ declare class ChatSession {
5844
6612
  * repeats and races harmless. */
5845
6613
  _flipRunRecord(entry: BgTaskEntry, status: IndexRunStatus, error?: string): void;
5846
6614
  maybeResumeIndexing(entry: BgTaskEntry, response: any, platform: string): void;
6615
+ /**
6616
+ * Send the next pass of a client-driven file (maybeResumeIndexing) and follow it. A POST
6617
+ * that failed on the way may still have been queued, so with a cref it becomes a pending
6618
+ * send the discovery listing looks for on the bg queue: found, it is followed like any
6619
+ * pass; not found by two complete listings, it is sent once more with a new cref. A
6620
+ * refusal, a second miss, or no way to look for it (no cref, no batch reads) ends the
6621
+ * chain: run:: says NEXT_PASS_NOT_SENT_TEXT.
6622
+ */
6623
+ private _sendNextIndexingPass;
5847
6624
  loadHistory(fetchMore?: boolean, token?: number): Promise<void>;
5848
6625
  uploadSingleAttachment(att: any, stageId?: string): Promise<Array<{
5849
6626
  name: string;
@@ -5859,4 +6636,4 @@ declare class ChatSession {
5859
6636
  bumpGate(): void;
5860
6637
  }
5861
6638
 
5862
- export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, type AiAgentPlatform, type AnchorBoxEl, type AnchorRowEl, type AnswerMode, type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, type BgTaskEntry, type BoundedChatOptions, type BuildDisplayListOptions, type BuildIndexingUserMessageOptions, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatGreetingParams, type ChatGreetingParts, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatStreamWiring, type ChatSystemPromptParams, type ChatTurnContext, type Citation, type CitationLinkPart, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, type DisplayEntry, type DuplicateUploadFile, type DuplicateUploadMatch, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, type EncodingClass, type ExtractDirective, FINDINGS_TABLE, FINDING_ID_PREFIX, type FillHistoryViewportOptions, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, type ImagePreviewContext, type IndexResetResult, type IndexRunPatch, type IndexRunStatus, type IndexingAttachmentInfo, type IndexingFileRef, type IndexingGroup, type IndexingGroupStatus, type IndexingRequestRef, type IndexingSystemPromptParams, type InlineLinkContext, type InlineLinkMarkupOptions, type InlineLinkPart, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, type LiveStreamUpdate, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, type MapHistoryOptions, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, type ParsedAiAgent, type PinnedDispatchContext, type PreviewImageEl, type ProjectAccessSetting, type ProjectSettingsData, type ProjectSettingsReader, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, type RenderableInlineLink, type RescueDecisionContext, type RetrievalHit, type RetrievalNote, type RowAnchor, type RunStubInfo, STREAM_POLL_INTERVAL, type ScrollAnchor, type ScrollAnchorOptions, type SearchFinding, type SseChunk, type SseParser, type SseProvider, type SseSnapshot, type SseToolCall, type StoredCopyIndexing, type StreamDispatchContext, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, type UploadAccessGroup, type VisionProfile, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, keyWords as findingKeyWords, findingsForTurn, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, statusPushEnabled, statusPushLive, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
6639
+ export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, type AiAgentPlatform, type AnchorBoxEl, type AnchorRowEl, type AnswerMode, type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, type BgTaskEntry, type BoundedChatOptions, type BuildDisplayListOptions, type BuildIndexingUserMessageOptions, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatGreetingParams, type ChatGreetingParts, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatStreamWiring, type ChatSystemPromptParams, type ChatTurnContext, type Citation, type CitationLinkPart, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, type DisplayEntry, type DuplicateUploadFile, type DuplicateUploadMatch, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, type EncodingClass, type ExtractDirective, type FillHistoryViewportOptions, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, type ImagePreviewContext, type IndexQueueIdentity, type IndexQueueSnapshot, type IndexQueueWatchHandle, type IndexQueueWatchOptions, type IndexResetResult, type IndexRunPatch, type IndexRunStatus, type IndexingAttachmentInfo, type IndexingFileRef, type IndexingGroup, type IndexingGroupStatus, type IndexingRequestRef, type IndexingSystemPromptParams, type InlineLinkContext, type InlineLinkMarkupOptions, type InlineLinkPart, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, LOOK_DEADLINE_MS, LOOK_FAST_MS, LOOK_SLOW_MS, LOOK_STALE_MS, type LiveStreamUpdate, type LookOutcome, type LookRequest, LookScheduler, type LookTrigger, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, type MapHistoryOptions, NOT_SENT_TEXT, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, type OpenItem, type OpenItemInit, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, type ParsedAiAgent, type PinnedDispatchContext, type PreviewImageEl, type ProjectAccessSetting, type ProjectSettingsData, type ProjectSettingsReader, RENDER_FROM_TOKEN, REQUEST_GONE_TEXT, REQUEST_UNREACHABLE_TEXT, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, type RenderableInlineLink, type RescueDecisionContext, type RetrievalHit, type RetrievalNote, type RowAnchor, type RunStubInfo, STREAM_POLL_INTERVAL, type ScrollAnchor, type ScrollAnchorOptions, type SseChunk, type SseParser, type SseProvider, type SseSnapshot, type SseToolCall, type StoredCopyIndexing, type StreamDispatchContext, TOOL_AND_RESPONSE_BUFFER, type TerminalContext, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, type UploadAccessGroup, type VisionProfile, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLiveTextIntoRunningRow, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, crefSupported, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isNotExistsError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isReturnTrigger, isServerExtractable, isServiceDbAttachmentHref, isTransportFailure, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, listedRequestText, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, newClientRef, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, reconcilerReadsEnabled, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, runSettleSideEffect, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, sideEffectDone, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, statusPushEnabled, statusPushLive, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };