@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
package/src/budget.ts CHANGED
@@ -10,39 +10,111 @@
10
10
  * the same moment from passing the limit together.
11
11
  */
12
12
 
13
+ import { decimal } from "@c9up/atom";
13
14
  import { add, exceeds, isZero, subtract } from "./cost.js";
14
- import { E_POLARIS_BUDGET_EXCEEDED } from "./errors.js";
15
+ import {
16
+ E_POLARIS_BUDGET_EXCEEDED,
17
+ E_POLARIS_INVALID_CONFIG,
18
+ } from "./errors.js";
15
19
 
16
20
  /**
17
- * Where spend is kept. `add` must be atomic (a Redis `INCRBYFLOAT`, an SQL
21
+ * Where spend is kept. `add` must be atomic (a Redis `INCRBY`, an SQL
18
22
  * `UPDATE … SET spent = spent + ?`): it is what reservations rely on.
19
23
  */
20
24
  export interface BudgetStore {
21
- /** Add `amount` (a decimal string, possibly negative) to `scope`, and answer the new total. */
22
- add(scope: string, amount: string): Promise<string>;
25
+ /**
26
+ * Add `amount` (a decimal string, possibly negative) to `key`, and answer
27
+ * the new total. `key` is the scope, followed by its period when the
28
+ * budget has one (`user:42@2026-12`). `expiresAt` (epoch milliseconds),
29
+ * given with a period, is when the key may be dropped: a store that keeps
30
+ * it for ever counts right, but grows with every period.
31
+ */
32
+ add(key: string, amount: string, expiresAt?: number): Promise<string>;
33
+ /**
34
+ * The decimals the store keeps, when it rounds what it adds (the Redis
35
+ * store keeps 9). A reservation then rounds its estimate and the final
36
+ * cost once each, half up, and moves the spend by their difference: what
37
+ * a request leaves in the store is its cost rounded once, whatever its
38
+ * estimate was. Rounding the estimate and the correction separately would
39
+ * not add up, and could undercount the spend. Leave it out for a store
40
+ * that keeps every decimal.
41
+ */
42
+ readonly decimals?: number;
23
43
  }
24
44
 
45
+ /** How long spend counts before it starts again at zero, in UTC. */
46
+ export type BudgetPeriod = "day" | "month";
47
+
25
48
  export interface BudgetConfig {
26
49
  /** The limit of a scope, as a decimal string in the pricing currency; `undefined` for none. */
27
50
  readonly limit:
28
51
  | { readonly [scope: string]: string }
29
52
  | ((scope: string) => string | undefined | Promise<string | undefined>);
53
+ /**
54
+ * Count spend per day or per month (UTC), from zero at the start of each.
55
+ * Default: no period, spend counts for as long as the store keeps it.
56
+ */
57
+ readonly period?: BudgetPeriod;
30
58
  /** Where spend is kept. Default: in memory, for one process and its lifetime. */
31
59
  readonly store?: BudgetStore;
32
60
  }
33
61
 
34
62
  /** A spend store in memory: one process, lost on restart. For tests and a single instance. */
