@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,30 @@
1
+ import {
2
+ E_POLARIS_AUTHENTICATION,
3
+ E_POLARIS_PROVIDER_REJECTED,
4
+ E_POLARIS_PROVIDER_UNAVAILABLE,
5
+ E_POLARIS_RATE_LIMITED,
6
+ } from "../errors.js";
7
+
8
+ /**
9
+ * The polaris error for a provider's HTTP error status, the same for every
10
+ * driver: 401 and 403 are the credentials, 429 the rate limit, 5xx (and
11
+ * Groq's 498, out of capacity) the provider failing, any other status a
12
+ * request the provider rejected.
13
+ */
14
+ export function errorForStatus(
15
+ provider: string,
16
+ status: number,
17
+ detail: string,
18
+ cause?: unknown,
19
+ ): Error {
20
+ const args: [string, string] = [provider, detail];
21
+ const options = cause === undefined ? undefined : { cause };
22
+ if (status === 401 || status === 403) {
23
+ return new E_POLARIS_AUTHENTICATION(args, options);
24
+ }
25
+ if (status === 429) return new E_POLARIS_RATE_LIMITED(args, options);
26
+ if (status >= 500 || status === 498) {
27
+ return new E_POLARIS_PROVIDER_UNAVAILABLE(args, options);
28
+ }
29
+ return new E_POLARIS_PROVIDER_REJECTED(args, options);
30
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * The errors of polaris, one class per code. An application tests
3
+ * `error.code` or `error instanceof errors.E_POLARIS_…`.
4
+ */
5
+
6
+ import { createError } from "@c9up/flare";
7
+
8
+ /** `@c9up/polaris/services/main` was used before `PolarisProvider.boot()` ran. */
9
+ export const E_POLARIS_NOT_BOOTED = createError(
10
+ "[polaris] used before PolarisProvider.boot() ran. Check that `@c9up/polaris/provider` is listed in your reamrc.ts providers.",
11
+ "E_POLARIS_NOT_BOOTED",
12
+ );
13
+
14
+ /** The application has no `polaris` config. */
15
+ export const E_POLARIS_MISSING_CONFIG = createError(
16
+ "[polaris] no `polaris` config was found. Add config/polaris.ts exporting defineConfig({ default, providers }).",
17
+ "E_POLARIS_MISSING_CONFIG",
18
+ );
19
+
20
+ /** A config value or a call option is out of range. */
21
+ export const E_POLARIS_INVALID_CONFIG = createError<[string]>(
22
+ "[polaris] invalid config: %s",
23
+ "E_POLARIS_INVALID_CONFIG",
24
+ );
25
+
26
+ /** `use()` was called with no name and the config sets no `default`. */
27
+ export const E_POLARIS_NO_DEFAULT_PROVIDER = createError(
28
+ "[polaris] use() was called without a provider name, and the config sets no `default`.",
29
+ "E_POLARIS_NO_DEFAULT_PROVIDER",
30
+ );
31
+
32
+ /** `use(name)` names a provider the config does not declare. */
33
+ export const E_POLARIS_UNKNOWN_PROVIDER = createError<[string, string]>(
34
+ "[polaris] the provider '%s' is not declared in config.providers. %s",
35
+ "E_POLARIS_UNKNOWN_PROVIDER",
36
+ );
37
+
38
+ /** A request is malformed (no messages, a bad token limit…). */
39
+ export const E_POLARIS_INVALID_REQUEST = createError<[string]>(
40
+ "[polaris] invalid request: %s",
41
+ "E_POLARIS_INVALID_REQUEST",
42
+ );
43
+
44
+ /** The provider cannot serve what the request asks for. Nothing was sent. */
45
+ export const E_POLARIS_UNSUPPORTED = createError<[string, string]>(
46
+ "[polaris] the provider '%s' does not support %s.",
47
+ "E_POLARIS_UNSUPPORTED",
48
+ );
49
+
50
+ /** The call did not finish within its deadline. */
51
+ export const E_POLARIS_TIMEOUT = createError<[number]>(
52
+ "[polaris] the provider call did not finish within %d ms.",
53
+ "E_POLARIS_TIMEOUT",
54
+ );
55
+
56
+ /** The provider sent a body larger than `maxResponseBytes`. */
57
+ export const E_POLARIS_RESPONSE_TOO_LARGE = createError<[number]>(
58
+ "[polaris] the provider's response is larger than %d bytes.",
59
+ "E_POLARIS_RESPONSE_TOO_LARGE",
60
+ );
61
+
62
+ /** A structured answer did not match its schema, or could not be had. */
63
+ export const E_POLARIS_INVALID_OUTPUT = createError<[string, string]>(
64
+ "[polaris] '%s' gave no valid answer: %s",
65
+ "E_POLARIS_INVALID_OUTPUT",
66
+ );
67
+
68
+ /** A request would go past its own `maxCost`, or its scope's budget. Nothing was sent. */
69
+ export const E_POLARIS_BUDGET_EXCEEDED = createError<[string, string]>(
70
+ "[polaris] the budget of %s (%s) does not cover this request.",
71
+ "E_POLARIS_BUDGET_EXCEEDED",
72
+ 429,
73
+ );
74
+
75
+ /** A budget applies, but the price table has no price for the model. Nothing was sent. */
76
+ export const E_POLARIS_UNKNOWN_PRICE = createError<[string]>(
77
+ "[polaris] a budget applies, but pricing has no price for the model '%s'.",
78
+ "E_POLARIS_UNKNOWN_PRICE",
79
+ );
80
+
81
+ /** A tool run was still calling tools at its last allowed step. */
82
+ export const E_POLARIS_TOO_MANY_STEPS = createError<[number]>(
83
+ "[polaris] the model was still calling tools after %d steps.",
84
+ "E_POLARIS_TOO_MANY_STEPS",
85
+ );
86
+
87
+ /**
88
+ * One reply called more tools than the run allows: none of its calls ran.
89
+ * A model steered by what it read could otherwise fire a side-effecting tool
90
+ * thousands of times at once.
91
+ */
92
+ export const E_POLARIS_TOO_MANY_TOOL_CALLS = createError<[number, number]>(
93
+ "[polaris] the model called %d tools in one reply, more than the %d allowed; none ran.",
94
+ "E_POLARIS_TOO_MANY_TOOL_CALLS",
95
+ );
96
+
97
+ /** A stream ended without its final `done` event. */
98
+ export const E_POLARIS_STREAM_INCOMPLETE = createError<[string]>(
99
+ "[polaris] the stream from '%s' ended before its final response.",
100
+ "E_POLARIS_STREAM_INCOMPLETE",
101
+ );
102
+
103
+ /** A driver returned something that breaks the contract (wrong vector count…). */
104
+ export const E_POLARIS_INVALID_RESPONSE = createError<[string, string]>(
105
+ "[polaris] the provider '%s' returned an invalid response: %s",
106
+ "E_POLARIS_INVALID_RESPONSE",
107
+ );
108
+
109
+ /*
110
+ * What a provider answered, once its driver's retries are spent. The HTTP
111
+ * status is the one an application's exception handler sends on if the error
112
+ * reaches it: the provider's own status (a 401 for a bad provider key) says
113
+ * nothing true about the end user's request, so it is never passed through.
114
+ */
115
+
116
+ /** The provider refused the key (401, 403). */
117
+ export const E_POLARIS_AUTHENTICATION = createError<[string, string]>(
118
+ "[polaris] '%s' refused the credentials: %s",
119
+ "E_POLARIS_AUTHENTICATION",
120
+ 502,
121
+ );
122
+
123
+ /** The provider is rate limiting this key (429), after the retries. */
124
+ export const E_POLARIS_RATE_LIMITED = createError<[string, string]>(
125
+ "[polaris] '%s' is rate limiting: %s",
126
+ "E_POLARIS_RATE_LIMITED",
127
+ 503,
128
+ );
129
+
130
+ /** The provider is overloaded or failing (5xx, 529), after the retries. */
131
+ export const E_POLARIS_PROVIDER_UNAVAILABLE = createError<[string, string]>(
132
+ "[polaris] '%s' is unavailable: %s",
133
+ "E_POLARIS_PROVIDER_UNAVAILABLE",
134
+ 503,
135
+ );
136
+
137
+ /** The provider rejected the request itself (400, 404, 413, 422…). */
138
+ export const E_POLARIS_PROVIDER_REJECTED = createError<[string, string]>(
139
+ "[polaris] '%s' rejected the request: %s",
140
+ "E_POLARIS_PROVIDER_REJECTED",
141
+ 502,
142
+ );
143
+
144
+ /** The provider could not be reached (DNS, connection, TLS), after the retries. */
145
+ export const E_POLARIS_PROVIDER_UNREACHABLE = createError<[string, string]>(
146
+ "[polaris] '%s' could not be reached: %s",
147
+ "E_POLARIS_PROVIDER_UNREACHABLE",
148
+ 502,
149
+ );
150
+
151
+ /** The test fake was asked for a reply it was not given. */
152
+ export const E_POLARIS_FAKE_NO_REPLY = createError(
153
+ "[polaris] the fake has no reply left. Script one with fake.reply(), fake.replyJson(), fake.callTool() or fake.fail().",
154
+ "E_POLARIS_FAKE_NO_REPLY",
155
+ );
156
+
157
+ /** An assertion of the test fake does not hold. */
158
+ export const E_POLARIS_ASSERTION_FAILED = createError<[string, string]>(
159
+ "[polaris] fake.%s() failed: %s",
160
+ "E_POLARIS_ASSERTION_FAILED",
161
+ );
162
+
163
+ /**
164
+ * A provider call failed, and its error mentioned a key given for that call.
165
+ * The message is the original one with the key replaced, and the original
166
+ * error is not attached.
167
+ */
168
+ export const E_POLARIS_PROVIDER_FAILED = createError<[string, string]>(
169
+ "[polaris] the call to '%s' failed: %s",
170
+ "E_POLARIS_PROVIDER_FAILED",
171
+ );
172
+
173
+ /**
174
+ * An MCP server could not be started or reached, broke the protocol, or
175
+ * answered with an error. Its connection's secrets (headers, token, the
176
+ * environment given to a stdio server) are taken out of the message.
177
+ */
178
+ export const E_POLARIS_MCP = createError<[string, string]>(
179
+ "[polaris] the MCP server '%s' failed: %s",
180
+ "E_POLARIS_MCP",
181
+ 502,
182
+ );
183
+
184
+ /**
185
+ * A skill folder cannot be read: no `SKILL.md`, a frontmatter that misses
186
+ * `name` or `description` or breaks their limits, a file over its size, a
187
+ * tool module that exports no tools.
188
+ */
189
+ export const E_POLARIS_INVALID_SKILL = createError<[string, string]>(
190
+ "[polaris] the skill at '%s' cannot be used: %s",
191
+ "E_POLARIS_INVALID_SKILL",
192
+ );
193
+
194
+ /**
195
+ * The application's tool and skill catalog cannot be built or used: a tool
196
+ * module that exports no tools, one name in two files, a manifest that is
197
+ * missing, unreadable or out of date.
198
+ */
199
+ export const E_POLARIS_INVALID_CATALOG = createError<[string]>(
200
+ "[polaris] the tool catalog cannot be used: %s",
201
+ "E_POLARIS_INVALID_CATALOG",
202
+ );
package/src/extract.ts ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * A structured answer: one JSON value matching a schema, checked by it.
3
+ *
4
+ * The schema goes to the provider's own structured-output mode when it has
5
+ * one, and otherwise through a tool the model is asked to call. Either way the
6
+ * answer is validated by the schema itself before it is returned, and an
7
+ * answer that fails goes back to the model with the schema's issues.
8
+ */
9
+
10
+ import type { Cost } from "./cost.js";
11
+ import {
12
+ E_POLARIS_INVALID_OUTPUT,
13
+ E_POLARIS_INVALID_REQUEST,
14
+ E_POLARIS_UNSUPPORTED,
15
+ } from "./errors.js";
16
+ import { addCost } from "./meter.js";
17
+ import { addUsage, NO_USAGE } from "./response.js";
18
+ import {
19
+ describeIssues,
20
+ objectJsonSchema,
21
+ type SchemaIssue,
22
+ type SchemaOutput,
23
+ type SchemaResult,
24
+ type StandardSchema,
25
+ } from "./schema.js";
26
+ import type {
27
+ ChatRequest,
28
+ ChatResponse,
29
+ DriverFeatures,
30
+ Message,
31
+ ToolCallPart,
32
+ Usage,
33
+ } from "./types.js";
34
+
35
+ /** A request whose answer is one value of `schema`. */
36
+ export type ExtractRequest<S extends StandardSchema> = Omit<
37
+ ChatRequest,
38
+ "output" | "tools" | "toolChoice"
39
+ > & {
40
+ readonly schema: S;
41
+ /** The answer's name, sent to the provider. Default `result`. */
42
+ readonly name?: string;
43
+ readonly description?: string;
44
+ };
45
+
46
+ export interface ExtractResult<T> {
47
+ /** The answer, as the schema returned it. */
48
+ readonly value: T;
49
+ /** The provider's last reply. */
50
+ readonly response: ChatResponse;
51
+ /** Requests sent: 1, or more when an answer failed the schema. */
52
+ readonly attempts: number;
53
+ /** Tokens of every request, added up. */
54
+ readonly usage: Usage;
55
+ /** What every request cost, added up, when each one is priced. */
56
+ readonly cost?: Cost;
57
+ }
58
+
59
+ const NAME = /^[a-zA-Z0-9_-]{1,64}$/;
60
+
61
+ /**
62
+ * Ask until the answer passes `schema`, `retries` more times at most.
63
+ * `send` is the client's `chat`, with the call's options already bound.
64
+ */
65
+ export async function extract<S extends StandardSchema>(
66
+ request: ExtractRequest<S>,
67
+ retries: number,
68
+ features: DriverFeatures & { readonly provider: string },
69
+ send: (request: ChatRequest) => Promise<ChatResponse>,
70
+ ): Promise<ExtractResult<SchemaOutput<S>>> {
71
+ const { schema, name: answerName, description, ...chat } = request;
72
+ const name = answerName ?? "result";
73
+ if (!NAME.test(name)) {
74
+ throw new E_POLARIS_INVALID_REQUEST([
75
+ `an answer's name is 1 to 64 letters, digits, '_' or '-'; '${name}' is not`,
76
+ ]);
77
+ }
78
+ const viaTool = !features.structuredOutput;
79
+ if (viaTool && !features.tools) {
80
+ throw new E_POLARIS_UNSUPPORTED([features.provider, "structured output"]);
81
+ }
82
+ const jsonSchema = objectJsonSchema(request.schema, "the answer");
83
+ const base: ChatRequest = viaTool
84
+ ? {
85
+ ...chat,
86
+ system: [
87
+ chat.system,
88
+ `Answer by calling the tool '${name}' with the result.`,
89
+ ]
90
+ .filter((part) => part !== undefined && part !== "")
91
+ .join("\n\n"),
92
+ tools: [
93
+ {
94
+ name,
95
+ description: description ?? "Return the result.",
96
+ inputSchema: jsonSchema,
97
+ },
98
+ ],
99
+ toolChoice: "auto",
100
+ }
101
+ : {
102
+ ...chat,
103
+ output: {
104
+ name,
105
+ schema: jsonSchema,
106
+ ...(description !== undefined ? { description } : {}),
107
+ },
108
+ };
109
+
110
+ const messages: Message[] = [...request.messages];
111
+ let usage: Usage = NO_USAGE;
112
+ let cost: Cost | undefined;
113
+ let priced = true;
114
+ let issues: readonly SchemaIssue[] = [];
115
+
116
+ for (let attempt = 1; attempt <= retries + 1; attempt++) {
117
+ const response = await send({ ...base, messages: [...messages] });
118
+ usage = addUsage(usage, response.usage);
119
+ cost = addCost(cost, response.cost);
120
+ priced = priced && response.cost !== undefined;
121
+ // An answer the provider refused or cut short will not get better by
122
+ // asking again the same way.
123
+ if (response.stopReason === "refusal") {
124
+ throw new E_POLARIS_INVALID_OUTPUT([
125
+ features.provider,
126
+ "the provider refused to answer",
127
+ ]);
128
+ }
129
+ if (response.stopReason === "max_tokens") {
130
+ throw new E_POLARIS_INVALID_OUTPUT([
131
+ features.provider,
132
+ "the answer was cut at the output limit; raise maxTokens",
133
+ ]);
134
+ }
135
+
136
+ const call = viaTool
137
+ ? response.toolCalls.find((candidate) => candidate.name === name)
138
+ : undefined;
139
+ const candidate = read(response, viaTool, call, name);
140
+ const result: SchemaResult<SchemaOutput<S>> =
141
+ "issues" in candidate
142
+ ? candidate
143
+ : await schema["~standard"].validate(candidate.value);
144
+ if (result.issues === undefined) {
145
+ return {
146
+ value: result.value,
147
+ response,
148
+ attempts: attempt,
149
+ usage,
150
+ ...(priced && cost !== undefined ? { cost } : {}),
151
+ };
152
+ }
153
+
154
+ issues = result.issues;
155
+ messages.push(response.message, feedback(issues, call, name));
156
+ }
157
+
158
+ throw new E_POLARIS_INVALID_OUTPUT(
159
+ [
160
+ features.provider,
161
+ `the answer did not match the schema after ${retries + 1} attempts: ${describeIssues(issues)}`,
162
+ ],
163
+ { cause: { issues } },
164
+ );
165
+ }
166
+
167
+ /** The value the reply holds, or why it holds none. */
168
+ function read(
169
+ response: ChatResponse,
170
+ viaTool: boolean,
171
+ call: ToolCallPart | undefined,
172
+ name: string,
173
+ ): { readonly value: unknown } | { readonly issues: readonly SchemaIssue[] } {
174
+ if (viaTool) {
175
+ return call
176
+ ? { value: call.input }
177
+ : { issues: [{ message: `the answer did not call the tool '${name}'` }] };
178
+ }
179
+ try {
180
+ return { value: JSON.parse(response.text) };
181
+ } catch {
182
+ return { issues: [{ message: "the answer is not valid JSON" }] };
183
+ }
184
+ }
185
+
186
+ /** What the model is told about an answer that failed, to try again. */
187
+ function feedback(
188
+ issues: readonly SchemaIssue[],
189
+ call: ToolCallPart | undefined,
190
+ name: string,
191
+ ): Message {
192
+ const problems = describeIssues(issues);
193
+ if (call) {
194
+ return {
195
+ role: "user",
196
+ content: [
197
+ {
198
+ type: "tool_result",
199
+ toolCallId: call.id,
200
+ content: `Invalid input: ${problems}`,
201
+ isError: true,
202
+ },
203
+ {
204
+ type: "text",
205
+ text: `Call the tool '${name}' again with corrected input.`,
206
+ },
207
+ ],
208
+ };
209
+ }
210
+ return {
211
+ role: "user",
212
+ content: `Your answer did not match the schema: ${problems}. Answer again.`,
213
+ };
214
+ }
package/src/index.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `@c9up/polaris`: one API for language models, whatever the provider.
3
+ */
4
+
5
+ import "./augmentations.js";
6
+
7
+ export {
8
+ type BudgetConfig,
9
+ type BudgetPeriod,
10
+ type BudgetStore,
11
+ memoryBudgetStore,
12
+ } from "./budget.js";
13
+ export type { Cost, ModelPrice, Pricing } from "./cost.js";
14
+ export * as errors from "./errors.js";
15
+ export type { ExtractRequest, ExtractResult } from "./extract.js";
16
+ export { JSON_SCHEMA_KEYWORDS, jsonSchema } from "./json-schema.js";
17
+ export type { ExchangeEntry, ExchangeLog } from "./log.js";
18
+ export {
19
+ type DeclaredProviders,
20
+ defineConfig,
21
+ Polaris,
22
+ type PolarisService,
23
+ } from "./Polaris.js";
24
+ export {
25
+ type CallOptions,
26
+ type ClientOptions,
27
+ type ExtractOptions,
28
+ PolarisClient,
29
+ type RunEvent,
30
+ type RunOptions,
31
+ type RunRequest,
32
+ type RunResult,
33
+ type StreamToOptions,
34
+ } from "./PolarisClient.js";
35
+ export {
36
+ type AnthropicConfig,
37
+ type OpenAICompatibleConfig,
38
+ providers,
39
+ } from "./providers.js";
40
+ export {
41
+ type RedisBudgetClient,
42
+ type RedisBudgetStoreOptions,
43
+ type RedisBudgetTransaction,
44
+ redisBudgetStore,
45
+ } from "./redis-budget.js";
46
+ export {
47
+ addUsage,
48
+ createResponse,
49
+ NO_USAGE,
50
+ type ResponseInput,
51
+ } from "./response.js";
52
+ export type {
53
+ SchemaIssue,
54
+ SchemaOutput,
55
+ SchemaResult,
56
+ StandardSchema,
57
+ } from "./schema.js";
58
+ export {
59
+ ClientLeft,
60
+ type DoneEventData,
61
+ type RunDoneEventData,
62
+ type SseFailure,
63
+ type SseSink,
64
+ type StreamRunToResult,
65
+ type StreamToResult,
66
+ type ToolResultEventData,
67
+ } from "./sse.js";
68
+ export type {
69
+ FakeCall,
70
+ FakeOptions,
71
+ FakeProvider,
72
+ FakeReply,
73
+ } from "./testing/FakeProvider.js";
74
+ export {
75
+ defineTool,
76
+ type ExecuteContext,
77
+ type JsonSchemaToolSpec,
78
+ MAX_RUN_TOOLS,
79
+ type PolarisTool,
80
+ type ToolContext,
81
+ ToolError,
82
+ type ToolOutcome,
83
+ type ToolSpec,
84
+ } from "./tools.js";
85
+ export type * from "./types.js";