@stackfactor/agent-utils 1.13.4 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/README.md +667 -23
  2. package/dist/cjs/agentProto.d.ts +13 -3
  3. package/dist/cjs/agentProto.d.ts.map +1 -1
  4. package/dist/cjs/agentProto.js +25 -4
  5. package/dist/cjs/backoff.d.ts +17 -0
  6. package/dist/cjs/backoff.d.ts.map +1 -0
  7. package/dist/cjs/backoff.js +26 -0
  8. package/dist/cjs/cancellation.d.ts +22 -0
  9. package/dist/cjs/cancellation.d.ts.map +1 -0
  10. package/dist/cjs/cancellation.js +36 -0
  11. package/dist/cjs/cli.d.ts +3 -0
  12. package/dist/cjs/cli.d.ts.map +1 -0
  13. package/dist/cjs/cli.js +85 -0
  14. package/dist/cjs/client.d.ts +11 -0
  15. package/dist/cjs/client.d.ts.map +1 -1
  16. package/dist/cjs/client.js +27 -0
  17. package/dist/cjs/const.d.ts +23 -0
  18. package/dist/cjs/const.d.ts.map +1 -1
  19. package/dist/cjs/const.js +23 -0
  20. package/dist/cjs/daemon.d.ts +94 -0
  21. package/dist/cjs/daemon.d.ts.map +1 -0
  22. package/dist/cjs/daemon.js +507 -0
  23. package/dist/cjs/daemonConfig.d.ts +45 -0
  24. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  25. package/dist/cjs/daemonConfig.js +148 -0
  26. package/dist/cjs/daemonEnv.d.ts +10 -0
  27. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  28. package/dist/cjs/daemonEnv.js +12 -0
  29. package/dist/cjs/durable/clientTool.d.ts +39 -0
  30. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  31. package/dist/cjs/durable/clientTool.js +90 -0
  32. package/dist/cjs/durable/index.d.ts +9 -0
  33. package/dist/cjs/durable/index.d.ts.map +1 -0
  34. package/dist/cjs/durable/index.js +16 -0
  35. package/dist/cjs/durable/journal.d.ts +218 -0
  36. package/dist/cjs/durable/journal.d.ts.map +1 -0
  37. package/dist/cjs/durable/journal.js +392 -0
  38. package/dist/cjs/durable/pause.d.ts +84 -0
  39. package/dist/cjs/durable/pause.d.ts.map +1 -0
  40. package/dist/cjs/durable/pause.js +241 -0
  41. package/dist/cjs/durable/resume.d.ts +27 -0
  42. package/dist/cjs/durable/resume.d.ts.map +1 -0
  43. package/dist/cjs/durable/resume.js +80 -0
  44. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  46. package/dist/cjs/durable/snapshotSaver.js +81 -0
  47. package/dist/cjs/durable/step.d.ts +28 -0
  48. package/dist/cjs/durable/step.d.ts.map +1 -0
  49. package/dist/cjs/durable/step.js +43 -0
  50. package/dist/cjs/index.d.ts +30 -7
  51. package/dist/cjs/index.d.ts.map +1 -1
  52. package/dist/cjs/index.js +28 -1
  53. package/dist/cjs/infrastructure.d.ts +50 -0
  54. package/dist/cjs/infrastructure.d.ts.map +1 -0
  55. package/dist/cjs/infrastructure.js +163 -0
  56. package/dist/cjs/langChain.d.ts +15 -3
  57. package/dist/cjs/langChain.d.ts.map +1 -1
  58. package/dist/cjs/langChain.js +986 -180
  59. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  60. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  61. package/dist/cjs/learningActivityMedia.js +861 -0
  62. package/dist/cjs/learningContentPlan.d.ts +105 -0
  63. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  64. package/dist/cjs/learningContentPlan.js +305 -0
  65. package/dist/cjs/learningContentThread.d.ts +184 -0
  66. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  67. package/dist/cjs/learningContentThread.js +407 -0
  68. package/dist/cjs/logger.d.ts +1 -0
  69. package/dist/cjs/logger.d.ts.map +1 -1
  70. package/dist/cjs/logger.js +17 -3
  71. package/dist/cjs/modelRates.d.ts +40 -0
  72. package/dist/cjs/modelRates.d.ts.map +1 -0
  73. package/dist/cjs/modelRates.js +76 -0
  74. package/dist/cjs/referenceContext.d.ts +4 -145
  75. package/dist/cjs/referenceContext.d.ts.map +1 -1
  76. package/dist/cjs/referenceContext.js +16 -251
  77. package/dist/cjs/retry.d.ts +64 -0
  78. package/dist/cjs/retry.d.ts.map +1 -0
  79. package/dist/cjs/retry.js +138 -0
  80. package/dist/cjs/runtimeContext.d.ts +8 -1
  81. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  82. package/dist/cjs/runtimeContext.js +3 -1
  83. package/dist/cjs/serve.d.ts +3 -2
  84. package/dist/cjs/serve.d.ts.map +1 -1
  85. package/dist/cjs/serve.js +32 -2
  86. package/dist/cjs/sourceStore.d.ts +378 -0
  87. package/dist/cjs/sourceStore.d.ts.map +1 -0
  88. package/dist/cjs/sourceStore.js +872 -0
  89. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  90. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  91. package/dist/cjs/stackfactorKnowledge.js +108 -44
  92. package/dist/cjs/tavily.d.ts +108 -4
  93. package/dist/cjs/tavily.d.ts.map +1 -1
  94. package/dist/cjs/tavily.js +242 -21
  95. package/dist/cjs/usage.d.ts.map +1 -1
  96. package/dist/cjs/usage.js +9 -15
  97. package/dist/cjs/version.d.ts +3 -0
  98. package/dist/cjs/version.d.ts.map +1 -0
  99. package/dist/cjs/version.js +5 -0
  100. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  102. package/dist/cjs/workflow/bookkeeping.js +75 -0
  103. package/dist/cjs/workflow/index.d.ts +13 -0
  104. package/dist/cjs/workflow/index.d.ts.map +1 -0
  105. package/dist/cjs/workflow/index.js +51 -0
  106. package/dist/cjs/workflow/limits.d.ts +52 -0
  107. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  108. package/dist/cjs/workflow/limits.js +62 -0
  109. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  111. package/dist/cjs/workflow/platformTransport.js +115 -0
  112. package/dist/cjs/workflow/retrying.d.ts +44 -0
  113. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  114. package/dist/cjs/workflow/retrying.js +82 -0
  115. package/dist/cjs/workflow/run.d.ts +195 -0
  116. package/dist/cjs/workflow/run.d.ts.map +1 -0
  117. package/dist/cjs/workflow/run.js +858 -0
  118. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  119. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  120. package/dist/cjs/workflow/testing/index.js +6 -0
  121. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  124. package/dist/cjs/workflow/transport.d.ts +219 -0
  125. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  126. package/dist/cjs/workflow/transport.js +19 -0
  127. package/dist/esm/agentProto.d.ts +13 -3
  128. package/dist/esm/agentProto.d.ts.map +1 -1
  129. package/dist/esm/agentProto.js +23 -3
  130. package/dist/esm/backoff.d.ts +17 -0
  131. package/dist/esm/backoff.d.ts.map +1 -0
  132. package/dist/esm/backoff.js +22 -0
  133. package/dist/esm/cancellation.d.ts +22 -0
  134. package/dist/esm/cancellation.d.ts.map +1 -0
  135. package/dist/esm/cancellation.js +27 -0
  136. package/dist/esm/cli.d.ts +3 -0
  137. package/dist/esm/cli.d.ts.map +1 -0
  138. package/dist/esm/cli.js +80 -0
  139. package/dist/esm/client.d.ts +11 -0
  140. package/dist/esm/client.d.ts.map +1 -1
  141. package/dist/esm/client.js +25 -1
  142. package/dist/esm/const.d.ts +23 -0
  143. package/dist/esm/const.d.ts.map +1 -1
  144. package/dist/esm/const.js +23 -0
  145. package/dist/esm/daemon.d.ts +94 -0
  146. package/dist/esm/daemon.d.ts.map +1 -0
  147. package/dist/esm/daemon.js +499 -0
  148. package/dist/esm/daemonConfig.d.ts +45 -0
  149. package/dist/esm/daemonConfig.d.ts.map +1 -0
  150. package/dist/esm/daemonConfig.js +142 -0
  151. package/dist/esm/daemonEnv.d.ts +10 -0
  152. package/dist/esm/daemonEnv.d.ts.map +1 -0
  153. package/dist/esm/daemonEnv.js +9 -0
  154. package/dist/esm/durable/clientTool.d.ts +39 -0
  155. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  156. package/dist/esm/durable/clientTool.js +82 -0
  157. package/dist/esm/durable/index.d.ts +9 -0
  158. package/dist/esm/durable/index.d.ts.map +1 -0
  159. package/dist/esm/durable/index.js +8 -0
  160. package/dist/esm/durable/journal.d.ts +218 -0
  161. package/dist/esm/durable/journal.d.ts.map +1 -0
  162. package/dist/esm/durable/journal.js +374 -0
  163. package/dist/esm/durable/pause.d.ts +84 -0
  164. package/dist/esm/durable/pause.d.ts.map +1 -0
  165. package/dist/esm/durable/pause.js +226 -0
  166. package/dist/esm/durable/resume.d.ts +27 -0
  167. package/dist/esm/durable/resume.d.ts.map +1 -0
  168. package/dist/esm/durable/resume.js +72 -0
  169. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  171. package/dist/esm/durable/snapshotSaver.js +77 -0
  172. package/dist/esm/durable/step.d.ts +28 -0
  173. package/dist/esm/durable/step.d.ts.map +1 -0
  174. package/dist/esm/durable/step.js +36 -0
  175. package/dist/esm/index.d.ts +30 -7
  176. package/dist/esm/index.d.ts.map +1 -1
  177. package/dist/esm/index.js +20 -4
  178. package/dist/esm/infrastructure.d.ts +50 -0
  179. package/dist/esm/infrastructure.d.ts.map +1 -0
  180. package/dist/esm/infrastructure.js +156 -0
  181. package/dist/esm/langChain.d.ts +15 -3
  182. package/dist/esm/langChain.d.ts.map +1 -1
  183. package/dist/esm/langChain.js +984 -179
  184. package/dist/esm/learningActivityMedia.d.ts +196 -0
  185. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  186. package/dist/esm/learningActivityMedia.js +807 -0
  187. package/dist/esm/learningContentPlan.d.ts +105 -0
  188. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  189. package/dist/esm/learningContentPlan.js +299 -0
  190. package/dist/esm/learningContentThread.d.ts +184 -0
  191. package/dist/esm/learningContentThread.d.ts.map +1 -0
  192. package/dist/esm/learningContentThread.js +364 -0
  193. package/dist/esm/logger.d.ts +1 -0
  194. package/dist/esm/logger.d.ts.map +1 -1
  195. package/dist/esm/logger.js +17 -3
  196. package/dist/esm/modelRates.d.ts +40 -0
  197. package/dist/esm/modelRates.d.ts.map +1 -0
  198. package/dist/esm/modelRates.js +68 -0
  199. package/dist/esm/referenceContext.d.ts +4 -145
  200. package/dist/esm/referenceContext.d.ts.map +1 -1
  201. package/dist/esm/referenceContext.js +16 -243
  202. package/dist/esm/retry.d.ts +64 -0
  203. package/dist/esm/retry.d.ts.map +1 -0
  204. package/dist/esm/retry.js +127 -0
  205. package/dist/esm/runtimeContext.d.ts +8 -1
  206. package/dist/esm/runtimeContext.d.ts.map +1 -1
  207. package/dist/esm/runtimeContext.js +3 -1
  208. package/dist/esm/serve.d.ts +3 -2
  209. package/dist/esm/serve.d.ts.map +1 -1
  210. package/dist/esm/serve.js +33 -3
  211. package/dist/esm/sourceStore.d.ts +378 -0
  212. package/dist/esm/sourceStore.d.ts.map +1 -0
  213. package/dist/esm/sourceStore.js +855 -0
  214. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  215. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  216. package/dist/esm/stackfactorKnowledge.js +101 -41
  217. package/dist/esm/tavily.d.ts +108 -4
  218. package/dist/esm/tavily.d.ts.map +1 -1
  219. package/dist/esm/tavily.js +237 -20
  220. package/dist/esm/usage.d.ts.map +1 -1
  221. package/dist/esm/usage.js +9 -15
  222. package/dist/esm/version.d.ts +3 -0
  223. package/dist/esm/version.d.ts.map +1 -0
  224. package/dist/esm/version.js +2 -0
  225. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  227. package/dist/esm/workflow/bookkeeping.js +67 -0
  228. package/dist/esm/workflow/index.d.ts +13 -0
  229. package/dist/esm/workflow/index.d.ts.map +1 -0
  230. package/dist/esm/workflow/index.js +10 -0
  231. package/dist/esm/workflow/limits.d.ts +52 -0
  232. package/dist/esm/workflow/limits.d.ts.map +1 -0
  233. package/dist/esm/workflow/limits.js +59 -0
  234. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  235. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  236. package/dist/esm/workflow/platformTransport.js +110 -0
  237. package/dist/esm/workflow/retrying.d.ts +44 -0
  238. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  239. package/dist/esm/workflow/retrying.js +73 -0
  240. package/dist/esm/workflow/run.d.ts +195 -0
  241. package/dist/esm/workflow/run.d.ts.map +1 -0
  242. package/dist/esm/workflow/run.js +850 -0
  243. package/dist/esm/workflow/testing/index.d.ts +3 -0
  244. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  245. package/dist/esm/workflow/testing/index.js +2 -0
  246. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  248. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  249. package/dist/esm/workflow/transport.d.ts +219 -0
  250. package/dist/esm/workflow/transport.d.ts.map +1 -0
  251. package/dist/esm/workflow/transport.js +16 -0
  252. package/package.json +8 -7
