@c9up/polaris 0.0.0-stage → 0.1.1

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 +1146 -2
  3. package/dist/Polaris.d.ts +80 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +208 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +184 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +576 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +40 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +79 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +18 -0
  16. package/dist/augmentations.d.ts.map +1 -0
  17. package/dist/augmentations.js +9 -0
  18. package/dist/augmentations.js.map +1 -0
  19. package/dist/budget.d.ts +77 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +134 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/catalog/catalog.d.ts +37 -0
  24. package/dist/catalog/catalog.d.ts.map +1 -0
  25. package/dist/catalog/catalog.js +145 -0
  26. package/dist/catalog/catalog.js.map +1 -0
  27. package/dist/catalog/discover.d.ts +64 -0
  28. package/dist/catalog/discover.d.ts.map +1 -0
  29. package/dist/catalog/discover.js +148 -0
  30. package/dist/catalog/discover.js.map +1 -0
  31. package/dist/catalog/index.d.ts +8 -0
  32. package/dist/catalog/index.d.ts.map +1 -0
  33. package/dist/catalog/index.js +8 -0
  34. package/dist/catalog/index.js.map +1 -0
  35. package/dist/commands/index.d.ts +82 -0
  36. package/dist/commands/index.d.ts.map +1 -0
  37. package/dist/commands/index.js +278 -0
  38. package/dist/commands/index.js.map +1 -0
  39. package/dist/cost.d.ts +50 -0
  40. package/dist/cost.d.ts.map +1 -0
  41. package/dist/cost.js +131 -0
  42. package/dist/cost.js.map +1 -0
  43. package/dist/drivers/anthropic.d.ts +44 -0
  44. package/dist/drivers/anthropic.d.ts.map +1 -0
  45. package/dist/drivers/anthropic.js +539 -0
  46. package/dist/drivers/anthropic.js.map +1 -0
  47. package/dist/drivers/openai-compatible.d.ts +54 -0
  48. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  49. package/dist/drivers/openai-compatible.js +699 -0
  50. package/dist/drivers/openai-compatible.js.map +1 -0
  51. package/dist/drivers/status.d.ts +8 -0
  52. package/dist/drivers/status.d.ts.map +1 -0
  53. package/dist/drivers/status.js +21 -0
  54. package/dist/drivers/status.js.map +1 -0
  55. package/dist/errors.d.ts +79 -0
  56. package/dist/errors.d.ts.map +1 -0
  57. package/dist/errors.js +86 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/extract.d.ts +38 -0
  60. package/dist/extract.d.ts.map +1 -0
  61. package/dist/extract.js +144 -0
  62. package/dist/extract.js.map +1 -0
  63. package/dist/index.d.ts +21 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +15 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/json-schema.d.ts +33 -0
  68. package/dist/json-schema.d.ts.map +1 -0
  69. package/dist/json-schema.js +508 -0
  70. package/dist/json-schema.js.map +1 -0
  71. package/dist/log.d.ts +47 -0
  72. package/dist/log.d.ts.map +1 -0
  73. package/dist/log.js +35 -0
  74. package/dist/log.js.map +1 -0
  75. package/dist/mcp/client.d.ts +81 -0
  76. package/dist/mcp/client.d.ts.map +1 -0
  77. package/dist/mcp/client.js +401 -0
  78. package/dist/mcp/client.js.map +1 -0
  79. package/dist/mcp/endpoint.d.ts +54 -0
  80. package/dist/mcp/endpoint.d.ts.map +1 -0
  81. package/dist/mcp/endpoint.js +158 -0
  82. package/dist/mcp/endpoint.js.map +1 -0
  83. package/dist/mcp/host.d.ts +42 -0
  84. package/dist/mcp/host.d.ts.map +1 -0
  85. package/dist/mcp/host.js +111 -0
  86. package/dist/mcp/host.js.map +1 -0
  87. package/dist/mcp/http.d.ts +32 -0
  88. package/dist/mcp/http.d.ts.map +1 -0
  89. package/dist/mcp/http.js +190 -0
  90. package/dist/mcp/http.js.map +1 -0
  91. package/dist/mcp/index.d.ts +23 -0
  92. package/dist/mcp/index.d.ts.map +1 -0
  93. package/dist/mcp/index.js +21 -0
  94. package/dist/mcp/index.js.map +1 -0
  95. package/dist/mcp/manifest.d.ts +36 -0
  96. package/dist/mcp/manifest.d.ts.map +1 -0
  97. package/dist/mcp/manifest.js +40 -0
  98. package/dist/mcp/manifest.js.map +1 -0
  99. package/dist/mcp/rpc.d.ts +39 -0
  100. package/dist/mcp/rpc.d.ts.map +1 -0
  101. package/dist/mcp/rpc.js +149 -0
  102. package/dist/mcp/rpc.js.map +1 -0
  103. package/dist/mcp/stdio.d.ts +24 -0
  104. package/dist/mcp/stdio.d.ts.map +1 -0
  105. package/dist/mcp/stdio.js +157 -0
  106. package/dist/mcp/stdio.js.map +1 -0
  107. package/dist/mcp/worker-main.d.ts +6 -0
  108. package/dist/mcp/worker-main.d.ts.map +1 -0
  109. package/dist/mcp/worker-main.js +17 -0
  110. package/dist/mcp/worker-main.js.map +1 -0
  111. package/dist/mcp/worker.d.ts +54 -0
  112. package/dist/mcp/worker.d.ts.map +1 -0
  113. package/dist/mcp/worker.js +166 -0
  114. package/dist/mcp/worker.js.map +1 -0
  115. package/dist/meter.d.ts +63 -0
  116. package/dist/meter.d.ts.map +1 -0
  117. package/dist/meter.js +94 -0
  118. package/dist/meter.js.map +1 -0
  119. package/dist/providers.d.ts +23 -0
  120. package/dist/providers.d.ts.map +1 -0
  121. package/dist/providers.js +21 -0
  122. package/dist/providers.js.map +1 -0
  123. package/dist/redact.d.ts +12 -0
  124. package/dist/redact.d.ts.map +1 -0
  125. package/dist/redact.js +77 -0
  126. package/dist/redact.js.map +1 -0
  127. package/dist/redis-budget.d.ts +45 -0
  128. package/dist/redis-budget.d.ts.map +1 -0
  129. package/dist/redis-budget.js +56 -0
  130. package/dist/redis-budget.js.map +1 -0
  131. package/dist/response.d.ts +39 -0
  132. package/dist/response.d.ts.map +1 -0
  133. package/dist/response.js +109 -0
  134. package/dist/response.js.map +1 -0
  135. package/dist/schema.d.ts +45 -0
  136. package/dist/schema.d.ts.map +1 -0
  137. package/dist/schema.js +43 -0
  138. package/dist/schema.js.map +1 -0
  139. package/dist/server-sent.d.ts +9 -0
  140. package/dist/server-sent.d.ts.map +1 -0
  141. package/dist/server-sent.js +74 -0
  142. package/dist/server-sent.js.map +1 -0
  143. package/dist/server-tools.d.ts +12 -0
  144. package/dist/server-tools.d.ts.map +1 -0
  145. package/dist/server-tools.js +71 -0
  146. package/dist/server-tools.js.map +1 -0
  147. package/dist/services/catalog.d.ts +19 -0
  148. package/dist/services/catalog.d.ts.map +1 -0
  149. package/dist/services/catalog.js +37 -0
  150. package/dist/services/catalog.js.map +1 -0
  151. package/dist/services/main.d.ts +23 -0
  152. package/dist/services/main.d.ts.map +1 -0
  153. package/dist/services/main.js +43 -0
  154. package/dist/services/main.js.map +1 -0
  155. package/dist/skills/folder.d.ts +32 -0
  156. package/dist/skills/folder.d.ts.map +1 -0
  157. package/dist/skills/folder.js +170 -0
  158. package/dist/skills/folder.js.map +1 -0
  159. package/dist/skills/frontmatter.d.ts +15 -0
  160. package/dist/skills/frontmatter.d.ts.map +1 -0
  161. package/dist/skills/frontmatter.js +92 -0
  162. package/dist/skills/frontmatter.js.map +1 -0
  163. package/dist/skills/index.d.ts +18 -0
  164. package/dist/skills/index.d.ts.map +1 -0
  165. package/dist/skills/index.js +18 -0
  166. package/dist/skills/index.js.map +1 -0
  167. package/dist/skills/kit.d.ts +39 -0
  168. package/dist/skills/kit.d.ts.map +1 -0
  169. package/dist/skills/kit.js +124 -0
  170. package/dist/skills/kit.js.map +1 -0
  171. package/dist/skills/skill.d.ts +67 -0
  172. package/dist/skills/skill.d.ts.map +1 -0
  173. package/dist/skills/skill.js +114 -0
  174. package/dist/skills/skill.js.map +1 -0
  175. package/dist/sse.d.ts +95 -0
  176. package/dist/sse.d.ts.map +1 -0
  177. package/dist/sse.js +117 -0
  178. package/dist/sse.js.map +1 -0
  179. package/dist/testing/FakeProvider.d.ts +85 -0
  180. package/dist/testing/FakeProvider.d.ts.map +1 -0
  181. package/dist/testing/FakeProvider.js +214 -0
  182. package/dist/testing/FakeProvider.js.map +1 -0
  183. package/dist/testing/index.d.ts +7 -0
  184. package/dist/testing/index.d.ts.map +1 -0
  185. package/dist/testing/index.js +7 -0
  186. package/dist/testing/index.js.map +1 -0
  187. package/dist/tool-modules.d.ts +17 -0
  188. package/dist/tool-modules.d.ts.map +1 -0
  189. package/dist/tool-modules.js +43 -0
  190. package/dist/tool-modules.js.map +1 -0
  191. package/dist/tools.d.ts +132 -0
  192. package/dist/tools.d.ts.map +1 -0
  193. package/dist/tools.js +250 -0
  194. package/dist/tools.js.map +1 -0
  195. package/dist/transport.d.ts +23 -0
  196. package/dist/transport.d.ts.map +1 -0
  197. package/dist/transport.js +83 -0
  198. package/dist/transport.js.map +1 -0
  199. package/dist/types.d.ts +397 -0
  200. package/dist/types.d.ts.map +1 -0
  201. package/dist/types.js +12 -0
  202. package/dist/types.js.map +1 -0
  203. package/package.json +97 -3
  204. package/src/Polaris.ts +304 -0
  205. package/src/PolarisClient.ts +828 -0
  206. package/src/PolarisProvider.ts +111 -0
  207. package/src/augmentations.ts +20 -0
  208. package/src/budget.ts +201 -0
  209. package/src/catalog/catalog.ts +180 -0
  210. package/src/catalog/discover.ts +234 -0
  211. package/src/catalog/index.ts +19 -0
  212. package/src/commands/index.ts +412 -0
  213. package/src/cost.ts +176 -0
  214. package/src/drivers/anthropic.ts +703 -0
  215. package/src/drivers/openai-compatible.ts +907 -0
  216. package/src/drivers/status.ts +30 -0
  217. package/src/errors.ts +202 -0
  218. package/src/extract.ts +214 -0
  219. package/src/index.ts +85 -0
  220. package/src/json-schema.ts +597 -0
  221. package/src/log.ts +86 -0
  222. package/src/mcp/client.ts +532 -0
  223. package/src/mcp/endpoint.ts +229 -0
  224. package/src/mcp/host.ts +140 -0
  225. package/src/mcp/http.ts +276 -0
  226. package/src/mcp/index.ts +51 -0
  227. package/src/mcp/manifest.ts +73 -0
  228. package/src/mcp/rpc.ts +197 -0
  229. package/src/mcp/stdio.ts +190 -0
  230. package/src/mcp/worker-main.ts +18 -0
  231. package/src/mcp/worker.ts +212 -0
  232. package/src/meter.ts +199 -0
  233. package/src/providers.ts +25 -0
  234. package/src/redact.ts +81 -0
  235. package/src/redis-budget.ts +85 -0
  236. package/src/response.ts +143 -0
  237. package/src/schema.ts +88 -0
  238. package/src/server-sent.ts +70 -0
  239. package/src/server-tools.ts +77 -0
  240. package/src/services/catalog.ts +43 -0
  241. package/src/services/main.ts +49 -0
  242. package/src/skills/folder.ts +231 -0
  243. package/src/skills/frontmatter.ts +92 -0
  244. package/src/skills/index.ts +38 -0
  245. package/src/skills/kit.ts +163 -0
  246. package/src/skills/skill.ts +171 -0
  247. package/src/sse.ts +194 -0
  248. package/src/testing/FakeProvider.ts +322 -0
  249. package/src/testing/index.ts +12 -0
  250. package/src/tool-modules.ts +49 -0
  251. package/src/tools.ts +399 -0
  252. package/src/transport.ts +107 -0
  253. package/src/types.ts +434 -0
