@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,49 @@
1
+ /**
2
+ * Tool modules: the files a skill's `tools/` folder and the application's
3
+ * tool folders hold. Each exports a tool, a list of tools, or a function
4
+ * (sync or async) returning one, as `default` or `tools`.
5
+ */
6
+
7
+ import { extname } from "node:path";
8
+ import { isTool, type PolarisTool } from "./tools.js";
9
+
10
+ const EXTENSIONS = new Set([".js", ".mjs", ".ts", ".mts"]);
11
+
12
+ /**
13
+ * Is `file` (a base name) a tool module? A file whose name starts with `_` or
14
+ * `.`, a declaration file and a test are not: shared code goes in `_x.ts`.
15
+ */
16
+ export function isToolModuleFile(file: string): boolean {
17
+ return (
18
+ EXTENSIONS.has(extname(file)) &&
19
+ !/^[._]/.test(file) &&
20
+ !/\.d\.[mc]?ts$|\.(test|spec)\.[mc]?[jt]s$/.test(file)
21
+ );
22
+ }
23
+
24
+ /**
25
+ * The tools a module exports, or why it has none: `failed to load: ...` or
26
+ * `must export a tool...`. A function that is not itself a tool is called.
27
+ */
28
+ export async function importToolModule(
29
+ url: string,
30
+ ): Promise<PolarisTool[] | string> {
31
+ let exported: unknown;
32
+ try {
33
+ const module: unknown = await import(url);
34
+ exported =
35
+ typeof module === "object" && module !== null
36
+ ? (Reflect.get(module, "default") ?? Reflect.get(module, "tools"))
37
+ : undefined;
38
+ if (typeof exported === "function" && !isTool(exported)) {
39
+ exported = await exported();
40
+ }
41
+ } catch (error) {
42
+ return `failed to load: ${error instanceof Error ? error.message : String(error)}`;
43
+ }
44
+ const list: unknown[] = Array.isArray(exported) ? exported : [exported];
45
+ if (list.length === 0 || !list.every(isTool)) {
46
+ return "must export a tool, a list of tools, or a function returning one, as `default` or `tools`";
47
+ }
48
+ return list;
49
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Tools the model may call, and the loop that runs them.
3
+ *
4
+ * A tool's input is described by a {@link StandardSchema} (a rune schema,
5
+ * `rune.create({...})`, is one), or by a plain JSON Schema (`inputSchema`).
6
+ */
7
+
8
+ import {
9
+ E_POLARIS_INVALID_REQUEST,
10
+ E_POLARIS_TOO_MANY_STEPS,
11
+ E_POLARIS_TOO_MANY_TOOL_CALLS,
12
+ } from "./errors.js";
13
+ import { jsonSchema } from "./json-schema.js";
14
+ import {
15
+ describeIssues,
16
+ objectJsonSchema,
17
+ type SchemaOutput,
18
+ type SchemaResult,
19
+ type StandardSchema,
20
+ } from "./schema.js";
21
+ import type {
22
+ JsonSchema,
23
+ ToolCallPart,
24
+ ToolDefinition,
25
+ ToolResultPart,
26
+ } from "./types.js";
27
+
28
+ /** What a tool's handler is given besides its input. */
29
+ export interface ToolContext {
30
+ /** The call's id, as the model gave it. */
31
+ readonly toolCallId: string;
32
+ /** Aborted when the run is cancelled or runs out of time. */
33
+ readonly signal: AbortSignal;
34
+ /**
35
+ * Add tools to the run: the model can call them from the run's next
36
+ * request. A tool already in the run is left as it is; one of the run's
37
+ * `inactiveTools` becomes callable. Another tool under a name the run
38
+ * already has, or more than {@link MAX_RUN_TOOLS} tools in all, is refused
39
+ * with a {@link ToolError}, which the model reads. Outside a run (a tool
40
+ * executed by hand), it throws that error too.
41
+ */
42
+ addTools(tools: readonly PolarisTool[]): void;
43
+ }
44
+
45
+ /** What `execute` is given: a run passes `addTools`, a caller may leave it out. */
46
+ export type ExecuteContext = Omit<ToolContext, "addTools"> &
47
+ Partial<Pick<ToolContext, "addTools">>;
48
+
49
+ function outsideRun(): never {
50
+ throw new ToolError("Tools can only be added during a run.");
51
+ }
52
+
53
+ /**
54
+ * An error whose message the model may read. Throw it from a handler to tell
55
+ * the model what went wrong ("No canton named 'Genf'"); every other error
56
+ * reaches the model as a bare "the tool failed", so its message, stack and
57
+ * whatever secret it carries stay on the server.
58
+ */
59
+ export class ToolError extends Error {
60
+ constructor(message: string) {
61
+ super(message);
62
+ this.name = "ToolError";
63
+ }
64
+ }
65
+
66
+ /** A tool as `defineTool()` builds it. */
67
+ export interface PolarisTool {
68
+ readonly name: string;
69
+ /** What is sent to the model. */
70
+ readonly definition: ToolDefinition;
71
+ /** Validate the model's input, then run the handler. Never throws. */
72
+ execute(call: ToolCallPart, context: ExecuteContext): Promise<ToolOutcome>;
73
+ }
74
+
75
+ /** How one tool call went. */
76
+ export type ToolOutcome =
77
+ | { readonly ok: true; readonly content: string }
78
+ | {
79
+ readonly ok: false;
80
+ readonly content: string;
81
+ /** What failed, for the application's logs. Never shown to the model. */
82
+ readonly error: unknown;
83
+ };
84
+
85
+ export interface ToolSpec<S extends StandardSchema> {
86
+ readonly name: string;
87
+ readonly description: string;
88
+ readonly schema: S;
89
+ /**
90
+ * Runs once the input passed the schema. A string goes to the model as it
91
+ * is; anything else is sent as JSON.
92
+ */
93
+ run(input: SchemaOutput<S>, context: ToolContext): unknown;
94
+ }
95
+
96
+ /**
97
+ * A tool whose input is described by a plain JSON Schema, checked by polaris
98
+ * (see {@link jsonSchema} for the keywords it checks). `I` is what the input
99
+ * is typed as.
100
+ */
101
+ export interface JsonSchemaToolSpec<I = Record<string, unknown>> {
102
+ readonly name: string;
103
+ readonly description: string;
104
+ /** An object schema: `{ type: 'object', properties: {...}, required: [...] }`. */
105
+ readonly inputSchema: JsonSchema;
106
+ run(input: I, context: ToolContext): unknown;
107
+ }
108
+
109
+ const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
110
+ /** The most tools one run holds, active and inactive. */
111
+ export const MAX_RUN_TOOLS = 128;
112
+ const FAILED = "The tool failed.";
113
+
114
+ /**
115
+ * Declare a tool. Its input is typed by its schema:
116
+ *
117
+ * const lookup = defineTool({
118
+ * name: 'canton_rule',
119
+ * description: 'Look up a tax rule for a Swiss canton',
120
+ * schema: rune.create({ canton: rune.string() }),
121
+ * run: async ({ canton }) => rules.find(canton),
122
+ * })
123
+ *
124
+ * or by a plain JSON Schema, as an MCP server or a skill gives it:
125
+ *
126
+ * defineTool({
127
+ * name: 'canton_rule',
128
+ * description: 'Look up a tax rule for a Swiss canton',
129
+ * inputSchema: { type: 'object', properties: { canton: { type: 'string' } }, required: ['canton'] },
130
+ * run: async ({ canton }) => rules.find(String(canton)),
131
+ * })
132
+ */
133
+ export function defineTool<S extends StandardSchema>(
134
+ spec: ToolSpec<S>,
135
+ ): PolarisTool;
136
+ export function defineTool<I = Record<string, unknown>>(
137
+ spec: JsonSchemaToolSpec<I>,
138
+ ): PolarisTool;
139
+ export function defineTool(
140
+ spec: ToolSpec<StandardSchema> | JsonSchemaToolSpec<unknown>,
141
+ ): PolarisTool {
142
+ if (!TOOL_NAME.test(spec.name)) {
143
+ throw new E_POLARIS_INVALID_REQUEST([
144
+ `a tool name is 1 to 64 letters, digits, '_' or '-'; '${spec.name}' is not`,
145
+ ]);
146
+ }
147
+ const label = `tool '${spec.name}'`;
148
+ const hasSchema = "schema" in spec && spec.schema !== undefined;
149
+ const hasInputSchema =
150
+ "inputSchema" in spec && spec.inputSchema !== undefined;
151
+ if (hasSchema === hasInputSchema) {
152
+ throw new E_POLARIS_INVALID_REQUEST([
153
+ `${label} takes one of \`schema\` (a Standard Schema) and \`inputSchema\` (a JSON Schema)`,
154
+ ]);
155
+ }
156
+ const schema: StandardSchema = hasSchema
157
+ ? (spec as ToolSpec<StandardSchema>).schema
158
+ : jsonSchema((spec as JsonSchemaToolSpec<unknown>).inputSchema, label);
159
+ const standard = schema["~standard"];
160
+ const inputSchema = objectJsonSchema(schema, label);
161
+ const run = spec.run as (input: unknown, context: ToolContext) => unknown;
162
+
163
+ return {
164
+ name: spec.name,
165
+ definition: { name: spec.name, description: spec.description, inputSchema },
166
+ async execute(call, context) {
167
+ let result: SchemaResult<unknown>;
168
+ try {
169
+ result = await standard.validate(call.input);
170
+ } catch (error) {
171
+ return { ok: false, content: FAILED, error };
172
+ }
173
+ if (result.issues !== undefined) {
174
+ return {
175
+ ok: false,
176
+ content: `Invalid input: ${describeIssues(result.issues)}`,
177
+ error: result.issues,
178
+ };
179
+ }
180
+ const handed: ToolContext = {
181
+ toolCallId: context.toolCallId,
182
+ signal: context.signal,
183
+ addTools: context.addTools ?? outsideRun,
184
+ };
185
+ try {
186
+ return {
187
+ ok: true,
188
+ content: toContent(await run(result.value, handed)),
189
+ };
190
+ } catch (error) {
191
+ return {
192
+ ok: false,
193
+ content: error instanceof ToolError ? error.message : FAILED,
194
+ error,
195
+ };
196
+ }
197
+ },
198
+ };
199
+ }
200
+
201
+ function toContent(value: unknown): string {
202
+ if (typeof value === "string") return value;
203
+ if (value === undefined) return "";
204
+ return JSON.stringify(value);
205
+ }
206
+
207
+ /** Called with every failed tool call, and the error the model does not see. */
208
+ export type OnToolError = (error: unknown, call: ToolCallPart) => void;
209
+
210
+ /** Whether `value` is a tool built by {@link defineTool}. */
211
+ export function isTool(value: unknown): value is PolarisTool {
212
+ return (
213
+ typeof value === "object" &&
214
+ value !== null &&
215
+ typeof Reflect.get(value, "name") === "string" &&
216
+ typeof Reflect.get(value, "execute") === "function" &&
217
+ typeof Reflect.get(value, "definition") === "object"
218
+ );
219
+ }
220
+
221
+ /**
222
+ * The tools of one run: those the model may call, those sent but not
223
+ * callable yet (`inactiveTools`), and those added during the current turn,
224
+ * which join the run once the turn is answered, so the calls of one turn all
225
+ * see the same tools.
226
+ */
227
+ export class RunTools {
228
+ /** Every tool sent to the model, in the order it is sent. */
229
+ readonly #sent: PolarisTool[] = [];
230
+ readonly #active = new Map<string, PolarisTool>();
231
+ readonly #inactive = new Map<string, PolarisTool>();
232
+ /** Added during the current turn: new tools, and inactive ones made callable. */
233
+ readonly #added = new Map<string, PolarisTool>();
234
+ readonly #activated = new Set<string>();
235
+
236
+ constructor(
237
+ active: readonly PolarisTool[],
238
+ inactive: readonly PolarisTool[] = [],
239
+ ) {
240
+ for (const [list, into] of [
241
+ [active, this.#active],
242
+ [inactive, this.#inactive],
243
+ ] as const) {
244
+ for (const tool of list) {
245
+ if (!isTool(tool)) {
246
+ throw new E_POLARIS_INVALID_REQUEST([
247
+ "a run's tools must be built by `defineTool()`",
248
+ ]);
249
+ }
250
+ if (this.#has(tool.name)) {
251
+ throw new E_POLARIS_INVALID_REQUEST([
252
+ `two tools are named '${tool.name}'`,
253
+ ]);
254
+ }
255
+ into.set(tool.name, tool);
256
+ this.#sent.push(tool);
257
+ }
258
+ }
259
+ if (this.#sent.length > MAX_RUN_TOOLS) {
260
+ throw new E_POLARIS_INVALID_REQUEST([
261
+ `a run holds at most ${MAX_RUN_TOOLS} tools`,
262
+ ]);
263
+ }
264
+ }
265
+
266
+ #has(name: string): boolean {
267
+ return this.#active.has(name) || this.#inactive.has(name);
268
+ }
269
+
270
+ /** What the next request sends. */
271
+ definitions(): ToolDefinition[] {
272
+ return this.#sent.map((tool) => tool.definition);
273
+ }
274
+
275
+ /** The tool a call names, `inactive` when it is not callable yet. */
276
+ find(name: string): PolarisTool | "inactive" | undefined {
277
+ return (
278
+ this.#active.get(name) ??
279
+ (this.#inactive.has(name) ? "inactive" : undefined)
280
+ );
281
+ }
282
+
283
+ /**
284
+ * Take tools a handler added: they join the run at {@link commit}, once
285
+ * the turn is answered. All of them or none.
286
+ */
287
+ stage(tools: readonly PolarisTool[]): void {
288
+ if (!Array.isArray(tools) || !tools.every(isTool)) {
289
+ throw new E_POLARIS_INVALID_REQUEST([
290
+ "`addTools` takes tools built by `defineTool()`",
291
+ ]);
292
+ }
293
+ const added = new Map<string, PolarisTool>();
294
+ const activated = new Set<string>();
295
+ for (const tool of tools) {
296
+ if (this.#inactive.get(tool.name) === tool) {
297
+ activated.add(tool.name);
298
+ continue;
299
+ }
300
+ const known =
301
+ this.#active.get(tool.name) ??
302
+ this.#inactive.get(tool.name) ??
303
+ this.#added.get(tool.name) ??
304
+ added.get(tool.name);
305
+ if (known === tool) continue;
306
+ if (known !== undefined) {
307
+ throw new ToolError(
308
+ `A tool named '${tool.name}' is already in this run; nothing was added.`,
309
+ );
310
+ }
311
+ added.set(tool.name, tool);
312
+ }
313
+ if (this.#sent.length + this.#added.size + added.size > MAX_RUN_TOOLS) {
314
+ throw new ToolError(
315
+ `This run cannot hold more than ${MAX_RUN_TOOLS} tools; nothing was added.`,
316
+ );
317
+ }
318
+ for (const [name, tool] of added) this.#added.set(name, tool);
319
+ for (const name of activated) this.#activated.add(name);
320
+ }
321
+
322
+ /** Let the tools added during the turn into the run. */
323
+ commit(): void {
324
+ for (const name of this.#activated) {
325
+ // Only an inactive tool is activated, and only here does it leave.
326
+ const tool = this.#inactive.get(name) as PolarisTool;
327
+ this.#inactive.delete(name);
328
+ this.#active.set(name, tool);
329
+ }
330
+ for (const [name, tool] of this.#added) {
331
+ this.#active.set(name, tool);
332
+ this.#sent.push(tool);
333
+ }
334
+ this.#activated.clear();
335
+ this.#added.clear();
336
+ }
337
+ }
338
+
339
+ /** Run one call, and answer it. Never rejects. */
340
+ export async function runToolCall(
341
+ call: ToolCallPart,
342
+ tools: RunTools,
343
+ signal: AbortSignal,
344
+ onToolError: OnToolError | undefined,
345
+ ): Promise<ToolResultPart> {
346
+ const tool = tools.find(call.name);
347
+ const outcome: ToolOutcome =
348
+ tool === "inactive"
349
+ ? {
350
+ ok: false,
351
+ content: `The tool '${call.name}' is not available yet.`,
352
+ error: new Error(`inactive tool '${call.name}'`),
353
+ }
354
+ : tool
355
+ ? await tool.execute(call, {
356
+ toolCallId: call.id,
357
+ signal,
358
+ addTools: (added) => tools.stage(added),
359
+ })
360
+ : {
361
+ ok: false,
362
+ content: `There is no tool named '${call.name}'.`,
363
+ error: new Error(`unknown tool '${call.name}'`),
364
+ };
365
+ if (!outcome.ok) onToolError?.(outcome.error, call);
366
+ return {
367
+ type: "tool_result",
368
+ toolCallId: call.id,
369
+ content: outcome.content,
370
+ ...(outcome.ok ? {} : { isError: true }),
371
+ };
372
+ }
373
+
374
+ /** Run every call of one turn, at once, and answer them in one message. */
375
+ export function runToolCalls(
376
+ calls: readonly ToolCallPart[],
377
+ tools: RunTools,
378
+ signal: AbortSignal,
379
+ onToolError: OnToolError | undefined,
380
+ ): Promise<ToolResultPart[]> {
381
+ return Promise.all(
382
+ calls.map((call) => runToolCall(call, tools, signal, onToolError)),
383
+ );
384
+ }
385
+
386
+ /** The error a run raises when it is still calling tools at its last step. */
387
+ export function tooManySteps(maxSteps: number): Error {
388
+ return new E_POLARIS_TOO_MANY_STEPS([maxSteps]);
389
+ }
390
+
391
+ /** Refuse a reply that calls more tools than `maxToolCalls`, before any runs. */
392
+ export function checkToolCalls(
393
+ calls: readonly unknown[],
394
+ maxToolCalls: number,
395
+ ): void {
396
+ if (calls.length > maxToolCalls) {
397
+ throw new E_POLARIS_TOO_MANY_TOOL_CALLS([calls.length, maxToolCalls]);
398
+ }
399
+ }
@@ -0,0 +1,107 @@
1
+ import {
2
+ E_POLARIS_PROVIDER_REJECTED,
3
+ E_POLARIS_RESPONSE_TOO_LARGE,
4
+ } from "./errors.js";
5
+ import type { Transport } from "./types.js";
6
+
7
+ /** Statuses whose response has no body by definition. */
8
+ const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
9
+
10
+ /**
11
+ * Wrap `base` so every request it sends carries `signal`, follows no redirect,
12
+ * and reads no response body longer than `maxBytes`.
13
+ *
14
+ * A redirect is refused, never followed: on another origin, `fetch` would
15
+ * drop `Authorization` but send every other header (`api-key`,
16
+ * `x-goog-api-key`...) and, on a 307 or 308, the whole prompt again. The
17
+ * provider is the configured origin and nothing else.
18
+ *
19
+ * The size is counted on the bytes as they arrive, not taken from
20
+ * `Content-Length` alone: a compressed or chunked body announces nothing true
21
+ * about what it will decode to. A declared length over the bound is refused
22
+ * before reading anything.
23
+ */
24
+ export function boundFetch(
25
+ base: Transport,
26
+ signal: AbortSignal,
27
+ maxBytes: number,
28
+ provider: string,
29
+ ): Transport {
30
+ return async (input, init) => {
31
+ const own = init?.signal;
32
+ const response = await base(input, {
33
+ ...init,
34
+ redirect: "manual",
35
+ signal: own ? AbortSignal.any([signal, own]) : signal,
36
+ });
37
+
38
+ // A browser answers a manual redirect with an opaque response, status 0.
39
+ if (
40
+ response.type === "opaqueredirect" ||
41
+ (response.status >= 300 && response.status < 400)
42
+ ) {
43
+ await response.body?.cancel().catch(() => undefined);
44
+ throw new E_POLARIS_PROVIDER_REJECTED([
45
+ provider,
46
+ `it answered with a redirect (HTTP ${response.status}), which polaris does not follow`,
47
+ ]);
48
+ }
49
+
50
+ const declared = Number(response.headers.get("content-length"));
51
+ if (Number.isFinite(declared) && declared > maxBytes) {
52
+ await response.body?.cancel().catch(() => undefined);
53
+ throw new E_POLARIS_RESPONSE_TOO_LARGE([maxBytes]);
54
+ }
55
+ if (response.body === null || NULL_BODY_STATUSES.has(response.status)) {
56
+ return response;
57
+ }
58
+
59
+ let seen = 0;
60
+ const limited = response.body.pipeThrough(
61
+ new TransformStream<Uint8Array, Uint8Array>({
62
+ transform(chunk, controller) {
63
+ seen += chunk.byteLength;
64
+ if (seen > maxBytes) {
65
+ controller.error(new E_POLARIS_RESPONSE_TOO_LARGE([maxBytes]));
66
+ return;
67
+ }
68
+ controller.enqueue(chunk);
69
+ },
70
+ }),
71
+ );
72
+ return new Response(limited, {
73
+ status: response.status,
74
+ statusText: response.statusText,
75
+ headers: response.headers,
76
+ });
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Settle with `promise`, or reject with `signal.reason` as soon as `signal`
82
+ * aborts — so a driver that ignores its signal still cannot outlive the
83
+ * deadline.
84
+ */
85
+ export function untilAborted<T>(
86
+ promise: Promise<T>,
87
+ signal: AbortSignal,
88
+ ): Promise<T> {
89
+ if (signal.aborted) {
90
+ promise.catch(() => undefined);
91
+ return Promise.reject(signal.reason);
92
+ }
93
+ return new Promise<T>((resolve, reject) => {
94
+ const onAbort = () => reject(signal.reason);
95
+ signal.addEventListener("abort", onAbort, { once: true });
96
+ promise.then(
97
+ (value) => {
98
+ signal.removeEventListener("abort", onAbort);
99
+ resolve(value);
100
+ },
101
+ (error: unknown) => {
102
+ signal.removeEventListener("abort", onAbort);
103
+ reject(error);
104
+ },
105
+ );
106
+ });
107
+ }