@stackfactor/agent-utils 1.13.4 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +688 -23
- package/dist/cjs/agentProto.d.ts +13 -3
- package/dist/cjs/agentProto.d.ts.map +1 -1
- package/dist/cjs/agentProto.js +25 -4
- package/dist/cjs/backoff.d.ts +17 -0
- package/dist/cjs/backoff.d.ts.map +1 -0
- package/dist/cjs/backoff.js +26 -0
- package/dist/cjs/cancellation.d.ts +22 -0
- package/dist/cjs/cancellation.d.ts.map +1 -0
- package/dist/cjs/cancellation.js +36 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.d.ts.map +1 -0
- package/dist/cjs/cli.js +85 -0
- package/dist/cjs/client.d.ts +11 -0
- package/dist/cjs/client.d.ts.map +1 -1
- package/dist/cjs/client.js +27 -0
- package/dist/cjs/const.d.ts +23 -0
- package/dist/cjs/const.d.ts.map +1 -1
- package/dist/cjs/const.js +23 -0
- package/dist/cjs/daemon.d.ts +94 -0
- package/dist/cjs/daemon.d.ts.map +1 -0
- package/dist/cjs/daemon.js +507 -0
- package/dist/cjs/daemonConfig.d.ts +45 -0
- package/dist/cjs/daemonConfig.d.ts.map +1 -0
- package/dist/cjs/daemonConfig.js +148 -0
- package/dist/cjs/daemonEnv.d.ts +10 -0
- package/dist/cjs/daemonEnv.d.ts.map +1 -0
- package/dist/cjs/daemonEnv.js +12 -0
- package/dist/cjs/durable/clientTool.d.ts +39 -0
- package/dist/cjs/durable/clientTool.d.ts.map +1 -0
- package/dist/cjs/durable/clientTool.js +90 -0
- package/dist/cjs/durable/index.d.ts +9 -0
- package/dist/cjs/durable/index.d.ts.map +1 -0
- package/dist/cjs/durable/index.js +16 -0
- package/dist/cjs/durable/journal.d.ts +218 -0
- package/dist/cjs/durable/journal.d.ts.map +1 -0
- package/dist/cjs/durable/journal.js +392 -0
- package/dist/cjs/durable/pause.d.ts +84 -0
- package/dist/cjs/durable/pause.d.ts.map +1 -0
- package/dist/cjs/durable/pause.js +241 -0
- package/dist/cjs/durable/resume.d.ts +27 -0
- package/dist/cjs/durable/resume.d.ts.map +1 -0
- package/dist/cjs/durable/resume.js +80 -0
- package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
- package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/cjs/durable/snapshotSaver.js +81 -0
- package/dist/cjs/durable/step.d.ts +28 -0
- package/dist/cjs/durable/step.d.ts.map +1 -0
- package/dist/cjs/durable/step.js +43 -0
- package/dist/cjs/index.d.ts +30 -7
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +28 -1
- package/dist/cjs/infrastructure.d.ts +50 -0
- package/dist/cjs/infrastructure.d.ts.map +1 -0
- package/dist/cjs/infrastructure.js +163 -0
- package/dist/cjs/langChain.d.ts +15 -3
- package/dist/cjs/langChain.d.ts.map +1 -1
- package/dist/cjs/langChain.js +986 -180
- package/dist/cjs/learningActivityMedia.d.ts +196 -0
- package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
- package/dist/cjs/learningActivityMedia.js +861 -0
- package/dist/cjs/learningContentPlan.d.ts +117 -0
- package/dist/cjs/learningContentPlan.d.ts.map +1 -0
- package/dist/cjs/learningContentPlan.js +327 -0
- package/dist/cjs/learningContentThread.d.ts +213 -0
- package/dist/cjs/learningContentThread.d.ts.map +1 -0
- package/dist/cjs/learningContentThread.js +448 -0
- package/dist/cjs/logger.d.ts +1 -0
- package/dist/cjs/logger.d.ts.map +1 -1
- package/dist/cjs/logger.js +17 -3
- package/dist/cjs/modelRates.d.ts +40 -0
- package/dist/cjs/modelRates.d.ts.map +1 -0
- package/dist/cjs/modelRates.js +76 -0
- package/dist/cjs/referenceContext.d.ts +4 -145
- package/dist/cjs/referenceContext.d.ts.map +1 -1
- package/dist/cjs/referenceContext.js +16 -251
- package/dist/cjs/retry.d.ts +64 -0
- package/dist/cjs/retry.d.ts.map +1 -0
- package/dist/cjs/retry.js +138 -0
- package/dist/cjs/runtimeContext.d.ts +8 -1
- package/dist/cjs/runtimeContext.d.ts.map +1 -1
- package/dist/cjs/runtimeContext.js +3 -1
- package/dist/cjs/serve.d.ts +3 -2
- package/dist/cjs/serve.d.ts.map +1 -1
- package/dist/cjs/serve.js +32 -2
- package/dist/cjs/sourceStore.d.ts +378 -0
- package/dist/cjs/sourceStore.d.ts.map +1 -0
- package/dist/cjs/sourceStore.js +872 -0
- package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
- package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/cjs/stackfactorKnowledge.js +108 -44
- package/dist/cjs/tavily.d.ts +108 -4
- package/dist/cjs/tavily.d.ts.map +1 -1
- package/dist/cjs/tavily.js +242 -21
- package/dist/cjs/usage.d.ts.map +1 -1
- package/dist/cjs/usage.js +9 -15
- package/dist/cjs/version.d.ts +3 -0
- package/dist/cjs/version.d.ts.map +1 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
- package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/cjs/workflow/bookkeeping.js +75 -0
- package/dist/cjs/workflow/index.d.ts +13 -0
- package/dist/cjs/workflow/index.d.ts.map +1 -0
- package/dist/cjs/workflow/index.js +51 -0
- package/dist/cjs/workflow/limits.d.ts +52 -0
- package/dist/cjs/workflow/limits.d.ts.map +1 -0
- package/dist/cjs/workflow/limits.js +62 -0
- package/dist/cjs/workflow/platformTransport.d.ts +39 -0
- package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/platformTransport.js +115 -0
- package/dist/cjs/workflow/retrying.d.ts +44 -0
- package/dist/cjs/workflow/retrying.d.ts.map +1 -0
- package/dist/cjs/workflow/retrying.js +82 -0
- package/dist/cjs/workflow/run.d.ts +195 -0
- package/dist/cjs/workflow/run.d.ts.map +1 -0
- package/dist/cjs/workflow/run.js +858 -0
- package/dist/cjs/workflow/testing/index.d.ts +3 -0
- package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/index.js +6 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
- package/dist/cjs/workflow/transport.d.ts +219 -0
- package/dist/cjs/workflow/transport.d.ts.map +1 -0
- package/dist/cjs/workflow/transport.js +19 -0
- package/dist/esm/agentProto.d.ts +13 -3
- package/dist/esm/agentProto.d.ts.map +1 -1
- package/dist/esm/agentProto.js +23 -3
- package/dist/esm/backoff.d.ts +17 -0
- package/dist/esm/backoff.d.ts.map +1 -0
- package/dist/esm/backoff.js +22 -0
- package/dist/esm/cancellation.d.ts +22 -0
- package/dist/esm/cancellation.d.ts.map +1 -0
- package/dist/esm/cancellation.js +27 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.d.ts.map +1 -0
- package/dist/esm/cli.js +80 -0
- package/dist/esm/client.d.ts +11 -0
- package/dist/esm/client.d.ts.map +1 -1
- package/dist/esm/client.js +25 -1
- package/dist/esm/const.d.ts +23 -0
- package/dist/esm/const.d.ts.map +1 -1
- package/dist/esm/const.js +23 -0
- package/dist/esm/daemon.d.ts +94 -0
- package/dist/esm/daemon.d.ts.map +1 -0
- package/dist/esm/daemon.js +499 -0
- package/dist/esm/daemonConfig.d.ts +45 -0
- package/dist/esm/daemonConfig.d.ts.map +1 -0
- package/dist/esm/daemonConfig.js +142 -0
- package/dist/esm/daemonEnv.d.ts +10 -0
- package/dist/esm/daemonEnv.d.ts.map +1 -0
- package/dist/esm/daemonEnv.js +9 -0
- package/dist/esm/durable/clientTool.d.ts +39 -0
- package/dist/esm/durable/clientTool.d.ts.map +1 -0
- package/dist/esm/durable/clientTool.js +82 -0
- package/dist/esm/durable/index.d.ts +9 -0
- package/dist/esm/durable/index.d.ts.map +1 -0
- package/dist/esm/durable/index.js +8 -0
- package/dist/esm/durable/journal.d.ts +218 -0
- package/dist/esm/durable/journal.d.ts.map +1 -0
- package/dist/esm/durable/journal.js +374 -0
- package/dist/esm/durable/pause.d.ts +84 -0
- package/dist/esm/durable/pause.d.ts.map +1 -0
- package/dist/esm/durable/pause.js +226 -0
- package/dist/esm/durable/resume.d.ts +27 -0
- package/dist/esm/durable/resume.d.ts.map +1 -0
- package/dist/esm/durable/resume.js +72 -0
- package/dist/esm/durable/snapshotSaver.d.ts +38 -0
- package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
- package/dist/esm/durable/snapshotSaver.js +77 -0
- package/dist/esm/durable/step.d.ts +28 -0
- package/dist/esm/durable/step.d.ts.map +1 -0
- package/dist/esm/durable/step.js +36 -0
- package/dist/esm/index.d.ts +30 -7
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +20 -4
- package/dist/esm/infrastructure.d.ts +50 -0
- package/dist/esm/infrastructure.d.ts.map +1 -0
- package/dist/esm/infrastructure.js +156 -0
- package/dist/esm/langChain.d.ts +15 -3
- package/dist/esm/langChain.d.ts.map +1 -1
- package/dist/esm/langChain.js +984 -179
- package/dist/esm/learningActivityMedia.d.ts +196 -0
- package/dist/esm/learningActivityMedia.d.ts.map +1 -0
- package/dist/esm/learningActivityMedia.js +807 -0
- package/dist/esm/learningContentPlan.d.ts +117 -0
- package/dist/esm/learningContentPlan.d.ts.map +1 -0
- package/dist/esm/learningContentPlan.js +320 -0
- package/dist/esm/learningContentThread.d.ts +213 -0
- package/dist/esm/learningContentThread.d.ts.map +1 -0
- package/dist/esm/learningContentThread.js +403 -0
- package/dist/esm/logger.d.ts +1 -0
- package/dist/esm/logger.d.ts.map +1 -1
- package/dist/esm/logger.js +17 -3
- package/dist/esm/modelRates.d.ts +40 -0
- package/dist/esm/modelRates.d.ts.map +1 -0
- package/dist/esm/modelRates.js +68 -0
- package/dist/esm/referenceContext.d.ts +4 -145
- package/dist/esm/referenceContext.d.ts.map +1 -1
- package/dist/esm/referenceContext.js +16 -243
- package/dist/esm/retry.d.ts +64 -0
- package/dist/esm/retry.d.ts.map +1 -0
- package/dist/esm/retry.js +127 -0
- package/dist/esm/runtimeContext.d.ts +8 -1
- package/dist/esm/runtimeContext.d.ts.map +1 -1
- package/dist/esm/runtimeContext.js +3 -1
- package/dist/esm/serve.d.ts +3 -2
- package/dist/esm/serve.d.ts.map +1 -1
- package/dist/esm/serve.js +33 -3
- package/dist/esm/sourceStore.d.ts +378 -0
- package/dist/esm/sourceStore.d.ts.map +1 -0
- package/dist/esm/sourceStore.js +855 -0
- package/dist/esm/stackfactorKnowledge.d.ts +91 -7
- package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
- package/dist/esm/stackfactorKnowledge.js +101 -41
- package/dist/esm/tavily.d.ts +108 -4
- package/dist/esm/tavily.d.ts.map +1 -1
- package/dist/esm/tavily.js +237 -20
- package/dist/esm/usage.d.ts.map +1 -1
- package/dist/esm/usage.js +9 -15
- package/dist/esm/version.d.ts +3 -0
- package/dist/esm/version.d.ts.map +1 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/workflow/bookkeeping.d.ts +78 -0
- package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
- package/dist/esm/workflow/bookkeeping.js +67 -0
- package/dist/esm/workflow/index.d.ts +13 -0
- package/dist/esm/workflow/index.d.ts.map +1 -0
- package/dist/esm/workflow/index.js +10 -0
- package/dist/esm/workflow/limits.d.ts +52 -0
- package/dist/esm/workflow/limits.d.ts.map +1 -0
- package/dist/esm/workflow/limits.js +59 -0
- package/dist/esm/workflow/platformTransport.d.ts +39 -0
- package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
- package/dist/esm/workflow/platformTransport.js +110 -0
- package/dist/esm/workflow/retrying.d.ts +44 -0
- package/dist/esm/workflow/retrying.d.ts.map +1 -0
- package/dist/esm/workflow/retrying.js +73 -0
- package/dist/esm/workflow/run.d.ts +195 -0
- package/dist/esm/workflow/run.d.ts.map +1 -0
- package/dist/esm/workflow/run.js +850 -0
- package/dist/esm/workflow/testing/index.d.ts +3 -0
- package/dist/esm/workflow/testing/index.d.ts.map +1 -0
- package/dist/esm/workflow/testing/index.js +2 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
- package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
- package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
- package/dist/esm/workflow/transport.d.ts +219 -0
- package/dist/esm/workflow/transport.d.ts.map +1 -0
- package/dist/esm/workflow/transport.js +16 -0
- package/package.json +8 -7
package/dist/esm/tavily.js
CHANGED
|
@@ -4,7 +4,11 @@ import constants from "./const.js";
|
|
|
4
4
|
import errorHandlingHelper from "./errorHandling.js";
|
|
5
5
|
import logger from "./logger.js";
|
|
6
6
|
import { getAbortSignal } from "./runtimeContext.js";
|
|
7
|
+
import { isRequestCancelled, requestCancelledError, throwIfRequestCancelled } from "./cancellation.js";
|
|
7
8
|
import { recordUsage } from "./usage.js";
|
|
9
|
+
import { requirePricedModel } from "./modelRates.js";
|
|
10
|
+
import { RETRY_WAITS } from "./retry.js";
|
|
11
|
+
import { noteAttempted, noteSources, noteUsage } from "./durable/journal.js";
|
|
8
12
|
const TAVILY_API_BASE = "https://api.tavily.com";
|
|
9
13
|
/**
|
|
10
14
|
* Context budgets, in characters, applied to everything a tool hands back to
|
|
@@ -77,8 +81,9 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
77
81
|
* before the time this library already told the caller it had.
|
|
78
82
|
*
|
|
79
83
|
* Rate-limit (429) and server (5xx) responses are retried with exponential
|
|
80
|
-
* backoff — everything else
|
|
81
|
-
*
|
|
84
|
+
* backoff — everything else fails immediately. A request its caller
|
|
85
|
+
* cancelled makes no call and stops with "Request cancelled by caller",
|
|
86
|
+
* before a call, during one and between retries.
|
|
82
87
|
* @param endpoint - The Tavily endpoint name, e.g. `"search"`
|
|
83
88
|
* @param body - Request body in the API's snake_case form; `undefined` values
|
|
84
89
|
* are dropped so Tavily applies its own defaults
|
|
@@ -86,7 +91,11 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
86
91
|
* @param timeoutSeconds - Per-request timeout forwarded to Tavily
|
|
87
92
|
* @returns The parsed JSON response
|
|
88
93
|
*/
|
|
94
|
+
/** The name Tavily's credits are counted and priced under. */
|
|
95
|
+
const TAVILY_MODEL = "tavily";
|
|
89
96
|
const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
|
|
97
|
+
// Tavily bills credits like a model bills tokens: no rate, no call.
|
|
98
|
+
await requirePricedModel(TAVILY_MODEL);
|
|
90
99
|
const payload = {
|
|
91
100
|
include_usage: true,
|
|
92
101
|
timeout: timeoutSeconds,
|
|
@@ -96,6 +105,8 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
|
|
|
96
105
|
payload[key] = value;
|
|
97
106
|
}
|
|
98
107
|
for (let attempt = 0;; attempt++) {
|
|
108
|
+
// A cancelled request makes no further call, and says so.
|
|
109
|
+
throwIfRequestCancelled();
|
|
99
110
|
let response;
|
|
100
111
|
try {
|
|
101
112
|
response = await fetch(`${TAVILY_API_BASE}/${endpoint}`, {
|
|
@@ -111,6 +122,10 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
|
|
|
111
122
|
});
|
|
112
123
|
}
|
|
113
124
|
catch (err) {
|
|
125
|
+
// The request's own signal ended the fetch: the caller is gone, and
|
|
126
|
+
// Tavily did not fail.
|
|
127
|
+
if (isRequestCancelled())
|
|
128
|
+
throw requestCancelledError();
|
|
114
129
|
throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Tavily ${endpoint} request failed: ${err?.message || String(err)}`);
|
|
115
130
|
}
|
|
116
131
|
if (response.ok)
|
|
@@ -124,8 +139,6 @@ const callTavily = async (endpoint, body, apiKey, timeoutSeconds) => {
|
|
|
124
139
|
throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Tavily ${endpoint} returned ${response.status}: ${detail.slice(0, 500)}`);
|
|
125
140
|
}
|
|
126
141
|
};
|
|
127
|
-
/** The name Tavily's credits are counted and priced under. */
|
|
128
|
-
const TAVILY_MODEL = "tavily";
|
|
129
142
|
/**
|
|
130
143
|
* Counts one Tavily call's credits and records the URLs it returned. Credits
|
|
131
144
|
* come from the response's own `usage` block; they are counted into the
|
|
@@ -142,7 +155,9 @@ const TAVILY_MODEL = "tavily";
|
|
|
142
155
|
const recordTavilyUsage = (tracker, _config, credits, sources) => {
|
|
143
156
|
if (Number.isFinite(credits) && credits > 0) {
|
|
144
157
|
recordUsage(TAVILY_MODEL, "credits", credits);
|
|
158
|
+
noteUsage("tavilyCredits", credits);
|
|
145
159
|
}
|
|
160
|
+
noteSources(sources);
|
|
146
161
|
if (!tracker)
|
|
147
162
|
return;
|
|
148
163
|
if (typeof tracker.cost !== "number")
|
|
@@ -172,6 +187,8 @@ const recordTavilyUsage = (tracker, _config, credits, sources) => {
|
|
|
172
187
|
* @param urls - The URLs sent
|
|
173
188
|
*/
|
|
174
189
|
const recordAttemptedUrls = (tracker, urls) => {
|
|
190
|
+
if (urls.length > 0)
|
|
191
|
+
noteAttempted(urls);
|
|
175
192
|
if (!tracker || urls.length === 0)
|
|
176
193
|
return;
|
|
177
194
|
const attempted = tracker.attemptedUrls || (tracker.attemptedUrls = []);
|
|
@@ -492,25 +509,33 @@ const isWebUrl = (url) => {
|
|
|
492
509
|
* fetch under `failed_results`. So a URL listed there is unreachable, and every
|
|
493
510
|
* other URL of a batch Tavily answered is reachable (the results may name a
|
|
494
511
|
* URL by its address after a redirect, which is why they are not matched). A
|
|
495
|
-
* batch whose call fails outright, or a config without `tavilyAPIKey`,
|
|
496
|
-
*
|
|
512
|
+
* batch whose call fails outright, or a config without `tavilyAPIKey`, says
|
|
513
|
+
* nothing about its URLs: they are `unchecked`, which is not `unreachable`.
|
|
514
|
+
* The caller decides what an unchecked link is worth; dropping it as dead
|
|
515
|
+
* loses every citation to one failed call.
|
|
497
516
|
*
|
|
498
|
-
* @param urls - The URLs to check; a URL given twice is checked once
|
|
517
|
+
* @param urls - The URLs to check; a URL given twice is checked once. A value
|
|
518
|
+
* that is no string is in no set
|
|
499
519
|
* @param config - The integration config; supplies `tavilyAPIKey`
|
|
500
520
|
* @param usageTracker - Optional accumulator the credits are counted into
|
|
501
|
-
* @returns The given URLs, exactly as passed,
|
|
521
|
+
* @returns The given URLs, exactly as passed, each in one of the three sets
|
|
502
522
|
*/
|
|
503
|
-
export const
|
|
504
|
-
const
|
|
505
|
-
const
|
|
506
|
-
|
|
507
|
-
|
|
523
|
+
export const checkUrls = async (urls, config, usageTracker = null) => {
|
|
524
|
+
const check = { reachable: new Set(), unreachable: new Set(), unchecked: new Set() };
|
|
525
|
+
const given = [...new Set(urls.filter((url) => typeof url === "string"))];
|
|
526
|
+
const candidates = given.filter((url) => isWebUrl(url.trim()));
|
|
527
|
+
for (const url of given) {
|
|
528
|
+
if (!isWebUrl(url.trim()))
|
|
529
|
+
check.unreachable.add(url);
|
|
530
|
+
}
|
|
508
531
|
if (candidates.length === 0)
|
|
509
|
-
return
|
|
532
|
+
return check;
|
|
510
533
|
const apiKey = config?.tavilyAPIKey;
|
|
511
534
|
if (!apiKey) {
|
|
512
|
-
logger.log(null, logger.levels.warn, `Tavily reachability: no tavilyAPIKey, so none of ${candidates.length} URL(s) is
|
|
513
|
-
|
|
535
|
+
logger.log(null, logger.levels.warn, `Tavily reachability: no tavilyAPIKey, so none of ${candidates.length} URL(s) is checked`);
|
|
536
|
+
for (const url of candidates)
|
|
537
|
+
check.unchecked.add(url);
|
|
538
|
+
return check;
|
|
514
539
|
}
|
|
515
540
|
const batches = [];
|
|
516
541
|
for (let start = 0; start < candidates.length; start += EXTRACT_MAX_URLS) {
|
|
@@ -526,7 +551,13 @@ export const checkUrlsReachable = async (urls, config, usageTracker = null) => {
|
|
|
526
551
|
}, apiKey, REACHABILITY_TIMEOUT_SECONDS);
|
|
527
552
|
}
|
|
528
553
|
catch (err) {
|
|
529
|
-
|
|
554
|
+
// A cancelled request is not a check that failed: its links are not
|
|
555
|
+
// "unchecked", to be waited for and asked again. It stops.
|
|
556
|
+
if (isRequestCancelled())
|
|
557
|
+
throw err;
|
|
558
|
+
logger.log(null, logger.levels.warn, `Tavily reachability: the check of ${batch.length} URL(s) failed (${err?.message || String(err)}), so none of them is checked`);
|
|
559
|
+
for (const url of batch)
|
|
560
|
+
check.unchecked.add(url);
|
|
530
561
|
return;
|
|
531
562
|
}
|
|
532
563
|
recordTavilyUsage(usageTracker, config, data?.usage?.credits || 0, []);
|
|
@@ -534,16 +565,202 @@ export const checkUrlsReachable = async (urls, config, usageTracker = null) => {
|
|
|
534
565
|
.map((entry) => typeof entry?.url === "string" ? urlMatchKey(entry.url) : "")
|
|
535
566
|
.filter(Boolean));
|
|
536
567
|
for (const url of batch) {
|
|
537
|
-
|
|
538
|
-
reachable.add(url);
|
|
568
|
+
(failed.has(urlMatchKey(url)) ? check.unreachable : check.reachable).add(url);
|
|
539
569
|
}
|
|
540
570
|
}));
|
|
541
|
-
return
|
|
571
|
+
return check;
|
|
572
|
+
};
|
|
573
|
+
/** What a URL that is not `http:` or `https:` is answered with. */
|
|
574
|
+
const NOT_A_WEB_URL = "Not a web address";
|
|
575
|
+
/** What every URL is answered with when the config has no `tavilyAPIKey`. */
|
|
576
|
+
const NO_PAGE_READER = "The page reader is not configured";
|
|
577
|
+
/** What a URL Tavily neither returned nor listed as failed is answered with. */
|
|
578
|
+
const NOT_RETURNED = "The page reader returned nothing for it";
|
|
579
|
+
/**
|
|
580
|
+
* Reads URLs in full, without a model: each page's whole text as markdown, or
|
|
581
|
+
* why it could not be read. What a run's source store holds of the pages its
|
|
582
|
+
* references point at (`sourceStore.prepareSources`).
|
|
583
|
+
*
|
|
584
|
+
* Nothing is trimmed here: Tavily returns whatever the page holds, which for a
|
|
585
|
+
* long PDF is over a million characters. The caller holds the text outside the
|
|
586
|
+
* model's context and hands it over a page at a time.
|
|
587
|
+
*
|
|
588
|
+
* They go in batches of 20, Tavily's limit, and are billed and recorded like
|
|
589
|
+
* every other Tavily call (`tavilyCredits`, `webSearchSources`,
|
|
590
|
+
* `attemptedUrls`). A URL Tavily could not fetch is asked for once more: its
|
|
591
|
+
* answer does not tell a page that is gone from one that failed for a moment.
|
|
592
|
+
* Tavily may name a result by the address it was redirected to, so a URL it
|
|
593
|
+
* neither returned under its own address nor listed as failed is asked for
|
|
594
|
+
* again on its own, where the one result is its.
|
|
595
|
+
*
|
|
596
|
+
* @param urls - The URLs to read; a URL given twice is read once. A value
|
|
597
|
+
* that is no string is left out
|
|
598
|
+
* @param config - The integration config; supplies `tavilyAPIKey`
|
|
599
|
+
* @param usageTracker - Optional accumulator the credits are counted into
|
|
600
|
+
* @returns One entry per distinct URL, in the order given
|
|
601
|
+
*/
|
|
602
|
+
export const readUrls = async (urls, config, usageTracker = null) => {
|
|
603
|
+
const given = [...new Set(urls.filter((url) => typeof url === "string"))];
|
|
604
|
+
const reads = new Map(given.map((url) => [url, { url, error: NOT_A_WEB_URL }]));
|
|
605
|
+
const candidates = given.filter((url) => isWebUrl(url.trim()));
|
|
606
|
+
const answers = () => given.map((url) => reads.get(url));
|
|
607
|
+
if (candidates.length === 0)
|
|
608
|
+
return answers();
|
|
609
|
+
const apiKey = config?.tavilyAPIKey;
|
|
610
|
+
if (!apiKey) {
|
|
611
|
+
logger.log(null, logger.levels.warn, `Tavily read: no tavilyAPIKey, so none of ${candidates.length} URL(s) is read`);
|
|
612
|
+
for (const url of candidates)
|
|
613
|
+
reads.set(url, { url, error: NO_PAGE_READER });
|
|
614
|
+
return answers();
|
|
615
|
+
}
|
|
616
|
+
/** Reads one batch; returns the URLs to ask for again, and whether on their own. */
|
|
617
|
+
const readBatch = async (batch) => {
|
|
618
|
+
recordAttemptedUrls(usageTracker, batch.map((url) => url.trim()));
|
|
619
|
+
let data;
|
|
620
|
+
try {
|
|
621
|
+
data = await callTavily("extract", { urls: batch.map((url) => url.trim()), format: "markdown" }, apiKey, DEFAULT_TIMEOUT_SECONDS);
|
|
622
|
+
}
|
|
623
|
+
catch (err) {
|
|
624
|
+
if (isRequestCancelled())
|
|
625
|
+
throw err;
|
|
626
|
+
const error = err?.message || String(err);
|
|
627
|
+
logger.log(null, logger.levels.warn, `Tavily read: the read of ${batch.length} URL(s) failed (${error})`);
|
|
628
|
+
for (const url of batch)
|
|
629
|
+
reads.set(url, { url, error });
|
|
630
|
+
return { failed: batch, unmatched: [] };
|
|
631
|
+
}
|
|
632
|
+
const results = Array.isArray(data?.results) ? data.results : [];
|
|
633
|
+
recordTavilyUsage(usageTracker, config, data?.usage?.credits || 0, results.map((result) => ({
|
|
634
|
+
url: result?.url,
|
|
635
|
+
...(result?.title ? { title: result.title } : {}),
|
|
636
|
+
})));
|
|
637
|
+
const byKey = new Map(results
|
|
638
|
+
.filter((result) => typeof result?.url === "string")
|
|
639
|
+
.map((result) => [urlMatchKey(result.url), result]));
|
|
640
|
+
const failures = new Map((Array.isArray(data?.failed_results) ? data.failed_results : [])
|
|
641
|
+
.filter((entry) => typeof entry?.url === "string")
|
|
642
|
+
.map((entry) => [urlMatchKey(entry.url), String(entry?.error || "Failed to fetch url")]));
|
|
643
|
+
const failed = [];
|
|
644
|
+
const unmatched = [];
|
|
645
|
+
for (const url of batch) {
|
|
646
|
+
const key = urlMatchKey(url);
|
|
647
|
+
// A batch of one has one answer, whatever address it is named by.
|
|
648
|
+
const result = byKey.get(key) ?? (batch.length === 1 && !failures.size ? results[0] : undefined);
|
|
649
|
+
if (result) {
|
|
650
|
+
reads.set(url, {
|
|
651
|
+
url,
|
|
652
|
+
text: typeof result.raw_content === "string" ? result.raw_content : "",
|
|
653
|
+
...(typeof result.title === "string" && result.title ? { title: result.title } : {}),
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
else if (failures.has(key) || (batch.length === 1 && failures.size > 0)) {
|
|
657
|
+
reads.set(url, { url, error: failures.get(key) ?? [...failures.values()][0] });
|
|
658
|
+
failed.push(url);
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
reads.set(url, { url, error: NOT_RETURNED });
|
|
662
|
+
unmatched.push(url);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return { failed, unmatched };
|
|
666
|
+
};
|
|
667
|
+
const batchesOf = (list) => {
|
|
668
|
+
const batches = [];
|
|
669
|
+
for (let start = 0; start < list.length; start += EXTRACT_MAX_URLS) {
|
|
670
|
+
batches.push(list.slice(start, start + EXTRACT_MAX_URLS));
|
|
671
|
+
}
|
|
672
|
+
return batches;
|
|
673
|
+
};
|
|
674
|
+
const first = await Promise.all(batchesOf(candidates).map(readBatch));
|
|
675
|
+
const again = first.flatMap((outcome) => outcome.failed);
|
|
676
|
+
const alone = first.flatMap((outcome) => outcome.unmatched);
|
|
677
|
+
// Once more, and no further: what a second answer leaves unread stays unread.
|
|
678
|
+
await Promise.all([
|
|
679
|
+
...batchesOf(again).map(readBatch),
|
|
680
|
+
...alone.map((url) => readBatch([url])),
|
|
681
|
+
]);
|
|
682
|
+
return answers();
|
|
683
|
+
};
|
|
684
|
+
/**
|
|
685
|
+
* A cited link's check did not run, after the retries: Tavily's call for it
|
|
686
|
+
* failed, or no key was configured. Such a link is not dead, so nothing is
|
|
687
|
+
* dropped for it; the person is asked to try again. Its message is the coded
|
|
688
|
+
* JSON an agent's failure carries (`{ code, message }`, 503), so `serve`
|
|
689
|
+
* answers the person with the sentence, not a 500.
|
|
690
|
+
*/
|
|
691
|
+
export class LinksNotCheckedError extends Error {
|
|
692
|
+
code = 503;
|
|
693
|
+
/** How many of the links went unchecked. */
|
|
694
|
+
unchecked;
|
|
695
|
+
/** How many links were checked, each once. */
|
|
696
|
+
total;
|
|
697
|
+
/**
|
|
698
|
+
* @param unchecked How many of the links went unchecked
|
|
699
|
+
* @param total How many links were checked, each once
|
|
700
|
+
*/
|
|
701
|
+
constructor(unchecked, total) {
|
|
702
|
+
super(JSON.stringify({
|
|
703
|
+
code: 503,
|
|
704
|
+
message: `The cited links could not be checked (${unchecked} of ${total}). Try again shortly.`,
|
|
705
|
+
}));
|
|
706
|
+
this.name = "LinksNotCheckedError";
|
|
707
|
+
this.unchecked = unchecked;
|
|
708
|
+
this.total = total;
|
|
709
|
+
Object.setPrototypeOf(this, LinksNotCheckedError.prototype);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* The cited links that are dead: the ones Tavily could not fetch, and any
|
|
714
|
+
* that is no web link (`checkUrls`). A link whose check did not run (one
|
|
715
|
+
* dropped connection fails the 20 links of its call) is checked again, with
|
|
716
|
+
* the others like it and no link already settled, after each of the waits.
|
|
717
|
+
* One still unchecked after them is not called dead: the call throws, so the
|
|
718
|
+
* caller drops nothing for a check that did not run.
|
|
719
|
+
*
|
|
720
|
+
* @param urls - The links; a link given twice is checked once
|
|
721
|
+
* @param config - The integration config; supplies `tavilyAPIKey`
|
|
722
|
+
* @param usageTracker - Optional accumulator the credits are counted into
|
|
723
|
+
* @param options - `waits` (default RETRY_WAITS) and `sleep`
|
|
724
|
+
* @returns The dead links, each exactly as passed
|
|
725
|
+
* @throws {LinksNotCheckedError} When a link is still unchecked after the waits
|
|
726
|
+
*/
|
|
727
|
+
export const unreachableUrls = async (urls, config, usageTracker = null, options = {}) => {
|
|
728
|
+
const pause = options.sleep ?? sleep;
|
|
729
|
+
let check = await checkUrls(urls, config, usageTracker);
|
|
730
|
+
const total = check.reachable.size + check.unreachable.size + check.unchecked.size;
|
|
731
|
+
const dead = new Set(check.unreachable);
|
|
732
|
+
for (const ms of options.waits ?? RETRY_WAITS) {
|
|
733
|
+
if (check.unchecked.size === 0)
|
|
734
|
+
break;
|
|
735
|
+
logger.log(null, logger.levels.warn, `Tavily reachability: ${check.unchecked.size} of ${total} link(s) could not be checked; checking them again in ${ms} ms`);
|
|
736
|
+
await pause(ms);
|
|
737
|
+
check = await checkUrls([...check.unchecked], config, usageTracker);
|
|
738
|
+
for (const url of check.unreachable)
|
|
739
|
+
dead.add(url);
|
|
740
|
+
}
|
|
741
|
+
if (check.unchecked.size > 0)
|
|
742
|
+
throw new LinksNotCheckedError(check.unchecked.size, total);
|
|
743
|
+
return dead;
|
|
542
744
|
};
|
|
745
|
+
/**
|
|
746
|
+
* The URLs of `checkUrls` that Tavily fetched, and nothing about the rest.
|
|
747
|
+
*
|
|
748
|
+
* @deprecated Use `checkUrls`. This answer cannot tell a dead link from one
|
|
749
|
+
* whose check did not run, so a caller that drops what is missing from it
|
|
750
|
+
* drops every link when one call fails.
|
|
751
|
+
* @param urls - The URLs to check
|
|
752
|
+
* @param config - The integration config; supplies `tavilyAPIKey`
|
|
753
|
+
* @param usageTracker - Optional accumulator the credits are counted into
|
|
754
|
+
* @returns The given URLs, exactly as passed, that resolve
|
|
755
|
+
*/
|
|
756
|
+
export const checkUrlsReachable = async (urls, config, usageTracker = null) => (await checkUrls(urls, config, usageTracker)).reachable;
|
|
543
757
|
export default {
|
|
544
758
|
assertTavilyUsable,
|
|
545
759
|
buildTavilyTools,
|
|
760
|
+
checkUrls,
|
|
546
761
|
checkUrlsReachable,
|
|
762
|
+
readUrls,
|
|
763
|
+
unreachableUrls,
|
|
547
764
|
getTavilyOptions,
|
|
548
765
|
recordTavilyUsage,
|
|
549
766
|
};
|
package/dist/esm/usage.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/usage.ts"],"names":[],"mappings":"
|
|
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/esm/usage.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { integration as clientIntegration } from "@stackfactor/client-api";
|
|
3
3
|
import logger from "./logger.js";
|
|
4
|
+
import { retryTransient } from "./retry.js";
|
|
4
5
|
import { getContext } from "./runtimeContext.js";
|
|
5
6
|
/**
|
|
6
7
|
* What an agent used, and how the platform gets to know.
|
|
@@ -27,8 +28,7 @@ export const USAGE_UNITS = [
|
|
|
27
28
|
];
|
|
28
29
|
/** Entries one report may carry (the platform's limit). */
|
|
29
30
|
const REPORT_ENTRIES_MAX = 100;
|
|
30
|
-
/**
|
|
31
|
-
const REPORT_ATTEMPTS = 3;
|
|
31
|
+
/** 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). */
|
|
32
32
|
const REPORT_RETRY_BASE_MS = 500;
|
|
33
33
|
/** How often work that is still running reports what it used so far. */
|
|
34
34
|
export const USAGE_REPORT_INTERVAL_MS = 60_000;
|
|
@@ -81,22 +81,16 @@ export const recordUsage = (model, unit, amount) => {
|
|
|
81
81
|
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
82
82
|
const defaultReport = (usage, reportId, token) => clientIntegration.reportRunUsage(usage, reportId, token);
|
|
83
83
|
/**
|
|
84
|
-
* Sends one report, again when it fails
|
|
85
|
-
*
|
|
84
|
+
* Sends one report, again when it fails for a reason that may pass
|
|
85
|
+
* (retryTransient: a 5xx, a rate limit, the network; never a refusal), under
|
|
86
|
+
* the same name every time: the platform charges a report it has seen only
|
|
87
|
+
* once.
|
|
86
88
|
*/
|
|
87
89
|
const send = async (entries, token, report, retryBaseMs) => {
|
|
88
90
|
const reportId = randomUUID();
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
catch (error) {
|
|
95
|
-
if (attempt >= REPORT_ATTEMPTS)
|
|
96
|
-
throw error;
|
|
97
|
-
await delay(retryBaseMs * 2 ** (attempt - 1));
|
|
98
|
-
}
|
|
99
|
-
}
|
|
91
|
+
await retryTransient("the usage report", () => report(entries, reportId, token), {
|
|
92
|
+
waits: [retryBaseMs, retryBaseMs * 2],
|
|
93
|
+
});
|
|
100
94
|
};
|
|
101
95
|
/**
|
|
102
96
|
* Reports what the request used and has not reported yet. Never throws, and
|
|
@@ -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,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,67 @@
|
|
|
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
|
+
export const STATE_VERSION = 1;
|
|
11
|
+
/** Turn records kept, the oldest dropped first. */
|
|
12
|
+
export const TURNS_KEPT = 50;
|
|
13
|
+
const emptyRunner = () => ({ outbox: [], turns: [], lastWrite: null });
|
|
14
|
+
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
15
|
+
/**
|
|
16
|
+
* Splits a stored `state` into the agent's part and the runner's. A state this
|
|
17
|
+
* runner did not write (null on a new workflow, or a value from before the
|
|
18
|
+
* runner) is all the agent's. One written by a newer runner is refused rather
|
|
19
|
+
* than read as the agent's: wrapping it again would bury that runner's
|
|
20
|
+
* bookkeeping where neither runner would find it.
|
|
21
|
+
*/
|
|
22
|
+
export const readState = (stored) => {
|
|
23
|
+
if (isObject(stored) && "runner" in stored && "v" in stored) {
|
|
24
|
+
if (stored.v !== STATE_VERSION) {
|
|
25
|
+
throw new Error(`workflow state was written by a newer runner (v ${String(stored.v)}); this runner reads v ${STATE_VERSION}`);
|
|
26
|
+
}
|
|
27
|
+
const runner = isObject(stored.runner) ? stored.runner : {};
|
|
28
|
+
return {
|
|
29
|
+
agent: stored.agent ?? null,
|
|
30
|
+
runner: {
|
|
31
|
+
outbox: Array.isArray(runner.outbox) ? [...runner.outbox] : [],
|
|
32
|
+
turns: Array.isArray(runner.turns) ? [...runner.turns] : [],
|
|
33
|
+
lastWrite: isObject(runner.lastWrite) ? runner.lastWrite : null,
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
return { agent: stored ?? null, runner: emptyRunner() };
|
|
38
|
+
};
|
|
39
|
+
/** The agent's part of a stored state. */
|
|
40
|
+
export const agentOf = (stored) => readState(stored).agent;
|
|
41
|
+
/**
|
|
42
|
+
* The state as stored: the agent's part and the runner's, versioned. The
|
|
43
|
+
* runner's part is copied, so a body already sent (and retried as sent) does
|
|
44
|
+
* not change when the runner's bookkeeping moves on.
|
|
45
|
+
*/
|
|
46
|
+
export const storedState = (agent, runner) => ({
|
|
47
|
+
v: STATE_VERSION,
|
|
48
|
+
agent: agent === undefined ? null : agent,
|
|
49
|
+
runner: {
|
|
50
|
+
outbox: [...runner.outbox],
|
|
51
|
+
turns: [...runner.turns],
|
|
52
|
+
lastWrite: runner.lastWrite ? { ...runner.lastWrite } : null,
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
/** The turn records with `record` added, the last {@link TURNS_KEPT}. */
|
|
56
|
+
export const withTurn = (turns, record) => [...turns, record].slice(-TURNS_KEPT);
|
|
57
|
+
/**
|
|
58
|
+
* The outbox to send: what an earlier attempt of the turn stored and did not
|
|
59
|
+
* clear, and what this attempt added, one entry per key (the later wins, in
|
|
60
|
+
* the earlier's place).
|
|
61
|
+
*/
|
|
62
|
+
export const mergeOutbox = (stored, added) => {
|
|
63
|
+
const byKey = new Map();
|
|
64
|
+
for (const entry of [...stored, ...added])
|
|
65
|
+
byKey.set(entry.key, entry);
|
|
66
|
+
return [...byKey.values()];
|
|
67
|
+
};
|
|
@@ -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"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The `workflow` module (runner spec): `workflow.run`, its transports
|
|
2
|
+
// (`platformTransport`, `retrying`), `workflow.LIMITS` and the in-memory
|
|
3
|
+
// transport, `workflow.testing.memoryTransport()`, with the wire types an
|
|
4
|
+
// agent's turns are written against.
|
|
5
|
+
import * as testing from "./testing/index.js";
|
|
6
|
+
export { run, messageAdapter } from "./run.js";
|
|
7
|
+
export { platformTransport } from "./platformTransport.js";
|
|
8
|
+
export { retrying } from "./retrying.js";
|
|
9
|
+
export { LIMITS } from "./limits.js";
|
|
10
|
+
export { testing };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The limits the platform enforces on an agent workflow (runner spec §2):
|
|
3
|
+
* backend-core's `INTEGRATIONS.WORKFLOW` values, every number and pattern of
|
|
4
|
+
* it, plus the lease's default length (`AGENT_POOL.TASK_LEASE_DEFAULT_SECONDS`,
|
|
5
|
+
* which agent pools §13 put in place of `SERVICE_LEASE_SECONDS` and
|
|
6
|
+
* `JOB_LEASE_DEFAULT_SECONDS`). The in-memory transport enforces them, and a
|
|
7
|
+
* turn can plan around them (declare fewer waits, keep `state` small).
|
|
8
|
+
*
|
|
9
|
+
* Core's contract test asserts its constants equal these (runner spec §6,
|
|
10
|
+
* change 3), so the two cannot drift without a failing test. Frozen, so no
|
|
11
|
+
* agent can loosen a limit for every other caller in the process.
|
|
12
|
+
*/
|
|
13
|
+
export declare const LIMITS: Readonly<{
|
|
14
|
+
STATE_MAX_BYTES: number;
|
|
15
|
+
INBOX_MAX: 200;
|
|
16
|
+
INBOX_EVENT_DATA_MAX_BYTES: number;
|
|
17
|
+
SIGNAL_INPUT_MAX_BYTES: number;
|
|
18
|
+
OPEN_WAITS_MAX: 50;
|
|
19
|
+
OPEN_INPUT_WAITS_MAX: 16;
|
|
20
|
+
OPEN_WAITS_MAX_BYTES: number;
|
|
21
|
+
SETTLED_WAITS_KEPT: 100;
|
|
22
|
+
CHECKPOINT_MAX_BYTES: number;
|
|
23
|
+
QUEUED_RUN_RETRY_SECONDS: 60;
|
|
24
|
+
ENDED_RETENTION_DAYS: 30;
|
|
25
|
+
MAX_TURNS: 1000;
|
|
26
|
+
MAX_TURNS_PER_HOUR: 60;
|
|
27
|
+
MIN_TIMER_SECONDS: 60;
|
|
28
|
+
INPUT_MAX_ATTEMPTS: 3;
|
|
29
|
+
WORKFLOW_SWEEP_PER_TENANT: 500;
|
|
30
|
+
KEY_PATTERN: RegExp;
|
|
31
|
+
WAIT_TAG_PATTERN: RegExp;
|
|
32
|
+
WAIT_FIELD_MAX_CHARS: 128;
|
|
33
|
+
CODE_MAX_CHARS: 256;
|
|
34
|
+
CONTACTS_MAX: 20;
|
|
35
|
+
ADDRESSEES_MAX: 20;
|
|
36
|
+
MAX_QUESTIONS_PER_WAIT: 20;
|
|
37
|
+
QUESTIONS_MAX_BYTES: number;
|
|
38
|
+
ANSWERS_MAX_BYTES: number;
|
|
39
|
+
TITLE_MAX_CHARS: 200;
|
|
40
|
+
QUESTION_MAX_CHARS: 2000;
|
|
41
|
+
DETAILS_MAX_CHARS: 20000;
|
|
42
|
+
CHOICES_MAX: 20;
|
|
43
|
+
CHOICE_MAX_CHARS: 200;
|
|
44
|
+
ANSWER_TEXT_MAX_CHARS: 20000;
|
|
45
|
+
REJECT_MESSAGE_MAX_CHARS: 4000;
|
|
46
|
+
TOOL_WAIT_DEFAULT_DEADLINE_SECONDS: 900;
|
|
47
|
+
TOOL_NAME_MAX_CHARS: 128;
|
|
48
|
+
TOOL_ERROR_MESSAGE_MAX_CHARS: 4000;
|
|
49
|
+
TASK_LEASE_DEFAULT_SECONDS: 7200;
|
|
50
|
+
}>;
|
|
51
|
+
export type Limits = typeof LIMITS;
|
|
52
|
+
//# sourceMappingURL=limits.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limits.d.ts","sourceRoot":"","sources":["../../../src/workflow/limits.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4CjB,CAAC;AAEH,MAAM,MAAM,MAAM,GAAG,OAAO,MAAM,CAAC"}
|