bunnyquery 1.19.0 → 1.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,7 +14,9 @@
14
14
  */
15
15
  import { buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingContinueMessage, buildIndexingRenderMessage, buildIndexingRenderContinueTemplate, buildIndexingWindowMessage } from './prompts';
16
16
  import { isServerExtractable, isPagedReadFile, isImageVisionFile, isWindowedReadFile, makeExtractPlaceholder, makeRenderPlaceholder, makeWindowPlaceholder, RENDER_PAGES_PER_WINDOW, type ExtractDirective, type FileUrlDirective } from './office';
17
- import { chatEngineConfig, resolveForwardRequest, resolveForwardRequestHistory, pollOpt, windowedIndexingEnabled, liveStreamingEnabled, liveStreamingSocketEnabled, resolveWebAccess } from './config';
17
+ import { chatEngineConfig, resolveForwardRequest, resolveForwardRequestHistory, pollOpt, windowedIndexingEnabled, liveStreamingEnabled, liveStreamingSocketEnabled, resolveWebAccess, resolveAnswerMode } from './config';
18
+ import { type AnswerMode } from './project_settings';
19
+ import { csrEnvelopeError } from './errors';
18
20
  // Output sizing lives in budget.ts so the request cap and the reserve the input
19
21
  // budget subtracts cannot drift; getMaxOutputTokens also clamps per model.
20
22
  import { getMaxOutputTokens, getModelContextWindow } from './budget';
