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/dist/engine.mjs
CHANGED
|
@@ -78,6 +78,30 @@ function normalizeSkipDuplicateFiles(value) {
|
|
|
78
78
|
function skipDuplicateFilesFrom(data) {
|
|
79
79
|
return data ? normalizeSkipDuplicateFiles(data.skip_duplicate_files) : DEFAULT_SKIP_DUPLICATE_FILES;
|
|
80
80
|
}
|
|
81
|
+
var ANSWER_MODES = ["standard", "fast", "thorough"];
|
|
82
|
+
var DEFAULT_ANSWER_MODE = "standard";
|
|
83
|
+
var ANSWER_MODE_SETTING_LABEL = "Answer mode";
|
|
84
|
+
var ANSWER_MODE_LABELS = {
|
|
85
|
+
standard: "Standard",
|
|
86
|
+
fast: "Fast",
|
|
87
|
+
thorough: "Thorough"
|
|
88
|
+
};
|
|
89
|
+
var ANSWER_MODE_HINTS = {
|
|
90
|
+
standard: "The AI model decides how long to think. This is the default.",
|
|
91
|
+
fast: "Shorter thinking for quicker answers. Best for simple questions.",
|
|
92
|
+
thorough: "Longer thinking before answering. Slower, and uses more tokens."
|
|
93
|
+
};
|
|
94
|
+
var ANSWER_MODE_OPTIONS = ANSWER_MODES.map((value) => ({
|
|
95
|
+
value,
|
|
96
|
+
label: ANSWER_MODE_LABELS[value],
|
|
97
|
+
hint: ANSWER_MODE_HINTS[value]
|
|
98
|
+
}));
|
|
99
|
+
function normalizeAnswerMode(value) {
|
|
100
|
+
return value === "fast" || value === "thorough" ? value : DEFAULT_ANSWER_MODE;
|
|
101
|
+
}
|
|
102
|
+
function answerModeFrom(data) {
|
|
103
|
+
return normalizeAnswerMode(data ? data.answer_mode : void 0);
|
|
104
|
+
}
|
|
81
105
|
var CHAT_GREETING_MAX_LENGTH = 400;
|
|
82
106
|
function normalizeChatGreeting(value) {
|
|
83
107
|
if (typeof value !== "string") return "";
|
|
@@ -167,6 +191,9 @@ function projectWebAccess(service) {
|
|
|
167
191
|
function projectSkipDuplicateFiles(service) {
|
|
168
192
|
return skipDuplicateFilesFrom(cachedProjectSettings(service));
|
|
169
193
|
}
|
|
194
|
+
function projectAnswerMode(service) {
|
|
195
|
+
return answerModeFrom(cachedProjectSettings(service));
|
|
196
|
+
}
|
|
170
197
|
function setProjectSettings(service, data) {
|
|
171
198
|
if (!service) return;
|
|
172
199
|
cache.set(service, { data: data || null, settled: true, inflight: null });
|
|
@@ -249,6 +276,10 @@ function resolveWebAccess(service, override) {
|
|
|
249
276
|
if (!service) return Promise.resolve(underCeiling(webAccessFrom(null), opt, override));
|
|
250
277
|
return loadProjectSettings(service).then(webAccessFrom, () => false).then((setting) => underCeiling(setting, opt, override));
|
|
251
278
|
}
|
|
279
|
+
function resolveAnswerMode(service) {
|
|
280
|
+
if (!service) return Promise.resolve(answerModeFrom(null));
|
|
281
|
+
return loadProjectSettings(service).then(answerModeFrom, () => answerModeFrom(null));
|
|
282
|
+
}
|
|
252
283
|
function skipDuplicateFilesEnabled(service) {
|
|
253
284
|
const opt = _config ? _config.skipDuplicateFiles : void 0;
|
|
254
285
|
return underCeiling(skipDuplicateFilesFrom(service ? cachedProjectSettings(service) : null), opt);
|
|
@@ -807,38 +838,44 @@ function buildChatSystemPrompt(params) {
|
|
|
807
838
|
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`}.
|
|
808
839
|
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.
|
|
809
840
|
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.`;
|
|
810
|
-
const
|
|
841
|
+
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.`;
|
|
842
|
+
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.`;
|
|
843
|
+
const groupIsAuthorized = indexGroupLiteral === '"authorized"' || indexGroupLiteral === "1";
|
|
844
|
+
const groupIsPublic = indexGroupLiteral === '"public"' || indexGroupLiteral === "0";
|
|
845
|
+
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'.`;
|
|
811
846
|
let systemPrompt = `
|
|
812
847
|
You are a dedicated assistant for the project ID: "${projectId}".
|
|
813
848
|
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.
|
|
814
849
|
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.
|
|
815
850
|
${groundingRules}
|
|
851
|
+
${webRule}
|
|
816
852
|
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.
|
|
817
|
-
FINDING THE DATA: the database is the way in, for every kind of file.
|
|
818
|
-
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
|
|
853
|
+
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.
|
|
854
|
+
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.
|
|
819
855
|
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.
|
|
820
856
|
${documentRules}
|
|
821
|
-
Complete answers over stored data:
|
|
822
|
-
|
|
823
|
-
|
|
857
|
+
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.
|
|
858
|
+
${accessGroupRule}
|
|
859
|
+
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.
|
|
860
|
+
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.
|
|
824
861
|
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.
|
|
825
862
|
- 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.
|
|
826
|
-
- 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>"
|
|
863
|
+
- 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.
|
|
827
864
|
${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).`}
|
|
828
|
-
Stored files
|
|
829
|
-
File links:
|
|
830
|
-
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"),
|
|
865
|
+
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.
|
|
866
|
+
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.
|
|
867
|
+
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.
|
|
831
868
|
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.
|
|
832
869
|
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.
|
|
833
870
|
Finding an extracted media file: it is INDEXED, and its location is a stored VALUE. Get it by QUERYING, never by constructing a filename.
|
|
834
871
|
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.
|
|
835
|
-
The reliable query is getRecords with reference "src::<the document's storage path>"
|
|
872
|
+
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.
|
|
836
873
|
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.
|
|
837
874
|
So "show me the photo of part X" is: find the record for that part, take its "__MEDIA__/..." value, link it.
|
|
838
875
|
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.
|
|
839
|
-
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.
|
|
876
|
+
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.
|
|
840
877
|
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.
|
|
841
|
-
File generation: When the user asks for DATABASE records as a file (CSV, spreadsheet, export, download), call exportRecordsToFile
|
|
878
|
+
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:
|
|
842
879
|
\`\`\`filename.csv
|
|
843
880
|
item,qty,total
|
|
844
881
|
Carrots,55,$38.50
|
|
@@ -851,7 +888,7 @@ About BunnyQuery (this app - questions about it are in scope):
|
|
|
851
888
|
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.
|
|
852
889
|
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.`}
|
|
853
890
|
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" ? `
|
|
854
|
-
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" ? `
|
|
891
|
+
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" ? `
|
|
855
892
|
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.` : ""}`;
|
|
856
893
|
if (greeting) {
|
|
857
894
|
systemPrompt += `
|
|
@@ -1035,6 +1072,165 @@ Records for the earlier windows/pages of this file are ALREADY saved (they refer
|
|
|
1035
1072
|
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.`;
|
|
1036
1073
|
}
|
|
1037
1074
|
|
|
1075
|
+
// src/engine/errors.ts
|
|
1076
|
+
var STATUS_MESSAGE = {
|
|
1077
|
+
"408": "The AI provider timed out before it started.",
|
|
1078
|
+
"409": "The AI provider rejected the request as conflicting.",
|
|
1079
|
+
"413": "The request was too large for the AI provider.",
|
|
1080
|
+
"429": "The AI provider is rate limiting requests right now.",
|
|
1081
|
+
"500": "The AI provider hit an internal error.",
|
|
1082
|
+
"502": "The AI provider is temporarily unreachable.",
|
|
1083
|
+
"503": "The AI provider is temporarily unavailable.",
|
|
1084
|
+
"504": "The AI provider timed out."
|
|
1085
|
+
};
|
|
1086
|
+
function isTransientStatus(status) {
|
|
1087
|
+
return status === 408 || status === 425 || status === 429 || status >= 500;
|
|
1088
|
+
}
|
|
1089
|
+
function isCsrStatusEnvelope(res) {
|
|
1090
|
+
return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
|
|
1091
|
+
}
|
|
1092
|
+
function csrEnvelopeError(input) {
|
|
1093
|
+
if (!isCsrStatusEnvelope(input)) return void 0;
|
|
1094
|
+
if (input.status !== "failed") return void 0;
|
|
1095
|
+
return input.error != null ? input.error : { message: "The AI provider request failed." };
|
|
1096
|
+
}
|
|
1097
|
+
function getErrorMessage(input) {
|
|
1098
|
+
var envErr = csrEnvelopeError(input);
|
|
1099
|
+
if (envErr !== void 0) input = envErr;
|
|
1100
|
+
if (!input) return "Something went wrong.";
|
|
1101
|
+
if (typeof input === "string") return input;
|
|
1102
|
+
if (input.error && input.error.message) return input.error.message;
|
|
1103
|
+
if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
|
|
1104
|
+
if (input.body && typeof input.body.message === "string") return input.body.message;
|
|
1105
|
+
if (input.message) return input.message;
|
|
1106
|
+
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
|
|
1107
|
+
if (status) {
|
|
1108
|
+
var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
|
|
1109
|
+
return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
|
|
1110
|
+
}
|
|
1111
|
+
return "Something went wrong.";
|
|
1112
|
+
}
|
|
1113
|
+
function isRetriedFailure(input) {
|
|
1114
|
+
var envErr = csrEnvelopeError(input);
|
|
1115
|
+
if (envErr !== void 0) input = envErr;
|
|
1116
|
+
return !!input && typeof input === "object" && input.retried === true;
|
|
1117
|
+
}
|
|
1118
|
+
function isErrorResponseBody(response) {
|
|
1119
|
+
var envErr = csrEnvelopeError(response);
|
|
1120
|
+
if (envErr !== void 0) response = envErr;
|
|
1121
|
+
if (!response || typeof response !== "object") return envErr !== void 0;
|
|
1122
|
+
if (typeof response.status_code === "number" && response.status_code >= 400) return true;
|
|
1123
|
+
if (response.type === "error") return true;
|
|
1124
|
+
if (response.error && (response.error.message || response.error.type)) return true;
|
|
1125
|
+
var body = response.body;
|
|
1126
|
+
if (body && typeof body === "object") {
|
|
1127
|
+
if (body.type === "error") return true;
|
|
1128
|
+
if (body.error && (body.error.message || body.error.type)) return true;
|
|
1129
|
+
}
|
|
1130
|
+
if (typeof response.message === "string" && response.message.length) {
|
|
1131
|
+
var hasClaude = Array.isArray(response.content);
|
|
1132
|
+
var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
|
|
1133
|
+
if (!hasClaude && !hasOpenAI) return true;
|
|
1134
|
+
}
|
|
1135
|
+
return false;
|
|
1136
|
+
}
|
|
1137
|
+
function isNonRetryableRequestError(input) {
|
|
1138
|
+
var envErr = csrEnvelopeError(input);
|
|
1139
|
+
if (envErr !== void 0) input = envErr;
|
|
1140
|
+
if (!input || typeof input !== "object") return false;
|
|
1141
|
+
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
|
|
1142
|
+
var param = void 0;
|
|
1143
|
+
var blobs = [];
|
|
1144
|
+
var sources = [input.error, input.body && input.body.error, input.body, input];
|
|
1145
|
+
for (var i = 0; i < sources.length; i++) {
|
|
1146
|
+
var e = sources[i];
|
|
1147
|
+
if (!e) continue;
|
|
1148
|
+
if (typeof e === "string") {
|
|
1149
|
+
blobs.push(e);
|
|
1150
|
+
continue;
|
|
1151
|
+
}
|
|
1152
|
+
if (typeof e !== "object") continue;
|
|
1153
|
+
if (param === void 0 && e.param != null) param = e.param;
|
|
1154
|
+
if (typeof e.code === "string") blobs.push(e.code);
|
|
1155
|
+
if (typeof e.type === "string") blobs.push(e.type);
|
|
1156
|
+
if (typeof e.message === "string") blobs.push(e.message);
|
|
1157
|
+
}
|
|
1158
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1159
|
+
if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
|
|
1160
|
+
return true;
|
|
1161
|
+
}
|
|
1162
|
+
var isClientReqStatus = status === 400 || status === 422;
|
|
1163
|
+
if (isClientReqStatus && param != null && param !== "") return true;
|
|
1164
|
+
if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
|
|
1165
|
+
return true;
|
|
1166
|
+
}
|
|
1167
|
+
return false;
|
|
1168
|
+
}
|
|
1169
|
+
function isAuthExpiredError(input) {
|
|
1170
|
+
var envErr = csrEnvelopeError(input);
|
|
1171
|
+
if (envErr !== void 0) input = envErr;
|
|
1172
|
+
if (!input) return false;
|
|
1173
|
+
var blobs = [];
|
|
1174
|
+
var push = function(v) {
|
|
1175
|
+
if (typeof v === "string" && v) blobs.push(v);
|
|
1176
|
+
};
|
|
1177
|
+
if (typeof input === "string") push(input);
|
|
1178
|
+
else {
|
|
1179
|
+
push(input.message);
|
|
1180
|
+
push(input.code);
|
|
1181
|
+
if (input.error) {
|
|
1182
|
+
push(input.error.message);
|
|
1183
|
+
push(input.error.code);
|
|
1184
|
+
push(input.error.type);
|
|
1185
|
+
}
|
|
1186
|
+
if (input.body) {
|
|
1187
|
+
push(input.body.message);
|
|
1188
|
+
if (input.body.error) {
|
|
1189
|
+
push(input.body.error.message);
|
|
1190
|
+
push(input.body.error.code);
|
|
1191
|
+
push(input.body.error.type);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (typeof input.status === "number" && input.status === 401) return true;
|
|
1195
|
+
if (typeof input.status_code === "number" && input.status_code === 401) return true;
|
|
1196
|
+
}
|
|
1197
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1198
|
+
if (!hay) return false;
|
|
1199
|
+
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;
|
|
1200
|
+
}
|
|
1201
|
+
function isProviderApiKeyError(input) {
|
|
1202
|
+
var envErr = csrEnvelopeError(input);
|
|
1203
|
+
if (envErr !== void 0) input = envErr;
|
|
1204
|
+
if (!input) return false;
|
|
1205
|
+
var blobs = [];
|
|
1206
|
+
var push = function(v) {
|
|
1207
|
+
if (typeof v === "string" && v) blobs.push(v);
|
|
1208
|
+
};
|
|
1209
|
+
if (typeof input === "string") push(input);
|
|
1210
|
+
else {
|
|
1211
|
+
push(input.message);
|
|
1212
|
+
push(input.code);
|
|
1213
|
+
push(input.type);
|
|
1214
|
+
if (input.error) {
|
|
1215
|
+
push(input.error.message);
|
|
1216
|
+
push(input.error.code);
|
|
1217
|
+
push(input.error.type);
|
|
1218
|
+
}
|
|
1219
|
+
if (input.body) {
|
|
1220
|
+
push(input.body.message);
|
|
1221
|
+
push(input.body.type);
|
|
1222
|
+
if (input.body.error) {
|
|
1223
|
+
push(input.body.error.message);
|
|
1224
|
+
push(input.body.error.code);
|
|
1225
|
+
push(input.body.error.type);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
var hay = blobs.join(" | ").toLowerCase();
|
|
1230
|
+
if (!hay) return false;
|
|
1231
|
+
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;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1038
1234
|
// src/engine/links.ts
|
|
1039
1235
|
var EXPIRED_ATTACHMENT_URL_HOST = "_expired_.url";
|
|
1040
1236
|
var EXPIRED_ATTACHMENT_URL_ORIGIN = "https://" + EXPIRED_ATTACHMENT_URL_HOST;
|
|
@@ -1899,12 +2095,41 @@ var OLDEST_NANO_REASONING_EFFORT = "high";
|
|
|
1899
2095
|
var isOpenAINano = (model) => {
|
|
1900
2096
|
const normalized = (model).trim().toLowerCase();
|
|
1901
2097
|
if (!/(^|-)nano(-|$)/.test(normalized)) return false;
|
|
2098
|
+
return openAITakesReasoningEffort(normalized);
|
|
2099
|
+
};
|
|
2100
|
+
var openAITakesReasoningEffort = (model) => {
|
|
2101
|
+
const normalized = (model || DEFAULT_OPENAI_MODEL).trim().toLowerCase();
|
|
1902
2102
|
const match = normalized.match(/^gpt-(\d+)(?:\.(\d+))?(-[a-z0-9.\-]+)?$/);
|
|
1903
2103
|
if (!match) return false;
|
|
1904
2104
|
const major = Number(match[1]);
|
|
1905
2105
|
const minor = match[2] === void 0 ? null : Number(match[2]);
|
|
1906
2106
|
return major > 5 || major === 5 && minor !== null && minor >= 4;
|
|
1907
2107
|
};
|
|
2108
|
+
var claudeTakesEffort = (model) => {
|
|
2109
|
+
const normalized = (model || DEFAULT_CLAUDE_MODEL).trim().toLowerCase().replace(/\[1m\]$/, "");
|
|
2110
|
+
const match = normalized.match(/^claude-([a-z]+)(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:-\d{8})?$/);
|
|
2111
|
+
if (!match) return false;
|
|
2112
|
+
const family = match[1];
|
|
2113
|
+
if (family === "fable" || family === "mythos") return true;
|
|
2114
|
+
if (match[2] === void 0) return false;
|
|
2115
|
+
const major = Number(match[2]);
|
|
2116
|
+
const minor = match[3] === void 0 ? 0 : Number(match[3]);
|
|
2117
|
+
if (family === "opus") return major > 4 || major === 4 && minor >= 5;
|
|
2118
|
+
if (family === "sonnet") return major > 4 || major === 4 && minor >= 6;
|
|
2119
|
+
if (family === "haiku") return major > 5 || major === 5 && minor >= 5;
|
|
2120
|
+
return false;
|
|
2121
|
+
};
|
|
2122
|
+
var ANSWER_MODE_EFFORT = {
|
|
2123
|
+
standard: null,
|
|
2124
|
+
fast: "low",
|
|
2125
|
+
thorough: "high"
|
|
2126
|
+
};
|
|
2127
|
+
function chatEffortFields(platform, model, mode) {
|
|
2128
|
+
const effort = mode ? ANSWER_MODE_EFFORT[mode] : null;
|
|
2129
|
+
if (!effort) return {};
|
|
2130
|
+
if (platform === "openai") return openAITakesReasoningEffort(model) ? { reasoning: { effort } } : {};
|
|
2131
|
+
return claudeTakesEffort(model) ? { output_config: { effort } } : {};
|
|
2132
|
+
}
|
|
1908
2133
|
var variantIndexingOptions = (model) => {
|
|
1909
2134
|
if (!isOpenAINano(model) || !isOldestNano(model)) return {};
|
|
1910
2135
|
return {
|
|
@@ -2041,6 +2266,80 @@ function applyHistoryCacheBreakpoint(messages) {
|
|
|
2041
2266
|
var POLL_INTERVAL = 3e3;
|
|
2042
2267
|
var STREAM_POLL_INTERVAL = 1e3;
|
|
2043
2268
|
var MAX_CONCURRENT_BG_POLLS = 6;
|
|
2269
|
+
var mcpListToolsCache = /* @__PURE__ */ new Map();
|
|
2270
|
+
var mcpListToolsReuseOff = false;
|
|
2271
|
+
var MCP_LIST_TOOLS_OFF_PREFIX = "bunnyquery:mcp-list-tools-off:";
|
|
2272
|
+
function mcpListToolsOffStored(service) {
|
|
2273
|
+
try {
|
|
2274
|
+
return typeof localStorage !== "undefined" && !!localStorage.getItem(MCP_LIST_TOOLS_OFF_PREFIX + service);
|
|
2275
|
+
} catch (_) {
|
|
2276
|
+
return false;
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
function storeMcpListToolsOff(service) {
|
|
2280
|
+
if (!service) return;
|
|
2281
|
+
try {
|
|
2282
|
+
if (typeof localStorage !== "undefined") localStorage.setItem(MCP_LIST_TOOLS_OFF_PREFIX + service, String(Date.now()));
|
|
2283
|
+
} catch (_) {
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
var SERVER_PLACEHOLDERS = ["$CLIENT_SECRET", "$ACCESS_TOKEN", "$ID_TOKEN"];
|
|
2287
|
+
function failureText(failure) {
|
|
2288
|
+
const env = csrEnvelopeError(failure);
|
|
2289
|
+
const f = env !== void 0 ? env : failure;
|
|
2290
|
+
if (f == null) return "";
|
|
2291
|
+
if (typeof f === "string") return f.toLowerCase();
|
|
2292
|
+
let text = "";
|
|
2293
|
+
try {
|
|
2294
|
+
text = JSON.stringify(f) || "";
|
|
2295
|
+
} catch (_) {
|
|
2296
|
+
text = "";
|
|
2297
|
+
}
|
|
2298
|
+
if (typeof f.message === "string") text += " " + f.message;
|
|
2299
|
+
return text.toLowerCase();
|
|
2300
|
+
}
|
|
2301
|
+
function failureStatus(failure) {
|
|
2302
|
+
const env = csrEnvelopeError(failure);
|
|
2303
|
+
const f = env !== void 0 ? env : failure;
|
|
2304
|
+
if (!f || typeof f !== "object") return void 0;
|
|
2305
|
+
const v = typeof f.status_code === "number" ? f.status_code : typeof f.status === "number" ? f.status : void 0;
|
|
2306
|
+
return v;
|
|
2307
|
+
}
|
|
2308
|
+
function mcpListToolsKey(serverUrl, anonymous, service, publicProjectId, userId) {
|
|
2309
|
+
return JSON.stringify([serverUrl, anonymous ? "anonymous" : "signed-in", service, publicProjectId || "", userId || ""]);
|
|
2310
|
+
}
|
|
2311
|
+
function rememberMcpListTools(turn, body) {
|
|
2312
|
+
if (!turn || !turn.mcpToolsKey || mcpListToolsReuseOff) return;
|
|
2313
|
+
const output = body && Array.isArray(body.output) ? body.output : null;
|
|
2314
|
+
if (!output) return;
|
|
2315
|
+
for (let i = output.length - 1; i >= 0; i--) {
|
|
2316
|
+
const item = output[i];
|
|
2317
|
+
if (!item || item.type !== "mcp_list_tools" || item.server_label !== MCP_NAME) continue;
|
|
2318
|
+
if (item.error || typeof item.id !== "string" || !item.id || !Array.isArray(item.tools)) continue;
|
|
2319
|
+
let toolsText = "";
|
|
2320
|
+
try {
|
|
2321
|
+
toolsText = JSON.stringify(item.tools);
|
|
2322
|
+
} catch (_) {
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
if (SERVER_PLACEHOLDERS.some((ph) => toolsText.indexOf(ph) !== -1)) return;
|
|
2326
|
+
mcpListToolsCache.set(turn.mcpToolsKey, { type: "mcp_list_tools", id: item.id, server_label: item.server_label, tools: item.tools });
|
|
2327
|
+
return;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
function forgetMcpListToolsOnFailure(turn, failure) {
|
|
2331
|
+
if (!turn || !turn.mcpToolsInjected) return;
|
|
2332
|
+
if (turn.mcpToolsKey) mcpListToolsCache.delete(turn.mcpToolsKey);
|
|
2333
|
+
const text = failureText(failure);
|
|
2334
|
+
const status = failureStatus(failure);
|
|
2335
|
+
const namesItem = text.indexOf("mcp_list_tools") !== -1 || !!turn.mcpToolsItemId && text.indexOf(turn.mcpToolsItemId.toLowerCase()) !== -1;
|
|
2336
|
+
if (namesItem) {
|
|
2337
|
+
mcpListToolsReuseOff = true;
|
|
2338
|
+
storeMcpListToolsOff(turn.mcpToolsService);
|
|
2339
|
+
return;
|
|
2340
|
+
}
|
|
2341
|
+
if (status === 400 || status === 422 || text.indexOf("invalid_request_error") !== -1) mcpListToolsReuseOff = true;
|
|
2342
|
+
}
|
|
2044
2343
|
async function callClaudeWithMcp({
|
|
2045
2344
|
prompt,
|
|
2046
2345
|
messages,
|
|
@@ -2056,6 +2355,7 @@ async function callClaudeWithMcp({
|
|
|
2056
2355
|
webAccess
|
|
2057
2356
|
}) {
|
|
2058
2357
|
const web = await resolveWebAccess(service, typeof webAccess === "boolean" ? webAccess : void 0);
|
|
2358
|
+
const effortFields = chatEffortFields("claude", model, await resolveAnswerMode(service));
|
|
2059
2359
|
const mcpServerDefinition = {
|
|
2060
2360
|
type: "url",
|
|
2061
2361
|
name: mcpServer.name,
|
|
@@ -2083,6 +2383,8 @@ async function callClaudeWithMcp({
|
|
|
2083
2383
|
data: {
|
|
2084
2384
|
model,
|
|
2085
2385
|
max_tokens: maxTokens,
|
|
2386
|
+
// `output_config: {effort}` for a fast or thorough project, nothing otherwise.
|
|
2387
|
+
...effortFields,
|
|
2086
2388
|
// Top level beside model/messages/mcp_servers, which is where the
|
|
2087
2389
|
// Messages API takes it.
|
|
2088
2390
|
...stream.body,
|
|
@@ -2143,11 +2445,27 @@ async function callClaudeWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2143
2445
|
authorizationToken: endpoint.token
|
|
2144
2446
|
}});
|
|
2145
2447
|
}
|
|
2146
|
-
async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope) {
|
|
2448
|
+
async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system, model, userId, extractContent, fileUrls, onResponse, onError, mcpScope, turn) {
|
|
2147
2449
|
const endpoint = mcpEndpointFor(mcpScope?.anonymous, mcpScope?.publicProjectId, service);
|
|
2148
2450
|
const resolvedModel = model || DEFAULT_OPENAI_MODEL;
|
|
2149
2451
|
const imageDetail = getOpenAIImageDetail(resolvedModel);
|
|
2452
|
+
const serverUrl = mcpChatUrl(endpoint.url, "openai", resolvedModel);
|
|
2150
2453
|
const web = await resolveWebAccess(service);
|
|
2454
|
+
const effortFields = chatEffortFields("openai", resolvedModel, await resolveAnswerMode(service));
|
|
2455
|
+
let listedTools;
|
|
2456
|
+
if (turn) {
|
|
2457
|
+
turn.mcpToolsKey = void 0;
|
|
2458
|
+
turn.mcpToolsInjected = false;
|
|
2459
|
+
turn.mcpToolsService = void 0;
|
|
2460
|
+
turn.mcpToolsItemId = void 0;
|
|
2461
|
+
if (turn.reuseMcpToolList && !mcpListToolsReuseOff && !mcpListToolsOffStored(service)) {
|
|
2462
|
+
turn.mcpToolsKey = mcpListToolsKey(serverUrl, mcpScope?.anonymous, service, mcpScope?.publicProjectId, turn.userId);
|
|
2463
|
+
turn.mcpToolsService = service;
|
|
2464
|
+
listedTools = mcpListToolsCache.get(turn.mcpToolsKey);
|
|
2465
|
+
turn.mcpToolsInjected = !!listedTools;
|
|
2466
|
+
if (listedTools) turn.mcpToolsItemId = listedTools.id;
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2151
2469
|
const messageList = messages && messages.length ? prepareOpenAIMessages(messages, imageDetail) : [
|
|
2152
2470
|
{
|
|
2153
2471
|
role: "user",
|
|
@@ -2161,6 +2479,12 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2161
2479
|
content: system
|
|
2162
2480
|
}
|
|
2163
2481
|
] : [],
|
|
2482
|
+
// Right after the system message, exactly as OpenAI returned it, so OpenAI
|
|
2483
|
+
// skips asking the MCP server for its tools again. Absent unless stored.
|
|
2484
|
+
// This item passes through the server's $CLIENT_SECRET / $ACCESS_TOKEN /
|
|
2485
|
+
// $ID_TOKEN substitution; rememberMcpListTools never stores a listing that
|
|
2486
|
+
// contains one of those literals.
|
|
2487
|
+
...listedTools ? [{ type: listedTools.type, id: listedTools.id, server_label: listedTools.server_label, tools: listedTools.tools }] : [],
|
|
2164
2488
|
...messageList.map((m) => ({
|
|
2165
2489
|
role: m.role,
|
|
2166
2490
|
content: m.content
|
|
@@ -2183,6 +2507,8 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2183
2507
|
data: {
|
|
2184
2508
|
model: resolvedModel,
|
|
2185
2509
|
max_output_tokens: getMaxOutputTokens("openai", resolvedModel),
|
|
2510
|
+
// `reasoning: {effort}` for a fast or thorough project, nothing otherwise.
|
|
2511
|
+
...effortFields,
|
|
2186
2512
|
// Top level beside model/input/tools, which is where the Responses API
|
|
2187
2513
|
// takes it.
|
|
2188
2514
|
...stream.body,
|
|
@@ -2193,7 +2519,7 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
2193
2519
|
{
|
|
2194
2520
|
type: "mcp",
|
|
2195
2521
|
server_label: MCP_NAME,
|
|
2196
|
-
server_url:
|
|
2522
|
+
server_url: serverUrl,
|
|
2197
2523
|
require_approval: "never",
|
|
2198
2524
|
// No `headers` at all for an anonymous turn: `Bearer ` with an
|
|
2199
2525
|
// empty token is a credential the MCP server rejects, and the
|
|
@@ -3149,165 +3475,6 @@ function buildChatGreeting(params) {
|
|
|
3149
3475
|
return { lead, name, tail, text: lead + (name ? " " + name : "") + tail };
|
|
3150
3476
|
}
|
|
3151
3477
|
|
|
3152
|
-
// src/engine/errors.ts
|
|
3153
|
-
var STATUS_MESSAGE = {
|
|
3154
|
-
"408": "The AI provider timed out before it started.",
|
|
3155
|
-
"409": "The AI provider rejected the request as conflicting.",
|
|
3156
|
-
"413": "The request was too large for the AI provider.",
|
|
3157
|
-
"429": "The AI provider is rate limiting requests right now.",
|
|
3158
|
-
"500": "The AI provider hit an internal error.",
|
|
3159
|
-
"502": "The AI provider is temporarily unreachable.",
|
|
3160
|
-
"503": "The AI provider is temporarily unavailable.",
|
|
3161
|
-
"504": "The AI provider timed out."
|
|
3162
|
-
};
|
|
3163
|
-
function isTransientStatus(status) {
|
|
3164
|
-
return status === 408 || status === 425 || status === 429 || status >= 500;
|
|
3165
|
-
}
|
|
3166
|
-
function isCsrStatusEnvelope(res) {
|
|
3167
|
-
return !!res && typeof res === "object" && !Array.isArray(res) && typeof res.status === "string" && typeof res.id === "string" && "in_queue" in res;
|
|
3168
|
-
}
|
|
3169
|
-
function csrEnvelopeError(input) {
|
|
3170
|
-
if (!isCsrStatusEnvelope(input)) return void 0;
|
|
3171
|
-
if (input.status !== "failed") return void 0;
|
|
3172
|
-
return input.error != null ? input.error : { message: "The AI provider request failed." };
|
|
3173
|
-
}
|
|
3174
|
-
function getErrorMessage(input) {
|
|
3175
|
-
var envErr = csrEnvelopeError(input);
|
|
3176
|
-
if (envErr !== void 0) input = envErr;
|
|
3177
|
-
if (!input) return "Something went wrong.";
|
|
3178
|
-
if (typeof input === "string") return input;
|
|
3179
|
-
if (input.error && input.error.message) return input.error.message;
|
|
3180
|
-
if (input.body && input.body.error && input.body.error.message) return input.body.error.message;
|
|
3181
|
-
if (input.body && typeof input.body.message === "string") return input.body.message;
|
|
3182
|
-
if (input.message) return input.message;
|
|
3183
|
-
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : 0;
|
|
3184
|
-
if (status) {
|
|
3185
|
-
var text = STATUS_MESSAGE[String(status)] || (status >= 500 ? "The AI provider returned a server error." : "The AI provider rejected the request.");
|
|
3186
|
-
return text + " (error " + status + ")" + (isTransientStatus(status) ? " This is usually temporary, please try again." : "");
|
|
3187
|
-
}
|
|
3188
|
-
return "Something went wrong.";
|
|
3189
|
-
}
|
|
3190
|
-
function isRetriedFailure(input) {
|
|
3191
|
-
var envErr = csrEnvelopeError(input);
|
|
3192
|
-
if (envErr !== void 0) input = envErr;
|
|
3193
|
-
return !!input && typeof input === "object" && input.retried === true;
|
|
3194
|
-
}
|
|
3195
|
-
function isErrorResponseBody(response) {
|
|
3196
|
-
var envErr = csrEnvelopeError(response);
|
|
3197
|
-
if (envErr !== void 0) response = envErr;
|
|
3198
|
-
if (!response || typeof response !== "object") return envErr !== void 0;
|
|
3199
|
-
if (typeof response.status_code === "number" && response.status_code >= 400) return true;
|
|
3200
|
-
if (response.type === "error") return true;
|
|
3201
|
-
if (response.error && (response.error.message || response.error.type)) return true;
|
|
3202
|
-
var body = response.body;
|
|
3203
|
-
if (body && typeof body === "object") {
|
|
3204
|
-
if (body.type === "error") return true;
|
|
3205
|
-
if (body.error && (body.error.message || body.error.type)) return true;
|
|
3206
|
-
}
|
|
3207
|
-
if (typeof response.message === "string" && response.message.length) {
|
|
3208
|
-
var hasClaude = Array.isArray(response.content);
|
|
3209
|
-
var hasOpenAI = typeof response.output_text === "string" || Array.isArray(response.output) || Array.isArray(response.choices);
|
|
3210
|
-
if (!hasClaude && !hasOpenAI) return true;
|
|
3211
|
-
}
|
|
3212
|
-
return false;
|
|
3213
|
-
}
|
|
3214
|
-
function isNonRetryableRequestError(input) {
|
|
3215
|
-
var envErr = csrEnvelopeError(input);
|
|
3216
|
-
if (envErr !== void 0) input = envErr;
|
|
3217
|
-
if (!input || typeof input !== "object") return false;
|
|
3218
|
-
var status = typeof input.status_code === "number" ? input.status_code : typeof input.status === "number" ? input.status : void 0;
|
|
3219
|
-
var param = void 0;
|
|
3220
|
-
var blobs = [];
|
|
3221
|
-
var sources = [input.error, input.body && input.body.error, input.body, input];
|
|
3222
|
-
for (var i = 0; i < sources.length; i++) {
|
|
3223
|
-
var e = sources[i];
|
|
3224
|
-
if (!e) continue;
|
|
3225
|
-
if (typeof e === "string") {
|
|
3226
|
-
blobs.push(e);
|
|
3227
|
-
continue;
|
|
3228
|
-
}
|
|
3229
|
-
if (typeof e !== "object") continue;
|
|
3230
|
-
if (param === void 0 && e.param != null) param = e.param;
|
|
3231
|
-
if (typeof e.code === "string") blobs.push(e.code);
|
|
3232
|
-
if (typeof e.type === "string") blobs.push(e.type);
|
|
3233
|
-
if (typeof e.message === "string") blobs.push(e.message);
|
|
3234
|
-
}
|
|
3235
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3236
|
-
if (hay.indexOf("unknown_parameter") !== -1 || hay.indexOf("unknown parameter") !== -1 || hay.indexOf("unsupported_parameter") !== -1 || hay.indexOf("unsupported parameter") !== -1) {
|
|
3237
|
-
return true;
|
|
3238
|
-
}
|
|
3239
|
-
var isClientReqStatus = status === 400 || status === 422;
|
|
3240
|
-
if (isClientReqStatus && param != null && param !== "") return true;
|
|
3241
|
-
if (isClientReqStatus && hay.indexOf("invalid_request") !== -1 && (hay.indexOf("parameter") !== -1 || hay.indexOf("param") !== -1)) {
|
|
3242
|
-
return true;
|
|
3243
|
-
}
|
|
3244
|
-
return false;
|
|
3245
|
-
}
|
|
3246
|
-
function isAuthExpiredError(input) {
|
|
3247
|
-
var envErr = csrEnvelopeError(input);
|
|
3248
|
-
if (envErr !== void 0) input = envErr;
|
|
3249
|
-
if (!input) return false;
|
|
3250
|
-
var blobs = [];
|
|
3251
|
-
var push = function(v) {
|
|
3252
|
-
if (typeof v === "string" && v) blobs.push(v);
|
|
3253
|
-
};
|
|
3254
|
-
if (typeof input === "string") push(input);
|
|
3255
|
-
else {
|
|
3256
|
-
push(input.message);
|
|
3257
|
-
push(input.code);
|
|
3258
|
-
if (input.error) {
|
|
3259
|
-
push(input.error.message);
|
|
3260
|
-
push(input.error.code);
|
|
3261
|
-
push(input.error.type);
|
|
3262
|
-
}
|
|
3263
|
-
if (input.body) {
|
|
3264
|
-
push(input.body.message);
|
|
3265
|
-
if (input.body.error) {
|
|
3266
|
-
push(input.body.error.message);
|
|
3267
|
-
push(input.body.error.code);
|
|
3268
|
-
push(input.body.error.type);
|
|
3269
|
-
}
|
|
3270
|
-
}
|
|
3271
|
-
if (typeof input.status === "number" && input.status === 401) return true;
|
|
3272
|
-
if (typeof input.status_code === "number" && input.status_code === 401) return true;
|
|
3273
|
-
}
|
|
3274
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3275
|
-
if (!hay) return false;
|
|
3276
|
-
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;
|
|
3277
|
-
}
|
|
3278
|
-
function isProviderApiKeyError(input) {
|
|
3279
|
-
var envErr = csrEnvelopeError(input);
|
|
3280
|
-
if (envErr !== void 0) input = envErr;
|
|
3281
|
-
if (!input) return false;
|
|
3282
|
-
var blobs = [];
|
|
3283
|
-
var push = function(v) {
|
|
3284
|
-
if (typeof v === "string" && v) blobs.push(v);
|
|
3285
|
-
};
|
|
3286
|
-
if (typeof input === "string") push(input);
|
|
3287
|
-
else {
|
|
3288
|
-
push(input.message);
|
|
3289
|
-
push(input.code);
|
|
3290
|
-
push(input.type);
|
|
3291
|
-
if (input.error) {
|
|
3292
|
-
push(input.error.message);
|
|
3293
|
-
push(input.error.code);
|
|
3294
|
-
push(input.error.type);
|
|
3295
|
-
}
|
|
3296
|
-
if (input.body) {
|
|
3297
|
-
push(input.body.message);
|
|
3298
|
-
push(input.body.type);
|
|
3299
|
-
if (input.body.error) {
|
|
3300
|
-
push(input.body.error.message);
|
|
3301
|
-
push(input.body.error.code);
|
|
3302
|
-
push(input.body.error.type);
|
|
3303
|
-
}
|
|
3304
|
-
}
|
|
3305
|
-
}
|
|
3306
|
-
var hay = blobs.join(" | ").toLowerCase();
|
|
3307
|
-
if (!hay) return false;
|
|
3308
|
-
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;
|
|
3309
|
-
}
|
|
3310
|
-
|
|
3311
3478
|
// src/engine/citations.ts
|
|
3312
3479
|
var DATA_TOOL_NAMES = [
|
|
3313
3480
|
"getRecords",
|
|
@@ -7072,7 +7239,7 @@ var _ChatSession = class _ChatSession {
|
|
|
7072
7239
|
* one it was composed for. Falls back to the live read only when a caller
|
|
7073
7240
|
* omits them.
|
|
7074
7241
|
*/
|
|
7075
|
-
_callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner) {
|
|
7242
|
+
_callProviderFor(platform, prompt, messages, system, model, userId, extractContent, fileUrls, projectId, owner, turn) {
|
|
7076
7243
|
if (projectId === void 0 || owner === void 0) {
|
|
7077
7244
|
var id = this.host.getIdentity();
|
|
7078
7245
|
if (projectId === void 0) projectId = id.projectId;
|
|
@@ -7080,14 +7247,49 @@ var _ChatSession = class _ChatSession {
|
|
|
7080
7247
|
}
|
|
7081
7248
|
var liveId = this.host.getIdentity();
|
|
7082
7249
|
var mcpScope = { anonymous: liveId.anonymous, publicProjectId: liveId.publicProjectId };
|
|
7083
|
-
|
|
7250
|
+
if (turn) turn.userId = liveId.anonymous ? "" : liveId.userId || "";
|
|
7251
|
+
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);
|
|
7252
|
+
}
|
|
7253
|
+
/**
|
|
7254
|
+
* A fresh per-send record for the request builder (see requests.ts ChatTurnContext).
|
|
7255
|
+
* Chat turns only, and only OpenAI reuses a tool listing: Claude's MCP connector has no
|
|
7256
|
+
* equivalent item, and indexing passes never come through here. Off unless the host
|
|
7257
|
+
* set `reuseMcpToolList: true` in configureChatEngine.
|
|
7258
|
+
*/
|
|
7259
|
+
_newChatTurn(platform) {
|
|
7260
|
+
var on = false;
|
|
7261
|
+
try {
|
|
7262
|
+
on = chatEngineConfig().reuseMcpToolList === true;
|
|
7263
|
+
} catch (_) {
|
|
7264
|
+
on = false;
|
|
7265
|
+
}
|
|
7266
|
+
return { reuseMcpToolList: platform === "openai" && on };
|
|
7267
|
+
}
|
|
7268
|
+
/**
|
|
7269
|
+
* What a settled chat turn means for the stored MCP tool listing: a failure drops it
|
|
7270
|
+
* when the turn carried it (forgetMcpListToolsOnFailure decides whether reuse also
|
|
7271
|
+
* stops); a good OpenAI body refreshes it. A stopped poll or a cancelled row says
|
|
7272
|
+
* nothing either way. Applied once per turn: an exception thrown later by a UI
|
|
7273
|
+
* handler on the same chain is not a provider failure.
|
|
7274
|
+
*/
|
|
7275
|
+
_settleChatTurnTools(turn, response, failed) {
|
|
7276
|
+
if (!turn || turn.settled) return;
|
|
7277
|
+
turn.settled = true;
|
|
7278
|
+
if (failed || isErrorResponseBody(response)) {
|
|
7279
|
+
forgetMcpListToolsOnFailure(turn, response);
|
|
7280
|
+
return;
|
|
7281
|
+
}
|
|
7282
|
+
if (isPollStopped(response) || this._isCancelledPollResult(response)) return;
|
|
7283
|
+
rememberMcpListTools(turn, response);
|
|
7084
7284
|
}
|
|
7085
7285
|
dispatchAgentRequest(params) {
|
|
7086
7286
|
var self = this;
|
|
7087
7287
|
var dispatchItemId;
|
|
7288
|
+
var turn;
|
|
7088
7289
|
var sendAndPoll = function() {
|
|
7290
|
+
turn = self._newChatTurn(params.aiPlatform);
|
|
7089
7291
|
return Promise.resolve(
|
|
7090
|
-
self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner)
|
|
7292
|
+
self._callProviderFor(params.aiPlatform, params.text, params.boundedMessages, params.systemPrompt, params.aiModel, params.userId, params.extractContent, params.fileUrls, params.projectId, params.owner, turn)
|
|
7091
7293
|
).then(function(initial) {
|
|
7092
7294
|
if (initial && initial.poll && (initial.status === "pending" || initial.status === "running")) {
|
|
7093
7295
|
if (initial.id) {
|
|
@@ -7116,12 +7318,14 @@ var _ChatSession = class _ChatSession {
|
|
|
7116
7318
|
}
|
|
7117
7319
|
return response;
|
|
7118
7320
|
}).then(function(response) {
|
|
7321
|
+
self._settleChatTurnTools(turn, response);
|
|
7119
7322
|
if (isPollStopped(response) || self._isCancelledPollResult(response)) return { content: "", isError: false, cancelled: true };
|
|
7120
7323
|
if (isErrorResponseBody(response)) return { content: getErrorMessage(response), isError: true };
|
|
7121
7324
|
var answer = params.aiPlatform === "openai" ? extractOpenAIText(response) : extractClaudeText(response);
|
|
7122
7325
|
answer = (answer || "").trim();
|
|
7123
7326
|
return { content: answer || "No text response received from AI provider.", isError: false, retrieval: extractRetrievalNote(response, answer), body: response };
|
|
7124
7327
|
}).catch(function(err) {
|
|
7328
|
+
self._settleChatTurnTools(turn, err, true);
|
|
7125
7329
|
return { content: getErrorMessage(err), isError: true };
|
|
7126
7330
|
}).then(function(result) {
|
|
7127
7331
|
delete self.pendingAgentRequests[params.key];
|
|
@@ -7526,7 +7730,8 @@ var _ChatSession = class _ChatSession {
|
|
|
7526
7730
|
this.scrollForDispatch(stageId);
|
|
7527
7731
|
var capturedComposed = composed, capturedPlatform = aiPlatform, capturedKey = key;
|
|
7528
7732
|
var capturedQueuedLid = queuedBubble._localId;
|
|
7529
|
-
|
|
7733
|
+
var queuedTurn = this._newChatTurn(aiPlatform);
|
|
7734
|
+
Promise.resolve(this._callProviderFor(aiPlatform, composed, boundedQ.messages, systemPrompt, aiModel, chatQueue, extractContent, fileUrls, id.projectId, id.owner, queuedTurn)).then(function(result) {
|
|
7530
7735
|
var sendingIdx = self.getHistoryCacheKey() !== capturedKey ? -1 : self.state.messages.findIndex(function(m) {
|
|
7531
7736
|
return m.isSendingToServer && (m.isPendingQueued || m.isPendingInProcess) && m.role === "user" && !m._stageId && (m._ownerKey === void 0 || m._ownerKey === capturedKey);
|
|
7532
7737
|
});
|
|
@@ -7547,14 +7752,18 @@ var _ChatSession = class _ChatSession {
|
|
|
7547
7752
|
});
|
|
7548
7753
|
if (serverId) self._trackPoll(serverId, "fg", qp);
|
|
7549
7754
|
return qp.then(function(res) {
|
|
7755
|
+
self._settleChatTurnTools(queuedTurn, res);
|
|
7550
7756
|
if (isPollStopped(res)) return;
|
|
7551
7757
|
return self.onQueuedSendResponse(capturedComposed, res, capturedPlatform, serverId, capturedKey);
|
|
7552
7758
|
}).catch(function(err) {
|
|
7759
|
+
self._settleChatTurnTools(queuedTurn, err, true);
|
|
7553
7760
|
return self.onQueuedSendError(capturedComposed, err, serverId, capturedKey);
|
|
7554
7761
|
});
|
|
7555
7762
|
}
|
|
7763
|
+
self._settleChatTurnTools(queuedTurn, result);
|
|
7556
7764
|
return self.onQueuedSendResponse(capturedComposed, result, capturedPlatform, serverId, capturedKey);
|
|
7557
7765
|
}).catch(function(err) {
|
|
7766
|
+
self._settleChatTurnTools(queuedTurn, err, true);
|
|
7558
7767
|
return self.onQueuedSendError(capturedComposed, err, void 0, capturedKey);
|
|
7559
7768
|
});
|
|
7560
7769
|
return;
|
|
@@ -7575,8 +7784,9 @@ var _ChatSession = class _ChatSession {
|
|
|
7575
7784
|
this.updateHistoryCache();
|
|
7576
7785
|
this.state.sending = true;
|
|
7577
7786
|
this.scrollForDispatch(stageId);
|
|
7787
|
+
var immediateUserLid = immediateUser._localId;
|
|
7578
7788
|
var historyForLlm = this.state.messages.filter(function(m) {
|
|
7579
|
-
if (m === immediateUser) return false;
|
|
7789
|
+
if (m === immediateUser || immediateUserLid && m && m._localId === immediateUserLid) return false;
|
|
7580
7790
|
return !m.isPending && !m.isPendingQueued && !m.isPendingInProcess && !m.isPendingOlder && !m.isCancelled && !m.isBackgroundTask && !m.isError;
|
|
7581
7791
|
});
|
|
7582
7792
|
historyForLlm.push({ role: "user", content: llmComposed });
|
|
@@ -7587,7 +7797,7 @@ var _ChatSession = class _ChatSession {
|
|
|
7587
7797
|
projectId: id.projectId,
|
|
7588
7798
|
history: historyForLlm
|
|
7589
7799
|
});
|
|
7590
|
-
var
|
|
7800
|
+
var immediatePlaceholderLid = immediatePlaceholder._localId;
|
|
7591
7801
|
var run = this.dispatchAgentRequest({
|
|
7592
7802
|
key,
|
|
7593
7803
|
projectId: id.projectId,
|
|
@@ -10560,6 +10770,6 @@ var _ChatSession = class _ChatSession {
|
|
|
10560
10770
|
_ChatSession.RUN_PASS_PAGE = 10;
|
|
10561
10771
|
var ChatSession = _ChatSession;
|
|
10562
10772
|
|
|
10563
|
-
export { BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, FINDINGS_TABLE, FINDING_ID_PREFIX, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, keyWords as findingKeyWords, findingsForTurn, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
|
|
10773
|
+
export { ANSWER_MODES, ANSWER_MODE_HINTS, ANSWER_MODE_LABELS, ANSWER_MODE_OPTIONS, ANSWER_MODE_SETTING_LABEL, BG_INDEXING_QUEUE_SUFFIX, BOM, BOM_EXTS, CHAT_GREETING_MAX_LENGTH, CLAUDE_INPUT_CAP_RATIO, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DATA_TOOL_NAMES, DEFAULT_ANSWER_MODE, DEFAULT_CLAUDE_MODEL, DEFAULT_CONTEXT_WINDOW, DEFAULT_OPENAI_MODEL, DEFAULT_SKIP_DUPLICATE_FILES, DEFAULT_UPLOAD_ACCESS_GROUP, DEFAULT_WEB_ACCESS, DUPLICATE_LOOKUP_LIMIT, DUPLICATE_LOOKUP_MAX_CANDIDATES, DUPLICATE_LOOKUP_TIMEOUT_MS, EMPTY_INDEXING_REPLY, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, EXPIRED_LINK_REFRESH_EXPIRES_SECONDS, EXT_CONTENT_TYPES, FINDINGS_TABLE, FINDING_ID_PREFIX, HISTORY_BUDGET_RATIO, HISTORY_FILL_SLACK_PX, HISTORY_TOKEN_BUDGET, HTML_EXTS, HTML_HEAD_WINDOW, IMAGE_PREVIEWS_PER_MESSAGE, INDEXING_COMPLETE_MARKER, INDEXING_MAX_OUTPUT_TOKENS, INLINE_LINK_GLYPH, INLINE_LINK_UNAVAILABLE_GLYPH, INLINE_LINK_UNAVAILABLE_SUFFIX, INPUT_CAP_RATIO, LINK_LABEL_MAX_DISPLAY_CHARS, LINK_REFRESH_WINDOW_MS, MAX_CONCURRENT_BG_POLLS, MAX_HISTORY_FILL_PAGES, MAX_HISTORY_MESSAGES, MAX_OUTPUT_BY_MODEL, MAX_OUTPUT_TOKENS, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MINT_CACHE_GENERATION, MIN_INPUT_TOKEN_BUDGET, MIN_PER_REQUEST_INPUT_CAP, NO_DATA_TOOL_MARK, OUTPUT_TOKEN_RESERVE, PAGE_TEXT_TABLE, POLL_INTERVAL, PRESIGN_SAFETY_MARGIN_MS, PREVIEWABLE_IMAGE_CONTENT_TYPES, PREVIEW_BROWSER_CACHE_SECONDS, PREVIEW_LAYOUT_BOX_SELECTOR, PREVIEW_URL_EXPIRES_SECONDS, PROJECT_SETTINGS_ACCESS_GROUP, PROJECT_SETTINGS_TABLE, PROJECT_SETTINGS_UNIQUE_ID, RENDER_FROM_TOKEN, RETRIEVAL_NOTES_MAX, RETRIEVAL_NOTES_TOKEN_BUDGET, RETRIEVAL_NOTE_MAX_CHARS, RETRIEVAL_NOTE_MAX_ITEMS, RETRIEVAL_NOTE_PREFIX, RTF_EXTS, RUN_RECORD_WORKING_STALE_MS, STREAM_POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, UPLOAD_ACCESS_GROUPS, UPLOAD_ACCESS_HINTS, UPLOAD_ACCESS_LABELS, UPLOAD_ACCESS_OPTIONS, XML_EXTS, __resetSplitHistoryState, accessSettingFrom, adoptLocalAnswerIntoPage, answerModeFrom, answerUsedNoDataTool, applyEncodingDeclaration, applyRetrievalNotes, asksUploadAccessFrom, bgIndexingQueueName, buildAiAgentValue, buildBoundedChatMessages, buildChatDisplayList, buildChatGreeting, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildHistoryItemFullId, buildIndexingContinueMessage, buildIndexingRenderContinueTemplate, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, buildIndexingWindowMessage, cachedProjectSettings, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, canonicalizePathForm, chatCacheKey, chatEffortFields, chatEngineConfig, chatGreetingFrom, chatStreamWiring, citationFileName, citationLinkPart, citationsFor, classifyInlineLink, clearAttachmentParsers, clearImagePreviewCache, clearProjectSettings, composeUserMessage, configureChatEngine, configureProjectSettings, contentTypeForExt, createHistoryFiller, createInlineLinkRegex, createScrollAnchor, createSseParser, csrEnvelopeError, encodePathSegments, encodingClassForExt, ensureHtmlCharset, ensureXmlEncoding, escapeInlineHtml, escapeRtfNonAscii, estimateMessageTokens, estimateTextTokens, extOf, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, extractRetrievalNote, fetchLiveIndexingKeys, fillHistoryViewport, filterListByClearHorizon, findAttachmentParser, findDuplicateUpload, keyWords as findingKeyWords, findingsForTurn, formatChatTimestamp, formatDuration, formatRetrievalNote, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, getInputTokenBudget, getMaxOutputTokens, getModelContextWindow, getProjectContextWindow, getSplitChatHistory, getVisionProfile, groupAttachmentFailures, hasBom, hydrateImagePreviews, indexDoneUniqueId, indexScopeKey, indexingAccessGroup, isAuthExpiredError, isBgIndexingQueue, isCsrStatusEnvelope, isDataToolName, isDuplicateCandidateId, isErrorResponseBody, isHttpUrlLike, isImageVisionFile, isIndexingRequestText, isLinkUnavailable, isNonRetryableRequestError, isOfficeFile, isPagedReadFile, isPreviewableImagePath, isProviderApiKeyError, isRetriedFailure, isRetrievalNote, isServerExtractable, isServiceDbAttachmentHref, isWindowedReadFile, linkUnavailableKeyForHref, linkUnavailableKeyForPath, linkUnavailableKeysForPath, listClaudeModels, listOpenAIModels, liveSafePrefix, loadProjectSettings, looksLikeRtf, makeExtractPlaceholder, mapHistoryListToMessages, markImagePreviewStale, mayKeepStreamedAnswer, mintCacheBustStamp, needsBomForExt, normalizeAnswerMode, normalizeAttachmentPathCandidate, normalizeChatGreeting, normalizeExt, normalizeProjectAccessSetting, normalizeSkipDuplicateFiles, normalizeStoredPathTarget, normalizeTextContent, normalizeTrailingInlineToken, normalizeUploadAccessGroup, normalizeWebAccess, notifyAgentSaveAttachment, parseAiAgentValue, parseAttachmentContent, parseIndexingLabel, parseIndexingRequestText, patchProjectSettings, peekImagePreviewUrl, prepareDownloadText, presignExpiryEpochMs, previewImageContentType, previewLayoutBox, previewMintCacheToken, previewableExtOf, primeProjectSettings, projectAccessSetting, projectAnswerMode, projectAsksUploadAccess, projectChatGreeting, projectSettingsSettled, projectSkipDuplicateFiles, projectUploadAccessGroup, projectWebAccess, providerBodyWasRead, readExpiredAttachmentHref, readyProjectSettings, registerAttachmentParser, registerModelContextWindows, renderInlineLinkHtml, repairUrlEntities, repairUrlWhitespace, resetFileIndexOnServer, resolveAnswerMode, resolveImagePreviewUrl, resolveSkipDuplicateFiles, resolveWebAccess, retrievalNoteFromText, retrievalNoteOfAnswer, runIndexUniqueId, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, setProjectContextWindow, setProjectSettings, shouldRescueInFlightMessage, skapiSupportsStreaming, skipDuplicateFilesEnabled, skipDuplicateFilesFrom, streamRecoveryEnabled, streamRecoveryLabels, streamRecoveryPhase, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay, typewriterResumeIndex, uploadAccessGroupFrom, upsertIndexRunRecordSafe, wallClockNow, webAccessEnabled, webAccessFrom };
|
|
10564
10774
|
//# sourceMappingURL=engine.mjs.map
|
|
10565
10775
|
//# sourceMappingURL=engine.mjs.map
|