@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,407 @@
1
+ "use strict";
2
+ //
3
+ // learningContentThread — the rules of a lesson's two thread lines: the
4
+ // opening that ties the lesson to what it builds on, and the closing that
5
+ // hands over to what follows. Pure functions; nothing here calls a model.
6
+ //
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.writeThread = exports.threadRulesForPrompt = exports.threadProblems = exports.namesTerm = exports.findPositionPhrases = exports.countSentences = exports.countWords = exports.THREAD_LIMITS = void 0;
42
+ const zod_1 = require("zod");
43
+ const langChain_js_1 = __importStar(require("./langChain.js"));
44
+ const cancellation_js_1 = require("./cancellation.js");
45
+ const learningContentPlan_js_1 = require("./learningContentPlan.js");
46
+ /** The limits of the two lines. Opening: at most 60 words and 3 sentences. Closing: at most 30 words and 2 sentences. */
47
+ exports.THREAD_LIMITS = Object.freeze({ OPENING_WORDS: 60, OPENING_SENTENCES: 3, CLOSING_WORDS: 30, CLOSING_SENTENCES: 2 });
48
+ const HAS_WORD = /[\p{L}\p{N}]/u;
49
+ // Text is compared in Unicode NFC form throughout.
50
+ const nfc = (text) => String(text ?? "").normalize("NFC");
51
+ /**
52
+ * The number of runs of non-whitespace that hold a letter or a digit.
53
+ * "" and " — " are 0. A line is blank when this is 0.
54
+ */
55
+ const countWords = (text) => nfc(text)
56
+ .split(/\s+/)
57
+ .filter((run) => HAS_WORD.test(run)).length;
58
+ exports.countWords = countWords;
59
+ const ABBREVIATIONS = new Set(["e.g", "i.e", "etc", "vs", "mr", "mrs", "ms", "dr", "prof", "st"]);
60
+ const CLOSERS = new Set(['"', "'", ")", "]", "”", "’", "»"]);
61
+ // A period after one of these is not an end when a digit follows ("No. 4", "Art. 6").
62
+ const NUMBERED = new Set(["no", "art", "sec", "fig", "approx"]);
63
+ const LOOK_BACK = 12;
64
+ const isMark = (c) => c === "." || c === "!" || c === "?";
65
+ const isSpace = (c) => /\s/.test(c);
66
+ // Whether the lone period at `periodAt` (its own index) is not the end of a
67
+ // sentence: after an abbreviation, after "No", "Art", "Sec", "Fig" or "approx" before a digit (`afterSpaceAt`
68
+ // is where the text goes on after the whitespace), or after an initial. It
69
+ // looks back at most LOOK_BACK characters, so a scan of a long text stays linear.
70
+ const periodIsNotAnEnd = (text, periodAt, afterSpaceAt) => {
71
+ const token = text
72
+ .slice(Math.max(0, periodAt - LOOK_BACK), periodAt)
73
+ .match(/\S*$/)[0]
74
+ .replace(/^[^\p{L}\p{N}]+/u, "");
75
+ const lower = token.toLowerCase();
76
+ if (NUMBERED.has(lower))
77
+ return afterSpaceAt < text.length && /\d/.test(text[afterSpaceAt]);
78
+ if (ABBREVIATIONS.has(lower))
79
+ return true;
80
+ // A single capital letter that stands alone or follows a period (J. Smith, U.S.), not one glued to a digit or a hyphen.
81
+ return /^\p{Lu}$/u.test(token) || /\.\p{Lu}$/u.test(token);
82
+ };
83
+ /**
84
+ * The number of sentences. A sentence ends at one or more of . ! ? (with any
85
+ * closing " ' ) ] ” ’ » after them) followed by whitespace or the end of the
86
+ * text. Not an end: a mark followed by whitespace and then a lower-case letter;
87
+ * a period after e.g, i.e, etc, vs, Mr, Mrs, Ms, Dr, Prof or St (any case), or
88
+ * after No, Art, Sec, Fig or approx (any case) when a digit follows; a period after a single capital letter that
89
+ * stands alone or follows a period (not one glued to a digit or a hyphen). A
90
+ * piece with no letter or digit is not a sentence. Text with no end mark is one
91
+ * sentence when it has a word, else 0. The scan is linear.
92
+ */
93
+ const countSentences = (text) => {
94
+ const source = nfc(text);
95
+ const length = source.length;
96
+ let count = 0;
97
+ let from = 0;
98
+ let at = 0;
99
+ while (at < length) {
100
+ if (!isMark(source[at])) {
101
+ at += 1;
102
+ continue;
103
+ }
104
+ const start = at;
105
+ let marksEnd = at;
106
+ while (marksEnd < length && isMark(source[marksEnd]))
107
+ marksEnd += 1;
108
+ let end = marksEnd;
109
+ while (end < length && CLOSERS.has(source[end]))
110
+ end += 1;
111
+ at = end;
112
+ if (end < length && !isSpace(source[end]))
113
+ continue;
114
+ let next = end;
115
+ while (next < length && isSpace(source[next]))
116
+ next += 1;
117
+ if (next < length && /\p{Ll}/u.test(source[next]))
118
+ continue;
119
+ if (marksEnd - start === 1 && source[start] === "." && periodIsNotAnEnd(source, start, next))
120
+ continue;
121
+ if (HAS_WORD.test(source.slice(from, end)))
122
+ count += 1;
123
+ from = end;
124
+ }
125
+ if (HAS_WORD.test(source.slice(from)))
126
+ count += 1;
127
+ return count;
128
+ };
129
+ exports.countSentences = countSentences;
130
+ const B = "(?<![\\p{L}\\p{N}])";
131
+ const E = "(?![\\p{L}\\p{N}])";
132
+ const RELATIVE = "last|previous|prior|earlier|preceding|next|following|upcoming|later|subsequent";
133
+ const ORDINAL = "first|second|third|fourth|fifth|final";
134
+ const NUMBER_WORD = "one|two|three|four|five|six|seven|eight|nine|ten";
135
+ const VERB = "saw|seen|learned|learnt|met|covered|discussed|explored|defined|introduced|studied|mentioned|noted|looked";
136
+ // A lesson word, singular or plural, but not "lesson(s) learned" or "video call" and its kin.
137
+ const LESSON_WORD = `lessons?(?!\\s+(?:learned|learnt)${E})`;
138
+ const OTHER_LESSON = `videos?(?!\\s+(?:calls?|conferences?|meetings?|chats?)${E})|lectures?`;
139
+ const OTHER_UNIT = `(?:${OTHER_LESSON}|modules?|chapters?|episodes?|sections?)`;
140
+ // A unit followed by "of" and something other than a part of the course is content, not position.
141
+ const COURSE_PART = `(?:(?:this|the|our)\\s+)?(?:course|series|module|level|programme|program|path)${E}`;
142
+ const NOT_OF_CONTENT = `(?!\\s+of\\s+(?!${COURSE_PART})\\S)`;
143
+ // Not a position phrase when the word right before it is one of these ("your first video", "a later section").
144
+ // A lesson is always one: "in a later lesson" and "your next lesson" are about the course.
145
+ const NOT_AFTER_OWNER = "(?<!(?:^|[^\\p{L}\\p{N}])(?:your|my|their|his|her|its|a|an|each|every|any)\\s+)";
146
+ const NOT_AFTER_THE = "(?<!(?:^|[^\\p{L}\\p{N}])the\\s+)";
147
+ const NOT_COURSE_OF = `(?!\\s+of${E})`;
148
+ const VERB_AHEAD = "learn|see|meet|explore|cover|look|study|discover";
149
+ const VERB_DONE = "learned|learnt|mastered|covered|seen|met|studied|explored";
150
+ const POSITION_PATTERNS = [
151
+ `(?:${RELATIVE}|${ORDINAL})\\s+${LESSON_WORD}${E}${NOT_OF_CONTENT}`,
152
+ `${NOT_AFTER_OWNER}(?:${RELATIVE})\\s+${OTHER_UNIT}${E}${NOT_OF_CONTENT}`,
153
+ `${NOT_AFTER_OWNER}(?:${ORDINAL})\\s+(?:${OTHER_LESSON})${E}${NOT_OF_CONTENT}`,
154
+ `(?:lessons?|videos?|lectures?)\\s+(?:\\d+|${NUMBER_WORD})${E}`,
155
+ `as\\s+(?:we|you)(?:\\s+have|['’]ve)?\\s+(?:${VERB})`,
156
+ `as\\s+(?:discussed|mentioned|covered|shown|noted|explained|seen)\\s+(?:earlier|before|previously|above)`,
157
+ `(?:earlier|later|previously|so\\s+far)\\s+in\\s+(?:this|the)\\s+course${NOT_COURSE_OF}`,
158
+ `previously,?\\s+(?:we|you)`,
159
+ `(?:we|you)\\s+previously\\s+(?:${VERB})`,
160
+ `earlier,?\\s+(?:we|you)\\s+(?:${VERB})`,
161
+ `${NOT_AFTER_THE}last\\s+time,?\\s+(?:we|you)`,
162
+ `in\\s+(?:the|our)\\s+(?:previous|last|next|following|earlier)\\s+(?:unit(?!\\s+tests?${E})|topic|part|class)${E}${NOT_OF_CONTENT}`,
163
+ `next,?\\s+(?:we|you)(?:\\s+will|['’]ll)\\s+(?:${VERB_AHEAD})`,
164
+ `before\\s+this,?\\s+(?:we|you)`,
165
+ `now\\s+that\\s+(?:we|you)(?:\\s+have|['’]ve)\\s+(?:${VERB_DONE})`,
166
+ `as\\s+(?:we|you)\\s+will\\s+see`,
167
+ `coming\\s+up\\s+next`,
168
+ `up\\s+next`,
169
+ ].map((body) => new RegExp(`${B}(?:${body})${E}`, "giu"));
170
+ /**
171
+ * Every phrase of the text that depends on the order of lessons, as written in
172
+ * the text (each run of whitespace as one space), in the order the phrases
173
+ * start. [] when none. Case-insensitive, on word boundaries. The families:
174
+ * a relative word (last, previous, prior, earlier, preceding, next, following,
175
+ * upcoming, later, subsequent) then a unit (lesson, video, lecture, module,
176
+ * chapter, episode, section); an ordinal (first ... fifth, final) then
177
+ * lesson, video or lecture; lesson, video or lecture with a number ("lessons 4",
178
+ * "lesson one"); "as we saw" and its kin ("as you have learned", "as we've
179
+ * seen"); "as discussed earlier" and its kin; "earlier in this course" and its
180
+ * kin ("so far in the course"); "previously we"; "we previously saw"; "earlier,
181
+ * you met"; "last time, we"; "in" + the or our + previous, last, next, following
182
+ * or earlier + unit, topic, part or class ("in the previous unit"); "next, you
183
+ * will learn" and its kin (next, optional comma, we or you, will or 'll, then
184
+ * learn, see, meet, explore, cover, look, study or discover); "before this, you"
185
+ * (or we); "now that you have learned" and its kin (have or 've, then learned,
186
+ * learnt, mastered, covered, seen, met, studied or explored); "as you will
187
+ * see" (or we); "up next" and "coming up next". Not a position phrase: a unit
188
+ * (or a part, topic or class of the "in the next ..." family) followed by "of"
189
+ * and something other than a part of the course (course, series, module, level,
190
+ * programme, program, path, with or without this, the or our); a unit followed
191
+ * by "test" or "tests" in the "in the next unit" form; "lesson learned"; "video
192
+ * call", "video meetings" and their kin; a module, chapter, episode, section
193
+ * or session with a number; "session" as a unit; a relative word then a unit
194
+ * other than lesson, or an ordinal then video or lecture, when the word right
195
+ * before it is your, my, their, his, her, its, a, an, each, every or any ("your
196
+ * first video" is content; "a later lesson" and "your next lesson" are always
197
+ * about the course); "last time, we"
198
+ * when the word right before it is "the"; "earlier in this course" and its kin
199
+ * when "of" follows. Where two overlap, the one that starts first is kept, and
200
+ * of two that start together the longer.
201
+ */
202
+ const findPositionPhrases = (text) => {
203
+ const source = nfc(text);
204
+ const found = [];
205
+ for (const pattern of POSITION_PATTERNS) {
206
+ pattern.lastIndex = 0;
207
+ let match;
208
+ while ((match = pattern.exec(source)))
209
+ found.push({ start: match.index, end: match.index + match[0].length });
210
+ }
211
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
212
+ const kept = [];
213
+ let reached = -1;
214
+ for (const hit of found) {
215
+ if (hit.start < reached)
216
+ continue;
217
+ kept.push(hit);
218
+ reached = hit.end;
219
+ }
220
+ return kept.map((hit) => source.slice(hit.start, hit.end).replace(/\s+/g, " "));
221
+ };
222
+ exports.findPositionPhrases = findPositionPhrases;
223
+ const wordsOf = (text) => nfc(text).match(/[\p{L}\p{N}]+/gu) ?? [];
224
+ const isPluralOf = (plural, word) => plural === `${word}s` ||
225
+ plural === `${word}es` ||
226
+ (word.endsWith("y") && plural === `${word.slice(0, -1)}ies`) ||
227
+ (word.endsWith("is") && plural === `${word.slice(0, -2)}es`);
228
+ const wordsMatch = (a, b) => {
229
+ const x = a.toLowerCase();
230
+ const y = b.toLowerCase();
231
+ return x === y || isPluralOf(x, y) || isPluralOf(y, x);
232
+ };
233
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
234
+ /**
235
+ * Whether the text names the term, in the form given or its plural. A word is a
236
+ * run of letters and digits; two words match when they are equal ignoring case,
237
+ * or one is the other's plural (plus "s", plus "es", "y" replaced by "ies", or "is" replaced by "es").
238
+ * A term with a word of 3 or more characters is named when every such word of it
239
+ * matches some word of the text, and every shorter word of it that is in capitals
240
+ * or holds a digit ("AI", "1") is in the text as a whole word, written the same,
241
+ * with an optional "s" after it.
242
+ * A term with no word of 3 or more characters ("AI", "P x I") is named when the
243
+ * text holds the whole term as written (any run of whitespace in it matching any run of whitespace), bounded by characters that are not
244
+ * letters or digits, with an optional "s" after it; ignoring case, unless the
245
+ * term is all in capitals, which is matched as written. Compared in NFC form.
246
+ * A term that ends in one part in round brackets holding a word of two letters
247
+ * or more, such as "Personal protective equipment (PPE)", is named when the
248
+ * text names the part before the brackets or the part inside them, each judged
249
+ * by the rules above. Any other brackets ("Article 6(1)(f)", "Regulation (EU)
250
+ * 2016/679") are read as spaces, and the whole term is judged.
251
+ */
252
+ const namesTerm = (text, term) => {
253
+ const whole = nfc(term);
254
+ const trailing = /^([^()]*[^()\s])\s*\(([^()]*)\)\s*$/u.exec(whole);
255
+ if (trailing && /\p{L}{2}/u.test(trailing[2]))
256
+ return namesPart(text, trailing[1]) || namesPart(text, trailing[2]);
257
+ return namesPart(text, whole.replace(/[()]/g, " "));
258
+ };
259
+ exports.namesTerm = namesTerm;
260
+ const namesPart = (text, term) => {
261
+ const wanted = nfc(term).trim();
262
+ if (wanted === "")
263
+ return true;
264
+ const termWords = wordsOf(wanted);
265
+ const longWords = termWords.filter((word) => word.length >= 3);
266
+ if (longWords.length === 0) {
267
+ const allCapitals = wanted === wanted.toUpperCase() && wanted !== wanted.toLowerCase();
268
+ const pattern = wanted.split(/\s+/).map(escapeRegExp).join("\\s+");
269
+ return new RegExp(`${B}${pattern}s?${E}`, allCapitals ? "u" : "iu").test(nfc(text));
270
+ }
271
+ const textWords = wordsOf(text);
272
+ const shortRequired = termWords.filter((word) => word.length < 3 && (/\d/.test(word) || (word === word.toUpperCase() && word !== word.toLowerCase())));
273
+ return longWords.every((word) => textWords.some((candidate) => wordsMatch(word, candidate))) && shortRequired.every((word) => textWords.some((candidate) => candidate === word || candidate === `${word}s`));
274
+ };
275
+ /**
276
+ * What is wrong with the two lines, one sentence each, written for the model
277
+ * that must fix them. [] when nothing is. A line is blank when it has no word.
278
+ * In order: the opening is blank; the closing is blank; the opening's words,
279
+ * then its sentences; the closing's words, then its sentences; each position
280
+ * phrase (opening first, with advice that depends on the line); each built-on
281
+ * term the opening does not name (an entry without a term is passed over). A
282
+ * blank line gets only its "blank" problem.
283
+ */
284
+ const threadProblems = (lines, planContext) => {
285
+ const opening = nfc(lines?.opening);
286
+ const closing = nfc(lines?.closing);
287
+ const openingBlank = (0, exports.countWords)(opening) === 0;
288
+ const closingBlank = (0, exports.countWords)(closing) === 0;
289
+ const problems = [];
290
+ if (openingBlank)
291
+ problems.push("The opening is blank; write it.");
292
+ if (closingBlank)
293
+ problems.push("The closing is blank; write it.");
294
+ if (!openingBlank) {
295
+ const words = (0, exports.countWords)(opening);
296
+ if (words > exports.THREAD_LIMITS.OPENING_WORDS)
297
+ problems.push(`The opening has ${words} words; the limit is ${exports.THREAD_LIMITS.OPENING_WORDS}.`);
298
+ const sentences = (0, exports.countSentences)(opening);
299
+ if (sentences > exports.THREAD_LIMITS.OPENING_SENTENCES)
300
+ problems.push(`The opening has ${sentences} sentences; the limit is ${exports.THREAD_LIMITS.OPENING_SENTENCES}.`);
301
+ }
302
+ if (!closingBlank) {
303
+ const words = (0, exports.countWords)(closing);
304
+ if (words > exports.THREAD_LIMITS.CLOSING_WORDS)
305
+ problems.push(`The closing has ${words} words; the limit is ${exports.THREAD_LIMITS.CLOSING_WORDS}.`);
306
+ const sentences = (0, exports.countSentences)(closing);
307
+ if (sentences > exports.THREAD_LIMITS.CLOSING_SENTENCES)
308
+ problems.push(`The closing has ${sentences} sentences; the limit is ${exports.THREAD_LIMITS.CLOSING_SENTENCES}.`);
309
+ }
310
+ const advice = { opening: "name the idea itself instead", closing: "say the idea the course turns to instead" };
311
+ for (const [name, line, blank] of [["opening", opening, openingBlank], ["closing", closing, closingBlank]]) {
312
+ if (blank)
313
+ continue;
314
+ for (const phrase of (0, exports.findPositionPhrases)(line)) {
315
+ problems.push(`The ${name} says "${phrase}", which depends on the order of lessons; ${advice[name]}.`);
316
+ }
317
+ }
318
+ if (!openingBlank) {
319
+ for (const entry of planContext?.buildsOn ?? []) {
320
+ const term = entry && typeof entry.term === "string" ? entry.term : "";
321
+ if (term.trim() === "")
322
+ continue;
323
+ if (!(0, exports.namesTerm)(opening, term))
324
+ problems.push(`The opening does not name the term "${term}", which this lesson builds on; name it.`);
325
+ }
326
+ }
327
+ return problems;
328
+ };
329
+ exports.threadProblems = threadProblems;
330
+ /** The rules as data, for the user message of the model that writes the lines. The example phrases are each found by findPositionPhrases. */
331
+ const threadRulesForPrompt = () => ({
332
+ opening: { maxWords: exports.THREAD_LIMITS.OPENING_WORDS, maxSentences: exports.THREAD_LIMITS.OPENING_SENTENCES, namesEachTermItBuildsOn: true },
333
+ closing: { maxWords: exports.THREAD_LIMITS.CLOSING_WORDS, maxSentences: exports.THREAD_LIMITS.CLOSING_SENTENCES },
334
+ neverRefersToLessonOrder: ["the last video", "lesson 4", "the next lesson", "as we saw", "earlier in this course", "last time, we", "in the previous unit", "next, you will learn", "now that you have learned", "up next"],
335
+ });
336
+ exports.threadRulesForPrompt = threadRulesForPrompt;
337
+ // Structure only: the rules are checked in code, so a broken rule is never a schema failure.
338
+ const threadAnswerSchema = zod_1.z.object({ opening: zod_1.z.string(), closing: zod_1.z.string() });
339
+ /**
340
+ * Asks a model for a lesson's two thread lines, checks them with
341
+ * {@link threadProblems} and, when they break a rule, asks once more with
342
+ * the problems. At most two model calls. A model call that throws is a failed
343
+ * attempt and is retried once, with these exceptions: a cancelled request and an
344
+ * error with code 402 are thrown on, untouched, with no further call; an error
345
+ * that is a rate limit (as the library itself recognises one: a status or code of
346
+ * 429, in whichever field the provider puts it) is a failed attempt with no second call (the library has already
347
+ * waited and retried a rate limit itself). A 503 is an ordinary failed attempt.
348
+ * The result carries `error` (the same error object) when `lines` is null and the
349
+ * last attempt's model call threw. The model is called with 10 arguments, or 11
350
+ * (the usage tracker last) when `input.usageTracker` is given.
351
+ * @throws The error of a plan context that does not parse, or of a cancelled request or a 402
352
+ */
353
+ const writeThread = async (input) => {
354
+ const planContext = learningContentPlan_js_1.planContextSchema.parse(input.planContext);
355
+ const base = [
356
+ { role: "system", content: input.instructions },
357
+ { role: "user", content: JSON.stringify({ planContext, learningTargets: input.learningTargets ?? [], takeaways: input.takeaways ?? [], rules: (0, exports.threadRulesForPrompt)() }) },
358
+ ];
359
+ const attempt = async (messages) => {
360
+ let answer;
361
+ try {
362
+ answer = await langChain_js_1.default.runPromptWithModel(input.modelName, { ...input.config, agentic: false, tavily: undefined }, messages, null, 0, 100, true, threadAnswerSchema, input.agentName ?? "Thread writer", [], ...(input.usageTracker != null ? [input.usageTracker] : []));
363
+ }
364
+ catch (error) {
365
+ if ((0, cancellation_js_1.isRequestCancelled)() || error?.code === 402)
366
+ throw error;
367
+ return { answer: null, lines: null, problems: [`The model call failed: ${error?.message ?? String(error)}`], error, rateLimited: (0, langChain_js_1.isRateLimitError)(error) };
368
+ }
369
+ let parsed;
370
+ try {
371
+ parsed = threadAnswerSchema.parse(JSON.parse(answer));
372
+ }
373
+ catch {
374
+ return { answer, lines: null, problems: ["The answer was not a JSON object with an opening and a closing."] };
375
+ }
376
+ const lines = { opening: parsed.opening.trim(), closing: parsed.closing.trim() };
377
+ const problems = (0, exports.threadProblems)(lines, planContext);
378
+ return problems.length === 0 ? { answer, lines, problems: [] } : { answer, lines: null, problems };
379
+ };
380
+ const first = await attempt(base);
381
+ if (first.lines)
382
+ return { lines: first.lines, problems: [], attempts: 1 };
383
+ if (first.rateLimited)
384
+ return { lines: null, problems: first.problems, attempts: 1, error: first.error };
385
+ const retryMessages = first.answer === null
386
+ ? base
387
+ : [
388
+ ...base,
389
+ { role: "assistant", content: first.answer },
390
+ { role: "user", content: `Your two lines were rejected:\n${first.problems.map((p) => `- ${p}`).join("\n")}\n\nReturn both lines again, corrected.` },
391
+ ];
392
+ const second = await attempt(retryMessages);
393
+ if (second.lines)
394
+ return { lines: second.lines, problems: [], attempts: 2 };
395
+ return { lines: null, problems: second.problems, attempts: 2, ...("error" in second ? { error: second.error } : {}) };
396
+ };
397
+ exports.writeThread = writeThread;
398
+ exports.default = {
399
+ THREAD_LIMITS: exports.THREAD_LIMITS,
400
+ countSentences: exports.countSentences,
401
+ countWords: exports.countWords,
402
+ findPositionPhrases: exports.findPositionPhrases,
403
+ namesTerm: exports.namesTerm,
404
+ threadProblems: exports.threadProblems,
405
+ threadRulesForPrompt: exports.threadRulesForPrompt,
406
+ writeThread: exports.writeThread,
407
+ };
@@ -24,6 +24,7 @@ declare const _default: {
24
24
  readonly debug: "debug";
25
25
  readonly silly: "silly";
26
26
  };
