@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
@@ -3,14 +3,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkUrlsReachable = exports.buildTavilyTools = exports.assertTavilyUsable = exports.getTavilyOptions = void 0;
6
+ exports.checkUrlsReachable = exports.unreachableUrls = exports.LinksNotCheckedError = exports.readUrls = exports.checkUrls = exports.buildTavilyTools = exports.assertTavilyUsable = exports.getTavilyOptions = void 0;
7
7
  const langchain_1 = require("langchain");
8
8
  const zod_1 = require("zod");
9
9
  const const_js_1 = __importDefault(require("./const.js"));
10
10
  const errorHandling_js_1 = __importDefault(require("./errorHandling.js"));
11
11
  const logger_js_1 = __importDefault(require("./logger.js"));
12
12
  const runtimeContext_js_1 = require("./runtimeContext.js");
13
+ const cancellation_js_1 = require("./cancellation.js");
13
14
  const usage_js_1 = require("./usage.js");
15
+ const modelRates_js_1 = require("./modelRates.js");
16
+ const retry_js_1 = require("./retry.js");
17
+ const journal_js_1 = require("./durable/journal.js");
14
18
  const TAVILY_API_BASE = "https://api.tavily.com";
15
19
  /**
16
20
  * Context budgets, in characters, applied to everything a tool hands back to
@@ -85,8 +89,9 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
85
89
  * before the time this library already told the caller it had.
86
90
  *
87
91
  * Rate-limit (429) and server (5xx) responses are retried with exponential
88
- * backoff — everything else, including a caller-cancelled request, fails
89
- * immediately.
92
+ * backoff — everything else fails immediately. A request its caller
93
+ * cancelled makes no call and stops with "Request cancelled by caller",
94
+ * before a call, during one and between retries.
90
95
  * @param endpoint - The Tavily endpoint name, e.g. `"search"`
91
96
  * @param body - Request body in the API's snake_case form; `undefined` values
92
97
  * are dropped so Tavily applies its own defaults
@@ -94,7 +99,11 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
94
99
  * @param timeoutSeconds - Per-request timeout forwarded to Tavily
95
100
  * @returns The parsed JSON response
96
101
  */
102
+ /** The name Tavily's credits are counted and priced under. */
103
+ const TAVILY_MODEL = "tavily";
97
104
  const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
105
+ // Tavily bills credits like a model bills tokens: no rate, no call.
106
+ await (0, modelRates_js_1.requirePricedModel)(TAVILY_MODEL);
98
107
  const payload = {
99
108
  include_usage: true,
100
109
  timeout: timeoutSeconds,
@@ -104,6 +113,8 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
104
113
  payload[key] = value;
105
114
  }
106
115
  for (let attempt = 0;; attempt++) {
116
+ // A cancelled request makes no further call, and says so.
117
+ (0, cancellation_js_1.throwIfRequestCancelled)();
107
118
  let response;
108
119
  try {
109
120
  response = await fetch(`${TAVILY_API_BASE}/${endpoint}`, {
@@ -119,6 +130,10 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
119
130
  });
120
131
  }
121
132
  catch (err) {
133
+ // The request's own signal ended the fetch: the caller is gone, and
134
+ // Tavily did not fail.
135
+ if ((0, cancellation_js_1.isRequestCancelled)())
136
+ throw (0, cancellation_js_1.requestCancelledError)();
122
137
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Tavily ${endpoint} request failed: ${err?.message || String(err)}`);
123
138
  }
124
139
  if (response.ok)
@@ -132,8 +147,6 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
132
147
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Tavily ${endpoint} returned ${response.status}: ${detail.slice(0, 500)}`);
133
148
  }
134
149
  };
135
- /** The name Tavily's credits are counted and priced under. */
136
- const TAVILY_MODEL = "tavily";
137
150
  /**
138
151
  * Counts one Tavily call's credits and records the URLs it returned. Credits
139
152
  * come from the response's own `usage` block; they are counted into the
@@ -150,7 +163,9 @@ const TAVILY_MODEL = "tavily";
150
163
  const recordTavilyUsage = (tracker, _config, credits, sources) => {
151
164
  if (Number.isFinite(credits) && credits > 0) {
152
165
  (0, usage_js_1.recordUsage)(TAVILY_MODEL, "credits", credits);
166
+ (0, journal_js_1.noteUsage)("tavilyCredits", credits);
153
167
  }
168
+ (0, journal_js_1.noteSources)(sources);
154
169
  if (!tracker)
155
170
  return;
156
171
  if (typeof tracker.cost !== "number")
@@ -180,6 +195,8 @@ const recordTavilyUsage = (tracker, _config, credits, sources) => {
180
195
  * @param urls - The URLs sent
181
196
  */
