@stackfactor/agent-utils 1.13.4 → 1.32.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.
Files changed (252) hide show
  1. package/README.md +667 -23
  2. package/dist/cjs/agentProto.d.ts +13 -3
  3. package/dist/cjs/agentProto.d.ts.map +1 -1
  4. package/dist/cjs/agentProto.js +25 -4
  5. package/dist/cjs/backoff.d.ts +17 -0
  6. package/dist/cjs/backoff.d.ts.map +1 -0
  7. package/dist/cjs/backoff.js +26 -0
  8. package/dist/cjs/cancellation.d.ts +22 -0
  9. package/dist/cjs/cancellation.d.ts.map +1 -0
  10. package/dist/cjs/cancellation.js +36 -0
  11. package/dist/cjs/cli.d.ts +3 -0
  12. package/dist/cjs/cli.d.ts.map +1 -0
  13. package/dist/cjs/cli.js +85 -0
  14. package/dist/cjs/client.d.ts +11 -0
  15. package/dist/cjs/client.d.ts.map +1 -1
  16. package/dist/cjs/client.js +27 -0
  17. package/dist/cjs/const.d.ts +23 -0
  18. package/dist/cjs/const.d.ts.map +1 -1
  19. package/dist/cjs/const.js +23 -0
  20. package/dist/cjs/daemon.d.ts +94 -0
  21. package/dist/cjs/daemon.d.ts.map +1 -0
  22. package/dist/cjs/daemon.js +507 -0
  23. package/dist/cjs/daemonConfig.d.ts +45 -0
  24. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  25. package/dist/cjs/daemonConfig.js +148 -0
  26. package/dist/cjs/daemonEnv.d.ts +10 -0
  27. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  28. package/dist/cjs/daemonEnv.js +12 -0
  29. package/dist/cjs/durable/clientTool.d.ts +39 -0
  30. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  31. package/dist/cjs/durable/clientTool.js +90 -0
  32. package/dist/cjs/durable/index.d.ts +9 -0
  33. package/dist/cjs/durable/index.d.ts.map +1 -0
  34. package/dist/cjs/durable/index.js +16 -0
  35. package/dist/cjs/durable/journal.d.ts +218 -0
  36. package/dist/cjs/durable/journal.d.ts.map +1 -0
  37. package/dist/cjs/durable/journal.js +392 -0
  38. package/dist/cjs/durable/pause.d.ts +84 -0
  39. package/dist/cjs/durable/pause.d.ts.map +1 -0
  40. package/dist/cjs/durable/pause.js +241 -0
  41. package/dist/cjs/durable/resume.d.ts +27 -0
  42. package/dist/cjs/durable/resume.d.ts.map +1 -0
  43. package/dist/cjs/durable/resume.js +80 -0
  44. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  46. package/dist/cjs/durable/snapshotSaver.js +81 -0
  47. package/dist/cjs/durable/step.d.ts +28 -0
  48. package/dist/cjs/durable/step.d.ts.map +1 -0
  49. package/dist/cjs/durable/step.js +43 -0
  50. package/dist/cjs/index.d.ts +30 -7
  51. package/dist/cjs/index.d.ts.map +1 -1
  52. package/dist/cjs/index.js +28 -1
  53. package/dist/cjs/infrastructure.d.ts +50 -0
  54. package/dist/cjs/infrastructure.d.ts.map +1 -0
  55. package/dist/cjs/infrastructure.js +163 -0
  56. package/dist/cjs/langChain.d.ts +15 -3
  57. package/dist/cjs/langChain.d.ts.map +1 -1
  58. package/dist/cjs/langChain.js +986 -180
  59. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  60. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  61. package/dist/cjs/learningActivityMedia.js +861 -0
  62. package/dist/cjs/learningContentPlan.d.ts +105 -0
  63. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  64. package/dist/cjs/learningContentPlan.js +305 -0
  65. package/dist/cjs/learningContentThread.d.ts +184 -0
  66. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  67. package/dist/cjs/learningContentThread.js +407 -0
  68. package/dist/cjs/logger.d.ts +1 -0
  69. package/dist/cjs/logger.d.ts.map +1 -1
  70. package/dist/cjs/logger.js +17 -3
  71. package/dist/cjs/modelRates.d.ts +40 -0
  72. package/dist/cjs/modelRates.d.ts.map +1 -0
  73. package/dist/cjs/modelRates.js +76 -0
  74. package/dist/cjs/referenceContext.d.ts +4 -145
  75. package/dist/cjs/referenceContext.d.ts.map +1 -1
  76. package/dist/cjs/referenceContext.js +16 -251
  77. package/dist/cjs/retry.d.ts +64 -0
  78. package/dist/cjs/retry.d.ts.map +1 -0
  79. package/dist/cjs/retry.js +138 -0
  80. package/dist/cjs/runtimeContext.d.ts +8 -1
  81. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  82. package/dist/cjs/runtimeContext.js +3 -1
  83. package/dist/cjs/serve.d.ts +3 -2
  84. package/dist/cjs/serve.d.ts.map +1 -1
  85. package/dist/cjs/serve.js +32 -2
  86. package/dist/cjs/sourceStore.d.ts +378 -0
  87. package/dist/cjs/sourceStore.d.ts.map +1 -0
  88. package/dist/cjs/sourceStore.js +872 -0
  89. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  90. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  91. package/dist/cjs/stackfactorKnowledge.js +108 -44
  92. package/dist/cjs/tavily.d.ts +108 -4
  93. package/dist/cjs/tavily.d.ts.map +1 -1
  94. package/dist/cjs/tavily.js +242 -21
  95. package/dist/cjs/usage.d.ts.map +1 -1
  96. package/dist/cjs/usage.js +9 -15
  97. package/dist/cjs/version.d.ts +3 -0
  98. package/dist/cjs/version.d.ts.map +1 -0
  99. package/dist/cjs/version.js +5 -0
  100. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  102. package/dist/cjs/workflow/bookkeeping.js +75 -0
  103. package/dist/cjs/workflow/index.d.ts +13 -0
  104. package/dist/cjs/workflow/index.d.ts.map +1 -0
  105. package/dist/cjs/workflow/index.js +51 -0
  106. package/dist/cjs/workflow/limits.d.ts +52 -0
  107. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  108. package/dist/cjs/workflow/limits.js +62 -0
  109. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  111. package/dist/cjs/workflow/platformTransport.js +115 -0
  112. package/dist/cjs/workflow/retrying.d.ts +44 -0
  113. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  114. package/dist/cjs/workflow/retrying.js +82 -0
  115. package/dist/cjs/workflow/run.d.ts +195 -0
  116. package/dist/cjs/workflow/run.d.ts.map +1 -0
  117. package/dist/cjs/workflow/run.js +858 -0
  118. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  119. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  120. package/dist/cjs/workflow/testing/index.js +6 -0
  121. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  124. package/dist/cjs/workflow/transport.d.ts +219 -0
  125. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  126. package/dist/cjs/workflow/transport.js +19 -0
  127. package/dist/esm/agentProto.d.ts +13 -3
  128. package/dist/esm/agentProto.d.ts.map +1 -1
  129. package/dist/esm/agentProto.js +23 -3
  130. package/dist/esm/backoff.d.ts +17 -0
  131. package/dist/esm/backoff.d.ts.map +1 -0
  132. package/dist/esm/backoff.js +22 -0
  133. package/dist/esm/cancellation.d.ts +22 -0
  134. package/dist/esm/cancellation.d.ts.map +1 -0
  135. package/dist/esm/cancellation.js +27 -0
  136. package/dist/esm/cli.d.ts +3 -0
  137. package/dist/esm/cli.d.ts.map +1 -0
  138. package/dist/esm/cli.js +80 -0
  139. package/dist/esm/client.d.ts +11 -0
  140. package/dist/esm/client.d.ts.map +1 -1
  141. package/dist/esm/client.js +25 -1
  142. package/dist/esm/const.d.ts +23 -0
  143. package/dist/esm/const.d.ts.map +1 -1
  144. package/dist/esm/const.js +23 -0
  145. package/dist/esm/daemon.d.ts +94 -0
  146. package/dist/esm/daemon.d.ts.map +1 -0
  147. package/dist/esm/daemon.js +499 -0
  148. package/dist/esm/daemonConfig.d.ts +45 -0
  149. package/dist/esm/daemonConfig.d.ts.map +1 -0
  150. package/dist/esm/daemonConfig.js +142 -0
  151. package/dist/esm/daemonEnv.d.ts +10 -0
  152. package/dist/esm/daemonEnv.d.ts.map +1 -0
  153. package/dist/esm/daemonEnv.js +9 -0
  154. package/dist/esm/durable/clientTool.d.ts +39 -0
  155. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  156. package/dist/esm/durable/clientTool.js +82 -0
  157. package/dist/esm/durable/index.d.ts +9 -0
  158. package/dist/esm/durable/index.d.ts.map +1 -0
  159. package/dist/esm/durable/index.js +8 -0
  160. package/dist/esm/durable/journal.d.ts +218 -0
  161. package/dist/esm/durable/journal.d.ts.map +1 -0
  162. package/dist/esm/durable/journal.js +374 -0
  163. package/dist/esm/durable/pause.d.ts +84 -0
  164. package/dist/esm/durable/pause.d.ts.map +1 -0
  165. package/dist/esm/durable/pause.js +226 -0
  166. package/dist/esm/durable/resume.d.ts +27 -0
  167. package/dist/esm/durable/resume.d.ts.map +1 -0
  168. package/dist/esm/durable/resume.js +72 -0
  169. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  171. package/dist/esm/durable/snapshotSaver.js +77 -0
  172. package/dist/esm/durable/step.d.ts +28 -0
  173. package/dist/esm/durable/step.d.ts.map +1 -0
  174. package/dist/esm/durable/step.js +36 -0
  175. package/dist/esm/index.d.ts +30 -7
  176. package/dist/esm/index.d.ts.map +1 -1
  177. package/dist/esm/index.js +20 -4
  178. package/dist/esm/infrastructure.d.ts +50 -0
  179. package/dist/esm/infrastructure.d.ts.map +1 -0
  180. package/dist/esm/infrastructure.js +156 -0
  181. package/dist/esm/langChain.d.ts +15 -3
  182. package/dist/esm/langChain.d.ts.map +1 -1
  183. package/dist/esm/langChain.js +984 -179
  184. package/dist/esm/learningActivityMedia.d.ts +196 -0
  185. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  186. package/dist/esm/learningActivityMedia.js +807 -0
  187. package/dist/esm/learningContentPlan.d.ts +105 -0
  188. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  189. package/dist/esm/learningContentPlan.js +299 -0
  190. package/dist/esm/learningContentThread.d.ts +184 -0
  191. package/dist/esm/learningContentThread.d.ts.map +1 -0
  192. package/dist/esm/learningContentThread.js +364 -0
  193. package/dist/esm/logger.d.ts +1 -0
  194. package/dist/esm/logger.d.ts.map +1 -1
  195. package/dist/esm/logger.js +17 -3
  196. package/dist/esm/modelRates.d.ts +40 -0
  197. package/dist/esm/modelRates.d.ts.map +1 -0
  198. package/dist/esm/modelRates.js +68 -0
  199. package/dist/esm/referenceContext.d.ts +4 -145
  200. package/dist/esm/referenceContext.d.ts.map +1 -1
  201. package/dist/esm/referenceContext.js +16 -243
  202. package/dist/esm/retry.d.ts +64 -0
  203. package/dist/esm/retry.d.ts.map +1 -0
  204. package/dist/esm/retry.js +127 -0
  205. package/dist/esm/runtimeContext.d.ts +8 -1
  206. package/dist/esm/runtimeContext.d.ts.map +1 -1
  207. package/dist/esm/runtimeContext.js +3 -1
  208. package/dist/esm/serve.d.ts +3 -2
  209. package/dist/esm/serve.d.ts.map +1 -1
  210. package/dist/esm/serve.js +33 -3
  211. package/dist/esm/sourceStore.d.ts +378 -0
  212. package/dist/esm/sourceStore.d.ts.map +1 -0
  213. package/dist/esm/sourceStore.js +855 -0
  214. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  215. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  216. package/dist/esm/stackfactorKnowledge.js +101 -41
  217. package/dist/esm/tavily.d.ts +108 -4
  218. package/dist/esm/tavily.d.ts.map +1 -1
  219. package/dist/esm/tavily.js +237 -20
  220. package/dist/esm/usage.d.ts.map +1 -1
  221. package/dist/esm/usage.js +9 -15
  222. package/dist/esm/version.d.ts +3 -0
  223. package/dist/esm/version.d.ts.map +1 -0
  224. package/dist/esm/version.js +2 -0
  225. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  227. package/dist/esm/workflow/bookkeeping.js +67 -0
  228. package/dist/esm/workflow/index.d.ts +13 -0
  229. package/dist/esm/workflow/index.d.ts.map +1 -0
  230. package/dist/esm/workflow/index.js +10 -0
  231. package/dist/esm/workflow/limits.d.ts +52 -0
  232. package/dist/esm/workflow/limits.d.ts.map +1 -0
  233. package/dist/esm/workflow/limits.js +59 -0
  234. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  235. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  236. package/dist/esm/workflow/platformTransport.js +110 -0
  237. package/dist/esm/workflow/retrying.d.ts +44 -0
  238. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  239. package/dist/esm/workflow/retrying.js +73 -0
  240. package/dist/esm/workflow/run.d.ts +195 -0
  241. package/dist/esm/workflow/run.d.ts.map +1 -0
  242. package/dist/esm/workflow/run.js +850 -0
  243. package/dist/esm/workflow/testing/index.d.ts +3 -0
  244. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  245. package/dist/esm/workflow/testing/index.js +2 -0
  246. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  248. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  249. package/dist/esm/workflow/transport.d.ts +219 -0
  250. package/dist/esm/workflow/transport.d.ts.map +1 -0
  251. package/dist/esm/workflow/transport.js +16 -0
  252. package/package.json +8 -7