@@ -335,8 +337,18 @@ const isOpenAINano = (model?: string) => {
335
337
 
336
338
  // Family floor, same shape as getOpenAIImageDetail's. "Contains nano" alone also matches
337
339
  // gpt-4.1-nano and anything else a project might name, and these are body fields an older
338
- // model REJECTS rather than ignores: one 400 with no retry kills every indexing pass. Only
339
- // gpt-5.4 and newer are known to take `text.verbosity` and `reasoning.effort`.
340
+ // model REJECTS rather than ignores: one 400 with no retry kills every indexing pass.
341
+ return openAITakesReasoningEffort(normalized);
342
+ };
343
+
344
+ /**
345
+ * The family floor for `text.verbosity` and `reasoning.effort` on OpenAI: only gpt-5.4 and
346
+ * newer are known to take them. Shared by the indexing knob above and the chat answer mode
347
+ * (chatEffortFields), because an older model REJECTS these fields rather than ignoring them.
348
+ * Anything that does not parse as gpt-<major>[.<minor>][-variant] answers false.
349
+ */
350
+ const openAITakesReasoningEffort = (model?: string) => {
351
+ const normalized = (model || DEFAULT_OPENAI_MODEL).trim().toLowerCase();
340
352
  const match = normalized.match(/^gpt-(\d+)(?:\.(\d+))?(-[a-z0-9.\-]+)?$/);
341
353
  if (!match) return false;
342
354
  const major = Number(match[1]);
@@ -344,6 +356,49 @@ const isOpenAINano = (model?: string) => {
344
356
  return major > 5 || (major === 5 && minor !== null && minor >= 4);
345
357
  };
346
358
 
359
+ /**
360
+ * True for the Claude models known to take `output_config.effort` (GA, no beta header):
361
+ * Opus 4.5 and newer, the 4.6 and newer family (Sonnet 4.6, Opus 4.6 to 4.8), Sonnet 5.x,
362
+ * Opus 5.x, Haiku 5.5 and newer, and every Fable and Mythos model. The field is an ERROR on
363
+ * Haiku 4.5, Sonnet 4.5 and older, so those, and any id that does not parse, answer false.
364
+ * A dated snapshot ("claude-opus-4-5-20251101") reads as its base model.
365
+ */
366
+ const claudeTakesEffort = (model?: string) => {
367
+ const normalized = (model || DEFAULT_CLAUDE_MODEL).trim().toLowerCase().replace(/\[1m\]$/, '');
368
+ const match = normalized.match(/^claude-([a-z]+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:-\d{8})?$/);
369
+ if (!match) return false;
370
+ const family = match[1];
371
+ if (family === 'fable' || family === 'mythos') return true;
372
+ if (match[2] === undefined) return false;
373
+ const major = Number(match[2]);
374
+ const minor = match[3] === undefined ? 0 : Number(match[3]);
375
+ if (family === 'opus') return major > 4 || (major === 4 && minor >= 5);
376
+ if (family === 'sonnet') return major > 4 || (major === 4 && minor >= 6);
377
+ if (family === 'haiku') return major > 5 || (major === 5 && minor >= 5);
378
+ return false;
379
+ };
380
+
381
+ /** The effort a chat answer mode asks for; null for 'standard' (send nothing). */
382
+ const ANSWER_MODE_EFFORT: Record<AnswerMode, 'low' | 'high' | null> = {
383
+ standard: null,
384
+ fast: 'low',
385
+ thorough: 'high',
386
+ };
387
+
388
+ /**
389
+ * The body fields a CHAT turn's answer mode adds, for the one provider and model the turn
390
+ * runs on. An empty object, i.e. nothing at all, for 'standard' (the default) and for any
391
+ * model not known to accept the field, so a project that never set a mode sends the exact
392
+ * request it sent before the setting existed. OpenAI takes `reasoning: {effort}`, Claude
393
+ * takes `output_config: {effort}`. Never used by an indexing pass.
394
+ */
395
+ export function chatEffortFields(platform: 'claude' | 'openai', model: string | undefined, mode: AnswerMode | undefined): Record<string, any> {
396
+ const effort = mode ? ANSWER_MODE_EFFORT[mode] : null;
397
+ if (!effort) return {};
398
+ if (platform === 'openai') return openAITakesReasoningEffort(model) ? { reasoning: { effort } } : {};
399
+ return claudeTakesEffort(model) ? { output_config: { effort } } : {};
400
+ }
401
+
347
402
  /**
348
403
  * The indexing-only body knobs, for the ONE tier that needs them: gpt-5.4-nano.
349
404
  *
@@ -685,6 +740,159 @@ export const STREAM_POLL_INTERVAL = 1000;
685
740
  //
686
741
  // FOREGROUND polls (a reply the user is actively waiting on) are never capped.
687
742
  export const MAX_CONCURRENT_BG_POLLS = 6;
743
+
744
+ /**
745
+ * What a chat turn hands the OpenAI request builder about itself, and what the builder
746
+ * writes back. Created per turn by ChatSession; a host that calls the builder directly
747
+ * and passes nothing gets exactly the request it always got.
748
+ */
749
+ export type ChatTurnContext = {
750
+ /**
751
+ * Reuse the MCP tool listing OpenAI returned on an earlier chat turn (OpenAI only).
752
+ * Every OpenAI turn otherwise starts with OpenAI asking our MCP server for its tools,
753
+ * four sequential requests (server/discover, initialize, notifications/initialized,
754
+ * tools/list), about 0.6 s before the model starts. OpenAI's docs: "As long as the
755
+ * mcp_list_tools item is present in the context of an API request, the API will not
756
+ * fetch a list of tools from the MCP server again at each turn."
757
+ */
758
+ reuseMcpToolList?: boolean;
759
+ /** Who the turn runs as. Part of the listing key: a different user can see a different list. */
760
+ userId?: string;
761
+ /** Written by the builder: the key this turn's listing is stored under. */
762
+ mcpToolsKey?: string;
763
+ /** Written by the builder: true when a stored listing rode in this turn's input. */
764
+ mcpToolsInjected?: boolean;
765
+ /** Written by the builder: the project the listing belongs to (for the per-project off verdict). */
766
+ mcpToolsService?: string;
767
+ /** Written by the builder: the id of the listing that rode in this turn's input. */
768
+ mcpToolsItemId?: string;
769
+ /** Set by ChatSession once the turn's outcome was applied, so a later handler cannot apply it twice. */
770
+ settled?: boolean;
771
+ };
772
+
773
+ type McpListToolsItem = { type: 'mcp_list_tools'; id: string; server_label: string; tools: any[] };
774
+
775
+ /**
776
+ * The last good `mcp_list_tools` output item per listing key, for this page's lifetime.
777
+ * Memory only: a reload starts empty and its first turn lets OpenAI fetch the list.
778
+ *
779
+ * The key is everything that can change what tools/list answers: the exact server_url
780
+ * (endpoint, `profile` and `ctx`), signed in or anonymous, the project, and the user.
781
+ */
782
+ const mcpListToolsCache = new Map<string, McpListToolsItem>();
783
+ /**
784
+ * Set once a turn that carried a stored listing was refused as a malformed request
785
+ * (see forgetMcpListToolsOnFailure). From then on this page never injects one again.
786
+ */
787
+ let mcpListToolsReuseOff = false;
788
+
789
+ /**
790
+ * Per project, in this browser: OpenAI refused the injected item itself. Kept in
791
+ * localStorage so an account that will not take the item (for example one with zero
792
+ * data retention) costs one failed turn per browser, not one per page load. Wrapped in
793
+ * try/catch everywhere: storage can be missing or blocked, and then the verdict simply
794
+ * lasts for this page (mcpListToolsReuseOff).
795
+ */
796
+ const MCP_LIST_TOOLS_OFF_PREFIX = 'bunnyquery:mcp-list-tools-off:';
797
+
798
+ function mcpListToolsOffStored(service: string): boolean {
799
+ try {
800
+ return typeof localStorage !== 'undefined' && !!localStorage.getItem(MCP_LIST_TOOLS_OFF_PREFIX + service);
801
+ } catch (_) {
802
+ return false;
803
+ }
804
+ }
805
+
806
+ function storeMcpListToolsOff(service: string | undefined): void {
807
+ if (!service) return;
808
+ try {
809
+ if (typeof localStorage !== 'undefined') localStorage.setItem(MCP_LIST_TOOLS_OFF_PREFIX + service, String(Date.now()));
810
+ } catch (_) {
811
+ // Storage blocked: the page-level flag still holds for this page.
812
+ }
813
+ }
814
+
815
+ /**
816
+ * The server's enqueue step replaces these literals in every string of the request
817
+ * data with the project's secret or the caller's tokens. Before tool-list reuse, tool
818
+ * descriptions never passed through that step (OpenAI fetched them itself). A listing
819
+ * that mentions one of them is therefore never stored, so it can never be injected.
820
+ * Chat-profile tool text should not contain them in the first place.
821
+ */
822
+ const SERVER_PLACEHOLDERS = ['$CLIENT_SECRET', '$ACCESS_TOKEN', '$ID_TOKEN'];
823
+
824
+ function failureText(failure: any): string {
825
+ const env = csrEnvelopeError(failure);
826
+ const f = env !== undefined ? env : failure;
827
+ if (f == null) return '';
828
+ if (typeof f === 'string') return f.toLowerCase();
829
+ let text = '';
830
+ try { text = JSON.stringify(f) || ''; } catch (_) { text = ''; }
831
+ if (typeof f.message === 'string') text += ' ' + f.message;
832
+ return text.toLowerCase();
833
+ }
834
+
835
+ function failureStatus(failure: any): number | undefined {
836
+ const env = csrEnvelopeError(failure);
837
+ const f = env !== undefined ? env : failure;
838
+ if (!f || typeof f !== 'object') return undefined;
839
+ const v = typeof f.status_code === 'number' ? f.status_code : typeof f.status === 'number' ? f.status : undefined;
840
+ return v;
841
+ }
842
+
843
+ function mcpListToolsKey(serverUrl: string, anonymous: boolean | undefined, service: string, publicProjectId: string | undefined, userId: string | undefined): string {
844
+ return JSON.stringify([serverUrl, anonymous ? 'anonymous' : 'signed-in', service, publicProjectId || '', userId || '']);
845
+ }
846
+
847
+ /**
848
+ * Keep the listing a settled OpenAI chat turn returned, under the key its request was
849
+ * built with. Only an item from our own server (server_label === MCP_NAME) that carries
850
+ * no error and a tools array is kept, and it is kept exactly as received. A body with no
851
+ * such item (an error, or a turn that already carried the stored item, which OpenAI then
852
+ * does not list again) leaves the stored entry as it is.
853
+ */
854
+ export function rememberMcpListTools(turn: ChatTurnContext | undefined, body: any): void {
855
+ if (!turn || !turn.mcpToolsKey || mcpListToolsReuseOff) return;
856
+ const output = body && Array.isArray(body.output) ? body.output : null;
857
+ if (!output) return;
858
+ for (let i = output.length - 1; i >= 0; i--) {
859
+ const item = output[i];
860
+ if (!item || item.type !== 'mcp_list_tools' || item.server_label !== MCP_NAME) continue;
861
+ if (item.error || typeof item.id !== 'string' || !item.id || !Array.isArray(item.tools)) continue;
862
+ let toolsText = '';
863
+ try { toolsText = JSON.stringify(item.tools); } catch (_) { return; }
864
+ if (SERVER_PLACEHOLDERS.some((ph) => toolsText.indexOf(ph) !== -1)) return;
865
+ mcpListToolsCache.set(turn.mcpToolsKey, { type: 'mcp_list_tools', id: item.id, server_label: item.server_label, tools: item.tools });
866
+ return;
867
+ }
868
+ }
869
+
870
+ /**
871
+ * A chat turn failed. If it carried a stored listing, that entry is always dropped, so
872
+ * the next message goes out the way it did before reuse existed (OpenAI fetches the list
873
+ * itself) and a good answer stores a fresh one. How far the verdict reaches depends on
874
+ * the failure:
875
+ * - the error names the item (`mcp_list_tools` or the injected id): reuse stays off for
876
+ * this project in this browser (localStorage) and for this page;
877
+ * - any other malformed-request refusal (HTTP 400 / 422, `invalid_request_error`):
878
+ * reuse stays off for this page;
879
+ * - anything else (rate limit, provider 5xx, network, a timeout): only the entry goes.
880
+ * The failed turn itself is not retried: its error shows like any other provider error.
881
+ */
882
+ export function forgetMcpListToolsOnFailure(turn: ChatTurnContext | undefined, failure?: any): void {
883
+ if (!turn || !turn.mcpToolsInjected) return;
884
+ if (turn.mcpToolsKey) mcpListToolsCache.delete(turn.mcpToolsKey);
885
+ const text = failureText(failure);
886
+ const status = failureStatus(failure);
887
+ const namesItem = text.indexOf('mcp_list_tools') !== -1 || (!!turn.mcpToolsItemId && text.indexOf(turn.mcpToolsItemId.toLowerCase()) !== -1);
888
+ if (namesItem) {
889
+ mcpListToolsReuseOff = true;
890
+ storeMcpListToolsOff(turn.mcpToolsService);
891
+ return;
892
+ }
893
+ if (status === 400 || status === 422 || text.indexOf('invalid_request_error') !== -1) mcpListToolsReuseOff = true;
894
+ }
895
+
688
896
  export async function callClaudeWithMcp({
689
897
  prompt,
690
898
  messages,
@@ -703,6 +911,10 @@ export async function callClaudeWithMcp({
703
911
  // builder directly gets the same switch: the project's setting is the ceiling,
704
912
  // and an explicit `false` (here or in the config) restricts below it.
705
913
  const web = await resolveWebAccess(service, typeof webAccess === 'boolean' ? webAccess : undefined);
914
+ // The project's answer mode. Empty (no field at all) for 'standard' and for a model
915
+ // that does not take `output_config.effort`. Same store as the web switch above, so
916
+ // this joins the read that already settled rather than starting a second one.
917
+ const effortFields = chatEffortFields('claude', model, await resolveAnswerMode(service));
706
918
  const mcpServerDefinition: Record<string, any> = {
707
919
  type: 'url',
708
920
  name: mcpServer.name,
@@ -738,6 +950,8 @@ export async function callClaudeWithMcp({
738
950
  data: {
739
951
  model,
740
952
  max_tokens: maxTokens,
953
+ // `output_config: {effort}` for a fast or thorough project, nothing otherwise.
954
+ ...effortFields,
741
955
  // Top level beside model/messages/mcp_servers, which is where the
742
956
  // Messages API takes it.
743
957
  ...stream.body,
@@ -840,13 +1054,34 @@ export async function callOpenAIWithPublicMcp(
840
1054
  onResponse?: (res: any) => void,
841
1055
  onError?: (err: any) => void,
842
1056
  mcpScope?: { anonymous?: boolean; publicProjectId?: string },
1057
+ turn?: ChatTurnContext,
843
1058
  ) {
844
1059
  const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
845
1060
  const resolvedModel = model || DEFAULT_OPENAI_MODEL;
846
1061
  const imageDetail = getOpenAIImageDetail(resolvedModel);
1062
+ const serverUrl = mcpChatUrl(endpoint.url, 'openai', resolvedModel);
847
1063
  // The project's web switch: host option, then the `web_access` setting, then
848
1064
  // off. Awaited so the first turn after a page load reads the stored value.
849
1065
  const web = await resolveWebAccess(service);
1066
+ // The project's answer mode, from the same settled read. Empty (no `reasoning`
1067
+ // key at all) for 'standard' and for a model older than gpt-5.4.
1068
+ const effortFields = chatEffortFields('openai', resolvedModel, await resolveAnswerMode(service));
1069
+ // The tool listing an earlier chat turn got for this exact server_url, user and
1070
+ // project, if the caller opted in. See ChatTurnContext.
1071
+ let listedTools: McpListToolsItem | undefined;
1072
+ if (turn) {
1073
+ turn.mcpToolsKey = undefined;
1074
+ turn.mcpToolsInjected = false;
1075
+ turn.mcpToolsService = undefined;
1076
+ turn.mcpToolsItemId = undefined;
1077
+ if (turn.reuseMcpToolList && !mcpListToolsReuseOff && !mcpListToolsOffStored(service)) {
1078
+ turn.mcpToolsKey = mcpListToolsKey(serverUrl, mcpScope?.anonymous, service, mcpScope?.publicProjectId, turn.userId);
1079
+ turn.mcpToolsService = service;
1080
+ listedTools = mcpListToolsCache.get(turn.mcpToolsKey);
1081
+ turn.mcpToolsInjected = !!listedTools;
1082
+ if (listedTools) turn.mcpToolsItemId = listedTools.id;
1083
+ }
1084
+ }
850
1085
  const messageList =
851
1086
  messages && messages.length
852
1087
  ? prepareOpenAIMessages(messages, imageDetail)
@@ -866,6 +1101,14 @@ export async function callOpenAIWithPublicMcp(
866
1101
  },
867
1102
  ]
868
1103
  : []),
1104
+ // Right after the system message, exactly as OpenAI returned it, so OpenAI
1105
+ // skips asking the MCP server for its tools again. Absent unless stored.
1106
+ // This item passes through the server's $CLIENT_SECRET / $ACCESS_TOKEN /
1107
+ // $ID_TOKEN substitution; rememberMcpListTools never stores a listing that
1108
+ // contains one of those literals.
1109
+ ...(listedTools
1110
+ ? [{ type: listedTools.type, id: listedTools.id, server_label: listedTools.server_label, tools: listedTools.tools }]
1111
+ : []),
869
1112
  ...messageList.map((m) => ({
870
1113
  role: m.role,
871
1114
  content: m.content,
@@ -891,6 +1134,8 @@ export async function callOpenAIWithPublicMcp(
891
1134
  data: {
892
1135
  model: resolvedModel,
893
1136
  max_output_tokens: getMaxOutputTokens('openai', resolvedModel),
1137
+ // `reasoning: {effort}` for a fast or thorough project, nothing otherwise.
1138
+ ...effortFields,
894
1139
  // Top level beside model/input/tools, which is where the Responses API
895
1140
  // takes it.
896
1141
  ...stream.body,
@@ -905,7 +1150,7 @@ export async function callOpenAIWithPublicMcp(
905
1150
  {
906
1151
  type: 'mcp',
907
1152
  server_label: MCP_NAME,
908
- server_url: mcpChatUrl(endpoint.url, 'openai', resolvedModel),
1153
+ server_url: serverUrl,
909
1154
  require_approval: 'never',
910
1155
  // No `headers` at all for an anonymous turn: `Bearer ` with an
911
1156
  // empty token is a credential the MCP server rejects, and the
@@ -37,6 +37,9 @@ import {
37
37
  ANTHROPIC_MESSAGES_API_URL,
38
38
  OPENAI_RESPONSES_API_URL,
39
39
  upsertIndexRunRecordSafe,
40
+ rememberMcpListTools,
41
+ forgetMcpListToolsOnFailure,
42
+ type ChatTurnContext,
40
43
  type IndexRunStatus,
41
44
  type IndexRunPatch,
42
45
  type BgTaskEntry,
@@ -674,6 +677,8 @@ export class ChatSession {
674
677
  passPaging: {},
675
678
  liveIndexChecked: false,
676
679
  liveIndexRunning: {},
680
+ liveIndexRunningChecked: false,
681
+ liveIndexSettled: {},
677
682
  stoppedIndexIds: {},
678
683
  };
679
684
  this.bgTaskQueue = [];
@@ -701,8 +706,8 @@ export class ChatSession {
701
706
  /** What the display layer needs to decide whether a run is finished. `keys` holds
702
707
  * every file the server still has indexing work for; `checked` is false until the
703
708
  * first answer for this chat, and false means "we do not know yet". */
704
- getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean; running: { [fileKey: string]: boolean } } {
705
- return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {} };
709
+ getLiveIndexState(): { keys: { [fileKey: string]: boolean }; checked: boolean; running: { [fileKey: string]: boolean }; runningChecked: boolean; settled: { [fileKey: string]: boolean } } {
710
+ return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {}, runningChecked: !!this.state.liveIndexRunningChecked, settled: this.state.liveIndexSettled || {} };
706
711
  }
707
712
 
708
713
  /** Passes that were on a row when the user stopped it, so the display layer can
@@ -1003,6 +1008,11 @@ export class ChatSession {
1003
1008
  // and omits the 20 about to run. Absence would then read as "finished" for
1004
1009
  // exactly the files that have not been touched yet. Report not-knowing instead.
1005
1010
  var truncated = false;
1011
+ // The RUNNING half on its own. A file indexes in at most a few parallel lanes, so the
1012
+ // running list practically never fills; the pending one fills on any bulk upload. A
1013
+ // complete running half still proves something when the pending half is cut off: a
1014
+ // file whose run is open and which is not running is waiting its turn.
1015
+ var runningTruncated = false;
1006
1016
  // Locally settled already. The adopt path refuses these items for the same
1007
1017
  // reason and says why: the status index is eventually consistent, so the pass
1008
1018
  // that just finished can still come back as running. Counting it as live work
@@ -1016,7 +1026,16 @@ export class ChatSession {
1016
1026
  });
1017
1027
  for (var li = 0; li < lists.length; li++) {
1018
1028
  var list = lists[li] && Array.isArray(lists[li].list) ? lists[li].list : [];
1019
- if (list.length >= WORKER_PASS_ADOPT_LIMIT) truncated = true;
1029
+ // Cut off when it came back full OR the server says more exist: a filtered
1030
+ // listing can return fewer rows than asked for and still not be the end, and
1031
+ // reading that page as whole turned every file past it into "Indexed".
1032
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || (lists[li] && lists[li].endOfList === false)) {
1033
+ truncated = true;
1034
+ // Which half this is, from its items (the callers pass them in either order).
1035
+ for (var si = 0; si < list.length; si++) {
1036
+ if (list[si] && list[si].status === 'running') { runningTruncated = true; break; }
1037
+ }
1038
+ }
1020
1039
  for (var i = 0; i < list.length; i++) {
1021
1040
  var item = list[i];
1022
1041
  if (!item || (item.status !== 'pending' && item.status !== 'running')) continue;
@@ -1053,7 +1072,19 @@ export class ChatSession {
1053
1072
  if (!changed) for (var r2 in wasRun) if (!running[r2]) { changed = true; break; }
1054
1073
  }
1055
1074
  this.state.liveIndexKeys = next;
1075
+ if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
1076
+ // Files seen to LEAVE the queue: live in the previous look, absent from a complete
1077
+ // one. Kept until the file is live again, so a later look that comes back cut off
1078
+ // (a bulk upload behind it) cannot turn its "Indexed" back into "Indexing".
1079
+ var settledNow = this.state.liveIndexSettled || {};
1080
+ var settledNext: { [k: string]: boolean } = {};
1081
+ for (var sk in settledNow) if (settledNow[sk] && !next[sk]) settledNext[sk] = true;
1082
+ if (nowChecked) {
1083
+ for (var wk in was) if (was[wk] && !next[wk]) { if (!settledNext[wk]) changed = true; settledNext[wk] = true; }
1084
+ }
1085
+ this.state.liveIndexSettled = settledNext;
1056
1086
  this.state.liveIndexRunning = running;
1087
+ this.state.liveIndexRunningChecked = !runningTruncated;
1057
1088
  this.state.liveIndexChecked = nowChecked;
1058
1089
  this._liveIndexAt = nowMs();
1059
1090
  // Claim the snapshot for the CURRENT chat. Both callers verify identity before
@@ -1075,6 +1106,8 @@ export class ChatSession {
1075
1106
  private _resetLiveIndexKeys(): void {
1076
1107
  this.state.liveIndexKeys = {};
1077
1108
  this.state.liveIndexRunning = {};
1109
+ this.state.liveIndexRunningChecked = false;
1110
+ this.state.liveIndexSettled = {};
1078
1111
  this.state.liveIndexChecked = false;
1079
1112
  this._liveIndexAt = 0;
1080
1113
  // Steps loaded into rows belong to that chat too.
@@ -2777,7 +2810,7 @@ export class ChatSession {
2777
2810
  * one it was composed for. Falls back to the live read only when a caller
2778
2811
  * omits them.
2779
2812
  */
2780
- private _callProviderFor(platform: string, prompt: string, messages: any, system: string, model: string | undefined, userId: string, extractContent: any, fileUrls?: any, projectId?: string, owner?: string) {
2813
+ private _callProviderFor(platform: string, prompt: string, messages: any, system: string, model: string | undefined, userId: string, extractContent: any, fileUrls?: any, projectId?: string, owner?: string, turn?: ChatTurnContext) {
2781
2814
  if (projectId === undefined || owner === undefined) {
2782
2815
  var id = this.host.getIdentity();
2783
2816
  if (projectId === undefined) projectId = id.projectId;
@@ -2791,11 +2824,41 @@ export class ChatSession {
2791
2824
  // read-only and public-records-only whoever calls it.
2792
2825
  var liveId = this.host.getIdentity();
2793
2826
  var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
2827
+ // The tool-listing key's user half comes from the same live read, because the
2828
+ // listing belongs to whoever the MCP endpoint authenticates as on THIS send.
2829
+ if (turn) turn.userId = liveId.anonymous ? '' : (liveId.userId || '');
2794
2830
  return platform === 'openai'
2795
- ? callOpenAIWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, undefined, undefined, mcpScope)
2831
+ ? callOpenAIWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, undefined, undefined, mcpScope, turn)
2796
2832
  : callClaudeWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, undefined, undefined, mcpScope);
2797
2833
  }
2798
2834
 
2835
+ /**
2836
+ * A fresh per-send record for the request builder (see requests.ts ChatTurnContext).
2837
+ * Chat turns only, and only OpenAI reuses a tool listing: Claude's MCP connector has no
2838
+ * equivalent item, and indexing passes never come through here. Off unless the host
2839
+ * set `reuseMcpToolList: true` in configureChatEngine.
2840
+ */
2841
+ private _newChatTurn(platform: string): ChatTurnContext {
2842
+ var on = false;
2843
+ try { on = chatEngineConfig().reuseMcpToolList === true; } catch (_) { on = false; }
2844
+ return { reuseMcpToolList: platform === 'openai' && on };
2845
+ }
2846
+
2847
+ /**
2848
+ * What a settled chat turn means for the stored MCP tool listing: a failure drops it
2849
+ * when the turn carried it (forgetMcpListToolsOnFailure decides whether reuse also
2850
+ * stops); a good OpenAI body refreshes it. A stopped poll or a cancelled row says
2851
+ * nothing either way. Applied once per turn: an exception thrown later by a UI
2852
+ * handler on the same chain is not a provider failure.
2853
+ */
2854
+ private _settleChatTurnTools(turn: ChatTurnContext | undefined, response: any, failed?: boolean): void {
2855
+ if (!turn || turn.settled) return;
2856
+ turn.settled = true;
2857
+ if (failed || isErrorResponseBody(response)) { forgetMcpListToolsOnFailure(turn, response); return; }
2858
+ if (isPollStopped(response) || this._isCancelledPollResult(response)) return;
2859
+ rememberMcpListTools(turn, response);
2860
+ }
2861
+
2799
2862
  dispatchAgentRequest(params: any) {
2800
2863
  var self = this;
2801
2864
  // Id of the in-flight item this dispatch polls. Recorded in
@@ -2805,9 +2868,13 @@ export class ChatSession {
2805
2868
  // stops covering an item once pendingAgentRequests clears — e.g. a queued
2806
2869
  // message still in flight after the immediate one resolved.)
2807
2870
  var dispatchItemId: string | undefined;
2871
+ // The builder record of the LATEST send: an auth-refresh retry re-enters
2872
+ // sendAndPoll and gets a new one, and only the send that settles counts.
2873
+ var turn: ChatTurnContext | undefined;
2808
2874
  var sendAndPoll = function () {
2875
+ turn = self._newChatTurn(params.aiPlatform);
2809
2876
  return Promise.resolve(
2810
- self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner)
2877
+ self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner, turn)
2811
2878
  ).then(function (initial: any) {
2812
2879
  if (initial && initial.poll && (initial.status === 'pending' || initial.status === 'running')) {
2813
2880
  if (initial.id) {
@@ -2853,6 +2920,7 @@ export class ChatSession {
2853
2920
  // Read as a provider body, both extract to nothing, and the turn was
2854
2921
  // stamped "No text response received from AI provider." and the cache
2855
2922
  // kept that as the answer to a question the user had stopped waiting on.
2923
+ self._settleChatTurnTools(turn, response);
2856
2924
  if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: '', isError: false, cancelled: true };
2857
2925
  if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
2858
2926
  var answer = (params.aiPlatform === 'openai' ? extractOpenAIText(response) : extractClaudeText(response));
@@ -2861,7 +2929,7 @@ export class ChatSession {
2861
2929
  // streamed turn's `response` is already the assembled body here).
2862
2930
  return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
2863
2931
  })
2864
- .catch(function (err: any) { return { content: getErrorMessage(err), isError: true }; })
2932
+ .catch(function (err: any) { self._settleChatTurnTools(turn, err, true); return { content: getErrorMessage(err), isError: true }; })
2865
2933
  .then(function (result: any) {
2866
2934
  // Land the resolved reply in the shared history cache. This runs
2867
2935
  // independently of the view lifecycle, so a reply is captured even
@@ -3336,7 +3404,8 @@ export class ChatSession {
3336
3404
 
3337
3405
  var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
3338
3406
  var capturedQueuedLid = queuedBubble._localId;
3339
- Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner))
3407
+ var queuedTurn = this._newChatTurn(aiPlatform);
3408
+ Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner, queuedTurn))
3340
3409
  .then(function (result: any) {
3341
3410
  // Only ack a bubble that belongs to THIS chat — the search is
3342
3411
  // positional, so on another project it would stamp this turn's
@@ -3376,12 +3445,13 @@ export class ChatSession {
3376
3445
  });
3377
3446
  if (serverId) self._trackPoll(serverId, 'fg', qp);
3378
3447
  return qp
3379
- .then(function (res: any) { if (isPollStopped(res)) return; return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey); })
3380
- .catch(function (err: any) { return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey); });
3448
+ .then(function (res: any) { self._settleChatTurnTools(queuedTurn, res); if (isPollStopped(res)) return; return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey); })
3449
+ .catch(function (err: any) { self._settleChatTurnTools(queuedTurn, err, true); return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey); });
3381
3450
  }
3451
+ self._settleChatTurnTools(queuedTurn, result);
3382
3452
  return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
3383
3453
  })
3384
- .catch(function (err: any) { return self.onQueuedSendError(capturedComposed, err, undefined, capturedKey); });
3454
+ .catch(function (err: any) { self._settleChatTurnTools(queuedTurn, err, true); return self.onQueuedSendError(capturedComposed, err, undefined, capturedKey); });
3385
3455
  return;
3386
3456
  }
3387
3457
 
@@ -3440,8 +3510,17 @@ export class ChatSession {
3440
3510
  // end of the list once a message sent after it (while its files uploaded)
3441
3511
  // has already been answered — and a history that ends on an assistant turn
3442
3512
  // hits exactly the `last.role !== 'user'` bail described above.
3513
+ //
3514
+ // The bubble is excluded by its _localId, NOT by `m === immediateUser`. A host may
3515
+ // hold the state as a Vue reactive() (agent.vue does), and then every element the
3516
+ // filter sees is a reactive PROXY of the object pushed above, never the object
3517
+ // itself, so the identity test never matched: the bubble passed the filter (it has
3518
+ // none of the pending flags) and the push below added the same message again. Every
3519
+ // immediate send from bunnyquery.com went out with the question twice at the end of
3520
+ // `input` / `messages`. The widget's plain state was never affected.
3521
+ var immediateUserLid = immediateUser._localId;
3443
3522
  var historyForLlm = this.state.messages.filter(function (m) {
3444
- if (m === immediateUser) return false;
3523
+ if (m === immediateUser || (immediateUserLid && m && m._localId === immediateUserLid)) return false;
3445
3524
  return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder &&
3446
3525
  !m.isCancelled && !m.isBackgroundTask && !m.isError;
3447
3526
  });
@@ -3450,7 +3529,7 @@ export class ChatSession {
3450
3529
  platform: aiPlatform, model: aiModel, systemPrompt: systemPrompt, projectId: id.projectId,
3451
3530
  history: historyForLlm,
3452
3531
  });
3453
- var immediateUserLid = immediateUser._localId, immediatePlaceholderLid = immediatePlaceholder._localId;
3532
+ var immediatePlaceholderLid = immediatePlaceholder._localId;
3454
3533
  var run = this.dispatchAgentRequest({
3455
3534
  key: key, projectId: id.projectId, owner: id.owner, aiPlatform: aiPlatform, aiModel: aiModel,
3456
3535
  systemPrompt: systemPrompt, text: composed, boundedMessages: bounded.messages, userId: chatQueue,
@@ -5325,9 +5404,23 @@ export class ChatSession {
5325
5404
  }
5326
5405
 
5327
5406
  /** The page progress to show for a file's row, or null (see _refreshPageProgress). */
5328
- pageProgressFor(storagePath?: string): { saved: number; total: number | null } | null {
5329
- if (!storagePath || !this.state.indexPageProgress) return null;
5330
- var p = this.state.indexPageProgress[storagePath];
5407
+ pageProgressFor(storagePath?: string, fileName?: string): { saved: number; total: number | null } | null {
5408
+ var map = this.state.indexPageProgress;
5409
+ if (!map) return null;
5410
+ var p = storagePath ? map[storagePath] : undefined;
5411
+ // A row put together from passes the queue check just found can lack its storage
5412
+ // path for a moment (the first of them carries it); the file NAME still finds the
5413
+ // progress then, when exactly one file of that name is being followed.
5414
+ if (!p && fileName) {
5415
+ var hit: string | null = null;
5416
+ for (var k in map) {
5417
+ if (k === fileName || k.slice(-(fileName.length + 1)) === '/' + fileName) {
5418
+ if (hit) { hit = null; break; }
5419
+ hit = k;
5420
+ }
5421
+ }
5422
+ if (hit) p = map[hit];
5423
+ }
5331
5424
  return p ? { saved: p.saved, total: p.total } : null;
5332
5425
  }
5333
5426
 
@@ -5336,7 +5429,7 @@ export class ChatSession {
5336
5429
  var complete = true;
5337
5430
  for (var r = 0; r < results.length; r++) {
5338
5431
  var list = results[r] && Array.isArray(results[r].list) ? results[r].list : [];
5339
- if (list.length >= WORKER_PASS_ADOPT_LIMIT) complete = false;
5432
+ if (list.length >= WORKER_PASS_ADOPT_LIMIT || (results[r] && results[r].endOfList === false)) complete = false;
5340
5433
  for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === 'string') ids[list[i].id] = true;
5341
5434
  }
5342
5435
  this._lastLiveLook = complete ? { svcId: svcId, platform: platform, at: Date.now(), ids: ids } : null;
@@ -6744,6 +6837,12 @@ export class ChatSession {
6744
6837
  uploadSingleAttachment(att: any, stageId?: string): Promise<Array<{ name: string; url: string; storagePath: string }>> {
6745
6838
  var self = this;
6746
6839
  var id = this.host.getIdentity();
6840
+ // Read BEFORE the status is reset below: a chip in "indexError" is one whose
6841
+ // bytes are already stored and only whose indexing failed. Its retry (the next
6842
+ // Send) re-indexes the stored copies through the "file is already there,
6843
+ // reindex it" path: no second upload, no "already exists" question about the
6844
+ // user's own file, no duplicate check (agent.vue isIndexRetry).
6845
+ var isIndexRetry = att.status === 'indexError';
6747
6846
  // progress stays null until the first byte-progress event. Every upload
6748
6847
  // opens with a get-signed-url round trip that reports nothing, so a chip
6749
6848
  // initialised to 0 rendered an empty, motionless bar for the whole
@@ -6810,7 +6909,9 @@ export class ChatSession {
6810
6909
  onProgress: onProg, setAbort: function (abort) { att._abort = abort; },
6811
6910
  });
6812
6911
  };
6813
- return findDuplicate(member).then(function (dup) {
6912
+ if (isIndexRetry) { hadExists = true; existedBefore = true; }
6913
+ return (isIndexRetry ? Promise.resolve(null) : findDuplicate(member)).then(function (dup) {
6914
+ if (isIndexRetry) return;
6814
6915
  if (dup) {
6815
6916
  duplicateOf = dup;
6816
6917
  console.log('[chat-engine] skipping an upload the user already has:', member.storagePath, '->', dup);
@@ -6841,7 +6942,22 @@ export class ChatSession {
6841
6942
  // A duplicate takes the STORED copy's url: the same reuse an EXISTS
6842
6943
  // answer gets when the user keeps the file, minus the prompt and
6843
6944
  // minus the re-index.
6844
- return self.host.getTemporaryUrl(duplicateOf || member.storagePath);
6945
+ return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function (err: any) {
6946
+ // A file nobody has indexed yet is readable by the project OWNER only
6947
+ // (the store's access rule), so for any other uploader the link to the
6948
+ // file they just uploaded is refused ("No access to this file.") and the
6949
+ // file could never be indexed. Its file record makes it a file of the
6950
+ // uploader's chosen group, which they can read: create it now (the step
6951
+ // below would have created the same record a moment later, and a second
6952
+ // create is refused harmlessly) and ask again.
6953
+ var ecode = err && (err.code || (err.body && err.body.code));
6954
+ var emsg = String((err && (err.message || (err.body && err.body.message))) || err || '');
6955
+ var refused = /no access to this file/i.test(emsg) || (ecode === 'INVALID_REQUEST' && /access/i.test(emsg));
6956
+ if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== 'function') throw err;
6957
+ return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
6958
+ name: member.file.name, mime: member.file.type || self.host.getMimeType(member.file.name), size: member.file.size,
6959
+ })).then(function () { return self.host.getTemporaryUrl(member.storagePath); });
6960
+ });
6845
6961
  }).then(function (url: string) {
6846
6962
  if (skipped) return; // guard the indexing branch for a skipped member
6847
6963
  if (duplicateOf) {
@@ -7027,7 +7143,9 @@ export class ChatSession {
7027
7143
  snapshot.forEach(function (att: any) {
7028
7144
  chain = chain.then(function () {
7029
7145
  if (!self.state.attachments.some(function (a: any) { return a.id === att.id; })) return; // removed
7030
- if (att.status === 'done' || att.status === 'indexError') {
7146
+ // "indexError" is NOT collected as-is: its upload worked but its indexing
7147
+ // did not, and uploadSingleAttachment retries just the indexing.
7148
+ if (att.status === 'done') {
7031
7149
  if (att.kind === 'folder' && att.uploadedUrls) {
7032
7150
  att.uploadedUrls.forEach(function (u: any) { collected.push({ name: u.path, url: u.url, storagePath: u.storagePath }); });
7033
7151
  return;