@@ -0,0 +1,241 @@
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.snapshotOf = exports.checkCheckpointSize = exports.waitOf = exports.planPause = exports.deadlineOf = exports.majorOf = exports.versions = exports.versionOf = exports.drainSleep = exports.SNAPSHOT_VERSION = exports.SNAPSHOT_FORMAT = exports.APPROVAL_DEFAULT_DEADLINE_SECONDS = exports.AGENT_PAUSE_DRAIN_MS = exports.PAUSE_TAG_PREFIX = void 0;
7
+ const node_zlib_1 = require("node:zlib");
8
+ const const_js_1 = __importDefault(require("../const.js"));
9
+ const limits_js_1 = require("../workflow/limits.js");
10
+ const journal_js_1 = require("./journal.js");
11
+ // The pause (design #964 §10.2): a turn's interrupts become the questions of
12
+ // one `input` wait, and the turn's journal and paused threads become the
13
+ // conversation checkpoint (§5.5) saved before the wait is declared.
14
+ /** The tag of a pause's wait: `durable:<checkpoint step>`, so its resume finds the snapshot it was declared for. */
15
+ exports.PAUSE_TAG_PREFIX = "durable:";
16
+ /** How long a pause waits for the units still running before it saves the checkpoint. */
17
+ exports.AGENT_PAUSE_DRAIN_MS = 120_000;
18
+ /** An approval or a question waits this long when config.approvals sets no deadline. */
19
+ exports.APPROVAL_DEFAULT_DEADLINE_SECONDS = 7 * 24 * 3600;
20
+ exports.SNAPSHOT_FORMAT = "stackfactor.durable-turn";
21
+ exports.SNAPSHOT_VERSION = 1;
22
+ const INTERNAL = const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR;
23
+ /**
24
+ * Waits `ms` of wall time, or less when `signal` aborts: the drain waits for
25
+ * work that is really running, so a test's virtual clock does not apply. The
26
+ * timer does not keep the process alive.
27
+ */
28
+ const drainSleep = (ms, signal) => new Promise((resolve) => {
29
+ const timer = setTimeout(resolve, ms);
30
+ timer.unref?.();
31
+ signal?.addEventListener("abort", () => {
32
+ clearTimeout(timer);
33
+ resolve();
34
+ }, { once: true });
35
+ });
36
+ exports.drainSleep = drainSleep;
37
+ // ── Versions ────────────────────────────────────────────────────────────
38
+ /** `require` in the CommonJS build; in the ES module build, one resolving from the working directory. */
39
+ const nodeRequire = () => {
40
+ if (typeof require === "function")
41
+ return require;
42
+ try {
43
+ return process.getBuiltinModule("node:module").createRequire(`${process.cwd()}/`);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ };
49
+ /** A package's version by the path of its package.json, or "unknown" when it cannot be read. */
50
+ const versionOf = (id) => {
51
+ try {
52
+ return String(nodeRequire()?.(id)?.version ?? "unknown");
53
+ }
54
+ catch {
55
+ return "unknown";
56
+ }
57
+ };
58
+ exports.versionOf = versionOf;
59
+ /**
60
+ * The versions a snapshot records: agent-utils' own (read relative to this
61
+ * file, so only in the CommonJS build; "unknown" in the ES module build,
62
+ * where it is informational only) and `@langchain/langgraph` as agent-utils
63
+ * resolves it, whose major a resume checks.
64
+ */
65
+ const versions = () => ({
66
+ agentUtils: typeof require === "function" ? (0, exports.versionOf)("../../../package.json") : "unknown",
67
+ langgraph: (0, exports.versionOf)("@langchain/langgraph/package.json"),
68
+ });
69
+ exports.versions = versions;
70
+ /** A version's major: the part before the first dot. */
71
+ const majorOf = (version) => String(version).split(".")[0];
72
+ exports.majorOf = majorOf;
73
+ // ── Questions ───────────────────────────────────────────────────────────
74
+ const clip = (text, max) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
75
+ /** A question for a person from a raw interrupt: a string, or `{ question, details?, choices?, allowFreeText? }`. */
76
+ const questionValue = (stop, interrupt) => {
77
+ const value = interrupt.value;
78
+ if (typeof value === "string")
79
+ return { question: value };
80
+ if (value && typeof value === "object" && typeof value.question === "string") {
81
+ return {
82
+ question: value.question,
83
+ ...(value.details !== undefined ? { details: value.details } : {}),
84
+ ...(value.choices !== undefined ? { choices: value.choices } : {}),
85
+ ...(value.allowFreeText !== undefined ? { allowFreeText: value.allowFreeText } : {}),
86
+ };
87
+ }
88
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: interrupt ${interrupt.id} of ${stop.key} asks nothing a person can answer: interrupt() a string or { question, details?, choices?, allowFreeText? }`);
89
+ };
90
+ /**
91
+ * One interrupt as a RunQuestion (§6.1, I2): `tool` for a client tool's call
92
+ * (`{ kind: "tool", name, args }`), `approval` when its value has
93
+ * actionRequests (humanInTheLoopMiddleware's HITLRequest), else `question`.
94
+ */
95
+ const questionOf = (stop, interrupt) => {
96
+ const id = `g:${stop.key}:${interrupt.id}`;
97
+ const value = interrupt.value;
98
+ if (value && typeof value === "object" && value.kind === "tool" && typeof value.name === "string") {
99
+ return {
100
+ id,
101
+ kind: "tool",
102
+ value: {
103
+ name: value.name,
104
+ args: value.args && typeof value.args === "object" ? value.args : {},
105
+ ...(typeof value.description === "string" && value.description.length > 0 ? { description: value.description } : {}),
106
+ },
107
+ };
108
+ }
109
+ if (value && typeof value === "object" && Array.isArray(value.actionRequests)) {
110
+ return { id, kind: "approval", value: { actionRequests: value.actionRequests, reviewConfigs: value.reviewConfigs } };
111
+ }
112
+ return { id, kind: "question", value: questionValue(stop, interrupt) };
113
+ };
114
+ /** The wait's deadline, declared at `now`. */
115
+ const deadlineOf = (plan, now) => new Date(plan.dueAt ?? now + plan.dueInMs).toISOString();
116
+ exports.deadlineOf = deadlineOf;
117
+ const timeOf = (value, what) => {
118
+ const ms = value instanceof Date ? value.getTime() : typeof value === "string" ? Date.parse(value) : NaN;
119
+ if (Number.isNaN(ms))
120
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: ${what} is not a time`);
121
+ return ms;
122
+ };
123
+ /**
124
+ * The wait a paused turn releases with: every interrupt of every unit that
125
+ * stopped, as one wait's questions. A tool wait (client tools' calls only) is
126
+ * addressed to config.clientTools.addressees, or the workflow's creator, and
127
+ * due config.clientTools.deadline seconds from now (default
128
+ * TOOL_WAIT_DEFAULT_DEADLINE_SECONDS, the earliest across the units); any
129
+ * other to config.approvals.addressees, or the creator, by the earliest
130
+ * config.approvals.deadline, or in seven days. A person cannot run a tool and
131
+ * a machine cannot answer a question, so one pause cannot ask both (I2).
132
+ */
133
+ const planPause = (turn, { event = false } = {}) => {
134
+ const all = turn.interruptions.flatMap((stop) => stop.interrupts.map((interrupt) => questionOf(stop, interrupt)));
135
+ if (all.length === 0)
136
+ throw (0, journal_js_1.failure)(INTERNAL, "durable: the turn paused with nothing to ask");
137
+ const tools = all.filter((question) => question.kind === "tool");
138
+ if (tools.length > 0 && tools.length < all.length) {
139
+ throw (0, journal_js_1.failure)(INTERNAL, "durable: a turn cannot wait on a client tool and a person at once: its client tool calls and its approvals or questions paused together; run them in separate turns");
140
+ }
141
+ // One wait asks at most MAX_QUESTIONS_PER_WAIT (core's limit, mirrored in
142
+ // LIMITS); the calls past it stay paused and are asked once these are
143
+ // answered, as LangGraph interrupts again on every call it has no answer for.
144
+ const questions = all.slice(0, limits_js_1.LIMITS.MAX_QUESTIONS_PER_WAIT);
145
+ const bytes = Buffer.byteLength(JSON.stringify(questions), "utf8");
146
+ if (bytes > limits_js_1.LIMITS.QUESTIONS_MAX_BYTES) {
147
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: the pause's questions are ${bytes} bytes of JSON, over QUESTIONS_MAX_BYTES (${limits_js_1.LIMITS.QUESTIONS_MAX_BYTES}): a tool call's args or an approval's request are too large to ask`);
148
+ }
149
+ const asked = new Set(questions.map((question) => question.id));
150
+ const forTools = tools.length > 0;
151
+ const setting = forTools ? "config.clientTools" : "config.approvals";
152
+ const addressees = new Set();
153
+ let dueAt = null;
154
+ let toolDueInMs = null;
155
+ for (const stop of turn.interruptions) {
156
+ if (!stop.interrupts.some((interrupt) => asked.has(`g:${stop.key}:${interrupt.id}`)))
157
+ continue;
158
+ const options = (forTools ? stop.options?.clientTools : stop.options?.approvals) ?? null;
159
+ if (event && !options?.addressees) {
160
+ // An event's run carries the event's user, who need not be the
161
+ // workflow's creator, and the platform does not tell the runner the
162
+ // creator yet (Ruling 34): the agent says who answers.
163
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: an event's turn must name who answers: set ${setting}.addressees (an event's run does not know the workflow's creator)`);
164
+ }
165
+ for (const id of options?.addressees ?? (turn.creator ? [turn.creator] : []))
166
+ addressees.add(String(id));
167
+ if (forTools) {
168
+ const ms = Number(options?.deadline ?? limits_js_1.LIMITS.TOOL_WAIT_DEFAULT_DEADLINE_SECONDS) * 1000;
169
+ toolDueInMs = toolDueInMs === null ? ms : Math.min(toolDueInMs, ms);
170
+ }
171
+ else if (options?.deadline !== undefined && options?.deadline !== null) {
172
+ const at = timeOf(options.deadline, "config.approvals.deadline");
173
+ dueAt = dueAt === null ? at : Math.min(dueAt, at);
174
+ }
175
+ }
176
+ if (addressees.size === 0) {
177
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: nobody to ask: the workflow has no creator; set ${setting}.addressees`);
178
+ }
179
+ const names = (kind, of) => [
180
+ ...new Set(questions.filter((question) => question.kind === kind).flatMap(of)),
181
+ ];
182
+ const approvals = names("approval", (question) => question.value.actionRequests.map((action) => action.name));
183
+ const title = forTools
184
+ ? `Client tool call: ${names("tool", (question) => [question.value.name]).join(", ")}`
185
+ : approvals.length > 0
186
+ ? `Approval needed: ${approvals.join(", ")}`
187
+ : String(questions[0].value.question);
188
+ return {
189
+ questions,
190
+ title: clip(title, limits_js_1.LIMITS.TITLE_MAX_CHARS),
191
+ addressees: [...addressees],
192
+ dueAt,
193
+ dueInMs: toolDueInMs ?? exports.APPROVAL_DEFAULT_DEADLINE_SECONDS * 1000,
194
+ };
195
+ };
196
+ exports.planPause = planPause;
197
+ /** The pause's `input` wait, tagged with the checkpoint step it was saved as, declared at `now`. */
198
+ const waitOf = (plan, step, now) => ({
199
+ kind: "input",
200
+ tag: `${exports.PAUSE_TAG_PREFIX}${step}`,
201
+ prompt: { title: plan.title, questions: plan.questions },
202
+ addressees: plan.addressees,
203
+ deadline: (0, exports.deadlineOf)(plan, now),
204
+ });
205
+ exports.waitOf = waitOf;
206
+ /**
207
+ * Refuses a checkpoint over CHECKPOINT_MAX_BYTES before it is sent: the
208
+ * platform would answer 413 for a body it has already been sent whole.
209
+ * @param bytes - The gzipped snapshot
210
+ * @param max - The limit; LIMITS.CHECKPOINT_MAX_BYTES
211
+ */
212
+ const checkCheckpointSize = (bytes, max = limits_js_1.LIMITS.CHECKPOINT_MAX_BYTES) => {
213
+ if (bytes.length > max) {
214
+ throw (0, journal_js_1.failure)(INTERNAL, `durable: the conversation checkpoint is ${bytes.length} bytes gzipped, over CHECKPOINT_MAX_BYTES (${max}): keep large tool outputs and media out of the conversation (store them in a durable.step and pass ids)`);
215
+ }
216
+ };
217
+ exports.checkCheckpointSize = checkCheckpointSize;
218
+ /**
219
+ * The conversation checkpoint (design §5.5): the journal, the paused threads,
220
+ * the questions of this pause and the turn's own input, as gzip of JSON.
221
+ */
222
+ const snapshotOf = async (turn, plan, ref) => {
223
+ const { journal, threads } = await turn.export(new Set(plan.questions.map((question) => question.id)));
224
+ const json = JSON.stringify({
225
+ format: exports.SNAPSHOT_FORMAT,
226
+ version: exports.SNAPSHOT_VERSION,
227
+ ...(0, exports.versions)(),
228
+ savedAt: new Date(turn.now()).toISOString(),
229
+ journal,
230
+ threads,
231
+ pending: plan.questions,
232
+ turn: { input: ref.input ?? null, decision: ref.decision ?? null },
233
+ });
234
+ return {
235
+ bytes: (0, node_zlib_1.gzipSync)(Buffer.from(json, "utf8")),
236
+ size: Buffer.byteLength(json, "utf8"),
237
+ entries: Object.keys(journal.entries).length,
238
+ threads: Object.keys(threads).length,
239
+ };
240
+ };
241
+ exports.snapshotOf = snapshotOf;
@@ -0,0 +1,27 @@
1
+ import type { Checkpoint } from "../workflow/transport.js";
2
+ import { DurableTurn } from "./journal.js";
3
+ /** Whether an input is the answer to a paused turn's wait: a resolved `input` wait tagged `durable:<step>`. Any other outcome is the turn's to decide. */
4
+ export declare const isPausedResume: (input: any) => boolean;
5
+ /** What a resume restores: the paused turn's own input and decision, and its journal. */
6
+ export interface Restored {
7
+ input: any;
8
+ decision: any;
9
+ step: number;
10
+ turn: DurableTurn;
11
+ }
12
+ /**
13
+ * Reads the conversation checkpoint a paused turn's wait was declared for,
14
+ * and rebuilds the turn from it with the wait's answers merged in. Refuses,
15
+ * with "the paused state could not be read", a checkpoint that is missing,
16
+ * fails its sha256, belongs to another pause, or was written by another
17
+ * format or another major of LangGraph (the agent was rebuilt while it
18
+ * waited).
19
+ * @param input - The resume input (`isPausedResume`)
20
+ * @param checkpoint - What `getCheckpoint` answered
21
+ * @param init - The rebuilt turn's creator and clock
22
+ */
23
+ export declare const restore: (input: any, checkpoint: Checkpoint | null, init: {
24
+ creator?: string | null;
25
+ now?: () => number;
26
+ }) => Restored;
27
+ //# sourceMappingURL=resume.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resume.d.ts","sourceRoot":"","sources":["../../../src/durable/resume.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAW,MAAM,cAAc,CAAC;AAUpD,0JAA0J;AAC1J,eAAO,MAAM,cAAc,GAAI,OAAO,GAAG,KAAG,OAKJ,CAAC;AAEzC,yFAAyF;AACzF,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,GAAG,CAAC;IACX,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,WAAW,CAAC;CACnB;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,OAAO,GAClB,OAAO,GAAG,EACV,YAAY,UAAU,GAAG,IAAI,EAC7B,MAAM;IAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;CAAE,KACpD,QA4CF,CAAC"}
@@ -0,0 +1,80 @@
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.restore = exports.isPausedResume = void 0;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_zlib_1 = require("node:zlib");
9
+ const const_js_1 = __importDefault(require("../const.js"));
10
+ const journal_js_1 = require("./journal.js");
11
+ const pause_js_1 = require("./pause.js");
12
+ // The resume (design #964 §10.2): the answers to a paused turn's wait bring
13
+ // back its conversation checkpoint, and the same turn runs again on its own
14
+ // input, its journal and paused threads restored.
15
+ const unreadable = (why) => (0, journal_js_1.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `the paused state could not be read: ${why}`);
16
+ /** Whether an input is the answer to a paused turn's wait: a resolved `input` wait tagged `durable:<step>`. Any other outcome is the turn's to decide. */
17
+ const isPausedResume = (input) => input?.type === "resume" &&
18
+ input.kind === "input" &&
19
+ input.outcome === "resolved" &&
20
+ typeof input.tag === "string" &&
21
+ input.tag.startsWith(pause_js_1.PAUSE_TAG_PREFIX);
22
+ exports.isPausedResume = isPausedResume;
23
+ /**
24
+ * Reads the conversation checkpoint a paused turn's wait was declared for,
25
+ * and rebuilds the turn from it with the wait's answers merged in. Refuses,
26
+ * with "the paused state could not be read", a checkpoint that is missing,
27
+ * fails its sha256, belongs to another pause, or was written by another
28
+ * format or another major of LangGraph (the agent was rebuilt while it
29
+ * waited).
30
+ * @param input - The resume input (`isPausedResume`)
31
+ * @param checkpoint - What `getCheckpoint` answered
32
+ * @param init - The rebuilt turn's creator and clock
33
+ */
34
+ const restore = (input, checkpoint, init) => {
35
+ const answers = input?.input?.answers;
36
+ if (input?.truncated || !answers || typeof answers !== "object") {
37
+ throw (0, journal_js_1.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, "the answers to the paused turn did not arrive whole; it cannot be resumed");
38
+ }
39
+ if (!checkpoint || checkpoint.gone || !checkpoint.bytes)
40
+ throw unreadable("the workflow has no conversation checkpoint");
41
+ // client-api reads the step from the x-sf-checkpoint-step header: without it, NaN.
42
+ if (typeof checkpoint.step !== "number" || !Number.isInteger(checkpoint.step)) {
43
+ throw unreadable("the platform did not say which checkpoint it holds (no step)");
44
+ }
45
+ const step = String(input.tag).slice(pause_js_1.PAUSE_TAG_PREFIX.length);
46
+ if (String(checkpoint.step) !== step) {
47
+ throw unreadable(`its wait is for checkpoint ${step}, and the workflow's is ${checkpoint.step} (a later pause replaced it)`);
48
+ }
49
+ const bytes = Buffer.from(checkpoint.bytes);
50
+ // Fail closed, as for the step: a checkpoint whose integrity cannot be checked is not restored.
51
+ if (typeof checkpoint.sha256 !== "string" || !checkpoint.sha256) {
52
+ throw unreadable("the platform did not say the checkpoint's sha256");
53
+ }
54
+ if ((0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex") !== checkpoint.sha256) {
55
+ throw unreadable("its sha256 does not match its bytes");
56
+ }
57
+ let snapshot;
58
+ try {
59
+ snapshot = JSON.parse((0, node_zlib_1.gunzipSync)(bytes).toString("utf8"));
60
+ }
61
+ catch {
62
+ snapshot = null;
63
+ }
64
+ if (snapshot?.format !== pause_js_1.SNAPSHOT_FORMAT)
65
+ throw unreadable("it is not a durable turn snapshot");
66
+ if (snapshot.version !== pause_js_1.SNAPSHOT_VERSION) {
67
+ throw unreadable(`it is snapshot version ${snapshot.version}, and this agent-utils reads version ${pause_js_1.SNAPSHOT_VERSION}`);
68
+ }
69
+ const running = (0, pause_js_1.versions)().langgraph;
70
+ if ((0, pause_js_1.majorOf)(snapshot.langgraph) !== (0, pause_js_1.majorOf)(running)) {
71
+ throw unreadable(`it was paused under LangGraph ${snapshot.langgraph} and runs now on LangGraph ${running}: the agent was rebuilt with an incompatible LangGraph while it waited`);
72
+ }
73
+ return {
74
+ input: snapshot.turn?.input ?? null,
75
+ decision: snapshot.turn?.decision ?? null,
76
+ step: Number(checkpoint.step),
77
+ turn: new journal_js_1.DurableTurn({ journal: snapshot.journal, threads: snapshot.threads, answers, creator: init.creator, now: init.now }),
78
+ };
79
+ };
80
+ exports.restore = restore;
@@ -0,0 +1,38 @@
1
+ import { MemorySaver } from "@langchain/langgraph";
2
+ /** One namespace of a thread as the snapshot keeps it: its latest checkpoint and that checkpoint's writes, base64. */
3
+ export interface SavedCheckpoint {
4
+ checkpointId: string;
5
+ /** Its parent's id, so `getTuple` still answers `parentConfig`; the parent itself is not kept. */
6
+ parentId: string | null;
7
+ checkpoint: string;
8
+ metadata: string;
9
+ /** `MemorySaver.writes` of the checkpoint: `"<taskId>,<idx>"` → `[taskId, channel, value]`. */
10
+ writes: Record<string, [string, string, string]>;
11
+ }
12
+ /** Threads by id, then namespace (`""` for the graph's own). */
13
+ export type SavedThreads = Record<string, Record<string, SavedCheckpoint>>;
14
+ /**
15
+ * LangGraph's `MemorySaver` whose threads export as JSON (design #964 §10.2):
16
+ * what a paused turn's conversation checkpoint carries. `exportThreads` keeps
17
+ * only the latest checkpoint of each thread and namespace, with its writes
18
+ * (the pending writes and the interrupts a resume reads); earlier checkpoints
19
+ * are history a resume never reads. `fromThreads` / `importThreads` are the
20
+ * reverse. An agent built with one can pause in one process and resume in
21
+ * another: `createAgent(..., { checkpointer: new durable.SnapshotSaver() })`.
22
+ *
23
+ * A latest-only export is enough for a `createAgent` graph: its `messages`
24
+ * channel is a reducer, not a delta channel, so nothing walks the ancestors
25
+ * (spike item 2, `getDeltaChannelHistory` never called).
26
+ */
27
+ export declare class SnapshotSaver extends MemorySaver {
28
+ /**
29
+ * The latest checkpoint of each thread and namespace, with its writes.
30
+ * @param threadIds - Only these threads; every thread when omitted
31
+ */
32
+ exportThreads(threadIds?: string[]): SavedThreads;
33
+ /** Adds exported threads, replacing a namespace this saver already holds. */
34
+ importThreads(threads: SavedThreads): void;
35
+ /** A saver holding exported threads. */
36
+ static fromThreads(threads: SavedThreads): SnapshotSaver;
37
+ }
38
+ //# sourceMappingURL=snapshotSaver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshotSaver.d.ts","sourceRoot":"","sources":["../../../src/durable/snapshotSaver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,sHAAsH;AACtH,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,kGAAkG;IAClG,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,+FAA+F;IAC/F,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAClD;AAED,gEAAgE;AAChE,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,CAAC;AAS3E;;;;;;;;;;;;GAYG;AACH,qBAAa,aAAc,SAAQ,WAAW;IAC5C;;;OAGG;IACH,aAAa,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,GAAG,YAAY;IA2BjD,6EAA6E;IAC7E,aAAa,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI;IAmB1C,wCAAwC;IACxC,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,YAAY,GAAG,aAAa;CAKzD"}
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SnapshotSaver = void 0;
4
+ const langgraph_1 = require("@langchain/langgraph");
5
+ const toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
6
+ const fromBase64 = (text) => new Uint8Array(Buffer.from(text, "base64"));
7
+ /** MemorySaver's key for a checkpoint's writes. */
8
+ const writesKey = (threadId, namespace, checkpointId) => JSON.stringify([threadId, namespace, checkpointId]);
9
+ /**
10
+ * LangGraph's `MemorySaver` whose threads export as JSON (design #964 §10.2):
11
+ * what a paused turn's conversation checkpoint carries. `exportThreads` keeps
12
+ * only the latest checkpoint of each thread and namespace, with its writes
13
+ * (the pending writes and the interrupts a resume reads); earlier checkpoints
14
+ * are history a resume never reads. `fromThreads` / `importThreads` are the
15
+ * reverse. An agent built with one can pause in one process and resume in
16
+ * another: `createAgent(..., { checkpointer: new durable.SnapshotSaver() })`.
17
+ *
18
+ * A latest-only export is enough for a `createAgent` graph: its `messages`
19
+ * channel is a reducer, not a delta channel, so nothing walks the ancestors
20
+ * (spike item 2, `getDeltaChannelHistory` never called).
21
+ */
22
+ class SnapshotSaver extends langgraph_1.MemorySaver {
23
+ /**
24
+ * The latest checkpoint of each thread and namespace, with its writes.
25
+ * @param threadIds - Only these threads; every thread when omitted
26
+ */
27
+ exportThreads(threadIds) {
28
+ const threads = {};
29
+ const ids = threadIds ?? Object.keys(this.storage);
30
+ for (const threadId of ids) {
31
+ const namespaces = this.storage[threadId];
32
+ if (!namespaces)
33
+ continue;
34
+ for (const [namespace, checkpoints] of Object.entries(namespaces)) {
35
+ // Checkpoint ids are time-ordered (uuid6); MemorySaver takes the greatest as the latest.
36
+ const latest = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0];
37
+ if (latest === undefined)
38
+ continue;
39
+ const [checkpoint, metadata, parentId] = checkpoints[latest];
40
+ const writes = {};
41
+ for (const [inner, [taskId, channel, value]] of Object.entries(this.writes[writesKey(threadId, namespace, latest)] ?? {})) {
42
+ writes[inner] = [taskId, channel, toBase64(value)];
43
+ }
44
+ (threads[threadId] ??= {})[namespace] = {
45
+ checkpointId: latest,
46
+ parentId: parentId ?? null,
47
+ checkpoint: toBase64(checkpoint),
48
+ metadata: toBase64(metadata),
49
+ writes,
50
+ };
51
+ }
52
+ }
53
+ return threads;
54
+ }
55
+ /** Adds exported threads, replacing a namespace this saver already holds. */
56
+ importThreads(threads) {
57
+ for (const [threadId, namespaces] of Object.entries(threads ?? {})) {
58
+ const thread = (this.storage[threadId] ??= Object.create(null));
59
+ for (const [namespace, saved] of Object.entries(namespaces)) {
60
+ thread[namespace] = Object.create(null);
61
+ thread[namespace][saved.checkpointId] = [
62
+ fromBase64(saved.checkpoint),
63
+ fromBase64(saved.metadata),
64
+ saved.parentId ?? undefined,
65
+ ];
66
+ const writes = Object.create(null);
67
+ for (const [inner, [taskId, channel, value]] of Object.entries(saved.writes ?? {})) {
68
+ writes[inner] = [taskId, channel, fromBase64(value)];
69
+ }
70
+ this.writes[writesKey(threadId, namespace, saved.checkpointId)] = writes;
71
+ }
72
+ }
73
+ }
74
+ /** A saver holding exported threads. */
75
+ static fromThreads(threads) {
76
+ const saver = new SnapshotSaver();
77
+ saver.importThreads(threads);
78
+ return saver;
79
+ }
80
+ }
81
+ exports.SnapshotSaver = SnapshotSaver;
@@ -0,0 +1,28 @@
1
+ export interface StepOptions {
2
+ /**
3
+ * The tracker the step's calls count their usage into. A step that finished
4
+ * returns its saved result on the turn's resume without running, so what
5
+ * its calls used is given back here, and only here (the platform was told
6
+ * when it was spent).
7
+ */
8
+ usageTracker?: any;
9
+ }
10
+ /**
11
+ * Runs `fn` once per turn (design #964 §10.2): when a paused turn runs again,
12
+ * a step that already finished returns its saved result instead of running.
13
+ * Put every side effect or paid call that is not an LLM call, between the
14
+ * start of a turn and a possible pause, in a step (rule 1). The key names the
15
+ * step in its scope, and `fn` runs in a scope of its own, so the calls it
16
+ * makes are journaled under it; when it finishes they are dropped and only
17
+ * its result is kept. Results are JSON: return ids, not bytes (rule 4).
18
+ *
19
+ * Outside a `workflow.run` turn, or inside an agent's tool (whose agent
20
+ * already keeps what its tools did), `fn` simply runs.
21
+ *
22
+ * @param key - The step's name in its scope: the same on every run of the turn
23
+ * @param fn - The work
24
+ * @param options - `usageTracker`, to have a replayed step's usage given back
25
+ * @returns What `fn` returned, or its saved copy on a replay
26
+ */
27
+ export declare const step: <T>(key: string, fn: () => Promise<T>, options?: StepOptions) => Promise<T>;
28
+ //# sourceMappingURL=step.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step.d.ts","sourceRoot":"","sources":["../../../src/durable/step.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,WAAW;IAC1B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,GAAG,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI,GAAU,CAAC,EAAE,KAAK,MAAM,EAAE,IAAI,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,UAAS,WAAgB,KAAG,OAAO,CAAC,CAAC,CAerG,CAAC"}
@@ -0,0 +1,43 @@
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.step = void 0;
7
+ const const_js_1 = __importDefault(require("../const.js"));
8
+ const journal_js_1 = require("./journal.js");
9
+ /**
10
+ * Runs `fn` once per turn (design #964 §10.2): when a paused turn runs again,
11
+ * a step that already finished returns its saved result instead of running.
12
+ * Put every side effect or paid call that is not an LLM call, between the
13
+ * start of a turn and a possible pause, in a step (rule 1). The key names the
14
+ * step in its scope, and `fn` runs in a scope of its own, so the calls it
15
+ * makes are journaled under it; when it finishes they are dropped and only
16
+ * its result is kept. Results are JSON: return ids, not bytes (rule 4).
17
+ *
18
+ * Outside a `workflow.run` turn, or inside an agent's tool (whose agent
19
+ * already keeps what its tools did), `fn` simply runs.
20
+ *
21
+ * @param key - The step's name in its scope: the same on every run of the turn
22
+ * @param fn - The work
23
+ * @param options - `usageTracker`, to have a replayed step's usage given back
24
+ * @returns What `fn` returned, or its saved copy on a replay
25
+ */
26
+ const step = async (key, fn, options = {}) => {
27
+ if (typeof key !== "string" || key.length === 0) {
28
+ throw (0, journal_js_1.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, "durable.step needs a key: durable.step(key, fn)");
29
+ }
30
+ // "/" separates scopes in the journal's keys: step "x/llm#0" would be taken
31
+ // for the first call of step "x" and replay its result.
32
+ if (key.includes("/")) {
33
+ throw (0, journal_js_1.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable.step needs a key without "/": ${JSON.stringify(key)} names a scope`);
34
+ }
35
+ if (typeof fn !== "function") {
36
+ throw (0, journal_js_1.failure)(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, "durable.step needs a function: durable.step(key, fn)");
37
+ }
38
+ const frame = (0, journal_js_1.currentFrame)();
39
+ if (!frame || frame.passthrough)
40
+ return fn();
41
+ return frame.turn.step(frame, key, fn, options?.usageTracker ?? null);
42
+ };
43
+ exports.step = step;
@@ -6,25 +6,48 @@ import { serve, runOnce, isRunOnceExecution, EXECUTION_ENV } from "./serve.js";
6
6
  import { callAgent, checkAgent } from "./client.js";
7
7
  import * as runtimeContext from "./runtimeContext.js";
8
8
  import { recordUsage, USAGE_UNITS } from "./usage.js";
9
+ import { requirePricedModel } from "./modelRates.js";
9
10
  import stackfactorKnowledge from "./stackfactorKnowledge.js";
10
11
  import referenceContext, { KnowledgeAccessError } from "./referenceContext.js";
11
- import { checkUrlsReachable } from "./tavily.js";
12
+ import sourceStore from "./sourceStore.js";
13
+ import { LinksNotCheckedError, checkUrls, checkUrlsReachable, readUrls, unreachableUrls } from "./tavily.js";
14
+ import { RETRY_WAITS, isNetworkFailure, isTransient, messageOf, retryTransient, statusOf } from "./retry.js";
15
+ import * as workflow from "./workflow/index.js";
16
+ import * as durable from "./durable/index.js";
17
+ import daemon from "./daemon.js";
18
+ import learningActivityMedia from "./learningActivityMedia.js";
19
+ import learningContentPlan from "./learningContentPlan.js";
20
+ import learningContentThread from "./learningContentThread.js";
12
21
  export { constants };
13
22
  export { errorHandling, AppError };
14
23
  export type { ParsedError } from "./errorHandling.js";
15
24
  export { langChain };
16
25
  export type { UsageTracker } from "./langChain.js";
17
- export { checkUrlsReachable };
18
- export type { TavilyConfig, TavilyToolName } from "./tavily.js";
26
+ export { LinksNotCheckedError, checkUrls, checkUrlsReachable, readUrls, unreachableUrls };
27
+ export type { TavilyConfig, TavilyToolName, UnreachableUrlsOptions, UrlCheck, UrlRead } from "./tavily.js";
19
28
  export { logger };
20
29
  export { serve, runOnce, isRunOnceExecution, EXECUTION_ENV };
30
+ export { daemon };
31
+ export type { DaemonOptions, PoolTransport, Sleep, DaemonLog } from "./daemon.js";
32
+ export type { DaemonConfig } from "./daemonConfig.js";
21
33
  export { callAgent };
22
34
  export { checkAgent };
23
35
  export type { AgentExecuteRequest, CallAgentOptions, CheckAgentOptions, AgentHealth, } from "./client.js";
24
36
  export { runtimeContext };
25
- export { recordUsage, USAGE_UNITS };
37
+ export { workflow };
38
+ export { durable };
39
+ export { recordUsage, requirePricedModel, USAGE_UNITS };
26
40
  export type { UsageEntry, UsageUnit } from "./usage.js";
27
- export { stackfactorKnowledge, referenceContext, KnowledgeAccessError };
28
- export type { GroundingPassage, KnowledgeChunk, KnowledgeSearch, KnowledgeSource, SkippedSource, StackFactorReference, } from "./stackfactorKnowledge.js";
29
- export type { ReferenceContext, ReferencePage, ReferencePassage, SourceGuidance, StoredReference, } from "./referenceContext.js";
41
+ export { stackfactorKnowledge, referenceContext, sourceStore, KnowledgeAccessError };
42
+ export type { CitedPassage, KnowledgeOutline, KnowledgeOutlines, KnowledgePassage, KnowledgePassages, Source, SourceFinding, SourceOutlineEntry, SourceRead, SourceRecord, SourceProgress, OnSourceProgress, SourceStore, SourceUse, } from "./sourceStore.js";
43
+ export { RETRY_WAITS, isNetworkFailure, isTransient, messageOf, retryTransient, statusOf };
44
+ export type { RetryOptions } from "./retry.js";
45
+ export type { GroundingPassage, KnowledgeChunk, KnowledgeSearch, KnowledgeSource, PassageRole, SkippedSource, StackFactorReference, } from "./stackfactorKnowledge.js";
46
+ export type { StoredReference } from "./referenceContext.js";
47
+ export { learningActivityMedia };
48
+ export { learningContentPlan };
49
+ export { learningContentThread };
50
+ export type { ContentPlan, ContentPlanExtension, ContentPlanLesson, ContentPlanTerm, LearningContentThread, LearningContentThreadSentence } from "./learningContentPlan.js";
51
+ export type { PlanContext, ThreadLines, WriteThreadInput, WriteThreadResult } from "./learningContentThread.js";
52
+ export type { ActivityContentField, ActivityMediaChoices, ActivityMediaOptions, ActivityMediaPlatform, ActivityMediaSummary, ActivityMediaTarget, MediaCount, MediaIntegrationChoice, MotionGraphicStyle, } from "./learningActivityMedia.js";
30
53
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,YA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