@@ -0,0 +1,127 @@
1
+ //
2
+ // A platform call that failed for a reason that may pass, made again
3
+ //
4
+ // Candin, 2026-11-09: "if the generation is not possible due to technical
5
+ // issues, the generation should show an error and stop, instead of hiding the
6
+ // problem. Obviously the generation needs to be fault tolerant, so if an issue
7
+ // is transitory it should recover." A call that failed with one of
8
+ // TRANSIENT_STATUSES, or with no answer at all because of the network (a
9
+ // dropped connection, a timeout), is made again after a wait, twice by
10
+ // default; any other status (401, 403, 404, 422, every other 4xx), and any
11
+ // other failure with no status (a TypeError: a fault, not a passing one), is
12
+ // passed on at once. What still fails after the retries is the caller's to
13
+ // report: nothing here hides a failure.
14
+ //
15
+ // A breaker (one a run, or one a read of a skill's references): a key — a
16
+ // knowledge base — whose retries a call has spent is not waited for again
17
+ // while it keeps failing. Its next calls are made once each, so a knowledge
18
+ // base that is down costs its retries once, not once per search; the first
19
+ // call it answers closes the breaker on it again.
20
+ //
21
+ // The workflow runner's transport keeps its own policy (workflow/retrying.ts):
22
+ // its spec never retries a 4xx, a rate limit included.
23
+ //
24
+ import logger from "./logger.js";
25
+ /** The statuses a call is made again after: a timeout, a rate limit, a server or gateway failure. */
26
+ const TRANSIENT_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
27
+ /** The codes of a failure that got no answer because of the network. */
28
+ const NETWORK_CODES = new Set(["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EPIPE"]);
29
+ /** What the message of a failure with no status and no network code says when it is the network's. */
30
+ const NETWORK_MESSAGE = /network|timeout|socket|fetch failed/i;
31
+ /**
32
+ * What a TypeError with no status says when it is the network's: fetch
33
+ * rejects with `TypeError: fetch failed` when it gets no answer, and with
34
+ * `TypeError: terminated` when the connection drops while the answer is being
35
+ * read (a model's stream cut mid-answer, prod 2026-11-15). Any other TypeError
36
+ * is a fault, and its message (a property name, "socketPath is not a
37
+ * function") says nothing.
38
+ */
39
+ const FETCH_FAILED = /fetch failed|^terminated$/i;
40
+ /** How long to wait before each retry, in milliseconds: one retry each. */
41
+ export const RETRY_WAITS = Object.freeze([2000, 6000]);
42
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
43
+ /**
44
+ * A failure's message: an Error's own, any other value as text.
45
+ * @param error What a call failed with
46
+ */
47
+ export const messageOf = (error) => (error instanceof Error ? error.message : String(error));
48
+ /**
49
+ * The status a failed platform call answered with, as an axios error carries
50
+ * it: on `status`, else on `response.status`; a status sent as text is read
51
+ * as its number. Null when there is none.
52
+ * @param error What the call failed with
53
+ */
54
+ export const statusOf = (error) => {
55
+ const failed = error;
56
+ const status = failed?.status ?? failed?.response?.status;
57
+ if (status === undefined || status === null || status === "")
58
+ return null;
59
+ const number = Number(status);
60
+ return Number.isFinite(number) ? number : null;
61
+ };
62
+ /**
63
+ * Whether a failed call may succeed when made again: its status is one of
64
+ * TRANSIENT_STATUSES; or it has none and the network failed it — a TypeError
65
+ * only as fetch's "fetch failed"; any other failure by a code of
66
+ * NETWORK_CODES, or a message NETWORK_MESSAGE matches (a failure that is no
67
+ * Error is read as its text).
68
+ * @param error What the call failed with
69
+ */
70
+ export const isTransient = (error) => {
71
+ const failed = error;
72
+ const rawStatus = failed?.status ?? failed?.response?.status;
73
+ if (rawStatus !== undefined && rawStatus !== null)
74
+ return TRANSIENT_STATUSES.has(Number(rawStatus));
75
+ if (error instanceof TypeError)
76
+ return FETCH_FAILED.test(error.message);
77
+ const code = failed?.code;
78
+ return (typeof code === "string" && NETWORK_CODES.has(code)) || NETWORK_MESSAGE.test(messageOf(error));
79
+ };
80
+ /**
81
+ * Whether a call got no answer, or lost it part-way, because of the network:
82
+ * a failure with no status that may pass (isTransient). One that carries a
83
+ * status was answered, and is its caller's to read.
84
+ * @param error What the call failed with
85
+ */
86
+ export const isNetworkFailure = (error) => statusOf(error) === null && isTransient(error);
87
+ /**
88
+ * Makes a platform call, and makes it again after each of the waits while it
89
+ * fails for a reason that may pass (isTransient), logging each retry.
90
+ * @param what The call, as the log names it (`search "C#" in knowledge base kb-1`)
91
+ * @param call The call
92
+ * @param options `waits` (default RETRY_WAITS), `breaker` and `key`,
93
+ * `stopWhen`, `sleep`
94
+ * @returns What the call answered
95
+ * @throws What the call failed with: at once when it may not pass, or when
96
+ * `stopWhen` says retrying is pointless; the last failure once the
97
+ * retries are spent
98
+ */
99
+ export const retryTransient = async (what, call, options = {}) => {
100
+ const waits = options.waits ?? RETRY_WAITS;
101
+ const sleep = options.sleep ?? delay;
102
+ const key = typeof options.key === "string" ? options.key : null;
103
+ const breaker = key === null ? undefined : options.breaker;
104
+ const retries = breaker?.has(key) ? 0 : waits.length;
105
+ const attempts = waits.length + 1;
106
+ for (let attempt = 1;; attempt++) {
107
+ try {
108
+ const answer = await call();
109
+ breaker?.delete(key);
110
+ return answer;
111
+ }
112
+ catch (error) {
113
+ if (!isTransient(error) || options.stopWhen?.())
114
+ throw error;
115
+ if (attempt > retries) {
116
+ breaker?.add(key);
117
+ throw error;
118
+ }
119
+ const wait = waits[attempt - 1];
120
+ logger.log(null, logger.levels.warn, `retry: ${what} failed (${messageOf(error)}) on attempt ${attempt} of ${attempts}; trying again in ${wait} ms`);
121
+ await sleep(wait);
122
+ // asked again after the wait: a refusal may have landed meanwhile
123
+ if (options.stopWhen?.())
124
+ throw error;
125
+ }
126
+ }
127
+ };
@@ -18,7 +18,13 @@ export interface RequestContext {
18
18
  onProgress: ((update: {
19
19
  progress: number;
20
20
  message: string;
21
+ icon?: string;
21
22
  }) => void) | null;
23
+ /**
24
+ * Sends one item of the answer to the caller while the call is still running.
25
+ * `null` where there is no caller to send to (the self-check).
26
+ */
27
+ onPartialResult: ((item: unknown) => void) | null;
22
28
  /** Aborted when the caller cancels (e.g. the frontend socket dropped). */
23
29
  signal: AbortSignal | null;
24
30
  /** Identity + tenant resolved from the request's auth token (see serve). */
@@ -36,7 +42,8 @@ export declare const getContext: () => RequestContext | undefined;
36
42
  /** The active request's abort signal, or `null`. */
37
43
  export declare const getAbortSignal: () => AbortSignal | null;
38
44
  /**
39
- * Install global getters (`config`, `params`, `onProgress`, `request`, `event`)
45
+ * Install global getters (`config`, `params`, `onProgress`, `onPartialResult`,
46
+ * `request`, `event`)
40
47
  * that resolve to the active {@link RequestContext}. Idempotent; call once at
41
48
  * startup. After this, agent code referencing those globals transparently reads
42
49
  * the current request's values even under concurrency.
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeContext.d.ts","sourceRoot":"","sources":["../../src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OAAO,EAAE,GAAG,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IAEX,UAAU,EACN,CAAC,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC,GACxE,IAAI,CAAC;IACT;;;OAGG;IACH,eAAe,EAAE,CAAC,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IAClD,0EAA0E;IAC1E,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3B,4EAA4E;IAC5E,OAAO,CAAC,EAAE;QAAE,IAAI,EAAE,GAAG,CAAC;QAAC,MAAM,EAAE,GAAG,CAAA;KAAE,GAAG,IAAI,CAAC;IAC5C,kFAAkF;IAClF,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB;AAID,+DAA+D;AAC/D,eAAO,MAAM,cAAc,GAAI,CAAC,EAC9B,KAAK,cAAc,EACnB,IAAI,MAAM,OAAO,CAAC,CAAC,CAAC,KACnB,OAAO,CAAC,CAAC,CAAyB,CAAC;AAEtC,oEAAoE;AACpE,eAAO,MAAM,UAAU,QAAO,cAAc,GAAG,SAA+B,CAAC;AAE/E,oDAAoD;AACpD,eAAO,MAAM,cAAc,QAAO,WAAW,GAAG,IACZ,CAAC;AAIrC;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,QAAO,IAWjC,CAAC"}
@@ -8,7 +8,8 @@ export const getContext = () => storage.getStore();
8
8
  export const getAbortSignal = () => storage.getStore()?.signal ?? null;
9
9
  let installed = false;
10
10
  /**
11
- * Install global getters (`config`, `params`, `onProgress`, `request`, `event`)
11
+ * Install global getters (`config`, `params`, `onProgress`, `onPartialResult`,
12
+ * `request`, `event`)
12
13
  * that resolve to the active {@link RequestContext}. Idempotent; call once at
13
14
  * startup. After this, agent code referencing those globals transparently reads
14
15
  * the current request's values even under concurrency.
@@ -23,4 +24,5 @@ export const installGlobals = () => {
23
24
  define("request", () => storage.getStore()?.request);
24
25
  define("event", () => storage.getStore()?.event);
25
26
  define("onProgress", () => storage.getStore()?.onProgress);
27
+ define("onPartialResult", () => storage.getStore()?.onPartialResult);
26
28
  };
@@ -114,8 +114,9 @@ export declare const runOnce: (main: AgentMain, options?: ServeOptions) => Promi
114
114
  /**
115
115
  * Start a gRPC server that exposes `main` as the fleet-standard `Agent.Execute`
116
116
  * RPC. Per request it binds a {@link RequestContext} (so the agent's globals are
117
- * concurrency-safe), streams each `onProgress` event as a `Progress` frame, and
118
- * sends a final `Result` or `Error`. Caller cancellation (e.g. the frontend
117
+ * concurrency-safe), streams each `onProgress` event as a `Progress` frame and
118
+ * each `onPartialResult` item as a `Partial` frame, and sends a final `Result`
119
+ * or `Error`. Caller cancellation (e.g. the frontend
119
120
  * socket dropping) aborts the in-flight LLM call to stop billing.
120
121
  *
121
122
  * @example
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,eAAe,CAAC;AAYtC,OAAO,EAIL,KAAK,WAAW,EACjB,MAAM,YAAY,CAAC;AAwPpB;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG,CAAC,MAAM,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,OAAO,EAAE,GAAG,KACT,OAAO,CAAC;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,MAAM,EAAE,GAAG,CAAA;CAAE,CAAC,CAAC;AAEzC,MAAM,WAAW,YAAY;IAC3B,4EAA4E;IAC5E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wFAAwF;IACxF,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,uEAAuE;I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KAAE,CAAC,CAAC;IACxD,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,EAAE,CACN,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,MAAM,KACV,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CACpC;AAKD;;;;;;GAMG;AACH,eAAO,MAAM,aAAa;;;;;CAKhB,CAAC;AAEX,mFAAmF;AACnF,eAAO,MAAM,kBAAkB,GAAI,MAAK,MAAM,CAAC,UAAwB,KAAG,OACJ,CAAC;AAKvE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAAI,OAAO,GAAG,EAAE,SAAS,GAAG,KAAG,OAEhB,CAAC;AAKlD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,GAAG,EAAE,SAAS,GAAG,KAAG,OAGN,CAAC;AAmKrD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,GAClB,MAAM,SAAS,EACf,UAAS,YAAiB,KACzB,OAAO,CAAC,IAAI,CAiJd,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,KAAK,GAChB,MAAM,SAAS,EACf,UAAS,YAAiB,KACzB,IAAI,CAAC,MA4QP,CAAC"}
package/dist/esm/serve.js CHANGED
@@ -4,7 +4,7 @@ import { resolve, relative, isAbsolute } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { integration as clientIntegration, session as clientSession, } from "@stackfactor/client-api";
6
6
  import logger from "./logger.js";
7
- import { loadAgentService } from "./agentProto.js";
7
+ import { loadAgentService, progressIcon } from "./agentProto.js";
8
8
  import { MESSAGE_SIZE_OPTIONS } from "./messageLimits.js";
9
9
  import { runWithContext, installGlobals } from "./runtimeContext.js";
10
10
  import { UsageLedger, reportUsage, reportUsageWhileRunning, } from "./usage.js";
@@ -171,6 +171,7 @@ const runSelfCheck = async (checkCode, config, session) => {
171
171
  request: { session },
172
172
  event: 0,
173
173
  onProgress: null,
174
+ onPartialResult: null,
174
175
  signal: abort.signal,
175
176
  session,
176
177
  };
@@ -438,6 +439,9 @@ export const runOnce = async (main, options = {}) => {
438
439
  onProgress: (update) => {
439
440
  logger.log(null, logger.levels.info, `progress ${Math.round(update?.progress ?? 0)}%: ${update?.message ?? ""}`);
440
441
  },
442
+ // A job has no caller waiting on a stream, so an agent that sends
443
+ // partial results runs the same code here and they go nowhere.
444
+ onPartialResult: () => { },
441
445
  signal: abort.signal,
442
446
  session,
443
447
  usage: new UsageLedger(),
@@ -506,8 +510,9 @@ export const runOnce = async (main, options = {}) => {
506
510
  /**
507
511
  * Start a gRPC server that exposes `main` as the fleet-standard `Agent.Execute`
508
512
  * RPC. Per request it binds a {@link RequestContext} (so the agent's globals are
509
- * concurrency-safe), streams each `onProgress` event as a `Progress` frame, and
510
- * sends a final `Result` or `Error`. Caller cancellation (e.g. the frontend
513
+ * concurrency-safe), streams each `onProgress` event as a `Progress` frame and
514
+ * each `onPartialResult` item as a `Partial` frame, and sends a final `Result`
515
+ * or `Error`. Caller cancellation (e.g. the frontend
511
516
  * socket dropping) aborts the in-flight LLM call to stop billing.
512
517
  *
513
518
  * @example
@@ -538,9 +543,33 @@ export const serve = (main, options = {}) => {
538
543
  progress: {
539
544
  progress: Math.round(update?.progress ?? 0),
540
545
  message: update?.message ?? "",
546
+ icon: progressIcon(update?.icon),
541
547
  },
542
548
  });
543
549
  };
550
+ // Sends one item of the answer now, as a Partial frame, instead of with the
551
+ // final result. A value that cannot be sent is the agent's bug, so it
552
+ // throws to the agent; a write the stream refuses is not, so it is logged.
553
+ const onPartialResult = (item) => {
554
+ if (abort.signal.aborted)
555
+ return;
556
+ let itemJson;
557
+ try {
558
+ itemJson = JSON.stringify(item);
559
+ }
560
+ catch {
561
+ itemJson = undefined;
562
+ }
563
+ if (itemJson === undefined) {
564
+ throw new TypeError("onPartialResult needs a value that can be sent as JSON");
565
+ }
566
+ try {
567
+ call.write({ partial: { item_json: itemJson } });
568
+ }
569
+ catch (error) {
570
+ logger.log(null, logger.levels.error, `agent Execute could not send a partial result: ${error instanceof Error ? error.message : String(error)}`);
571
+ }
572
+ };
544
573
  const handle = async () => {
545
574
  // Authenticate first — refuse the call when the token is missing/invalid.
546
575
  // The exceptions carry no token by design and run with no session: see
@@ -572,6 +601,7 @@ export const serve = (main, options = {}) => {
572
601
  request: { ...request, session }, // expose identity/tenant to the agent
573
602
  event: req.event ?? 0,
574
603
  onProgress,
604
+ onPartialResult,
575
605
  signal: abort.signal,
576
606
  session,
577
607
  usage: new UsageLedger(),
@@ -0,0 +1,378 @@
1
+ import type { UsageTracker } from "./langChain.js";
2
+ /** Characters to a page of a web page; a document's page holds about as much (40 passages of ~500). */
3
+ export declare const DEFAULT_PAGE_CHARACTERS = 20000;
4
+ /** Positions (passages, when there are no gaps) to a page of a knowledge base document. */
5
+ export declare const DEFAULT_PAGE_PASSAGES = 40;
6
+ /** How many characters a stage may read through the tool. */
7
+ export declare const DEFAULT_READING_LIMIT = 200000;
8
+ /** A web page past this is not held: it is treated as unreadable, and said so. */
9
+ export declare const DEFAULT_MAX_PAGE_SOURCE_CHARACTERS = 5000000;
10
+ /** A document's outline as the platform answers it (client-api `DocumentOutline`). */
11
+ export interface KnowledgeOutline {
12
+ documentId: string;
13
+ name?: string | null;
14
+ title?: string | null;
15
+ url?: string | null;
16
+ positions: number;
17
+ passages: number;
18
+ characters: number;
19
+ sections: {
20
+ title: string | null;
21
+ from: number;
22
+ passages: number;
23
+ characters: number;
24
+ }[];
25
+ sectionsTruncated?: boolean;
26
+ }
27
+ /** A passage as the platform answers it (client-api `RetrievedChunk`). */
28
+ export interface KnowledgePassage {
29
+ _id: string;
30
+ documentId?: string;
31
+ chunkIndex?: number | null;
32
+ sectionTitle?: string | null;
33
+ text?: string;
34
+ [field: string]: unknown;
35
+ }
36
+ /** client-api `knowledgeBaseAgent.getDocumentOutlines`. */
37
+ export type KnowledgeOutlines = (knowledgeBaseId: string, documentIds: string[], token: string) => Promise<{
38
+ documents: KnowledgeOutline[];
39
+ }>;
40
+ /** client-api `knowledgeBaseAgent.getDocumentPassages`. */
41
+ export type KnowledgePassages = (knowledgeBaseId: string, documentId: string, options: {
42
+ from?: number;
43
+ limit?: number;
44
+ chunkIds?: string[];
45
+ }, token: string) => Promise<{
46
+ document: unknown | null;
47
+ passages: KnowledgePassage[];
48
+ next: number | null;
49
+ }>;
50
+ /** Where a section starts in a source. */
51
+ export interface SourceOutlineEntry {
52
+ /** The heading; for a source with none, the opening words of the page. */
53
+ title: string;
54
+ /** The page it starts on, from 1. */
55
+ page: number;
56
+ }
57
+ /** A passage a reference names, which is always shown. */
58
+ export interface CitedPassage {
59
+ /** The short ids of the references naming it. */
60
+ references: string[];
61
+ section: string | null;
62
+ text: string;
63
+ }
64
+ /** One thing the run's references point at. */
65
+ export interface Source {
66
+ /** Its short id, "s0"…: what the tool takes. */
67
+ id: string;
68
+ kind: "page" | "document";
69
+ title: string;
70
+ /** A page's address; never a knowledge base document's, which is behind the organization's sign-in. */
71
+ url: string | null;
72
+ /** The short ids ("r0"…) of the references pointing at it. */
73
+ references: string[];
74
+ /** Null when it can be read; else why not. */
75
+ unreadReason: string | null;
76
+ /**
77
+ * False for a page that is read on demand and has not been asked for yet:
78
+ * its size, pages and outline are not known, and whether it can be read is
79
+ * not either. True for everything else.
80
+ */
81
+ opened: boolean;
82
+ characters: number;
83
+ /** How many pages it is read in; 0 when it cannot be read or holds nothing. */
84
+ pageCount: number;
85
+ outline: SourceOutlineEntry[];
86
+ /** True when it has more sections than the outline lists. */
87
+ outlineTruncated: boolean;
88
+ /** True when the outline is page openings: the source has no headings. */
89
+ outlineFromOpenings: boolean;
90
+ /** The passages its references name that are still part of it. */
91
+ cited: CitedPassage[];
92
+ /** The sections its references named a passage in that is gone: where to look first. */
93
+ sectionHints: string[];
94
+ }
95
+ /** A run's sources, and how their pages are read. */
96
+ export interface SourceStore {
97
+ sources: Source[];
98
+ /** True when the references cite at least one knowledge base document. */
99
+ citesKnowledge: boolean;
100
+ /** The text of one page of a source, pages from 1. Throws on a page it does not have. */
101
+ readPage: (sourceId: string, page: number) => Promise<string>;
102
+ /**
103
+ * Reads a page that is read on demand, once, and fills in what it holds or
104
+ * why it could not be read. Answers the source; one already opened as it is.
105
+ * Throws on a source it does not have.
106
+ */
107
+ open: (sourceId: string) => Promise<Source>;
108
+ }
109
+ /** One read through the tool. */
110
+ export interface SourceRead {
111
+ /** The stage that read, as the caller named it. */
112
+ stage: string;
113
+ sourceId: string;
114
+ pages: number[];
115
+ characters: number;
116
+ }
117
+ /** What a run read through the tool, across its stages. */
118
+ export interface SourceRecord {
119
+ reads: SourceRead[];
120
+ /** The stages that asked for a page their reading limit had no room for. */
121
+ limitReached: string[];
122
+ }
123
+ /**
124
+ * What the store says it is doing, for the person watching the run: a line
125
+ * for the progress dialog and the lucide icon to show beside it. It names a
126
+ * source by its title, which is the title of a reference the person's own
127
+ * content carries; it never carries what was read, or a tool call's input.
128
+ */
129
+ export interface SourceProgress {
130
+ message: string;
131
+ icon: string;
132
+ }
133
+ /**
134
+ * Where the store reports what it is doing. It carries no percentage: the
135
+ * caller knows where its stage stands and adds it. What it throws is ignored:
136
+ * a progress line never stops a read.
137
+ */
138
+ export type OnSourceProgress = (update: SourceProgress) => void;
139
+ /** A new, empty record. */
140
+ export declare const newSourceRecord: () => SourceRecord;
141
+ /**
142
+ * Text divided into pages of at most `size` characters, each cut at the best
143
+ * boundary it has: before a markdown heading, else at a paragraph break, else
144
+ * after a sentence, else at a space, else at the size itself. Nothing is
145
+ * dropped: the pages joined are the text. A source need have no structure at
146
+ * all — a PDF can come back as one unbroken block.
147
+ * @param content The text
148
+ * @param size The most characters a page holds
149
+ */
150
+ export declare const splitIntoPages: (content: string, size?: number) => string[];
151
+ /**
152
+ * Prepares a run's sources: reads its pages, and fetches the outlines and the
153
+ * cited passages of its knowledge base documents. Nothing else of a document
154
+ * is fetched until a page of it is read.
155
+ *
156
+ * Which sources there are, and when a page is read, is the caller's to say:
157
+ *
158
+ * - `pages: "upFront"` (the default) reads every page before answering: for
159
+ * a run that writes from all its references, once.
160
+ * - `pages: "onDemand"` lists each page by title and url and reads it the
161
+ * first time it is opened (`store.open`, which the tool calls): for a run
162
+ * made many times over the same references, or over more pages than it
163
+ * will read (a judge ruling on one comment, a reviewer of a skill citing
164
+ * dozens). Until a page is opened its size is not known, so such a store
165
+ * never `fitsLimit` and is read through the tool.
166
+ * - `pages: "none"` leaves the pages out: no source is made of a WEB or
167
+ * PUBLICATION reference.
168
+ * - `documents: false` leaves the knowledge base documents out: no source
169
+ * is made of a STACKFACTOR reference, no knowledge base is asked, and none
170
+ * can stop the run.
171
+ *
172
+ * A reference left out keeps its short id: ids are positions in `references`.
173
+ *
174
+ * A page that cannot be read is a source with an `unreadReason`; so is a
175
+ * document the person may not open, or that is gone (the platform does not
176
+ * tell the two apart). A cited knowledge base that cannot be read at all —
177
+ * no token, a refusal, a failed call — throws a KnowledgeAccessError naming
178
+ * the documents, before any page is read.
179
+ *
180
+ * @param options `references` (the run's, as supplied: their index is their
181
+ * short id), `token` (the run's AGENT token), `outlines` and `passages`
182
+ * (client-api `knowledgeBaseAgent.getDocumentOutlines` and
183
+ * `getDocumentPassages`), `config` (supplies `tavilyAPIKey`),
184
+ * `usageTracker`, `pages` and `documents` (which sources, and when a page
185
+ * is read: see above), the sizes: `pageCharacters`, `pagePassages`,
186
+ * `maxPageSourceCharacters`, and `onProgress`: told, by title, which
187
+ * documents are being opened and which pages are being read, before each
188
+ * of those waits (also when a page read on demand is first opened)
189
+ * @throws KnowledgeAccessError When cited knowledge bases cannot be read
190
+ */
191
+ export declare const prepareSources: (options: {
192
+ references: unknown;
193
+ token: string | null | undefined;
194
+ outlines: KnowledgeOutlines;
195
+ passages: KnowledgePassages;
196
+ config?: any;
197
+ usageTracker?: UsageTracker | null;
198
+ pages?: "upFront" | "onDemand" | "none";
199
+ documents?: boolean;
200
+ pageCharacters?: number;
201
+ pagePassages?: number;
202
+ maxPageSourceCharacters?: number;
203
+ onProgress?: OnSourceProgress | null;
204
+ }) => Promise<SourceStore>;
205
+ /**
206
+ * Whether every source can go into the prompt whole: what they hold together
207
+ * is within `limit`. Judged from the outlines, before any document is fetched.
208
+ * Never with a page that is read on demand and not opened yet: what it holds
209
+ * is not known.
210
+ * @param store From `prepareSources`
211
+ * @param limit The stage's reading limit, in characters
212
+ */
213
+ export declare const fitsLimit: (store: SourceStore, limit?: number) => boolean;
214
+ /**
215
+ * Every readable source whole, for a prompt: only for a store that
216
+ * `fitsLimit`. Fetches every page of every document.
217
+ * @param store From `prepareSources`
218
+ * @returns `[{ id, references, title, url, text }]`
219
+ */
220
+ export declare const sourcesForPrompt: (store: SourceStore) => Promise<{
221
+ id: string;
222
+ references: string[];
223
+ title: string;
224
+ url: string | null;
225
+ text: string;
226
+ }[]>;
227
+ /**
228
+ * The sources as a prompt lists them when the model reads through the tool:
229
+ * what each is, how much it holds, who cites it, and where to look first.
230
+ * Unreadable ones are listed with why, so the model does not try them.
231
+ * @param store From `prepareSources`
232
+ */
233
+ export declare const sourceListForPrompt: (store: SourceStore) => Array<Record<string, unknown>>;
234
+ /**
235
+ * The passages the references name, for a prompt: always shown, whichever way
236
+ * the rest is read.
237
+ * @param store From `prepareSources`
238
+ */
239
+ export declare const citedPassagesForPrompt: (store: SourceStore) => {
240
+ source: string;
241
+ references: string[];
242
+ document: string;
243
+ section: string | null;
244
+ text: string;
245
+ }[];
246
+ /**
247
+ * The source tool for one stage: `list_sources`, `get_outline`, `read_pages`
248
+ * and `read_document`, over the run's store. It reads nothing else — no web,
249
+ * no search — and writes nothing but the record of what was read.
250
+ *
251
+ * A stage may read `limit` characters in all. A read that would pass it
252
+ * returns the whole pages that fit and says the limit is reached; a page is
253
+ * never cut.
254
+ *
255
+ * A page that is read on demand is read the first time any function but
256
+ * `list_sources` is asked for it; one that cannot be read answers why.
257
+ *
258
+ * @param store From `prepareSources`
259
+ * @param options `record` (shared across the run's stages), `stage` (this
260
+ * stage's name in the record), `limit` (default DEFAULT_READING_LIMIT),
261
+ * `onProgress` (told, by title, which source the stage is looking through
262
+ * or reading, and which pages, as it asks)
263
+ * @returns LangChain tool instances for the stage's tool list
264
+ */
265
+ export declare const sourceTools: (store: SourceStore, options: {
266
+ record: SourceRecord;
267
+ stage: string;
268
+ limit?: number;
269
+ onProgress?: OnSourceProgress | null;
270
+ }) => any[];
271
+ /** How much of a source a run read. */
272
+ export interface SourceUse {
273
+ source: Source;
274
+ pagesRead: number;
275
+ state: "unreadable" | "unopened" | "partial" | "full";
276
+ }
277
+ /**
278
+ * How much of each source was read, from the record.
279
+ * @param store From `prepareSources`
280
+ * @param record What the run read; null when everything was in the prompt,
281
+ * which counts as read in full
282
+ * @param stage Count only this stage's reads; all stages when not given
283
+ */
284
+ export declare const sourceUsage: (store: SourceStore, record: SourceRecord | null, stage?: string) => SourceUse[];
285
+ /**
286
+ * The readable sources a stage never opened: what a retry of the stage is
287
+ * told to read. A source whose only content is its cited passages, already in
288
+ * the prompt, is not among them.
289
+ * @param store From `prepareSources`
290
+ * @param record What the run read
291
+ * @param stage The stage
292
+ */
293
+ export declare const unconsultedSources: (store: SourceStore, record: SourceRecord, stage?: string) => Source[];
294
+ /** Something a person is told about how the sources were used. */
295
+ export interface SourceFinding {
296
+ type: "UNREADABLE" | "NOT_CONSULTED" | "ATTRIBUTED_UNREAD";
297
+ /** The short id of the reference it is about. */
298
+ reference: string;
299
+ /** The reference's title. */
300
+ title: string;
301
+ /**
302
+ * True on a finding about an unopened source when the stage ran out of its
303
+ * reading limit: the message then says so, since there was more to read
304
+ * than the stage could.
305
+ */
306
+ limitReached: boolean;
307
+ message: string;
308
+ }
309
+ /**
310
+ * What the person is told about the sources: one finding per reference whose
311
+ * source could not be read; and, when the model read through the tool, one
312
+ * per reference whose source was never opened — worded as an attribution to
313
+ * it when the content cites that reference. A source is flagged as unopened
314
+ * whatever the cause (Candin, 2026-11-18): when the stage ran out of its
315
+ * reading limit the finding says so, so the person knows why.
316
+ * @param store From `prepareSources`
317
+ * @param record What the run read; null when everything was in the prompt
318
+ * @param options `references` (as supplied, for their titles), `cited` (the
319
+ * short ids the content cites), `stage` (judge by this stage's reads)
320
+ */
321
+ export declare const sourceFindings: (store: SourceStore, record: SourceRecord | null, options?: {
322
+ references?: unknown;
323
+ cited?: unknown;
324
+ stage?: string;
325
+ }) => SourceFinding[];
326
+ declare const _default: {
327
+ DEFAULT_MAX_PAGE_SOURCE_CHARACTERS: number;
328
+ DEFAULT_PAGE_CHARACTERS: number;
329
+ DEFAULT_PAGE_PASSAGES: number;
330
+ DEFAULT_READING_LIMIT: number;
331
+ citedPassagesForPrompt: (store: SourceStore) => {
332
+ source: string;
333
+ references: string[];
334
+ document: string;
335
+ section: string | null;
336
+ text: string;
337
+ }[];
338
+ fitsLimit: (store: SourceStore, limit?: number) => boolean;
339
+ newSourceRecord: () => SourceRecord;
340
+ prepareSources: (options: {
341
+ references: unknown;
342
+ token: string | null | undefined;
343
+ outlines: KnowledgeOutlines;
344
+ passages: KnowledgePassages;
345
+ config?: any;
346
+ usageTracker?: UsageTracker | null;
347
+ pages?: "upFront" | "onDemand" | "none";
348
+ documents?: boolean;
349
+ pageCharacters?: number;
350
+ pagePassages?: number;
351
+ maxPageSourceCharacters?: number;
352
+ onProgress?: OnSourceProgress | null;
353
+ }) => Promise<SourceStore>;
354
+ sourceFindings: (store: SourceStore, record: SourceRecord | null, options?: {
355
+ references?: unknown;
356
+ cited?: unknown;
357
+ stage?: string;
358
+ }) => SourceFinding[];
359
+ sourceListForPrompt: (store: SourceStore) => Array<Record<string, unknown>>;
360
+ sourceTools: (store: SourceStore, options: {
361
+ record: SourceRecord;
362
+ stage: string;
363
+ limit?: number;
364
+ onProgress?: OnSourceProgress | null;
365
+ }) => any[];
366
+ sourceUsage: (store: SourceStore, record: SourceRecord | null, stage?: string) => SourceUse[];
367
+ sourcesForPrompt: (store: SourceStore) => Promise<{
368
+ id: string;
369
+ references: string[];
370
+ title: string;
371
+ url: string | null;
372
+ text: string;
373
+ }[]>;
374
+ splitIntoPages: (content: string, size?: number) => string[];
375
+ unconsultedSources: (store: SourceStore, record: SourceRecord, stage?: string) => Source[];
376
+ };
377
+ export default _default;
378
+ //# sourceMappingURL=sourceStore.d.ts.map