@@ -0,0 +1,166 @@
1
+ /**
2
+ * The worker protocol: how `ream mcp:serve` has the application's tools run
3
+ * by a long-lived Node process. One JSON object per line, both ways.
4
+ *
5
+ * Started as `node <worker> <tools.json>`, the worker imports the module the
6
+ * manifest names, then writes `{"type":"ready","protocol":1}`; when it cannot,
7
+ * `{"type":"failed","message":"..."}`, and it exits with code 1.
8
+ *
9
+ * Then, from the parent:
10
+ * {"type":"call","id":1,"name":"canton_rate","input":{...}}
11
+ * {"type":"cancel","id":1}
12
+ * and from the worker:
13
+ * {"type":"result","id":1,"ok":true,"content":"..."}
14
+ * {"type":"error","id":null,"message":"..."} a line it could not read
15
+ *
16
+ * Calls run side by side; each is answered once. `ok: false` is a failure
17
+ * meant for the agent (unknown tool, refused input, the tool's error), never
18
+ * a stack trace. The worker leaves when its stdin ends. stdout carries only
19
+ * the protocol: what the application writes there goes to stderr.
20
+ */
21
+ import { resolve } from "node:path";
22
+ import { pathToFileURL } from "node:url";
23
+ import { loadTools, ToolHost } from "./host.js";
24
+ import { isObject } from "./rpc.js";
25
+ /** The version of the protocol above. */
26
+ export const WORKER_PROTOCOL = 1;
27
+ /** The longest line the worker reads, in bytes. */
28
+ export const MAX_WORKER_LINE = 4 * 1024 * 1024;
29
+ /**
30
+ * Serve the protocol until `input` ends. Writes `ready` first. Resolves once
31
+ * the input ended and every call was answered.
32
+ */
33
+ export async function runWorker(options) {
34
+ const host = new ToolHost(options.tools, options.onToolError);
35
+ const max = options.maxLineBytes ?? MAX_WORKER_LINE;
36
+ const send = (message) => options.write(JSON.stringify(message));
37
+ const running = new Map();
38
+ const settled = [];
39
+ const handle = (line) => {
40
+ let message;
41
+ try {
42
+ message = JSON.parse(line);
43
+ }
44
+ catch {
45
+ send({ type: "error", id: null, message: "The line is not JSON." });
46
+ return;
47
+ }
48
+ const id = isObject(message) ? message.id : undefined;
49
+ if (!isObject(message) ||
50
+ (typeof id !== "string" && typeof id !== "number")) {
51
+ send({ type: "error", id: null, message: "The message has no id." });
52
+ return;
53
+ }
54
+ if (message.type === "cancel") {
55
+ running.get(id)?.abort();
56
+ return;
57
+ }
58
+ if (message.type !== "call" || typeof message.name !== "string") {
59
+ send({
60
+ type: "error",
61
+ id,
62
+ message: "The message is neither a call nor a cancel.",
63
+ });
64
+ return;
65
+ }
66
+ if (running.has(id)) {
67
+ send({ type: "error", id, message: "A call with this id is running." });
68
+ return;
69
+ }
70
+ const controller = new AbortController();
71
+ running.set(id, controller);
72
+ settled.push(host
73
+ .call(message.name, message.input, { signal: controller.signal })
74
+ .then((result) => {
75
+ running.delete(id);
76
+ send({ type: "result", id, ...result });
77
+ }));
78
+ };
79
+ send({ type: "ready", protocol: WORKER_PROTOCOL });
80
+ const tooLong = () => send({
81
+ type: "error",
82
+ id: null,
83
+ message: `The line is longer than ${max} bytes.`,
84
+ });
85
+ let pending = "";
86
+ let skipping = false;
87
+ options.input.setEncoding("utf8");
88
+ for await (const chunk of options.input) {
89
+ let text = pending + String(chunk);
90
+ pending = "";
91
+ let start = 0;
92
+ let newline = text.indexOf("\n");
93
+ while (newline !== -1) {
94
+ const line = text.slice(start, newline).trim();
95
+ if (skipping)
96
+ skipping = false;
97
+ else if (Buffer.byteLength(line, "utf8") > max)
98
+ tooLong();
99
+ else if (line !== "")
100
+ handle(line);
101
+ start = newline + 1;
102
+ newline = text.indexOf("\n", start);
103
+ }
104
+ text = text.slice(start);
105
+ if (skipping)
106
+ continue;
107
+ if (Buffer.byteLength(text, "utf8") > max) {
108
+ tooLong();
109
+ skipping = true;
110
+ continue;
111
+ }
112
+ pending = text;
113
+ }
114
+ if (!skipping && pending.trim() !== "")
115
+ handle(pending.trim());
116
+ await Promise.all(settled);
117
+ }
118
+ /**
119
+ * Read the manifest, import its tools, and serve the protocol on the
120
+ * process's stdin and stdout. What the application writes to stdout goes to
121
+ * stderr. A failure to start is written as `failed`, with exit code 1.
122
+ */
123
+ export async function startWorker(manifestPath, { readFile, process: proc }) {
124
+ const out = proc.stdout.write.bind(proc.stdout);
125
+ const write = (line) => {
126
+ out(`${line}\n`);
127
+ };
128
+ // Only the protocol on stdout: console.log and the like go to stderr.
129
+ proc.stdout.write = proc.stderr.write.bind(proc.stderr);
130
+ const log = (text) => {
131
+ proc.stderr.write(`[polaris worker] ${text}\n`);
132
+ };
133
+ proc.on("unhandledRejection", (reason) => {
134
+ log(`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
135
+ });
136
+ let tools;
137
+ try {
138
+ if (manifestPath === undefined) {
139
+ throw new Error("usage: node worker-main.js <tools.json>");
140
+ }
141
+ const manifest = JSON.parse(await readFile(manifestPath));
142
+ if (!isObject(manifest) || typeof manifest.module !== "string") {
143
+ throw new Error(`'${manifestPath}' is not a tools manifest`);
144
+ }
145
+ if (manifest.protocol !== WORKER_PROTOCOL) {
146
+ throw new Error(`'${manifestPath}' asks for worker protocol ${String(manifest.protocol)}; this polaris speaks ${WORKER_PROTOCOL}`);
147
+ }
148
+ const base = pathToFileURL(resolve(manifestPath));
149
+ tools = await loadTools(new URL(manifest.module, base));
150
+ }
151
+ catch (error) {
152
+ write(JSON.stringify({
153
+ type: "failed",
154
+ message: error instanceof Error ? error.message : String(error),
155
+ }));
156
+ proc.exitCode = 1;
157
+ return;
158
+ }
159
+ await runWorker({
160
+ tools,
161
+ input: proc.stdin,
162
+ write,
163
+ onToolError: (error, call) => log(`'${call.name}' failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`),
164
+ });
165
+ }
166
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/mcp/worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAA0B,QAAQ,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC,yCAAyC;AACzC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AAEjC,mDAAmD;AACnD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAc/C;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAsB;IACrD,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAC9D,MAAM,GAAG,GAAG,OAAO,CAAC,YAAY,IAAI,eAAe,CAAC;IACpD,MAAM,IAAI,GAAG,CAAC,OAAgC,EAAQ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e,EAAE,CACjH,CAAC;QACH,CAAC;QACD,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC;QAClD,KAAK,GAAG,MAAM,SAAS,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,KAAK,CACJ,IAAI,CAAC,SAAS,CAAC;YACd,IAAI,EAAE,QAAQ;YACd,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;SAC/D,CAAC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC;QAClB,OAAO;IACR,CAAC;IACD,MAAM,SAAS,CAAC;QACf,KAAK;QACL,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,KAAK;QACL,WAAW,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAC5B,GAAG,CACF,IAAI,IAAI,CAAC,IAAI,aAAa,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CACnG;KACF,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Prices, budgets and the exchange log, around each provider call.
3
+ *
4
+ * Before the call: its price is found, the request's own ceiling (`maxCost`)
5
+ * checked, and its estimated cost reserved on the scope's budget; a refusal
6
+ * sends nothing. After it: the reservation is replaced by the real cost, the
7
+ * cost is put on the response, and the exchange is logged.
8
+ */
9
+ import { type BudgetConfig, type BudgetStore } from "./budget.js";
10
+ import { type Cost, type ModelPrice, type Pricing } from "./cost.js";
11
+ import { type ExchangeEntry, type ExchangeLog } from "./log.js";
12
+ import type { ChatRequest, ChatResponse, EmbedRequest, EmbedResponse, StopReason, Usage } from "./types.js";
13
+ export interface MeterConfig {
14
+ readonly pricing?: Pricing;
15
+ readonly budget?: BudgetConfig & {
16
+ readonly store: BudgetStore;
17
+ };
18
+ readonly log?: ExchangeLog;
19
+ }
20
+ /** What polaris needs to meter one call. */
21
+ export interface MeterInput {
22
+ readonly operation: ExchangeEntry["operation"];
23
+ readonly provider: string;
24
+ readonly request: ChatRequest | EmbedRequest;
25
+ /** The model the call is expected to run on: the request's, or the driver's default. */
26
+ readonly model: string | undefined;
27
+ /** Estimate the call's most expensive outcome at `price`, for a budget. */
28
+ estimate(price: ModelPrice): string;
29
+ readonly scope?: string;
30
+ readonly maxCost?: string;
31
+ }
32
+ /** How a metered call ended. */
33
+ export interface MeterOutcome {
34
+ readonly model: string;
35
+ readonly usage: Usage;
36
+ /**
37
+ * Whether the provider reported usage that can be priced. Without it the
38
+ * call has no cost, and its estimate stays on the budget: a missing count
39
+ * is not a free call.
40
+ */
41
+ readonly usageKnown: boolean;
42
+ readonly responseId?: string;
43
+ readonly stopReason?: StopReason;
44
+ readonly response: ChatResponse | EmbedResponse;
45
+ }
46
+ /** One metered call, opened before it is sent and closed once. */
47
+ export interface Ticket {
48
+ /** The call answered: settle the budget, log, and answer its cost. */
49
+ finish(outcome: MeterOutcome): Promise<Cost | undefined>;
50
+ /**
51
+ * The call failed. `spent` says whether the provider may have billed it
52
+ * (a stream cut after it started): its estimate is then kept on the budget.
53
+ */
54
+ fail(error: unknown, options: {
55
+ cancelled: boolean;
56
+ spent: boolean;
57
+ }): Promise<void>;
58
+ }
59
+ /** Open the meter of one call. Throws, before anything is sent, when its budget refuses it. */
60
+ export declare function openTicket(config: MeterConfig, input: MeterInput): Promise<Ticket>;
61
+ /** Two costs added up, exactly, when both are known and in one currency. */
62
+ export declare function addCost(a: Cost | undefined, b: Cost | undefined): Cost | undefined;
63
+ //# sourceMappingURL=meter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meter.d.ts","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IG;IACH,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,aAAa,CAAC;CAChD;AAED,kEAAkE;AAClE,MAAM,WAAW,MAAM;IACtB,sEAAsE;IACtE,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,CAAC;IACzD;;;OAGG;IACH,IAAI,CACH,KAAK,EAAE,OAAO,EACd,OAAO,EAAE;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAC7C,OAAO,CAAC,IAAI,CAAC,CAAC;CACjB;AAED,+FAA+F;AAC/F,wBAAsB,UAAU,CAC/B,MAAM,EAAE,WAAW,EACnB,KAAK,EAAE,UAAU,GACf,OAAO,CAAC,MAAM,CAAC,CA2FjB;AAED,4EAA4E;AAC5E,wBAAgB,OAAO,CACtB,CAAC,EAAE,IAAI,GAAG,SAAS,EACnB,CAAC,EAAE,IAAI,GAAG,SAAS,GACjB,IAAI,GAAG,SAAS,CAIlB"}
package/dist/meter.js ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Prices, budgets and the exchange log, around each provider call.
3
+ *
4
+ * Before the call: its price is found, the request's own ceiling (`maxCost`)
5
+ * checked, and its estimated cost reserved on the scope's budget; a refusal
6
+ * sends nothing. After it: the reservation is replaced by the real cost, the
7
+ * cost is put on the response, and the exchange is logged.
8
+ */
9
+ import { limitOf, reserve, } from "./budget.js";
10
+ import { add, costOf, exceeds, priceFor, } from "./cost.js";
11
+ import { E_POLARIS_BUDGET_EXCEEDED, E_POLARIS_INVALID_REQUEST, E_POLARIS_UNKNOWN_PRICE, } from "./errors.js";
12
+ import { codeOf, writeLog, } from "./log.js";
13
+ /** Open the meter of one call. Throws, before anything is sent, when its budget refuses it. */
14
+ export async function openTicket(config, input) {
15
+ const started = Date.now();
16
+ const price = priceFor(config.pricing, input.model);
17
+ const limit = input.scope !== undefined && config.budget !== undefined
18
+ ? await limitOf(config.budget, input.scope)
19
+ : undefined;
20
+ if (input.scope !== undefined && config.budget === undefined) {
21
+ throw new E_POLARIS_INVALID_REQUEST([
22
+ "`scope` was given, but the config declares no `budget`",
23
+ ]);
24
+ }
25
+ let reservation;
26
+ if (limit !== undefined || input.maxCost !== undefined) {
27
+ // A budget cannot be kept without knowing what the model costs: refuse
28
+ // rather than let the call through unmetered.
29
+ if (price === undefined) {
30
+ throw new E_POLARIS_UNKNOWN_PRICE([input.model ?? "(no model)"]);
31
+ }
32
+ const estimate = input.estimate(price);
33
+ if (input.maxCost !== undefined && exceeds(estimate, input.maxCost)) {
34
+ throw new E_POLARIS_BUDGET_EXCEEDED(["this request", input.maxCost]);
35
+ }
36
+ if (input.scope !== undefined && config.budget !== undefined) {
37
+ reservation = await reserve(config.budget.store, input.scope, limit, estimate, config.budget.period);
38
+ }
39
+ }
40
+ const entry = (status) => ({
41
+ provider: input.provider,
42
+ model: input.model,
43
+ operation: input.operation,
44
+ status,
45
+ durationMs: Date.now() - started,
46
+ ...(input.scope !== undefined ? { scope: input.scope } : {}),
47
+ });
48
+ return {
49
+ async finish(outcome) {
50
+ const answered = priceFor(config.pricing, outcome.model) ?? price;
51
+ const amount = answered !== undefined && outcome.usageKnown
52
+ ? costOf(answered, outcome.usage)
53
+ : undefined;
54
+ const cost = amount !== undefined && config.pricing !== undefined
55
+ ? { amount, currency: config.pricing.currency }
56
+ : undefined;
57
+ // Without a price for the model that answered, or usage to price, the
58
+ // estimate stays.
59
+ if (reservation !== undefined && amount !== undefined) {
60
+ await reservation.settle(amount);
61
+ }
62
+ await writeLog(config.log, {
63
+ ...entry("ok"),
64
+ model: outcome.model,
65
+ usage: outcome.usage,
66
+ ...(cost !== undefined ? { cost } : {}),
67
+ ...(outcome.responseId !== undefined
68
+ ? { responseId: outcome.responseId }
69
+ : {}),
70
+ ...(outcome.stopReason !== undefined
71
+ ? { stopReason: outcome.stopReason }
72
+ : {}),
73
+ }, { request: input.request, response: outcome.response });
74
+ return cost;
75
+ },
76
+ async fail(error, options) {
77
+ if (reservation !== undefined && !options.spent)
78
+ await reservation.release();
79
+ await writeLog(config.log, {
80
+ ...entry(options.cancelled ? "cancelled" : "error"),
81
+ errorCode: codeOf(error),
82
+ }, { request: input.request });
83
+ },
84
+ };
85
+ }
86
+ /** Two costs added up, exactly, when both are known and in one currency. */
87
+ export function addCost(a, b) {
88
+ if (a === undefined)
89
+ return b;
90
+ if (b === undefined || a.currency !== b.currency)
91
+ return a;
92
+ return { amount: add(a.amount, b.amount), currency: a.currency };
93
+ }
94
+ //# sourceMappingURL=meter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meter.js","sourceRoot":"","sources":["../src/meter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAGN,OAAO,EAEP,OAAO,GACP,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,GAAG,EAEH,MAAM,EACN,OAAO,EAGP,QAAQ,GACR,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,yBAAyB,EACzB,yBAAyB,EACzB,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,MAAM,EAGN,QAAQ,GACR,MAAM,UAAU,CAAC;AA0DlB,+FAA+F;AAC/F,MAAM,CAAC,KAAK,UAAU,UAAU,CAC/B,MAAmB,EACnB,KAAiB;IAEjB,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC3B,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;IACpD,MAAM,KAAK,GACV,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS;QACvD,CAAC,CAAC,MAAM,OAAO,CAAC,MA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's `transports`:
3
+ *
4
+ * defineConfig({
5
+ * default: 'claude',
6
+ * providers: {
7
+ * claude: providers.anthropic({ model: 'claude-opus-5-5' }),
8
+ * local: providers.openaiCompatible({ baseURL: 'http://localhost:11434/v1', model: 'qwen3' }),
9
+ * },
10
+ * })
11
+ *
12
+ * A helper returns a factory; the driver is built, and its SDK loaded, the
13
+ * first time the provider is used.
14
+ */
15
+ import { anthropic } from "./drivers/anthropic.js";
16
+ import { openaiCompatible } from "./drivers/openai-compatible.js";
17
+ export declare const providers: {
18
+ anthropic: typeof anthropic;
19
+ openaiCompatible: typeof openaiCompatible;
20
+ };
21
+ export type { AnthropicConfig } from "./drivers/anthropic.js";
22
+ export type { OpenAICompatibleConfig } from "./drivers/openai-compatible.js";
23
+ //# sourceMappingURL=providers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.d.ts","sourceRoot":"","sources":["../src/providers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,eAAO,MAAM,SAAS;;;CAGrB,CAAC;AAEF,YAAY,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,YAAY,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One helper per provider polaris ships, as @adonisjs/mail's `transports`:
3
+ *
4
+ * defineConfig({
5
+ * default: 'claude',
6
+ * providers: {
7
+ * claude: providers.anthropic({ model: 'claude-opus-5-5' }),
8
+ * local: providers.openaiCompatible({ baseURL: 'http://localhost:11434/v1', model: 'qwen3' }),
9
+ * },
10
+ * })
11
+ *
12
+ * A helper returns a factory; the driver is built, and its SDK loaded, the
13
+ * first time the provider is used.
14
+ */
15
+ import { anthropic } from "./drivers/anthropic.js";
16
+ import { openaiCompatible } from "./drivers/openai-compatible.js";
17
+ export const providers = {
18
+ anthropic,
19
+ openaiCompatible,
20
+ };
21
+ //# sourceMappingURL=providers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers.js","sourceRoot":"","sources":["../src/providers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,MAAM,CAAC,MAAM,SAAS,GAAG;IACxB,SAAS;IACT,gBAAgB;CAChB,CAAC"}
@@ -0,0 +1,12 @@
1
+ /** Replace every occurrence of each secret in `text`. */
2
+ export declare function redact(text: string, secrets: readonly string[]): string;
3
+ /**
4
+ * The error to raise for a failed call that was given `secrets`.
5
+ *
6
+ * An error that holds none of them is returned as it is. One that holds any is
7
+ * replaced by `E_POLARIS_PROVIDER_FAILED` (or what `replace` builds), whose
8
+ * message is the original one with the secrets taken out, and which keeps no
9
+ * reference to the original.
10
+ */
11
+ export declare function scrub(error: unknown, provider: string, secrets: readonly (string | undefined)[], replace?: (provider: string, message: string) => Error): unknown;
12
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":"AAOA,yDAAyD;AACzD,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAIvE;AA+CD;;;;;;;GAOG;AACH,wBAAgB,KAAK,CACpB,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,SAAS,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,EACxC,OAAO,GAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,KACD,GAC7C,OAAO,CAOT"}
package/dist/redact.js ADDED
@@ -0,0 +1,77 @@
1
+ import { E_POLARIS_PROVIDER_FAILED } from "./errors.js";
2
+ const REDACTED = "[redacted]";
3
+ /** How many values the scan visits before it assumes the worst. */
4
+ const MAX_VISITS = 2_000;
5
+ const MAX_DEPTH = 8;
6
+ /** Replace every occurrence of each secret in `text`. */
7
+ export function redact(text, secrets) {
8
+ let out = text;
9
+ for (const secret of secrets)
10
+ out = out.split(secret).join(REDACTED);
11
+ return out;
12
+ }
13
+ /**
14
+ * Whether `value` holds one of `secrets` anywhere a logger or an error report
15
+ * could reach: its message, stack, cause, own properties, nested objects,
16
+ * arrays and `Headers`.
17
+ *
18
+ * A value too large or too deep to scan in full counts as holding one: the
19
+ * error it came from is then replaced, which loses detail but leaks nothing.
20
+ */
21
+ function holdsSecret(value, secrets) {
22
+ const seen = new Set();
23
+ let visits = 0;
24
+ const visit = (current, depth) => {
25
+ visits += 1;
26
+ if (visits > MAX_VISITS || depth > MAX_DEPTH)
27
+ return true;
28
+ if (typeof current === "string") {
29
+ return secrets.some((secret) => current.includes(secret));
30
+ }
31
+ if (typeof current !== "object" || current === null)
32
+ return false;
33
+ if (seen.has(current))
34
+ return false;
35
+ seen.add(current);
36
+ if (current instanceof Headers) {
37
+ for (const [, header] of current) {
38
+ if (visit(header, depth + 1))
39
+ return true;
40
+ }
41
+ return false;
42
+ }
43
+ if (current instanceof Error) {
44
+ if (visit(current.message, depth + 1))
45
+ return true;
46
+ if (visit(current.stack, depth + 1))
47
+ return true;
48
+ if (visit(current.cause, depth + 1))
49
+ return true;
50
+ }
51
+ if (Array.isArray(current)) {
52
+ return current.some((item) => visit(item, depth + 1));
53
+ }
54
+ for (const key of Object.keys(current)) {
55
+ if (visit(Reflect.get(current, key), depth + 1))
56
+ return true;
57
+ }
58
+ return false;
59
+ };
60
+ return visit(value, 0);
61
+ }
62
+ /**
63
+ * The error to raise for a failed call that was given `secrets`.
64
+ *
65
+ * An error that holds none of them is returned as it is. One that holds any is
66
+ * replaced by `E_POLARIS_PROVIDER_FAILED` (or what `replace` builds), whose
67
+ * message is the original one with the secrets taken out, and which keeps no
68
+ * reference to the original.
69
+ */
70
+ export function scrub(error, provider, secrets, replace = (name, message) => new E_POLARIS_PROVIDER_FAILED([name, message])) {
71
+ const live = secrets.filter((secret) => typeof secret === "string" && secret !== "");
72
+ if (live.length === 0 || !holdsSecret(error, live))
73
+ return error;
74
+ const message = error instanceof Error ? error.message : String(error);
75
+ return replace(provider, redact(message, live));
76
+ }
77
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.js","sourceRoot":"","sources":["../src/redact.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAExD,MAAM,QAAQ,GAAG,YAAY,CAAC;AAC9B,mEAAmE;AACnE,MAAM,UAAU,GAAG,KAAK,CAAC;AACzB,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,yDAAyD;AACzD,MAAM,UAAU,MAAM,CAAC,IAAY,EAAE,OAA0B;IAC9D,IAAI,GAAG,GAAG,IAAI,CAAC;IACf,KAAK,MAAM,MAAM,IAAI,OAAO;QAAE,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACrE,OAAO,GAAG,CAAC;AACZ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,WAAW,CAAC,KAAc,EAAE,OAA0B;IAC9D,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,MAAM,GAAG,CAAC,CAAC;IAEf,MAAM,KAAK,GAAG,CAAC,OAAgB,EAAE,KAAa,EAAW,EAAE;QAC1D,MAAM,IAAI,CAAC,CAAC;QACZ,IAAI,MAAM,GAAG,UAAU,IAAI,KAAK,GAAG,SAAS;YAAE,OAAO,IAAI,CAAC;QAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE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C,CAAC;gBAAE,OAAO,IAAI,CAAC;QAC9D,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC,CAAC;IAEF,OAAO,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;AACxB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,KAAK,CACpB,KAAc,EACd,QAAgB,EAChB,OAAwC,EACxC,UAAwD,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CACzE,IAAI,yBAAyB,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IAE/C,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAC1B,CAAC,MAAM,EAAoB,EAAE,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,EAAE,CACzE,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IACjE,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,OAAO,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;AACjD,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A budget store in Redis, shared by every instance that talks to the same
3
+ * server: what one instance reserves, the others see at once.
4
+ *
5
+ * Spend is kept as an integer count of billionths of the pricing currency, so
6
+ * that Redis adds it with `INCRBY`, exactly and atomically, where
7
+ * `INCRBYFLOAT` would add binary floats. A key's expiry is set in the same
8
+ * `MULTI` as the addition: a key is never left without one by a process that
9
+ * died between the two.
10
+ */
11
+ import type { BudgetStore } from "./budget.js";
12
+ /** The commands of a `MULTI` the store queues. */
13
+ export interface RedisBudgetTransaction {
14
+ incrby(key: string, increment: string): RedisBudgetTransaction;
15
+ pexpireat(key: string, unixTimeMilliseconds: number): RedisBudgetTransaction;
16
+ exec(): Promise<[error: Error | null, result: unknown][] | null>;
17
+ }
18
+ /**
19
+ * What the store needs of a Redis client: an ioredis client and a
20
+ * `@c9up/quasar` connection both fit as they are.
21
+ */
22
+ export interface RedisBudgetClient {
23
+ multi(): RedisBudgetTransaction;
24
+ }
25
+ export interface RedisBudgetStoreOptions {
26
+ /** Put before every key, to share one database with others. Default: `polaris:budget:`. */
27
+ readonly prefix?: string;
28
+ }
29
+ /**
30
+ * A budget store in Redis, for budgets shared by several instances:
31
+ *
32
+ * budget: { limit, period: 'month', store: redisBudgetStore(() => redis.connection()) }
33
+ *
34
+ * `client` is the client, or a function that answers it, called on each
35
+ * addition: a config file read before the Redis connections are booted can
36
+ * then name one.
37
+ *
38
+ * Amounts are rounded to nine decimals (half away from zero, so a release
39
+ * cancels its reservation exactly), and a key counts exactly up to about nine
40
+ * million units of the currency. The store declares those nine decimals: a
41
+ * reservation rounds its estimate and the final cost to them once each, so a
42
+ * request leaves exactly its rounded cost in the key.
43
+ */
44
+ export declare function redisBudgetStore(client: RedisBudgetClient | (() => RedisBudgetClient), options?: RedisBudgetStoreOptions): BudgetStore;
45
+ //# sourceMappingURL=redis-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-budget.d.ts","sourceRoot":"","sources":["../src/redis-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,kDAAkD;AAClD,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,sBAAsB,CAAC;IAC/D,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,GAAG,sBAAsB,CAAC;IAC7E,IAAI,IAAI,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC;CACjE;AAED;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IACjC,KAAK,IAAI,sBAAsB,CAAC;CAChC;AAED,MAAM,WAAW,uBAAuB;IACvC,2FAA2F;IAC3F,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CACzB;AAOD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAC/B,MAAM,EAAE,iBAAiB,GAAG,CAAC,MAAM,iBAAiB,CAAC,EACrD,OAAO,GAAE,uBAA4B,GACnC,WAAW,CA2Bb"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A budget store in Redis, shared by every instance that talks to the same
3
+ * server: what one instance reserves, the others see at once.
4
+ *
5
+ * Spend is kept as an integer count of billionths of the pricing currency, so
6
+ * that Redis adds it with `INCRBY`, exactly and atomically, where
7
+ * `INCRBYFLOAT` would add binary floats. A key's expiry is set in the same
8
+ * `MULTI` as the addition: a key is never left without one by a process that
9
+ * died between the two.
10
+ */
11
+ import { decimal } from "@c9up/atom";
12
+ /** Spend is counted in billionths of the currency. */
13
+ const DECIMALS = 9;
14
+ const UNIT = "1000000000";
15
+ const STEP = "0.000000001";
16
+ /**
17
+ * A budget store in Redis, for budgets shared by several instances:
18
+ *
19
+ * budget: { limit, period: 'month', store: redisBudgetStore(() => redis.connection()) }
20
+ *
21
+ * `client` is the client, or a function that answers it, called on each
22
+ * addition: a config file read before the Redis connections are booted can
23
+ * then name one.
24
+ *
25
+ * Amounts are rounded to nine decimals (half away from zero, so a release
26
+ * cancels its reservation exactly), and a key counts exactly up to about nine
27
+ * million units of the currency. The store declares those nine decimals: a
28
+ * reservation rounds its estimate and the final cost to them once each, so a
29
+ * request leaves exactly its rounded cost in the key.
30
+ */
31
+ export function redisBudgetStore(client, options = {}) {
32
+ const prefix = options.prefix ?? "polaris:budget:";
33
+ return {
34
+ decimals: DECIMALS,
35
+ async add(key, amount, expiresAt) {
36
+ const name = prefix + key;
37
+ const increment = decimal(amount).times(UNIT).toFixed(0, "half-up");
38
+ const redis = typeof client === "function" ? client() : client;
39
+ let transaction = redis.multi().incrby(name, increment);
40
+ if (expiresAt !== undefined)
41
+ transaction = transaction.pexpireat(name, expiresAt);
42
+ const replies = await transaction.exec();
43
+ if (replies === null) {
44
+ throw new Error(`[polaris] the budget transaction on '${name}' was aborted`);
45
+ }
46
+ const [error, total] = replies[0] ?? [null, undefined];
47
+ if (error !== null)
48
+ throw error;
49
+ if (typeof total !== "number" || !Number.isSafeInteger(total)) {
50
+ throw new Error(`[polaris] the spend under '${name}' is past what a budget counts exactly`);
51
+ }
52
+ return decimal(total).times(STEP).toString();
53
+ },
54
+ };
55
+ }
56
+ //# sourceMappingURL=redis-budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-budget.js","sourceRoot":"","sources":["../src/redis-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAuBrC,sDAAsD;AACtD,MAAM,QAAQ,GAAG,CAAC,CAAC;AACnB,MAAM,IAAI,GAAG,YAAY,CAAC;AAC1B,MAAM,IAAI,GAAG,aAAa,CAAC;AAE3B;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,gBAAgB,CAC/B,MAAqD,EACrD,UAAmC,EAAE;IAErC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,iBAAiB,CAAC;IACnD,OAAO;QACN,QAAQ,EAAE,QAAQ;QAClB,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS;YAC/B,MAAM,IAAI,GAAG,MAAM,GAAG,GAAG,CAAC;YAC1B,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;YACpE,MAAM,KAAK,GAAG,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAA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