@c9up/polaris 0.1.0 → 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 (217) hide show
  1. package/README.md +614 -10
  2. package/dist/Polaris.d.ts +6 -2
  3. package/dist/Polaris.d.ts.map +1 -1
  4. package/dist/Polaris.js +14 -0
  5. package/dist/Polaris.js.map +1 -1
  6. package/dist/PolarisClient.d.ts +51 -3
  7. package/dist/PolarisClient.d.ts.map +1 -1
  8. package/dist/PolarisClient.js +213 -45
  9. package/dist/PolarisClient.js.map +1 -1
  10. package/dist/PolarisProvider.d.ts +7 -2
  11. package/dist/PolarisProvider.d.ts.map +1 -1
  12. package/dist/PolarisProvider.js +34 -2
  13. package/dist/PolarisProvider.js.map +1 -1
  14. package/dist/augmentations.d.ts +4 -1
  15. package/dist/augmentations.d.ts.map +1 -1
  16. package/dist/augmentations.js +1 -1
  17. package/dist/budget.d.ts +39 -6
  18. package/dist/budget.d.ts.map +1 -1
  19. package/dist/budget.js +79 -12
  20. package/dist/budget.js.map +1 -1
  21. package/dist/catalog/catalog.d.ts +37 -0
  22. package/dist/catalog/catalog.d.ts.map +1 -0
  23. package/dist/catalog/catalog.js +145 -0
  24. package/dist/catalog/catalog.js.map +1 -0
  25. package/dist/catalog/discover.d.ts +64 -0
  26. package/dist/catalog/discover.d.ts.map +1 -0
  27. package/dist/catalog/discover.js +148 -0
  28. package/dist/catalog/discover.js.map +1 -0
  29. package/dist/catalog/index.d.ts +8 -0
  30. package/dist/catalog/index.d.ts.map +1 -0
  31. package/dist/catalog/index.js +8 -0
  32. package/dist/catalog/index.js.map +1 -0
  33. package/dist/commands/index.d.ts +82 -0
  34. package/dist/commands/index.d.ts.map +1 -0
  35. package/dist/commands/index.js +278 -0
  36. package/dist/commands/index.js.map +1 -0
  37. package/dist/cost.d.ts +3 -1
  38. package/dist/cost.d.ts.map +1 -1
  39. package/dist/cost.js +8 -3
  40. package/dist/cost.js.map +1 -1
  41. package/dist/drivers/anthropic.d.ts +6 -1
  42. package/dist/drivers/anthropic.d.ts.map +1 -1
  43. package/dist/drivers/anthropic.js +166 -21
  44. package/dist/drivers/anthropic.js.map +1 -1
  45. package/dist/drivers/openai-compatible.d.ts +1 -1
  46. package/dist/drivers/openai-compatible.d.ts.map +1 -1
  47. package/dist/drivers/openai-compatible.js +106 -70
  48. package/dist/drivers/openai-compatible.js.map +1 -1
  49. package/dist/errors.d.ts +24 -0
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js +24 -0
  52. package/dist/errors.js.map +1 -1
  53. package/dist/index.d.ts +6 -4
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +3 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/json-schema.d.ts +33 -0
  58. package/dist/json-schema.d.ts.map +1 -0
  59. package/dist/json-schema.js +508 -0
  60. package/dist/json-schema.js.map +1 -0
  61. package/dist/log.d.ts.map +1 -1
  62. package/dist/log.js +3 -1
  63. package/dist/log.js.map +1 -1
  64. package/dist/mcp/client.d.ts +81 -0
  65. package/dist/mcp/client.d.ts.map +1 -0
  66. package/dist/mcp/client.js +401 -0
  67. package/dist/mcp/client.js.map +1 -0
  68. package/dist/mcp/endpoint.d.ts +54 -0
  69. package/dist/mcp/endpoint.d.ts.map +1 -0
  70. package/dist/mcp/endpoint.js +158 -0
  71. package/dist/mcp/endpoint.js.map +1 -0
  72. package/dist/mcp/host.d.ts +42 -0
  73. package/dist/mcp/host.d.ts.map +1 -0
  74. package/dist/mcp/host.js +111 -0
  75. package/dist/mcp/host.js.map +1 -0
  76. package/dist/mcp/http.d.ts +32 -0
  77. package/dist/mcp/http.d.ts.map +1 -0
  78. package/dist/mcp/http.js +190 -0
  79. package/dist/mcp/http.js.map +1 -0
  80. package/dist/mcp/index.d.ts +23 -0
  81. package/dist/mcp/index.d.ts.map +1 -0
  82. package/dist/mcp/index.js +21 -0
  83. package/dist/mcp/index.js.map +1 -0
  84. package/dist/mcp/manifest.d.ts +36 -0
  85. package/dist/mcp/manifest.d.ts.map +1 -0
  86. package/dist/mcp/manifest.js +40 -0
  87. package/dist/mcp/manifest.js.map +1 -0
  88. package/dist/mcp/rpc.d.ts +39 -0
  89. package/dist/mcp/rpc.d.ts.map +1 -0
  90. package/dist/mcp/rpc.js +149 -0
  91. package/dist/mcp/rpc.js.map +1 -0
  92. package/dist/mcp/stdio.d.ts +24 -0
  93. package/dist/mcp/stdio.d.ts.map +1 -0
  94. package/dist/mcp/stdio.js +157 -0
  95. package/dist/mcp/stdio.js.map +1 -0
  96. package/dist/mcp/worker-main.d.ts +6 -0
  97. package/dist/mcp/worker-main.d.ts.map +1 -0
  98. package/dist/mcp/worker-main.js +17 -0
  99. package/dist/mcp/worker-main.js.map +1 -0
  100. package/dist/mcp/worker.d.ts +54 -0
  101. package/dist/mcp/worker.d.ts.map +1 -0
  102. package/dist/mcp/worker.js +166 -0
  103. package/dist/mcp/worker.js.map +1 -0
  104. package/dist/meter.d.ts +6 -0
  105. package/dist/meter.d.ts.map +1 -1
  106. package/dist/meter.js +6 -3
  107. package/dist/meter.js.map +1 -1
  108. package/dist/redact.d.ts +4 -3
  109. package/dist/redact.d.ts.map +1 -1
  110. package/dist/redact.js +5 -4
  111. package/dist/redact.js.map +1 -1
  112. package/dist/redis-budget.d.ts +45 -0
  113. package/dist/redis-budget.d.ts.map +1 -0
  114. package/dist/redis-budget.js +56 -0
  115. package/dist/redis-budget.js.map +1 -0
  116. package/dist/response.d.ts +21 -3
  117. package/dist/response.d.ts.map +1 -1
  118. package/dist/response.js +71 -7
  119. package/dist/response.js.map +1 -1
  120. package/dist/server-sent.d.ts +9 -0
  121. package/dist/server-sent.d.ts.map +1 -0
  122. package/dist/server-sent.js +74 -0
  123. package/dist/server-sent.js.map +1 -0
  124. package/dist/server-tools.d.ts +12 -0
  125. package/dist/server-tools.d.ts.map +1 -0
  126. package/dist/server-tools.js +71 -0
  127. package/dist/server-tools.js.map +1 -0
  128. package/dist/services/catalog.d.ts +19 -0
  129. package/dist/services/catalog.d.ts.map +1 -0
  130. package/dist/services/catalog.js +37 -0
  131. package/dist/services/catalog.js.map +1 -0
  132. package/dist/skills/folder.d.ts +32 -0
  133. package/dist/skills/folder.d.ts.map +1 -0
  134. package/dist/skills/folder.js +170 -0
  135. package/dist/skills/folder.js.map +1 -0
  136. package/dist/skills/frontmatter.d.ts +15 -0
  137. package/dist/skills/frontmatter.d.ts.map +1 -0
  138. package/dist/skills/frontmatter.js +92 -0
  139. package/dist/skills/frontmatter.js.map +1 -0
  140. package/dist/skills/index.d.ts +18 -0
  141. package/dist/skills/index.d.ts.map +1 -0
  142. package/dist/skills/index.js +18 -0
  143. package/dist/skills/index.js.map +1 -0
  144. package/dist/skills/kit.d.ts +39 -0
  145. package/dist/skills/kit.d.ts.map +1 -0
  146. package/dist/skills/kit.js +124 -0
  147. package/dist/skills/kit.js.map +1 -0
  148. package/dist/skills/skill.d.ts +67 -0
  149. package/dist/skills/skill.d.ts.map +1 -0
  150. package/dist/skills/skill.js +114 -0
  151. package/dist/skills/skill.js.map +1 -0
  152. package/dist/sse.d.ts +43 -6
  153. package/dist/sse.d.ts.map +1 -1
  154. package/dist/sse.js +44 -18
  155. package/dist/sse.js.map +1 -1
  156. package/dist/testing/FakeProvider.d.ts.map +1 -1
  157. package/dist/testing/FakeProvider.js +1 -0
  158. package/dist/testing/FakeProvider.js.map +1 -1
  159. package/dist/tool-modules.d.ts +17 -0
  160. package/dist/tool-modules.d.ts.map +1 -0
  161. package/dist/tool-modules.js +43 -0
  162. package/dist/tool-modules.js.map +1 -0
  163. package/dist/tools.d.ts +69 -5
  164. package/dist/tools.d.ts.map +1 -1
  165. package/dist/tools.js +174 -31
  166. package/dist/tools.js.map +1 -1
  167. package/dist/transport.d.ts +8 -3
  168. package/dist/transport.d.ts.map +1 -1
  169. package/dist/transport.js +19 -4
  170. package/dist/transport.js.map +1 -1
  171. package/dist/types.d.ts +106 -2
  172. package/dist/types.d.ts.map +1 -1
  173. package/package.json +22 -1
  174. package/src/Polaris.ts +25 -1
  175. package/src/PolarisClient.ts +288 -51
  176. package/src/PolarisProvider.ts +40 -2
  177. package/src/augmentations.ts +4 -1
  178. package/src/budget.ts +115 -15
  179. package/src/catalog/catalog.ts +180 -0
  180. package/src/catalog/discover.ts +234 -0
  181. package/src/catalog/index.ts +19 -0
  182. package/src/commands/index.ts +412 -0
  183. package/src/cost.ts +9 -3
  184. package/src/drivers/anthropic.ts +203 -20
  185. package/src/drivers/openai-compatible.ts +143 -76
  186. package/src/errors.ts +41 -0
  187. package/src/index.ts +16 -0
  188. package/src/json-schema.ts +597 -0
  189. package/src/log.ts +3 -1
  190. package/src/mcp/client.ts +532 -0
  191. package/src/mcp/endpoint.ts +229 -0
  192. package/src/mcp/host.ts +140 -0
  193. package/src/mcp/http.ts +276 -0
  194. package/src/mcp/index.ts +51 -0
  195. package/src/mcp/manifest.ts +73 -0
  196. package/src/mcp/rpc.ts +197 -0
  197. package/src/mcp/stdio.ts +190 -0
  198. package/src/mcp/worker-main.ts +18 -0
  199. package/src/mcp/worker.ts +212 -0
  200. package/src/meter.ts +13 -2
  201. package/src/redact.ts +6 -3
  202. package/src/redis-budget.ts +85 -0
  203. package/src/response.ts +86 -8
  204. package/src/server-sent.ts +70 -0
  205. package/src/server-tools.ts +77 -0
  206. package/src/services/catalog.ts +43 -0
  207. package/src/skills/folder.ts +231 -0
  208. package/src/skills/frontmatter.ts +92 -0
  209. package/src/skills/index.ts +38 -0
  210. package/src/skills/kit.ts +163 -0
  211. package/src/skills/skill.ts +171 -0
  212. package/src/sse.ts +88 -22
  213. package/src/testing/FakeProvider.ts +1 -0
  214. package/src/tool-modules.ts +49 -0
  215. package/src/tools.ts +260 -27
  216. package/src/transport.ts +25 -3
  217. package/src/types.ts +108 -2