182
197
  const recordAttemptedUrls = (tracker, urls) => {
198
+ if (urls.length > 0)
199
+ (0, journal_js_1.noteAttempted)(urls);
183
200
  if (!tracker || urls.length === 0)
184
201
  return;
185
202
  const attempted = tracker.attemptedUrls || (tracker.attemptedUrls = []);
@@ -501,25 +518,33 @@ const isWebUrl = (url) => {
501
518
  * fetch under `failed_results`. So a URL listed there is unreachable, and every
502
519
  * other URL of a batch Tavily answered is reachable (the results may name a
503
520
  * URL by its address after a redirect, which is why they are not matched). A
504
- * batch whose call fails outright, or a config without `tavilyAPIKey`,
505
- * confirms none of its URLs: a link that could not be checked is not trusted.
521
+ * batch whose call fails outright, or a config without `tavilyAPIKey`, says
522
+ * nothing about its URLs: they are `unchecked`, which is not `unreachable`.
523
+ * The caller decides what an unchecked link is worth; dropping it as dead
524
+ * loses every citation to one failed call.
506
525
  *
507
- * @param urls - The URLs to check; a URL given twice is checked once
526
+ * @param urls - The URLs to check; a URL given twice is checked once. A value
527
+ * that is no string is in no set
508
528
  * @param config - The integration config; supplies `tavilyAPIKey`
509
529
  * @param usageTracker - Optional accumulator the credits are counted into
510
- * @returns The given URLs, exactly as passed, that resolve
530
+ * @returns The given URLs, exactly as passed, each in one of the three sets
511
531
  */
512
- const checkUrlsReachable = async (urls, config, usageTracker = null) => {
513
- const reachable = new Set();
514
- const candidates = [
515
- ...new Set(urls.filter((url) => typeof url === "string" && isWebUrl(url.trim()))),
516
- ];
532
+ const checkUrls = async (urls, config, usageTracker = null) => {
533
+ const check = { reachable: new Set(), unreachable: new Set(), unchecked: new Set() };
534
+ const given = [...new Set(urls.filter((url) => typeof url === "string"))];
535
+ const candidates = given.filter((url) => isWebUrl(url.trim()));
536
+ for (const url of given) {
537
+ if (!isWebUrl(url.trim()))
538
+ check.unreachable.add(url);
539
+ }
517
540
  if (candidates.length === 0)
518
- return reachable;
541
+ return check;
519
542
  const apiKey = config?.tavilyAPIKey;
520
543
  if (!apiKey) {
521
- logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily reachability: no tavilyAPIKey, so none of ${candidates.length} URL(s) is confirmed`);
522
- return reachable;
544
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily reachability: no tavilyAPIKey, so none of ${candidates.length} URL(s) is checked`);
545
+ for (const url of candidates)
546
+ check.unchecked.add(url);
547
+ return check;
523
548
  }
524
549
  const batches = [];
525
550
  for (let start = 0; start < candidates.length; start += EXTRACT_MAX_URLS) {
@@ -535,7 +560,13 @@ const checkUrlsReachable = async (urls, config, usageTracker = null) => {
535
560
  }, apiKey, REACHABILITY_TIMEOUT_SECONDS);
536
561
  }
537
562
  catch (err) {
538
- logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily reachability: the check of ${batch.length} URL(s) failed (${err?.message || String(err)}), so none of them is confirmed`);
563
+ // A cancelled request is not a check that failed: its links are not
564
+ // "unchecked", to be waited for and asked again. It stops.
565
+ if ((0, cancellation_js_1.isRequestCancelled)())
566
+ throw err;
567
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily reachability: the check of ${batch.length} URL(s) failed (${err?.message || String(err)}), so none of them is checked`);
568
+ for (const url of batch)
569
+ check.unchecked.add(url);
539
570
  return;
540
571
  }
541
572
  recordTavilyUsage(usageTracker, config, data?.usage?.credits || 0, []);
@@ -543,17 +574,207 @@ const checkUrlsReachable = async (urls, config, usageTracker = null) => {
543
574
  .map((entry) => typeof entry?.url === "string" ? urlMatchKey(entry.url) : "")
544
575
  .filter(Boolean));
545
576
  for (const url of batch) {
546
- if (!failed.has(urlMatchKey(url)))
547
- reachable.add(url);
577
+ (failed.has(urlMatchKey(url)) ? check.unreachable : check.reachable).add(url);
548
578
  }
549
579
  }));