27
+ messageOf: (request: any, level: string, message: string) => string;
27
28
  };
28
29
  export default _default;
29
30
  //# sourceMappingURL=logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAiEA;;;;;;;;;;;;;GAaG;AACH,KAAK,QAAQ,GACT,OAAO,GACP,MAAM,GACN,MAAM,GACN,MAAM,GACN,SAAS,GACT,OAAO,GACP,OAAO,CAAC;;mBAGD,GAAG,SACL,QAAQ,WACN,MAAM,YACN,GAAG,KACX,IAAI;;;;;;;;;;;AA0BP,wBAGE"}
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAiEA;;;;;;;;;;;;;GAaG;AACH,KAAK,QAAQ,GACT,OAAO,GACP,MAAM,GACN,MAAM,GACN,MAAM,GACN,SAAS,GACT,OAAO,GACP,OAAO,CAAC;;mBAGD,GAAG,SACL,QAAQ,WACN,MAAM,YACN,GAAG,KACX,IAAI;;;;;;;;;;yBA8BqB,GAAG,SAAS,MAAM,WAAW,MAAM,KAAG,MAAM;;AAOxE,wBAIE"}
@@ -59,11 +59,9 @@ const log = (request, level, message, options = {}) => {
59
59
  traceId = spanContext.traceId;
60
60
  spanId = spanContext.spanId;
61
61
  }
