@stackfactor/agent-utils 1.13.3 → 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 (253) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +667 -23
  3. package/dist/cjs/agentProto.d.ts +13 -3
  4. package/dist/cjs/agentProto.d.ts.map +1 -1
  5. package/dist/cjs/agentProto.js +25 -4
  6. package/dist/cjs/backoff.d.ts +17 -0
  7. package/dist/cjs/backoff.d.ts.map +1 -0
  8. package/dist/cjs/backoff.js +26 -0
  9. package/dist/cjs/cancellation.d.ts +22 -0
  10. package/dist/cjs/cancellation.d.ts.map +1 -0
  11. package/dist/cjs/cancellation.js +36 -0
  12. package/dist/cjs/cli.d.ts +3 -0
  13. package/dist/cjs/cli.d.ts.map +1 -0
  14. package/dist/cjs/cli.js +85 -0
  15. package/dist/cjs/client.d.ts +11 -0
  16. package/dist/cjs/client.d.ts.map +1 -1
  17. package/dist/cjs/client.js +27 -0
  18. package/dist/cjs/const.d.ts +23 -0
  19. package/dist/cjs/const.d.ts.map +1 -1
  20. package/dist/cjs/const.js +23 -0
  21. package/dist/cjs/daemon.d.ts +94 -0
  22. package/dist/cjs/daemon.d.ts.map +1 -0
  23. package/dist/cjs/daemon.js +507 -0
  24. package/dist/cjs/daemonConfig.d.ts +45 -0
  25. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  26. package/dist/cjs/daemonConfig.js +148 -0
  27. package/dist/cjs/daemonEnv.d.ts +10 -0
  28. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  29. package/dist/cjs/daemonEnv.js +12 -0
  30. package/dist/cjs/durable/clientTool.d.ts +39 -0
  31. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  32. package/dist/cjs/durable/clientTool.js +90 -0
  33. package/dist/cjs/durable/index.d.ts +9 -0
  34. package/dist/cjs/durable/index.d.ts.map +1 -0
  35. package/dist/cjs/durable/index.js +16 -0
  36. package/dist/cjs/durable/journal.d.ts +218 -0
  37. package/dist/cjs/durable/journal.d.ts.map +1 -0
  38. package/dist/cjs/durable/journal.js +392 -0
  39. package/dist/cjs/durable/pause.d.ts +84 -0
  40. package/dist/cjs/durable/pause.d.ts.map +1 -0
  41. package/dist/cjs/durable/pause.js +241 -0
  42. package/dist/cjs/durable/resume.d.ts +27 -0
  43. package/dist/cjs/durable/resume.d.ts.map +1 -0
  44. package/dist/cjs/durable/resume.js +80 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  46. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  47. package/dist/cjs/durable/snapshotSaver.js +81 -0
  48. package/dist/cjs/durable/step.d.ts +28 -0
  49. package/dist/cjs/durable/step.d.ts.map +1 -0
  50. package/dist/cjs/durable/step.js +43 -0
  51. package/dist/cjs/index.d.ts +30 -7
  52. package/dist/cjs/index.d.ts.map +1 -1
  53. package/dist/cjs/index.js +28 -1
  54. package/dist/cjs/infrastructure.d.ts +50 -0
  55. package/dist/cjs/infrastructure.d.ts.map +1 -0
  56. package/dist/cjs/infrastructure.js +163 -0
  57. package/dist/cjs/langChain.d.ts +15 -3
  58. package/dist/cjs/langChain.d.ts.map +1 -1
  59. package/dist/cjs/langChain.js +986 -180
  60. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  61. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  62. package/dist/cjs/learningActivityMedia.js +861 -0
  63. package/dist/cjs/learningContentPlan.d.ts +105 -0
  64. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  65. package/dist/cjs/learningContentPlan.js +305 -0
  66. package/dist/cjs/learningContentThread.d.ts +184 -0
  67. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  68. package/dist/cjs/learningContentThread.js +407 -0
  69. package/dist/cjs/logger.d.ts +1 -0
  70. package/dist/cjs/logger.d.ts.map +1 -1
  71. package/dist/cjs/logger.js +17 -3
  72. package/dist/cjs/modelRates.d.ts +40 -0
  73. package/dist/cjs/modelRates.d.ts.map +1 -0
  74. package/dist/cjs/modelRates.js +76 -0
  75. package/dist/cjs/referenceContext.d.ts +4 -145
  76. package/dist/cjs/referenceContext.d.ts.map +1 -1
  77. package/dist/cjs/referenceContext.js +16 -251
  78. package/dist/cjs/retry.d.ts +64 -0
  79. package/dist/cjs/retry.d.ts.map +1 -0
  80. package/dist/cjs/retry.js +138 -0
  81. package/dist/cjs/runtimeContext.d.ts +8 -1
  82. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  83. package/dist/cjs/runtimeContext.js +3 -1
  84. package/dist/cjs/serve.d.ts +3 -2
  85. package/dist/cjs/serve.d.ts.map +1 -1
  86. package/dist/cjs/serve.js +32 -2
  87. package/dist/cjs/sourceStore.d.ts +378 -0
  88. package/dist/cjs/sourceStore.d.ts.map +1 -0
  89. package/dist/cjs/sourceStore.js +872 -0
  90. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  91. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  92. package/dist/cjs/stackfactorKnowledge.js +108 -44
  93. package/dist/cjs/tavily.d.ts +108 -4
  94. package/dist/cjs/tavily.d.ts.map +1 -1
  95. package/dist/cjs/tavily.js +242 -21
  96. package/dist/cjs/usage.d.ts.map +1 -1
  97. package/dist/cjs/usage.js +9 -15
  98. package/dist/cjs/version.d.ts +3 -0
  99. package/dist/cjs/version.d.ts.map +1 -0
  100. package/dist/cjs/version.js +5 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  102. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  103. package/dist/cjs/workflow/bookkeeping.js +75 -0
  104. package/dist/cjs/workflow/index.d.ts +13 -0
  105. package/dist/cjs/workflow/index.d.ts.map +1 -0
  106. package/dist/cjs/workflow/index.js +51 -0
  107. package/dist/cjs/workflow/limits.d.ts +52 -0
  108. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  109. package/dist/cjs/workflow/limits.js +62 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  111. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  112. package/dist/cjs/workflow/platformTransport.js +115 -0
  113. package/dist/cjs/workflow/retrying.d.ts +44 -0
  114. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  115. package/dist/cjs/workflow/retrying.js +82 -0
  116. package/dist/cjs/workflow/run.d.ts +195 -0
  117. package/dist/cjs/workflow/run.d.ts.map +1 -0
  118. package/dist/cjs/workflow/run.js +858 -0
  119. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  120. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  121. package/dist/cjs/workflow/testing/index.js +6 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  124. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  125. package/dist/cjs/workflow/transport.d.ts +219 -0
  126. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  127. package/dist/cjs/workflow/transport.js +19 -0
  128. package/dist/esm/agentProto.d.ts +13 -3
  129. package/dist/esm/agentProto.d.ts.map +1 -1
  130. package/dist/esm/agentProto.js +23 -3
  131. package/dist/esm/backoff.d.ts +17 -0
  132. package/dist/esm/backoff.d.ts.map +1 -0
  133. package/dist/esm/backoff.js +22 -0
  134. package/dist/esm/cancellation.d.ts +22 -0
  135. package/dist/esm/cancellation.d.ts.map +1 -0
  136. package/dist/esm/cancellation.js +27 -0
  137. package/dist/esm/cli.d.ts +3 -0
  138. package/dist/esm/cli.d.ts.map +1 -0
  139. package/dist/esm/cli.js +80 -0
  140. package/dist/esm/client.d.ts +11 -0
  141. package/dist/esm/client.d.ts.map +1 -1
  142. package/dist/esm/client.js +25 -1
  143. package/dist/esm/const.d.ts +23 -0
  144. package/dist/esm/const.d.ts.map +1 -1
  145. package/dist/esm/const.js +23 -0
  146. package/dist/esm/daemon.d.ts +94 -0
  147. package/dist/esm/daemon.d.ts.map +1 -0
  148. package/dist/esm/daemon.js +499 -0
  149. package/dist/esm/daemonConfig.d.ts +45 -0
  150. package/dist/esm/daemonConfig.d.ts.map +1 -0
  151. package/dist/esm/daemonConfig.js +142 -0
  152. package/dist/esm/daemonEnv.d.ts +10 -0
  153. package/dist/esm/daemonEnv.d.ts.map +1 -0
  154. package/dist/esm/daemonEnv.js +9 -0
  155. package/dist/esm/durable/clientTool.d.ts +39 -0
  156. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  157. package/dist/esm/durable/clientTool.js +82 -0
  158. package/dist/esm/durable/index.d.ts +9 -0
  159. package/dist/esm/durable/index.d.ts.map +1 -0
  160. package/dist/esm/durable/index.js +8 -0
  161. package/dist/esm/durable/journal.d.ts +218 -0
  162. package/dist/esm/durable/journal.d.ts.map +1 -0
  163. package/dist/esm/durable/journal.js +374 -0
  164. package/dist/esm/durable/pause.d.ts +84 -0
  165. package/dist/esm/durable/pause.d.ts.map +1 -0
  166. package/dist/esm/durable/pause.js +226 -0
  167. package/dist/esm/durable/resume.d.ts +27 -0
  168. package/dist/esm/durable/resume.d.ts.map +1 -0
  169. package/dist/esm/durable/resume.js +72 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  171. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  172. package/dist/esm/durable/snapshotSaver.js +77 -0
  173. package/dist/esm/durable/step.d.ts +28 -0
  174. package/dist/esm/durable/step.d.ts.map +1 -0
  175. package/dist/esm/durable/step.js +36 -0
  176. package/dist/esm/index.d.ts +30 -7
  177. package/dist/esm/index.d.ts.map +1 -1
  178. package/dist/esm/index.js +20 -4
  179. package/dist/esm/infrastructure.d.ts +50 -0
  180. package/dist/esm/infrastructure.d.ts.map +1 -0
  181. package/dist/esm/infrastructure.js +156 -0
  182. package/dist/esm/langChain.d.ts +15 -3
  183. package/dist/esm/langChain.d.ts.map +1 -1
  184. package/dist/esm/langChain.js +984 -179
  185. package/dist/esm/learningActivityMedia.d.ts +196 -0
  186. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  187. package/dist/esm/learningActivityMedia.js +807 -0
  188. package/dist/esm/learningContentPlan.d.ts +105 -0
  189. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  190. package/dist/esm/learningContentPlan.js +299 -0
  191. package/dist/esm/learningContentThread.d.ts +184 -0
  192. package/dist/esm/learningContentThread.d.ts.map +1 -0
  193. package/dist/esm/learningContentThread.js +364 -0
  194. package/dist/esm/logger.d.ts +1 -0
  195. package/dist/esm/logger.d.ts.map +1 -1
  196. package/dist/esm/logger.js +17 -3
  197. package/dist/esm/modelRates.d.ts +40 -0
  198. package/dist/esm/modelRates.d.ts.map +1 -0
  199. package/dist/esm/modelRates.js +68 -0
  200. package/dist/esm/referenceContext.d.ts +4 -145
  201. package/dist/esm/referenceContext.d.ts.map +1 -1
  202. package/dist/esm/referenceContext.js +16 -243
  203. package/dist/esm/retry.d.ts +64 -0
  204. package/dist/esm/retry.d.ts.map +1 -0
  205. package/dist/esm/retry.js +127 -0
  206. package/dist/esm/runtimeContext.d.ts +8 -1
  207. package/dist/esm/runtimeContext.d.ts.map +1 -1
  208. package/dist/esm/runtimeContext.js +3 -1
  209. package/dist/esm/serve.d.ts +3 -2
  210. package/dist/esm/serve.d.ts.map +1 -1
  211. package/dist/esm/serve.js +33 -3
  212. package/dist/esm/sourceStore.d.ts +378 -0
  213. package/dist/esm/sourceStore.d.ts.map +1 -0
  214. package/dist/esm/sourceStore.js +855 -0
  215. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  216. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  217. package/dist/esm/stackfactorKnowledge.js +101 -41
  218. package/dist/esm/tavily.d.ts +108 -4
  219. package/dist/esm/tavily.d.ts.map +1 -1
  220. package/dist/esm/tavily.js +237 -20
  221. package/dist/esm/usage.d.ts.map +1 -1
  222. package/dist/esm/usage.js +9 -15
  223. package/dist/esm/version.d.ts +3 -0
  224. package/dist/esm/version.d.ts.map +1 -0
  225. package/dist/esm/version.js +2 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  227. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  228. package/dist/esm/workflow/bookkeeping.js +67 -0
  229. package/dist/esm/workflow/index.d.ts +13 -0
  230. package/dist/esm/workflow/index.d.ts.map +1 -0
  231. package/dist/esm/workflow/index.js +10 -0
  232. package/dist/esm/workflow/limits.d.ts +52 -0
  233. package/dist/esm/workflow/limits.d.ts.map +1 -0
  234. package/dist/esm/workflow/limits.js +59 -0
  235. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  236. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  237. package/dist/esm/workflow/platformTransport.js +110 -0
  238. package/dist/esm/workflow/retrying.d.ts +44 -0
  239. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  240. package/dist/esm/workflow/retrying.js +73 -0
  241. package/dist/esm/workflow/run.d.ts +195 -0
  242. package/dist/esm/workflow/run.d.ts.map +1 -0
  243. package/dist/esm/workflow/run.js +850 -0
  244. package/dist/esm/workflow/testing/index.d.ts +3 -0
  245. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  246. package/dist/esm/workflow/testing/index.js +2 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  248. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  249. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  250. package/dist/esm/workflow/transport.d.ts +219 -0
  251. package/dist/esm/workflow/transport.d.ts.map +1 -0
  252. package/dist/esm/workflow/transport.js +16 -0
  253. package/package.json +11 -9
