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.
- package/README.md +31 -0
- package/bunnyquery.css +15 -0
- package/bunnyquery.js +521 -173
- package/dist/engine.cjs +501 -193
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +5188 -5051
- package/dist/engine.d.ts +5188 -5051
- package/dist/engine.mjs +491 -194
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/config.ts +27 -1
- package/src/engine/host.ts +6 -0
- package/src/engine/index.ts +19 -0
- package/src/engine/indexing_groups.ts +46 -4
- 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 +138 -20
- package/src/widget.css +15 -0
package/dist/engine.cjs
CHANGED
|
@@ -80,6 +80,30 @@ function normalizeSkipDuplicateFiles(value) {
|
|
|
80
80
|
function skipDuplicateFilesFrom(data) {
|
|
81
81
|
return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
|
|
82
82
|
}
|
|
83
|
+
var ANSWER_MODES = ["standard", "fast", "thorough"];
|
|
84
|
+
var DEFAULT_ANSWER_MODE = "standard";
|
|
85
|
+
var ANSWER_MODE_SETTING_LABEL = "Answer mode";
|
|
86
|
+
var ANSWER_MODE_LABELS = {
|
|
87
|
+
standard: "Standard",
|
|
88
|
+
fast: "Fast",
|
|
89
|
+
thorough: "Thorough"
|
|
90
|
+
};
|
|
91
|
+
var ANSWER_MODE_HINTS = {
|
|
92
|
+
standard: "The AI model decides how long to think. This is the default.",
|
|
93
|
+
fast: "Shorter thinking for quicker answers. Best for simple questions.",
|
|
94
|
+
thorough: "Longer thinking before answering. Slower, and uses more tokens."
|
|
95
|
+
};
|
|
96
|
+
var ANSWER_MODE_OPTIONS = ANSWER_MODES.map((value) => ({
|
|
97
|
+
value,
|
|
98
|
+
label: ANSWER_MODE_LABELS[value],
|
|
99
|
+
hint: ANSWER_MODE_HINTS[value]
|
|
100
|
+
}));
|
|
101
|
+
function normalizeAnswerMode(value) {
|
|
102
|
+
return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
|
|
103
|
+
}
|
|
104
|
+
function answerModeFrom(data) {
|
|
105
|
+
return normalizeAnswerMode(data ? data.answer_mode : void 0);
|
|
106
|
+
}
|
|
83
107
|
var CHAT_GREETING_MAX_LENGTH = 400;
|
|
84
108
|
function normalizeChatGreeting(value) {
|
|
85
109
|
if (typeof value !== "string") return "";
|
|
@@ -169,6 +193,9 @@ function projectWebAccess(service) {
|
|
|
169
193
|
function projectSkipDuplicateFiles(service) {
|
|
170
194
|
return skipDuplicateFilesFrom(cachedProjectSettings(service));
|
|
171
195
|
}
|
|
196
|
+
function projectAnswerMode(service) {
|
|
197
|
+
return answerModeFrom(cachedProjectSettings(service));
|
|
198
|
+
}
|
|
172
199
|
function setProjectSettings(service, data) {
|
|
173
200
|
if (!service) return;
|
|
174
201
|
cache.set(service, { data: data || null, settled: true, inflight: null });
|
|
@@ -251,6 +278,10 @@ function resolveWebAccess(service, override) {
|
|
|
251
278
|
if (!service) return Promise.resolve(underCeiling(webAccessFrom(null), opt, override));
|
|
252
279
|
return loadProjectSettings(service).then(webAccessFrom, () => false).then((setting) => underCeiling(setting, opt, override));
|
|
253
280
|
}
|
|
281
|
+
function resolveAnswerMode(service) {
|
|
282
|
+
if (!service) return Promise.resolve(answerModeFrom(null));
|
|
283
|
+
return loadProjectSettings(service).then(answerModeFrom, () => answerModeFrom(null));
|
|
284
|
+
}
|
|
254
285
|
function skipDuplicateFilesEnabled(service) {
|
|
255
286
|
const opt = _config ? _config.skipDuplicateFiles : void 0;
|
|
256
287
|
return underCeiling(skipDuplicateFilesFrom(service ? cachedProjectSettings(service) : null), opt);
|
|
@@ -809,38 +840,44 @@ function buildChatSystemPrompt(params) {
|
|
|
809
840
|
WHEN THE DATA DOES NOT HAVE IT, SAY SO. Once you have searched the way these rules require and nothing answers the question, tell the user plainly, in their language, that this project's data does not contain it, and say what you searched (the tables, files or terms) so they can tell missing data from a missed search. Do not answer from memory instead, and do not turn a missing answer into a general explanation of the topic. Offer what would let you answer it: ${canUpload === false ? `another name or file to look under, or asking the project's owner to add it` : `the document to upload, or another name or file to look under`}.
|
|
810
841
|
KEEP WHAT THE DATA SAYS APART FROM WHAT YOU WORKED OUT. A total you computed, a comparison, a trend, an interpretation or a recommendation is yours, not the data's: label it as such ("calculated from...", "this suggests...") and name the rows or files it was made from. Never present an estimate, an assumption or an inference as something the data states.
|
|
811
842
|
These three rules govern every claim about the project's data. They do not limit the About BunnyQuery section (answer product questions from it), a greeting, or text the user explicitly asks you to write.`;
|
|
812
|
-
const
|
|
843
|
+
const webRule = webAccess ? `WEB ACCESS IS ON for this project: when the user asks for something that is not in the project's data, you may search the web for it, but every such fact must be marked as coming from the web (name the site), kept apart from what the project's data says, and never used to fill in or complete a document's content or a record. This is the one exception to the four sources named above.` : `This chat has no web tool: the web is never a source here.`;
|
|
844
|
+
const documentRules = `DOCUMENTS (a contract, a report, a manual, a letter, any uploaded file the user asks about the content of): FIRST FIND THE FILE, with getFileOutline when you know its storage path, otherwise by its "src::" record (see WHERE INDEXED CONTENT LIVES) using the name the user used. THEN FIND THE PAGE with searchText: with the file's path when the user named a file, without a path when they did not ("find a file that contains X"), and follow its description's steps to the end, including asking the user once, after quick results, before it searches all files. QUOTE THE EXACT TEXT it returned and CITE THE FILE AND THE PAGE ("report.pdf, page 7"); never present a paraphrase as a quote. A file with no page text is read with readFileContent instead and cited by its file name.`;
|
|
845
|
+
const groupIsAuthorized = indexGroupLiteral === '"authorized"' || indexGroupLiteral === "1";
|
|
846
|
+
const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
|
|
847
|
+
const accessGroupRule = `THIS PROJECT INDEXES AT access_group ${indexGroupLiteral}: pass access_group ${indexGroupLiteral} EXPLICITLY on EVERY query that names a table_name, whether it filters by index, by tag or by nothing. ${groupIsAuthorized ? `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which happens to be this project's group, but a plain table query is not auto-filled at all.` : `Do not rely on the defaults: an index or tag query sent with table_name but no group is auto-filled with "authorized", which is NOT this project's group, so it would search a group this project's data is not in and come back empty.`} Leaving access_group off a table query does NOT mean "all groups": only the project's owner is answered across every group, and any other user is answered from access_group 0 (public) alone${groupIsPublic ? "" : `, so a table indexed at ${indexGroupLiteral} comes back empty with its records sitting right there`}. Files uploaded before the project's setting changed may sit at another group, so when a table query comes back empty, retry it in the other groups among 0, 1 and "private" before concluding there is nothing. An index or tag filter matches inside ONE table and needs table_name: without it the call FAILS with an error, so read the error rather than guessing. Reference is the exception: reference ALONE spans EVERY table and EVERY access group, so getRecords with reference "src::<the file's storage path>" is the one call that returns a whole file's records wherever the indexer put them; adding table_name narrows it to that table, and access_group WITHOUT table_name fails with '"table" is required'.`;
|
|
813
848
|
let systemPrompt = `
|
|
814
849
|
You are a dedicated assistant for the project ID: "${projectId}".
|
|
815
850
|
Scope: Only answer questions about this project and its data. Do not answer questions about other projects or topics unrelated to this project. When the user refers to "my database", "my data", or "my files", treat those as references to this project's database and file storage. The ONE exception is BunnyQuery itself - what this app is, what it can do, and how to use it - which is always in scope: answer it from the "About BunnyQuery" section at the end of this prompt.
|
|
816
851
|
Knowledge lookup: Before saying you don't know or that something isn't in the chat history, ALWAYS query this project's database through the available MCP tools to look for the answer. The user's data is the source of truth - the chat transcript is not. Only respond with "I don't know" or "I couldn't find that" after you have actually searched the project's data and come back empty.
|
|
817
852
|
${groundingRules}
|
|
853
|
+
${webRule}
|
|
818
854
|
SAVED FINDINGS FIRST: where an earlier search found an answer is saved in table "search_findings" (one record per file page; its tags are the key words of the question that led there and of the search terms, stored lowercase without spaces). Before any other search, call getRecords with table_name "search_findings", access_group ${indexGroupLiteral} and tags set to ONE specific key word of the question (a name or a term, in the user's words; when nothing comes back, try one more word, or the word in the documents' language). A finding gives data.path and data.page: read THAT page (searchText with that path and the question's words) and answer from the page itself, quoting and citing it as usual. A finding is only a pointer, never the answer: when its page does not answer the question, or nothing is found, search as below.
|
|
819
|
-
FINDING THE DATA: the database is the way in, for every kind of file.
|
|
820
|
-
NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set
|
|
855
|
+
FINDING THE DATA: the database is the way in, for every kind of file. Follow the search path in getTables' description, with one exception for this project: when getTables' one page is the whole list (end_of_list true), skip its table-name search even when no name fits: you already see every table, and a table is never named after a company, a person or a single fact, so when no table fits, the answer is in a document's text: use searchText (DOCUMENTS below). Pick EVERY table that could hold the answer, not the first that fits. Read getIndexes and getTags one page each, never with fetch_all: name and tag lists can be millions of characters long and are never read whole, so when the name is not on that page, search for it with the user's words as their descriptions say. Never call getTags with neither table_name nor tag: that lists every tag of every table. Then getRecords in that table and group with the selector that matched (an index, one exact tag, or none for the whole table), always with fetch_all true. WHERE INDEXED CONTENT LIVES: a document's extracted content (PDF, Word, slides, scans) is in table "document_entries", one record per row / entry / section, with its page in "page"; spreadsheet rows are in "spreadsheet_rows". Files indexed before 2026-11-20 may still hold theirs in other tables, so a file's records are found wherever they are with getRecords reference "src::<path>". Every stored file has a record whose unique_id is "src::<its storage path>", so getUniqueId with unique_id "src::" and condition "gte" lists every file across every table (add the start of a path to narrow it; condition "lte" with a file name alone finds it in any folder). TAGS are stored lowercase without spaces or punctuation, plus one tag per word: search a tag as one word ("leak") or as the joined phrase ("oilleak"); the server also normalizes the tag you send.
|
|
856
|
+
NUMBERS FROM A SPREADSHEET are computed from the ROWS, never from one page and never from a guess. Each row of each sheet is one record in its table: reference "src::<path>", unique_id "row::<path>#<sheet>#R<n>", the cells by header name, plus "_sheet", "_row", "_grain" ("detail" or "summary") and, on a total or preamble row, "_row_type". Its tags carry the file name, the sheet, the grain and up to four key values of the row (a name, a code), so getRecords with one exact tag selects every row about that thing across all the files in the table. Workbooks state the same money more than once: a detail sheet, then per-song, per-album and per-artist sheets that re-total it, plus a summary. Use rows whose "_grain" is "detail" and whose "_row_type" is not "total", pick ONE sheet per file and say which, and never add a sheet to its summary. Fetch the COMPLETE matching set, keep only the rows whose column or tag names what was asked, then add them up carefully, in groups, and check that the group sums agree with the grand total. Quote the row count, the sheet(s) and the file(s) the figure was made from and label it as calculated.
|
|
821
857
|
A FILE TOTAL IS NOT A ROW'S TOTAL. The biggest number on a summary sheet is the whole file, not the thing that was asked about. Before quoting any figure, check it is scoped to what the question named: filter by the column that identifies it and report how many rows matched.
|
|
822
858
|
${documentRules}
|
|
823
|
-
Complete answers over stored data:
|
|
824
|
-
|
|
825
|
-
|
|
859
|
+
Complete answers over stored data: each uploaded file becomes many records, and ONE file is routinely SPLIT ACROSS SEVERAL TABLES - a summary row in one table, its page or row content in another, its extracted photos and other media in "__MEDIA__", and the indexer often invents a differently-named table on each pass. For anything NOT scoped to a single file, call getTables FIRST, run the query once per table that could hold the answer, and combine the results.
|
|
860
|
+
${accessGroupRule}
|
|
861
|
+
For any request that counts, sums, totals, lists every match, compares across records, finds which one, or asks whether something is present or ABSENT (for example "how many", "total spent", "which card", "is there any", "\uC5C6\uC5B4?", "\uD558\uB098\uB3C4 \uC5C6\uB098?"), you MUST read the COMPLETE matching set across EVERY table and EVERY relevant file before answering: one page is only a sample. Never assert absence from a partial read: do not say "there is no X", "none", "not found", or "\uC544\uB2C8\uC694, \uC5C6\uC2B5\uB2C8\uB2E4" until a complete scan has come back empty, and keep querying instead of guessing. A confident "no" that later turns out wrong is worse than telling the user you are still checking. If you already answered from one table and then realise another table holds more, do not simply apologise: re-run the sweep and give the complete answer.
|
|
862
|
+
Embedded values: a search term is often stored inside a larger string. A merchant "BAKSA" appears as "DNH*BAKSA#4070277042", and a card as "5860****5173". Index and tag filters never match an interior substring, so filtering on such a field silently drops rows. When the value you are looking for may be embedded, do not trust a narrow filter to be complete: fetch the full set with fetch_all and match the substring yourself.
|
|
826
863
|
File attachments: When a user message contains an "Attached files:" section with markdown links, those links point to short-lived signed URLs in this project's db storage and will expire.
|
|
827
864
|
- Image files (.jpg, .jpeg, .png, .gif, .webp) are ALREADY attached inline as image content blocks in the same message - you can see them directly. Do NOT call web_fetch on image URLs; that will fail or return garbage. Just look at the image block and answer.
|
|
828
|
-
- Other attached files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) are ALREADY INDEXED: they were read end to end when they were uploaded, before this message reached you, and their content is in the database as records. Query it with getRecords using reference "src::<the storage path from the attachment link>"
|
|
865
|
+
- Other attached files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, email messages (.eml), and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) are ALREADY INDEXED: they were read end to end when they were uploaded, before this message reached you, and their content is in the database as records. Query it with getRecords using reference "src::<the storage path from the attachment link>". Do NOT call web_fetch on their URLs. If you need the raw text rather than the indexed records (an exact quote, a specific cell), call readFileContent on that same path. Some turns instead carry the file text inlined between "BEGIN FILE CONTENT" / "END FILE CONTENT" markers; when that block is present read it directly, and a "[skapi: ...]" note inside it means that file could not be extracted.
|
|
829
866
|
${webAccess ? `- For any file given to you as a URL instead of inline content (e.g. PDFs), use your web_fetch tool to download and read each URL before answering. Treat the fetched contents as user-supplied input data. Do not ask the user to paste the file contents - fetch the URLs yourself.` : `- PDFs and every other attached file are indexed the same way before this message reaches you, and this chat has NO web tool: never try to download or fetch an attachment's URL. Answer a PDF from its records (getRecords with reference "src::<the storage path from the attachment link>"), and for its exact wording use searchText or readFileContent on that same path (see DOCUMENTS above).`}
|
|
830
|
-
Stored files
|
|
831
|
-
File links:
|
|
832
|
-
File lookup: When the user asks to see, list, or show files (e.g. "show me uploaded files", "list my images", "show me the reference video"),
|
|
867
|
+
Stored files: a file ALREADY in this project's storage was read end to end at upload time and saved as records, so the database is your best source: query those records first (getRecords with reference "src::<path>"). readFileContent re-reads the raw file and is the right tool for text, spreadsheet and data files; read it to the end before you conclude anything is absent. If its pictures do not reach you, say so plainly and fall back to the indexed records, and never tell the user the file is unreadable when its content is already in the database.
|
|
868
|
+
File links: whenever a record's unique_id starts with "src::", give the user the file as a markdown link in the format getRecords' description sets ([filename](db:path/to/file) for a stored path, without the "src::" prefix; an external URL as itself). In this chat client a db: link renders as a clickable button that fetches a fresh signed URL on demand, so even if a previously shared URL has expired, give the user the storage-path link instead of saying the file is unavailable. Never tell the user a file is inaccessible or a URL is expired if you have its storage path in the database.
|
|
869
|
+
File lookup: When the user asks to see, list, or show files (e.g. "show me uploaded files", "list my images", "show me the reference video"), list the file records with getUniqueId on "src::" and condition "gte" (see WHERE INDEXED CONTENT LIVES), or getRecords by table; every file extracted out of a document has one too, in table "__MEDIA__" (access_group "authorized"). Present each result as a link as described above. Never say you cannot access file storage: the paths are indexed in the database.
|
|
833
870
|
Showing images: "show me the photo", "\uBCF4\uC5EC\uC918", "display it" is a request for the file's LINK, nothing more. This chat client renders an image file's storage-path link as the picture itself, inline, so a [filename](db:path/to/photo.jpg) link IS the image on screen. Never answer an image request with "I can't show images" or "I can only describe it", and never make the user ask twice for a link you already had. If you have the path, give the link and let the client paint it. The same is true of any file the user asks to see: the link is the answer. Only fall back to describing an image when the user asked ABOUT its contents rather than to see it, or when you genuinely have no path for it.
|
|
834
871
|
Media inside a document is extracted into real files: every embedded PICTURE inside an uploaded document - photos, diagrams, chart images - is pulled out at upload time and saved as its OWN permanent file in this project's storage, in the folder "__MEDIA__/<the document's storage path>/". Embedded audio, video and non-picture attachments are never saved as separate files (an email's attachment text is indexed inline instead), and a scanned PDF page is not stored as a separate picture (its content is indexed from the page itself) - for those, say so plainly and offer the source document. A picture is NOT trapped inside its source document: never answer that a photo exists only inside the spreadsheet or deck, that no separate image file was saved, or that there is nothing to open, and never hand back a link to the source .xlsx or .pdf when the user asked for a picture inside it.
|
|
835
872
|
Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
|
|
836
873
|
RECOGNISE IT BY THE VALUE, NOT THE FIELD NAME. Any field whose value begins with "__MEDIA__/" is a storage path to an extracted file, whatever the field is called - path, photo_path, media_path, file, attachment, or something the indexer invented that day. A record's unique_id beginning "src::__MEDIA__/" marks it as a media record too.
|
|
837
|
-
The reliable query is getRecords with reference "src::<the document's storage path>"
|
|
874
|
+
The reliable query is getRecords with reference "src::<the document's storage path>". Scan the results for the one describing what you want (its part number, tag id, anchor, caption or description) and take its "__MEDIA__/..." value. Never let a table guess be the reason you report a file as missing.
|
|
838
875
|
Link it VERBATIM as [caption](db:<the path>). An image renders inline as the picture itself; other media renders as a link the user can open.
|
|
839
876
|
So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
|
|
840
877
|
IF THAT RECORD HAS NO PATH, JOIN ON LOCATION - this needs nothing to have been enriched. Every media record carries data.anchor (the cell or page it was embedded at), plus data.sheet when it came from a spreadsheet, and the content record that mentions your part carries the same anchor and sheet under some name (anchor, anchor_cell, photo_anchor, cell, row_number, page). So: read the anchor and sheet off the content record, query getRecords with reference "src::<the document>", and take the media record whose data.anchor, data.also_at or tags match the anchor, using data.sheet too when both records carry one. Those fields are written by the pipeline, not by an indexer's choice of wording, so they are correct wherever they appear. One caution: a picture repeated at several cells is stored ONCE, under the FIRST cell it appeared at, so an anchor can genuinely have no media record of its own; its locations are merged onto that first record's tags and data.also_at. Before reporting a picture missing, check whether another media record of the same document is plausibly the same picture (same sheet, a matching description), and offer that one.
|
|
841
|
-
THIS IS NOT ONLY ABOUT SPREADSHEET PHOTOS. Treat "show me the diagram in that deck" or "the picture in that PDF" exactly like a photo request: query for the media record, never reconstruct a filename.
|
|
878
|
+
THIS IS NOT ONLY ABOUT SPREADSHEET PHOTOS. Treat "show me the diagram in that deck" or "the picture in that PDF" exactly like a photo request: query for the media record, never reconstruct a filename.
|
|
842
879
|
A document may still have no media record: it was indexed before the "__MEDIA__" table existed, or its format is one whose embedded files are not extracted. Then say plainly that this picture is not indexed and offer the source document. One missing record is never evidence that media is not stored.
|
|
843
|
-
File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile
|
|
880
|
+
File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile and hand over its link the way its description says. Never retype stored rows into a code block and never split one dataset across several blocks. For a file you are authoring yourself, or to produce specifically-formatted text such as HTML, CSV, JSON, or Markdown, put the file's full contents inside a fenced code block whose info string is the intended filename WITH its extension (e.g. report.csv), NOT a language name like "csv". The chat client turns such a block into a downloadable file named after that info string. Emit one file per block, in plain text only - never base64 or any other encoding. Example for CSV:
|
|
844
881
|
\`\`\`filename.csv
|
|
845
882
|
item,qty,total
|
|
846
883
|
Carrots,55,$38.50
|
|
@@ -853,7 +890,7 @@ About BunnyQuery (this app - questions about it are in scope):
|
|
|
853
890
|
You are the assistant inside BunnyQuery, an AI assistant for the user's own business data. Instead of digging through folders, dashboards and files, the user uploads their documents, spreadsheets, images, notes and records, BunnyQuery indexes them into this project's database, and you answer questions, write reports and summarize from THAT data rather than from the open internet. Each project has its own data, its own AI platform (ChatGPT or Claude, powered by the project owner's own API key) and its own base prompt. BunnyQuery is built on Skapi (www.skapi.com), so the same project database is also reachable over MCP from any MCP-compatible AI client (mcp.broadwayinc.computer), and this chat can be embedded in a website as a widget with one script tag. Answer product questions from the facts in this section. If you are asked something about BunnyQuery that is NOT stated here - pricing, plan limits, a roadmap, a feature you cannot see - say you are not certain and point the user at the project owner or the BunnyQuery site, rather than inventing it.
|
|
854
891
|
How data gets in: ${canUpload === false ? `this user CANNOT upload in this session (they are not signed in, or the project's database is frozen for non-admins), and the attach affordances are hidden from them. Never instruct them to attach, drag in or upload a file, and never blame a missing answer on them not having uploaded it. Answer from what is already indexed, and when something genuinely is not in the project, say so and suggest asking the project's owner to add it.` : `the user attaches files to a chat message with the paperclip button in the composer, or drags and drops them onto the chat (whole folders work; up to 20 files per message). Uploaded files land in this project's file storage and are indexed automatically: read end to end and turned into database records. "Indexed" means exactly that, and it is why you can only answer from a file once its indexing has finished. While a file indexes, the chat shows a status row for it: yellow while it is working, green when it is indexed, red if it failed. A large file is indexed in windows over several passes, which takes longer; indexing runs on the server, so it keeps going if the user closes the page and the row is still there when they come back. The user can also paste plain text straight into the chat and ask you to save it - store it with the postRecords tool. BunnyQuery reads over 50 formats: office documents (.docx, .xlsx, .pptx, .hwp, .hwpx, .odt, .ods, .odp, .epub), email (.eml), PDFs, images, .csv/.tsv, .json, .xml, .html, .txt/.md and source code. Images and scanned PDFs are read with vision at index time.`}
|
|
855
892
|
Getting answers out: the user asks in plain language, in any language, and you answer from this project's data. You can also produce reports and downloadable files (CSV and the rest) as described in the File generation rules above, and any stored file can be handed back as a link, with images rendering inline in the chat.${client === "console" ? `
|
|
856
|
-
Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.` : ""}${client === "widget" ? `
|
|
893
|
+
Where things are in the BunnyQuery console (this user is in it, at bunnyquery.com): the left nav has "Query" (this chat), "Files" (browse this project's stored files, upload more, and see which are indexed), "Collaborators" (invite teammates or clients so they can ask questions themselves) and "Settings" (the AI platform, model and API key, the project's description / base prompt, which is added to your instructions, the Answer mode (Standard, Fast or Thorough: how quickly or how deeply you work on each answer), and the Freeze Database switch that blocks writes). Plans and billing live on the project's Subscription page - send the user there rather than quoting prices, which you do not know.` : ""}${client === "widget" ? `
|
|
857
894
|
This chat is the BunnyQuery widget embedded in a website, so the user may have no access to the project console: keep any instructions to what can be done here in the chat.` : ""}`;
|
|
858
895
|
if (greeting) {
|
|
859
896
|
systemPrompt += `
|
|
@@ -1037,6 +1074,165 @@ Records for the earlier windows/pages of this file are ALREADY saved (they refer
|
|
|
1037
1074
|
Index the REMAINING windows - one record per row/item, looking at any page images or embedded photos - saving as you go until readFileContent reports END OF FILE. A \xABPHOTO <cell>\xBB marker in a window marks an embedded picture whose extracted file already has a record in table "__MEDIA__": find it with getRecords reference "src::" + the storage path above and match the cell against data.anchor or tags (a repeated picture is stored under its first anchor only), then enrich it with updateRecords. Never create a photo record of your own and never construct a path for one. Do NOT re-save windows that are already saved. Set every record's reference to exactly "src::" + the storage path above (no sheet, window or summary suffix added). That file record already exists, so do NOT post it; enrich it with updateRecords. When the ENTIRE file is finally indexed, end your message with the token INDEXING_COMPLETE.`;
|
|
1038
1075
|
}
|
|
1039
1076
|
|
|
1077
|
+
// src/engine/errors.ts
|
|
1078
|
+
var STATUS_MESSAGE = {
|
|
1079
|
+
"408": "The AI provider timed out before it started.",
|
|
1080
|
+
"409": "The AI provider rejected the request as conflicting.",
|
|
1081
|
+
"413": "The request was too large for the AI provider.",
|
|
1082
|
+
"429": "The AI provider is rate limiting requests right now.",
|
|
1083
|
+
"500": "The AI provider hit an internal error.",
|
|
1084
|
+
"502": "The AI provider is temporarily unreachable.",
|
|
1085
|
+
"503": "The AI provider is temporarily unavailable.",
|
|
1086
|
+
"504": "The AI provider timed out."
|
|
1087
|
+
};
|
|
1088
|
+
function isTransientStatus(status) {
|
|
1089
|
+
return status === 408 || status === 425 || status === 429 || status >= 500;
|
|
1090
|
+
}
|
|
1091
|
+
function isCsrStatusEnvelope(res) {
|
|
1092
|
+
return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
|
|
1093
|
+
}
|
|
1094
|
+
function csrEnvelopeError(input) {
|
|
1095
|
+
if (!isCsrStatusEnvelope(input)) return void 0;
|
|
1096
|
+
if (input.status !== "failed") return void 0;
|
|
1097
|
+
return input.error != null ? input.error : { message: "The AI provider request failed." };
|
|
1098
|
+
}
|
|
1099
|
+
function getErrorMessage(input) {
|
|
1100
|
+
var envErr = csrEnvelopeError(input);
|
|
1101
|
+
if (envErr !== void 0) input = envErr;
|
|
1102
|
+
if (!input) return "Something went wrong.";
|
|
1103
|
+
if (typeof input === "string") return input;
|
|
1104
|
+
if (input.error && input.error.message) return input.error.message;
|
|
1105
|
+
if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
|
|
1106
|
+
if (input.body && typeof input.body.message === "string") return input.body.message;
|
|
1107
|
+
if (input.message) return input.message;
|
|
1108
|
+
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
|
|
1109
|
+
if (status) {
|
|
1110
|
+
var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
|
|
1111
|
+
return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
|
|
1112
|
+
}
|
|
1113
|
+
return "Something went wrong.";
|
|
1114
|
+
}
|
|
1115
|
+
function isRetriedFailure(input) {
|
|
1116
|
+
var envErr = csrEnvelopeError(input);
|
|
1117
|
+
if (envErr !== void 0) input = envErr;
|
|
1118
|
+
return !!input && typeof input === "object" && input.retried === true;
|
|
1119
|
+
}
|
|
1120
|
+
function isErrorResponseBody(response) {
|
|
1121
|
+
var envErr = csrEnvelopeError(response);
|
|
1122
|
+
if (envErr !== void 0) response = envErr;
|
|
1123
|
+
if (!response || typeof response !== "object") return envErr !== void 0;
|
|
1124
|
+
if (typeof response.status_code === "number" && response.status_code >= 400) return true;
|
|
1125
|
+
if (response.type === "error") return true;
|
|
1126
|
+
if (response.error && (response.error.message || response.error.type)) return true;
|
|
1127
|
+
var body = response.body;
|
|
1128
|
+
if (body && typeof body === "object") {
|
|
1129
|
+
if (body.type === "error") return true;
|
|
1130
|
+
if (body.error && (body.error.message || body.error.type)) return true;
|
|
1131
|
+
}
|
|
1132
|
+
if (typeof response.message === "string" && response.message.length) {
|
|
1133
|
+
var hasClaude = Array.isArray(response.content);
|
|
1134
|
+
var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
|
|
1135
|
+
if (!hasClaude && !hasOpenAI) return true;
|
|
1136
|
+
}
|
|
1137
|
+
return false;
|
|
1138
|
+
}
|
|
1139
|
+
function isNonRetryableRequestError(input) {
|
|
1140
|
+
var envErr = csrEnvelopeError(input);
|
|
1141
|
+
if (envErr !== void 0) input = envErr;
|
|
1142
|
+
if (!input || typeof input !== "object") return false;
|
|
1143
|
+
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
|
|
1144
|
+
var param = void 0;
|
|
1145
|
+
var blobs = [];
|
|
1146
|
+
var sources = [input.error, input.body && input.body.error, input.body, input];
|
|
1147
|
+
for (var i = 0; i < sources.length; i++) {
|
|
1148
|
+
var e = sources[i];
|
|
1149
|
+
if (!e) continue;
|
|
1150
|
+
if (typeof e === "string") {
|
|
1151
|
+
blobs.push(e);
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
if (typeof e !== "object") continue;
|
|
1155
|
+
if (param === void 0 && e.param != null) param = e.param;
|
|
1156
|
+
if (typeof e.code === "string") blobs.push(e.code);
|
|
1157
|
+
if (typeof e.type === "string") blobs.push(e.type);
|
|
1158
|
+
if (typeof e.message === "string") blobs.push(e.message);
|
|
1159
|
+
}
|
|
1160
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1161
|
+
if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
|
|
1162
|
+
return true;
|
|
1163
|
+
}
|
|
1164
|
+
var isClientReqStatus = status === 400 || status === 422;
|
|
1165
|
+
if (isClientReqStatus && param != null && param !== "") return true;
|
|
1166
|
+
if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
|
|
1167
|
+
return true;
|
|
1168
|
+
}
|
|
1169
|
+
return false;
|
|
1170
|
+
}
|
|
1171
|
+
function isAuthExpiredError(input) {
|
|
1172
|
+
var envErr = csrEnvelopeError(input);
|
|
1173
|
+
if (envErr !== void 0) input = envErr;
|
|
1174
|
+
if (!input) return false;
|
|
1175
|
+
var blobs = [];
|
|
1176
|
+
var push = function(v) {
|
|
1177
|
+
if (typeof v === "string" && v) blobs.push(v);
|
|
1178
|
+
};
|
|
1179
|
+
if (typeof input === "string") push(input);
|
|
1180
|
+
else {
|
|
1181
|
+
push(input.message);
|
|
1182
|
+
push(input.code);
|
|
1183
|
+
if (input.error) {
|
|
1184
|
+
push(input.error.message);
|
|
1185
|
+
push(input.error.code);
|
|
1186
|
+
push(input.error.type);
|
|
1187
|
+
}
|
|
1188
|
+
if (input.body) {
|
|
1189
|
+
push(input.body.message);
|
|
1190
|
+
if (input.body.error) {
|
|
1191
|
+
push(input.body.error.message);
|
|
1192
|
+
push(input.body.error.code);
|
|
1193
|
+
push(input.body.error.type);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
if (typeof input.status === "number" && input.status === 401) return true;
|
|
1197
|
+
if (typeof input.status_code === "number" && input.status_code === 401) return true;
|
|
1198
|
+
}
|
|
1199
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1200
|
+
if (!hay) return false;
|
|
1201
|
+
return hay.indexOf("token has expired") !== -1 || hay.indexOf("token is expired") !== -1 || hay.indexOf("expired_token") !== -1 || hay.indexOf("invalid_token") !== -1 || hay.indexOf("unauthorized") !== -1 || hay.indexOf("not authorized") !== -1 || hay.indexOf("invalid_request") !== -1 && hay.indexOf("token") !== -1;
|
|
1202
|
+
}
|
|
1203
|
+
function isProviderApiKeyError(input) {
|
|
1204
|
+
var envErr = csrEnvelopeError(input);
|
|
1205
|
+
if (envErr !== void 0) input = envErr;
|
|
1206
|
+
if (!input) return false;
|
|
1207
|
+
var blobs = [];
|
|
1208
|
+
var push = function(v) {
|
|
1209
|
+
if (typeof v === "string" && v) blobs.push(v);
|
|
1210
|
+
};
|
|
1211
|
+
if (typeof input === "string") push(input);
|
|
1212
|
+
else {
|
|
1213
|
+
push(input.message);
|
|
1214
|
+
push(input.code);
|
|
1215
|
+
push(input.type);
|
|
1216
|
+
if (input.error) {
|
|
1217
|
+
push(input.error.message);
|
|
1218
|
+
push(input.error.code);
|
|
1219
|
+
push(input.error.type);
|
|
1220
|
+
}
|
|
1221
|
+
if (input.body) {
|
|
1222
|
+
push(input.body.message);
|
|
1223
|
+
push(input.body.type);
|
|
1224
|
+
if (input.body.error) {
|
|
1225
|
+
push(input.body.error.message);
|
|
1226
|
+
push(input.body.error.code);
|
|
1227
|
+
push(input.body.error.type);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1232
|
+
if (!hay) return false;
|
|
1233
|
+
return hay.indexOf("authentication_error") !== -1 || hay.indexOf("invalid_api_key") !== -1 || hay.indexOf("invalid x-api-key") !== -1 || hay.indexOf("incorrect api key") !== -1 || hay.indexOf("invalid api key") !== -1 || hay.indexOf("no api key provided") !== -1;
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1040
1236
|
// src/engine/links.ts
|
|
1041
1237
|
var EXPIRED_ATTACHMENT_URL_HOST = "_expired_.url";
|
|
1042
1238
|
var EXPIRED_ATTACHMENT_URL_ORIGIN = "https://" + EXPIRED_ATTACHMENT_URL_HOST;
|
|
@@ -1901,12 +2097,41 @@ var OLDEST_NANO_REASONING_EFFORT = "high";
|
|
|
1901
2097
|
var isOpenAINano = (model) => {
|
|
1902
2098
|
const normalized = (model).trim().toLowerCase();
|
|
1903
2099
|
if (!/(^|-)nano(-|$)/.test(normalized)) return false;
|
|
2100
|
+
return openAITakesReasoningEffort(normalized);
|
|
2101
|
+
};
|
|
2102
|
+
var openAITakesReasoningEffort = (model) => {
|
|
2103
|
+
const normalized = (model || DEFAULT_OPENAI_MODEL).trim().toLowerCase();
|
|
1904
2104
|
const match = normalized.match(/^gpt-(\d+)(?:\.(\d+))?(-[a-z0-9.\-]+)?$/);
|
|
1905
2105
|
if (!match) return false;
|
|
1906
2106
|
const major = Number(match[1]);
|
|
1907
2107
|
const minor = match[2] === void 0 ? null : Number(match[2]);
|
|
1908
2108
|
return major > 5 || major === 5 && minor !== null && minor >= 4;
|
|
1909
2109
|
};
|
|
2110
|
+
var claudeTakesEffort = (model) => {
|
|
2111
|
+
const normalized = (model || DEFAULT_CLAUDE_MODEL).trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
2112
|
+
const match = normalized.match(/^claude-([a-z]+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:-\d{8})?$/);
|
|
2113
|
+
if (!match) return false;
|
|
2114
|
+
const family = match[1];
|
|
2115
|
+
if (family === "fable" || family === "mythos") return true;
|
|
2116
|
+
if (match[2] === void 0) return false;
|
|
2117
|
+
const major = Number(match[2]);
|
|
2118
|
+
const minor = match[3] === void 0 ? 0 : Number(match[3]);
|
|
2119
|
+
if (family === "opus") return major > 4 || major === 4 && minor >= 5;
|
|
2120
|
+
if (family === "sonnet") return major > 4 || major === 4 && minor >= 6;
|
|
2121
|
+
if (family === "haiku") return major > 5 || major === 5 && minor >= 5;
|
|
2122
|
+
return false;
|
|
2123
|
+
};
|
|
2124
|
+
var ANSWER_MODE_EFFORT = {
|
|
2125
|
+
standard: null,
|
|
2126
|
+
fast: "low",
|
|
2127
|
+
thorough: "high"
|
|
2128
|
+
};
|
|
2129
|
+
function chatEffortFields(platform, model, mode) {
|
|
2130
|
+
const effort = mode ? ANSWER_MODE_EFFORT[mode] : null;
|
|
2131
|
+
if (!effort) return {};
|
|
2132
|
+
if (platform === "openai") return openAITakesReasoningEffort(model) ? { reasoning: { effort } } : {};
|
|
2133
|
+
return claudeTakesEffort(model) ? { output_config: { effort } } : {};
|
|
2134
|
+
}
|
|
1910
2135
|
var variantIndexingOptions = (model) => {
|
|
1911
2136
|
if (!isOpenAINano(model) || !isOldestNano(model)) return {};
|
|
1912
2137
|
return {
|
|
@@ -2043,6 +2268,80 @@ function applyHistoryCacheBreakpoint(messages) {
|
|
|
2043
2268
|
var POLL_INTERVAL = 3e3;
|
|
2044
2269
|
var STREAM_POLL_INTERVAL = 1e3;
|
|
2045
2270
|
var MAX_CONCURRENT_BG_POLLS = 6;
|
|
2271
|
+
var mcpListToolsCache = /* @__PURE__ */ new Map();
|
|
2272
|
+
var mcpListToolsReuseOff = false;
|
|
2273
|
+
var MCP_LIST_TOOLS_OFF_PREFIX = "bunnyquery:mcp-list-tools-off:";
|
|
2274
|
+
function mcpListToolsOffStored(service) {
|
|
2275
|
+
try {
|
|
2276
|
+
return typeof localStorage !== "undefined" && !!localStorage.getItem(MCP_LIST_TOOLS_OFF_PREFIX + service);
|
|
2277
|
+
} catch (_) {
|
|
2278
|
+
return false;
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
function storeMcpListToolsOff(service) {
|
|
2282
|
+
if (!service) return;
|
|
2283
|
+
try {
|
|
2284
|
+
if (typeof localStorage !== "undefined") localStorage.setItem(MCP_LIST_TOOLS_OFF_PREFIX + service, String(Date.now()));
|
|
2285
|
+
} catch (_) {
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
var SERVER_PLACEHOLDERS = ["$CLIENT_SECRET", "$ACCESS_TOKEN", "$ID_TOKEN"];
|
|
2289
|
+
function failureText(failure) {
|
|
2290
|
+
const env = csrEnvelopeError(failure);
|
|
2291
|
+
const f = env !== void 0 ? env : failure;
|
|
2292
|
+
if (f == null) return "";
|
|
2293
|
+
if (typeof f === "string") return f.toLowerCase();
|
|
2294
|
+
let text = "";
|
|
2295
|
+
try {
|
|
2296
|
+
text = JSON.stringify(f) || "";
|
|
2297
|
+
} catch (_) {
|
|
2298
|
+
text = "";
|
|
2299
|
+
}
|
|
2300
|
+
if (typeof f.message === "string") text += " " + f.message;
|
|
2301
|
+
return text.toLowerCase();
|
|
2302
|
+
}
|
|
2303
|
+
function failureStatus(failure) {
|
|
2304
|
+
const env = csrEnvelopeError(failure);
|
|
2305
|
+
const f = env !== void 0 ? env : failure;
|
|
2306
|
+
if (!f || typeof f !== "object") return void 0;
|
|
2307
|
+
const v = typeof f.status_code === "number" ? f.status_code : typeof f.status === "number" ? f.status : void 0;
|
|
2308
|
+
return v;
|
|
2309
|
+
}
|
|
2310
|
+
function mcpListToolsKey(serverUrl, anonymous, service, publicProjectId, userId) {
|
|
2311
|
+
return JSON.stringify([serverUrl, anonymous ? "anonymous" : "signed-in", service, publicProjectId || "", userId || ""]);
|
|
2312
|
+
}
|
|
2313
|
+
function rememberMcpListTools(turn, body) {
|
|
2314
|
+
if (!turn || !turn.mcpToolsKey || mcpListToolsReuseOff) return;
|
|
2315
|
+
const output = body && Array.isArray(body.output) ? body.output : null;
|
|
2316
|
+
if (!output) return;
|
|
2317
|
+
for (let i = output.length - 1; i >= 0; i--) {
|
|
2318
|
+
const item = output[i];
|
|
2319
|
+
if (!item || item.type !== "mcp_list_tools" || item.server_label !== MCP_NAME) continue;
|
|
2320
|
+
if (item.error || typeof item.id !== "string" || !item.id || !Array.isArray(item.tools)) continue;
|
|
2321
|
+
let toolsText = "";
|
|
2322
|
+
try {
|
|
2323
|
+
toolsText = JSON.stringify(item.tools);
|
|
2324
|
+
} catch (_) {
|
|
2325
|
+
return;
|
|
2326
|
+
}
|
|
2327
|
+
if (SERVER_PLACEHOLDERS.some((ph) => toolsText.indexOf(ph) !== -1)) return;
|
|
2328
|
+
mcpListToolsCache.set(turn.mcpToolsKey, { type: "mcp_list_tools", id: item.id, server_label: item.server_label, tools: item.tools });
|
|
2329
|
+
return;
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
function forgetMcpListToolsOnFailure(turn, failure) {
|
|
2333
|
+
if (!turn || !turn.mcpToolsInjected) return;
|
|
2334
|
+
if (turn.mcpToolsKey) mcpListToolsCache.delete(turn.mcpToolsKey);
|
|
2335
|
+
const text = failureText(failure);
|
|
2336
|
+
const status = failureStatus(failure);
|
|
2337
|
+
const namesItem = text.indexOf("mcp_list_tools") !== -1 || !!turn.mcpToolsItemId && text.indexOf(turn.mcpToolsItemId.toLowerCase()) !== -1;
|
|
2338
|
+
if (namesItem) {
|
|
2339
|
+
mcpListToolsReuseOff = true;
|
|
2340
|
+
storeMcpListToolsOff(turn.mcpToolsService);
|
|
2341
|
+
return;
|
|
2342
|
+
}
|
|
2343
|
+
if (status === 400 || status === 422 || text.indexOf("invalid_request_error") !== -1) mcpListToolsReuseOff = true;
|
|
2344
|
+
}
|
|
2046
2345
|
async function callClaudeWithMcp({
|
|
2047
2346
|
prompt,
|
|
2048
2347
|
messages,
|
|
@@ -2058,6 +2357,7 @@ async function callClaudeWithMcp({
|
|
|
2058
2357
|
webAccess
|
|
2059
2358
|
}) {
|
|
2060
2359
|
const web = await resolveWebAccess(service, typeof webAccess === "boolean" ? webAccess : void 0);
|
|
2360
|
+
const effortFields = chatEffortFields("claude", model, await resolveAnswerMode(service));
|
|
2061
2361
|
const mcpServerDefinition = {
|
|
2062
2362
|
type: "url",
|
|
2063
2363
|
name: mcpServer.name,
|
|
@@ -2085,6 +2385,8 @@ async function callClaudeWithMcp({
|
|
|
2085
2385
|
data: {
|
|
2086
2386
|
model,
|
|
2087
2387
|
max_tokens: maxTokens,
|
|
2388
|
+
// `output_config: {effort}` for a fast or thorough project, nothing otherwise.
|
|
2389
|
+
...effortFields,
|
|
2088
2390
|
// Top level beside model/messages/mcp_servers, which is where the
|
|
2089
2391
|
// Messages API takes it.
|
|
2090
2392
|
...stream.body,
|
|
@@ -2145,11 +2447,27 @@ async function callClaudeWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2145
2447
|
authorizationToken: endpoint.token
|
|
2146
2448
|
}});
|
|
2147
2449
|
}
|
|
2148
|
-
async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope) {
|
|
2450
|
+
async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope, turn) {
|
|
2149
2451
|
const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
|
|
2150
2452
|
const resolvedModel = model || DEFAULT_OPENAI_MODEL;
|
|
2151
2453
|
const imageDetail = getOpenAIImageDetail(resolvedModel);
|
|
2454
|
+
const serverUrl = mcpChatUrl(endpoint.url, "openai", resolvedModel);
|
|
2152
2455
|
const web = await resolveWebAccess(service);
|
|
2456
|
+
const effortFields = chatEffortFields("openai", resolvedModel, await resolveAnswerMode(service));
|
|
2457
|
+
let listedTools;
|
|
2458
|
+
if (turn) {
|
|
2459
|
+
turn.mcpToolsKey = void 0;
|
|
2460
|
+
turn.mcpToolsInjected = false;
|
|
2461
|
+
turn.mcpToolsService = void 0;
|
|
2462
|
+
turn.mcpToolsItemId = void 0;
|
|
2463
|
+
if (turn.reuseMcpToolList && !mcpListToolsReuseOff && !mcpListToolsOffStored(service)) {
|
|
2464
|
+
turn.mcpToolsKey = mcpListToolsKey(serverUrl, mcpScope?.anonymous, service, mcpScope?.publicProjectId, turn.userId);
|
|
2465
|
+
turn.mcpToolsService = service;
|
|
2466
|
+
listedTools = mcpListToolsCache.get(turn.mcpToolsKey);
|
|
2467
|
+
turn.mcpToolsInjected = !!listedTools;
|
|
2468
|
+
if (listedTools) turn.mcpToolsItemId = listedTools.id;
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2153
2471
|
const messageList = messages && messages.length ? prepareOpenAIMessages(messages, imageDetail) : [
|
|
2154
2472
|
{
|
|
2155
2473
|
role: "user",
|
|
@@ -2163,6 +2481,12 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2163
2481
|
content: system
|
|
2164
2482
|
}
|
|
2165
2483
|
] : [],
|
|
2484
|
+
// Right after the system message, exactly as OpenAI returned it, so OpenAI
|
|
2485
|
+
// skips asking the MCP server for its tools again. Absent unless stored.
|
|
2486
|
+
// This item passes through the server's $CLIENT_SECRET / $ACCESS_TOKEN /
|
|
2487
|
+
// $ID_TOKEN substitution; rememberMcpListTools never stores a listing that
|
|
2488
|
+
// contains one of those literals.
|
|
2489
|
+
...listedTools ? [{ type: listedTools.type, id: listedTools.id, server_label: listedTools.server_label, tools: listedTools.tools }] : [],
|
|
2166
2490
|
...messageList.map((m) => ({
|
|
2167
2491
|
role: m.role,
|
|
2168
2492
|
content: m.content
|
|
@@ -2185,6 +2509,8 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2185
2509
|
data: {
|
|
2186
2510
|
model: resolvedModel,
|
|
2187
2511
|
max_output_tokens: getMaxOutputTokens("openai", resolvedModel),
|
|
2512
|
+
// `reasoning: {effort}` for a fast or thorough project, nothing otherwise.
|
|
2513
|
+
...effortFields,
|
|
2188
2514
|
// Top level beside model/input/tools, which is where the Responses API
|
|
2189
2515
|
// takes it.
|
|
2190
2516
|
...stream.body,
|
|
@@ -2195,7 +2521,7 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2195
2521
|
{
|
|
2196
2522
|
type: "mcp",
|
|
2197
2523
|
server_label: MCP_NAME,
|
|
2198
|
-
server_url:
|
|
2524
|
+
server_url: serverUrl,
|
|
2199
2525
|
require_approval: "never",
|
|
2200
2526
|
// No `headers` at all for an anonymous turn: `Bearer ` with an
|
|
2201
2527
|
// empty token is a credential the MCP server rejects, and the
|
|
@@ -2838,12 +3164,38 @@ function buildChatDisplayList(messages, opts) {
|
|
|
2838
3164
|
} else if (!grp.finished && grp.driver === "worker" && !liveIndexChecked && !liveIndexKeys[grp.key]) {
|
|
2839
3165
|
grp.resolving = true;
|
|
2840
3166
|
grp.resolvingReason = "status";
|
|
3167
|
+
var openRun = opts && opts.runStubs && (grp.path && opts.runStubs[grp.path] || opts.runStubs[grp.key]);
|
|
3168
|
+
var runNow = opts && opts.liveIndexRunningKeys;
|
|
3169
|
+
if (opts && opts.liveIndexRunningChecked && openRun && openRun.status === "working" && runNow && !runNow[grp.key] && !(grp.path && runNow[grp.path]) && !(grp.name && runNow[grp.name])) {
|
|
3170
|
+
grp.resolving = false;
|
|
3171
|
+
grp.resolvingReason = void 0;
|
|
3172
|
+
grp.queued = true;
|
|
3173
|
+
}
|
|
2841
3174
|
} else {
|
|
2842
3175
|
grp.resolving = false;
|
|
2843
3176
|
}
|
|
2844
3177
|
var runningNow = opts && opts.liveIndexRunningKeys;
|
|
2845
|
-
if (runningNow && !grp.finished && !grp.resolving && grp.status === "active" &&
|
|
2846
|
-
|
|
3178
|
+
if (runningNow && !grp.finished && !grp.resolving && grp.status === "active" && !runningNow[grp.key] && !(grp.path && runningNow[grp.path]) && !(grp.name && runningNow[grp.name])) {
|
|
3179
|
+
var otherRunning = false;
|
|
3180
|
+
if (opts && opts.liveIndexRunningChecked) {
|
|
3181
|
+
for (var rk in runningNow) {
|
|
3182
|
+
if (runningNow[rk] && rk !== grp.key && rk !== grp.path && rk !== grp.name) {
|
|
3183
|
+
otherRunning = true;
|
|
3184
|
+
break;
|
|
3185
|
+
}
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
var openRun2 = opts && opts.runStubs && (grp.path && opts.runStubs[grp.path] || opts.runStubs[grp.key]);
|
|
3189
|
+
var waitingOpenRun = !!(opts && opts.liveIndexRunningChecked && openRun2 && openRun2.status === "working");
|
|
3190
|
+
var startedRun = false;
|
|
3191
|
+
for (var mi = 0; mi < grp.members.length; mi++) {
|
|
3192
|
+
var mm = grp.members[mi].msg;
|
|
3193
|
+
if (mm && mm.role === "assistant" && !mm.isPending && !mm.isPendingInProcess && !mm.isPendingQueued) {
|
|
3194
|
+
startedRun = true;
|
|
3195
|
+
break;
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
if (!startedRun && (liveIndexKeys[grp.key] || grp.path && liveIndexKeys[grp.path] || otherRunning || waitingOpenRun)) grp.queued = true;
|
|
2847
3199
|
}
|
|
2848
3200
|
}
|
|
2849
3201
|
var superseded = {};
|
|
@@ -2870,6 +3222,7 @@ function buildChatDisplayList(messages, opts) {
|
|
|
2870
3222
|
}
|
|
2871
3223
|
var now = opts && typeof opts.now === "number" ? opts.now : Date.now();
|
|
2872
3224
|
var runningKeys = opts && opts.liveIndexRunningKeys;
|
|
3225
|
+
var runningChecked = !!(opts && opts.liveIndexRunningChecked);
|
|
2873
3226
|
var stubClearedAt = opts && typeof opts.stubClearedAt === "number" && opts.stubClearedAt > 0 ? opts.stubClearedAt : 0;
|
|
2874
3227
|
for (var sp in runStubs) {
|
|
2875
3228
|
var rec = runStubs[sp];
|
|
@@ -2896,6 +3249,7 @@ function buildChatDisplayList(messages, opts) {
|
|
|
2896
3249
|
var st = "active";
|
|
2897
3250
|
var fin = false;
|
|
2898
3251
|
var res = false;
|
|
3252
|
+
var waitingStub = false;
|
|
2899
3253
|
var reason;
|
|
2900
3254
|
if (!live) {
|
|
2901
3255
|
if (rec.status === "done" || doneKeys[sp] || doneKeys[canonIndexKey(sp)] || doneKeys[fname] || doneKeys[canonIndexKey(fname)]) {
|
|
@@ -2913,6 +3267,8 @@ function buildChatDisplayList(messages, opts) {
|
|
|
2913
3267
|
} else if (typeof rec.started === "number" && now - rec.started > RUN_RECORD_WORKING_STALE_MS) {
|
|
2914
3268
|
st = "error";
|
|
2915
3269
|
fin = true;
|
|
3270
|
+
} else if (runningChecked && rec.status === "working") {
|
|
3271
|
+
waitingStub = true;
|
|
2916
3272
|
} else {
|
|
2917
3273
|
res = true;
|
|
2918
3274
|
reason = "status";
|
|
@@ -2946,7 +3302,7 @@ function buildChatDisplayList(messages, opts) {
|
|
|
2946
3302
|
resolving: res,
|
|
2947
3303
|
resolvingReason: reason,
|
|
2948
3304
|
stub: true,
|
|
2949
|
-
queued: live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
|
|
3305
|
+
queued: waitingStub || live && !!runningKeys && !runningKeys[sp] && !runningKeys[canonIndexKey(sp)] && !runningKeys[fname] ? true : void 0,
|
|
2950
3306
|
stubError: rec.error || (st === "error" && !rec.error ? "Indexing did not finish." : void 0)
|
|
2951
3307
|
};
|
|
2952
3308
|
stubList.push({ started: typeof rec.started === "number" ? rec.started : Infinity, group: sg });
|
|
@@ -3121,165 +3477,6 @@ function buildChatGreeting(params) {
|
|
|
3121
3477
|
return { lead, name, tail, text: lead + (name ? " " + name : "") + tail };
|
|
3122
3478
|
}
|
|
3123
3479
|
|
|
3124
|
-
// src/engine/errors.ts
|
|
3125
|
-
var STATUS_MESSAGE = {
|
|
3126
|
-
"408": "The AI provider timed out before it started.",
|
|
3127
|
-
"409": "The AI provider rejected the request as conflicting.",
|
|
3128
|
-
"413": "The request was too large for the AI provider.",
|
|
3129
|
-
"429": "The AI provider is rate limiting requests right now.",
|
|
3130
|
-
"500": "The AI provider hit an internal error.",
|
|
3131
|
-
"502": "The AI provider is temporarily unreachable.",
|
|
3132
|
-
"503": "The AI provider is temporarily unavailable.",
|
|
3133
|
-
"504": "The AI provider timed out."
|
|
3134
|
-
};
|
|
3135
|
-
function isTransientStatus(status) {
|
|
3136
|
-
return status === 408 || status === 425 || status === 429 || status >= 500;
|
|
3137
|
-
}
|
|
3138
|
-
function isCsrStatusEnvelope(res) {
|
|
3139
|
-
return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
|
|
3140
|
-
}
|
|
3141
|
-
function csrEnvelopeError(input) {
|
|
3142
|
-
if (!isCsrStatusEnvelope(input)) return void 0;
|
|
3143
|
-
if (input.status !== "failed") return void 0;
|
|
3144
|
-
return input.error != null ? input.error : { message: "The AI provider request failed." };
|
|
3145
|
-
}
|
|
3146
|
-
function getErrorMessage(input) {
|
|
3147
|
-
var envErr = csrEnvelopeError(input);
|
|
3148
|
-
if (envErr !== void 0) input = envErr;
|
|
3149
|
-
if (!input) return "Something went wrong.";
|
|
3150
|
-
if (typeof input === "string") return input;
|
|
3151
|
-
if (input.error && input.error.message) return input.error.message;
|
|
3152
|
-
if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
|
|
3153
|
-
if (input.body && typeof input.body.message === "string") return input.body.message;
|
|
3154
|
-
if (input.message) return input.message;
|
|
3155
|
-
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
|
|
3156
|
-
if (status) {
|
|
3157
|
-
var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
|
|
3158
|
-
return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
|
|
3159
|
-
}
|
|
3160
|
-
return "Something went wrong.";
|
|
3161
|
-
}
|
|
3162
|
-
function isRetriedFailure(input) {
|
|
3163
|
-
var envErr = csrEnvelopeError(input);
|
|
3164
|
-
if (envErr !== void 0) input = envErr;
|
|
3165
|
-
return !!input && typeof input === "object" && input.retried === true;
|
|
3166
|
-
}
|
|
3167
|
-
function isErrorResponseBody(response) {
|
|
3168
|
-
var envErr = csrEnvelopeError(response);
|
|
3169
|
-
if (envErr !== void 0) response = envErr;
|
|
3170
|
-
if (!response || typeof response !== "object") return envErr !== void 0;
|
|
3171
|
-
if (typeof response.status_code === "number" && response.status_code >= 400) return true;
|
|
3172
|
-
if (response.type === "error") return true;
|
|
3173
|
-
if (response.error && (response.error.message || response.error.type)) return true;
|
|
3174
|
-
var body = response.body;
|
|
3175
|
-
if (body && typeof body === "object") {
|
|
3176
|
-
if (body.type === "error") return true;
|
|
3177
|
-
if (body.error && (body.error.message || body.error.type)) return true;
|
|
3178
|
-
}
|
|
3179
|
-
if (typeof response.message === "string" && response.message.length) {
|
|
3180
|
-
var hasClaude = Array.isArray(response.content);
|
|
3181
|
-
var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
|
|
3182
|
-
if (!hasClaude && !hasOpenAI) return true;
|
|
3183
|
-
}
|
|
3184
|
-
return false;
|
|
3185
|
-
}
|
|
3186
|
-
function isNonRetryableRequestError(input) {
|
|
3187
|
-
var envErr = csrEnvelopeError(input);
|
|
3188
|
-
if (envErr !== void 0) input = envErr;
|
|
3189
|
-
if (!input || typeof input !== "object") return false;
|
|
3190
|
-
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
|
|
3191
|
-
var param = void 0;
|
|
3192
|
-
var blobs = [];
|
|
3193
|
-
var sources = [input.error, input.body && input.body.error, input.body, input];
|
|
3194
|
-
for (var i = 0; i < sources.length; i++) {
|
|
3195
|
-
var e = sources[i];
|
|
3196
|
-
if (!e) continue;
|
|
3197
|
-
if (typeof e === "string") {
|
|
3198
|
-
blobs.push(e);
|
|
3199
|
-
continue;
|
|
3200
|
-
}
|
|
3201
|
-
if (typeof e !== "object") continue;
|
|
3202
|
-
if (param === void 0 && e.param != null) param = e.param;
|
|
3203
|
-
if (typeof e.code === "string") blobs.push(e.code);
|
|
3204
|
-
if (typeof e.type === "string") blobs.push(e.type);
|
|
3205
|
-
if (typeof e.message === "string") blobs.push(e.message);
|
|
3206
|
-
}
|
|
3207
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3208
|
-
if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
|
|
3209
|
-
return true;
|
|
3210
|
-
}
|
|
3211
|
-
var isClientReqStatus = status === 400 || status === 422;
|
|
3212
|
-
if (isClientReqStatus && param != null && param !== "") return true;
|
|
3213
|
-
if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
|
|
3214
|
-
return true;
|
|
3215
|
-
}
|
|
3216
|
-
return false;
|
|
3217
|
-
}
|
|
3218
|
-
function isAuthExpiredError(input) {
|
|
3219
|
-
var envErr = csrEnvelopeError(input);
|
|
3220
|
-
if (envErr !== void 0) input = envErr;
|
|
3221
|
-
if (!input) return false;
|
|
3222
|
-
var blobs = [];
|
|
3223
|
-
var push = function(v) {
|
|
3224
|
-
if (typeof v === "string" && v) blobs.push(v);
|
|
3225
|
-
};
|
|
3226
|
-
if (typeof input === "string") push(input);
|
|
3227
|
-
else {
|
|
3228
|
-
push(input.message);
|
|
3229
|
-
push(input.code);
|
|
3230
|
-
if (input.error) {
|
|
3231
|
-
push(input.error.message);
|
|
3232
|
-
push(input.error.code);
|
|
3233
|
-
push(input.error.type);
|
|
3234
|
-
}
|
|
3235
|
-
if (input.body) {
|
|
3236
|
-
push(input.body.message);
|
|
3237
|
-
if (input.body.error) {
|
|
3238
|
-
push(input.body.error.message);
|
|
3239
|
-
push(input.body.error.code);
|
|
3240
|
-
push(input.body.error.type);
|
|
3241
|
-
}
|
|
3242
|
-
}
|
|
3243
|
-
if (typeof input.status === "number" && input.status === 401) return true;
|
|
3244
|
-
if (typeof input.status_code === "number" && input.status_code === 401) return true;
|
|
3245
|
-
}
|
|
3246
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3247
|
-
if (!hay) return false;
|
|
3248
|
-
return hay.indexOf("token has expired") !== -1 || hay.indexOf("token is expired") !== -1 || hay.indexOf("expired_token") !== -1 || hay.indexOf("invalid_token") !== -1 || hay.indexOf("unauthorized") !== -1 || hay.indexOf("not authorized") !== -1 || hay.indexOf("invalid_request") !== -1 && hay.indexOf("token") !== -1;
|
|
3249
|
-
}
|
|
3250
|
-
function isProviderApiKeyError(input) {
|
|
3251
|
-
var envErr = csrEnvelopeError(input);
|
|
3252
|
-
if (envErr !== void 0) input = envErr;
|
|
3253
|
-
if (!input) return false;
|
|
3254
|
-
var blobs = [];
|
|
3255
|
-
var push = function(v) {
|
|
3256
|
-
if (typeof v === "string" && v) blobs.push(v);
|
|
3257
|
-
};
|
|
3258
|
-
if (typeof input === "string") push(input);
|
|
3259
|
-
else {
|
|
3260
|
-
push(input.message);
|
|
3261
|
-
push(input.code);
|
|
3262
|
-
push(input.type);
|
|
3263
|
-
if (input.error) {
|
|
3264
|
-
push(input.error.message);
|
|
3265
|
-
push(input.error.code);
|
|
3266
|
-
push(input.error.type);
|
|
3267
|
-
}
|
|
3268
|
-
if (input.body) {
|
|
3269
|
-
push(input.body.message);
|
|
3270
|
-
push(input.body.type);
|
|
3271
|
-
if (input.body.error) {
|
|
3272
|
-
push(input.body.error.message);
|
|
3273
|
-
push(input.body.error.code);
|
|
3274
|
-
push(input.body.error.type);
|
|
3275
|
-
}
|
|
3276
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3279
|
-
if (!hay) return false;
|
|
3280
|
-
return hay.indexOf("authentication_error") !== -1 || hay.indexOf("invalid_api_key") !== -1 || hay.indexOf("invalid x-api-key") !== -1 || hay.indexOf("incorrect api key") !== -1 || hay.indexOf("invalid api key") !== -1 || hay.indexOf("no api key provided") !== -1;
|
|
3281
|
-
}
|
|
3282
|
-
|
|
3283
3480
|
// src/engine/citations.ts
|
|
3284
3481
|
var DATA_TOOL_NAMES = [
|
|
3285
3482
|
"getRecords",
|
|
@@ -5391,6 +5588,8 @@ var _ChatSession = class _ChatSession {
|
|
|
5391
5588
|
passPaging: {},
|
|
5392
5589
|
liveIndexChecked: false,
|
|
5393
5590
|
liveIndexRunning: {},
|
|
5591
|
+
liveIndexRunningChecked: false,
|
|
5592
|
+
liveIndexSettled: {},
|
|
5394
5593
|
stoppedIndexIds: {}
|
|
5395
5594
|
};
|
|
5396
5595
|
this.bgTaskQueue = [];
|
|
@@ -5418,7 +5617,7 @@ var _ChatSession = class _ChatSession {
|
|
|
5418
5617
|
* every file the server still has indexing work for; `checked` is false until the
|
|
5419
5618
|
* first answer for this chat, and false means "we do not know yet". */
|
|
5420
5619
|
getLiveIndexState() {
|
|
5421
|
-
return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {} };
|
|
5620
|
+
return { keys: this.state.liveIndexKeys, checked: this.state.liveIndexChecked, running: this.state.liveIndexRunning || {}, runningChecked: !!this.state.liveIndexRunningChecked, settled: this.state.liveIndexSettled || {} };
|
|
5422
5621
|
}
|
|
5423
5622
|
/** Passes that were on a row when the user stopped it, so the display layer can
|
|
5424
5623
|
* still tell that this run was stopped once the stop has left no other trace.
|
|
@@ -5702,6 +5901,7 @@ var _ChatSession = class _ChatSession {
|
|
|
5702
5901
|
var next = {};
|
|
5703
5902
|
var running = {};
|
|
5704
5903
|
var truncated = false;
|
|
5904
|
+
var runningTruncated = false;
|
|
5705
5905
|
var settledIds = {};
|
|
5706
5906
|
this.state.messages.forEach(function(m) {
|
|
5707
5907
|
if (!m._serverItemId) return;
|
|
@@ -5710,7 +5910,15 @@ var _ChatSession = class _ChatSession {
|
|
|
5710
5910
|
});
|
|
5711
5911
|
for (var li = 0; li < lists.length; li++) {
|
|
5712
5912
|
var list = lists[li] && Array.isArray(lists[li].list) ? lists[li].list : [];
|
|
5713
|
-
if (list.length >= WORKER_PASS_ADOPT_LIMIT
|
|
5913
|
+
if (list.length >= WORKER_PASS_ADOPT_LIMIT || lists[li] && lists[li].endOfList === false) {
|
|
5914
|
+
truncated = true;
|
|
5915
|
+
for (var si = 0; si < list.length; si++) {
|
|
5916
|
+
if (list[si] && list[si].status === "running") {
|
|
5917
|
+
runningTruncated = true;
|
|
5918
|
+
break;
|
|
5919
|
+
}
|
|
5920
|
+
}
|
|
5921
|
+
}
|
|
5714
5922
|
for (var i = 0; i < list.length; i++) {
|
|
5715
5923
|
var item = list[i];
|
|
5716
5924
|
if (!item || item.status !== "pending" && item.status !== "running") continue;
|
|
@@ -5755,7 +5963,19 @@ var _ChatSession = class _ChatSession {
|
|
|
5755
5963
|
}
|
|
5756
5964
|
}
|
|
5757
5965
|
this.state.liveIndexKeys = next;
|
|
5966
|
+
if (this.state.liveIndexRunningChecked !== !runningTruncated) changed = true;
|
|
5967
|
+
var settledNow = this.state.liveIndexSettled || {};
|
|
5968
|
+
var settledNext = {};
|
|
5969
|
+
for (var sk in settledNow) if (settledNow[sk] && !next[sk]) settledNext[sk] = true;
|
|
5970
|
+
if (nowChecked) {
|
|
5971
|
+
for (var wk in was) if (was[wk] && !next[wk]) {
|
|
5972
|
+
if (!settledNext[wk]) changed = true;
|
|
5973
|
+
settledNext[wk] = true;
|
|
5974
|
+
}
|
|
5975
|
+
}
|
|
5976
|
+
this.state.liveIndexSettled = settledNext;
|
|
5758
5977
|
this.state.liveIndexRunning = running;
|
|
5978
|
+
this.state.liveIndexRunningChecked = !runningTruncated;
|
|
5759
5979
|
this.state.liveIndexChecked = nowChecked;
|
|
5760
5980
|
this._liveIndexAt = nowMs();
|
|
5761
5981
|
this._liveIndexKey = this.getHistoryCacheKey();
|
|
@@ -5766,6 +5986,8 @@ var _ChatSession = class _ChatSession {
|
|
|
5766
5986
|
_resetLiveIndexKeys() {
|
|
5767
5987
|
this.state.liveIndexKeys = {};
|
|
5768
5988
|
this.state.liveIndexRunning = {};
|
|
5989
|
+
this.state.liveIndexRunningChecked = false;
|
|
5990
|
+
this.state.liveIndexSettled = {};
|
|
5769
5991
|
this.state.liveIndexChecked = false;
|
|
5770
5992
|
this._liveIndexAt = 0;
|
|
5771
5993
|
this.state.passPaging = {};
|
|
@@ -7019,7 +7241,7 @@ var _ChatSession = class _ChatSession {
|
|
|
7019
7241
|
* one it was composed for. Falls back to the live read only when a caller
|
|
7020
7242
|
* omits them.
|
|
7021
7243
|
*/
|
|
7022
|
-
_callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner) {
|
|
7244
|
+
_callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner, turn) {
|
|
7023
7245
|
if (projectId === void 0 || owner === void 0) {
|
|
7024
7246
|
var id = this.host.getIdentity();
|
|
7025
7247
|
if (projectId === void 0) projectId = id.projectId;
|
|
@@ -7027,14 +7249,49 @@ var _ChatSession = class _ChatSession {
|
|
|
7027
7249
|
}
|
|
7028
7250
|
var liveId = this.host.getIdentity();
|
|
7029
7251
|
var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
|
|
7030
|
-
|
|
7252
|
+
if (turn) turn.userId = liveId.anonymous ? "" : liveId.userId || "";
|
|
7253
|
+
return platform === "openai" ? callOpenAIWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope, turn) : callClaudeWithPublicMcp(prompt, projectId, owner, messages, system, model, userId, extractContent, fileUrls, void 0, void 0, mcpScope);
|
|
7254
|
+
}
|
|
7255
|
+
/**
|
|
7256
|
+
* A fresh per-send record for the request builder (see requests.ts ChatTurnContext).
|
|
7257
|
+
* Chat turns only, and only OpenAI reuses a tool listing: Claude's MCP connector has no
|
|
7258
|
+
* equivalent item, and indexing passes never come through here. Off unless the host
|
|
7259
|
+
* set `reuseMcpToolList: true` in configureChatEngine.
|
|
7260
|
+
*/
|
|
7261
|
+
_newChatTurn(platform) {
|
|
7262
|
+
var on = false;
|
|
7263
|
+
try {
|
|
7264
|
+
on = chatEngineConfig().reuseMcpToolList === true;
|
|
7265
|
+
} catch (_) {
|
|
7266
|
+
on = false;
|
|
7267
|
+
}
|
|
7268
|
+
return { reuseMcpToolList: platform === "openai" && on };
|
|
7269
|
+
}
|
|
7270
|
+
/**
|
|
7271
|
+
* What a settled chat turn means for the stored MCP tool listing: a failure drops it
|
|
7272
|
+
* when the turn carried it (forgetMcpListToolsOnFailure decides whether reuse also
|
|
7273
|
+
* stops); a good OpenAI body refreshes it. A stopped poll or a cancelled row says
|
|
7274
|
+
* nothing either way. Applied once per turn: an exception thrown later by a UI
|
|
7275
|
+
* handler on the same chain is not a provider failure.
|
|
7276
|
+
*/
|
|
7277
|
+
_settleChatTurnTools(turn, response, failed) {
|
|
7278
|
+
if (!turn || turn.settled) return;
|
|
7279
|
+
turn.settled = true;
|
|
7280
|
+
if (failed || isErrorResponseBody(response)) {
|
|
7281
|
+
forgetMcpListToolsOnFailure(turn, response);
|
|
7282
|
+
return;
|
|
7283
|
+
}
|
|
7284
|
+
if (isPollStopped(response) || this._isCancelledPollResult(response)) return;
|
|
7285
|
+
rememberMcpListTools(turn, response);
|
|
7031
7286
|
}
|
|
7032
7287
|
dispatchAgentRequest(params) {
|
|
7033
7288
|
var self = this;
|
|
7034
7289
|
var dispatchItemId;
|
|
7290
|
+
var turn;
|
|
7035
7291
|
var sendAndPoll = function() {
|
|
7292
|
+
turn = self._newChatTurn(params.aiPlatform);
|
|
7036
7293
|
return Promise.resolve(
|
|
7037
|
-
self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner)
|
|
7294
|
+
self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner, turn)
|
|
7038
7295
|
).then(function(initial) {
|
|
7039
7296
|
if (initial && initial.poll && (initial.status === "pending" || initial.status === "running")) {
|
|
7040
7297
|
if (initial.id) {
|
|
@@ -7063,12 +7320,14 @@ var _ChatSession = class _ChatSession {
|
|
|
7063
7320
|
}
|
|
7064
7321
|
return response;
|
|
7065
7322
|
}).then(function(response) {
|
|
7323
|
+
self._settleChatTurnTools(turn, response);
|
|
7066
7324
|
if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: "", isError: false, cancelled: true };
|
|
7067
7325
|
if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
|
|
7068
7326
|
var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
|
|
7069
7327
|
answer = (answer || "").trim();
|
|
7070
7328
|
return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
|
|
7071
7329
|
}).catch(function(err) {
|
|
7330
|
+
self._settleChatTurnTools(turn, err, true);
|
|
7072
7331
|
return { content: getErrorMessage(err), isError: true };
|
|
7073
7332
|
}).then(function(result) {
|
|
7074
7333
|
delete self.pendingAgentRequests[params.key];
|
|
@@ -7473,7 +7732,8 @@ var _ChatSession = class _ChatSession {
|
|
|
7473
7732
|
this.scrollForDispatch(stageId);
|
|
7474
7733
|
var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
|
|
7475
7734
|
var capturedQueuedLid = queuedBubble._localId;
|
|
7476
|
-
|
|
7735
|
+
var queuedTurn = this._newChatTurn(aiPlatform);
|
|
7736
|
+
Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner, queuedTurn)).then(function(result) {
|
|
7477
7737
|
var sendingIdx = self.getHistoryCacheKey() !== capturedKey ? -1 : self.state.messages.findIndex(function(m) {
|
|
7478
7738
|
return m.isSendingToServer && (m.isPendingQueued || m.isPendingInProcess) && m.role === "user" && !m._stageId && (m._ownerKey === void 0 || m._ownerKey === capturedKey);
|
|
7479
7739
|
});
|
|
@@ -7494,14 +7754,18 @@ var _ChatSession = class _ChatSession {
|
|
|
7494
7754
|
});
|
|
7495
7755
|
if (serverId) self._trackPoll(serverId, "fg", qp);
|
|
7496
7756
|
return qp.then(function(res) {
|
|
7757
|
+
self._settleChatTurnTools(queuedTurn, res);
|
|
7497
7758
|
if (isPollStopped(res)) return;
|
|
7498
7759
|
return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey);
|
|
7499
7760
|
}).catch(function(err) {
|
|
7761
|
+
self._settleChatTurnTools(queuedTurn, err, true);
|
|
7500
7762
|
return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey);
|
|
7501
7763
|
});
|
|
7502
7764
|
}
|
|
7765
|
+
self._settleChatTurnTools(queuedTurn, result);
|
|
7503
7766
|
return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
|
|
7504
7767
|
}).catch(function(err) {
|
|
7768
|
+
self._settleChatTurnTools(queuedTurn, err, true);
|
|
7505
7769
|
return self.onQueuedSendError(capturedComposed, err, void 0, capturedKey);
|
|
7506
7770
|
});
|
|
7507
7771
|
return;
|
|
@@ -7522,8 +7786,9 @@ var _ChatSession = class _ChatSession {
|
|
|
7522
7786
|
this.updateHistoryCache();
|
|
7523
7787
|
this.state.sending = true;
|
|
7524
7788
|
this.scrollForDispatch(stageId);
|
|
7789
|
+
var immediateUserLid = immediateUser._localId;
|
|
7525
7790
|
var historyForLlm = this.state.messages.filter(function(m) {
|
|
7526
|
-
if (m === immediateUser) return false;
|
|
7791
|
+
if (m === immediateUser || immediateUserLid && m && m._localId === immediateUserLid) return false;
|
|
7527
7792
|
return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder && !m.isCancelled && !m.isBackgroundTask && !m.isError;
|
|
7528
7793
|
});
|
|
7529
7794
|
historyForLlm.push({ role: "user", content: llmComposed });
|
|
@@ -7534,7 +7799,7 @@ var _ChatSession = class _ChatSession {
|
|
|
7534
7799
|
projectId: id.projectId,
|
|
7535
7800
|
history: historyForLlm
|
|
7536
7801
|
});
|
|
7537
|
-
var
|
|
7802
|
+
var immediatePlaceholderLid = immediatePlaceholder._localId;
|
|
7538
7803
|
var run = this.dispatchAgentRequest({
|
|
7539
7804
|
key,
|
|
7540
7805
|
projectId: id.projectId,
|
|
@@ -9134,9 +9399,23 @@ var _ChatSession = class _ChatSession {
|
|
|
9134
9399
|
});
|
|
9135
9400
|
}
|
|
9136
9401
|
/** The page progress to show for a file's row, or null (see _refreshPageProgress). */
|
|
9137
|
-
pageProgressFor(storagePath) {
|
|
9138
|
-
|
|
9139
|
-
|
|
9402
|
+
pageProgressFor(storagePath, fileName) {
|
|
9403
|
+
var map = this.state.indexPageProgress;
|
|
9404
|
+
if (!map) return null;
|
|
9405
|
+
var p = storagePath ? map[storagePath] : void 0;
|
|
9406
|
+
if (!p && fileName) {
|
|
9407
|
+
var hit = null;
|
|
9408
|
+
for (var k in map) {
|
|
9409
|
+
if (k === fileName || k.slice(-(fileName.length + 1)) === "/" + fileName) {
|
|
9410
|
+
if (hit) {
|
|
9411
|
+
hit = null;
|
|
9412
|
+
break;
|
|
9413
|
+
}
|
|
9414
|
+
hit = k;
|
|
9415
|
+
}
|
|
9416
|
+
}
|
|
9417
|
+
if (hit) p = map[hit];
|
|
9418
|
+
}
|
|
9140
9419
|
return p ? { saved: p.saved, total: p.total } : null;
|
|
9141
9420
|
}
|
|
9142
9421
|
_noteLiveLook(svcId, platform, results) {
|
|
@@ -9144,7 +9423,7 @@ var _ChatSession = class _ChatSession {
|
|
|
9144
9423
|
var complete = true;
|
|
9145
9424
|
for (var r = 0; r < results.length; r++) {
|
|
9146
9425
|
var list = results[r] && Array.isArray(results[r].list) ? results[r].list : [];
|
|
9147
|
-
if (list.length >= WORKER_PASS_ADOPT_LIMIT) complete = false;
|
|
9426
|
+
if (list.length >= WORKER_PASS_ADOPT_LIMIT || results[r] && results[r].endOfList === false) complete = false;
|
|
9148
9427
|
for (var i = 0; i < list.length; i++) if (list[i] && typeof list[i].id === "string") ids[list[i].id] = true;
|
|
9149
9428
|
}
|
|
9150
9429
|
this._lastLiveLook = complete ? { svcId, platform, at: Date.now(), ids } : null;
|
|
@@ -10175,6 +10454,7 @@ var _ChatSession = class _ChatSession {
|
|
|
10175
10454
|
uploadSingleAttachment(att, stageId) {
|
|
10176
10455
|
var self = this;
|
|
10177
10456
|
var id = this.host.getIdentity();
|
|
10457
|
+
var isIndexRetry = att.status === "indexError";
|
|
10178
10458
|
att.status = "uploading";
|
|
10179
10459
|
att.progress = null;
|
|
10180
10460
|
att.errorMessage = "";
|
|
@@ -10227,7 +10507,12 @@ var _ChatSession = class _ChatSession {
|
|
|
10227
10507
|
}
|
|
10228
10508
|
});
|
|
10229
10509
|
};
|
|
10230
|
-
|
|
10510
|
+
if (isIndexRetry) {
|
|
10511
|
+
hadExists = true;
|
|
10512
|
+
existedBefore = true;
|
|
10513
|
+
}
|
|
10514
|
+
return (isIndexRetry ? Promise.resolve(null) : findDuplicate(member)).then(function(dup) {
|
|
10515
|
+
if (isIndexRetry) return;
|
|
10231
10516
|
if (dup) {
|
|
10232
10517
|
duplicateOf = dup;
|
|
10233
10518
|
console.log("[chat-engine] skipping an upload the user already has:", member.storagePath, "->", dup);
|
|
@@ -10254,7 +10539,19 @@ var _ChatSession = class _ChatSession {
|
|
|
10254
10539
|
});
|
|
10255
10540
|
}).then(function() {
|
|
10256
10541
|
if (skipped) return;
|
|
10257
|
-
return self.host.getTemporaryUrl(duplicateOf || member.storagePath)
|
|
10542
|
+
return Promise.resolve(self.host.getTemporaryUrl(duplicateOf || member.storagePath)).catch(function(err) {
|
|
10543
|
+
var ecode = err && (err.code || err.body && err.body.code);
|
|
10544
|
+
var emsg = String(err && (err.message || err.body && err.body.message) || err || "");
|
|
10545
|
+
var refused = /no access to this file/i.test(emsg) || ecode === "INVALID_REQUEST" && /access/i.test(emsg);
|
|
10546
|
+
if (duplicateOf || !refused || typeof self.host.ensureFileIndexRecord !== "function") throw err;
|
|
10547
|
+
return Promise.resolve(self.host.ensureFileIndexRecord(member.storagePath, {
|
|
10548
|
+
name: member.file.name,
|
|
10549
|
+
mime: member.file.type || self.host.getMimeType(member.file.name),
|
|
10550
|
+
size: member.file.size
|
|
10551
|
+
})).then(function() {
|
|
10552
|
+
return self.host.getTemporaryUrl(member.storagePath);
|
|
10553
|
+
});
|
|
10554
|
+
});
|
|
10258
10555
|
}).then(function(url) {
|
|
10259
10556
|
if (skipped) return;
|
|
10260
10557
|
if (duplicateOf) {
|
|
@@ -10424,7 +10721,7 @@ var _ChatSession = class _ChatSession {
|
|
|
10424
10721
|
if (!self.state.attachments.some(function(a) {
|
|
10425
10722
|
return a.id === att.id;
|
|
10426
10723
|
})) return;
|
|
10427
|
-
if (att.status === "done"
|
|
10724
|
+
if (att.status === "done") {
|
|
10428
10725
|
if (att.kind === "folder" && att.uploadedUrls) {
|
|
10429
10726
|
att.uploadedUrls.forEach(function(u) {
|
|
10430
10727
|
collected.push({ name: u.path, url: u.url, storagePath: u.storagePath });
|
|
@@ -10475,6 +10772,11 @@ var _ChatSession = class _ChatSession {
|
|
|
10475
10772
|
_ChatSession.RUN_PASS_PAGE = 10;
|
|
10476
10773
|
var ChatSession = _ChatSession;
|
|
10477
10774
|
|
|
10775
|
+
exports.ANSWER_MODES = ANSWER_MODES;
|
|
10776
|
+
exports.ANSWER_MODE_HINTS = ANSWER_MODE_HINTS;
|
|
10777
|
+
exports.ANSWER_MODE_LABELS = ANSWER_MODE_LABELS;
|
|
10778
|
+
exports.ANSWER_MODE_OPTIONS = ANSWER_MODE_OPTIONS;
|
|
10779
|
+
exports.ANSWER_MODE_SETTING_LABEL = ANSWER_MODE_SETTING_LABEL;
|
|
10478
10780
|
exports.BG_INDEXING_QUEUE_SUFFIX = BG_INDEXING_QUEUE_SUFFIX;
|
|
10479
10781
|
exports.BOM = BOM;
|
|
10480
10782
|
exports.BOM_EXTS = BOM_EXTS;
|
|
@@ -10485,6 +10787,7 @@ exports.CONTEXT_WINDOW_BY_MODEL = CONTEXT_WINDOW_BY_MODEL;
|
|
|
10485
10787
|
exports.CONTEXT_WINDOW_DEFAULT = CONTEXT_WINDOW_DEFAULT;
|
|
10486
10788
|
exports.ChatSession = ChatSession;
|
|
10487
10789
|
exports.DATA_TOOL_NAMES = DATA_TOOL_NAMES;
|
|
10790
|
+
exports.DEFAULT_ANSWER_MODE = DEFAULT_ANSWER_MODE;
|
|
10488
10791
|
exports.DEFAULT_CLAUDE_MODEL = DEFAULT_CLAUDE_MODEL;
|
|
10489
10792
|
exports.DEFAULT_CONTEXT_WINDOW = DEFAULT_CONTEXT_WINDOW;
|
|
10490
10793
|
exports.DEFAULT_OPENAI_MODEL = DEFAULT_OPENAI_MODEL;
|
|
@@ -10555,6 +10858,7 @@ exports.XML_EXTS = XML_EXTS;
|
|
|
10555
10858
|
exports.__resetSplitHistoryState = __resetSplitHistoryState;
|
|
10556
10859
|
exports.accessSettingFrom = accessSettingFrom;
|
|
10557
10860
|
exports.adoptLocalAnswerIntoPage = adoptLocalAnswerIntoPage;
|
|
10861
|
+
exports.answerModeFrom = answerModeFrom;
|
|
10558
10862
|
exports.answerUsedNoDataTool = answerUsedNoDataTool;
|
|
10559
10863
|
exports.applyEncodingDeclaration = applyEncodingDeclaration;
|
|
10560
10864
|
exports.applyRetrievalNotes = applyRetrievalNotes;
|
|
@@ -10579,6 +10883,7 @@ exports.callClaudeWithPublicMcp = callClaudeWithPublicMcp;
|
|
|
10579
10883
|
exports.callOpenAIWithPublicMcp = callOpenAIWithPublicMcp;
|
|
10580
10884
|
exports.canonicalizePathForm = canonicalizePathForm;
|
|
10581
10885
|
exports.chatCacheKey = chatCacheKey;
|
|
10886
|
+
exports.chatEffortFields = chatEffortFields;
|
|
10582
10887
|
exports.chatEngineConfig = chatEngineConfig;
|
|
10583
10888
|
exports.chatGreetingFrom = chatGreetingFrom;
|
|
10584
10889
|
exports.chatStreamWiring = chatStreamWiring;
|
|
@@ -10673,6 +10978,7 @@ exports.markImagePreviewStale = markImagePreviewStale;
|
|
|
10673
10978
|
exports.mayKeepStreamedAnswer = mayKeepStreamedAnswer;
|
|
10674
10979
|
exports.mintCacheBustStamp = mintCacheBustStamp;
|
|
10675
10980
|
exports.needsBomForExt = needsBomForExt;
|
|
10981
|
+
exports.normalizeAnswerMode = normalizeAnswerMode;
|
|
10676
10982
|
exports.normalizeAttachmentPathCandidate = normalizeAttachmentPathCandidate;
|
|
10677
10983
|
exports.normalizeChatGreeting = normalizeChatGreeting;
|
|
10678
10984
|
exports.normalizeExt = normalizeExt;
|
|
@@ -10698,6 +11004,7 @@ exports.previewMintCacheToken = previewMintCacheToken;
|
|
|
10698
11004
|
exports.previewableExtOf = previewableExtOf;
|
|
10699
11005
|
exports.primeProjectSettings = primeProjectSettings;
|
|
10700
11006
|
exports.projectAccessSetting = projectAccessSetting;
|
|
11007
|
+
exports.projectAnswerMode = projectAnswerMode;
|
|
10701
11008
|
exports.projectAsksUploadAccess = projectAsksUploadAccess;
|
|
10702
11009
|
exports.projectChatGreeting = projectChatGreeting;
|
|
10703
11010
|
exports.projectSettingsSettled = projectSettingsSettled;
|
|
@@ -10713,6 +11020,7 @@ exports.renderInlineLinkHtml = renderInlineLinkHtml;
|
|
|
10713
11020
|
exports.repairUrlEntities = repairUrlEntities;
|
|
10714
11021
|
exports.repairUrlWhitespace = repairUrlWhitespace;
|
|
10715
11022
|
exports.resetFileIndexOnServer = resetFileIndexOnServer;
|
|
11023
|
+
exports.resolveAnswerMode = resolveAnswerMode;
|
|
10716
11024
|
exports.resolveImagePreviewUrl = resolveImagePreviewUrl;
|
|
10717
11025
|
exports.resolveSkipDuplicateFiles = resolveSkipDuplicateFiles;
|
|
10718
11026
|
exports.resolveWebAccess = resolveWebAccess;
|