62
- // eslint-disable-next-line security/detect-object-injection
63
- const icon = levelIcons[level] || "ℹ️";
64
62
  logger.log({
65
63
  level: level,
66
- message: `${icon} ${request && request.user ? request.user.email + " - " : ""}${message}`,
64
+ message: messageOf(request, level, message),
67
65
  trace: traceId
68
66
  ? `projects/${process.env.GOOGLE_CLOUD_PROJECT}/traces/${traceId}`
69
67
  : undefined,
@@ -71,7 +69,23 @@ const log = (request, level, message, options = {}) => {
71
69
  ...options,
72
70
  });
73
71
  };
72
+ /**
73
+ * The text a log line carries: the level's icon, then the user's email and a
74
+ * dash when the request has one (a person's request), then the message. An
75
+ * agent's run has a request with no user email, and gets no prefix — never
76
+ * "undefined - ".
77
+ * @param request - The request, or null
78
+ * @param level - The level, for its icon
79
+ * @param message - The message
80
+ */
81
+ const messageOf = (request, level, message) => {
82
+ // eslint-disable-next-line security/detect-object-injection
83
+ const icon = levelIcons[level] || "ℹ️";
84
+ const email = request?.user?.email;
85
+ return `${icon} ${typeof email === "string" && email ? `${email} - ` : ""}${message}`;
86
+ };
74
87
  exports.default = {
75
88
  log,
76
89
  levels,
90
+ messageOf,
77
91
  };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Whether a model may be called: only when the platform has a rate for it.