package/README.md CHANGED
@@ -4,13 +4,20 @@ Shared utilities for StackFactor AI agent services — LangChain helpers, struct
4
4
 
5
5
  ## Installation
6
6
 
7
+ Published to StackFactor's private Artifact Registry (`sf-devenv-npm-private`)
8
+ only; it is not on npmjs. Point the `@stackfactor` scope at the registry with
9
+ your gcloud credential first. Every StackFactor repo has `npm run ar-auth` for
10
+ this:
11
+
7
12
  ```bash
13
+ gcloud auth login
14
+ npm run ar-auth
8
15
  npm install @stackfactor/agent-utils
9
16
  ```
10
17
 
11
18
  ## Modules
12
19
 
13
- The package exports four modules:
20
+ The package's main modules:
14
21
 
15
22
  ```typescript
16
23
  import {
@@ -18,9 +25,15 @@ import {
18
25
  logger,
19
26
  errorHandling,
20
27
  constants,
28
+ workflow, // workflow.run: long-lived, multi-turn agent workflows
29
+ durable, // pausing inside an LLM tool loop (used within workflow.run turns)
21
30
  } from "@stackfactor/agent-utils";
22
31
  ```
23
32
 
33
+ It also exports `serve`, `runOnce`, `callAgent`, `recordUsage`, `stackfactorKnowledge`,
34
+ `referenceContext`, `sourceStore`, `retryTransient`, `learningActivityMedia`,
35
+ `learningContentPlan` and `learningContentThread`; see the sections below.
36
+
24
37
  ---
25
38
 
26
39
  ## `langChain`
@@ -32,15 +45,15 @@ Unified interface for running LLM prompts, managing LangChain agents, and genera
32
45
  Sends a prompt to an LLM and returns the response. Supports three execution modes:
33
46
 
34
47
  - **Agentic** (`config.agentic === true`) — creates and runs a LangChain agent with tools.
35
- - **Streaming** (`onProgressReport` provided) — streams the response with progress callbacks. Uses native `response_format` for OpenAI+schema, or NDJSON for other providers.
36
- - **Non-streaming** — direct invocation with JSON extraction.
48
+ - **Streaming** (`onProgressReport` provided) — streams the response with progress callbacks. Uses native `text.format` for OpenAI+schema, or NDJSON for other providers.
49
+ - **Non-streaming** — direct invocation with JSON extraction. The extractor reads JSON out of markdown fences and prose, unescapes a body quoted once too often (`{\"a\":1}` with literal backslashes, a JSON string holding JSON) — also when the escaped body holds raw line breaks or tabs, kept one of its string's two quotes (`{\"a\":1}"`), or sits inside prose or a fence — reads a body escaped only in part (`{"a":[],\"b\":\"c\"}`: each string is closed the way it opened, and a plain string is left as it is), removes invisible characters (BOM, zero-width marks) without touching non-ASCII text, and takes the array when the answer opens with one. What it still cannot read is reported with the parse reason and the code point of the character the parser stopped at. It repairs no structure: an answer with a bracket too many is not JSON, and is retried when a schema is given. When the answer was an escaped body, the message also says why the unescaped body failed — `; unescaped body (N characters): <parse reason>; character at position P: U+XXXX "c"; around position P: "…<60 characters each side>…"` — because the head-and-tail quote hides the middle: in production (2026-11-13) 20+ escaped ownership answers were retried with only the backslash at position 1 for a reason.
37
50
 
38
51
  When `expectsJsonResponse` is `true` (the default), JSON escape instructions are injected and the response is parsed. If a Zod `schema` is provided, the parsed result is validated.
39
52
 
40
53
  | Parameter | Type | Default | Description |
41
54
  | --------------------- | -------------------- | --------------- | -------------------------------------------------------------------------------------------------------- |
42
55
  | `modelName` | `string` | — | Model identifier: `"gpt-4o"`, `"claude-3-5-sonnet"`, `"gemini-1.5-pro"`, etc. |
43
- | `config` | `object` | — | API keys (`openAIAPIKey`, `anthropicAPIKey`, `googleAPIKey`), `temperature`, `agentic`, `recursionLimit`, `tavily`, `tavilyAPIKey` |
56
+ | `config` | `object` | — | API keys (`openAIAPIKey`, `anthropicAPIKey`, `googleAPIKey`), `temperature`, `reasoningEffort`, `agentic`, `recursionLimit`, `tavily`, `tavilyAPIKey` |
44
57
  | `prompt` | `string \| object[]` | — | Plain string or array of `{ role, content }` message objects |
45
58
  | `onProgressReport` | `function \| null` | `null` | Async callback receiving `{ message, progress }` updates |
46
59
  | `minPercent` | `number` | `0` | Lower bound for progress percentage |
