bunnyquery 1.19.1 → 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.
- package/README.md +31 -0
- package/bunnyquery.js +345 -149
- package/dist/engine.cjs +402 -181
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +5190 -5070
- package/dist/engine.d.ts +5190 -5070
- package/dist/engine.mjs +392 -182
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +27 -1
- package/src/engine/index.ts +19 -0
- package/src/engine/project_settings.ts +71 -0
- package/src/engine/prompts/chat_system_prompt.ts +77 -24
- package/src/engine/requests.ts +249 -4
- package/src/engine/session.ts +59 -10
package/src/engine/requests.ts
CHANGED
|
@@ -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.
|
|
339
|
-
|
|
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:
|
|
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
|
package/src/engine/session.ts
CHANGED
|
@@ -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,
|
|
@@ -2807,7 +2810,7 @@ export class ChatSession {
|
|
|
2807
2810
|
* one it was composed for. Falls back to the live read only when a caller
|
|
2808
2811
|
* omits them.
|
|
2809
2812
|
*/
|
|
2810
|
-
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) {
|
|
2811
2814
|
if (projectId === undefined || owner === undefined) {
|
|
2812
2815
|
var id = this.host.getIdentity();
|
|
2813
2816
|
if (projectId === undefined) projectId = id.projectId;
|
|
@@ -2821,11 +2824,41 @@ export class ChatSession {
|
|
|
2821
2824
|
// read-only and public-records-only whoever calls it.
|
|
2822
2825
|
var liveId = this.host.getIdentity();
|
|
2823
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 || '');
|
|
2824
2830
|
return platform === 'openai'
|
|
2825
|
-
? 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)
|
|
2826
2832
|
: callClaudeWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, undefined, undefined, mcpScope);
|
|
2827
2833
|
}
|
|
2828
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
|
+
|
|
2829
2862
|
dispatchAgentRequest(params: any) {
|
|
2830
2863
|
var self = this;
|
|
2831
2864
|
// Id of the in-flight item this dispatch polls. Recorded in
|
|
@@ -2835,9 +2868,13 @@ export class ChatSession {
|
|
|
2835
2868
|
// stops covering an item once pendingAgentRequests clears — e.g. a queued
|
|
2836
2869
|
// message still in flight after the immediate one resolved.)
|
|
2837
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;
|
|
2838
2874
|
var sendAndPoll = function () {
|
|
2875
|
+
turn = self._newChatTurn(params.aiPlatform);
|
|
2839
2876
|
return Promise.resolve(
|
|
2840
|
-
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)
|
|
2841
2878
|
).then(function (initial: any) {
|
|
2842
2879
|
if (initial && initial.poll && (initial.status === 'pending' || initial.status === 'running')) {
|
|
2843
2880
|
if (initial.id) {
|
|
@@ -2883,6 +2920,7 @@ export class ChatSession {
|
|
|
2883
2920
|
// Read as a provider body, both extract to nothing, and the turn was
|
|
2884
2921
|
// stamped "No text response received from AI provider." and the cache
|
|
2885
2922
|
// kept that as the answer to a question the user had stopped waiting on.
|
|
2923
|
+
self._settleChatTurnTools(turn, response);
|
|
2886
2924
|
if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: '', isError: false, cancelled: true };
|
|
2887
2925
|
if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
|
|
2888
2926
|
var answer = (params.aiPlatform === 'openai' ? extractOpenAIText(response) : extractClaudeText(response));
|
|
@@ -2891,7 +2929,7 @@ export class ChatSession {
|
|
|
2891
2929
|
// streamed turn's `response` is already the assembled body here).
|
|
2892
2930
|
return { content: answer || 'No text response received from AI provider.', isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
|
|
2893
2931
|
})
|
|
2894
|
-
.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 }; })
|
|
2895
2933
|
.then(function (result: any) {
|
|
2896
2934
|
// Land the resolved reply in the shared history cache. This runs
|
|
2897
2935
|
// independently of the view lifecycle, so a reply is captured even
|
|
@@ -3366,7 +3404,8 @@ export class ChatSession {
|
|
|
3366
3404
|
|
|
3367
3405
|
var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
|
|
3368
3406
|
var capturedQueuedLid = queuedBubble._localId;
|
|
3369
|
-
|
|
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))
|
|
3370
3409
|
.then(function (result: any) {
|
|
3371
3410
|
// Only ack a bubble that belongs to THIS chat — the search is
|
|
3372
3411
|
// positional, so on another project it would stamp this turn's
|
|
@@ -3406,12 +3445,13 @@ export class ChatSession {
|
|
|
3406
3445
|
});
|
|
3407
3446
|
if (serverId) self._trackPoll(serverId, 'fg', qp);
|
|
3408
3447
|
return qp
|
|
3409
|
-
.then(function (res: any) { if (isPollStopped(res)) return; return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey); })
|
|
3410
|
-
.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); });
|
|
3411
3450
|
}
|
|
3451
|
+
self._settleChatTurnTools(queuedTurn, result);
|
|
3412
3452
|
return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
|
|
3413
3453
|
})
|
|
3414
|
-
.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); });
|
|
3415
3455
|
return;
|
|
3416
3456
|
}
|
|
3417
3457
|
|
|
@@ -3470,8 +3510,17 @@ export class ChatSession {
|
|
|
3470
3510
|
// end of the list once a message sent after it (while its files uploaded)
|
|
3471
3511
|
// has already been answered — and a history that ends on an assistant turn
|
|
3472
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;
|
|
3473
3522
|
var historyForLlm = this.state.messages.filter(function (m) {
|
|
3474
|
-
if (m === immediateUser) return false;
|
|
3523
|
+
if (m === immediateUser || (immediateUserLid && m && m._localId === immediateUserLid)) return false;
|
|
3475
3524
|
return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder &&
|
|
3476
3525
|
!m.isCancelled && !m.isBackgroundTask && !m.isError;
|
|
3477
3526
|
});
|
|
@@ -3480,7 +3529,7 @@ export class ChatSession {
|
|
|
3480
3529
|
platform: aiPlatform, model: aiModel, systemPrompt: systemPrompt, projectId: id.projectId,
|
|
3481
3530
|
history: historyForLlm,
|
|
3482
3531
|
});
|
|
3483
|
-
var
|
|
3532
|
+
var immediatePlaceholderLid = immediatePlaceholder._localId;
|
|
3484
3533
|
var run = this.dispatchAgentRequest({
|
|
3485
3534
|
key: key, projectId: id.projectId, owner: id.owner, aiPlatform: aiPlatform, aiModel: aiModel,
|
|
3486
3535
|
systemPrompt: systemPrompt, text: composed, boundedMessages: bounded.messages, userId: chatQueue,
|