@stackfactor/agent-utils 1.13.4 → 1.33.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/README.md +688 -23
- package/dist/cjs/agentProto.d.ts +13 -3
- package/dist/cjs/agentProto.d.ts.map +1 -1
- package/dist/cjs/agentProto.js +25 -4
- package/dist/cjs/backoff.d.ts +17 -0
- package/dist/cjs/backoff.d.ts.map +1 -0
- package/dist/cjs/backoff.js +26 -0
- package/dist/cjs/cancellation.d.ts +22 -0
- package/dist/cjs/cancellation.d.ts.map +1 -0
- package/dist/cjs/cancellation.js +36 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.d.ts.map +1 -0
- package/dist/cjs/cli.js +85 -0
- package/dist/cjs/client.d.ts +11 -0
- package/dist/cjs/client.d.ts.map +1 -1
- package/dist/cjs/client.js +27 -0
- package/dist/cjs/const.d.ts +23 -0
- package/dist/cjs/const.d.ts.map +1 -1
- package/dist/cjs/const.js +23 -0
- package/dist/cjs/daemon.d.ts +94 -0
- package/dist/cjs/daemon.d.ts.map +1 -0
- package/dist/cjs/daemon.js +507 -0
- package/dist/cjs/daemonConfig.d.ts +45 -0
- package/dist/cjs/daemonConfig.d.ts.map +1 -0
- package/dist/cjs/daemonConfig.js +148 -0
- package/dist/cjs/daemonEnv.d.ts +10 -0
- package/dist/cjs/daemonEnv.d.ts.map +1 -0
- package/dist/cjs/daemonEnv.js +12 -0
- package/dist/cjs/durable/clientTool.d.ts +39 -0
- package/dist/cjs/durable/clientTool.d.ts.map +1 -0
- package/dist/cjs/durable/clientTool.js +90 -0
- package/dist/cjs/durable/index.d.ts +9 -0
- package/dist/cjs/durable/index.d.ts.map +1 -0
- package/dist/cjs/durable/index.js +16 -0
- package/dist/cjs/durable/journal.d.ts +218 -0
- package/dist/cjs/durable/journal.d.ts.map +1 -0
- package/dist/cjs/durable/journal.js +392 -0
- package/dist/cjs/durable/pause.d.ts +84 -0
- package/dist/cjs/durable/pause.d.ts.map +1 -0
- package/dist/cjs/durable/pause.js +241 -0
- package/dist/cjs/durable/resume.d.ts +27 -0
- package/dist/cjs/durable/resume.d.ts.map +1 -0
- package/dist/cjs/durable/resume.js +80 -0
- package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
- package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/cjs/durable/snapshotSaver.js +81 -0
- package/dist/cjs/durable/step.d.ts +28 -0
- package/dist/cjs/durable/step.d.ts.map +1 -0
- package/dist/cjs/durable/step.js +43 -0
- package/dist/cjs/index.d.ts +30 -7
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +28 -1
- package/dist/cjs/infrastructure.d.ts +50 -0
- package/dist/cjs/infrastructure.d.ts.map +1 -0
- package/dist/cjs/infrastructure.js +163 -0
- package/dist/cjs/langChain.d.ts +15 -3
- package/dist/cjs/langChain.d.ts.map +1 -1
- package/dist/cjs/langChain.js +986 -180
- package/dist/cjs/learningActivityMedia.d.ts +196 -0
- package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
- package/dist/cjs/learningActivityMedia.js +861 -0
- package/dist/cjs/learningContentPlan.d.ts +117 -0
- package/dist/cjs/learningContentPlan.d.ts.map +1 -0
- package/dist/cjs/learningContentPlan.js +327 -0
- package/dist/cjs/learningContentThread.d.ts +213 -0
- package/dist/cjs/learningContentThread.d.ts.map +1 -0
- package/dist/cjs/learningContentThread.js +448 -0
- package/dist/cjs/logger.d.ts +1 -0
- package/dist/cjs/logger.d.ts.map +1 -1
- package/dist/cjs/logger.js +17 -3
- package/dist/cjs/modelRates.d.ts +40 -0
- package/dist/cjs/modelRates.d.ts.map +1 -0
- package/dist/cjs/modelRates.js +76 -0
- package/dist/cjs/referenceContext.d.ts +4 -145
- package/dist/cjs/referenceContext.d.ts.map +1 -1
- package/dist/cjs/referenceContext.js +16 -251
- package/dist/cjs/retry.d.ts +64 -0
- package/dist/cjs/retry.d.ts.map +1 -0
- package/dist/cjs/retry.js +138 -0
- package/dist/cjs/runtimeContext.d.ts +8 -1
- package/dist/cjs/runtimeContext.d.ts.map +1 -1
- package/dist/cjs/runtimeContext.js +3 -1
- package/dist/cjs/serve.d.ts +3 -2
- package/dist/cjs/serve.d.ts.map +1 -1
- package/dist/cjs/serve.js +32 -2
- package/dist/cjs/sourceStore.d.ts +378 -0
- package/dist/cjs/sourceStore.d.ts.map +1 -0
- package/dist/cjs/sourceStore.js +872 -0
- package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
- package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/cjs/stackfactorKnowledge.js +108 -44
- package/dist/cjs/tavily.d.ts +108 -4
- package/dist/cjs/tavily.d.ts.map +1 -1
- package/dist/cjs/tavily.js +242 -21
- package/dist/cjs/usage.d.ts.map +1 -1
- package/dist/cjs/usage.js +9 -15
- package/dist/cjs/version.d.ts +3 -0
- package/dist/cjs/version.d.ts.map +1 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
- package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/cjs/workflow/bookkeeping.js +75 -0
- package/dist/cjs/workflow/index.d.ts +13 -0
- package/dist/cjs/workflow/index.d.ts.map +1 -0
- package/dist/cjs/workflow/index.js +51 -0
- package/dist/cjs/workflow/limits.d.ts +52 -0
- package/dist/cjs/workflow/limits.d.ts.map +1 -0
- package/dist/cjs/workflow/limits.js +62 -0
- package/dist/cjs/workflow/platformTransport.d.ts +39 -0
- package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/platformTransport.js +115 -0
- package/dist/cjs/workflow/retrying.d.ts +44 -0
- package/dist/cjs/workflow/retrying.d.ts.map +1 -0
- package/dist/cjs/workflow/retrying.js +82 -0
- package/dist/cjs/workflow/run.d.ts +195 -0
- package/dist/cjs/workflow/run.d.ts.map +1 -0
- package/dist/cjs/workflow/run.js +858 -0
- package/dist/cjs/workflow/testing/index.d.ts +3 -0
- package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/index.js +6 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
- package/dist/cjs/workflow/transport.d.ts +219 -0
- package/dist/cjs/workflow/transport.d.ts.map +1 -0
- package/dist/cjs/workflow/transport.js +19 -0
- package/dist/esm/agentProto.d.ts +13 -3
- package/dist/esm/agentProto.d.ts.map +1 -1
- package/dist/esm/agentProto.js +23 -3
- package/dist/esm/backoff.d.ts +17 -0
- package/dist/esm/backoff.d.ts.map +1 -0
- package/dist/esm/backoff.js +22 -0
- package/dist/esm/cancellation.d.ts +22 -0
- package/dist/esm/cancellation.d.ts.map +1 -0
- package/dist/esm/cancellation.js +27 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.d.ts.map +1 -0
- package/dist/esm/cli.js +80 -0
- package/dist/esm/client.d.ts +11 -0
- package/dist/esm/client.d.ts.map +1 -1
- package/dist/esm/client.js +25 -1
- package/dist/esm/const.d.ts +23 -0
- package/dist/esm/const.d.ts.map +1 -1
- package/dist/esm/const.js +23 -0
- package/dist/esm/daemon.d.ts +94 -0
- package/dist/esm/daemon.d.ts.map +1 -0
- package/dist/esm/daemon.js +499 -0
- package/dist/esm/daemonConfig.d.ts +45 -0
- package/dist/esm/daemonConfig.d.ts.map +1 -0
- package/dist/esm/daemonConfig.js +142 -0
- package/dist/esm/daemonEnv.d.ts +10 -0
- package/dist/esm/daemonEnv.d.ts.map +1 -0
- package/dist/esm/daemonEnv.js +9 -0
- package/dist/esm/durable/clientTool.d.ts +39 -0
- package/dist/esm/durable/clientTool.d.ts.map +1 -0
- package/dist/esm/durable/clientTool.js +82 -0
- package/dist/esm/durable/index.d.ts +9 -0
- package/dist/esm/durable/index.d.ts.map +1 -0
- package/dist/esm/durable/index.js +8 -0
- package/dist/esm/durable/journal.d.ts +218 -0
- package/dist/esm/durable/journal.d.ts.map +1 -0
- package/dist/esm/durable/journal.js +374 -0
- package/dist/esm/durable/pause.d.ts +84 -0
- package/dist/esm/durable/pause.d.ts.map +1 -0
- package/dist/esm/durable/pause.js +226 -0
- package/dist/esm/durable/resume.d.ts +27 -0
- package/dist/esm/durable/resume.d.ts.map +1 -0
- package/dist/esm/durable/resume.js +72 -0
- package/dist/esm/durable/snapshotSaver.d.ts +38 -0
- package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/esm/durable/snapshotSaver.js +77 -0
- package/dist/esm/durable/step.d.ts +28 -0
- package/dist/esm/durable/step.d.ts.map +1 -0
- package/dist/esm/durable/step.js +36 -0
- package/dist/esm/index.d.ts +30 -7
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +20 -4
- package/dist/esm/infrastructure.d.ts +50 -0
- package/dist/esm/infrastructure.d.ts.map +1 -0
- package/dist/esm/infrastructure.js +156 -0
- package/dist/esm/langChain.d.ts +15 -3
- package/dist/esm/langChain.d.ts.map +1 -1
- package/dist/esm/langChain.js +984 -179
- package/dist/esm/learningActivityMedia.d.ts +196 -0
- package/dist/esm/learningActivityMedia.d.ts.map +1 -0
- package/dist/esm/learningActivityMedia.js +807 -0
- package/dist/esm/learningContentPlan.d.ts +117 -0
- package/dist/esm/learningContentPlan.d.ts.map +1 -0
- package/dist/esm/learningContentPlan.js +320 -0
- package/dist/esm/learningContentThread.d.ts +213 -0
- package/dist/esm/learningContentThread.d.ts.map +1 -0
- package/dist/esm/learningContentThread.js +403 -0
- package/dist/esm/logger.d.ts +1 -0
- package/dist/esm/logger.d.ts.map +1 -1
- package/dist/esm/logger.js +17 -3
- package/dist/esm/modelRates.d.ts +40 -0
- package/dist/esm/modelRates.d.ts.map +1 -0
- package/dist/esm/modelRates.js +68 -0
- package/dist/esm/referenceContext.d.ts +4 -145
- package/dist/esm/referenceContext.d.ts.map +1 -1
- package/dist/esm/referenceContext.js +16 -243
- package/dist/esm/retry.d.ts +64 -0
- package/dist/esm/retry.d.ts.map +1 -0
- package/dist/esm/retry.js +127 -0
- package/dist/esm/runtimeContext.d.ts +8 -1
- package/dist/esm/runtimeContext.d.ts.map +1 -1
- package/dist/esm/runtimeContext.js +3 -1
- package/dist/esm/serve.d.ts +3 -2
- package/dist/esm/serve.d.ts.map +1 -1
- package/dist/esm/serve.js +33 -3
- package/dist/esm/sourceStore.d.ts +378 -0
- package/dist/esm/sourceStore.d.ts.map +1 -0
- package/dist/esm/sourceStore.js +855 -0
- package/dist/esm/stackfactorKnowledge.d.ts +91 -7
- package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/esm/stackfactorKnowledge.js +101 -41
- package/dist/esm/tavily.d.ts +108 -4
- package/dist/esm/tavily.d.ts.map +1 -1
- package/dist/esm/tavily.js +237 -20
- package/dist/esm/usage.d.ts.map +1 -1
- package/dist/esm/usage.js +9 -15
- package/dist/esm/version.d.ts +3 -0
- package/dist/esm/version.d.ts.map +1 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/workflow/bookkeeping.d.ts +78 -0
- package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/esm/workflow/bookkeeping.js +67 -0
- package/dist/esm/workflow/index.d.ts +13 -0
- package/dist/esm/workflow/index.d.ts.map +1 -0
- package/dist/esm/workflow/index.js +10 -0
- package/dist/esm/workflow/limits.d.ts +52 -0
- package/dist/esm/workflow/limits.d.ts.map +1 -0
- package/dist/esm/workflow/limits.js +59 -0
- package/dist/esm/workflow/platformTransport.d.ts +39 -0
- package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
- package/dist/esm/workflow/platformTransport.js +110 -0
- package/dist/esm/workflow/retrying.d.ts +44 -0
- package/dist/esm/workflow/retrying.d.ts.map +1 -0
- package/dist/esm/workflow/retrying.js +73 -0
- package/dist/esm/workflow/run.d.ts +195 -0
- package/dist/esm/workflow/run.d.ts.map +1 -0
- package/dist/esm/workflow/run.js +850 -0
- package/dist/esm/workflow/testing/index.d.ts +3 -0
- package/dist/esm/workflow/testing/index.d.ts.map +1 -0
- package/dist/esm/workflow/testing/index.js +2 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
- package/dist/esm/workflow/transport.d.ts +219 -0
- package/dist/esm/workflow/transport.d.ts.map +1 -0
- package/dist/esm/workflow/transport.js +16 -0
- package/package.json +8 -7
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Source store — what a run's references point at, read a page at a time
|
|
3
|
+
//
|
|
4
|
+
// A run reads what its references point at and discovers nothing. Those
|
|
5
|
+
// sources have no upper size: one PDF is over a million characters, a
|
|
6
|
+
// knowledge base document tens of thousands of passages. So a run never holds
|
|
7
|
+
// "everything": before any model call it prepares a store of its sources —
|
|
8
|
+
// what each is, how much it holds, where its sections start — and their text
|
|
9
|
+
// is then read a page at a time, on demand.
|
|
10
|
+
//
|
|
11
|
+
// - a page source is a WEB or PUBLICATION reference with an http(s) url. It
|
|
12
|
+
// is read once, in full, by Tavily (`tavily.readUrls`): Tavily has no
|
|
13
|
+
// paged read. The text is held here, outside the model's context, and
|
|
14
|
+
// divided into pages at the best boundary each has.
|
|
15
|
+
// - a document source is a knowledge base document STACKFACTOR references
|
|
16
|
+
// cite. Only its outline is fetched up front; its pages are fetched from
|
|
17
|
+
// the platform when they are read, under the run's own token, so a run
|
|
18
|
+
// reads only what the person it acts for may open. The passages its
|
|
19
|
+
// references name are fetched too: a cited passage is always shown.
|
|
20
|
+
//
|
|
21
|
+
// A small set of sources goes into the prompt whole (`fitsLimit`,
|
|
22
|
+
// `sourcesForPrompt`). Otherwise the model is given the source tool
|
|
23
|
+
// (`sourceTools`): `list_sources`, `get_outline`, `read_pages`,
|
|
24
|
+
// `read_document`. The tool reads only this store, never the web or a search,
|
|
25
|
+
// and keeps a record of what was read. From that record come what a person is
|
|
26
|
+
// told afterwards (`sourceFindings`): a page that could not be read, a source
|
|
27
|
+
// that was supplied and never opened, a statement attributed to one.
|
|
28
|
+
//
|
|
29
|
+
// A cited knowledge base that cannot be read stops the run, as it always has
|
|
30
|
+
// (Candin, 2026-10-13): a `KnowledgeAccessError`. A page that cannot be read
|
|
31
|
+
// does not: it is a finding.
|
|
32
|
+
//
|
|
33
|
+
import { tool } from "langchain";
|
|
34
|
+
import { z } from "zod";
|
|
35
|
+
import logger from "./logger.js";
|
|
36
|
+
import { KnowledgeAccessError } from "./referenceContext.js";
|
|
37
|
+
import { statusOf } from "./retry.js";
|
|
38
|
+
import { STACKFACTOR_REFERENCE, sourcesFromReferences } from "./stackfactorKnowledge.js";
|
|
39
|
+
import { readUrls } from "./tavily.js";
|
|
40
|
+
/** Characters to a page of a web page; a document's page holds about as much (40 passages of ~500). */
|
|
41
|
+
export const DEFAULT_PAGE_CHARACTERS = 20_000;
|
|
42
|
+
/** Positions (passages, when there are no gaps) to a page of a knowledge base document. */
|
|
43
|
+
export const DEFAULT_PAGE_PASSAGES = 40;
|
|
44
|
+
/** How many characters a stage may read through the tool. */
|
|
45
|
+
export const DEFAULT_READING_LIMIT = 200_000;
|
|
46
|
+
/** A web page past this is not held: it is treated as unreadable, and said so. */
|
|
47
|
+
export const DEFAULT_MAX_PAGE_SOURCE_CHARACTERS = 5_000_000;
|
|
48
|
+
/** The most outline entries a source lists. */
|
|
49
|
+
const OUTLINE_MAX_ENTRIES = 500;
|
|
50
|
+
/** The most pages one `read_pages` call returns. */
|
|
51
|
+
const READ_MAX_PAGES = 10;
|
|
52
|
+
/** The platform's limit on documents per outline call (backend-core DOCUMENT_READ.OUTLINE_MAX_DOCUMENTS). */
|
|
53
|
+
const OUTLINE_MAX_DOCUMENTS = 50;
|
|
54
|
+
/** The platform's limit on passages per read (backend-core DOCUMENT_READ.PASSAGES_MAX). */
|
|
55
|
+
const PASSAGES_MAX = 200;
|
|
56
|
+
/** How many characters of a page open its entry in an outline that has no headings. */
|
|
57
|
+
const OPENING_CHARACTERS = 80;
|
|
58
|
+
/** Statuses that mean the person may not read the knowledge base, or it is gone. */
|
|
59
|
+
const NO_ACCESS = new Set([401, 403, 404]);
|
|
60
|
+
const text = (value) => (typeof value === "string" ? value.trim() : "");
|
|
61
|
+
const id = (value) => typeof value === "string" ? value.trim() : value != null && typeof value === "object" ? String(value) : "";
|
|
62
|
+
/** The longest a source's title is shown in a progress line. */
|
|
63
|
+
const PROGRESS_TITLE_CHARACTERS = 80;
|
|
64
|
+
/** A source's title as a progress line shows it: quoted, and cut when long. */
|
|
65
|
+
const shown = (title) => {
|
|
66
|
+
const clean = title.replace(/\s+/g, " ").trim();
|
|
67
|
+
return `"${clean.length > PROGRESS_TITLE_CHARACTERS ? `${clean.slice(0, PROGRESS_TITLE_CHARACTERS - 1).trimEnd()}…` : clean}"`;
|
|
68
|
+
};
|
|
69
|
+
/** The titles of several sources in one progress line: the first two, then how many more. */
|
|
70
|
+
const shownTogether = (titles) => {
|
|
71
|
+
const [first, second, ...rest] = titles.map(shown);
|
|
72
|
+
if (!second)
|
|
73
|
+
return first;
|
|
74
|
+
if (rest.length === 0)
|
|
75
|
+
return `${first} and ${second}`;
|
|
76
|
+
return `${first}, ${second} and ${rest.length} more`;
|
|
77
|
+
};
|
|
78
|
+
/** The pages of one read as a progress line says them: "page 3", "pages 3 to 5", "pages 1, 4 and 7". */
|
|
79
|
+
const shownPages = (pages) => {
|
|
80
|
+
if (pages.length === 1)
|
|
81
|
+
return `page ${pages[0]}`;
|
|
82
|
+
const inARow = pages.every((page, index) => index === 0 || page === pages[index - 1] + 1);
|
|
83
|
+
if (inARow)
|
|
84
|
+
return `pages ${pages[0]} to ${pages[pages.length - 1]}`;
|
|
85
|
+
return `pages ${pages.slice(0, -1).join(", ")} and ${pages[pages.length - 1]}`;
|
|
86
|
+
};
|
|
87
|
+
/** Reports one line, whatever the caller's function does with it. */
|
|
88
|
+
const report = (onProgress, message, icon) => {
|
|
89
|
+
if (typeof onProgress !== "function")
|
|
90
|
+
return;
|
|
91
|
+
try {
|
|
92
|
+
onProgress({ icon, message });
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// A progress line never stops a read.
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
/** A new, empty record. */
|
|
99
|
+
export const newSourceRecord = () => ({ limitReached: [], reads: [] });
|
|
100
|
+
/** The kinds the platform retired; it reads them as PUBLICATION. */
|
|
101
|
+
const RETIRED_KINDS = new Set(["DOCUMENT", "KNOWLEDGE_BASE", "NOTE"]);
|
|
102
|
+
const kindOf = (reference) => {
|
|
103
|
+
const kind = reference?.kind;
|
|
104
|
+
return typeof kind !== "string" || kind === "" || RETIRED_KINDS.has(kind) ? "PUBLICATION" : kind;
|
|
105
|
+
};
|
|
106
|
+
/** Where a STACKFACTOR reference points, or null when it names no document. */
|
|
107
|
+
const pointerOf = (reference) => {
|
|
108
|
+
if (reference?.kind !== STACKFACTOR_REFERENCE.KIND)
|
|
109
|
+
return null;
|
|
110
|
+
const target = reference.target ?? {};
|
|
111
|
+
const isDocument = target.elementType === STACKFACTOR_REFERENCE.TARGET_ELEMENT_TYPE;
|
|
112
|
+
const knowledgeBaseId = id(reference.knowledgeBase?.knowledgeBaseId) || (isDocument ? id(target.parentId) : "");
|
|
113
|
+
const documentId = id(reference.knowledgeBase?.documentId) || (isDocument ? id(target.elementId) : "");
|
|
114
|
+
if (!knowledgeBaseId || !documentId)
|
|
115
|
+
return null;
|
|
116
|
+
return {
|
|
117
|
+
chunkId: id(reference.knowledgeBase?.chunkId),
|
|
118
|
+
documentId,
|
|
119
|
+
knowledgeBaseId,
|
|
120
|
+
section: text(reference.knowledgeBase?.sectionTitle),
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Text divided into pages of at most `size` characters, each cut at the best
|
|
125
|
+
* boundary it has: before a markdown heading, else at a paragraph break, else
|
|
126
|
+
* after a sentence, else at a space, else at the size itself. Nothing is
|
|
127
|
+
* dropped: the pages joined are the text. A source need have no structure at
|
|
128
|
+
* all — a PDF can come back as one unbroken block.
|
|
129
|
+
* @param content The text
|
|
130
|
+
* @param size The most characters a page holds
|
|
131
|
+
*/
|
|
132
|
+
export const splitIntoPages = (content, size = DEFAULT_PAGE_CHARACTERS) => {
|
|
133
|
+
const pages = [];
|
|
134
|
+
let rest = content;
|
|
135
|
+
// A boundary in the first half of a page would make pages of half the size.
|
|
136
|
+
const floor = Math.floor(size / 2);
|
|
137
|
+
const lastIndex = (window, pattern) => {
|
|
138
|
+
let found = -1;
|
|
139
|
+
for (const match of window.matchAll(pattern)) {
|
|
140
|
+
const at = (match.index ?? 0) + (match[1]?.length ?? 0);
|
|
141
|
+
if (at >= floor)
|
|
142
|
+
found = at;
|
|
143
|
+
}
|
|
144
|
+
return found;
|
|
145
|
+
};
|
|
146
|
+
while (rest.length > size) {
|
|
147
|
+
const window = rest.slice(0, size);
|
|
148
|
+
let cut = lastIndex(window, /(\n)(?=#{1,6}\s)/g);
|
|
149
|
+
if (cut < 0)
|
|
150
|
+
cut = lastIndex(window, /(\n\s*\n)/g);
|
|
151
|
+
if (cut < 0)
|
|
152
|
+
cut = lastIndex(window, /([.!?]["')\]]?\s)/g);
|
|
153
|
+
if (cut < 0)
|
|
154
|
+
cut = lastIndex(window, /(\s)/g);
|
|
155
|
+
if (cut < 0)
|
|
156
|
+
cut = size;
|
|
157
|
+
pages.push(rest.slice(0, cut));
|
|
158
|
+
rest = rest.slice(cut);
|
|
159
|
+
}
|
|
160
|
+
if (rest.length > 0)
|
|
161
|
+
pages.push(rest);
|
|
162
|
+
return pages;
|
|
163
|
+
};
|
|
164
|
+
/** The outline of pages of text: their markdown headings, else the opening words of each page. */
|
|
165
|
+
const outlineOfPages = (pages) => {
|
|
166
|
+
const headings = [];
|
|
167
|
+
pages.forEach((page, index) => {
|
|
168
|
+
for (const match of page.matchAll(/^#{1,6}\s+(.+?)\s*#*\s*$/gm)) {
|
|
169
|
+
const title = match[1].replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
|
|
170
|
+
if (title)
|
|
171
|
+
headings.push({ page: index + 1, title });
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
if (headings.length > 0) {
|
|
175
|
+
return {
|
|
176
|
+
outline: headings.slice(0, OUTLINE_MAX_ENTRIES),
|
|
177
|
+
outlineFromOpenings: false,
|
|
178
|
+
outlineTruncated: headings.length > OUTLINE_MAX_ENTRIES,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
const openings = pages.map((page, index) => ({
|
|
182
|
+
page: index + 1,
|
|
183
|
+
title: page.replace(/\s+/g, " ").trim().slice(0, OPENING_CHARACTERS),
|
|
184
|
+
}));
|
|
185
|
+
return {
|
|
186
|
+
outline: openings.slice(0, OUTLINE_MAX_ENTRIES),
|
|
187
|
+
outlineFromOpenings: true,
|
|
188
|
+
outlineTruncated: openings.length > OUTLINE_MAX_ENTRIES,
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
/** A document page as it is shown: its passages, each under its section when that changes. */
|
|
192
|
+
const renderPassages = (passages) => {
|
|
193
|
+
const parts = [];
|
|
194
|
+
let section;
|
|
195
|
+
for (const passage of passages) {
|
|
196
|
+
const body = text(passage.text);
|
|
197
|
+
if (!body)
|
|
198
|
+
continue;
|
|
199
|
+
const title = text(passage.sectionTitle) || null;
|
|
200
|
+
if (title !== section && title)
|
|
201
|
+
parts.push(`## ${title}`);
|
|
202
|
+
section = title;
|
|
203
|
+
parts.push(body);
|
|
204
|
+
}
|
|
205
|
+
return parts.join("\n\n");
|
|
206
|
+
};
|
|
207
|
+
/**
|
|
208
|
+
* Prepares a run's sources: reads its pages, and fetches the outlines and the
|
|
209
|
+
* cited passages of its knowledge base documents. Nothing else of a document
|
|
210
|
+
* is fetched until a page of it is read.
|
|
211
|
+
*
|
|
212
|
+
* Which sources there are, and when a page is read, is the caller's to say:
|
|
213
|
+
*
|
|
214
|
+
* - `pages: "upFront"` (the default) reads every page before answering: for
|
|
215
|
+
* a run that writes from all its references, once.
|
|
216
|
+
* - `pages: "onDemand"` lists each page by title and url and reads it the
|
|
217
|
+
* first time it is opened (`store.open`, which the tool calls): for a run
|
|
218
|
+
* made many times over the same references, or over more pages than it
|
|
219
|
+
* will read (a judge ruling on one comment, a reviewer of a skill citing
|
|
220
|
+
* dozens). Until a page is opened its size is not known, so such a store
|
|
221
|
+
* never `fitsLimit` and is read through the tool.
|
|
222
|
+
* - `pages: "none"` leaves the pages out: no source is made of a WEB or
|
|
223
|
+
* PUBLICATION reference.
|
|
224
|
+
* - `documents: false` leaves the knowledge base documents out: no source
|
|
225
|
+
* is made of a STACKFACTOR reference, no knowledge base is asked, and none
|
|
226
|
+
* can stop the run.
|
|
227
|
+
*
|
|
228
|
+
* A reference left out keeps its short id: ids are positions in `references`.
|
|
229
|
+
*
|
|
230
|
+
* A page that cannot be read is a source with an `unreadReason`; so is a
|
|
231
|
+
* document the person may not open, or that is gone (the platform does not
|
|
232
|
+
* tell the two apart). A cited knowledge base that cannot be read at all —
|
|
233
|
+
* no token, a refusal, a failed call — throws a KnowledgeAccessError naming
|
|
234
|
+
* the documents, before any page is read.
|
|
235
|
+
*
|
|
236
|
+
* @param options `references` (the run's, as supplied: their index is their
|
|
237
|
+
* short id), `token` (the run's AGENT token), `outlines` and `passages`
|
|
238
|
+
* (client-api `knowledgeBaseAgent.getDocumentOutlines` and
|
|
239
|
+
* `getDocumentPassages`), `config` (supplies `tavilyAPIKey`),
|
|
240
|
+
* `usageTracker`, `pages` and `documents` (which sources, and when a page
|
|
241
|
+
* is read: see above), the sizes: `pageCharacters`, `pagePassages`,
|
|
242
|
+
* `maxPageSourceCharacters`, and `onProgress`: told, by title, which
|
|
243
|
+
* documents are being opened and which pages are being read, before each
|
|
244
|
+
* of those waits (also when a page read on demand is first opened)
|
|
245
|
+
* @throws KnowledgeAccessError When cited knowledge bases cannot be read
|
|
246
|
+
*/
|
|
247
|
+
export const prepareSources = async (options) => {
|
|
248
|
+
const references = Array.isArray(options.references) ? options.references : [];
|
|
249
|
+
const pageCharacters = options.pageCharacters ?? DEFAULT_PAGE_CHARACTERS;
|
|
250
|
+
const pagePassages = Math.min(options.pagePassages ?? DEFAULT_PAGE_PASSAGES, PASSAGES_MAX);
|
|
251
|
+
const maxPageSource = options.maxPageSourceCharacters ?? DEFAULT_MAX_PAGE_SOURCE_CHARACTERS;
|
|
252
|
+
const pageMode = options.pages ?? "upFront";
|
|
253
|
+
const withDocuments = options.documents !== false;
|
|
254
|
+
// The sources in reference order: each url once, each document once.
|
|
255
|
+
const drafts = [];
|
|
256
|
+
const byKey = new Map();
|
|
257
|
+
references.forEach((reference, index) => {
|
|
258
|
+
if (!reference || typeof reference !== "object")
|
|
259
|
+
return;
|
|
260
|
+
const shortId = `r${index}`;
|
|
261
|
+
const pointer = pointerOf(reference);
|
|
262
|
+
const kind = kindOf(reference);
|
|
263
|
+
const url = text(reference.url);
|
|
264
|
+
// A kind of source the caller left out is no source at all.
|
|
265
|
+
if (pointer ? !withDocuments : pageMode === "none")
|
|
266
|
+
return;
|
|
267
|
+
const key = pointer
|
|
268
|
+
? `document|${pointer.knowledgeBaseId}|${pointer.documentId}`
|
|
269
|
+
: (kind === "WEB" || kind === "PUBLICATION") && /^https?:\/\//i.test(url)
|
|
270
|
+
? `page|${url}`
|
|
271
|
+
: "";
|
|
272
|
+
if (!key)
|
|
273
|
+
return;
|
|
274
|
+
const known = byKey.get(key);
|
|
275
|
+
if (known) {
|
|
276
|
+
known.references.push(shortId);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const draft = {
|
|
280
|
+
key,
|
|
281
|
+
kind: pointer ? "document" : "page",
|
|
282
|
+
pointer,
|
|
283
|
+
references: [shortId],
|
|
284
|
+
title: text(reference.title) || url || shortId,
|
|
285
|
+
url: pointer ? null : url,
|
|
286
|
+
};
|
|
287
|
+
byKey.set(key, draft);
|
|
288
|
+
drafts.push(draft);
|
|
289
|
+
});
|
|
290
|
+
// ── knowledge base documents: outlines and cited passages ──
|
|
291
|
+
const knowledge = withDocuments ? sourcesFromReferences(references) : [];
|
|
292
|
+
const citesKnowledge = knowledge.length > 0;
|
|
293
|
+
const outlineOf = new Map();
|
|
294
|
+
const citedOf = new Map();
|
|
295
|
+
const hintsOf = new Map();
|
|
296
|
+
const documentTitles = (unread) => references
|
|
297
|
+
.filter((reference) => {
|
|
298
|
+
const pointer = pointerOf(reference);
|
|
299
|
+
return pointer && unread.has(pointer.knowledgeBaseId);
|
|
300
|
+
})
|
|
301
|
+
.map((reference) => reference.title);
|
|
302
|
+
if (citesKnowledge) {
|
|
303
|
+
const token = options.token;
|
|
304
|
+
if (!token) {
|
|
305
|
+
const error = new KnowledgeAccessError({
|
|
306
|
+
documents: documentTitles(new Set(knowledge.map((source) => source.knowledgeBaseId))),
|
|
307
|
+
skipped: [],
|
|
308
|
+
});
|
|
309
|
+
logger.log(null, logger.levels.warn, `Source store: refused (${error.code}): no token`);
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
const skipped = new Map();
|
|
313
|
+
const skip = (knowledgeBaseId, error) => {
|
|
314
|
+
const status = statusOf(error);
|
|
315
|
+
const noAccess = status !== null && NO_ACCESS.has(status);
|
|
316
|
+
if (skipped.has(knowledgeBaseId) && !noAccess)
|
|
317
|
+
return;
|
|
318
|
+
skipped.set(knowledgeBaseId, {
|
|
319
|
+
knowledgeBaseId,
|
|
320
|
+
message: typeof error?.message === "string" ? error.message : String(error),
|
|
321
|
+
noAccess,
|
|
322
|
+
status,
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
report(options.onProgress, `Opening ${shownTogether(drafts.filter((draft) => draft.kind === "document").map((draft) => draft.title))}`, "library");
|
|
326
|
+
await Promise.all(knowledge.map(async ({ knowledgeBaseId, documentIds }) => {
|
|
327
|
+
const ids = documentIds ?? [];
|
|
328
|
+
try {
|
|
329
|
+
for (let start = 0; start < ids.length; start += OUTLINE_MAX_DOCUMENTS) {
|
|
330
|
+
const answer = await options.outlines(knowledgeBaseId, ids.slice(start, start + OUTLINE_MAX_DOCUMENTS), token);
|
|
331
|
+
for (const outline of Array.isArray(answer?.documents) ? answer.documents : []) {
|
|
332
|
+
outlineOf.set(`${knowledgeBaseId}|${id(outline.documentId)}`, outline);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
skip(knowledgeBaseId, error);
|
|
338
|
+
}
|
|
339
|
+
}));
|
|
340
|
+
// The passages references name, for the documents that can be read.
|
|
341
|
+
const named = new Map();
|
|
342
|
+
references.forEach((reference, index) => {
|
|
343
|
+
const pointer = pointerOf(reference);
|
|
344
|
+
if (!pointer?.chunkId)
|
|
345
|
+
return;
|
|
346
|
+
const key = `${pointer.knowledgeBaseId}|${pointer.documentId}`;
|
|
347
|
+
if (!outlineOf.has(key))
|
|
348
|
+
return;
|
|
349
|
+
const entry = named.get(key) ?? { byChunk: new Map(), documentId: pointer.documentId, knowledgeBaseId: pointer.knowledgeBaseId };
|
|
350
|
+
const chunk = entry.byChunk.get(pointer.chunkId) ?? { references: [], section: pointer.section };
|
|
351
|
+
chunk.references.push(`r${index}`);
|
|
352
|
+
entry.byChunk.set(pointer.chunkId, chunk);
|
|
353
|
+
named.set(key, entry);
|
|
354
|
+
});
|
|
355
|
+
await Promise.all([...named.entries()].map(async ([key, entry]) => {
|
|
356
|
+
if (skipped.has(entry.knowledgeBaseId))
|
|
357
|
+
return;
|
|
358
|
+
const chunkIds = [...entry.byChunk.keys()];
|
|
359
|
+
const found = new Map();
|
|
360
|
+
try {
|
|
361
|
+
for (let start = 0; start < chunkIds.length; start += PASSAGES_MAX) {
|
|
362
|
+
const answer = await options.passages(entry.knowledgeBaseId, entry.documentId, { chunkIds: chunkIds.slice(start, start + PASSAGES_MAX) }, token);
|
|
363
|
+
for (const passage of Array.isArray(answer?.passages) ? answer.passages : [])
|
|
364
|
+
found.set(id(passage._id), passage);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
skip(entry.knowledgeBaseId, error);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const cited = [];
|
|
372
|
+
const hints = [];
|
|
373
|
+
for (const [chunkId, chunk] of entry.byChunk) {
|
|
374
|
+
const passage = found.get(chunkId);
|
|
375
|
+
if (passage) {
|
|
376
|
+
cited.push({ references: chunk.references, section: text(passage.sectionTitle) || null, text: text(passage.text) });
|
|
377
|
+
}
|
|
378
|
+
else if (chunk.section && !hints.includes(chunk.section)) {
|
|
379
|
+
// The passage is gone (the document was ingested again): its section is where to look.
|
|
380
|
+
hints.push(chunk.section);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
citedOf.set(key, cited);
|
|
384
|
+
hintsOf.set(key, hints);
|
|
385
|
+
}));
|
|
386
|
+
if (skipped.size > 0) {
|
|
387
|
+
const error = new KnowledgeAccessError({
|
|
388
|
+
documents: documentTitles(new Set(skipped.keys())),
|
|
389
|
+
skipped: [...skipped.values()],
|
|
390
|
+
});
|
|
391
|
+
logger.log(null, logger.levels.warn, `Source store: refused (${error.code}): ${error.documents.length} document(s) unreadable; skipped knowledge bases: ${[...skipped.values()].map((source) => `${source.knowledgeBaseId} (noAccess: ${source.noAccess})`).join(", ")}`);
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
// ── pages: read once, in full; now, or each when it is first opened ──
|
|
396
|
+
const pageDrafts = drafts.filter((draft) => draft.kind === "page");
|
|
397
|
+
if (pageDrafts.length > 0 && pageMode === "upFront") {
|
|
398
|
+
report(options.onProgress, `Reading ${shownTogether(pageDrafts.map((draft) => draft.title))}`, "book-open");
|
|
399
|
+
}
|
|
400
|
+
const reads = pageDrafts.length > 0 && pageMode === "upFront"
|
|
401
|
+
? await readUrls(pageDrafts.map((draft) => draft.url), options.config, options.usageTracker ?? null)
|
|
402
|
+
: [];
|
|
403
|
+
const readOf = new Map(reads.map((read) => [read.url, read]));
|
|
404
|
+
const pagesOf = new Map();
|
|
405
|
+
/** What a page holds, or why it could not be read: the fields of its source that reading decides. */
|
|
406
|
+
const pageFields = (sourceId, read) => {
|
|
407
|
+
const unreadBecause = (reason) => ({
|
|
408
|
+
characters: 0,
|
|
409
|
+
outline: [],
|
|
410
|
+
outlineFromOpenings: false,
|
|
411
|
+
outlineTruncated: false,
|
|
412
|
+
pageCount: 0,
|
|
413
|
+
unreadReason: reason,
|
|
414
|
+
});
|
|
415
|
+
if (!read || read.error !== undefined || read.text === undefined) {
|
|
416
|
+
return unreadBecause(read?.error || "The page could not be read");
|
|
417
|
+
}
|
|
418
|
+
if (read.text.length > maxPageSource) {
|
|
419
|
+
return unreadBecause(`The page is too large to read (${read.text.length.toLocaleString("en-US")} characters)`);
|
|
420
|
+
}
|
|
421
|
+
const pages = splitIntoPages(read.text, pageCharacters);
|
|
422
|
+
pagesOf.set(sourceId, pages);
|
|
423
|
+
return { ...outlineOfPages(pages), characters: read.text.length, pageCount: pages.length, unreadReason: null };
|
|
424
|
+
};
|
|
425
|
+
const sources = drafts.map((draft, index) => {
|
|
426
|
+
const base = {
|
|
427
|
+
cited: [],
|
|
428
|
+
id: `s${index}`,
|
|
429
|
+
kind: draft.kind,
|
|
430
|
+
opened: true,
|
|
431
|
+
references: draft.references,
|
|
432
|
+
sectionHints: [],
|
|
433
|
+
title: draft.title,
|
|
434
|
+
url: draft.url,
|
|
435
|
+
};
|
|
436
|
+
const unread = (reason) => ({
|
|
437
|
+
...base,
|
|
438
|
+
characters: 0,
|
|
439
|
+
outline: [],
|
|
440
|
+
outlineFromOpenings: false,
|
|
441
|
+
outlineTruncated: false,
|
|
442
|
+
pageCount: 0,
|
|
443
|
+
unreadReason: reason,
|
|
444
|
+
});
|
|
445
|
+
if (draft.kind === "page") {
|
|
446
|
+
if (pageMode === "onDemand") {
|
|
447
|
+
// Not read yet: nothing is known of it but its title and its address.
|
|
448
|
+
return {
|
|
449
|
+
...base,
|
|
450
|
+
characters: 0,
|
|
451
|
+
opened: false,
|
|
452
|
+
outline: [],
|
|
453
|
+
outlineFromOpenings: false,
|
|
454
|
+
outlineTruncated: false,
|
|
455
|
+
pageCount: 0,
|
|
456
|
+
unreadReason: null,
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
return { ...base, ...pageFields(base.id, readOf.get(draft.url)) };
|
|
460
|
+
}
|
|
461
|
+
const pointer = draft.pointer;
|
|
462
|
+
const key = `${pointer.knowledgeBaseId}|${pointer.documentId}`;
|
|
463
|
+
const outline = outlineOf.get(key);
|
|
464
|
+
if (!outline) {
|
|
465
|
+
return unread("The document could not be read with your access, or is no longer in the knowledge base");
|
|
466
|
+
}
|
|
467
|
+
const sections = Array.isArray(outline.sections) ? outline.sections : [];
|
|
468
|
+
return {
|
|
469
|
+
...base,
|
|
470
|
+
characters: outline.characters ?? 0,
|
|
471
|
+
cited: citedOf.get(key) ?? [],
|
|
472
|
+
outline: sections
|
|
473
|
+
.filter((section) => text(section.title))
|
|
474
|
+
.map((section) => ({ page: Math.floor(section.from / pagePassages) + 1, title: text(section.title) })),
|
|
475
|
+
outlineFromOpenings: false,
|
|
476
|
+
outlineTruncated: outline.sectionsTruncated === true,
|
|
477
|
+
pageCount: Math.ceil((outline.positions ?? 0) / pagePassages),
|
|
478
|
+
sectionHints: hintsOf.get(key) ?? [],
|
|
479
|
+
title: text(outline.title) || text(outline.name) || draft.title,
|
|
480
|
+
unreadReason: null,
|
|
481
|
+
};
|
|
482
|
+
});
|
|
483
|
+
// A document's pages are fetched when read, each once.
|
|
484
|
+
const fetched = new Map();
|
|
485
|
+
const pointers = new Map(drafts.map((draft, index) => [`s${index}`, draft.pointer]));
|
|
486
|
+
const readPage = async (sourceId, page) => {
|
|
487
|
+
const source = sources.find((candidate) => candidate.id === sourceId);
|
|
488
|
+
if (!source)
|
|
489
|
+
throw new Error(`No source ${sourceId}`);
|
|
490
|
+
if (!source.opened)
|
|
491
|
+
throw new Error(`Source ${sourceId} has not been opened`);
|
|
492
|
+
if (source.unreadReason !== null)
|
|
493
|
+
throw new Error(`Source ${sourceId} could not be read: ${source.unreadReason}`);
|
|
494
|
+
if (!Number.isInteger(page) || page < 1 || page > source.pageCount) {
|
|
495
|
+
throw new Error(`Source ${sourceId} has pages 1 to ${source.pageCount}`);
|
|
496
|
+
}
|
|
497
|
+
if (source.kind === "page")
|
|
498
|
+
return pagesOf.get(sourceId)[page - 1];
|
|
499
|
+
const key = `${sourceId}|${page}`;
|
|
500
|
+
const known = fetched.get(key);
|
|
501
|
+
if (known)
|
|
502
|
+
return known;
|
|
503
|
+
const pointer = pointers.get(sourceId);
|
|
504
|
+
const from = (page - 1) * pagePassages;
|
|
505
|
+
const reading = options
|
|
506
|
+
.passages(pointer.knowledgeBaseId, pointer.documentId, { from, limit: pagePassages }, options.token)
|
|
507
|
+
.then((answer) => renderPassages((Array.isArray(answer?.passages) ? answer.passages : []).filter(
|
|
508
|
+
// Positions may have gaps: a page is its range of positions, whatever fills it.
|
|
509
|
+
(passage) => typeof passage.chunkIndex !== "number" || passage.chunkIndex < from + pagePassages)));
|
|
510
|
+
fetched.set(key, reading);
|
|
511
|
+
// A failed read is not kept: the next one asks again.
|
|
512
|
+
reading.catch(() => fetched.delete(key));
|
|
513
|
+
return reading;
|
|
514
|
+
};
|
|
515
|
+
// A page read on demand is read once, whoever asks and however many at once.
|
|
516
|
+
const opening = new Map();
|
|
517
|
+
const open = (sourceId) => {
|
|
518
|
+
const source = sources.find((candidate) => candidate.id === sourceId);
|
|
519
|
+
if (!source)
|
|
520
|
+
return Promise.reject(new Error(`No source ${sourceId}`));
|
|
521
|
+
if (source.opened)
|
|
522
|
+
return Promise.resolve(source);
|
|
523
|
+
const known = opening.get(sourceId);
|
|
524
|
+
if (known)
|
|
525
|
+
return known;
|
|
526
|
+
report(options.onProgress, `Reading ${shown(source.title)}`, "book-open");
|
|
527
|
+
const reading = readUrls([source.url], options.config, options.usageTracker ?? null).then(([read]) => {
|
|
528
|
+
// Filled in place: the store's list is what every reader of it holds.
|
|
529
|
+
Object.assign(source, pageFields(sourceId, read), { opened: true });
|
|
530
|
+
return source;
|
|
531
|
+
});
|
|
532
|
+
opening.set(sourceId, reading);
|
|
533
|
+
// A read that threw (a cancelled run) is not kept: the next one asks again.
|
|
534
|
+
reading.catch(() => opening.delete(sourceId));
|
|
535
|
+
return reading;
|
|
536
|
+
};
|
|
537
|
+
const unreadable = sources.filter((source) => source.unreadReason !== null).length;
|
|
538
|
+
const onDemand = sources.filter((source) => !source.opened).length;
|
|
539
|
+
logger.log(null, logger.levels.info, `Source store: ${sources.filter((source) => source.kind === "page").length} page(s)${onDemand > 0 ? ` (${onDemand} read on demand)` : ""}, ${sources.filter((source) => source.kind === "document").length} document(s), ${unreadable} unreadable`);
|
|
540
|
+
return { citesKnowledge, open, readPage, sources };
|
|
541
|
+
};
|
|
542
|
+
/** The sources that can be read and hold something, or may: a page not opened yet is one. */
|
|
543
|
+
const readable = (store) => store.sources.filter((source) => source.unreadReason === null && (!source.opened || source.pageCount > 0));
|
|
544
|
+
/**
|
|
545
|
+
* Whether every source can go into the prompt whole: what they hold together
|
|
546
|
+
* is within `limit`. Judged from the outlines, before any document is fetched.
|
|
547
|
+
* Never with a page that is read on demand and not opened yet: what it holds
|
|
548
|
+
* is not known.
|
|
549
|
+
* @param store From `prepareSources`
|
|
550
|
+
* @param limit The stage's reading limit, in characters
|
|
551
|
+
*/
|
|
552
|
+
export const fitsLimit = (store, limit = DEFAULT_READING_LIMIT) => store.sources.every((source) => source.opened) &&
|
|
553
|
+
readable(store).reduce((total, source) => total + source.characters, 0) <= limit;
|
|
554
|
+
/**
|
|
555
|
+
* Every readable source whole, for a prompt: only for a store that
|
|
556
|
+
* `fitsLimit`. Fetches every page of every document.
|
|
557
|
+
* @param store From `prepareSources`
|
|
558
|
+
* @returns `[{ id, references, title, url, text }]`
|
|
559
|
+
*/
|
|
560
|
+
export const sourcesForPrompt = async (store) => Promise.all(readable(store).map(async (source) => {
|
|
561
|
+
const pages = [];
|
|
562
|
+
for (let page = 1; page <= source.pageCount; page++)
|
|
563
|
+
pages.push(await store.readPage(source.id, page));
|
|
564
|
+
return {
|
|
565
|
+
id: source.id,
|
|
566
|
+
references: source.references,
|
|
567
|
+
text: source.kind === "page" ? pages.join("") : pages.filter(Boolean).join("\n\n"),
|
|
568
|
+
title: source.title,
|
|
569
|
+
url: source.url,
|
|
570
|
+
};
|
|
571
|
+
}));
|
|
572
|
+
/**
|
|
573
|
+
* The sources as a prompt lists them when the model reads through the tool:
|
|
574
|
+
* what each is, how much it holds, who cites it, and where to look first.
|
|
575
|
+
* Unreadable ones are listed with why, so the model does not try them.
|
|
576
|
+
* @param store From `prepareSources`
|
|
577
|
+
*/
|
|
578
|
+
export const sourceListForPrompt = (store) => store.sources.map((source) => ({
|
|
579
|
+
id: source.id,
|
|
580
|
+
kind: source.kind,
|
|
581
|
+
references: source.references,
|
|
582
|
+
title: source.title,
|
|
583
|
+
...(source.url ? { url: source.url } : {}),
|
|
584
|
+
...(source.unreadReason !== null
|
|
585
|
+
? { unreadable: source.unreadReason }
|
|
586
|
+
: source.opened
|
|
587
|
+
? { characters: source.characters, pages: source.pageCount }
|
|
588
|
+
: { notOpenedYet: true }),
|
|
589
|
+
...(source.sectionHints.length > 0 ? { lookFirstIn: source.sectionHints } : {}),
|
|
590
|
+
}));
|
|
591
|
+
/**
|
|
592
|
+
* The passages the references name, for a prompt: always shown, whichever way
|
|
593
|
+
* the rest is read.
|
|
594
|
+
* @param store From `prepareSources`
|
|
595
|
+
*/
|
|
596
|
+
export const citedPassagesForPrompt = (store) => store.sources.flatMap((source) => source.cited.map((passage) => ({
|
|
597
|
+
document: source.title,
|
|
598
|
+
references: passage.references,
|
|
599
|
+
section: passage.section,
|
|
600
|
+
source: source.id,
|
|
601
|
+
text: passage.text,
|
|
602
|
+
})));
|
|
603
|
+
const heading = (source, page) => `## ${source.title} (${source.id}), page ${page} of ${source.pageCount}`;
|
|
604
|
+
/**
|
|
605
|
+
* The source tool for one stage: `list_sources`, `get_outline`, `read_pages`
|
|
606
|
+
* and `read_document`, over the run's store. It reads nothing else — no web,
|
|
607
|
+
* no search — and writes nothing but the record of what was read.
|
|
608
|
+
*
|
|
609
|
+
* A stage may read `limit` characters in all. A read that would pass it
|
|
610
|
+
* returns the whole pages that fit and says the limit is reached; a page is
|
|
611
|
+
* never cut.
|
|
612
|
+
*
|
|
613
|
+
* A page that is read on demand is read the first time any function but
|
|
614
|
+
* `list_sources` is asked for it; one that cannot be read answers why.
|
|
615
|
+
*
|
|
616
|
+
* @param store From `prepareSources`
|
|
617
|
+
* @param options `record` (shared across the run's stages), `stage` (this
|
|
618
|
+
* stage's name in the record), `limit` (default DEFAULT_READING_LIMIT),
|
|
619
|
+
* `onProgress` (told, by title, which source the stage is looking through
|
|
620
|
+
* or reading, and which pages, as it asks)
|
|
621
|
+
* @returns LangChain tool instances for the stage's tool list
|
|
622
|
+
*/
|
|
623
|
+
export const sourceTools = (store, options) => {
|
|
624
|
+
const limit = options.limit ?? DEFAULT_READING_LIMIT;
|
|
625
|
+
let read = 0;
|
|
626
|
+
/** The source asked for, read first when it is a page read on demand; else why it cannot be read. */
|
|
627
|
+
const find = async (sourceId) => {
|
|
628
|
+
const listed = store.sources.find((candidate) => candidate.id === text(sourceId));
|
|
629
|
+
if (!listed)
|
|
630
|
+
return `There is no source "${text(sourceId)}". The sources are: ${store.sources.map((candidate) => candidate.id).join(", ") || "none"}.`;
|
|
631
|
+
const source = listed.opened ? listed : await store.open(listed.id);
|
|
632
|
+
if (source.unreadReason !== null)
|
|
633
|
+
return `Source ${source.id} ("${source.title}") could not be read: ${source.unreadReason}. Rest nothing on it.`;
|
|
634
|
+
if (source.pageCount === 0)
|
|
635
|
+
return `Source ${source.id} ("${source.title}") holds no text.`;
|
|
636
|
+
return source;
|
|
637
|
+
};
|
|
638
|
+
/** Reads pages in order until one does not fit what is left of the limit. */
|
|
639
|
+
const readPages = async (source, pages) => {
|
|
640
|
+
const parts = [];
|
|
641
|
+
const done = [];
|
|
642
|
+
let characters = 0;
|
|
643
|
+
let stopped = "";
|
|
644
|
+
for (const page of pages) {
|
|
645
|
+
const body = await store.readPage(source.id, page);
|
|
646
|
+
if (read + characters + body.length > limit) {
|
|
647
|
+
if (!(options.record.limitReached ??= []).includes(options.stage))
|
|
648
|
+
options.record.limitReached.push(options.stage);
|
|
649
|
+
stopped = `\n\n[Reading limit reached: page ${page} and any after it were not returned. You have read ${(read + characters).toLocaleString("en-US")} of ${limit.toLocaleString("en-US")} characters in this stage. Write from what you have read.]`;
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
parts.push(`${heading(source, page)}\n\n${body}`);
|
|
653
|
+
done.push(page);
|
|
654
|
+
characters += body.length;
|
|
655
|
+
}
|
|
656
|
+
if (done.length > 0) {
|
|
657
|
+
read += characters;
|
|
658
|
+
options.record.reads.push({ characters, pages: done, sourceId: source.id, stage: options.stage });
|
|
659
|
+
}
|
|
660
|
+
return parts.join("\n\n---\n\n") + stopped || "[Reading limit reached: nothing more can be read in this stage. Write from what you have read.]";
|
|
661
|
+
};
|
|
662
|
+
return [
|
|
663
|
+
tool(async () => {
|
|
664
|
+
report(options.onProgress, "Looking over the references", "list");
|
|
665
|
+
return JSON.stringify(sourceListForPrompt(store));
|
|
666
|
+
}, {
|
|
667
|
+
name: "list_sources",
|
|
668
|
+
description: "List the sources this content rests on: each one's id, title, kind, size in characters and pages, the references citing it, and whether it could be read.",
|
|
669
|
+
schema: z.object({}),
|
|
670
|
+
}),
|
|
671
|
+
tool(async ({ source_id }) => {
|
|
672
|
+
const source = await find(source_id);
|
|
673
|
+
if (typeof source === "string")
|
|
674
|
+
return source;
|
|
675
|
+
report(options.onProgress, `Looking through ${shown(source.title)}`, "list");
|
|
676
|
+
return JSON.stringify({
|
|
677
|
+
id: source.id,
|
|
678
|
+
title: source.title,
|
|
679
|
+
pages: source.pageCount,
|
|
680
|
+
...(source.outlineFromOpenings
|
|
681
|
+
? { note: "This source has no headings: each entry is the opening words of a page." }
|
|
682
|
+
: {}),
|
|
683
|
+
...(source.outlineTruncated ? { truncated: "The source has more sections than are listed." } : {}),
|
|
684
|
+
...(source.sectionHints.length > 0 ? { lookFirstIn: source.sectionHints } : {}),
|
|
685
|
+
outline: source.outline,
|
|
686
|
+
});
|
|
687
|
+
}, {
|
|
688
|
+
name: "get_outline",
|
|
689
|
+
description: "Get one source's outline: its section headings and the page each starts on. Use it to choose which pages of a long source to read.",
|
|
690
|
+
schema: z.object({ source_id: z.string().describe('The source\'s id, such as "s0".') }),
|
|
691
|
+
}),
|
|
692
|
+
tool(async ({ source_id, pages, section }) => {
|
|
693
|
+
const source = await find(source_id);
|
|
694
|
+
if (typeof source === "string")
|
|
695
|
+
return source;
|
|
696
|
+
let wanted = [];
|
|
697
|
+
if (Array.isArray(pages) && pages.length > 0) {
|
|
698
|
+
wanted = [...new Set(pages)].filter((page) => Number.isInteger(page) && page >= 1 && page <= source.pageCount).sort((a, b) => a - b);
|
|
699
|
+
if (wanted.length === 0)
|
|
700
|
+
return `Source ${source.id} has pages 1 to ${source.pageCount}.`;
|
|
701
|
+
}
|
|
702
|
+
else if (text(section)) {
|
|
703
|
+
const at = source.outline.findIndex((entry) => entry.title.toLowerCase() === text(section).toLowerCase());
|
|
704
|
+
if (at < 0)
|
|
705
|
+
return `Source ${source.id} has no section titled "${text(section)}". Get its outline for the titles.`;
|
|
706
|
+
const first = source.outline[at].page;
|
|
707
|
+
const next = source.outline.slice(at + 1).find((entry) => entry.page > first)?.page ?? source.pageCount + 1;
|
|
708
|
+
for (let page = first; page < Math.max(next, first + 1); page++)
|
|
709
|
+
wanted.push(page);
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
return "Say which pages to read, or which section.";
|
|
713
|
+
}
|
|
714
|
+
const now = wanted.slice(0, READ_MAX_PAGES);
|
|
715
|
+
report(options.onProgress, `Reading ${shown(source.title)}, ${shownPages(now)}${source.pageCount > now.length ? ` of ${source.pageCount}` : ""}`, "book-open");
|
|
716
|
+
const more = wanted.length > now.length
|
|
717
|
+
? `\n\n[${wanted.length - now.length} more page(s) were asked for: ${wanted.slice(now.length).join(", ")}. Ask for them in another call.]`
|
|
718
|
+
: "";
|
|
719
|
+
return (await readPages(source, now)) + more;
|
|
720
|
+
}, {
|
|
721
|
+
name: "read_pages",
|
|
722
|
+
description: `Read pages of a source: by page number, or the pages of one section by its title. At most ${READ_MAX_PAGES} pages per call.`,
|
|
723
|
+
schema: z.object({
|
|
724
|
+
source_id: z.string().describe('The source\'s id, such as "s0".'),
|
|
725
|
+
pages: z.array(z.number().int()).optional().describe("The page numbers to read, from 1."),
|
|
726
|
+
section: z.string().optional().describe("A section title from the source's outline, instead of page numbers."),
|
|
727
|
+
}),
|
|
728
|
+
}),
|
|
729
|
+
tool(async ({ source_id }) => {
|
|
730
|
+
const source = await find(source_id);
|
|
731
|
+
if (typeof source === "string")
|
|
732
|
+
return source;
|
|
733
|
+
if (read + source.characters > limit) {
|
|
734
|
+
return `Source ${source.id} is ${source.characters.toLocaleString("en-US")} characters in ${source.pageCount} pages, more than is left of this stage's reading limit (${Math.max(limit - read, 0).toLocaleString("en-US")} characters). Get its outline and read the pages that matter.`;
|
|
735
|
+
}
|
|
736
|
+
const all = Array.from({ length: source.pageCount }, (_, index) => index + 1);
|
|
737
|
+
report(options.onProgress, `Reading ${shown(source.title)}`, "book-open");
|
|
738
|
+
return readPages(source, all);
|
|
739
|
+
}, {
|
|
740
|
+
name: "read_document",
|
|
741
|
+
description: "Read a whole source in one call. Only for a source small enough for what is left of the reading limit; for a larger one, get its outline and read pages.",
|
|
742
|
+
schema: z.object({ source_id: z.string().describe('The source\'s id, such as "s0".') }),
|
|
743
|
+
}),
|
|
744
|
+
];
|
|
745
|
+
};
|
|
746
|
+
/**
|
|
747
|
+
* How much of each source was read, from the record.
|
|
748
|
+
* @param store From `prepareSources`
|
|
749
|
+
* @param record What the run read; null when everything was in the prompt,
|
|
750
|
+
* which counts as read in full
|
|
751
|
+
* @param stage Count only this stage's reads; all stages when not given
|
|
752
|
+
*/
|
|
753
|
+
export const sourceUsage = (store, record, stage) => store.sources.map((source) => {
|
|
754
|
+
if (source.unreadReason !== null)
|
|
755
|
+
return { pagesRead: 0, source, state: "unreadable" };
|
|
756
|
+
if (record === null && source.opened)
|
|
757
|
+
return { pagesRead: source.pageCount, source, state: "full" };
|
|
758
|
+
const pages = new Set((record?.reads ?? [])
|
|
759
|
+
.filter((read) => read.sourceId === source.id && (stage === undefined || read.stage === stage))
|
|
760
|
+
.flatMap((read) => read.pages));
|
|
761
|
+
return {
|
|
762
|
+
pagesRead: pages.size,
|
|
763
|
+
source,
|
|
764
|
+
// A source that holds nothing has nothing to open; a page read on
|
|
765
|
+
// demand and never asked for was not opened, whatever it holds.
|
|
766
|
+
state: pages.size === 0 && (!source.opened || source.pageCount > 0)
|
|
767
|
+
? "unopened"
|
|
768
|
+
: pages.size < source.pageCount
|
|
769
|
+
? "partial"
|
|
770
|
+
: "full",
|
|
771
|
+
};
|
|
772
|
+
});
|
|
773
|
+
/**
|
|
774
|
+
* The readable sources a stage never opened: what a retry of the stage is
|
|
775
|
+
* told to read. A source whose only content is its cited passages, already in
|
|
776
|
+
* the prompt, is not among them.
|
|
777
|
+
* @param store From `prepareSources`
|
|
778
|
+
* @param record What the run read
|
|
779
|
+
* @param stage The stage
|
|
780
|
+
*/
|
|
781
|
+
export const unconsultedSources = (store, record, stage) => sourceUsage(store, record, stage)
|
|
782
|
+
.filter((use) => use.state === "unopened")
|
|
783
|
+
.map((use) => use.source);
|
|
784
|
+
/**
|
|
785
|
+
* What the person is told about the sources: one finding per reference whose
|
|
786
|
+
* source could not be read; and, when the model read through the tool, one
|
|
787
|
+
* per reference whose source was never opened — worded as an attribution to
|
|
788
|
+
* it when the content cites that reference. A source is flagged as unopened
|
|
789
|
+
* whatever the cause (Candin, 2026-11-18): when the stage ran out of its
|
|
790
|
+
* reading limit the finding says so, so the person knows why.
|
|
791
|
+
* @param store From `prepareSources`
|
|
792
|
+
* @param record What the run read; null when everything was in the prompt
|
|
793
|
+
* @param options `references` (as supplied, for their titles), `cited` (the
|
|
794
|
+
* short ids the content cites), `stage` (judge by this stage's reads)
|
|
795
|
+
*/
|
|
796
|
+
export const sourceFindings = (store, record, options = {}) => {
|
|
797
|
+
const references = Array.isArray(options.references) ? options.references : [];
|
|
798
|
+
const cited = new Set((Array.isArray(options.cited) ? options.cited : []).map(text));
|
|
799
|
+
const titleOf = (shortId, fallback) => text(references[Number(shortId.slice(1))]?.title) || fallback;
|
|
800
|
+
// Without a stage, any stage that ran out counts.
|
|
801
|
+
const stopped = (record?.limitReached ?? []).some((stage) => options.stage === undefined || stage === options.stage);
|
|
802
|
+
const why = stopped
|
|
803
|
+
? " The sources supplied were larger than could be read while writing, and the reading limit was reached before this one was opened."
|
|
804
|
+
: "";
|
|
805
|
+
const findings = [];
|
|
806
|
+
for (const use of sourceUsage(store, record, options.stage)) {
|
|
807
|
+
for (const reference of use.source.references) {
|
|
808
|
+
const title = titleOf(reference, use.source.title);
|
|
809
|
+
if (use.state === "unreadable") {
|
|
810
|
+
findings.push({
|
|
811
|
+
message: `${use.source.kind === "page" ? "The page for reference" : "Reference"} "${title}" could not be read (${use.source.unreadReason}). This content was written without it.`,
|
|
812
|
+
limitReached: false,
|
|
813
|
+
reference,
|
|
814
|
+
title,
|
|
815
|
+
type: "UNREADABLE",
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
else if (use.state === "unopened") {
|
|
819
|
+
findings.push(cited.has(reference)
|
|
820
|
+
? {
|
|
821
|
+
message: `This content attributes a statement to reference "${title}", which was not consulted.${why}`,
|
|
822
|
+
limitReached: stopped,
|
|
823
|
+
reference,
|
|
824
|
+
title,
|
|
825
|
+
type: "ATTRIBUTED_UNREAD",
|
|
826
|
+
}
|
|
827
|
+
: {
|
|
828
|
+
message: `Reference "${title}" was supplied but not consulted when this content was written.${why}`,
|
|
829
|
+
limitReached: stopped,
|
|
830
|
+
reference,
|
|
831
|
+
title,
|
|
832
|
+
type: "NOT_CONSULTED",
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return findings;
|
|
838
|
+
};
|
|
839
|
+
export default {
|
|
840
|
+
DEFAULT_MAX_PAGE_SOURCE_CHARACTERS,
|
|
841
|
+
DEFAULT_PAGE_CHARACTERS,
|
|
842
|
+
DEFAULT_PAGE_PASSAGES,
|
|
843
|
+
DEFAULT_READING_LIMIT,
|
|
844
|
+
citedPassagesForPrompt,
|
|
845
|
+
fitsLimit,
|
|
846
|
+
newSourceRecord,
|
|
847
|
+
prepareSources,
|
|
848
|
+
sourceFindings,
|
|
849
|
+
sourceListForPrompt,
|
|
850
|
+
sourceTools,
|
|
851
|
+
sourceUsage,
|
|
852
|
+
sourcesForPrompt,
|
|
853
|
+
splitIntoPages,
|
|
854
|
+
unconsultedSources,
|
|
855
|
+
};
|