@@ -105,7 +118,19 @@ Constructs a LangChain agent with a model, system prompt, and tools. When `onRep
105
118
 
106
119
  Executes a LangChain agent with a user prompt. Registers callbacks for `tool_start`, `agent_action`, and error events when `onProgress` is provided. Logs execution time on completion.
107
120
 
108
- A tool event's `message` is plain language for the progress bar: the web tools read "Searching the web", "Reading web pages", "Listing the pages of a site" and "Reading the pages of a site", and any other tool reads as its name in words (`lookup_record` → "Using lookup record"). It never carries the model's reasoning or the tool's input; the raw name and input stay on the event's `tool` and `input`.
121
+ A tool event's `message` is plain language for the progress bar: the web tools read "Searching the web", "Reading web pages", "Listing the pages of a site" and "Reading the pages of a site", the source tool's functions "Looking over the references", "Looking through a reference" and "Reading a reference", and any other tool reads as its name in words (`lookup_record` → "Using lookup record"). It never carries the model's reasoning or the tool's input; the raw name and input stay on the event's `tool` and `input`.
122
+
123
+ A web tool's event also names the icon the progress dialog shows while it runs (`icon`: `search`, `globe`, `map`, `file-search`); a tool of the agent's own names none, and the dialog keeps its own icon.
124
+
125
+ #### Progress icons
126
+
127
+ Any progress update may name a [lucide](https://lucide.dev/icons) icon, and the progress dialog shows it in front of the message until the next update:
128
+
129
+ ```js
130
+ onProgress({ progress: 40, message: "Drafting the outline", icon: "list-tree" });
131
+ ```
132
+
133
+ `icon` is the icon's lucide name in kebab-case (`"globe"`, `"file-search"`). An update without one, or with a name the app does not know, shows the dialog's own icon. A value that is not shaped like an icon name is dropped before it leaves the agent.
109
134
 
110
135
  | Parameter | Type | Default | Description |
111
136
  | ------------ | ------------------ | ------- | -------------------------------- |
@@ -133,6 +158,24 @@ const response = await langChain.runAIAgent(
133
158
  );
134
159
  ```
135
160
 
161
+ #### Sending results as they are ready
162
+
163
+ `onPartialResult(item)` is a global, like `onProgress`. It sends one item of the answer to the caller while the call is still running, so a long call can show its first items without waiting for the last:
164
+
165
+ ```js
166
+ for (const section of sections) {
167
+ onPartialResult(await write(section));
168
+ }
169
+ ```
170
+
171
+ `item` must be a value that can be sent as JSON; anything else (`undefined`, a circular object) throws a `TypeError` to the agent, and the call carries on. Nothing is sent once the caller has cancelled, and a job run ignores it. A partial result is a preview: the final result must repeat every item sent, because a caller that does not read partial results sees only the final one.
172
+
173
+ Three things to allow for when you send them:
174
+
175
+ - An item can reach the caller more than once, because a retry above your agent runs it again and sends the item again. Name each item with an id the caller can key on, so it can replace an item it already has.
176
+ - Read the global defensively: `typeof onPartialResult === "function"`. It is absent on an older host and `null` in the self-check.
177
+ - In a job it does nothing, so do not rely on a job's caller seeing partial items.
178
+
136
179
  ---
137
180
 
138
181
  ### `langChain.runPromptWithModelForImageGeneration(modelName, config, prompt, options?)`
