@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,171 @@
1
+ /**
2
+ * A skill: instructions for one kind of task, the files they refer to, and
3
+ * the tools they need. Only its name and description reach the model at
4
+ * first; the rest when the model loads it.
5
+ */
6
+
7
+ import { E_POLARIS_INVALID_REQUEST } from "../errors.js";
8
+ import { isTool, type PolarisTool } from "../tools.js";
9
+
10
+ /** A skill name: lower-case letters, digits and single hyphens, 64 at most. */
11
+ export const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
12
+ export const MAX_SKILL_NAME = 64;
13
+ export const MAX_SKILL_DESCRIPTION = 1024;
14
+ /** Bytes of a skill's instructions, and of each file the model reads. */
15
+ export const MAX_SKILL_BYTES = 256 * 1024;
16
+
17
+ /** The files of a skill the model may read, by their path in the skill. */
18
+ export interface SkillFiles {
19
+ /** Every file's path, `/`-separated. */
20
+ list(): Promise<readonly string[]>;
21
+ /**
22
+ * A file's text. Rejects with a {@link SkillFileError}, whose message the
23
+ * model reads, when the path leaves the skill, names no file, or the file
24
+ * is too large or not text.
25
+ */
26
+ read(path: string): Promise<string>;
27
+ }
28
+
29
+ /** A skill as `defineSkill()` or `readSkill()` builds it. */
30
+ export interface PolarisSkill {
31
+ readonly name: string;
32
+ readonly description: string;
33
+ readonly instructions: string;
34
+ /** Callable once the model loaded the skill. */
35
+ readonly tools: readonly PolarisTool[];
36
+ readonly files: SkillFiles;
37
+ }
38
+
39
+ export interface SkillSpec {
40
+ /** Lower-case letters, digits and hyphens: `swiss-payroll`. */
41
+ readonly name: string;
42
+ /** What the skill is for, and when to load it: all the model sees at first. */
43
+ readonly description: string;
44
+ /** What the model reads when it loads the skill. */
45
+ readonly instructions: string;
46
+ /** The skill's tools, including an MCP server's (`client.tools`). */
47
+ readonly tools?: readonly PolarisTool[];
48
+ /** Further text the instructions refer to, by path: `{ 'reference/rates.md': '...' }`. */
49
+ readonly files?: Readonly<Record<string, string>>;
50
+ }
51
+
52
+ /** Why a skill's name, description or instructions are refused, if they are. */
53
+ export function skillProblem(
54
+ name: unknown,
55
+ description: unknown,
56
+ instructions: unknown,
57
+ ): string | undefined {
58
+ if (
59
+ typeof name !== "string" ||
60
+ name.length > MAX_SKILL_NAME ||
61
+ !SKILL_NAME.test(name)
62
+ ) {
63
+ return `a skill name is 1 to ${MAX_SKILL_NAME} lower-case letters, digits and single hyphens; '${String(name).slice(0, 80)}' is not`;
64
+ }
65
+ if (typeof description !== "string" || description.trim() === "") {
66
+ return `the skill '${name}' has no description`;
67
+ }
68
+ if (description.length > MAX_SKILL_DESCRIPTION) {
69
+ return `the description of the skill '${name}' is longer than ${MAX_SKILL_DESCRIPTION} characters`;
70
+ }
71
+ if (typeof instructions !== "string" || instructions.trim() === "") {
72
+ return `the skill '${name}' has no instructions`;
73
+ }
74
+ if (Buffer.byteLength(instructions, "utf8") > MAX_SKILL_BYTES) {
75
+ return `the instructions of the skill '${name}' are larger than ${MAX_SKILL_BYTES} bytes`;
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ /** Why a skill's tools are refused, if they are. */
81
+ export function toolsProblem(
82
+ name: string,
83
+ tools: readonly unknown[],
84
+ ): string | undefined {
85
+ const seen = new Set<string>();
86
+ for (const tool of tools) {
87
+ if (!isTool(tool))
88
+ return `the tools of the skill '${name}' must be built by defineTool()`;
89
+ if (seen.has(tool.name))
90
+ return `the skill '${name}' has two tools named '${tool.name}'`;
91
+ seen.add(tool.name);
92
+ }
93
+ return undefined;
94
+ }
95
+
96
+ /**
97
+ * Declare a skill in code:
98
+ *
99
+ * const payroll = defineSkill({
100
+ * name: 'swiss-payroll',
101
+ * description: 'Compute a Swiss payslip. Use it for any salary question.',
102
+ * instructions: '1. Ask for the canton...',
103
+ * tools: [socialRates, withholdingTax],
104
+ * files: { 'reference/avs.md': avsTable },
105
+ * })
106
+ */
107
+ export function defineSkill(spec: SkillSpec): PolarisSkill {
108
+ const tools = spec.tools ?? [];
109
+ const problem =
110
+ skillProblem(spec.name, spec.description, spec.instructions) ??
111
+ toolsProblem(spec.name, tools) ??
112
+ filesProblem(spec.name, spec.files ?? {});
113
+ if (problem !== undefined) throw new E_POLARIS_INVALID_REQUEST([problem]);
114
+ const files = new Map(Object.entries(spec.files ?? {}));
115
+ return {
116
+ name: spec.name,
117
+ description: spec.description.trim(),
118
+ instructions: spec.instructions.trim(),
119
+ tools: [...tools],
120
+ files: {
121
+ list: async () => [...files.keys()].sort(),
122
+ read: async (path) => {
123
+ const text = files.get(path);
124
+ if (text === undefined) {
125
+ throw new SkillFileError(
126
+ `The skill '${spec.name}' has no file '${path.slice(0, 200)}'.`,
127
+ );
128
+ }
129
+ return text;
130
+ },
131
+ },
132
+ };
133
+ }
134
+
135
+ function filesProblem(
136
+ name: string,
137
+ files: Readonly<Record<string, unknown>>,
138
+ ): string | undefined {
139
+ for (const [path, text] of Object.entries(files)) {
140
+ if (typeof text !== "string")
141
+ return `the file '${path}' of the skill '${name}' is not text`;
142
+ if (Buffer.byteLength(text, "utf8") > MAX_SKILL_BYTES) {
143
+ return `the file '${path}' of the skill '${name}' is larger than ${MAX_SKILL_BYTES} bytes`;
144
+ }
145
+ }
146
+ return undefined;
147
+ }
148
+
149
+ /** A file the model asked for cannot be read: the message is for the model. */
150
+ export class SkillFileError extends Error {
151
+ constructor(message: string) {
152
+ super(message);
153
+ this.name = "SkillFileError";
154
+ }
155
+ }
156
+
157
+ /** Whether `value` is a skill built by {@link defineSkill} or `readSkill()`. */
158
+ export function isSkill(value: unknown): value is PolarisSkill {
159
+ if (typeof value !== "object" || value === null) return false;
160
+ const files: unknown = Reflect.get(value, "files");
161
+ return (
162
+ typeof Reflect.get(value, "name") === "string" &&
163
+ typeof Reflect.get(value, "description") === "string" &&
164
+ typeof Reflect.get(value, "instructions") === "string" &&
165
+ Array.isArray(Reflect.get(value, "tools")) &&
166
+ typeof files === "object" &&
167
+ files !== null &&
168
+ typeof Reflect.get(files, "read") === "function" &&
169
+ typeof Reflect.get(files, "list") === "function"
170
+ );
171
+ }
package/src/sse.ts ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * A reply streamed to the browser as Server-Sent Events, over the response of
3
+ * the request that asked for it (ream's `ctx.response.sse()`).
4
+ *
5
+ * That stream, not a relay channel, is the transport here: it belongs to the
6
+ * one client waiting for this reply, and its close is a sure sign the client
7
+ * left, on every instance, which is what lets the provider request be
8
+ * cancelled. A relay channel reaches whoever subscribed, wherever they are,
9
+ * but cannot tell polaris that nobody listens any more.
10
+ */
11
+
12
+ import { codeOf } from "./log.js";
13
+ import type { RunEvent, RunResult } from "./PolarisClient.js";
14
+ import type {
15
+ ChatResponse,
16
+ StreamEvent,
17
+ ToolCallPart,
18
+ Usage,
19
+ } from "./types.js";
20
+
21
+ /**
22
+ * What polaris needs of an SSE stream: ream's `SseStream` fits as it is, and
23
+ * so does relay's.
24
+ */
25
+ export interface SseSink {
26
+ /** Send one named event. Answers `false` once the stream is closed. */
27
+ send(event: string, data: unknown): Promise<boolean> | boolean;
28
+ /** Called once when the stream closes, whoever closed it. */
29
+ onClose(callback: () => void): void;
30
+ /** Close the stream from the server. */
31
+ end(): Promise<void> | void;
32
+ }
33
+
34
+ /** How a streamed reply ended. */
35
+ export type StreamToResult =
36
+ | { readonly status: "done"; readonly response: ChatResponse }
37
+ | SseFailure;
38
+
39
+ /** How a streamed tool run ended. */
40
+ export type StreamRunToResult =
41
+ | { readonly status: "done"; readonly result: RunResult }
42
+ | SseFailure;
43
+
44
+ /** The ways a stream to the browser ends without its last event. */
45
+ export type SseFailure =
46
+ /** The client went away; the provider request was cancelled. */
47
+ | { readonly status: "client_left" }
48
+ /** The call failed; the client was sent an `error` event with its code. */
49
+ | { readonly status: "failed"; readonly error: unknown };
50
+
51
+ /** The `done` event's data: what a page needs, none of the provider's raw blocks. */
52
+ export interface DoneEventData {
53
+ readonly id: string;
54
+ readonly provider: string;
55
+ readonly model: string;
56
+ readonly text: string;
57
+ readonly stopReason: ChatResponse["stopReason"];
58
+ readonly usage: Usage;
59
+ }
60
+
61
+ /** The `done` event's data at the end of a run: its last reply, with the run's steps and tokens. */
62
+ export interface RunDoneEventData extends DoneEventData {
63
+ readonly steps: number;
64
+ }
65
+
66
+ /**
67
+ * The `tool_result` event's data. The result itself stays on the server: it
68
+ * is the application's data, read by the model, not meant for the page.
69
+ */
70
+ export interface ToolResultEventData {
71
+ readonly id: string;
72
+ readonly name: string;
73
+ readonly isError: boolean;
74
+ }
75
+
76
+ /** Why polaris cancelled the provider request: the client closed the stream. */
77
+ export class ClientLeft extends Error {
78
+ constructor() {
79
+ super("the client closed the stream");
80
+ this.name = "ClientLeft";
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Forward `events` to `sink` as events named by their type after `prefix`
86
+ * (`text`, `tool_call`, `done`…, and `error` on a failure), and end the stream
87
+ * after the last one. `leave` is aborted when the client closes the stream.
88
+ * `encode` gives an event's data, and the result when it is the last one.
89
+ * Never rejects: every outcome is in the result.
90
+ */
91
+ export async function pipeToSse<E extends { readonly type: string }, R>(
92
+ events: AsyncIterable<E>,
93
+ sink: SseSink,
94
+ leave: AbortController,
95
+ prefix: string,
96
+ encode: (event: E) => { readonly data: unknown; readonly last?: R },
97
+ ): Promise<R | SseFailure> {
98
+ try {
99
+ for await (const event of events) {
100
+ if (leave.signal.aborted) break;
101
+ const { data, last } = encode(event);
102
+ const sent = await sink.send(`${prefix}${event.type}`, data);
103
+ if (!sent) {
104
+ leave.abort(new ClientLeft());
105
+ break;
106
+ }
107
+ if (last !== undefined) {
108
+ await settle(() => sink.end());
109
+ return last;
110
+ }
111
+ }
112
+ // Leaving the loop early cancels the provider request.
113
+ return { status: "client_left" };
114
+ } catch (error) {
115
+ if (leave.signal.aborted) return { status: "client_left" };
116
+ // Only the code goes to the page: a message can carry the provider's
117
+ // details, or the application's.
118
+ await settle(() => sink.send(`${prefix}error`, { code: codeOf(error) }));
119
+ await settle(() => sink.end());
120
+ return { status: "failed", error };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Run `step` and swallow its failure: the stream is already closing, and the
126
+ * caller of `streamTo()` usually does not await it (a ream route must return
127
+ * before its stream starts), so a rejection would go unhandled.
128
+ */
129
+ async function settle(step: () => unknown): Promise<void> {
130
+ try {
131
+ await step();
132
+ } catch {
133
+ // The stream is gone; there is nobody left to tell.
134
+ }
135
+ }
136
+
137
+ /** A streamed reply's event, as `streamTo()` sends it. */
138
+ export function encodeStreamEvent(event: StreamEvent): {
139
+ readonly data: unknown;
140
+ readonly last?: StreamToResult;
141
+ } {
142
+ switch (event.type) {
143
+ case "text":
144
+ case "reasoning":
145
+ return { data: { text: event.text } };
146
+ case "tool_call":
147
+ return { data: toolCallData(event.call) };
148
+ case "done":
149
+ return {
150
+ data: doneData(event.response),
151
+ last: { status: "done", response: event.response },
152
+ };
153
+ }
154
+ }
155
+
156
+ /** A streamed run's event, as `streamRunTo()` sends it. */
157
+ export function encodeRunEvent(event: RunEvent): {
158
+ readonly data: unknown;
159
+ readonly last?: StreamRunToResult;
160
+ } {
161
+ switch (event.type) {
162
+ case "text":
163
+ case "reasoning":
164
+ return { data: { text: event.text } };
165
+ case "tool_call":
166
+ return { data: toolCallData(event.call) };
167
+ case "tool_result": {
168
+ const data: ToolResultEventData = {
169
+ id: event.call.id,
170
+ name: event.call.name,
171
+ isError: event.result.isError === true,
172
+ };
173
+ return { data };
174
+ }
175
+ case "done": {
176
+ const { result } = event;
177
+ const data: RunDoneEventData = {
178
+ ...doneData(result.response),
179
+ usage: result.usage,
180
+ steps: result.steps,
181
+ };
182
+ return { data, last: { status: "done", result } };
183
+ }
184
+ }
185
+ }
186
+
187
+ function toolCallData(call: ToolCallPart): unknown {
188
+ return { id: call.id, name: call.name, input: call.input };
189
+ }
190
+
191
+ function doneData(response: ChatResponse): DoneEventData {
192
+ const { id, provider, model, text, stopReason, usage } = response;
193
+ return { id, provider, model, text, stopReason, usage };
194
+ }
@@ -0,0 +1,322 @@
1
+ /**
2
+ * A provider that answers from a script, for tests: no network, no key.
3
+ *
4
+ * const fake = polaris.fake()
5
+ * fake.reply('Bonjour')
6
+ * await myAssistant.answer('hi')
7
+ * fake.assertSent((request) => request.system?.includes('newcomer'))
8
+ * polaris.restore()
9
+ *
10
+ * Every provider of the manager answers from the fake until `restore()`. It
11
+ * records each call, and reports usage, so cost and budget code runs as it
12
+ * would against a provider.
13
+ */
14
+
15
+ import {
16
+ E_POLARIS_ASSERTION_FAILED,
17
+ E_POLARIS_FAKE_NO_REPLY,
18
+ } from "../errors.js";
19
+ import { createResponse } from "../response.js";
20
+ import type {
21
+ AssistantPart,
22
+ ChatRequest,
23
+ ChatResponse,
24
+ DriverCall,
25
+ DriverFeatures,
26
+ EmbedRequest,
27
+ EmbedResponse,
28
+ PolarisDriver,
29
+ StopReason,
30
+ StreamEvent,
31
+ ToolCallPart,
32
+ Usage,
33
+ } from "../types.js";
34
+
35
+ /** One scripted reply. */
36
+ export interface FakeReply {
37
+ readonly text?: string;
38
+ readonly reasoning?: string;
39
+ readonly toolCalls?: readonly {
40
+ readonly name: string;
41
+ readonly input: unknown;
42
+ readonly id?: string;
43
+ }[];
44
+ /** Default: `tool_use` when the reply calls tools, `end` otherwise. */
45
+ readonly stopReason?: StopReason;
46
+ readonly usage?: Partial<Usage>;
47
+ /** Default: the request's model, or the fake's. */
48
+ readonly model?: string;
49
+ /** How a stream sends the text. Default: the whole text in one event. */
50
+ readonly chunks?: readonly string[];
51
+ }
52
+
53
+ export interface FakeOptions {
54
+ /** What the fake provider supports. Default: everything. */
55
+ readonly features?: Partial<DriverFeatures>;
56
+ /** The model it answers with when a request names none. Default `fake-model`. */
57
+ readonly model?: string;
58
+ /** Its embedding model. Default `fake-embedding`. */
59
+ readonly embeddingModel?: string;
60
+ /** The length of the vectors it returns. Default 8. */
61
+ readonly dimensions?: number;
62
+ /** Its output limit for a request that sets none, for budget estimates. Default 1 000. */
63
+ readonly maxTokens?: number;
64
+ }
65
+
66
+ /** A call the fake received. */
67
+ export interface FakeCall {
68
+ readonly operation: "chat" | "stream" | "embed";
69
+ /** The provider's name in the config. */
70
+ readonly provider: string;
71
+ readonly request: ChatRequest | EmbedRequest;
72
+ /** The per-call key, if one was given. */
73
+ readonly apiKey: string | undefined;
74
+ }
75
+
76
+ type Step = (request: ChatRequest) => ChatResponse | Promise<never>;
77
+
78
+ export class FakeProvider {
79
+ readonly #options: FakeOptions;
80
+ readonly #steps: Step[] = [];
81
+ readonly #calls: FakeCall[] = [];
82
+ #embedding: (input: string) => readonly number[];
83
+
84
+ constructor(options: FakeOptions = {}) {
85
+ this.#options = options;
86
+ const dimensions = options.dimensions ?? 8;
87
+ this.#embedding = (input) => deterministicVector(input, dimensions);
88
+ }
89
+
90
+ /** Answer the next request with `reply`: a text, or a scripted reply. */
91
+ reply(reply: string | FakeReply): this {
92
+ const scripted: FakeReply =
93
+ typeof reply === "string" ? { text: reply } : reply;
94
+ this.#steps.push((request) => this.#response(request, scripted));
95
+ return this;
96
+ }
97
+
98
+ /**
99
+ * Answer the next request with `value` as structured output: as JSON text
100
+ * when the request asks for structured output, as a call to its tool when
101
+ * it asks through a tool.
102
+ */
103
+ replyJson(
104
+ value: unknown,
105
+ extra: Omit<FakeReply, "text" | "toolCalls"> = {},
106
+ ): this {
107
+ this.#steps.push((request) => {
108
+ const tool =
109
+ request.output === undefined ? request.tools?.[0] : undefined;
110
+ return this.#response(
111
+ request,
112
+ tool
113
+ ? { ...extra, toolCalls: [{ name: tool.name, input: value }] }
114
+ : { ...extra, text: JSON.stringify(value) },
115
+ );
116
+ });
117
+ return this;
118
+ }
119
+
120
+ /** Answer the next request with a call to the tool `name`. */
121
+ callTool(name: string, input: unknown, id?: string): this {
122
+ return this.reply({
123
+ toolCalls: [{ name, input, ...(id !== undefined ? { id } : {}) }],
124
+ });
125
+ }
126
+
127
+ /** Make the next request fail with `error`. */
128
+ fail(error: unknown): this {
129
+ this.#steps.push(() => Promise.reject(error));
130
+ return this;
131
+ }
132
+
133
+ /** Compute each input's vector with `embed` instead of the fake's own. */
134
+ embedWith(embed: (input: string) => readonly number[]): this {
135
+ this.#embedding = embed;
136
+ return this;
137
+ }
138
+
139
+ /** Every call received, in order. */
140
+ get calls(): readonly FakeCall[] {
141
+ return this.#calls;
142
+ }
143
+
144
+ /** The chat and stream requests received, in order. */
145
+ get requests(): readonly ChatRequest[] {
146
+ return this.#calls.flatMap((call) =>
147
+ call.operation === "embed" || !isChat(call.request) ? [] : [call.request],
148
+ );
149
+ }
150
+
151
+ /** Replies scripted and not used yet. */
152
+ get pending(): number {
153
+ return this.#steps.length;
154
+ }
155
+
156
+ /** Fail unless a chat or stream request matching `matches` was received. */
157
+ assertSent(matches: (request: ChatRequest) => boolean = () => true): void {
158
+ if (!this.requests.some(matches)) {
159
+ throw new E_POLARIS_ASSERTION_FAILED([
160
+ "assertSent",
161
+ `no request out of ${this.requests.length} matched`,
162
+ ]);
163
+ }
164
+ }
165
+
166
+ /** Fail if a chat or stream request matching `matches` was received. */
167
+ assertNotSent(matches: (request: ChatRequest) => boolean = () => true): void {
168
+ const count = this.requests.filter(matches).length;
169
+ if (count > 0) {
170
+ throw new E_POLARIS_ASSERTION_FAILED([
171
+ "assertNotSent",
172
+ `${count} requests matched`,
173
+ ]);
174
+ }
175
+ }
176
+
177
+ /** Fail unless exactly `count` chat and stream requests were received. */
178
+ assertSentCount(count: number): void {
179
+ if (this.requests.length !== count) {
180
+ throw new E_POLARIS_ASSERTION_FAILED([
181
+ "assertSentCount",
182
+ `expected ${count} requests, received ${this.requests.length}`,
183
+ ]);
184
+ }
185
+ }
186
+
187
+ /** The driver this fake stands in with, for the provider named `name`. */
188
+ driver(name: string): PolarisDriver {
189
+ const options = this.#options;
190
+ const record = (
191
+ operation: FakeCall["operation"],
192
+ request: ChatRequest | EmbedRequest,
193
+ call: DriverCall,
194
+ ) => this.#record(operation, name, request, call);
195
+ const next = (request: ChatRequest) => this.#next(request);
196
+ const chunksOf = (response: ChatResponse) => this.#chunks.get(response);
197
+ const embed = (request: EmbedRequest) => this.#embed(request);
198
+ return {
199
+ provider: "fake",
200
+ features: {
201
+ tools: true,
202
+ structuredOutput: true,
203
+ images: true,
204
+ serverTools: true,
205
+ ...options.features,
206
+ },
207
+ defaults: {
208
+ model: options.model ?? "fake-model",
209
+ embeddingModel: options.embeddingModel ?? "fake-embedding",
210
+ maxTokens: options.maxTokens ?? 1_000,
211
+ streamMaxTokens: options.maxTokens ?? 1_000,
212
+ },
213
+ async chat(request, call) {
214
+ record("chat", request, call);
215
+ return next(request);
216
+ },
217
+ async *stream(request, call) {
218
+ record("stream", request, call);
219
+ const response = await next(request);
220
+ yield* streamOf(response, chunksOf(response));
221
+ },
222
+ async embed(request, call) {
223
+ record("embed", request, call);
224
+ return embed(request);
225
+ },
226
+ };
227
+ }
228
+
229
+ /** The chunks a reply streams its text in, when it was scripted with some. */
230
+ readonly #chunks = new WeakMap<ChatResponse, readonly string[]>();
231
+
232
+ #record(
233
+ operation: FakeCall["operation"],
234
+ provider: string,
235
+ request: ChatRequest | EmbedRequest,
236
+ call: DriverCall,
237
+ ): void {
238
+ this.#calls.push({ operation, provider, request, apiKey: call.apiKey });
239
+ }
240
+
241
+ async #next(request: ChatRequest): Promise<ChatResponse> {
242
+ const step = this.#steps.shift();
243
+ if (step === undefined) throw new E_POLARIS_FAKE_NO_REPLY();
244
+ return step(request);
245
+ }
246
+
247
+ #response(request: ChatRequest, reply: FakeReply): ChatResponse {
248
+ const calls: ToolCallPart[] = (reply.toolCalls ?? []).map(
249
+ (call, index) => ({
250
+ type: "tool_call",
251
+ id: call.id ?? `call_${this.#calls.length}_${index}`,
252
+ name: call.name,
253
+ input: call.input,
254
+ }),
255
+ );
256
+ const content: AssistantPart[] = [];
257
+ if (reply.reasoning !== undefined)
258
+ content.push({ type: "reasoning", text: reply.reasoning });
259
+ if (reply.text !== undefined && reply.text !== "")
260
+ content.push({ type: "text", text: reply.text });
261
+ content.push(...calls);
262
+ const response = createResponse({
263
+ id: `fake_${this.#calls.length}`,
264
+ provider: "fake",
265
+ model:
266
+ reply.model ?? request.model ?? this.#options.model ?? "fake-model",
267
+ content,
268
+ stopReason: reply.stopReason ?? (calls.length > 0 ? "tool_use" : "end"),
269
+ usage: { inputTokens: 10, outputTokens: 10, ...reply.usage },
270
+ });
271
+ if (reply.chunks !== undefined) this.#chunks.set(response, reply.chunks);
272
+ return response;
273
+ }
274
+
275
+ #embed(request: EmbedRequest): EmbedResponse {
276
+ const vectors = request.inputs.map((input) =>
277
+ Float32Array.from(this.#embedding(input)),
278
+ );
279
+ return {
280
+ provider: "fake",
281
+ model: request.model ?? this.#options.embeddingModel ?? "fake-embedding",
282
+ dimensions: vectors[0]?.length ?? 0,
283
+ vectors,
284
+ usage: {
285
+ inputTokens: request.inputs.reduce(
286
+ (total, input) => total + input.length,
287
+ 0,
288
+ ),
289
+ },
290
+ };
291
+ }
292
+ }
293
+
294
+ /** The events a stream of `response` yields: reasoning, the text in chunks, the tool calls, done. */
295
+ function* streamOf(
296
+ response: ChatResponse,
297
+ chunks: readonly string[] | undefined,
298
+ ): Generator<StreamEvent> {
299
+ for (const part of response.message.content) {
300
+ if (part.type === "reasoning") yield { type: "reasoning", text: part.text };
301
+ }
302
+ for (const text of chunks ?? (response.text === "" ? [] : [response.text])) {
303
+ yield { type: "text", text };
304
+ }
305
+ for (const call of response.toolCalls) yield { type: "tool_call", call };
306
+ yield { type: "done", response };
307
+ }
308
+
309
+ /** A vector that depends only on the text: the same input always lands at the same place. */
310
+ function deterministicVector(input: string, dimensions: number): number[] {
311
+ const vector = new Array<number>(dimensions).fill(0);
312
+ for (let index = 0; index < input.length; index++) {
313
+ const slot = index % dimensions;
314
+ vector[slot] = ((vector[slot] ?? 0) + input.charCodeAt(index)) % 1_000;
315
+ }
316
+ const norm = Math.hypot(...vector) || 1;
317
+ return vector.map((value) => value / norm);
318
+ }
319
+
320
+ function isChat(request: ChatRequest | EmbedRequest): request is ChatRequest {
321
+ return "messages" in request;
322
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@c9up/polaris/testing`: the provider that answers from a script.
3
+ * `polaris.fake()` hands one out; build one yourself to declare it as a
4
+ * provider: `providers: { main: () => fake.driver('main') }`.
5
+ */
6
+
7
+ export {
8
+ type FakeCall,
9
+ type FakeOptions,
10
+ FakeProvider,
11
+ type FakeReply,
12
+ } from "./FakeProvider.js";