35
63
  export function memoryBudgetStore(): BudgetStore {
36
- const spent = new Map<string, string>();
64
+ const spent = new Map<string, { total: string; expiresAt?: number }>();
65
+ // Expired keys are swept at most once per expiry passed, not on every add.
66
+ let nextSweep = Number.POSITIVE_INFINITY;
37
67
  return {
38
- async add(scope, amount) {
39
- const total = add(spent.get(scope) ?? "0", amount);
40
- spent.set(scope, total);
68
+ async add(key, amount, expiresAt) {
69
+ const now = Date.now();
70
+ if (now >= nextSweep) {
71
+ nextSweep = Number.POSITIVE_INFINITY;
72
+ for (const [name, entry] of spent) {
73
+ if (entry.expiresAt === undefined) continue;
74
+ if (entry.expiresAt <= now) spent.delete(name);
75
+ else nextSweep = Math.min(nextSweep, entry.expiresAt);
76
+ }
77
+ }
78
+ const total = add(spent.get(key)?.total ?? "0", amount);
79
+ spent.set(key, {
80
+ total,
81
+ ...(expiresAt !== undefined ? { expiresAt } : {}),
82
+ });
83
+ if (expiresAt !== undefined) nextSweep = Math.min(nextSweep, expiresAt);
41
84
  return total;
42
85
  },
43
86
  };
44
87
  }
45
88
 
89
+ /**
90
+ * How long a period's spend is kept after the period ends: long enough for a
91
+ * request sent just before midnight to settle into the period it reserved on.
92
+ */
93
+ const GRACE_MS = 24 * 60 * 60 * 1000;
94
+
95
+ /** The key a scope's spend is kept under at `now`, and when that key may go. */
96
+ export function periodKey(
97
+ scope: string,
98
+ period: BudgetPeriod | undefined,
99
+ now: number = Date.now(),
100
+ ): { readonly key: string; readonly expiresAt?: number } {
101
+ if (period === undefined) return { key: scope };
102
+ const date = new Date(now);
103
+ const year = date.getUTCFullYear();
104
+ const month = date.getUTCMonth();
105
+ const day = date.getUTCDate();
106
+ const pad = (value: number) => String(value).padStart(2, "0");
107
+ const label =
108
+ period === "month"
109
+ ? `${year}-${pad(month + 1)}`
110
+ : `${year}-${pad(month + 1)}-${pad(day)}`;
111
+ const end =
112
+ period === "month"
113
+ ? Date.UTC(year, month + 1, 1)
114
+ : Date.UTC(year, month, day + 1);
115
+ return { key: `${scope}@${label}`, expiresAt: end + GRACE_MS };
116
+ }
117
+
46
118
  /** What a reservation hands back to settle it. */
47
119
  export interface Reservation {
48
120
  /** Replace the reservation by what the request really cost. */
@@ -69,19 +141,32 @@ export async function limitOf(
69
141
  }
70
142
 
71
143
  /**
72
- * Reserve `estimate` on `scope`, or refuse with `E_POLARIS_BUDGET_EXCEEDED`
73
- * when that would go past `limit`. With no limit, nothing is reserved.
144
+ * Reserve `estimate` on `scope` for the current `period`, or refuse with
145
+ * `E_POLARIS_BUDGET_EXCEEDED` when that would go past `limit`. With no limit,
146
+ * nothing is reserved.
147
+ *
148
+ * The reservation keeps the key of the period it was made in: settled after
149
+ * midnight, it still lands on the day it counted against, and a reservation
150
+ * whose process died never settles but goes with its period's key.
74
151
  */
75
152
  export async function reserve(
76
153
  store: BudgetStore,
77
154
  scope: string,
78
155
  limit: string | undefined,
79
156
  estimate: string,
157
+ period?: BudgetPeriod,
80
158
  ): Promise<Reservation> {
81
159
  if (limit === undefined) return NOTHING;
82
- const total = await store.add(scope, estimate);
160
+ const round = rounding(store.decimals);
161
+ const reserved = round(estimate);
162
+ const { key, expiresAt } = periodKey(scope, period);
163
+ const move = (amount: string) =>
164
+ expiresAt === undefined
165
+ ? store.add(key, amount)
166
+ : store.add(key, amount, expiresAt);
167
+ const total = await move(reserved);
83
168
  if (exceeds(total, limit)) {
84
- await store.add(scope, `-${estimate}`);
169
+ await move(negate(reserved));
85
170
  throw new E_POLARIS_BUDGET_EXCEEDED([scope, limit]);
86
171
  }
87
172
  let open = true;
@@ -89,13 +174,28 @@ export async function reserve(
89
174
  async settle(cost) {
90
175
  if (!open) return;
91
176
  open = false;
92
- const difference = subtract(cost, estimate);
93
- if (!isZero(difference)) await store.add(scope, difference);
177
+ const difference = subtract(round(cost), reserved);
178
+ if (!isZero(difference)) await move(difference);
94
179
  },
95
180
  async release() {
96
181
  if (!open) return;
97
182
  open = false;
98
- await store.add(scope, `-${estimate}`);
183
+ await move(negate(reserved));
99
184
  },
100
185
  };
101
186
  }
187
+
188
+ /** Round an amount to the decimals a store keeps, or leave it as it is. */
189
+ function rounding(decimals: number | undefined): (amount: string) => string {
190
+ if (decimals === undefined) return (amount) => amount;
191
+ if (!Number.isSafeInteger(decimals) || decimals < 0) {
192
+ throw new E_POLARIS_INVALID_CONFIG([
193
+ "budget.store.decimals must be a non-negative integer",
194
+ ]);
195
+ }
196
+ return (amount) => decimal(amount).toFixed(decimals, "half-up");
197
+ }
198
+
199
+ function negate(amount: string): string {
200
+ return subtract("0", amount);
201
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The application's tools and skills, read from `polaris.json`. A run is
3
+ * given them by name; only the modules of the tools asked for are imported.
4
+ *
5
+ * const tools = await catalog.tools(['canton_rate'])
6
+ * const skills = useSkills(await catalog.skills(['payroll']))
7
+ */
8
+
9
+ import { existsSync } from "node:fs";
10
+ import { readFile } from "node:fs/promises";
11
+ import { dirname, resolve } from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+ import { E_POLARIS_INVALID_CATALOG } from "../errors.js";
14
+ import { isObject } from "../mcp/rpc.js";
15
+ import { type ReadSkillOptions, readSkill } from "../skills/folder.js";
16
+ import type { PolarisSkill } from "../skills/skill.js";
17
+ import { importToolModule } from "../tool-modules.js";
18
+ import type { PolarisTool } from "../tools.js";
19
+ import type { CatalogManifest, CatalogSkill, CatalogTool } from "./discover.js";
20
+
21
+ const REINDEX = "run `ream polaris:index`";
22
+
23
+ const isEntry = (value: unknown, path: "module" | "folder"): boolean =>
24
+ isObject(value) &&
25
+ typeof value.name === "string" &&
26
+ typeof value.description === "string" &&
27
+ typeof value[path] === "string";
28
+
29
+ function isManifest(value: unknown): value is CatalogManifest {
30
+ return (
31
+ isObject(value) &&
32
+ value.version === 1 &&
33
+ Array.isArray(value.tools) &&
34
+ value.tools.every((entry) => isEntry(entry, "module")) &&
35
+ Array.isArray(value.skills) &&
36
+ value.skills.every((entry) => isEntry(entry, "folder"))
37
+ );
38
+ }
39
+
40
+ /**
41
+ * A module's path as written, or its build output: in a build, `polaris.json`
42
+ * is copied beside the compiled code, where `x.ts` became `x.js`.
43
+ */
44
+ function compiled(path: string): string {
45
+ if (existsSync(path)) return path;
46
+ const built = path.replace(/\.ts$/, ".js").replace(/\.mts$/, ".mjs");
47
+ return existsSync(built) ? built : path;
48
+ }
49
+
50
+ export class Catalog {
51
+ readonly #manifest: CatalogManifest;
52
+ readonly #base: string;
53
+ /** The manifest's path, for messages; `undefined` when there was none. */
54
+ readonly #path: string | undefined;
55
+ readonly #modules = new Map<string, Promise<PolarisTool[]>>();
56
+
57
+ /** Paths in `manifest` are relative to `base`. */
58
+ constructor(manifest: CatalogManifest, base: string, path?: string) {
59
+ this.#manifest = manifest;
60
+ this.#base = base;
61
+ this.#path = path;
62
+ }
63
+
64
+ /**
65
+ * Read a manifest. A file that does not exist gives an empty catalog,
66
+ * which says so when a name is asked of it; one that is not a manifest
67
+ * throws `E_POLARIS_INVALID_CATALOG`.
68
+ */
69
+ static async read(path: string): Promise<Catalog> {
70
+ const absolute = resolve(path);
71
+ let text: string;
72
+ try {
73
+ text = await readFile(absolute, "utf8");
74
+ } catch {
75
+ return new Catalog(
76
+ { version: 1, tools: [], skills: [] },
77
+ dirname(absolute),
78
+ );
79
+ }
80
+ let manifest: unknown;
81
+ try {
82
+ manifest = JSON.parse(text);
83
+ } catch {
84
+ manifest = undefined;
85
+ }
86
+ if (!isManifest(manifest)) {
87
+ throw new E_POLARIS_INVALID_CATALOG([
88
+ `'${path}' is not a polaris manifest; ${REINDEX}`,
89
+ ]);
90
+ }
91
+ return new Catalog(manifest, dirname(absolute), path);
92
+ }
93
+
94
+ /** The tools found, by name and description, without importing them. */
95
+ get toolList(): readonly CatalogTool[] {
96
+ return this.#manifest.tools;
97
+ }
98
+
99
+ /** The skills found, by name and description, without reading them. */
100
+ get skillList(): readonly CatalogSkill[] {
101
+ return this.#manifest.skills;
102
+ }
103
+
104
+ #missing(kind: "tool" | "skill", name: string): never {
105
+ const where =
106
+ this.#path === undefined
107
+ ? `no manifest was found; ${REINDEX}`
108
+ : `'${this.#path}' lists none; ${REINDEX} after adding one`;
109
+ throw new E_POLARIS_INVALID_CATALOG([
110
+ `no ${kind} is named '${name.slice(0, 64)}': ${where}`,
111
+ ]);
112
+ }
113
+
114
+ /**
115
+ * The tools named, in that order; all of them when no name is given. Each
116
+ * module is imported once, on the first call that needs it.
117
+ */
118
+ async tools(names?: readonly string[]): Promise<PolarisTool[]> {
119
+ const entries =
120
+ names === undefined
121
+ ? this.#manifest.tools
122
+ : names.map(
123
+ (name) =>
124
+ this.#manifest.tools.find((tool) => tool.name === name) ??
125
+ this.#missing("tool", name),
126
+ );
127
+ const tools: PolarisTool[] = [];
128
+ for (const entry of entries) {
129
+ const exported = await this.#module(entry.module);
130
+ const tool = exported.find((item) => item.name === entry.name);
131
+ if (tool === undefined) {
132
+ throw new E_POLARIS_INVALID_CATALOG([
133
+ `'${entry.module}' no longer exports the tool '${entry.name}'; ${REINDEX}`,
134
+ ]);
135
+ }
136
+ tools.push(tool);
137
+ }
138
+ return tools;
139
+ }
140
+
141
+ #module(module: string): Promise<PolarisTool[]> {
142
+ let loading = this.#modules.get(module);
143
+ if (loading === undefined) {
144
+ const url = pathToFileURL(compiled(resolve(this.#base, module))).href;
145
+ loading = importToolModule(url).then((found) => {
146
+ if (typeof found === "string") {
147
+ throw new E_POLARIS_INVALID_CATALOG([`'${module}' ${found}`]);
148
+ }
149
+ return found;
150
+ });
151
+ // A failed import is tried again on the next call, not remembered.
152
+ loading.catch(() => this.#modules.delete(module));
153
+ this.#modules.set(module, loading);
154
+ }
155
+ return loading;
156
+ }
157
+
158
+ /**
159
+ * The skills named, in that order; all of them when no name is given.
160
+ * Each is read from its folder on every call (see `readSkill`).
161
+ */
162
+ async skills(
163
+ names?: readonly string[],
164
+ options?: ReadSkillOptions,
165
+ ): Promise<PolarisSkill[]> {
166
+ const entries =
167
+ names === undefined
168
+ ? this.#manifest.skills
169
+ : names.map(
170
+ (name) =>
171
+ this.#manifest.skills.find((skill) => skill.name === name) ??
172
+ this.#missing("skill", name),
173
+ );
174
+ return Promise.all(
175
+ entries.map((entry) =>
176
+ readSkill(resolve(this.#base, entry.folder), options),
177
+ ),
178
+ );
179
+ }
180
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Finding the application's tools and skills by convention: the folders and
3
+ * files its glob patterns match. `ream polaris:index` runs this at build and
4
+ * writes the result, `polaris.json`, so the running application reads a list
5
+ * instead of importing every tool module to learn its name.
6
+ */
7
+
8
+ import type { Dirent } from "node:fs";
9
+ import { glob, lstat, mkdir, readdir, writeFile } from "node:fs/promises";
10
+ import {
11
+ basename,
12
+ dirname,
13
+ isAbsolute,
14
+ join,
15
+ relative,
16
+ resolve,
17
+ sep,
18
+ } from "node:path";
19
+ import { pathToFileURL } from "node:url";
20
+ import { E_POLARIS_INVALID_CATALOG } from "../errors.js";
21
+ import { readSkill } from "../skills/folder.js";
22
+ import { importToolModule, isToolModuleFile } from "../tool-modules.js";
23
+
24
+ /** `catalog` in `config/polaris.ts`. Paths are relative to the application. */
25
+ export interface CatalogConfig {
26
+ /**
27
+ * Glob patterns of tool folders or tool files. A folder holds tool
28
+ * modules; a file is one. Default `['app/tools']`; a modular application
29
+ * names its modules: `['app/modules/*\/tools', 'app/modules/*\/http/*_tool.ts']`.
30
+ */
31
+ readonly tools?: readonly string[];
32
+ /**
33
+ * Glob patterns of skill folders: a folder with a `SKILL.md` is a skill,
34
+ * another holds skills, one per sub-folder. Default `['resources/skills']`.
35
+ */
36
+ readonly skills?: readonly string[];
37
+ /** Where `ream polaris:index` writes the list. Default `polaris.json`. */
38
+ readonly manifest?: string;
39
+ }
40
+
41
+ export const DEFAULT_TOOL_PATTERNS: readonly string[] = ["app/tools"];
42
+ export const DEFAULT_SKILL_PATTERNS: readonly string[] = ["resources/skills"];
43
+ export const DEFAULT_MANIFEST = "polaris.json";
44
+
45
+ /** What `polaris.json` holds. Paths are relative to it, with `/`. */
46
+ export interface CatalogManifest {
47
+ readonly version: 1;
48
+ readonly tools: readonly CatalogTool[];
49
+ readonly skills: readonly CatalogSkill[];
50
+ }
51
+
52
+ export interface CatalogTool {
53
+ readonly name: string;
54
+ readonly description: string;
55
+ /** The module that exports it. */
56
+ readonly module: string;
57
+ }
58
+
59
+ export interface CatalogSkill {
60
+ readonly name: string;
61
+ readonly description: string;
62
+ /** The folder that holds its `SKILL.md`. */
63
+ readonly folder: string;
64
+ }
65
+
66
+ export interface IndexCatalogOptions extends CatalogConfig {
67
+ /** The application's root. Default the current directory. */
68
+ readonly root?: string;
69
+ }
70
+
71
+ /** A path relative to `from`, with `/`. */
72
+ function relativePath(from: string, to: string): string {
73
+ return relative(from, to).split(sep).join("/");
74
+ }
75
+
76
+ /** The paths `pattern` matches under `root`, sorted, absolute. */
77
+ async function matches(root: string, pattern: string): Promise<string[]> {
78
+ if (
79
+ pattern.trim() === "" ||
80
+ isAbsolute(pattern) ||
81
+ pattern.split(/[\\/]/).includes("..")
82
+ ) {
83
+ throw new E_POLARIS_INVALID_CATALOG([
84
+ `the pattern '${pattern}' must be a path within the application`,
85
+ ]);
86
+ }
87
+ const found: string[] = [];
88
+ for await (const entry of glob(pattern, { cwd: root })) {
89
+ found.push(join(root, entry));
90
+ }
91
+ return found.sort();
92
+ }
93
+
94
+ const isDirectory = async (path: string): Promise<boolean> =>
95
+ (await lstat(path)).isDirectory();
96
+
97
+ async function subfolders(folder: string): Promise<Dirent[]> {
98
+ const entries = await readdir(folder, { withFileTypes: true });
99
+ return entries.sort((a, b) => a.name.localeCompare(b.name));
100
+ }
101
+
102
+ /** The tool modules the patterns lead to, each once, in pattern order. */
103
+ async function toolFiles(
104
+ root: string,
105
+ patterns: readonly string[],
106
+ ): Promise<string[]> {
107
+ const files = new Set<string>();
108
+ for (const pattern of patterns) {
109
+ for (const path of await matches(root, pattern)) {
110
+ if (await isDirectory(path)) {
111
+ for (const entry of await subfolders(path)) {
112
+ if (entry.isFile() && isToolModuleFile(entry.name)) {
113
+ files.add(join(path, entry.name));
114
+ }
115
+ }
116
+ } else if (isToolModuleFile(basename(path))) {
117
+ files.add(path);
118
+ }
119
+ }
120
+ }
121
+ return [...files];
122
+ }
123
+
124
+ /** The skill folders the patterns lead to, each once. */
125
+ async function skillFolders(
126
+ root: string,
127
+ patterns: readonly string[],
128
+ ): Promise<string[]> {
129
+ const folders = new Set<string>();
130
+ const hasSkill = (folder: string) =>
131
+ lstat(join(folder, "SKILL.md")).then(
132
+ () => true,
133
+ () => false,
134
+ );
135
+ for (const pattern of patterns) {
136
+ for (const path of await matches(root, pattern)) {
137
+ if (!(await isDirectory(path))) continue;
138
+ if (await hasSkill(path)) {
139
+ folders.add(path);
140
+ continue;
141
+ }
142
+ for (const entry of await subfolders(path)) {
143
+ const folder = join(path, entry.name);
144
+ if (
145
+ entry.isDirectory() &&
146
+ !entry.name.startsWith(".") &&
147
+ (await hasSkill(folder))
148
+ ) {
149
+ folders.add(folder);
150
+ }
151
+ }
152
+ }
153
+ }
154
+ return [...folders];
155
+ }
156
+
157
+ /**
158
+ * Find the tools and skills the patterns lead to, importing each tool module
159
+ * and reading each `SKILL.md` once. Throws `E_POLARIS_INVALID_CATALOG` when a
160
+ * module exports no tools, or when two tools or two skills share a name,
161
+ * naming both files; `E_POLARIS_INVALID_SKILL` for a skill folder that
162
+ * cannot be read. Paths in the result are relative to `base`.
163
+ */
164
+ export async function indexCatalog(
165
+ options: IndexCatalogOptions = {},
166
+ base?: string,
167
+ ): Promise<CatalogManifest> {
168
+ const root = resolve(options.root ?? ".");
169
+ const from = base ?? root;
170
+ const tools: CatalogTool[] = [];
171
+ const toolFile = new Map<string, string>();
172
+ for (const file of await toolFiles(
173
+ root,
174
+ options.tools ?? DEFAULT_TOOL_PATTERNS,
175
+ )) {
176
+ const shown = relativePath(root, file);
177
+ const found = await importToolModule(pathToFileURL(file).href);
178
+ if (typeof found === "string") {
179
+ throw new E_POLARIS_INVALID_CATALOG([`'${shown}' ${found}`]);
180
+ }
181
+ for (const tool of found) {
182
+ const other = toolFile.get(tool.name);
183
+ if (other !== undefined) {
184
+ throw new E_POLARIS_INVALID_CATALOG([
185
+ `two tools are named '${tool.name}': in '${other}' and in '${shown}'`,
186
+ ]);
187
+ }
188
+ toolFile.set(tool.name, shown);
189
+ tools.push({
190
+ name: tool.name,
191
+ description: tool.definition.description,
192
+ module: relativePath(from, file),
193
+ });
194
+ }
195
+ }
196
+
197
+ const skills: CatalogSkill[] = [];
198
+ const skillFolder = new Map<string, string>();
199
+ for (const folder of await skillFolders(
200
+ root,
201
+ options.skills ?? DEFAULT_SKILL_PATTERNS,
202
+ )) {
203
+ const shown = relativePath(root, folder);
204
+ const skill = await readSkill(folder);
205
+ const other = skillFolder.get(skill.name);
206
+ if (other !== undefined) {
207
+ throw new E_POLARIS_INVALID_CATALOG([
208
+ `two skills are named '${skill.name}': in '${other}' and in '${shown}'`,
209
+ ]);
210
+ }
211
+ skillFolder.set(skill.name, shown);
212
+ skills.push({
213
+ name: skill.name,
214
+ description: skill.description,
215
+ folder: relativePath(from, folder),
216
+ });
217
+ }
218
+ return { version: 1, tools, skills };
219
+ }
220
+
221
+ /**
222
+ * {@link indexCatalog}, written to the manifest (`polaris.json` at the root
223
+ * unless `manifest` says otherwise). Returns the manifest and its path.
224
+ */
225
+ export async function writeCatalog(
226
+ options: IndexCatalogOptions = {},
227
+ ): Promise<{ manifest: CatalogManifest; path: string }> {
228
+ const root = resolve(options.root ?? ".");
229
+ const path = resolve(root, options.manifest ?? DEFAULT_MANIFEST);
230
+ const manifest = await indexCatalog(options, dirname(path));
231
+ await mkdir(dirname(path), { recursive: true });
232
+ await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`);
233
+ return { manifest, path };
234
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@c9up/polaris/catalog`: the application's tools and skills, found by
3
+ * convention in the folders `config/polaris.ts` names, listed at build in
4
+ * `polaris.json`, and given to a run by name.
5
+ */
6
+
7
+ export { Catalog } from "./catalog.js";
8
+ export {
9
+ type CatalogConfig,
10
+ type CatalogManifest,
11
+ type CatalogSkill,
12
+ type CatalogTool,
13
+ DEFAULT_MANIFEST,
14
+ DEFAULT_SKILL_PATTERNS,
15
+ DEFAULT_TOOL_PATTERNS,
16
+ type IndexCatalogOptions,
17
+ indexCatalog,
18
+ writeCatalog,
19
+ } from "./discover.js";