@@ -0,0 +1,412 @@
1
+ /**
2
+ * `@c9up/polaris/commands`: the console commands polaris ships, registered
3
+ * once in the application's `reamrc.ts`:
4
+ *
5
+ * commands: [() => import('@c9up/polaris/commands')]
6
+ *
7
+ * ream polaris:index write polaris.json
8
+ * ream make:tool canton_rate app/tools/canton_rate.ts
9
+ * ream make:skill payroll --module hr where the skill pattern says
10
+ *
11
+ * The shape ream's kernel loads (`getMetaData` / `getCommand`), declared here
12
+ * so polaris does not import `@c9up/ream`. The commands do not boot the
13
+ * application: they read `catalog` from `config/polaris.ts` off disk.
14
+ */
15
+
16
+ import { existsSync } from "node:fs";
17
+ import { mkdir, writeFile } from "node:fs/promises";
18
+ import { dirname, join, relative, resolve } from "node:path";
19
+ import { pathToFileURL } from "node:url";
20
+ import {
21
+ type CatalogConfig,
22
+ DEFAULT_SKILL_PATTERNS,
23
+ DEFAULT_TOOL_PATTERNS,
24
+ writeCatalog,
25
+ } from "../catalog/discover.js";
26
+ import { isObject } from "../mcp/rpc.js";
27
+
28
+ interface ArgumentMetaData {
29
+ readonly type: "string";
30
+ readonly propertyName: string;
31
+ readonly argumentName: string;
32
+ readonly description: string;
33
+ readonly required: boolean;
34
+ }
35
+
36
+ interface FlagMetaData {
37
+ readonly type: "string" | "boolean";
38
+ readonly propertyName: string;
39
+ readonly flagName: string;
40
+ readonly description: string;
41
+ readonly alias: string[];
42
+ readonly required: boolean;
43
+ }
44
+
45
+ /** The static side the kernel reads. */
46
+ export interface PolarisCommandClass {
47
+ new (): { run(): Promise<void> };
48
+ readonly commandName: string;
49
+ readonly description: string;
50
+ readonly options: { readonly startApp: boolean };
51
+ readonly args: readonly ArgumentMetaData[];
52
+ readonly flags: readonly FlagMetaData[];
53
+ }
54
+
55
+ /** What the kernel reads to list a command without importing it. */
56
+ export interface CommandMetaData {
57
+ commandName: string;
58
+ namespace: string | null;
59
+ description: string;
60
+ aliases: string[];
61
+ options: Record<string, unknown>;
62
+ args: readonly unknown[];
63
+ flags: readonly unknown[];
64
+ }
65
+
66
+ const flag = (
67
+ propertyName: string,
68
+ flagName: string,
69
+ type: FlagMetaData["type"],
70
+ description: string,
71
+ ): FlagMetaData => ({
72
+ type,
73
+ propertyName,
74
+ flagName,
75
+ description,
76
+ alias: [],
77
+ required: false,
78
+ });
79
+
80
+ const nameArgument = (description: string): ArgumentMetaData => ({
81
+ type: "string",
82
+ propertyName: "name",
83
+ argumentName: "name",
84
+ description,
85
+ required: true,
86
+ });
87
+
88
+ const MAKE_FLAGS: readonly FlagMetaData[] = [
89
+ flag(
90
+ "module",
91
+ "module",
92
+ "string",
93
+ "The module to write into: replaces the `*` of the configured pattern",
94
+ ),
95
+ flag("dryRun", "dry-run", "boolean", "Show the file, write nothing"),
96
+ flag("force", "force", "boolean", "Overwrite a file that exists"),
97
+ ];
98
+
99
+ /** Where the commands print, so a test can listen. */
100
+ export interface CommandOutput {
101
+ log(text: string): void;
102
+ error(text: string): void;
103
+ }
104
+
105
+ let output: CommandOutput = console;
106
+
107
+ /** @internal Send the commands' output elsewhere (tests). */
108
+ export function setCommandOutput(value: CommandOutput): void {
109
+ output = value;
110
+ }
111
+
112
+ const fail = (message: string): void => {
113
+ output.error(`[polaris] ${message}`);
114
+ process.exitCode = 1;
115
+ };
116
+
117
+ /**
118
+ * The `catalog` of `config/polaris.ts`, read off disk. A config that cannot
119
+ * be imported gives the defaults, and the reason is printed.
120
+ */
121
+ export async function projectCatalogConfig(
122
+ cwd = process.cwd(),
123
+ ): Promise<CatalogConfig | false> {
124
+ const file = join(cwd, "config", "polaris.ts");
125
+ if (!existsSync(file)) return {};
126
+ try {
127
+ const module: unknown = await import(pathToFileURL(file).href);
128
+ const config = isObject(module) ? module.default : undefined;
129
+ const catalog = isObject(config) ? config.catalog : undefined;
130
+ if (catalog === false) return false;
131
+ return isCatalogConfig(catalog) ? catalog : {};
132
+ } catch (error) {
133
+ output.error(
134
+ `[polaris] config/polaris.ts could not be read, the default folders are used: ${error instanceof Error ? error.message : String(error)}`,
135
+ );
136
+ return {};
137
+ }
138
+ }
139
+
140
+ const isPatterns = (value: unknown): boolean =>
141
+ value === undefined ||
142
+ (Array.isArray(value) && value.every((item) => typeof item === "string"));
143
+
144
+ function isCatalogConfig(value: unknown): value is CatalogConfig {
145
+ return (
146
+ isObject(value) &&
147
+ isPatterns(value.tools) &&
148
+ isPatterns(value.skills) &&
149
+ (value.manifest === undefined || typeof value.manifest === "string")
150
+ );
151
+ }
152
+
153
+ /** `CantonRate`, `canton-rate`, `canton rate` -> `canton_rate`. */
154
+ export function snakeCase(name: string): string {
155
+ return name
156
+ .trim()
157
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
158
+ .replace(/[\s-]+/g, "_")
159
+ .toLowerCase();
160
+ }
161
+
162
+ /**
163
+ * The path a generator writes to, from the first pattern that fits:
164
+ * with `module`, the first with a `*` in a folder, which `module` replaces;
165
+ * without, the first with none. A `*` left in the last segment of a file
166
+ * pattern takes `file`; a folder pattern gets `file` appended.
167
+ */
168
+ export function destination(
169
+ patterns: readonly string[],
170
+ module: string | undefined,
171
+ file: string,
172
+ ): string | { problem: string } {
173
+ const folderStar = (pattern: string) =>
174
+ pattern
175
+ .split("/")
176
+ .slice(0, -1)
177
+ .some((part) => part.includes("*")) ||
178
+ (!isFilePattern(pattern) && pattern.includes("*"));
179
+ const pattern =
180
+ module === undefined
181
+ ? patterns.find((item) => !folderStar(item))
182
+ : patterns.find(folderStar);
183
+ if (pattern === undefined) {
184
+ return {
185
+ problem:
186
+ module === undefined
187
+ ? `every pattern (${patterns.join(", ")}) names a module: give --module`
188
+ : `no pattern (${patterns.join(", ")}) has a '*' for a module`,
189
+ };
190
+ }
191
+ let path = module === undefined ? pattern : pattern.replace("*", module);
192
+ if (isFilePattern(path)) {
193
+ const at = path.lastIndexOf("/") + 1;
194
+ const extension = path.slice(path.search(/\.[mc]?[jt]s$/));
195
+ const last = path.slice(at, path.length - extension.length);
196
+ path = `${path.slice(0, at)}${last.includes("*") ? last.replace("*", file) : file}${extension}`;
197
+ } else {
198
+ path = `${path.replace(/\/+$/, "")}/${file}.ts`;
199
+ }
200
+ if (/[*?[\]{}]/.test(path)) {
201
+ return {
202
+ problem: `the pattern '${pattern}' does not say where to write: use a plainer one first`,
203
+ };
204
+ }
205
+ return path;
206
+ }
207
+
208
+ function isFilePattern(pattern: string): boolean {
209
+ return /\.[mc]?[jt]s$/.test(pattern);
210
+ }
211
+
212
+ const MODULE_NAME = /^[a-z0-9][a-z0-9_-]*$/i;
213
+
214
+ /** Write `content` to `path` (relative to the cwd), honouring the flags. */
215
+ async function generate(
216
+ path: string,
217
+ content: string,
218
+ options: { dryRun: boolean; force: boolean },
219
+ ): Promise<void> {
220
+ const absolute = resolve(path);
221
+ const exists = existsSync(absolute);
222
+ if (options.dryRun) {
223
+ output.log(`${path}${exists ? " (exists)" : ""} - dry run`);
224
+ output.log(content);
225
+ return;
226
+ }
227
+ if (exists && !options.force) {
228
+ output.log(`skip ${path}: the file exists, use --force`);
229
+ return;
230
+ }
231
+ await mkdir(dirname(absolute), { recursive: true });
232
+ await writeFile(absolute, content);
233
+ output.log(`create ${path}`);
234
+ output.log("Run `ream polaris:index` to add it to polaris.json.");
235
+ }
236
+
237
+ export const TOOL_STUB = (
238
+ name: string,
239
+ ): string => `import { defineTool } from '@c9up/polaris'
240
+
241
+ export default defineTool({
242
+ name: '${name}',
243
+ description: 'TODO: what the tool does, and when the model should call it.',
244
+ inputSchema: {
245
+ type: 'object',
246
+ properties: {},
247
+ additionalProperties: false,
248
+ },
249
+ run: async () => {
250
+ return 'TODO'
251
+ },
252
+ })
253
+ `;
254
+
255
+ export const SKILL_STUB = (name: string): string => `---
256
+ name: ${name}
257
+ description: TODO: what the skill is for, and when the model should load it.
258
+ ---
259
+ # ${name}
260
+
261
+ TODO: the instructions the model follows once it loads this skill. Files
262
+ beside this one can be read with read_skill_file; tools go in tools/.
263
+ `;
264
+
265
+ class IndexCommand {
266
+ static readonly commandName = "polaris:index";
267
+ static readonly description =
268
+ "List the application's tools and skills in polaris.json";
269
+ static readonly options = { startApp: false };
270
+ static readonly args: readonly ArgumentMetaData[] = [];
271
+ static readonly flags: readonly FlagMetaData[] = [];
272
+
273
+ async run(): Promise<void> {
274
+ const config = await projectCatalogConfig();
275
+ if (config === false) {
276
+ fail("`catalog` is false in config/polaris.ts: nothing to index");
277
+ return;
278
+ }
279
+ try {
280
+ const { manifest, path } = await writeCatalog(config);
281
+ output.log(
282
+ `Wrote ${relative(process.cwd(), path)}: ${manifest.tools.length} tool(s), ${manifest.skills.length} skill(s).`,
283
+ );
284
+ } catch (error) {
285
+ fail(error instanceof Error ? error.message : String(error));
286
+ }
287
+ }
288
+ }
289
+
290
+ class MakeToolCommand {
291
+ static readonly commandName = "make:tool";
292
+ static readonly description = "Generate a polaris tool";
293
+ static readonly options = { startApp: false };
294
+ static readonly args = [
295
+ nameArgument("The tool's name, as the model sees it"),
296
+ ];
297
+ static readonly flags = MAKE_FLAGS;
298
+
299
+ declare name: string;
300
+ declare module: string | undefined;
301
+ declare dryRun: boolean | undefined;
302
+ declare force: boolean | undefined;
303
+
304
+ async run(): Promise<void> {
305
+ const name = snakeCase(this.name);
306
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(name)) {
307
+ fail(
308
+ `'${this.name}' is not a tool name: letters, digits and underscores, 64 at most, starting with a letter`,
309
+ );
310
+ return;
311
+ }
312
+ await make(this, name, name, "tools", TOOL_STUB(name));
313
+ }
314
+ }
315
+
316
+ class MakeSkillCommand {
317
+ static readonly commandName = "make:skill";
318
+ static readonly description = "Generate a polaris skill: a SKILL.md folder";
319
+ static readonly options = { startApp: false };
320
+ static readonly args = [nameArgument("The skill's name")];
321
+ static readonly flags = MAKE_FLAGS;
322
+
323
+ declare name: string;
324
+ declare module: string | undefined;
325
+ declare dryRun: boolean | undefined;
326
+ declare force: boolean | undefined;
327
+
328
+ async run(): Promise<void> {
329
+ const name = snakeCase(this.name).replace(/_/g, "-");
330
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || name.length > 64) {
331
+ fail(
332
+ `'${this.name}' is not a skill name: lower-case letters, digits and single hyphens, 64 at most`,
333
+ );
334
+ return;
335
+ }
336
+ await make(this, name, `${name}/SKILL`, "skills", SKILL_STUB(name));
337
+ }
338
+ }
339
+
340
+ async function make(
341
+ command: {
342
+ module: string | undefined;
343
+ dryRun: boolean | undefined;
344
+ force: boolean | undefined;
345
+ },
346
+ name: string,
347
+ file: string,
348
+ kind: "tools" | "skills",
349
+ content: string,
350
+ ): Promise<void> {
351
+ if (command.module !== undefined && !MODULE_NAME.test(command.module)) {
352
+ fail(`'${command.module}' is not a module name`);
353
+ return;
354
+ }
355
+ const config = await projectCatalogConfig();
356
+ const patterns =
357
+ config === false
358
+ ? []
359
+ : (config[kind] ??
360
+ (kind === "tools" ? DEFAULT_TOOL_PATTERNS : DEFAULT_SKILL_PATTERNS));
361
+ if (patterns.length === 0) {
362
+ fail(`config/polaris.ts lists no ${kind} folder`);
363
+ return;
364
+ }
365
+ // A skill is a folder: its SKILL.md never fits a file pattern.
366
+ const usable =
367
+ kind === "skills"
368
+ ? patterns.filter((pattern) => !isFilePattern(pattern))
369
+ : patterns;
370
+ const found = destination(usable, command.module, file);
371
+ if (typeof found !== "string") {
372
+ fail(`cannot place '${name}': ${found.problem}`);
373
+ return;
374
+ }
375
+ const path = kind === "skills" ? found.replace(/\.ts$/, ".md") : found;
376
+ await generate(path, content, {
377
+ dryRun: command.dryRun === true,
378
+ force: command.force === true,
379
+ });
380
+ }
381
+
382
+ const COMMANDS: readonly PolarisCommandClass[] = [
383
+ IndexCommand,
384
+ MakeToolCommand,
385
+ MakeSkillCommand,
386
+ ];
387
+
388
+ function serialize(command: PolarisCommandClass): CommandMetaData {
389
+ const colon = command.commandName.indexOf(":");
390
+ return {
391
+ commandName: command.commandName,
392
+ namespace: colon === -1 ? null : command.commandName.slice(0, colon),
393
+ description: command.description,
394
+ aliases: [],
395
+ options: { ...command.options },
396
+ args: command.args,
397
+ flags: command.flags,
398
+ };
399
+ }
400
+
401
+ export async function getMetaData(): Promise<CommandMetaData[]> {
402
+ return COMMANDS.map(serialize);
403
+ }
404
+
405
+ export async function getCommand(
406
+ metadata: CommandMetaData,
407
+ ): Promise<PolarisCommandClass | null> {
408
+ return (
409
+ COMMANDS.find((command) => command.commandName === metadata.commandName) ??
410
+ null
411
+ );
412
+ }
package/src/cost.ts CHANGED
@@ -84,18 +84,24 @@ export function costOf(price: ModelPrice, usage: Usage): string {
84
84
  /**
85
85
  * The most a chat request can cost: its input estimated from its length (few
86
86
  * characters per token, so the estimate errs high), and its output at the
87
- * full `maxTokens`.
87
+ * full `maxTokens`. A request that asks for caching may write its whole input
88
+ * to the cache, so its input is counted at the cache write price when that
89
+ * one is higher.
88
90
  */
89
91
  export function estimateChat(
90
92
  price: ModelPrice,
91
93
  request: ChatRequest,
92
94
  maxTokens: number,
93
95
  ): string {
96
+ const tokens = estimateTokens(request);
97
+ const written =
98
+ request.cache === true &&
99
+ decimal(price.cacheWrite ?? price.input).gt(price.input);
94
100
  return costOf(price, {
95
- inputTokens: estimateTokens(request),
101
+ inputTokens: written ? 0 : tokens,
96
102
  outputTokens: maxTokens,
97
103
  cacheReadTokens: 0,
98
- cacheWriteTokens: 0,
104
+ cacheWriteTokens: written ? tokens : 0,
99
105
  });
100
106
  }
101
107