@@ -163,6 +206,31 @@ const image = await langChain.runPromptWithModelForImageGeneration(
163
206
 
164
207
  ---
165
208
 
209
+ ### `langChain.runPromptWithModelForVideoGeneration(modelName, config, prompt, options?, usageTracker?)`
210
+
211
+ Generates one video clip and returns its bytes, never a link: every provider's link needs the API key that made it. Usage is counted in `seconds`.
212
+
213
+ | Model prefix | Provider | Status |
214
+ | -------------- | --------------------------------------- | -------------------------------------------------------------- |
215
+ | `gemini-omni-` | Google Gemini Omni, Interactions API | Current. `gemini-omni-1.2-flash` is Google's Veo replacement. |
216
+ | `veo-` | Google Veo, `predictLongRunning` | Shut down on the Gemini API (Veo 3.1 previews, 2026-10-22). |
217
+ | `sora-` | OpenAI Sora | Reported shut down by OpenAI (2026-09-24). |
218
+
219
+ **Omni options:** `aspectRatio` (`"16:9"` default, or `"9:16"`), `resolution` (`"360p"`, `"720p"` default, `"1080p"`, `"4k"`), `durationSeconds` (a whole number from 3 to 15, default 8), `pollTimeoutMs` (deadline for the whole generation, default 10 minutes). Omni has no negative prompt or person setting; those options are ignored.
220
+
221
+ **Returns:** `{ b64_json, mimeType, seconds, model }`.
222
+
223
+ ```typescript
224
+ const clip = await langChain.runPromptWithModelForVideoGeneration(
225
+ "gemini-omni-1.2-flash",
226
+ { googleAPIKey: "..." },
227
+ "A marble rolling along a wooden track",
228
+ { durationSeconds: 8 },
229
+ );
230
+ ```
231
+
232
+ ---
233
+
166
234
  ### `langChain.throwErrorIfNotSuccessful(response)`
167
235
 
168
236
  Guards that a response is a non-empty string. Throws an `INTERNAL_SERVER_ERROR` if not.
@@ -285,6 +353,48 @@ Which integration is asking is never yours to say: the platform puts a signed ru
285
353
  run's envelope (`request.runTicket`) and the helper sends it back with your token. You never touch
286
354
  it, and it cannot be used to read another integration's settings.
287
355
 
356
+ ## Run a pool daemon
357
+
358
+ `npx @stackfactor/agent-utils daemon` starts a pool daemon: it registers with the platform under a pool token, then reports in every `pollSeconds` until it is stopped.
359
+
360
+ ```bash
361
+ AGENT_POOL_TOKEN=sfp_… AGENT_POOL_BACKEND_URL=https://<your StackFactor backend> \
362
+ npx @stackfactor/agent-utils daemon --installation-name <name>
363
+ ```
364
+
365
+ **In this release the daemon registers and reports in but runs no agents** (it reports a capacity of 0). Workers come in the next release.
366
+
367
+ **Requirements.** Node.js 22.3 or later (`@stackfactor/client-api` requires it). The package installs from StackFactor's private Artifact Registry, not npmjs (see [Installation](#installation)), so the host running `npx` needs access to that registry. Whether the daemon will also be published anywhere else has not been decided.
368
+
369
+ | Flag | Variable | |
370
+ | --- | --- | --- |
371
+ | `--pool <token>` | `AGENT_POOL_TOKEN` | The pool token (required). Prefer the variable: a command-line argument is visible to other users of the host, and `--pool` prints a warning. |
372
+ | `--backend <url>` | `AGENT_POOL_BACKEND_URL` | The StackFactor backend that issued the pool token, http or https (required). **There is no default**: the token is sent only to the backend named here. The daemon logs its origin at start, and warns when it is plain `http:` on any host but `localhost`, `127.0.0.0/8` or `[::1]`, since the token would then travel in cleartext. A URL carrying credentials, a query or a fragment is refused. |
373
+ | `--installation-name <name>` | `AGENT_POOL_INSTALLATION` | Required for hosted and BYO pools. Names this installation of the daemon (a Helm release, a Docker host, a VM): every copy of one installation uses the same name, and the pool's page groups its daemons under it. 1-63 of `a-z`, `0-9` and `-`, alphanumeric at both ends. |
374
+ | | `AGENT_POOL_CLOUD`, `AGENT_POOL_REGION`, `AGENT_POOL_ACCOUNT`, `AGENT_POOL_CLUSTER` | Override infrastructure detection (`AGENT_POOL_CLOUD` is `gcp`, `aws`, `azure` or `other`). Detection asks only the link-local metadata address `169.254.169.254`. `AGENT_POOL_CLOUD=other` skips every metadata probe: use it to send no metadata traffic at all while still reporting the OS, architecture and orchestrator. |
375
+ | | `AGENT_POOL_REPORT_INFRASTRUCTURE=false` | Send the installation name only (`0`, `no` and `off` do the same). A value that is neither true nor false is refused, so a misspelt opt-out never goes on reporting. |
376
+
377
+ A flag wins over its variable. `agent-utils --help` prints the usage.
378
+
379
+ Only the flags and the environment the daemon was started with are read: **a `.env` file in the working directory supplies none of this**, so it can never name the backend the token is sent to. The token never appears in the daemon's output. Do not run it with `NODE_DEBUG=net` (or `NODE_DEBUG=*`): Node itself then prints every request's headers, the token among them.
380
+
381
+ What the daemon does with the platform's answers:
382
+
383
+ | Answer | The daemon |
384
+ | --- | --- |
385
+ | `403` (the pool is disabled) | Logs it and asks again every 60 s; it resumes by itself when the pool is enabled. |
386
+ | `404` on a claim (the platform no longer knows the daemon) | Registers again under the same installation name. |
387
+ | `401`, `400` | Exits `78` with the platform's reason: the token was revoked or has expired, or the registration is refused. |
388
+ | A network error, a `5xx`, a redirect | Tries again, backing off from 1 s to 15 s, for as long as it takes. A redirect is never followed with the token. |
389
+
390
+ | Exit code | Meaning |
391
+ | --- | --- |
392
+ | `0` | Stopped by SIGTERM or SIGINT, after deregistering (bounded to 5 s). A second signal, a second or more after the first, stops waiting for the deregister and exits at once. |
393
+ | `1` | An unexpected failure. Only the error's name is printed. |
394
+ | `64` | Usage: no command, or an unknown one. |
395
+ | `75` | The pool runs another version of agent-utils. The log line gives the command to restart on it: `npx @stackfactor/agent-utils@<version> daemon`. |
396
+ | `78` | The configuration or the token is wrong (no token, no backend, a malformed installation name, a token or registration the platform refuses). Restarting will not help. |
397
+
288
398
  ## The run lifecycle (job executions)
289
399
 
290
400
  An agent subscribed to a platform event with `runAs: job` is started as one Cloud Run job
@@ -310,11 +420,14 @@ What an agent used reaches the platform one way: the usage report. What a handle
310
420
 
311
421
  Every model call made through `langChain` and every Tavily call is counted for the request it ran in. `serve` and `runOnce` report what was counted once a minute while the handler runs, once more when it ends, and also when it throws. The agent prices nothing: it reports a model, a unit and an amount, and the platform applies its own rates and charges the tenant's AI credits.
312
422
 
313
- An agent that calls a provider without `langChain` counts the call itself:
423
+ **A model without a rate is never called.** What a model the platform has no rate for uses would be charged nothing, so before the first call to a model in a request, `langChain` and the Tavily tools ask the platform whether it has one. A request whose model has none fails with **402** before anything is spent, and one where the platform cannot be asked fails with **503**. A priced answer is kept for five minutes; an unpriced one is asked about again, so a model that is given a rate is callable at once. Outside a request, or in one with no token, nothing is charged and nothing is asked.
424
+
425
+ An agent that calls a provider without `langChain` asks first, and counts the call itself:
314
426
 
315
427
  ```typescript
316
- import { recordUsage } from "@stackfactor/agent-utils";
428
+ import { recordUsage, requirePricedModel } from "@stackfactor/agent-utils";
317
429
 
430
+ await requirePricedModel(model);
318
431
  const response = await anthropic.messages.create({ model, messages });
319
432
  recordUsage(model, "inputTokens", response.usage.input_tokens);
320
433
  recordUsage(model, "outputTokens", response.usage.output_tokens);
@@ -330,7 +443,190 @@ recordUsage(model, "outputTokens", response.usage.output_tokens);
330
443
  | `seconds` | Seconds of generated video |
331
444
  | `credits` | Credits of a metered service |
332
445
 
333
- `recordUsage` counts nothing outside a request, and nothing for an amount that is not a positive number. A report that fails is sent again twice under the same id, so it is charged once; one that still fails is logged and the run goes on.
446
+ `recordUsage` counts nothing outside a request, and nothing for an amount that is not a positive number. A report that fails for a reason that may pass (`retryTransient`: a 5xx, a rate limit, the network) is sent again twice under the same id, so it is charged once; one the platform refuses (a 4xx) is not sent again; what still cannot be sent is kept for the next report, or logged when there is none, and the run goes on.
447
+
448
+ ---
449
+
450
+ ## `workflow.run`
451
+
452
+ `workflow.run(handlers, options?)` returns an ordinary agent `main`, so `serve()` and `runOnce()`
453
+ run it like any agent. It owns the platform's workflow protocol: the lease, taking the inbox one
454
+ entry per turn, the end-of-turn saves, release / end / delete, letting go of a failed turn, and
455
+ (optionally) waiting a short while for a wait to resolve. You write the handlers:
456
+
457
+ ```typescript
458
+ import { workflow, serve } from "@stackfactor/agent-utils";
459
+
460
+ const main = workflow.run({
461
+ open: (input) => ({ create: true }), // which workflow, and may it be created
462
+ decide: ({ input, workflow }) => "run", // before the lease; must be total
463
+ turn: async ({ input, state, checkpoint, outbox }) => ({
464
+ state: { ...state, seen: true }, // the agent's own state
465
+ next: { wait: [/* WaitDecl */] }, // or {} to release, { end: true }, { delete: true }
466
+ result: { ok: true }, // the run's outcome when next.end
467
+ }),
468
+ onError: async ({ error, letGo }) => { await letGo(); },
469
+ send: async (entry) => { /* deliver one outbox entry; deduplicate on entry.key */ },
470
+ });
471
+ serve({ main });
472
+ ```
473
+
474
+ | Handler | What it is |
475
+ |---|---|
476
+ | `open(input)` | Picks the workflow the run's own input belongs to (`{ key?, create? }`). Default: key `""`, nothing created. Not consulted for a resume or queued-input run, which are bound to their workflow. An INTERACTIVE call is keyed by its run id. |
477
+ | `decide({ input, workflow })` | Runs **before** the lease with the workflow as read (or `null`) and answers `"run"`, `"ignore"`, `"reopen"`, `"create"` or `"delete"`. **It must be total**: a throw is logged and taken as `"run"`, so the input is decided again under the lease, where a failure is retried. |
478
+ | `turn({ input, decision, state, checkpoint, outbox, openWaits })` | One input, under the lease. Returns `{ state, next?, result? }`. `state` is the agent's state only (never the runner's bookkeeping). |
479
+ | `next` | `{ wait?, cancel?, contacts?, linger?, end?, delete? }`: waits to declare, waits to cancel, who is told of a halt, whether to wait for a quick resolution, and ending or deleting the workflow. `{}` releases. |
480
+ | `result` | The run's outcome when the turn ends the workflow. `main` returns `{ workflowId, outcome, turns, lingered, result }`; for an interactive call's rounds it returns the `result` itself, or nothing (the caller is then answered `queued`, or by its open tool wait). |
481
+ | `onError({ input, error, state, letGo })` | A turn threw. Default: let go, so the platform runs the input again from the last saved state. Errors from the platform carry the status and the platform's error code, never the agent token or the request body. |
482
+ | `send(entry)` | Delivers one outbox entry under the lease (`outbox.add({ key, ... })`); required once a turn adds one. The key is the same however often the turn runs, so receivers deduplicate. |
483
+
484
+ `checkpoint(state, { waits?, cancel?, contacts?, send? })` saves mid-turn.
485
+
486
+ Options: `linger: { maxMs, pollMs }` (wait after a turn for its waits to resolve; off unless
487
+ `maxMs` > 0 and never past the lease's `until`), `transport` (default `retrying(platformTransport(token))`),
488
+ `adapter` and `clock`.
489
+
490
+ A run whose lease is refused (`deferred`, `handled`, `halted`, `already-ended`, `missing`) ends
491
+ successfully with that outcome. For a bound run of an interactive call's workflow, or whose
492
+ workflow cannot be read, `main` returns nothing, so the platform answers the caller `queued`.
493
+
494
+ ### Testing: `workflow.testing.memoryTransport`
495
+
496
+ ```typescript
497
+ const mem = workflow.testing.memoryTransport();
498
+ const summary = await mem.execute(workflow.run(handlers, { transport: mem, clock: mem.clock }), message);
499
+ mem.snapshot(); // the workflow, its waits and checkpoint
500
+ mem.resolveWait(waitId, { answers }); // a person answers; returns the resume run to execute
501
+ ```
502
+
503
+ An in-process platform with the lease, inbox, waits, halting by the turn budget and rate, and
504
+ checkpoints; nothing reaches the network. `mem.settled(runId)` shows how `execute` settled a run.
505
+
506
+ ---
507
+
508
+ ## Pausing inside an LLM tool loop (`durable`)
509
+
510
+ A `workflow.run` turn can stop in the middle of an agentic `runPromptWithModel`, when the model
511
+ proposes a tool call that needs a person's approval or that only the caller's machine can run, and
512
+ go on from that point when the answer comes. Nothing is held while it waits: the turn saves a
513
+ **conversation checkpoint** (the paused LangGraph thread plus a journal of what the turn already
514
+ finished), releases with an `input` wait, and ends. The answer starts a run that loads the
515
+ checkpoint and runs **the same turn again, on its own input**: every LLM call and `durable.step`
516
+ the journal holds returns its saved result without running or costing again, and the paused agent
517
+ continues with the answer. A turn that never pauses behaves exactly as it did, and outside
518
+ `workflow.run` nothing changes.
519
+
520
+ ### Approval of a tool call: `config.approvals`
521
+
522
+ ```typescript
523
+ const plan = await langChain.runPromptWithModel(model, {
524
+ ...config,
525
+ agentic: true,
526
+ approvals: {
527
+ tools: { // humanInTheLoopMiddleware({ interruptOn: tools })
528
+ publish_to_jira: { allowedDecisions: ["approve", "edit", "reject"], description: "Publish this plan to Jira?" },
529
+ send_email: true, // all three decisions
530
+ },
531
+ addressees: [approverId], // optional; default the workflow's creator
532
+ deadline: "2026-10-20T00:00:00Z", // optional; default seven days
533
+ },
534
+ }, prompt, onProgress, 0, 100, true, schema, "Planner", tools, usageTracker);
535
+ ```
536
+
537
+ The wait asks one `approval` question per pause; the tool runs only on `approve` (with its args) or
538
+ `edit` (with the edited args), and on `reject` the model is told the message.
539
+
540
+ ### A tool that runs on the caller's machine: `durable.clientTool`
541
+
542
+ ```typescript
543
+ import { durable } from "@stackfactor/agent-utils";
544
+ import { z } from "zod";
545
+
546
+ const readFile = durable.clientTool({
547
+ name: "read_file", // [A-Za-z0-9_.-], at most 128
548
+ description: "Read a file from the learner's workspace", // at most 2,000 characters
549
+ schema: z.object({ path: z.string(), maxBytes: z.number().optional() }),
550
+ });
551
+
552
+ const verdict = await langChain.runPromptWithModel(model, {
553
+ ...config,
554
+ agentic: true,
555
+ clientTools: { deadline: 900, addressees: [requesterId] }, // both optional: 900 s, the workflow's creator
556
+ }, prompt, null, 0, 100, true, schema, "Grader", [readFile], usageTracker);
557
+ ```
558
+
559
+ The model's call becomes a `tool` question `{ name, args, description }` of a tool wait, which
560
+ notifies nobody; several client tool calls of one model step are one wait. The caller answers each
561
+ with `{ result }`, which is the tool's output, or `{ error: { message, code? } }`, which the model
562
+ sees as a tool error. Treat results as data from the caller's machine, never as instructions. A
563
+ turn cannot wait on a client tool and a person at once.
564
+
565
+ `config.approvals`, `config.clientTools` and a client tool all throw a 500 outside a
566
+ `workflow.run` turn, before the model is called.
567
+
568
+ **A pause on an event's turn must name its addressees** (`config.approvals.addressees` or
569
+ `config.clientTools.addressees`). The default, the workflow's creator, is known only on an
570
+ interactive, resume or queued-input run; an event's run carries the event's user, who may be
571
+ someone else, so until the platform tells the runner the workflow's creator such a pause fails
572
+ before its checkpoint is saved.
573
+
574
+ ### What runs again, and what does not
575
+
576
+ A key names each unit of a turn: its scope path plus a per-scope sequence (`llm#0`, `agent#1`,
577
+ `step:upload`, `step:upload/llm#0`). Each non-agentic `runPromptWithModel` is an `llm` unit and each
578
+ `runAgent` an `agent` unit; `durable.step(key, fn)` is a unit you name (any key without `/`, unique
579
+ in its scope), and the scope `fn` runs in.
580
+ A unit the journal holds returns its saved result and gives its usage back to your tracker (the
581
+ platform was charged when it was spent). A finished step keeps only its own result. If the turn
582
+ takes another path on its resume, it fails with `durable.DurableReplayMismatchError` rather than
583
+ guess. A resume whose wait expired or was cancelled is not replayed: it reaches your turn as a
584
+ `resume` input, and your turn decides what it means.
585
+
586
+ ```typescript
587
+ const ticket = await durable.step("ticket", () => jira.createTicket(draft), { usageTracker });
588
+ ```
589
+
590
+ **Rules for agent code**, between the start of a turn and a possible pause:
591
+
592
+ 1. Every side effect or paid call that is not an LLM call goes in `durable.step`, or is safe to
593
+ repeat. Quota consume in particular is not idempotent, and neither is a mid-turn
594
+ `checkpoint(state, { waits })` or `checkpoint(state, { send: true })`: the resumed turn runs it
595
+ again, declaring its waits a second time and sending its outbox again. Make such a checkpoint
596
+ after the turn's last possible pause, or keep what it declares and sends safe to repeat.
597
+ 2. Inside one scope, start units in the same order on every run; work whose start order depends on
598
+ timing goes in `durable.step` with an explicit key.
599
+ 3. Read time, randomness and environment data inside a step, or not at all, if the result changes
600
+ which units run.
601
+ 4. Step results are JSON. Return ids, not bytes: wrap "generate media + store it" in one step and
602
+ return the file id. A step returns the JSON copy of its result on the first run as well as on a
603
+ replay (a `Date` is a string both times). A result that is not JSON throws **before** it is
604
+ journaled, and `fn`'s side effect has already happened.
605
+ 5. **A step containing a pause re-runs its body up to the pause** on the resume: the step is only
606
+ journaled once it finishes. Put the pausing call last in the step, or keep what runs before it
607
+ safe to repeat.
608
+ 6. **Steps protect against a resume replay, not against a failed turn being re-run.** The journal
609
+ is saved only by a pause. A turn that throws (a step finished earlier in the same round, a
610
+ model call) is retried from the last saved state, and whatever it finished since the last
611
+ pause runs and costs again.
612
+
613
+ **Twenty calls per wait.** One wait asks at most 20 questions (`LIMITS.MAX_QUESTIONS_PER_WAIT`). When
614
+ the model proposes more tool calls than that, the first 20 are asked, and the rest stay paused and
615
+ are asked in the next round, once these are answered.
616
+
617
+ **A crash window on a resumed round.** A pause uploads the checkpoint (a PUT that *replaces* the
618
+ workflow's one checkpoint) before the turn's end-of-turn save declares the wait that names it. If a
619
+ resumed round crashes between the two, the re-queued resume still points at the checkpoint step it
620
+ was declared for, which has been replaced: it fails, and after the platform's `INPUT_MAX_ATTEMPTS`
621
+ the input is dropped as failed. The window is narrow (two calls) and the failure is loud, not
622
+ silent.
623
+
624
+ Also: let `durable.DurablePause` through. It is how the turn stops; a turn that catches it is paused
625
+ all the same and what it queued is dropped. Inside an agent's tools nothing is journaled (the agent
626
+ keeps what its tools did), but a tool that was interrupted runs again from its start, so put nothing
627
+ before its `interrupt()` that must not run twice. An agent you build yourself pauses when its
628
+ checkpointer is a `durable.SnapshotSaver`: `createAgent(name, model, system, tools, null, config,
629
+ tracker, { checkpointer: new durable.SnapshotSaver(), middleware })`, one saver per agent per turn.
334
630
 
