@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
@@ -0,0 +1,392 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.journaled = exports.currentFrame = exports.DurableTurn = exports.noteAttempted = exports.noteSources = exports.noteUsage = exports.activeTurn = exports.reapplyUsage = exports.emptyUsage = exports.failure = exports.DurablePause = exports.DurableReplayMismatchError = void 0;
7
+ const node_async_hooks_1 = require("node:async_hooks");
8
+ const langgraph_1 = require("@langchain/langgraph");
9
+ const const_js_1 = __importDefault(require("../const.js"));
10
+ const errorHandling_js_1 = require("../errorHandling.js");
11
+ const logger_js_1 = __importDefault(require("../logger.js"));
12
+ /**
13
+ * The paused turn ran again and took a different path: a unit at a key the
14
+ * journal holds is not the unit the journal saved there (the agent was
15
+ * republished between the pause and the resume). A 500 that fails the run
16
+ * rather than guess (design §12).
17
+ */
18
+ class DurableReplayMismatchError extends errorHandling_js_1.AppError {
19
+ key;
20
+ expected;
21
+ found;
22
+ constructor(key, expected, found) {
23
+ super({
24
+ code: const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR,
25
+ message: `The paused turn ran again and took a different path: at ${key} it saved a ${expected} and now starts a ${found}. The agent changed while the turn was paused, so it cannot be resumed.`,
26
+ });
27
+ this.key = key;
28
+ this.expected = expected;
29
+ this.found = found;
30
+ this.name = "DurableReplayMismatchError";
31
+ Object.setPrototypeOf(this, DurableReplayMismatchError.prototype);
32
+ }
33
+ }
34
+ exports.DurableReplayMismatchError = DurableReplayMismatchError;
35
+ /**
36
+ * Thrown to unwind a turn that paused (an interrupt in an LLM tool loop): the
37
+ * runner catches it, saves the conversation checkpoint and releases with the
38
+ * pause's input wait. Agent code lets it through.
39
+ */
40
+ class DurablePause extends Error {
41
+ constructor() {
42
+ super("durable: the turn paused for an answer; let this error through so the workflow runner can wait for it");
43
+ this.name = "DurablePause";
44
+ Object.setPrototypeOf(this, DurablePause.prototype);
45
+ }
46
+ }
47
+ exports.DurablePause = DurablePause;
48
+ /** A refusal with a status, as `errorHandling.create` makes them. */
49
+ const failure = (code, message) => new errorHandling_js_1.AppError({ code, message });
50
+ exports.failure = failure;
51
+ // ── Codecs: how a result is kept in the snapshot ────────────────────────
52
+ /** A step's result is JSON (rule 4): copied as JSON when it is recorded, so a caller's later change cannot reach the journal. */
53
+ const jsonCopy = (value) => value === undefined ? undefined : JSON.parse(JSON.stringify(value));
54
+ /** LangChain's own serializer, the one LangGraph keeps messages with: an agent's answer revives as messages. */
55
+ const serde = new langgraph_1.MemorySaver().serde;
56
+ const encodeLangChain = async (value) => {
57
+ if (value === undefined)
58
+ return undefined;
59
+ const [, bytes] = await serde.dumpsTyped(value);
60
+ return JSON.parse(Buffer.from(bytes).toString("utf8"));
61
+ };
62
+ const decodeLangChain = async (stored) => stored === undefined ? undefined : serde.loadsTyped("json", new TextEncoder().encode(JSON.stringify(stored)));
63
+ // ── Usage ───────────────────────────────────────────────────────────────
64
+ const emptyUsage = () => ({ cost: 0, tokens: {} });
65
+ exports.emptyUsage = emptyUsage;
66
+ const addTokens = (into, tokens) => {
67
+ for (const [key, amount] of Object.entries(tokens ?? {})) {
68
+ if (!Number.isFinite(amount) || amount <= 0)
69
+ continue;
70
+ into.tokens[key] = (into.tokens[key] || 0) + amount;
71
+ }
72
+ };
73
+ const addSources = (into, sources = []) => {
74
+ for (const source of sources) {
75
+ if (!source?.url)
76
+ continue;
77
+ const list = into.webSearchSources || (into.webSearchSources = []);
78
+ if (!list.some((entry) => entry.url === source.url))
79
+ list.push({ ...source });
80
+ }
81
+ };
82
+ const addAttempted = (into, urls = []) => {
83
+ for (const url of urls) {
84
+ const list = into.attemptedUrls || (into.attemptedUrls = []);
85
+ if (!list.includes(url))
86
+ list.push(url);
87
+ }
88
+ };
89
+ const addUsage = (into, usage) => {
90
+ if (!usage)
91
+ return;
92
+ addTokens(into, usage.tokens);
93
+ addSources(into, usage.webSearchSources);
94
+ addAttempted(into, usage.attemptedUrls);
95
+ };
96
+ /**
97
+ * Gives a replayed unit's usage back to the caller's tracker, and only to it:
98
+ * the platform's usage ledger (`recordUsage`) was told when it was spent.
99
+ */
100
+ const reapplyUsage = (tracker, usage) => {
101
+ if (!tracker || !usage)
102
+ return;
103
+ if (typeof tracker.cost !== "number")
104
+ tracker.cost = 0;
105
+ if (!tracker.tokens || typeof tracker.tokens !== "object")
106
+ tracker.tokens = {};
107
+ addUsage(tracker, usage);
108
+ };
109
+ exports.reapplyUsage = reapplyUsage;
110
+ const frames = new node_async_hooks_1.AsyncLocalStorage();
111
+ /** The turn a call runs in, when it may journal and pause: inside a `workflow.run` turn, outside an agent's tools. */
112
+ const activeTurn = () => {
113
+ const frame = frames.getStore();
114
+ return frame && !frame.passthrough ? frame.turn : null;
115
+ };
116
+ exports.activeTurn = activeTurn;
117
+ const eachUsage = (each) => {
118
+ for (let frame = frames.getStore(); frame; frame = frame.parent)
119
+ if (frame.usage)
120
+ each(frame.usage);
121
+ };
122
+ /** Counts usage into every unit the call runs in (`countUsage` and the Tavily tools call this beside the tracker). */
123
+ const noteUsage = (key, amount) => {
124
+ if (!Number.isFinite(amount) || amount <= 0)
125
+ return;
126
+ eachUsage((usage) => addTokens(usage, { [key]: amount }));
127
+ };
128
+ exports.noteUsage = noteUsage;
129
+ /** The web sources a Tavily call returned, into every unit the call runs in. */
130
+ const noteSources = (sources) => eachUsage((usage) => addSources(usage, sources));
131
+ exports.noteSources = noteSources;
132
+ /** The URLs `web_extract` asked for, into every unit the call runs in. */
133
+ const noteAttempted = (urls) => eachUsage((usage) => addAttempted(usage, urls));
134
+ exports.noteAttempted = noteAttempted;
135
+ const prefixOf = (scope) => (scope.prefix === "" ? "" : `${scope.prefix}/`);
136
+ /**
137
+ * One turn's journal and what it paused on. The runner makes one per turn and
138
+ * runs the turn in it; `langChain` journals its calls through it and
139
+ * `durable.step` its steps.
140
+ */
141
+ class DurableTurn {
142
+ entries = new Map();
143
+ paused = new Map();
144
+ threads = new Map();
145
+ answers = new Map();
146
+ used = new Set();
147
+ inflight = new Map();
148
+ /** The interrupts this turn stopped on; one wait asks them all. */
149
+ interruptions = [];
150
+ creator;
151
+ now;
152
+ /**
153
+ * Whether the turn runs on an event's input, whose run does not know the
154
+ * workflow's creator: a pause must then name its addressees (Ruling 34), a
155
+ * rule `checkPauseSettings` enforces before the model is called. The runner
156
+ * sets it once the turn's input is known (a resumed turn's is the paused
157
+ * turn's own).
158
+ */
159
+ event = false;
160
+ /** Units that returned their saved result instead of running. */
161
+ hits = 0;
162
+ constructor(init = {}) {
163
+ for (const [key, entry] of Object.entries(init.journal?.entries ?? {})) {
164
+ this.entries.set(key, { name: entry.name, usage: entry.usage ?? null, stored: entry.result, isLive: false });
165
+ }
166
+ for (const [key, unit] of Object.entries(init.journal?.paused ?? {}))
167
+ this.paused.set(key, unit);
168
+ for (const [key, thread] of Object.entries(init.threads ?? {}))
169
+ this.threads.set(key, thread);
170
+ for (const [id, answer] of Object.entries({ ...(init.journal?.answers ?? {}), ...(init.answers ?? {}) })) {
171
+ this.answers.set(id, answer);
172
+ }
173
+ this.creator = init.creator ?? null;
174
+ this.now = init.now ?? (() => Date.now());
175
+ }
176
+ /** Whether a unit of this turn stopped on an interrupt: nothing new starts after it. */
177
+ get pausing() {
178
+ return this.interruptions.length > 0;
179
+ }
180
+ /** Runs `fn` as this turn: its calls journal here. */
181
+ run(fn) {
182
+ return frames.run({ turn: this, scope: { prefix: "", seq: 0 }, usage: null, parent: null, passthrough: false }, async () => fn());
183
+ }
184
+ claim(key) {
185
+ if (this.used.has(key)) {
186
+ throw (0, exports.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable: ${key} ran twice in one turn; give each durable.step in a scope its own key`);
187
+ }
188
+ this.used.add(key);
189
+ }
190
+ /** A unit of the other kind saved at this position of the scope: the turn took another path. */
191
+ mismatch(key, other, found) {
192
+ const held = this.entries.get(other) ?? (this.paused.has(other) ? { name: "agent" } : null);
193
+ if (held && held.name !== found)
194
+ throw new DurableReplayMismatchError(key, held.name, found);
195
+ }
196
+ /** A unit the snapshot holds: what it finished in the run that paused (a key runs once per run, so never one finished in this run). */
197
+ async replay(frame, held, tracker) {
198
+ this.hits += 1;
199
+ (0, exports.reapplyUsage)(tracker, held.usage);
200
+ for (let up = frame; up; up = up.parent)
201
+ if (up.usage)
202
+ addUsage(up.usage, held.usage);
203
+ return held.name === "step" ? jsonCopy(held.stored) : await decodeLangChain(held.stored);
204
+ }
205
+ track(promise, key) {
206
+ this.inflight.set(promise, key);
207
+ const forget = () => {
208
+ this.inflight.delete(promise);
209
+ };
210
+ promise.then(forget, forget);
211
+ return promise;
212
+ }
213
+ /** The answers given to `key`'s interrupts, by interrupt id. */
214
+ resumeOf(key) {
215
+ const prefix = `g:${key}:`;
216
+ const resume = {};
217
+ for (const [id, answer] of this.answers)
218
+ if (id.startsWith(prefix))
219
+ resume[id.slice(prefix.length)] = answer;
220
+ return resume;
221
+ }
222
+ /** Forgets what the snapshot held under `key` and every key below it. */
223
+ forget(key, below) {
224
+ const under = (candidate) => candidate === key || (below && candidate.startsWith(`${key}/`));
225
+ for (const held of [...this.entries.keys()])
226
+ if (below && held.startsWith(`${key}/`))
227
+ this.entries.delete(held);
228
+ for (const paused of [...this.paused.keys()])
229
+ if (under(paused))
230
+ this.paused.delete(paused);
231
+ for (const thread of [...this.threads.keys()])
232
+ if (under(thread))
233
+ this.threads.delete(thread);
234
+ for (const id of [...this.answers.keys()]) {
235
+ const unit = id.slice(2, id.lastIndexOf(":"));
236
+ if (id.startsWith("g:") && under(unit))
237
+ this.answers.delete(id);
238
+ }
239
+ }
240
+ /**
241
+ * A `llm` or `agent` unit: its saved result when the journal holds one,
242
+ * else `body`, journaled when it finishes.
243
+ */
244
+ async unit(frame, name, tracker, body) {
245
+ if (this.pausing)
246
+ throw new DurablePause();
247
+ const n = frame.scope.seq++;
248
+ const key = `${prefixOf(frame.scope)}${name}#${n}`;
249
+ this.claim(key);
250
+ this.mismatch(key, `${prefixOf(frame.scope)}${name === "llm" ? "agent" : "llm"}#${n}`, name);
251
+ const held = this.entries.get(key);
252
+ if (held)
253
+ return (await this.replay(frame, held, tracker));
254
+ const paused = this.paused.get(key) ?? null;
255
+ const usage = (0, exports.emptyUsage)();
256
+ const unitFrame = { turn: this, scope: { prefix: key, seq: 0 }, usage, parent: frame, passthrough: name === "agent" };
257
+ const context = {
258
+ key,
259
+ paused,
260
+ thread: this.threads.get(key) ?? null,
261
+ resume: this.resumeOf(key),
262
+ pause: (stop) => {
263
+ this.interruptions.push({ ...stop, key, usage });
264
+ throw new DurablePause();
265
+ },
266
+ };
267
+ if (paused) {
268
+ const asked = [...(paused.asked ?? [])].sort();
269
+ if (asked.length === 0) {
270
+ // Its wait asked none of its calls (others filled the wait): it waits
271
+ // on, unchanged, and is asked this time.
272
+ this.interruptions.push({
273
+ key,
274
+ interrupts: paused.interrupts ?? [],
275
+ thread: context.thread,
276
+ usage: paused.usage,
277
+ counted: paused.counted,
278
+ options: paused.options ?? {},
279
+ });
280
+ this.forget(key, false);
281
+ throw new DurablePause();
282
+ }
283
+ // Each answer goes to the call it was asked for: a map with other ids
284
+ // would reach LangGraph as one value for every interrupt.
285
+ const given = Object.keys(context.resume).sort();
286
+ if (given.length !== asked.length || given.some((id, i) => id !== asked[i])) {
287
+ throw (0, exports.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable: the answers to ${key} are not the ones its wait asked: it asked ${asked.join(", ")} and was answered ${given.join(", ") || "nothing"}`);
288
+ }
289
+ // Counted before the pause, in the run that spent it: the tracker only.
290
+ (0, exports.reapplyUsage)(tracker, paused.usage);
291
+ for (let up = unitFrame; up; up = up.parent)
292
+ if (up.usage)
293
+ addUsage(up.usage, paused.usage);
294
+ this.forget(key, false);
295
+ }
296
+ const value = await this.track(frames.run(unitFrame, () => body(context)), key);
297
+ this.entries.set(key, { name, usage, live: value, isLive: true });
298
+ return value;
299
+ }
300
+ /** `durable.step`: its saved result when the journal holds one, else `fn` in a scope of its own. */
301
+ async step(frame, key, fn, tracker) {
302
+ if (this.pausing)
303
+ throw new DurablePause();
304
+ const full = `${prefixOf(frame.scope)}step:${key}`;
305
+ this.claim(full);
306
+ const held = this.entries.get(full);
307
+ if (held) {
308
+ if (held.name !== "step")
309
+ throw new DurableReplayMismatchError(full, held.name, "step");
310
+ return (await this.replay(frame, held, tracker));
311
+ }
312
+ const usage = (0, exports.emptyUsage)();
313
+ const stepFrame = { turn: this, scope: { prefix: full, seq: 0 }, usage, parent: frame, passthrough: false };
314
+ const value = await this.track(frames.run(stepFrame, () => fn()), full);
315
+ // A finished step keeps only its own result: its children never run again.
316
+ // The caller gets a JSON copy of that (serialized once for the journal), so a Date is a
317
+ // string whether the step ran now or is replayed. A result that is not
318
+ // JSON throws here, before anything is journaled: `fn`'s side effect has
319
+ // already happened, and the step runs again on the next attempt.
320
+ let stored;
321
+ try {
322
+ stored = jsonCopy(value);
323
+ }
324
+ catch (error) {
325
+ this.forget(full, true);
326
+ throw (0, exports.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable.step "${key}" returned a result that is not JSON (${error.message}): return plain data, such as ids`);
327
+ }
328
+ this.forget(full, true);
329
+ this.entries.set(full, { name: "step", usage, stored, isLive: false });
330
+ return jsonCopy(stored);
331
+ }
332
+ /**
333
+ * Waits for the units still running when the turn paused, so that what they
334
+ * finish is journaled and not run again on the resume (up to `ms`). Answers
335
+ * the keys of those still running then.
336
+ */
337
+ async drain(ms, sleep) {
338
+ if (this.inflight.size === 0)
339
+ return [];
340
+ const stop = new AbortController();
341
+ const settled = Promise.allSettled([...this.inflight.keys()]).then(() => true);
342
+ const drained = await Promise.race([settled, sleep(ms, stop.signal).then(() => false)]);
343
+ stop.abort();
344
+ if (drained)
345
+ return [];
346
+ const running = [...this.inflight.values()];
347
+ for (const key of running) {
348
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `durable: ${key} was still running ${Math.round(ms / 1000)} s after the turn paused; it will run again when the turn resumes`);
349
+ }
350
+ return running;
351
+ }
352
+ /** The journal and the paused threads for the snapshot: every finished entry, the paused units, the answers still needed. */
353
+ /**
354
+ * @param asked - The ids (`g:<key>:<interruptId>`) of the questions this
355
+ * pause's wait asks; every interrupt when omitted
356
+ */
357
+ async export(asked) {
358
+ const entries = {};
359
+ for (const [key, held] of this.entries) {
360
+ const result = held.isLive ? (held.name === "step" ? jsonCopy(held.live) : await encodeLangChain(held.live)) : held.stored;
361
+ entries[key] = { name: held.name, ...(result !== undefined ? { result } : {}), ...(held.usage ? { usage: held.usage } : {}) };
362
+ }
363
+ const paused = Object.fromEntries(this.paused);
364
+ const threads = Object.fromEntries(this.threads);
365
+ for (const stop of this.interruptions) {
366
+ paused[stop.key] = {
367
+ usage: stop.usage,
368
+ counted: stop.counted,
369
+ interrupts: stop.interrupts,
370
+ asked: stop.interrupts.map((interrupt) => interrupt.id).filter((id) => !asked || asked.has(`g:${stop.key}:${id}`)),
371
+ options: stop.options,
372
+ };
373
+ threads[stop.key] = stop.thread;
374
+ }
375
+ return { journal: { entries, answers: Object.fromEntries(this.answers), paused }, threads };
376
+ }
377
+ }
378
+ exports.DurableTurn = DurableTurn;
379
+ /** The frame a call runs in, or null outside a `workflow.run` turn. */
380
+ const currentFrame = () => frames.getStore() ?? null;
381
+ exports.currentFrame = currentFrame;
382
+ /**
383
+ * Runs a `llm` or `agent` unit through the turn's journal: outside a turn, or
384
+ * under an agent's tools, `body` runs as it always has.
385
+ */
386
+ const journaled = async (name, tracker, body) => {
387
+ const frame = frames.getStore();
388
+ if (!frame || frame.passthrough)
389
+ return body(null);
390
+ return frame.turn.unit(frame, name, tracker, body);
391
+ };
392
+ exports.journaled = journaled;
@@ -0,0 +1,84 @@
1
+ import type { RunQuestion, WaitDecl } from "../workflow/transport.js";
2
+ import type { DurableTurn } from "./journal.js";
3
+ /** The tag of a pause's wait: `durable:<checkpoint step>`, so its resume finds the snapshot it was declared for. */
4
+ export declare const PAUSE_TAG_PREFIX = "durable:";
5
+ /** How long a pause waits for the units still running before it saves the checkpoint. */
6
+ export declare const AGENT_PAUSE_DRAIN_MS = 120000;
7
+ /** An approval or a question waits this long when config.approvals sets no deadline. */
8
+ export declare const APPROVAL_DEFAULT_DEADLINE_SECONDS: number;
9
+ export declare const SNAPSHOT_FORMAT = "stackfactor.durable-turn";
10
+ export declare const SNAPSHOT_VERSION = 1;
11
+ /**
12
+ * Waits `ms` of wall time, or less when `signal` aborts: the drain waits for
13
+ * work that is really running, so a test's virtual clock does not apply. The
14
+ * timer does not keep the process alive.
15
+ */
16
+ export declare const drainSleep: (ms: number, signal?: AbortSignal | null) => Promise<void>;
17
+ /** A package's version by the path of its package.json, or "unknown" when it cannot be read. */
18
+ export declare const versionOf: (id: string) => string;
19
+ /**
20
+ * The versions a snapshot records: agent-utils' own (read relative to this
21
+ * file, so only in the CommonJS build; "unknown" in the ES module build,
22
+ * where it is informational only) and `@langchain/langgraph` as agent-utils
23
+ * resolves it, whose major a resume checks.
24
+ */
25
+ export declare const versions: () => {
26
+ agentUtils: string;
27
+ langgraph: string;
28
+ };
29
+ /** A version's major: the part before the first dot. */
30
+ export declare const majorOf: (version: string) => string;
31
+ /**
32
+ * What a pause asks, of whom, until when. The deadline is resolved when the
33
+ * wait is declared, after the checkpoint upload ({@link deadlineOf}): counted
34
+ * from before it, a short one could be under the platform's floor by then.
35
+ */
36
+ export interface PausePlan {
37
+ questions: RunQuestion[];
38
+ title: string;
39
+ addressees: string[];
40
+ /** The earliest deadline config.approvals set, in ms; null when none did. */
41
+ dueAt: number | null;
42
+ /** Otherwise how long from the declaration: config.clientTools.deadline's earliest, or seven days. */
43
+ dueInMs: number;
44
+ }
45
+ /** The wait's deadline, declared at `now`. */
46
+ export declare const deadlineOf: (plan: PausePlan, now: number) => string;
47
+ /**
48
+ * The wait a paused turn releases with: every interrupt of every unit that
49
+ * stopped, as one wait's questions. A tool wait (client tools' calls only) is
50
+ * addressed to config.clientTools.addressees, or the workflow's creator, and
51
+ * due config.clientTools.deadline seconds from now (default
52
+ * TOOL_WAIT_DEFAULT_DEADLINE_SECONDS, the earliest across the units); any
53
+ * other to config.approvals.addressees, or the creator, by the earliest
54
+ * config.approvals.deadline, or in seven days. A person cannot run a tool and
55
+ * a machine cannot answer a question, so one pause cannot ask both (I2).
56
+ */
57
+ export declare const planPause: (turn: DurableTurn, { event }?: {
58
+ event?: boolean;
59
+ }) => PausePlan;
60
+ /** The pause's `input` wait, tagged with the checkpoint step it was saved as, declared at `now`. */
61
+ export declare const waitOf: (plan: PausePlan, step: number, now: number) => WaitDecl;
62
+ /**
63
+ * Refuses a checkpoint over CHECKPOINT_MAX_BYTES before it is sent: the
64
+ * platform would answer 413 for a body it has already been sent whole.
65
+ * @param bytes - The gzipped snapshot
66
+ * @param max - The limit; LIMITS.CHECKPOINT_MAX_BYTES
67
+ */
68
+ export declare const checkCheckpointSize: (bytes: Uint8Array, max?: number) => void;
69
+ /** The turn that paused, run again on its resume: its own input and `decide`'s answer for it. */
70
+ export interface PausedTurnRef {
71
+ input: unknown;
72
+ decision: string | null;
73
+ }
74
+ /**
75
+ * The conversation checkpoint (design §5.5): the journal, the paused threads,
76
+ * the questions of this pause and the turn's own input, as gzip of JSON.
77
+ */
78
+ export declare const snapshotOf: (turn: DurableTurn, plan: PausePlan, ref: PausedTurnRef) => Promise<{
79
+ bytes: Buffer;
80
+ size: number;
81
+ entries: number;
82
+ threads: number;
83
+ }>;
84
+ //# sourceMappingURL=pause.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pause.d.ts","sourceRoot":"","sources":["../../../src/durable/pause.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAGtE,OAAO,KAAK,EAAE,WAAW,EAA2B,MAAM,cAAc,CAAC;AAMzE,oHAAoH;AACpH,eAAO,MAAM,gBAAgB,aAAa,CAAC;AAC3C,yFAAyF;AACzF,eAAO,MAAM,oBAAoB,SAAU,CAAC;AAC5C,wFAAwF;AACxF,eAAO,MAAM,iCAAiC,QAAgB,CAAC;AAC/D,eAAO,MAAM,eAAe,6BAA6B,CAAC;AAC1D,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAIlC;;;;GAIG;AACH,eAAO,MAAM,UAAU,GAAI,IAAI,MAAM,EAAE,SAAS,WAAW,GAAG,IAAI,KAAG,OAAO,CAAC,IAAI,CAY7E,CAAC;AAcL,gGAAgG;AAChG,eAAO,MAAM,SAAS,GAAI,IAAI,MAAM,KAAG,MAMtC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,QAAO;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAGjE,CAAC;AAEH,wDAAwD;AACxD,eAAO,MAAM,OAAO,GAAI,SAAS,MAAM,KAAG,MAAuC,CAAC;AAiDlF;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,WAAW,EAAE,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,6EAA6E;IAC7E,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,sGAAsG;IACtG,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,8CAA8C;AAC9C,eAAO,MAAM,UAAU,GAAI,MAAM,SAAS,EAAE,KAAK,MAAM,KAAG,MAAkE,CAAC;AAQ7H;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,GAAI,MAAM,WAAW,EAAE,YAAmB;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,KAAG,SAmE1F,CAAC;AAEF,oGAAoG;AACpG,eAAO,MAAM,MAAM,GAAI,MAAM,SAAS,EAAE,MAAM,MAAM,EAAE,KAAK,MAAM,KAAG,QAMlE,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,UAAU,EAAE,MAAK,MAAoC,KAAG,IAOlG,CAAC;AAIF,iGAAiG;AACjG,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,OAAO,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU,GACrB,MAAM,WAAW,EACjB,MAAM,SAAS,EACf,KAAK,aAAa,KACjB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAkB3E,CAAC"}