550
- return reachable;
580
+ return check;
581
+ };
582
+ exports.checkUrls = checkUrls;
583
+ /** What a URL that is not `http:` or `https:` is answered with. */
584
+ const NOT_A_WEB_URL = "Not a web address";
585
+ /** What every URL is answered with when the config has no `tavilyAPIKey`. */
586
+ const NO_PAGE_READER = "The page reader is not configured";
587
+ /** What a URL Tavily neither returned nor listed as failed is answered with. */
588
+ const NOT_RETURNED = "The page reader returned nothing for it";
589
+ /**
590
+ * Reads URLs in full, without a model: each page's whole text as markdown, or
591
+ * why it could not be read. What a run's source store holds of the pages its
592
+ * references point at (`sourceStore.prepareSources`).
593
+ *
594
+ * Nothing is trimmed here: Tavily returns whatever the page holds, which for a
595
+ * long PDF is over a million characters. The caller holds the text outside the
596
+ * model's context and hands it over a page at a time.
597
+ *
598
+ * They go in batches of 20, Tavily's limit, and are billed and recorded like
599
+ * every other Tavily call (`tavilyCredits`, `webSearchSources`,
600
+ * `attemptedUrls`). A URL Tavily could not fetch is asked for once more: its
601
+ * answer does not tell a page that is gone from one that failed for a moment.
602
+ * Tavily may name a result by the address it was redirected to, so a URL it
603
+ * neither returned under its own address nor listed as failed is asked for
604
+ * again on its own, where the one result is its.
605
+ *
606
+ * @param urls - The URLs to read; a URL given twice is read once. A value
607
+ * that is no string is left out
608
+ * @param config - The integration config; supplies `tavilyAPIKey`
609
+ * @param usageTracker - Optional accumulator the credits are counted into
610
+ * @returns One entry per distinct URL, in the order given
611
+ */
612
+ const readUrls = async (urls, config, usageTracker = null) => {
613
+ const given = [...new Set(urls.filter((url) => typeof url === "string"))];
614
+ const reads = new Map(given.map((url) => [url, { url, error: NOT_A_WEB_URL }]));
615
+ const candidates = given.filter((url) => isWebUrl(url.trim()));
616
+ const answers = () => given.map((url) => reads.get(url));
617
+ if (candidates.length === 0)
618
+ return answers();
619
+ const apiKey = config?.tavilyAPIKey;
620
+ if (!apiKey) {
621
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily read: no tavilyAPIKey, so none of ${candidates.length} URL(s) is read`);
622
+ for (const url of candidates)
623
+ reads.set(url, { url, error: NO_PAGE_READER });
624
+ return answers();
625
+ }
626
+ /** Reads one batch; returns the URLs to ask for again, and whether on their own. */
627
+ const readBatch = async (batch) => {
628
+ recordAttemptedUrls(usageTracker, batch.map((url) => url.trim()));
629
+ let data;
630
+ try {
631
+ data = await callTavily("extract", { urls: batch.map((url) => url.trim()), format: "markdown" }, apiKey, DEFAULT_TIMEOUT_SECONDS);
632
+ }
633
+ catch (err) {
634
+ if ((0, cancellation_js_1.isRequestCancelled)())
635
+ throw err;
636
+ const error = err?.message || String(err);
637
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily read: the read of ${batch.length} URL(s) failed (${error})`);
638
+ for (const url of batch)
639
+ reads.set(url, { url, error });
640
+ return { failed: batch, unmatched: [] };
641
+ }
642
+ const results = Array.isArray(data?.results) ? data.results : [];
643
+ recordTavilyUsage(usageTracker, config, data?.usage?.credits || 0, results.map((result) => ({
644
+ url: result?.url,
645
+ ...(result?.title ? { title: result.title } : {}),
646
+ })));
647
+ const byKey = new Map(results
648
+ .filter((result) => typeof result?.url === "string")
649
+ .map((result) => [urlMatchKey(result.url), result]));
650
+ const failures = new Map((Array.isArray(data?.failed_results) ? data.failed_results : [])
651
+ .filter((entry) => typeof entry?.url === "string")
652
+ .map((entry) => [urlMatchKey(entry.url), String(entry?.error || "Failed to fetch url")]));
653
+ const failed = [];
654
+ const unmatched = [];
655
+ for (const url of batch) {
656
+ const key = urlMatchKey(url);
657
+ // A batch of one has one answer, whatever address it is named by.
658
+ const result = byKey.get(key) ?? (batch.length === 1 && !failures.size ? results[0] : undefined);
659
+ if (result) {
660
+ reads.set(url, {
661
+ url,
662
+ text: typeof result.raw_content === "string" ? result.raw_content : "",
663
+ ...(typeof result.title === "string" && result.title ? { title: result.title } : {}),
664
+ });
665
+ }
666
+ else if (failures.has(key) || (batch.length === 1 && failures.size > 0)) {
667
+ reads.set(url, { url, error: failures.get(key) ?? [...failures.values()][0] });
668
+ failed.push(url);
669
+ }
670
+ else {
671
+ reads.set(url, { url, error: NOT_RETURNED });
672
+ unmatched.push(url);
673
+ }
674
+ }
675
+ return { failed, unmatched };
676
+ };
677
+ const batchesOf = (list) => {
678
+ const batches = [];
679
+ for (let start = 0; start < list.length; start += EXTRACT_MAX_URLS) {
680
+ batches.push(list.slice(start, start + EXTRACT_MAX_URLS));
681
+ }
682
+ return batches;
683
+ };
684
+ const first = await Promise.all(batchesOf(candidates).map(readBatch));
685
+ const again = first.flatMap((outcome) => outcome.failed);
686
+ const alone = first.flatMap((outcome) => outcome.unmatched);
687
+ // Once more, and no further: what a second answer leaves unread stays unread.
688
+ await Promise.all([
689
+ ...batchesOf(again).map(readBatch),
690
+ ...alone.map((url) => readBatch([url])),
691
+ ]);
692
+ return answers();
693
+ };
694
+ exports.readUrls = readUrls;
695
+ /**
696
+ * A cited link's check did not run, after the retries: Tavily's call for it
697
+ * failed, or no key was configured. Such a link is not dead, so nothing is
698
+ * dropped for it; the person is asked to try again. Its message is the coded
699
+ * JSON an agent's failure carries (`{ code, message }`, 503), so `serve`
700
+ * answers the person with the sentence, not a 500.
701
+ */
702
+ class LinksNotCheckedError extends Error {
703
+ code = 503;
704
+ /** How many of the links went unchecked. */
705
+ unchecked;
706
+ /** How many links were checked, each once. */
707
+ total;
708
+ /**
709
+ * @param unchecked How many of the links went unchecked
710
+ * @param total How many links were checked, each once
711
+ */
712
+ constructor(unchecked, total) {
713
+ super(JSON.stringify({
714
+ code: 503,
715
+ message: `The cited links could not be checked (${unchecked} of ${total}). Try again shortly.`,
716
+ }));
717
+ this.name = "LinksNotCheckedError";
718
+ this.unchecked = unchecked;
719
+ this.total = total;
720
+ Object.setPrototypeOf(this, LinksNotCheckedError.prototype);
721
+ }
722
+ }
723
+ exports.LinksNotCheckedError = LinksNotCheckedError;
724
+ /**
725
+ * The cited links that are dead: the ones Tavily could not fetch, and any
726
+ * that is no web link (`checkUrls`). A link whose check did not run (one
727
+ * dropped connection fails the 20 links of its call) is checked again, with
728
+ * the others like it and no link already settled, after each of the waits.
729
+ * One still unchecked after them is not called dead: the call throws, so the
730
+ * caller drops nothing for a check that did not run.
731
+ *
732
+ * @param urls - The links; a link given twice is checked once
733
+ * @param config - The integration config; supplies `tavilyAPIKey`
734
+ * @param usageTracker - Optional accumulator the credits are counted into
735
+ * @param options - `waits` (default RETRY_WAITS) and `sleep`
736
+ * @returns The dead links, each exactly as passed
737
+ * @throws {LinksNotCheckedError} When a link is still unchecked after the waits
738
+ */
739
+ const unreachableUrls = async (urls, config, usageTracker = null, options = {}) => {
740
+ const pause = options.sleep ?? sleep;
741
+ let check = await (0, exports.checkUrls)(urls, config, usageTracker);
742
+ const total = check.reachable.size + check.unreachable.size + check.unchecked.size;
743
+ const dead = new Set(check.unreachable);
744
+ for (const ms of options.waits ?? retry_js_1.RETRY_WAITS) {
745
+ if (check.unchecked.size === 0)
746
+ break;
747
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Tavily reachability: ${check.unchecked.size} of ${total} link(s) could not be checked; checking them again in ${ms} ms`);
748
+ await pause(ms);
749
+ check = await (0, exports.checkUrls)([...check.unchecked], config, usageTracker);
750
+ for (const url of check.unreachable)
751
+ dead.add(url);
752
+ }
753
+ if (check.unchecked.size > 0)
754
+ throw new LinksNotCheckedError(check.unchecked.size, total);
755
+ return dead;
551
756
  };
757
+ exports.unreachableUrls = unreachableUrls;
758
+ /**
759
+ * The URLs of `checkUrls` that Tavily fetched, and nothing about the rest.
760
+ *
761
+ * @deprecated Use `checkUrls`. This answer cannot tell a dead link from one
762
+ * whose check did not run, so a caller that drops what is missing from it
763
+ * drops every link when one call fails.
764
+ * @param urls - The URLs to check
765
+ * @param config - The integration config; supplies `tavilyAPIKey`
766
+ * @param usageTracker - Optional accumulator the credits are counted into
767
+ * @returns The given URLs, exactly as passed, that resolve
768
+ */
769
+ const checkUrlsReachable = async (urls, config, usageTracker = null) => (await (0, exports.checkUrls)(urls, config, usageTracker)).reachable;
552
770
  exports.checkUrlsReachable = checkUrlsReachable;
553
771
  exports.default = {
554
772
  assertTavilyUsable: exports.assertTavilyUsable,
555
773
  buildTavilyTools: exports.buildTavilyTools,
774
+ checkUrls: exports.checkUrls,
556
775
  checkUrlsReachable: exports.checkUrlsReachable,
776
+ readUrls: exports.readUrls,
777
+ unreachableUrls: exports.unreachableUrls,
557
778
  getTavilyOptions: exports.getTavilyOptions,
558
779
  recordTavilyUsage,
559
780
  };
@@ -1 +1 @@
1
- {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/usage.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEtE;;;;;;;;;;;;GAYG;AAEH,sEAAsE;AACtE,eAAO,MAAM,WAAW,uHAQd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,mFAAmF;AACnF,MAAM,MAAM,WAAW,GAAG,CACxB,KAAK,EAAE,UAAU,EAAE,EACnB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,KACV,OAAO,CAAC,OAAO,CAAC,CAAC;AAOtB,wEAAwE;AACxE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAI/C;;GAEG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,OAAO,CAAiC;IAEhD,kGAAkG;IAClG,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAkBzD,gDAAgD;IAChD,IAAI,IAAI,UAAU,EAAE;IAMpB,4CAA4C;IAC5C,IAAI,OAAO,IAAI,OAAO,CAErB;CACF;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,EAAE,MAAM,SAAS,EAAE,QAAQ,MAAM,KAAG,IAE5E,CAAC;AA8BF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GACtB,SAAS,IAAI,CAAC,cAAc,EAAE,OAAO,GAAG,SAAS,CAAC,GAAG,SAAS,EAC9D,UAAS;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,KAC3E,OAAO,CAAC,IAAI,CAuCd,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,GAClC,SAAS,IAAI,CAAC,cAAc,EAAE,OAAO,GAAG,SAAS,CAAC,EAClD,UAAS;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,KAChF,CAAC,MAAM,IAAI,CAMb,CAAC"}
1
+ {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/usage.ts"],"names":[],"mappings":"AAIA,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEtE;;;;;;;;;;;;GAYG;AAEH,sEAAsE;AACtE,eAAO,MAAM,WAAW,uHAQd,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,mFAAmF;AACnF,MAAM,MAAM,WAAW,GAAG,CACxB,KAAK,EAAE,UAAU,EAAE,EACnB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,KACV,OAAO,CAAC,OAAO,CAAC,CAAC;AAMtB,wEAAwE;AACxE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAI/C;;GAEG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,OAAO,CAAiC;IAEhD,kGAAkG;IAClG,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAkBzD,gDAAgD;IAChD,IAAI,IAAI,UAAU,EAAE;IAMpB,4CAA4C;IAC5C,IAAI,OAAO,IAAI,OAAO,CAErB;CACF;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,EAAE,MAAM,SAAS,EAAE,QAAQ,MAAM,KAAG,IAE5E,CAAC;AA0BF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GACtB,SAAS,IAAI,CAAC,cAAc,EAAE,OAAO,GAAG,SAAS,CAAC,GAAG,SAAS,EAC9D,UAAS;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,KAC3E,OAAO,CAAC,IAAI,CAuCd,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,GAClC,SAAS,IAAI,CAAC,cAAc,EAAE,OAAO,GAAG,SAAS,CAAC,EAClD,UAAS;IAAE,MAAM,CAAC,EAAE,WAAW,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,KAChF,CAAC,MAAM,IAAI,CAMb,CAAC"}
package/dist/cjs/usage.js CHANGED
@@ -7,6 +7,7 @@ exports.reportUsageWhileRunning = exports.reportUsage = exports.recordUsage = ex
7
7
  const node_crypto_1 = require("node:crypto");
8
8
  const client_api_1 = require("@stackfactor/client-api");
9
9
  const logger_js_1 = __importDefault(require("./logger.js"));
10
+ const retry_js_1 = require("./retry.js");
10
11
  const runtimeContext_js_1 = require("./runtimeContext.js");
11
12
  /**
12
13
  * What an agent used, and how the platform gets to know.
@@ -33,8 +34,7 @@ exports.USAGE_UNITS = [
33
34
  ];
34
35
  /** Entries one report may carry (the platform's limit). */
35
36
  const REPORT_ENTRIES_MAX = 100;
36
- /** How often a report is tried before it is given up on, and the first wait between tries. */
37
- const REPORT_ATTEMPTS = 3;
37
+ /** The first wait before a report that failed for a reason that may pass is sent again; the second wait is twice it (three attempts). */
38
38
  const REPORT_RETRY_BASE_MS = 500;
39
39
  /** How often work that is still running reports what it used so far. */
40
40
  exports.USAGE_REPORT_INTERVAL_MS = 60_000;
@@ -89,22 +89,16 @@ exports.recordUsage = recordUsage;
89
89
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
90
90
  const defaultReport = (usage, reportId, token) => client_api_1.integration.reportRunUsage(usage, reportId, token);
91
91
  /**
92
- * Sends one report, again when it fails, under the same name every time: the
93
- * platform charges a report it has seen only once.
92
+ * Sends one report, again when it fails for a reason that may pass
93
+ * (retryTransient: a 5xx, a rate limit, the network; never a refusal), under
94
+ * the same name every time: the platform charges a report it has seen only
95
+ * once.
94
96
  */
95
97
  const send = async (entries, token, report, retryBaseMs) => {
96
98
  const reportId = (0, node_crypto_1.randomUUID)();
97
- for (let attempt = 1;; attempt++) {
98
- try {
99
- await report(entries, reportId, token);
100
- return;
101
- }
102
- catch (error) {
103
- if (attempt >= REPORT_ATTEMPTS)
104
- throw error;
105
- await delay(retryBaseMs * 2 ** (attempt - 1));
106
- }
107
- }
99
+ await (0, retry_js_1.retryTransient)("the usage report", () => report(entries, reportId, token), {
100
+ waits: [retryBaseMs, retryBaseMs * 2],
101
+ });
108
102
  };
109
103
  /**
110
104
  * Reports what the request used and has not reported yet. Never throws, and
@@ -0,0 +1,3 @@
1
+ /** This package's version, written by scripts/write-version.js at build time; do not edit. */
2
+ export declare const VERSION = "1.32.0";
3
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,eAAO,MAAM,OAAO,WAAW,CAAC"}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ /** This package's version, written by scripts/write-version.js at build time; do not edit. */
5
+ exports.VERSION = "1.32.0";
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The runner's bookkeeping, kept apart from the agent's state (runner spec
3
+ * §3, decision 5). The workflow's `state` is stored as `{ v: 1, agent, runner }`:
4
+ * `agent` is the agent's own state, the only part a turn receives and
5
+ * returns; `runner` holds the outbox, the last 50 turn records and the
6
+ * last-write stamp, in the shapes of agent-utils #60's `OutboxEntry`,
7
+ * `TurnRecord` and `LastWrite`. The platform never reads `state`, so the
8
+ * split costs nothing there.
9
+ */
10
+ /** A notification a turn sends under the lease, keyed so a resend is recognised by its receiver. */
11
+ export interface OutboxEntry {
12
+ key: string;
13
+ [field: string]: unknown;
14
+ }
15
+ /**
16
+ * The write that stored the state as it is: the run that made it and an id
17
+ * fresh per call, the same across that call's retries. A retry answered with
18
+ * a version mismatch re-reads the workflow: this call's id there means the
19
+ * write landed (runner spec §7).
20
+ */
21
+ export interface LastWrite {
22
+ batchJobId: string | null;
23
+ id: string;
24
+ }
25
+ /** One turn this runner took, recorded with the save that ends it. */
26
+ export interface TurnRecord {
27
+ /** The input's id: its inbox entry. */
28
+ turn: string;
29
+ /** The event's type, or the input's kind (`resume`, `interactive`). */
30
+ eventType: string;
31
+ batchJobId: string | null;
32
+ at: string;
33
+ /** What the turn chose: `release`, `end` or `delete`. */
34
+ outcome: unknown;
35
+ /** Set on the turn that ended the workflow. */
36
+ terminal?: boolean;
37
+ }
38
+ export interface RunnerState {
39
+ outbox: OutboxEntry[];
40
+ turns: TurnRecord[];
41
+ lastWrite: LastWrite | null;
42
+ }
43
+ export interface StoredState {
44
+ v: 1;
45
+ agent: unknown;
46
+ runner: RunnerState;
47
+ }
48
+ export declare const STATE_VERSION = 1;
49
+ /** Turn records kept, the oldest dropped first. */
50
+ export declare const TURNS_KEPT = 50;
51
+ /**
52
+ * Splits a stored `state` into the agent's part and the runner's. A state this
53
+ * runner did not write (null on a new workflow, or a value from before the
54
+ * runner) is all the agent's. One written by a newer runner is refused rather
55
+ * than read as the agent's: wrapping it again would bury that runner's
56
+ * bookkeeping where neither runner would find it.
57
+ */
58
+ export declare const readState: (stored: unknown) => {
59
+ agent: unknown;
60
+ runner: RunnerState;
61
+ };
62
+ /** The agent's part of a stored state. */
63
+ export declare const agentOf: (stored: unknown) => unknown;
64
+ /**
65
+ * The state as stored: the agent's part and the runner's, versioned. The
66
+ * runner's part is copied, so a body already sent (and retried as sent) does
67
+ * not change when the runner's bookkeeping moves on.
68
+ */
69
+ export declare const storedState: (agent: unknown, runner: RunnerState) => StoredState;
70
+ /** The turn records with `record` added, the last {@link TURNS_KEPT}. */
71
+ export declare const withTurn: (turns: TurnRecord[], record: TurnRecord) => TurnRecord[];
72
+ /**
73
+ * The outbox to send: what an earlier attempt of the turn stored and did not
74
+ * clear, and what this attempt added, one entry per key (the later wins, in
75
+ * the earlier's place).
76
+ */
77
+ export declare const mergeOutbox: (stored: OutboxEntry[], added: OutboxEntry[]) => OutboxEntry[];
78
+ //# sourceMappingURL=bookkeeping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bookkeeping.d.ts","sourceRoot":"","sources":["../../../src/workflow/bookkeeping.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,oGAAoG;AACpG,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACxB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,sEAAsE;AACtE,MAAM,WAAW,UAAU;IACzB,uCAAuC;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,yDAAyD;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,SAAS,EAAE,SAAS,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,WAAW;IAC1B,CAAC,EAAE,CAAC,CAAC;IACL,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,eAAO,MAAM,aAAa,IAAI,CAAC;AAE/B,mDAAmD;AACnD,eAAO,MAAM,UAAU,KAAK,CAAC;AAO7B;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,GAAI,QAAQ,OAAO,KAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,WAAW,CAAA;CAkBhF,CAAC;AAEF,0CAA0C;AAC1C,eAAO,MAAM,OAAO,GAAI,QAAQ,OAAO,KAAG,OAAkC,CAAC;AAE7E;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,OAAO,EAAE,QAAQ,WAAW,KAAG,WAQhE,CAAC;AAEH,yEAAyE;AACzE,eAAO,MAAM,QAAQ,GAAI,OAAO,UAAU,EAAE,EAAE,QAAQ,UAAU,KAAG,UAAU,EACtC,CAAC;AAExC;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAAI,QAAQ,WAAW,EAAE,EAAE,OAAO,WAAW,EAAE,KAAG,WAAW,EAIpF,CAAC"}
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ /**
3
+ * The runner's bookkeeping, kept apart from the agent's state (runner spec
4
+ * §3, decision 5). The workflow's `state` is stored as `{ v: 1, agent, runner }`:
5
+ * `agent` is the agent's own state, the only part a turn receives and
6
+ * returns; `runner` holds the outbox, the last 50 turn records and the
7
+ * last-write stamp, in the shapes of agent-utils #60's `OutboxEntry`,
8
+ * `TurnRecord` and `LastWrite`. The platform never reads `state`, so the
9
+ * split costs nothing there.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.mergeOutbox = exports.withTurn = exports.storedState = exports.agentOf = exports.readState = exports.TURNS_KEPT = exports.STATE_VERSION = void 0;
13
+ exports.STATE_VERSION = 1;
14
+ /** Turn records kept, the oldest dropped first. */
15
+ exports.TURNS_KEPT = 50;
16
+ const emptyRunner = () => ({ outbox: [], turns: [], lastWrite: null });
17
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
18
+ /**
19
+ * Splits a stored `state` into the agent's part and the runner's. A state this
20
+ * runner did not write (null on a new workflow, or a value from before the
21
+ * runner) is all the agent's. One written by a newer runner is refused rather
22
+ * than read as the agent's: wrapping it again would bury that runner's
23
+ * bookkeeping where neither runner would find it.
24
+ */
25
+ const readState = (stored) => {
26
+ if (isObject(stored) && "runner" in stored && "v" in stored) {
27
+ if (stored.v !== exports.STATE_VERSION) {
28
+ throw new Error(`workflow state was written by a newer runner (v ${String(stored.v)}); this runner reads v ${exports.STATE_VERSION}`);
29
+ }
30
+ const runner = isObject(stored.runner) ? stored.runner : {};
31
+ return {
32
+ agent: stored.agent ?? null,
33
+ runner: {
34
+ outbox: Array.isArray(runner.outbox) ? [...runner.outbox] : [],
35
+ turns: Array.isArray(runner.turns) ? [...runner.turns] : [],
36
+ lastWrite: isObject(runner.lastWrite) ? runner.lastWrite : null,
37
+ },
38
+ };
39
+ }
40
+ return { agent: stored ?? null, runner: emptyRunner() };
41
+ };
42
+ exports.readState = readState;
43
+ /** The agent's part of a stored state. */
44
+ const agentOf = (stored) => (0, exports.readState)(stored).agent;
45
+ exports.agentOf = agentOf;
46
+ /**
47
+ * The state as stored: the agent's part and the runner's, versioned. The
48
+ * runner's part is copied, so a body already sent (and retried as sent) does
49
+ * not change when the runner's bookkeeping moves on.
50
+ */
51
+ const storedState = (agent, runner) => ({
52
+ v: exports.STATE_VERSION,
53
+ agent: agent === undefined ? null : agent,
54
+ runner: {
55
+ outbox: [...runner.outbox],
56
+ turns: [...runner.turns],
57
+ lastWrite: runner.lastWrite ? { ...runner.lastWrite } : null,
58
+ },
59
+ });
60
+ exports.storedState = storedState;
61
+ /** The turn records with `record` added, the last {@link TURNS_KEPT}. */
62
+ const withTurn = (turns, record) => [...turns, record].slice(-exports.TURNS_KEPT);
63
+ exports.withTurn = withTurn;
64
+ /**
65
+ * The outbox to send: what an earlier attempt of the turn stored and did not
66
+ * clear, and what this attempt added, one entry per key (the later wins, in
67
+ * the earlier's place).
68
+ */
69
+ const mergeOutbox = (stored, added) => {
70
+ const byKey = new Map();
71
+ for (const entry of [...stored, ...added])
72
+ byKey.set(entry.key, entry);
73
+ return [...byKey.values()];
74
+ };
75
+ exports.mergeOutbox = mergeOutbox;
@@ -0,0 +1,13 @@
1
+ import * as testing from "./testing/index.js";
2
+ export { run, messageAdapter } from "./run.js";
3
+ export type { Decision, WorkflowInput, InteractiveInput, Next, TurnResult, TurnArgs, CheckpointFn, CheckpointOptions, Outbox, Handlers, LingerOptions, Clock, RunStart, InputAdapter, RunOptions, RunOutcome, RunSummary, } from "./run.js";
4
+ export { platformTransport } from "./platformTransport.js";
5
+ export type { WorkflowCalls } from "./platformTransport.js";
6
+ export { retrying } from "./retrying.js";
7
+ export type { RetryOptions } from "./retrying.js";
8
+ export type { OutboxEntry, TurnRecord, LastWrite } from "./bookkeeping.js";
9
+ export { LIMITS } from "./limits.js";
10
+ export type { Limits } from "./limits.js";
11
+ export { testing };
12
+ export type { Workflow, WaitDecl, WaitKind, WaitReason, Input, PlatformInput, RunQuestion, RunAnswer, OpenWait, WorkflowTransport, WorkflowOperation, LeaseBody, LeaseAnswer, TakeAnswer, SaveBody, SaveAnswer, ReleaseBody, ReleaseAnswer, EndBody, EndAnswer, LetGoAnswer, ReopenAnswer, DeleteAnswer, CancelAnswer, SignalBody, Checkpoint, CheckpointSaveAnswer, } from "./transport.js";
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/workflow/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC;AAE9C,OAAO,EAAE,GAAG,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC/C,YAAY,EACV,QAAQ,EACR,aAAa,EACb,gBAAgB,EAChB,IAAI,EACJ,UAAU,EACV,QAAQ,EACR,YAAY,EACZ,iBAAiB,EACjB,MAAM,EACN,QAAQ,EACR,aAAa,EACb,KAAK,EACL,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,UAAU,EACV,UAAU,GACX,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE3E,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,YAAY,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAE,CAAC;AAEnB,YAAY,EACV,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,KAAK,EACL,aAAa,EACb,WAAW,EACX,SAAS,EACT,QAAQ,EACR,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,WAAW,EACX,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,EACX,aAAa,EACb,OAAO,EACP,SAAS,EACT,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,EACV,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}