3
+ *
4
+ * What an agent uses is priced by the platform (see usage), and what a model
5
+ * without a rate uses is charged nothing: the tokens are counted, the tenant's
6
+ * AI credits are not touched. So before a model is called through this
7
+ * package, the platform is asked whether it has a rate, and a request whose
8
+ * model has none fails before anything is spent.
9
+ *
10
+ * An agent that calls a provider itself asks with {@link requirePricedModel}
11
+ * before the call, as it counts what the call used with `recordUsage` after.
12
+ */
13
+ /** How long a model the platform priced is taken to be priced, without asking again. */
14
+ export declare const PRICED_FOR_MS: number;
15
+ /** Asks the platform which of `models` have no rate. */
16
+ export type UnpricedLookup = (models: string[], token: string) => Promise<string[]>;
17
+ /**
18
+ * Fails unless the platform has a rate for `model`. Outside a request, or in
19
+ * one that carries no token, nothing is charged for what is used, so there is
20
+ * nothing to ask and the call goes ahead.
21
+ * @param model - The model's id, as its provider names it
22
+ * @throws 402 when the model has no rate; 503 when the platform cannot be asked.
23
+ * Either way, nothing has been called yet.
24
+ */
25
+ export declare const requirePricedModel: (model: string) => Promise<void>;
26
+ /** Forgets which models were priced, so each is asked about again. */
27
+ export declare const forget: () => void;
28
+ export declare const api: {
29
+ lookup: UnpricedLookup;
30
+ };
31
+ declare const _default: {
32
+ requirePricedModel: (model: string) => Promise<void>;
33
+ forget: () => void;
34
+ api: {
35
+ lookup: UnpricedLookup;
36
+ };
37
+ PRICED_FOR_MS: number;
38
+ };
39
+ export default _default;
40
+ //# sourceMappingURL=modelRates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modelRates.d.ts","sourceRoot":"","sources":["../../src/modelRates.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;GAWG;AAEH,wFAAwF;AACxF,eAAO,MAAM,aAAa,QAAa,CAAC;AAExC,wDAAwD;AACxD,MAAM,MAAM,cAAc,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;AAYpF;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAAU,OAAO,MAAM,KAAG,OAAO,CAAC,IAAI,CA+BpE,CAAC;AAEF,sEAAsE;AACtE,eAAO,MAAM,MAAM,QAAO,IAEzB,CAAC;AAGF,eAAO,MAAM,GAAG,EAAE;IAAE,MAAM,EAAE,cAAc,CAAA;CAEzC,CAAC;;gCAzC8C,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;kBAkC5C,IAAI;;gBAKF,cAAc;;;;AAI1C,wBAAkE"}
@@ -0,0 +1,76 @@
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.api = exports.forget = exports.requirePricedModel = exports.PRICED_FOR_MS = void 0;
7
+ const client_api_1 = require("@stackfactor/client-api");
8
+ const errorHandling_js_1 = __importDefault(require("./errorHandling.js"));
9
+ const logger_js_1 = __importDefault(require("./logger.js"));
10
+ const runtimeContext_js_1 = require("./runtimeContext.js");
11
+ /**
12
+ * Whether a model may be called: only when the platform has a rate for it.
13
+ *
14
+ * What an agent uses is priced by the platform (see usage), and what a model
15
+ * without a rate uses is charged nothing: the tokens are counted, the tenant's
16
+ * AI credits are not touched. So before a model is called through this
17
+ * package, the platform is asked whether it has a rate, and a request whose
18
+ * model has none fails before anything is spent.
19
+ *
20
+ * An agent that calls a provider itself asks with {@link requirePricedModel}
21
+ * before the call, as it counts what the call used with `recordUsage` after.
22
+ */
23
+ /** How long a model the platform priced is taken to be priced, without asking again. */
24
+ exports.PRICED_FOR_MS = 5 * 60_000;
25
+ /** HTTP 402: the request asks for work the platform cannot charge for. */
26
+ const UNPRICED = 402;
27
+ /** HTTP 503: the platform could not say. */
28
+ const UNKNOWN = 503;
29
+ // Rates are the platform's, one table for every tenant, so what one request
30
+ // learned holds for every other. Only a priced answer is kept: a model that
31
+ // is given a rate is callable at once, and one without is asked about again.
32
+ const pricedAt = new Map();
33
+ /**
34
+ * Fails unless the platform has a rate for `model`. Outside a request, or in
35
+ * one that carries no token, nothing is charged for what is used, so there is
36
+ * nothing to ask and the call goes ahead.
37
+ * @param model - The model's id, as its provider names it
38
+ * @throws 402 when the model has no rate; 503 when the platform cannot be asked.
39
+ * Either way, nothing has been called yet.
40
+ */
41
+ const requirePricedModel = async (model) => {
42
+ const name = typeof model === "string" ? model.trim() : "";
43
+ if (!name)
44
+ return;
45
+ const context = (0, runtimeContext_js_1.getContext)();
46
+ const token = context?.request?.authToken ?? context?.request?.authorization;
47
+ if (!context || !token)
48
+ return;
49
+ const at = pricedAt.get(name);
50
+ if (at !== undefined && Date.now() - at < exports.PRICED_FOR_MS)
51
+ return;
52
+ let unpriced;
53
+ try {
54
+ unpriced = await exports.api.lookup([name], token);
55
+ }
56
+ catch (error) {
57
+ // Not called, rather than called and possibly never charged.
58
+ logger_js_1.default.log(null, logger_js_1.default.levels.error, `could not ask whether "${name}" has a rate: ${error?.message ?? error}`);
59
+ throw errorHandling_js_1.default.create(UNKNOWN, `Could not confirm that "${name}" has a rate, so it was not called. Try again shortly.`);
60
+ }
61
+ if (Array.isArray(unpriced) && unpriced.includes(name)) {
62
+ throw errorHandling_js_1.default.create(UNPRICED, `The model "${name}" has no rate, so what it uses could not be charged to the tenant's AI credits. It was not called. Add a rate for it, or configure a model that has one.`);
63
+ }
64
+ pricedAt.set(name, Date.now());
65
+ };
66
+ exports.requirePricedModel = requirePricedModel;
67
+ /** Forgets which models were priced, so each is asked about again. */
68
+ const forget = () => {
69
+ pricedAt.clear();
70
+ };
71
+ exports.forget = forget;
72
+ // Internal calls go through this object so tests can replace the lookup.
73
+ exports.api = {
74
+ lookup: (models, token) => client_api_1.integration.getUnpricedModels(models, token),
75
+ };
76
+ exports.default = { requirePricedModel: exports.requirePricedModel, forget: exports.forget, api: exports.api, PRICED_FOR_MS: exports.PRICED_FOR_MS };