bunnyquery 1.5.7 → 1.6.0
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/bunnyquery.js +141 -7
- package/dist/engine.cjs +142 -6
- package/dist/engine.cjs.map +1 -1
- package/dist/engine.d.mts +33 -1
- package/dist/engine.d.ts +33 -1
- package/dist/engine.mjs +141 -7
- package/dist/engine.mjs.map +1 -1
- package/package.json +1 -1
- package/src/engine/office.ts +25 -0
- package/src/engine/prompts/index.ts +2 -0
- package/src/engine/prompts/indexing_system_prompt.ts +5 -3
- package/src/engine/prompts/indexing_user_message.ts +82 -0
- package/src/engine/requests.ts +75 -17
- package/src/engine/session.ts +65 -0
package/dist/engine.d.mts
CHANGED
|
@@ -241,6 +241,23 @@ type BuildIndexingUserMessageOptions = {
|
|
|
241
241
|
pagedRead?: boolean;
|
|
242
242
|
};
|
|
243
243
|
declare function buildIndexingUserMessage(attachment: IndexingAttachmentInfo, options?: BuildIndexingUserMessageOptions): string;
|
|
244
|
+
/**
|
|
245
|
+
* User message for a VISION file (PDF): its pages are delivered as RENDERED PAGE IMAGES that
|
|
246
|
+
* the proxy worker injects into THIS message at the `placeholder` token (tool-result images
|
|
247
|
+
* render on neither provider, so the pages must be image blocks in the message itself). Each
|
|
248
|
+
* pass shows one WINDOW of pages starting at `renderFrom` (0-based); the resume loop advances
|
|
249
|
+
* the window a pass at a time until the injected note says the last window was reached.
|
|
250
|
+
*
|
|
251
|
+
* renderFrom === 0 is the FIRST pass (leads with "A new file has just been uploaded." so the
|
|
252
|
+
* client builds the "Indexing: <name>" bubble); renderFrom > 0 is a RESUME pass (leads with
|
|
253
|
+
* "CONTINUE indexing" like the paged continue message, so it is not a duplicate primary bubble).
|
|
254
|
+
*/
|
|
255
|
+
declare function buildIndexingRenderMessage(attachment: IndexingAttachmentInfo, placeholder: string, renderFrom: number): string;
|
|
256
|
+
/**
|
|
257
|
+
* User message for a RESUME pass: a previous indexing pass could not finish this large
|
|
258
|
+
* file, so continue it from where the already-saved records leave off (never restart).
|
|
259
|
+
*/
|
|
260
|
+
declare function buildIndexingContinueMessage(attachment: IndexingAttachmentInfo): string;
|
|
244
261
|
|
|
245
262
|
/**
|
|
246
263
|
* Error detection + message extraction (pure). Moved verbatim from the
|
|
@@ -387,6 +404,18 @@ type AttachmentSaveInfo = {
|
|
|
387
404
|
* takes precedence over server-side office extraction / web_fetch.
|
|
388
405
|
*/
|
|
389
406
|
parsedContent?: string;
|
|
407
|
+
/**
|
|
408
|
+
* True for a RESUME pass: a previous indexing pass could not finish this (large)
|
|
409
|
+
* file, so continue it - always via readFileContent paging, with a "continue"
|
|
410
|
+
* message telling the agent to resume from where the saved records leave off.
|
|
411
|
+
*/
|
|
412
|
+
continueIndexing?: boolean;
|
|
413
|
+
/**
|
|
414
|
+
* For an image-vision file (PDF), the 0-based PAGE the render window should start at.
|
|
415
|
+
* The worker renders [renderFrom, renderFrom+RENDER_PAGES_PER_WINDOW) and injects them
|
|
416
|
+
* as image blocks; the resume loop advances this by a window each pass.
|
|
417
|
+
*/
|
|
418
|
+
renderFrom?: number;
|
|
390
419
|
};
|
|
391
420
|
declare function notifyAgentSaveAttachment(info: AttachmentSaveInfo): Promise<any>;
|
|
392
421
|
declare function extractClaudeText(response: any): any;
|
|
@@ -407,6 +436,8 @@ type BgTaskEntry = {
|
|
|
407
436
|
poll: ((opts: {
|
|
408
437
|
latency: number;
|
|
409
438
|
}) => Promise<any>) | undefined;
|
|
439
|
+
/** How many CONTINUE passes have already run for this file (resume-across-passes). */
|
|
440
|
+
resumePass?: number;
|
|
410
441
|
};
|
|
411
442
|
declare function getChatHistory(params: {
|
|
412
443
|
service?: string;
|
|
@@ -582,6 +613,7 @@ declare class ChatSession {
|
|
|
582
613
|
handleHistoryItemResolution(itemId: string, response: any, platform: string): void;
|
|
583
614
|
applyHistoryItemResolution(itemId: string, response: any, platform: string): void;
|
|
584
615
|
drainBgTaskQueue(): void;
|
|
616
|
+
maybeResumeIndexing(entry: BgTaskEntry, response: any, platform: string): void;
|
|
585
617
|
loadHistory(fetchMore?: boolean, token?: number): Promise<void>;
|
|
586
618
|
uploadSingleAttachment(att: any): Promise<Array<{
|
|
587
619
|
name: string;
|
|
@@ -597,4 +629,4 @@ declare class ChatSession {
|
|
|
597
629
|
bumpGate(): void;
|
|
598
630
|
}
|
|
599
631
|
|
|
600
|
-
export { type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, type BgTaskEntry, type BoundedChatOptions, type BuildIndexingUserMessageOptions, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatSystemPromptParams, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, type ExtractDirective, HISTORY_TOKEN_BUDGET, type IndexingAttachmentInfo, type IndexingSystemPromptParams, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, type MapHistoryOptions, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
|
632
|
+
export { type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, type BgTaskEntry, type BoundedChatOptions, type BuildIndexingUserMessageOptions, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatSystemPromptParams, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, type ExtractDirective, HISTORY_TOKEN_BUDGET, type IndexingAttachmentInfo, type IndexingSystemPromptParams, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, type MapHistoryOptions, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingContinueMessage, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
package/dist/engine.d.ts
CHANGED
|
@@ -241,6 +241,23 @@ type BuildIndexingUserMessageOptions = {
|
|
|
241
241
|
pagedRead?: boolean;
|
|
242
242
|
};
|
|
243
243
|
declare function buildIndexingUserMessage(attachment: IndexingAttachmentInfo, options?: BuildIndexingUserMessageOptions): string;
|
|
244
|
+
/**
|
|
245
|
+
* User message for a VISION file (PDF): its pages are delivered as RENDERED PAGE IMAGES that
|
|
246
|
+
* the proxy worker injects into THIS message at the `placeholder` token (tool-result images
|
|
247
|
+
* render on neither provider, so the pages must be image blocks in the message itself). Each
|
|
248
|
+
* pass shows one WINDOW of pages starting at `renderFrom` (0-based); the resume loop advances
|
|
249
|
+
* the window a pass at a time until the injected note says the last window was reached.
|
|
250
|
+
*
|
|
251
|
+
* renderFrom === 0 is the FIRST pass (leads with "A new file has just been uploaded." so the
|
|
252
|
+
* client builds the "Indexing: <name>" bubble); renderFrom > 0 is a RESUME pass (leads with
|
|
253
|
+
* "CONTINUE indexing" like the paged continue message, so it is not a duplicate primary bubble).
|
|
254
|
+
*/
|
|
255
|
+
declare function buildIndexingRenderMessage(attachment: IndexingAttachmentInfo, placeholder: string, renderFrom: number): string;
|
|
256
|
+
/**
|
|
257
|
+
* User message for a RESUME pass: a previous indexing pass could not finish this large
|
|
258
|
+
* file, so continue it from where the already-saved records leave off (never restart).
|
|
259
|
+
*/
|
|
260
|
+
declare function buildIndexingContinueMessage(attachment: IndexingAttachmentInfo): string;
|
|
244
261
|
|
|
245
262
|
/**
|
|
246
263
|
* Error detection + message extraction (pure). Moved verbatim from the
|
|
@@ -387,6 +404,18 @@ type AttachmentSaveInfo = {
|
|
|
387
404
|
* takes precedence over server-side office extraction / web_fetch.
|
|
388
405
|
*/
|
|
389
406
|
parsedContent?: string;
|
|
407
|
+
/**
|
|
408
|
+
* True for a RESUME pass: a previous indexing pass could not finish this (large)
|
|
409
|
+
* file, so continue it - always via readFileContent paging, with a "continue"
|
|
410
|
+
* message telling the agent to resume from where the saved records leave off.
|
|
411
|
+
*/
|
|
412
|
+
continueIndexing?: boolean;
|
|
413
|
+
/**
|
|
414
|
+
* For an image-vision file (PDF), the 0-based PAGE the render window should start at.
|
|
415
|
+
* The worker renders [renderFrom, renderFrom+RENDER_PAGES_PER_WINDOW) and injects them
|
|
416
|
+
* as image blocks; the resume loop advances this by a window each pass.
|
|
417
|
+
*/
|
|
418
|
+
renderFrom?: number;
|
|
390
419
|
};
|
|
391
420
|
declare function notifyAgentSaveAttachment(info: AttachmentSaveInfo): Promise<any>;
|
|
392
421
|
declare function extractClaudeText(response: any): any;
|
|
@@ -407,6 +436,8 @@ type BgTaskEntry = {
|
|
|
407
436
|
poll: ((opts: {
|
|
408
437
|
latency: number;
|
|
409
438
|
}) => Promise<any>) | undefined;
|
|
439
|
+
/** How many CONTINUE passes have already run for this file (resume-across-passes). */
|
|
440
|
+
resumePass?: number;
|
|
410
441
|
};
|
|
411
442
|
declare function getChatHistory(params: {
|
|
412
443
|
service?: string;
|
|
@@ -582,6 +613,7 @@ declare class ChatSession {
|
|
|
582
613
|
handleHistoryItemResolution(itemId: string, response: any, platform: string): void;
|
|
583
614
|
applyHistoryItemResolution(itemId: string, response: any, platform: string): void;
|
|
584
615
|
drainBgTaskQueue(): void;
|
|
616
|
+
maybeResumeIndexing(entry: BgTaskEntry, response: any, platform: string): void;
|
|
585
617
|
loadHistory(fetchMore?: boolean, token?: number): Promise<void>;
|
|
586
618
|
uploadSingleAttachment(att: any): Promise<Array<{
|
|
587
619
|
name: string;
|
|
@@ -597,4 +629,4 @@ declare class ChatSession {
|
|
|
597
629
|
bumpGate(): void;
|
|
598
630
|
}
|
|
599
631
|
|
|
600
|
-
export { type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, type BgTaskEntry, type BoundedChatOptions, type BuildIndexingUserMessageOptions, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatSystemPromptParams, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, type ExtractDirective, HISTORY_TOKEN_BUDGET, type IndexingAttachmentInfo, type IndexingSystemPromptParams, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, type MapHistoryOptions, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
|
632
|
+
export { type AttachmentFailureGroup, type AttachmentParser, type AttachmentSaveInfo, BG_INDEXING_QUEUE_SUFFIX, type BgTaskEntry, type BoundedChatOptions, type BuildIndexingUserMessageOptions, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, type CallClaudeWithMcpParams, type ChatEngineConfig, type ChatHost, type ChatIdentity, type ChatMessage, ChatSession, type ChatState, type ChatSystemPromptParams, type ClaudeMcpServerRequest, type ClaudeMcpToolConfig, type ClaudeMessage, type ClaudeRole, type ComposedUserMessage, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, type ExtractDirective, HISTORY_TOKEN_BUDGET, type IndexingAttachmentInfo, type IndexingSystemPromptParams, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, type MapHistoryOptions, OUTPUT_TOKEN_RESERVE, type OpenAIMessage, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingContinueMessage, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
package/dist/engine.mjs
CHANGED
|
@@ -160,12 +160,23 @@ function isPagedReadFile(name, mime) {
|
|
|
160
160
|
const m = (mime || "").toLowerCase();
|
|
161
161
|
return m === "application/pdf" || m === "application/vnd.ms-excel" || m.includes("spreadsheetml") || m.includes("opendocument.spreadsheet");
|
|
162
162
|
}
|
|
163
|
+
function isImageVisionFile(name, mime) {
|
|
164
|
+
const ext = (name || "").split(".").pop()?.toLowerCase() || "";
|
|
165
|
+
return ext === "pdf" || (mime || "").toLowerCase() === "application/pdf";
|
|
166
|
+
}
|
|
163
167
|
var _extractPlaceholderSeq = 0;
|
|
164
168
|
function makeExtractPlaceholder(seed) {
|
|
165
169
|
_extractPlaceholderSeq += 1;
|
|
166
170
|
const slug = (seed || "file").replace(/[^a-zA-Z0-9]+/g, "_").slice(-48);
|
|
167
171
|
return `{{SKAPI_FILE_CONTENT::${slug}-${_extractPlaceholderSeq}}}`;
|
|
168
172
|
}
|
|
173
|
+
var _renderPlaceholderSeq = 0;
|
|
174
|
+
function makeRenderPlaceholder(seed) {
|
|
175
|
+
_renderPlaceholderSeq += 1;
|
|
176
|
+
const slug = (seed || "file").replace(/[^a-zA-Z0-9]+/g, "_").slice(-48);
|
|
177
|
+
return `{{SKAPI_RENDER::${slug}-${_renderPlaceholderSeq}}}`;
|
|
178
|
+
}
|
|
179
|
+
var RENDER_PAGES_PER_WINDOW = 5;
|
|
169
180
|
function composeUserMessage(text, attachmentUrls) {
|
|
170
181
|
let composed = text;
|
|
171
182
|
if (attachmentUrls.length > 0) {
|
|
@@ -263,12 +274,14 @@ function buildIndexingSystemPrompt(params) {
|
|
|
263
274
|
let systemPrompt = `You are a background indexing agent for project ${service}.
|
|
264
275
|
- 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.
|
|
265
276
|
- Most files (office documents like .docx/.xlsx/.pptx/.hwp/.hwpx/.ods, and text/data/code files like .csv/.tsv/.json/.xml/.txt/.md and source code) have ALREADY been extracted on the server and included inline in the user message between the "BEGIN FILE CONTENT" / "END FILE CONTENT" markers - read that directly. If the inline content is a "[skapi: ...]" note, the file could not be extracted - index it from its metadata only.
|
|
266
|
-
- BIG
|
|
267
|
-
-
|
|
277
|
+
- BIG SPREADSHEETS / TEXT: the inline content may be only the FIRST part of a large file (it can end with a truncation or "more remains" note). For big spreadsheets and big text/data files READ THE FILE WITH THE readFileContent TOOL: it returns the file ONE WINDOW at a time (spreadsheets as coordinate-tagged grid rows, text as a range of characters). Pass the file's storage path. After each window: datafy it into records and SAVE them, THEN if the window says MORE REMAINS call readFileContent again with the cursor it gives you. Repeat until it says END OF FILE, so the WHOLE file is indexed - never stop after the first window. (Do NOT call readFileContent on a PDF - see the next line.)
|
|
278
|
+
- PDFs (scanned or not): you do NOT read a PDF with a tool or a URL. Its pages are RENDERED and embedded directly in the user message as IMAGE blocks, a WINDOW of pages at a time. LOOK at the embedded page images and datafy every one. The note beside them tells you whether MORE pages remain: if so, save this window's records and stop (a follow-up pass shows the next window automatically); only when the note says it was the LAST window is the PDF fully seen. Do NOT call readFileContent or web_fetch for a PDF.
|
|
279
|
+
- VISION: when the message (a readFileContent window, an embedded PDF page, or an inline attachment) includes IMAGES - scanned/rendered PDF pages, or photos embedded in a spreadsheet next to a row/block - LOOK at them and capture what they show as record data (the reading/values in a scanned table, the part/defect/condition visible in a photo). The image IS part of the data; correlate each photo with its labelled block ("PHOTO A3" markers tie a photo to that grid row).
|
|
268
280
|
- Whatever the file type, use the file's storage path (the "storage path" metadata line) as the "src::" unique_id - never the inline content or a temporary URL.
|
|
269
281
|
- TABULAR data (any spreadsheet - .csv/.tsv/.xlsx/.xls/.ods, or sheet-like rows): you MUST save EVERY data row as its own record (ONE record per row) with that row's actual column values in the record's "data", keyed by the header names, in a dedicated table (e.g. "spreadsheet_rows"). Do NOT summarize, sample only a few rows, or save just file metadata - index the whole sheet, paging through it with readFileContent when it is large. Make MULTIPLE postRecords calls in batches (e.g. 30-50 rows per call) rather than one oversized call. This per-row completeness OVERRIDES brevity. ALSO save one file-level summary record (file name, sheet name(s), column headers, total row count, overall summary) - this is the record that carries the file's "src::" unique_id - and link EVERY per-row record to it via reference (set each row record's reference to that src:: file record; the row records themselves do NOT carry a src:: unique_id). The per-row records AND this reference linkage are BOTH mandatory: the linkage is what lets the whole sheet be found and cleaned up together when the file is re-indexed.
|
|
270
282
|
- EPUB / e-books / long-form books (.epub or any book-length prose, provided inline in reading order with chapter headings preserved): you MUST save ONE record per CHAPTER (or, when chapters are unclear, per major section/topic) in a dedicated table (e.g. "book_chapters") - never collapse the whole book into a single record. Each chapter record's "data" must capture the chapter title plus its order/number AND a substantive summary of that chapter's content (key events, arguments, characters, places, concepts, terms, notable quotes). Apply AS MANY relevant tags as possible to EVERY chapter record (characters, locations, themes, topics, key concepts, key terms, dates, named entities) so the book is easy to SEARCH and cross-reference later - this is the whole point. ALSO save one book-level record (title, author, language, overall summary, chapter list / table of contents, genre/subjects) and link each chapter record to it via reference. This per-chapter completeness OVERRIDES brevity; human-readable summaries only, never raw/binary bytes.
|
|
271
|
-
- This is a background indexing task: do ALL the MCP saving FIRST, never reply mid-task, and never ask the user questions. Always use the MCP tools to save what you learn - be exhaustive about meaning (and, for tabular data, about every row). SAVE AS YOU GO: persist each window's records before reading the next, so progress is never lost. If the file is so large you cannot finish in one turn, still save everything you have read so far
|
|
283
|
+
- This is a background indexing task: do ALL the MCP saving FIRST, never reply mid-task, and never ask the user questions. Always use the MCP tools to save what you learn - be exhaustive about meaning (and, for tabular data, about every row). SAVE AS YOU GO: persist each window's records before reading the next, so progress is never lost. If the file is so large you cannot finish in one turn, still save everything you have read so far; a follow-up pass will automatically continue from where you stopped. Never store raw or binary bytes (base64, blobs); describe them in human-readable text instead.
|
|
284
|
+
- COMPLETION SIGNAL: only when you have fully read and saved the ENTIRE file (for readFileContent files: reached "END OF FILE"; for PDFs: the embedded page-image note said it was the LAST window - with all rows/pages/items saved), end your final message with the token INDEXING_COMPLETE on its own line. If you did NOT finish the whole file (more rows/pages remain), do NOT write that token - leaving it out is how the system knows to run another pass to continue.
|
|
272
285
|
- Only AFTER every save is done, send exactly ONE final message summarizing what you indexed - never just "Indexing complete", and never a raw/base64/binary value or a large pasted dump. Keep it to a few factual sentences or a short markdown bullet list covering: the file name, its content type, each table you wrote to with its record/row count and the key columns/fields or topics captured, and anything that could not be extracted. Follow this shape - Indexed <file name> (<content type>): saved <N> records to <table(s)> capturing <key columns/fields or topics>; could not extract: <gaps, or none>.`;
|
|
273
286
|
if (serviceDescription) {
|
|
274
287
|
systemPrompt += `
|
|
@@ -311,6 +324,48 @@ Read this file with the readFileContent tool, using the storage path above - do
|
|
|
311
324
|
}
|
|
312
325
|
return head + `- temporary URL (fetch this to read the file contents): ${attachment.url}`;
|
|
313
326
|
}
|
|
327
|
+
function buildIndexingRenderMessage(attachment, placeholder, renderFrom) {
|
|
328
|
+
const from = Math.max(0, renderFrom || 0);
|
|
329
|
+
const src = `src::${attachment.storagePath}`;
|
|
330
|
+
const meta = `File metadata:
|
|
331
|
+
- name: ${attachment.name}
|
|
332
|
+
- storage path: ${attachment.storagePath}
|
|
333
|
+
` + (attachment.mime ? `- mime type: ${attachment.mime}
|
|
334
|
+
` : "");
|
|
335
|
+
const datafy = `
|
|
336
|
+
${placeholder}
|
|
337
|
+
|
|
338
|
+
LOOK at each rendered page image in this message and DATAFY what it shows: for EVERY page call postRecords and save records - one record per row / table entry / line item visible on the page (or one record for the page if it is prose), capturing every value you can read (OCR the text, read tables cell by cell, describe any photos/diagrams). Use the storage path above for the "src::" unique_id.
|
|
339
|
+
|
|
340
|
+
The note next to the images tells you whether MORE pages remain after this window. If MORE remain: save this window's records and STOP - do NOT write INDEXING_COMPLETE; another pass shows the next window automatically. Only when the note says this is the LAST window (you have seen the whole file) AND everything is saved, end your message with the token INDEXING_COMPLETE.`;
|
|
341
|
+
if (from === 0) {
|
|
342
|
+
return `A new file has just been uploaded. Index it now.
|
|
343
|
+
|
|
344
|
+
` + meta + `
|
|
345
|
+
This is a PDF. Its pages are delivered to you as RENDERED PAGE IMAGES embedded directly in this message (you do NOT need any tool, URL, or web_fetch to see them). You are shown a WINDOW of pages at a time, starting at page ${from + 1}.
|
|
346
|
+
` + datafy;
|
|
347
|
+
}
|
|
348
|
+
return `CONTINUE indexing a PDF whose previous pass did not finish.
|
|
349
|
+
|
|
350
|
+
` + meta + `
|
|
351
|
+
Records for the earlier pages are ALREADY saved (they reference "${src}"). The NEXT window of rendered page images (starting at page ${from + 1}) is embedded in this message. Datafy each page as before and do NOT re-save pages that are already saved.
|
|
352
|
+
` + datafy;
|
|
353
|
+
}
|
|
354
|
+
function buildIndexingContinueMessage(attachment) {
|
|
355
|
+
const src = `src::${attachment.storagePath}`;
|
|
356
|
+
return `CONTINUE indexing a file whose previous pass did not finish.
|
|
357
|
+
|
|
358
|
+
File metadata:
|
|
359
|
+
- name: ${attachment.name}
|
|
360
|
+
- storage path: ${attachment.storagePath}
|
|
361
|
+
` + (attachment.mime ? `- mime type: ${attachment.mime}
|
|
362
|
+
` : "") + `
|
|
363
|
+
Records for the earlier windows/pages of this file are ALREADY saved (they reference "${src}"). First call getRecords with reference "${src}" to see how far the previous pass got (the furthest page/row/window already saved). Then call readFileContent with the storage path above and a CURSOR that RESUMES just after that point - do NOT start at the beginning. The cursor is derivable from what you already saved:
|
|
364
|
+
- PDF: the cursor is the NUMBER OF PAGES already read (0-based next page). If you saved up to page N, call readFileContent with cursor="N" to get page N+1 onward.
|
|
365
|
+
- Spreadsheet: the cursor is "<sheetIndex>:<nextRow>" (0-based sheet index, 1-based row). If you saved up to row R of sheet S, use cursor="S:R+1".
|
|
366
|
+
- Text: the cursor is the character offset already read.
|
|
367
|
+
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. Do NOT re-save windows that are already saved. Use the storage path above for the "src::" unique_id. When the ENTIRE file is finally indexed, end your message with the token INDEXING_COMPLETE.`;
|
|
368
|
+
}
|
|
314
369
|
|
|
315
370
|
// src/engine/errors.ts
|
|
316
371
|
function getErrorMessage(input) {
|
|
@@ -815,14 +870,26 @@ async function callOpenAIWithPublicMcp(prompt, service, owner, messages, system,
|
|
|
815
870
|
}
|
|
816
871
|
});
|
|
817
872
|
}
|
|
873
|
+
async function notifyAgentContinueIndexing(info) {
|
|
874
|
+
return notifyAgentSaveAttachment({ ...info, continueIndexing: true });
|
|
875
|
+
}
|
|
818
876
|
async function notifyAgentSaveAttachment(info) {
|
|
819
877
|
const { platform, service, owner, attachment, parsedContent } = info;
|
|
820
|
-
const
|
|
821
|
-
const
|
|
878
|
+
const continuing = !!info.continueIndexing;
|
|
879
|
+
const visionFile = !parsedContent && isImageVisionFile(attachment.name, attachment.mime);
|
|
880
|
+
const renderFrom = Math.max(0, info.renderFrom || 0);
|
|
881
|
+
const renderPlaceholder = visionFile ? makeRenderPlaceholder(attachment.storagePath) : void 0;
|
|
882
|
+
const skapiRender = visionFile && renderPlaceholder ? {
|
|
883
|
+
_skapi_render: [
|
|
884
|
+
{ path: attachment.storagePath, from: renderFrom, count: RENDER_PAGES_PER_WINDOW, placeholder: renderPlaceholder, name: attachment.name, mime: attachment.mime }
|
|
885
|
+
]
|
|
886
|
+
} : {};
|
|
887
|
+
const pagedRead = !visionFile && (continuing || !parsedContent && isPagedReadFile(attachment.name, attachment.mime));
|
|
888
|
+
const serverExtract = !visionFile && !continuing && !parsedContent && !pagedRead && isServerExtractable(attachment.name, attachment.mime);
|
|
822
889
|
const placeholder = serverExtract ? makeExtractPlaceholder(attachment.storagePath) : void 0;
|
|
823
890
|
const extractContent = serverExtract && placeholder ? [{ path: attachment.storagePath, placeholder, name: attachment.name, mime: attachment.mime }] : void 0;
|
|
824
891
|
const skapiExtract = extractContent && extractContent.length ? { _skapi_extract: extractContent } : {};
|
|
825
|
-
const userMessage = buildIndexingUserMessage(
|
|
892
|
+
const userMessage = visionFile && renderPlaceholder ? buildIndexingRenderMessage(attachment, renderPlaceholder, renderFrom) : continuing ? buildIndexingContinueMessage(attachment) : buildIndexingUserMessage(
|
|
826
893
|
attachment,
|
|
827
894
|
parsedContent ? { inlineContent: parsedContent } : placeholder ? { inlineContentPlaceholder: placeholder } : pagedRead ? { pagedRead: true } : void 0
|
|
828
895
|
);
|
|
@@ -850,6 +917,7 @@ async function notifyAgentSaveAttachment(info) {
|
|
|
850
917
|
model: resolvedModel2,
|
|
851
918
|
max_output_tokens: MAX_TOKENS,
|
|
852
919
|
...skapiExtract,
|
|
920
|
+
...skapiRender,
|
|
853
921
|
input: [
|
|
854
922
|
{ role: "system", content: systemPrompt },
|
|
855
923
|
{
|
|
@@ -894,6 +962,7 @@ async function notifyAgentSaveAttachment(info) {
|
|
|
894
962
|
model: resolvedModel,
|
|
895
963
|
max_tokens: MAX_TOKENS,
|
|
896
964
|
...skapiExtract,
|
|
965
|
+
...skapiRender,
|
|
897
966
|
system: [
|
|
898
967
|
{
|
|
899
968
|
type: "text",
|
|
@@ -990,6 +1059,9 @@ async function listOpenAIModels(service, owner) {
|
|
|
990
1059
|
});
|
|
991
1060
|
}
|
|
992
1061
|
var BG_INDEXING_QUEUE_SUFFIX = "-bg";
|
|
1062
|
+
var INDEXING_COMPLETE_MARKER = "INDEXING_COMPLETE";
|
|
1063
|
+
var MAX_INDEXING_RESUME_PASSES = 6;
|
|
1064
|
+
var MAX_VISION_RESUME_PASSES = 40;
|
|
993
1065
|
async function getChatHistory(params, fetchOptions) {
|
|
994
1066
|
const url = params.platform === "claude" ? ANTHROPIC_MESSAGES_API_URL : OPENAI_RESPONSES_API_URL;
|
|
995
1067
|
const p = Object.assign(
|
|
@@ -1798,6 +1870,7 @@ var ChatSession = class {
|
|
|
1798
1870
|
this.historyItemPolls.delete(itemId);
|
|
1799
1871
|
var isErr = isErrorResponseBody(response);
|
|
1800
1872
|
var answer = isErr ? getErrorMessage(response) : ((platform === "openai" ? extractOpenAIText(response) : extractClaudeText(response)) || "").trim();
|
|
1873
|
+
if (!isErr && answer) answer = answer.split(INDEXING_COMPLETE_MARKER).join("").trim();
|
|
1801
1874
|
var idx = this.state.messages.findIndex(function(m) {
|
|
1802
1875
|
return m.isPending && m._serverItemId === itemId;
|
|
1803
1876
|
});
|
|
@@ -1871,8 +1944,10 @@ var ChatSession = class {
|
|
|
1871
1944
|
if (!self.historyItemPolls.has(entry.id) && typeof entry.poll === "function") {
|
|
1872
1945
|
self.historyItemPolls.set(entry.id, true);
|
|
1873
1946
|
var capturedId = entry.id, capturedPlat = plat;
|
|
1947
|
+
var capturedEntry = entry;
|
|
1874
1948
|
entry.poll({ latency: POLL_INTERVAL }).then(function(response) {
|
|
1875
1949
|
self.handleHistoryItemResolution(capturedId, response, capturedPlat);
|
|
1950
|
+
self.maybeResumeIndexing(capturedEntry, response, capturedPlat);
|
|
1876
1951
|
}).catch(function(err) {
|
|
1877
1952
|
self.historyItemPolls.delete(capturedId);
|
|
1878
1953
|
var isNotExists = err && (err.code === "NOT_EXISTS" || err.body && err.body.code === "NOT_EXISTS");
|
|
@@ -1895,6 +1970,65 @@ var ChatSession = class {
|
|
|
1895
1970
|
});
|
|
1896
1971
|
this.promoteNextBgQueuedToRunning();
|
|
1897
1972
|
}
|
|
1973
|
+
// Resume-across-passes: if a background INDEXING task for a paged file (spreadsheet or
|
|
1974
|
+
// PDF) finished WITHOUT the completion marker, the agent ran out of room before reading
|
|
1975
|
+
// the whole file - dispatch a CONTINUE pass (up to a cap) that resumes from where the
|
|
1976
|
+
// already-saved records leave off. Additive + guarded so it never loops forever and
|
|
1977
|
+
// never breaks the resolution path.
|
|
1978
|
+
maybeResumeIndexing(entry, response, platform) {
|
|
1979
|
+
var self = this;
|
|
1980
|
+
try {
|
|
1981
|
+
if (!entry || !entry.storagePath) return;
|
|
1982
|
+
if (!isPagedReadFile(entry.filename, entry.mime)) return;
|
|
1983
|
+
if (isErrorResponseBody(response)) return;
|
|
1984
|
+
var answer = (platform === "openai" ? extractOpenAIText(response) : extractClaudeText(response)) || "";
|
|
1985
|
+
if (answer.indexOf(INDEXING_COMPLETE_MARKER) !== -1) return;
|
|
1986
|
+
var pass = (entry.resumePass || 0) + 1;
|
|
1987
|
+
var isVision = isImageVisionFile(entry.filename, entry.mime);
|
|
1988
|
+
var maxPasses = isVision ? MAX_VISION_RESUME_PASSES : MAX_INDEXING_RESUME_PASSES;
|
|
1989
|
+
if (pass > maxPasses) return;
|
|
1990
|
+
var id = this.host.getIdentity();
|
|
1991
|
+
if (!id || id.platform === "none" || id.serviceId !== entry.serviceId) return;
|
|
1992
|
+
var renderFrom = isVision ? pass * RENDER_PAGES_PER_WINDOW : void 0;
|
|
1993
|
+
notifyAgentContinueIndexing({
|
|
1994
|
+
platform: id.platform,
|
|
1995
|
+
model: id.model,
|
|
1996
|
+
service: id.serviceId,
|
|
1997
|
+
owner: id.owner,
|
|
1998
|
+
userId: id.userId || id.serviceId,
|
|
1999
|
+
serviceName: id.serviceName,
|
|
2000
|
+
serviceDescription: id.serviceDescription,
|
|
2001
|
+
renderFrom,
|
|
2002
|
+
attachment: {
|
|
2003
|
+
name: entry.filename,
|
|
2004
|
+
storagePath: entry.storagePath,
|
|
2005
|
+
mime: entry.mime,
|
|
2006
|
+
size: entry.size,
|
|
2007
|
+
url: ""
|
|
2008
|
+
}
|
|
2009
|
+
}).then(function(ack) {
|
|
2010
|
+
if (ack && typeof ack.id === "string") {
|
|
2011
|
+
self.bgTaskQueue.push({
|
|
2012
|
+
serviceId: id.serviceId,
|
|
2013
|
+
platform: id.platform,
|
|
2014
|
+
id: ack.id,
|
|
2015
|
+
filename: entry.filename,
|
|
2016
|
+
storagePath: entry.storagePath,
|
|
2017
|
+
isReindex: entry.isReindex,
|
|
2018
|
+
mime: entry.mime,
|
|
2019
|
+
size: entry.size,
|
|
2020
|
+
status: ack.status === "running" ? "running" : "pending",
|
|
2021
|
+
poll: ack.poll,
|
|
2022
|
+
resumePass: pass
|
|
2023
|
+
});
|
|
2024
|
+
self.drainBgTaskQueue();
|
|
2025
|
+
}
|
|
2026
|
+
}, function(e) {
|
|
2027
|
+
console.error("[chat-engine] resume-indexing dispatch failed", e);
|
|
2028
|
+
});
|
|
2029
|
+
} catch (e) {
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
1898
2032
|
// --- history fetch + pagination --------------------------------------
|
|
1899
2033
|
// Initial load (fetchMore=false) replaces the list (with in-flight rescue +
|
|
1900
2034
|
// cancelled-merge) and attaches polls to running/pending items; pagination
|
|
@@ -2256,6 +2390,6 @@ var ChatSession = class {
|
|
|
2256
2390
|
}
|
|
2257
2391
|
};
|
|
2258
2392
|
|
|
2259
|
-
export { BG_INDEXING_QUEUE_SUFFIX, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, HISTORY_TOKEN_BUDGET, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, OUTPUT_TOKEN_RESERVE, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
|
2393
|
+
export { BG_INDEXING_QUEUE_SUFFIX, CLAUDE_PER_REQUEST_INPUT_CAP, CONTEXT_WINDOW_BY_MODEL, CONTEXT_WINDOW_DEFAULT, ChatSession, DEFAULT_CLAUDE_MODEL, DEFAULT_OPENAI_MODEL, EXPIRED_ATTACHMENT_URL_HOST, EXPIRED_ATTACHMENT_URL_ORIGIN, HISTORY_TOKEN_BUDGET, LINK_LABEL_MAX_DISPLAY_CHARS, MAX_HISTORY_MESSAGES, MAX_PARSED_CONTENT_CHARS, MCP_NAME, MIN_INPUT_TOKEN_BUDGET, OUTPUT_TOKEN_RESERVE, POLL_INTERVAL, TOOL_AND_RESPONSE_BUFFER, buildBoundedChatMessages, buildChatSystemPrompt, buildDisplayExpiredAttachmentHref, buildIndexingContinueMessage, buildIndexingRenderMessage, buildIndexingSystemPrompt, buildIndexingUserMessage, callClaudeWithMcp, callClaudeWithPublicMcp, callOpenAIWithPublicMcp, chatEngineConfig, clearAttachmentParsers, composeUserMessage, configureChatEngine, createInlineLinkRegex, encodePathSegments, estimateMessageTokens, estimateTextTokens, extractClaudeText, extractLastUserTextFromRequest, extractOpenAIText, extractRemotePathFromAttachmentHref, filterListByClearHorizon, findAttachmentParser, getAttachmentParsers, getChatHistory, getContextWindow, getErrorMessage, getExpiredAttachmentVisiblePath, groupAttachmentFailures, isAuthExpiredError, isErrorResponseBody, isNonRetryableRequestError, isOfficeFile, isServerExtractable, isServiceDbAttachmentHref, listClaudeModels, listOpenAIModels, makeExtractPlaceholder, mapHistoryListToMessages, normalizeAttachmentPathCandidate, normalizeTextContent, notifyAgentSaveAttachment, parseAttachmentContent, registerAttachmentParser, safeDecodeURIComponent, sanitizeAttachmentLinksForHistory, stripFileBlocksFromHistory, transformContentWithImages, transformContentWithOpenAIImages, truncateLabelForDisplay };
|
|
2260
2394
|
//# sourceMappingURL=engine.mjs.map
|
|
2261
2395
|
//# sourceMappingURL=engine.mjs.map
|