335
631
  ---
336
632
 
@@ -422,46 +718,391 @@ A model that cannot tell it received half a regulation will reason over the half
422
718
  - Every URL `web_extract` asked Tavily for is on `usageTracker.attemptedUrls`, each once, whether Tavily could read it or not; a URL `allowedUrls` refused was never asked for and is not there. `webSearchSources` holds what Tavily answered, under the address it answered with; `attemptedUrls` is what the run tried to read, so a caller can check a model's claim that it read a page.
423
719
  - Per-URL failures are surfaced in the tool result instead of being dropped, so a fetch failure is not mistaken for an absence of content.
424
720
  - Tool calls honour the caller's abort signal, so a cancelled run stops paying for in-flight crawls.
721
+ - A cancelled request stops, and says so. Once the request's signal is aborted (its caller cancelled the call, or the call's stream broke), no Tavily call and no model call is started, one in flight ends, and each fails with a 400 `Request cancelled by caller` (`src/cancellation.ts`), in the plain, streaming and agentic model paths alike. A link check under a cancelled request is not a check that failed: its links are not counted as unchecked, nothing is waited for or asked again, and no `LinksNotCheckedError` is thrown.
425
722
 
426
723
  ### Checking that cited links resolve
427
724
 
428
- `checkUrlsReachable(urls, config, usageTracker?)` returns the URLs, exactly as passed, that Tavily could fetch. Use it in place of requesting a link yourself. Cited links come from web pages anyone can publish, so a link, its redirects or its DNS can point inside StackFactor's network; a request this process sends would go there through StackFactor's own egress addresses. Tavily fetches from its own infrastructure.
725
+ `unreachableUrls(urls, config, usageTracker?, options?)` answers the cited links that are dead, each exactly as passed. Use it in place of requesting a link yourself. Cited links come from web pages anyone can publish, so a link, its redirects or its DNS can point inside StackFactor's network; a request this process sends would go there through StackFactor's own egress addresses. Tavily fetches from its own infrastructure.
726
+
727
+ ```js
728
+ const { unreachableUrls } = require("@stackfactor/agent-utils");
729
+
730
+ const dead = await unreachableUrls(references.map((r) => r.url), config, usageTracker);
731
+ const kept = references.filter((r) => !r.url || !dead.has(r.url));
732
+ ```
733
+
734
+ - A link whose check did not run (its Tavily call failed, or the config has no `tavilyAPIKey`) is checked again with the others like it, after each of `RETRY_WAITS` (`options.waits`, `options.sleep`).
735
+ - One still unchecked after that throws `LinksNotCheckedError`: `unchecked`, `total`, `code` 503, and a message that is the coded JSON an agent's failure carries, so `serve` answers the person "The cited links could not be checked (n of m). Try again shortly." Nothing is dropped as dead for a check that did not run.
736
+
737
+ `unreachableUrls` is built on `checkUrls`, for a caller that wants the three answers itself. `checkUrls(urls, config, usageTracker?)` asks Tavily to fetch the URLs and answers three sets, each URL exactly as passed: `reachable`, `unreachable` and `unchecked`.
429
738
 
430
739
  ```js
431
- const { checkUrlsReachable } = require("@stackfactor/agent-utils");
740
+ const { checkUrls } = require("@stackfactor/agent-utils");
432
741
 
433
- const live = await checkUrlsReachable(references.map((r) => r.url), config, usageTracker);
434
- const kept = references.filter((r) => !r.url || live.has(r.url));
742
+ const check = await checkUrls(references.map((r) => r.url), config, usageTracker);
435
743
  ```
436
744
 
437
745
  - Only `http:` and `https:` URLs are sent, 20 per call (Tavily's limit), at basic depth: 1 credit per 5 URLs fetched, failed ones free. Credits are billed like any Tavily call; the URLs are not added to `webSearchSources`.
438
- - A URL Tavily lists under `failed_results` is unreachable. A batch whose call fails, or a config without `tavilyAPIKey`, confirms none of its URLs. It never throws.
746
+ - `unreachable`: a URL Tavily lists under `failed_results`, or one that is no `http:` or `https:` URL.
747
+ - `unchecked`: the URLs of a batch whose call failed, or every web URL when the config has no `tavilyAPIKey`. Nothing is known about these links. Do not drop them as dead: one failed call would take every citation with it. It never throws.
748
+ - `checkUrlsReachable(urls, config, usageTracker?)` is deprecated. It returns only the `reachable` set, so its caller cannot tell a dead link from an unchecked one.
439
749
  - No `config.tavily` or `agentic` is needed: it calls Tavily directly, not through the model.
440
750
 
441
751
  ---
442
752
 
443
- ## Reading references (`referenceContext`)
753
+ ## References and the unreadable-knowledge error (`referenceContext`)
444
754
 
445
- An agent reading a skill's (or a microskill's, a question's) references gathers what they point at once, with `referenceContext.gatherReferenceContext({ references, queries, search, token, topK?, maxPassages?, maxPages? })`:
755
+ Reading what references point at is `sourceStore`'s work ([below](#reading-sources-a-page-at-a-time-sourcestore)). `referenceContext` keeps what every reading agent shares: how references are shown to a model and stored, and the error a run stops with.
446
756
 
447
- - **pages**: WEB and PUBLICATION references with an http(s) url, each `{ id: "r<N>", title, url }`, opened by the model through Tavily `extract`. All of them by default; `maxPages` keeps the first N in reference order.
448
- - **passages**: the passages of the knowledge base documents STACKFACTOR references cite, searched under the run's token (client-api `knowledgeBaseAgent.search`). A passage names the references citing its chunk (`knowledgeBase.chunkId`); when none does, every reference citing its document. The best-ranked 40 are kept (`maxPassages`).
757
+ - `referencesForModel(references)` shows each reference under its short id `r<N>` (N its index in the supplied list); a STACKFACTOR reference loses its ids and its url. `referenceForModel` does the same for one.
758
+ - `citedReferences(ids, supplied, origin?)` maps the short ids a model cited back to the supplied references, stored (`toStoredReference`).
449
759
 
450
- **A cited knowledge base that cannot be read stops the run.** With no token, or when the person may not open a cited knowledge base (401, 403, 404) or its search fails, it throws `KnowledgeAccessError` (exported from the package and from `referenceContext`). A search that fails for any reason other than access is tried once more, 200 ms later, before it counts as failed; a refusal is not asked again.
760
+ **A cited knowledge base that cannot be read stops the run.** With no token, or when the person may not open a cited knowledge base (401, 403, 404) or reading it fails, `sourceStore.prepareSources` throws `KnowledgeAccessError` (exported from the package and from `referenceContext`).
451
761
 
452
762
  | Field | Value |
453
763
  | ----------- | -------------------------------------------------------------------------------------------- |
454
764
  | `code` | `403` when every skipped knowledge base refused the person (or there was no token), else `502` |
455
765
  | `documents` | The titles of the STACKFACTOR references citing those knowledge bases, each once |
456
- | `skipped` | The knowledge bases that could not be searched, and why |
457
- | `message` | `The knowledge base documents this content cites could not be read with your access: "A", "B".` (502: `…could not be read: the knowledge base search failed for "A".`) |
766
+ | `skipped` | The knowledge bases that could not be read, and why |
767
+ | `message` | `The knowledge base documents this content cites could not be read with your access: "A", "B".` (502: `…could not be read: reading the knowledge base failed for "A".`) |
768
+
769
+ The agent answers with `code` and `message`, so the person sees which documents could not be read. An agent that does not catch it answers the same: `serve` and `runOnce` turn an uncaught `KnowledgeAccessError` (known by its `name`, so a second copy of this package counts too) into an error with its own `code` and `message`, not a 500. Grounding from skill coverage (`stackfactorKnowledge.retrievePassages`) still skips a knowledge base it cannot read.
458
770
 
459
- The agent answers with `code` and `message`, so the person sees which documents could not be read. An agent that does not catch it answers the same: `serve` and `runOnce` turn an uncaught `KnowledgeAccessError` (known by its `name`, so a second copy of this package counts too) into an error with its own `code` and `message`, not a 500. A search that works and finds nothing is not an error: the run gets no passages and the `none` guidance. Grounding from skill coverage (`stackfactorKnowledge.retrievePassages`) still skips a knowledge base it cannot read.
771
+ The older reader (`gatherReferenceContext`, `toolsFor`, `composeSourceInstructions`, `referencePassagesForPrompt`, `sourceGuidanceFrom`, `REFERENCE_PASSAGES_KEY`) was removed in 1.29.0: every agent reads through `sourceStore`.
460
772
 
461
- `referenceContext.toolsFor(context)` gives the run its tools: `{ tavily: { tools: ["extract"], allowedUrls } }` when there are pages (their urls), else `{}`. Spread it after `tavily: undefined`, so `web_extract` reads only the referenced pages.
773
+ **What a passage is for, and what it covers.** Ingestion labels each passage with a role (`passageRole`: `teaching` or `logistics`) and writes it a one-line title from its content (`passageTitle`); the platform's search returns both (backend-core #1058), and a passage ingested before that carries neither.
774
+
775
+ - `retrievePassages` leaves out a `logistics` passage (an agenda, a schedule, a syllabus, a title slide: it matches any query on the course's subject and teaches nothing). Every grounding search asks the platform to leave them out itself (`excludePassageRoles: ["logistics"]`, backend-core #1065), so the search still answers `topK` passages: dropped only after the search, they took more than half of each answer with them (7 of 10 searches of 8 kept none, 2026-11-16). A platform that does not know the option answers them all the same, so any that come back are dropped here and counted: `[Knowledge Base] <n> logistics passage(s) the search answered were left out: …`. `includeLogistics: true` asks for them and keeps them. A passage with no role is kept.
776
+ - `retrievePassages` takes `microSkills`: names of the knowledge bases' microskills, as their microskill lists name them. Every search is asked to put the passages ingestion labelled with one of them first (backend-core #1072), and they rank first in the answer too, each marked `labelled: true`, ahead of every other passage whatever its score (one the search's two legs missed has none). Searched by name alone, a microskill's own passages lost to ones sharing words with the skill's name (2026-11-17). A platform that does not know the option answers as before and marks nothing.
777
+ - `passageHeading(passage)` is the title written from the content, else the document's own heading (`sectionTitle`). A slide's own heading is often a time allowance ("Total Time: 40 minutes") or the heading of the slide before. It is what `passagesForPrompt` shows as `section`, and what `referencesFor` writes as the reference's `description`, so a reader can match a passage to its citation.
778
+ - A reference's pointer keeps the document's own heading (`knowledgeBase.sectionTitle`): that, not the description, tells two passages of one section from two sections.
462
779
 
463
780
  ---
464
781
 
782
+ ## Reading sources a page at a time (`sourceStore`)
783
+
784
+ What references point at has no upper size: one PDF is over a million characters, a knowledge base document tens of thousands of passages. `sourceStore` lets a run read them whatever their size.
785
+
786
+ **Prepare, once per run, before any model call:**
787
+
788
+ ```typescript
789
+ import { sourceStore } from "@stackfactor/agent-utils";
790
+ import { knowledgeBaseAgent } from "@stackfactor/client-api";
791
+
792
+ const store = await sourceStore.prepareSources({
793
+ references, // as supplied: a reference's index is its short id, r0, r1…
794
+ token: request.authToken, // the run's AGENT token
795
+ outlines: knowledgeBaseAgent.getDocumentOutlines,
796
+ passages: knowledgeBaseAgent.getDocumentPassages,
797
+ config, // supplies tavilyAPIKey
798
+ usageTracker,
799
+ });
800
+ ```
801
+
802
+ - **A page source** is a WEB or PUBLICATION reference with an http(s) url. It is read once, in full, by Tavily (`readUrls`, which has no paged read), held outside the model's context and divided into pages of about 20,000 characters at the best boundary each has: a heading, else a paragraph break, else a sentence end.
803
+ - **A document source** is a knowledge base document STACKFACTOR references cite. Only its outline is fetched up front (client-api `getDocumentOutlines`, 1.39.0); its pages, 40 positions each, are fetched from the platform when they are read, each once. The passages its references name (`knowledgeBase.chunkId`) are fetched too and are always shown (`citedPassagesForPrompt`). One that is gone, because the document was ingested again, leaves its section as where to look first (`sectionHints`).
804
+
805
+ Each source is `{ id: "s<N>", kind, title, url, references, unreadReason, characters, pageCount, outline, cited, sectionHints }`. A source with no headings is outlined by the opening words of each page (`outlineFromOpenings`).
806
+
807
+ **A cited knowledge base that cannot be read stops the run**: `KnowledgeAccessError`. **A page that cannot be read does not**: it is a source with an `unreadReason`, and a finding (below). So is a document the person may not open or that is gone, which the platform does not tell apart, and a page past `maxPageSourceCharacters` (5,000,000).
808
+
809
+ **Then, per stage that reads sources:**
810
+
811
+ ```typescript
812
+ if (sourceStore.fitsLimit(store, limit)) {
813
+ // Everything goes into the prompt, and no tool is needed.
814
+ input.sources = await sourceStore.sourcesForPrompt(store);
815
+ } else {
816
+ input.sources = sourceStore.sourceListForPrompt(store);
817
+ tools.push(...sourceStore.sourceTools(store, { record, stage: "write", limit }));
818
+ }
819
+ input.citedPassages = sourceStore.citedPassagesForPrompt(store);
820
+ ```
821
+
822
+ `record` is one `sourceStore.newSourceRecord()` for the run, shared by its stages. `limit` is how many characters the stage may read through the tool (200,000 by default): set it from the context of the stage's model.
823
+
824
+ **The tool** has four functions and no other. None searches, opens a link or writes.
825
+
826
+ | Function | What it does | Recorded |
827
+ | --------------- | --------------------------------------------------------------------------------------------------------- | -------- |
828
+ | `list_sources` | Every source: id, title, kind, size, pages, the references citing it, whether it could be read | No |
829
+ | `get_outline` | One source's sections and the page each starts on | No |
830
+ | `read_pages` | Pages of a source, by number or by section title, at most 10 a call; each headed "page N of M" | Yes |
831
+ | `read_document` | A whole source, when it fits what is left of the limit; otherwise it points at the outline | Yes |
832
+
833
+ A read returns whole pages only. One that would pass the stage's limit returns the pages that fit and says the limit is reached.
834
+
835
+ **Afterwards:**
836
+
837
+ - **Telling the person what is being read.** `prepareSources` and `sourceTools` take `onProgress`, a function given `{ message, icon }` each time the store is about to open or read something: `Opening "Runbook"` before the knowledge base is asked, `Reading "A", "B" and 2 more` before the pages are read, and through the tool `Looking over the references`, `Looking through "Rulebook"`, `Reading "Rulebook", pages 3 to 5 of 12`. A source is named by its title (a reference's own, cut at 80 characters); nothing that was read and no tool input is in the line. It carries no percentage, so pass it through with the stage's own: `onProgress: (update) => onProgress({ ...update, progress: 20 })`. What the function throws is ignored. Without it, the four tool functions still read in plain words in the tool events of `runPromptWithModel` ("Reading a reference").
838
+ - `sourceStore.unconsultedSources(store, record, stage)`: the readable sources the stage never opened. An agent retries the stage once, telling the model to read them.
839
+ - **Which sources, and when a page is read.** `prepareSources` takes `pages` and `documents`:
840
+ - `pages: "upFront"` (default): every page is read before it answers. For a run that writes from all its references, once.
841
+ - `pages: "onDemand"`: each page is listed by title and url and read the first time it is opened (`store.open(id)`, which every tool function but `list_sources` calls). For a run made many times over the same references, or over more pages than it will read: a judge ruling on one comment, a reviewer of a skill citing dozens. A source not opened has `opened: false` and no size, so such a store never `fitsLimit`: it is read through the tool. A page that cannot be read says so when it is opened.
842
+ - `pages: "none"`, `documents: false`: that kind of reference is no source at all; with `documents: false` no knowledge base is asked and none can stop the run. References left out keep their short ids.
843
+ - `sourceStore.sourceFindings(store, record, { references, cited, stage })`: what the person is told, each `{ type, reference, title, limitReached, message }`. `UNREADABLE` for every reference whose source could not be read; and, when the model read through the tool, `NOT_CONSULTED` for one whose source was never opened, or `ATTRIBUTED_UNREAD` when the content cites it (`cited`: the short ids). Pass `null` as the record when everything was in the prompt: only `UNREADABLE` applies. A source opened at any page counts as consulted. A source left unopened is a finding whatever the cause: when the stage ran out of its reading limit, `limitReached` is true and the message says so.
844
+ - `sourceStore.sourceUsage(store, record, stage?)`: pages read of each source, and `unreadable`, `unopened`, `partial` or `full`.
845
+
846
+ ---
847
+
848
+ ## Retrying a platform call (`retryTransient`)
849
+
850
+ One rule for every platform call an agent makes (Candin, 2026-11-09): a failure that may pass is retried, a failure that will not pass is reported at once, and nothing is hidden.
851
+
852
+ ```typescript
853
+ import { retryTransient, RETRY_WAITS, isTransient, isNetworkFailure } from "@stackfactor/agent-utils";
854
+
855
+ const breaker = new Set<string>(); // one per run
856
+ const coverage = await retryTransient("skill coverage", () => knowledgeBase.getSkillCoverage(name, token));
857
+ const list = await retryTransient(`the microskill list of ${kbId}`, () => knowledgeBase.listMicroSkills(kbId, name, token), {
858
+ breaker,
859
+ key: kbId,
860
+ });
861
+ ```
862
+
863
+ `retryTransient(what, call, options?)` makes `call` and, while it fails for a reason that may pass, makes it again after each of `options.waits` (default `RETRY_WAITS`: 2 s, then 6 s — three attempts), logging each retry at `warn` (`retry: <what> failed (<message>) on attempt 1 of 3; trying again in 2000 ms`). What still fails after the last wait is rethrown unchanged: the caller reports it. `isTransient(error)` is the rule:
864
+
865
+ | Failure | Retried |
866
+ | --- | --- |
867
+ | 408, 425, 429, 500, 502, 503, 504 (on `error.status` or `error.response.status`) | yes |
868
+ | No status, and the network failed it: `code` `ECONNRESET`, `ECONNREFUSED`, `ETIMEDOUT`, `ENOTFOUND`, `EAI_AGAIN` or `EPIPE`, a message saying network, timeout, socket or `fetch failed`, or fetch's `TypeError: terminated` (the connection dropped while the answer was being read) | yes |
869
+ | 401, 403, 404, 422 and every other 4xx: the platform's answer | no |
870
+ | A `TypeError` (other than fetch's `fetch failed` and `terminated`), an `Error` with no status and no network signature: a fault in the code | no |
871
+
872
+ `isNetworkFailure(error)` is the second row alone: a failure with no status that may pass. `langChain.runPromptWithModel` and `langChain.runAgent` make a model call again on it, after each of `RETRY_WAITS`, logging `Connection to "<model>" dropped (<message>), trying again in 2000 ms (1/2)` at `warn`: a stream cut mid-answer is discarded and asked for again (an agent run restarts from its prompt, or continues its checkpointed thread), and what still fails after the second retry is rethrown unchanged. A failure that carries a status is left to the rate-limit wait or thrown at once, as before.
873
+
874
+ Options:
875
+
876
+ - `breaker` + `key`: a `Set` shared by the calls of one run and the key the call belongs to (a knowledge base id). A key whose retries a call has spent is added; its next calls are made once, with no retry and no wait, so a knowledge base that is down costs the run its retries once, not once per search. The first call it answers takes it out again. With no `key`, the breaker is left alone.
877
+ - `stopWhen`: asked after each failure and after each wait; when true (the knowledge base refused the person meanwhile), the failure is passed on at once.
878
+ - `sleep`: how to wait, for tests.
879
+
880
+ `stackfactorKnowledge.retrievePassages` retries its searches with it, and takes `retry: { waits, breaker, sleep }` to share a run's breaker. The workflow runner's transport keeps its own policy (`workflow.retrying`): its spec never retries a 4xx.
881
+
882
+ ---
883
+
884
+ ## The media of a learning activity (`learningActivityMedia`)
885
+
886
+ The agent that writes a video or a text activity also makes its media. The
887
+ activity is written with prompts where its images, clips and Motion Graphics go
888
+ and, for a video, a narration script per scene. Once it is written,
889
+ `generateActivityMedia` generates each file, stores it as media of the activity
890
+ and gives the element the id of what was stored (`{ _id, set: true }`). The
891
+ content never carries a file: whoever shows the activity downloads each one by
892
+ its id. The caller (the editor, the learning content job, another agent)
893
+ generates no media itself.
894
+
895
+ ```typescript
896
+ import { learningActivityMedia } from "@stackfactor/agent-utils";
897
+
898
+ const summary = await learningActivityMedia.generateActivityMedia(activity, {
899
+ field: "videoContent", // or "textContent"
900
+ target: { learningContentId, microSkillId, learningActivityId },
901
+ token: request.authToken,
902
+ choices: { videoClipsEnabled: true, motionGraphicsEnabled: true },
903
+ signal,
904
+ onProgress: ({ done, total, message }) => {},
905
+ });
906
+ ```
907
+
908
+ - **`target`** is where the files are stored. `microSkillId` is the skill's
909
+ micro skill id. A caller that names no target gets the activity with its
910
+ prompts, as before: check with `isActivityMediaTarget`.
911
+ - **`choices`** say which media are made and by which integration. Each of
912
+ `imageIntegrationId`, `videoClipIntegrationId` and `motionGraphicIntegrationId`
913
+ is an integration id, `"NONE"` to skip that kind, or absent for the platform's
914
+ default. Absent, images are made, and clips and films only when
915
+ `videoClipsEnabled` / `motionGraphicsEnabled` is true. `narration: false`
916
+ leaves a video's audio to its first play.
917
+ - **Order**: films and images together, then clips, then a video's narration. A
918
+ film's narration replaces its scene's, so narration and clip lengths follow it.
919
+ - **Failures** fail nothing. An element whose file could not be made keeps its
920
+ prompt; the summary lists it in `failed`, with counts per kind.
921
+ - Every generation goes through `contentGenerator.generateContent` and every
922
+ file through the learning content media routes, with the run's token.
923
+ - Images are re-encoded to JPEG when the agent has `sharp` installed, and
924
+ stored as generated otherwise.
925
+
926
+ ### Recording some scenes again: `prepareScenesNarration`
927
+
928
+ When a few lines of a video change after it was made (its two thread lines, for
929
+ example), the audio of the scenes they sit in is stale. `prepareScenesNarration`
930
+ stores those scenes' audio again, each from all its lines, and generates nothing
931
+ else.
932
+
933
+ ```typescript
934
+ const summary = await learningActivityMedia.prepareScenesNarration(
935
+ activity, // { videoContent }, changed in place
936
+ [firstSceneId, lastSceneId],
937
+ { field: "videoContent", target, token: request.authToken, signal },
938
+ );
939
+ // summary.narration: { prepared, deferred, silent }
940
+ ```
941
+
942
+ - A scene id that matches no scene is ignored. A named scene that says nothing
943
+ counts as `silent`.
944
+ - `choices` is not read: the caller asked for these scenes.
945
+ - What the scenes cost is **added** to the video's stored `audioUsage`. Its
946
+ `scenes` stays the number of scenes of the last whole preparation.
947
+ `generateActivityMedia` still replaces `audioUsage` with what it prepared.
948
+ - Notes, retries and cancellation work as in `generateActivityMedia`.
949
+
950
+ ## The learning content plan (`learningContentPlan`, `learningContentThread`)
951
+
952
+ A learning content plan threads the lessons of a course together: one
953
+ through-line, a role for each lesson, the terms each lesson owns and the terms
954
+ it builds on. The planner agent writes the plan. Each lesson agent is given its
955
+ lesson's part of it, a **plan context**, and writes two **thread lines**: an
956
+ opening that places the lesson, and a closing that hands on.
957
+
958
+ These two modules hold the rules, so the three agents cannot disagree on them.
959
+ Two rules of their own:
960
+
961
+ - **An agent's instructions for a step stay in its `config.yaml`**, as every
962
+ prompt does. This package holds no prompt text.
963
+ - **The rules reach the model as data** in the user message
964
+ (`threadRulesForPrompt()`), from the same constants the checks use.
965
+
966
+ ### A planner writes a new plan
967
+
968
+ ```typescript
969
+ import { langChain, learningContentPlan } from "@stackfactor/agent-utils";
970
+
971
+ // planSchema is structure only, so every provider's structured output takes
972
+ // it; each limit is a refinement, which the model call retries on.
973
+ const answer = await langChain.runPromptWithModel(
974
+ model, { ...config, agentic: false, tavily: undefined }, messages,
975
+ null, 0, 100, true, learningContentPlan.planSchema, "Plan writer",
976
+ );
977
+ // Parse again: the string the call answers keeps keys the schema does not know.
978
+ const plan = learningContentPlan.planSchema.parse(JSON.parse(answer));
979
+ // The fit with the skill needs the skill's order, which only the caller has.
980
+ const problems = learningContentPlan.planProblems(plan, microSkillIdsInCourseOrder);
981
+ ```
982
+
983
+ - `PLAN_LIMITS` is a frozen copy of `@stackfactor/client-api`'s
984
+ `learningContentPlan.LEARNING_CONTENT_PLAN.LIMITS`, which mirrors core: the
985
+ through-line 200 characters, a role 160, `handsTo` 120, a term 60, a
986
+ definition 200; a lesson builds on at most 2 terms and owns at most 3.
987
+ - `planSchema` also refuses two lessons for one micro-skill and two terms with
988
+ one key. Each message names the lesson or the term.
989
+ - `planProblems(plan, microSkillIds)` answers one sentence per misfit: a
990
+ micro-skill with no lesson, a lesson or a term owner that is not a
991
+ micro-skill of the skill, a `buildsOn` key that names no term, or one whose
992
+ term is owned by the same lesson or a later one. It never throws.
993
+ - `planContextSchema` parses what a lesson agent is given: unknown keys are
994
+ dropped, and a missing `handsTo` becomes `""`.
995
+ - Types: `ContentPlan`, `ContentPlanLesson`, `ContentPlanTerm`,
996
+ `ContentPlanExtension`. `PlanContext` is client-api's
997
+ `LearningContentPlanContext`. `LearningContentThread` and
998
+ `LearningContentThreadSentence` are client-api's types of what a lesson
999
+ stores.
1000
+
1001
+ ### A planner extends a plan
1002
+
1003
+ When a skill gains micro-skills, the lessons already written must not change:
1004
+ a new term given to a written lesson would put that lesson out of date. So the
1005
+ model is asked for the new lessons and the new terms only.
1006
+
1007
+ ```typescript
1008
+ // 1. The model answers an extension: { lessons, terms }, the new ones only.
1009
+ const extension = learningContentPlan.planExtensionSchema.parse(JSON.parse(answer));
1010
+ // 2. Judged against the plan it extends and the skill's order.
1011
+ const problems = learningContentPlan.extensionProblems(extension, existingPlan, microSkillIdsInCourseOrder);
1012
+ // 3. The plan to save: the existing entries, then the new ones.
1013
+ const plan = learningContentPlan.mergePlanExtension(existingPlan, extension);
1014
+ // 4. Totals across old and new, such as more than 3 terms for one owner.
1015
+ learningContentPlan.planSchema.parse(plan);
1016
+ ```
1017
+
1018
+ - `planExtensionSchema` checks limits and duplicates within the extension.
1019
+ - `extensionProblems` answers one sentence per misfit of a NEW entry: a
1020
+ micro-skill without a lesson and none in the extension; a lesson for a
1021
+ micro-skill that has one already, or that is not in the skill; a term whose
1022
+ key the plan has; a term owned by a written lesson ("a new term is owned by a
1023
+ new lesson"), or by a micro-skill with no lesson in the extension; a
1024
+ `buildsOn` key that names no term, or one owned by the same lesson or a later
1025
+ one. A new lesson may build on a written lesson's term when that lesson comes
1026
+ earlier. It never reports the existing entries and never throws.
1027
+ - `mergePlanExtension` fills a stored lesson's missing `handsTo`, changes
1028
+ neither argument, and drops `version`, `writtenAt` and `writtenBy`: send the
1029
+ version that was read when saving.
1030
+ - What the skill made stale in the existing plan (a lesson or a term of a
1031
+ micro-skill that left) stays in the merged plan: the platform repairs it on
1032
+ save. `planProblems` on the merged plan would list those, so it is not the
1033
+ check for an extension.
1034
+
1035
+ ### A lesson agent writes its thread lines
1036
+
1037
+ ```typescript
1038
+ import { learningContentThread } from "@stackfactor/agent-utils";
1039
+
1040
+ const { lines, problems, attempts, error } = await learningContentThread.writeThread({
1041
+ modelName: config.selectedModelForGeneratingContent,
1042
+ config,
1043
+ instructions: config.writeThreadInstructions, // the agent's own, from config.yaml
1044
+ planContext,
1045
+ learningTargets, // [{ title, description? }]
1046
+ takeaways,
1047
+ agentName: "Thread writer", // the name the model call runs under
1048
+ });
1049
+ if (lines) {
1050
+ // place lines.opening and lines.closing in the lesson, and answer `thread`
1051
+ } else {
1052
+ // a whole lesson: answer an empty `thread` object and go on; `problems` says why
1053
+ // a thread-only update: throw `error` when it is there, else report `problems`
1054
+ }
1055
+ ```
1056
+
1057
+ `writeThread` makes at most two model calls: one, and one retry that shows the
1058
+ model its answer and what was wrong with it. It switches `agentic` and `tavily`
1059
+ off for the call, and passes a usage tracker only when given one.
1060
+
1061
+ | What happens in a call | Outcome |
1062
+ | --- | --- |
1063
+ | The lines break a rule | A failed attempt; the retry is told the problems |
1064
+ | The model call throws | A failed attempt; `error` holds what was thrown |
1065
+ | The model call is rate limited | A failed attempt and no second call: the library has already waited |
1066
+ | The request was cancelled, or the model has no rate (402) | Thrown on |
1067
+
1068
+ `error` is in the result only when `lines` is null and the last attempt failed
1069
+ in the call itself.
1070
+
1071
+ | Rule (`threadProblems`) | Opening | Closing |
1072
+ | --- | --- | --- |
1073
+ | Not blank (a line of only punctuation is blank) | yes | yes |
1074
+ | Words, at most (`THREAD_LIMITS`) | 60 | 30 |
1075
+ | Sentences, at most | 3 | 2 |
1076
+ | No phrase that depends on the order of lessons | yes | yes |
1077
+ | Names each term the lesson builds on | yes | |
1078
+
1079
+ `threadRulesForPrompt()` gives the same rules as data: the limits,
1080
+ `opening.namesEachTermItBuildsOn`, and example phrases the checker refuses.
1081
+
1082
+ - **A phrase that depends on the order of lessons** (`findPositionPhrases`) is
1083
+ one that breaks when lessons are reordered or watched alone: "the last
1084
+ video", "the next lesson", "in a later lesson", "lesson 4", "as we saw",
1085
+ "earlier in this course", "in the previous unit", "last time, we", "next, you
1086
+ will learn", "now that you have learned", "up next". A relative word ("last",
1087
+ "next", "previous" and their kin) counts before a lesson, video, lecture,
1088
+ module, chapter, episode or section; an ordinal ("first", "final") and a
1089
+ number count only with a lesson, video or lecture. Content is left alone:
1090
+ "Chapter 3 of the GDPR", "the first lesson learned from the incident", "the
1091
+ next video call", "record your first video", "review at the next session",
1092
+ "the first unit test", "the last time you missed a deadline".
1093
+ - **A sentence** (`countSentences`) ends at `.`, `!` or `?` followed by
1094
+ whitespace or the end. An abbreviation ("e.g.", "Dr.", "Art. 6"), an initial,
1095
+ a decimal and a mark followed by a lower-case letter do not end one.
1096
+ - **A term is named** (`namesTerm`) when each of its words of three letters or
1097
+ more is in the line, as written or in its plural, and each shorter word in
1098
+ capitals or with a digit ("AI", "1") stands in it as written. A term with
1099
+ only short words ("AI") must stand as a whole. A term that ends in a
1100
+ bracketed form, "Personal protective equipment (PPE)", is named by either
1101
+ form.
1102
+
1103
+ Each problem is a sentence the model can act on, for example
1104
+ `The opening has 72 words; the limit is 60.`
1105
+
465
1106
  ## Supported Models
466
1107
 
467
1108
  ### Text / Chat
@@ -472,7 +1113,9 @@ The agent answers with `code` and `message`, so the person sees which documents
472
1113
  | Anthropic | `claude-` | `claude-3-5-sonnet`, `claude-3-opus` |
473
1114
  | Google | `gemini-` | `gemini-1.5-pro`, `gemini-2.0-flash` |
474
1115
 
475
- Native structured output is configured per provider when a Zod `schema` is passed: `response_format` with a JSON schema for `gpt-*`, `output_config.format` for `claude-*`, and JSON mode plus `responseSchema` for `gemini-*`.
1116
+ Native structured output is configured per provider when a Zod `schema` is passed: `text.format` with a JSON schema for `gpt-*` (the Responses API), `output_config.format` for `claude-*`, and JSON mode plus `responseSchema` for `gemini-*`.
1117
+
1118
+ Every `gpt-*` call goes to OpenAI's Responses API (`/v1/responses`), not Chat Completions, which refuses function tools beside a reasoning model's reasoning (`gpt-5.6*`, the gpt-6 generation). Requests are sent with `store: false`, so OpenAI keeps no response; a reasoning model in a tool loop is asked for its reasoning in encrypted form (`include: ["reasoning.encrypted_content"]`) and gets it back on the next turn.
476
1119
 
477
1120
  Output token limits are not configurable. Anthropic requires `max_tokens` on every request, so `claude-*` is pinned to `64000` with streaming always enabled; `gpt-*` and `gemini-*` are sent no limit and use each provider's own default, which is that model's maximum.
478
1121
 
@@ -495,6 +1138,7 @@ The `config` object accepted by LangChain methods supports the following keys:
495
1138
  | `anthropicAPIKey` | `string` | Anthropic API key |
496
1139
  | `googleAPIKey` | `string` | Google AI API key |
497
1140
  | `temperature` | `number` | Sampling temperature |
1141
+ | `reasoningEffort` | `string` | `low`, `medium`, `high`, `xhigh` or `max`: sent as `output_config.effort` to Claude models from Opus 4.6 / Sonnet 4.6 on (Opus 5.5 defaults to `medium`, Opus 5 to `high`). An invalid value, or a Claude model that rejects the parameter, is ignored with a warning; Gemini and GPT models ignore the key silently. OpenAI models take no `reasoningEffort` from the config and keep their own default reasoning, with or without tools |
498
1142
  | `agentic` | `boolean` | Enable agentic mode in `runPromptWithModel` |
499
1143
  | `recursionLimit` | `number` | Max agent steps (default: `25`) |
500
1144
  | `tavilyAPIKey` | `string` | Tavily API key; required when `tavily` is set |