@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/meter.ts CHANGED
@@ -66,6 +66,12 @@ export interface MeterInput {
66
66
  export interface MeterOutcome {
67
67
  readonly model: string;
68
68
  readonly usage: Usage;
69
+ /**
70
+ * Whether the provider reported usage that can be priced. Without it the
71
+ * call has no cost, and its estimate stays on the budget: a missing count
72
+ * is not a free call.
73
+ */
74
+ readonly usageKnown: boolean;
69
75
  readonly responseId?: string;
70
76
  readonly stopReason?: StopReason;
71
77
  readonly response: ChatResponse | EmbedResponse;
@@ -119,6 +125,7 @@ export async function openTicket(
119
125
  input.scope,
120
126
  limit,
121
127
  estimate,
128
+ config.budget.period,
122
129
  );
123
130
  }
124
131
  }
@@ -135,12 +142,16 @@ export async function openTicket(
135
142
  return {
136
143
  async finish(outcome) {
137
144
  const answered = priceFor(config.pricing, outcome.model) ?? price;
138
- const amount = answered ? costOf(answered, outcome.usage) : undefined;
145
+ const amount =
146
+ answered !== undefined && outcome.usageKnown
147
+ ? costOf(answered, outcome.usage)
148
+ : undefined;
139
149
  const cost =
140
150
  amount !== undefined && config.pricing !== undefined
141
151
  ? { amount, currency: config.pricing.currency }
142
152
  : undefined;
143
- // Without a price for the model that answered, the estimate stays.
153
+ // Without a price for the model that answered, or usage to price, the
154
+ // estimate stays.
144
155
  if (reservation !== undefined && amount !== undefined) {
145
156
  await reservation.settle(amount);
146
157
  }
package/src/redact.ts CHANGED
@@ -61,18 +61,21 @@ function holdsSecret(value: unknown, secrets: readonly string[]): boolean {
61
61
  * The error to raise for a failed call that was given `secrets`.
62
62
  *
63
63
  * An error that holds none of them is returned as it is. One that holds any is
64
- * replaced by `E_POLARIS_PROVIDER_FAILED`, whose message is the original one
65
- * with the secrets taken out, and which keeps no reference to the original.
64
+ * replaced by `E_POLARIS_PROVIDER_FAILED` (or what `replace` builds), whose
65
+ * message is the original one with the secrets taken out, and which keeps no
66
+ * reference to the original.
66
67
  */
67
68
  export function scrub(
68
69
  error: unknown,
69
70
  provider: string,
70
71
  secrets: readonly (string | undefined)[],
72
+ replace: (provider: string, message: string) => Error = (name, message) =>
73
+ new E_POLARIS_PROVIDER_FAILED([name, message]),
71
74
  ): unknown {
72
75
  const live = secrets.filter(
73
76
  (secret): secret is string => typeof secret === "string" && secret !== "",
74
77
  );
75
78
  if (live.length === 0 || !holdsSecret(error, live)) return error;
76
79
  const message = error instanceof Error ? error.message : String(error);
77
- return new E_POLARIS_PROVIDER_FAILED([provider, redact(message, live)]);
80
+ return replace(provider, redact(message, live));
78
81
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * A budget store in Redis, shared by every instance that talks to the same
3
+ * server: what one instance reserves, the others see at once.
4
+ *
5
+ * Spend is kept as an integer count of billionths of the pricing currency, so
6
+ * that Redis adds it with `INCRBY`, exactly and atomically, where
7
+ * `INCRBYFLOAT` would add binary floats. A key's expiry is set in the same
8
+ * `MULTI` as the addition: a key is never left without one by a process that
9
+ * died between the two.
10
+ */
11
+
12
+ import { decimal } from "@c9up/atom";
13
+ import type { BudgetStore } from "./budget.js";
14
+
15
+ /** The commands of a `MULTI` the store queues. */
16
+ export interface RedisBudgetTransaction {
17
+ incrby(key: string, increment: string): RedisBudgetTransaction;
18
+ pexpireat(key: string, unixTimeMilliseconds: number): RedisBudgetTransaction;
19
+ exec(): Promise<[error: Error | null, result: unknown][] | null>;
20
+ }
21
+
22
+ /**
23
+ * What the store needs of a Redis client: an ioredis client and a
24
+ * `@c9up/quasar` connection both fit as they are.
25
+ */
26
+ export interface RedisBudgetClient {
27
+ multi(): RedisBudgetTransaction;
28
+ }
29
+
30
+ export interface RedisBudgetStoreOptions {
31
+ /** Put before every key, to share one database with others. Default: `polaris:budget:`. */
32
+ readonly prefix?: string;
33
+ }
34
+
35
+ /** Spend is counted in billionths of the currency. */
36
+ const DECIMALS = 9;
37
+ const UNIT = "1000000000";
38
+ const STEP = "0.000000001";
39
+
40
+ /**
41
+ * A budget store in Redis, for budgets shared by several instances:
42
+ *
43
+ * budget: { limit, period: 'month', store: redisBudgetStore(() => redis.connection()) }
44
+ *
45
+ * `client` is the client, or a function that answers it, called on each
46
+ * addition: a config file read before the Redis connections are booted can
47
+ * then name one.
48
+ *
49
+ * Amounts are rounded to nine decimals (half away from zero, so a release
50
+ * cancels its reservation exactly), and a key counts exactly up to about nine
51
+ * million units of the currency. The store declares those nine decimals: a
52
+ * reservation rounds its estimate and the final cost to them once each, so a
53
+ * request leaves exactly its rounded cost in the key.
54
+ */
55
+ export function redisBudgetStore(
56
+ client: RedisBudgetClient | (() => RedisBudgetClient),
57
+ options: RedisBudgetStoreOptions = {},
58
+ ): BudgetStore {
59
+ const prefix = options.prefix ?? "polaris:budget:";
60
+ return {
61
+ decimals: DECIMALS,
62
+ async add(key, amount, expiresAt) {
63
+ const name = prefix + key;
64
+ const increment = decimal(amount).times(UNIT).toFixed(0, "half-up");
65
+ const redis = typeof client === "function" ? client() : client;
66
+ let transaction = redis.multi().incrby(name, increment);
67
+ if (expiresAt !== undefined)
68
+ transaction = transaction.pexpireat(name, expiresAt);
69
+ const replies = await transaction.exec();
70
+ if (replies === null) {
71
+ throw new Error(
72
+ `[polaris] the budget transaction on '${name}' was aborted`,
73
+ );
74
+ }
75
+ const [error, total] = replies[0] ?? [null, undefined];
76
+ if (error !== null) throw error;
77
+ if (typeof total !== "number" || !Number.isSafeInteger(total)) {
78
+ throw new Error(
79
+ `[polaris] the spend under '${name}' is past what a budget counts exactly`,
80
+ );
81
+ }
82
+ return decimal(total).times(STEP).toString();
83
+ },
84
+ };
85
+ }
package/src/response.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AssistantPart,
3
3
  ChatResponse,
4
+ ServerContainer,
4
5
  StopReason,
5
6
  ToolCallPart,
6
7
  Usage,
@@ -12,7 +13,13 @@ export interface ResponseInput {
12
13
  readonly model: string;
13
14
  readonly content: readonly AssistantPart[];
14
15
  readonly stopReason: StopReason;
15
- readonly usage?: Partial<Usage>;
16
+ /**
17
+ * The token counts as the provider reported them, unchecked: leave it out
18
+ * when it reported none.
19
+ */
20
+ readonly usage?: { readonly [K in keyof Usage]?: unknown };
21
+ /** The provider's container the reply ran code in. */
22
+ readonly container?: ServerContainer;
16
23
  }
17
24
 
18
25
  /** Usage of nothing yet: what a sum of usages starts from. */
@@ -25,19 +32,57 @@ export const NO_USAGE: Usage = {
25
32
 
26
33
  /** Two usages added up: the cost of a run or of several attempts. */
27
34
  export function addUsage(a: Usage, b: Usage): Usage {
35
+ const serverToolUse = addCounters(a.serverToolUse, b.serverToolUse);
28
36
  return {
29
37
  inputTokens: a.inputTokens + b.inputTokens,
30
38
  outputTokens: a.outputTokens + b.outputTokens,
31
39
  cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
32
40
  cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,
41
+ ...(serverToolUse !== undefined ? { serverToolUse } : {}),
33
42
  };
34
43
  }
35
44
 
45
+ type Counters = NonNullable<Usage["serverToolUse"]>;
46
+
47
+ function addCounters(
48
+ a: Counters | undefined,
49
+ b: Counters | undefined,
50
+ ): Counters | undefined {
51
+ if (a === undefined) return b;
52
+ if (b === undefined) return a;
53
+ const sum: Record<string, number> = { ...a };
54
+ for (const [counter, count] of Object.entries(b)) {
55
+ sum[counter] = (sum[counter] ?? 0) + count;
56
+ }
57
+ return sum;
58
+ }
59
+
60
+ /** Whether `value` can be a count of tokens: a whole number, 0 or more. */
61
+ export function isTokenCount(value: unknown): value is number {
62
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
63
+ }
64
+
65
+ /** Whether every count of `usage` can be one. */
66
+ export function isUsage(usage: Usage): boolean {
67
+ return (
68
+ isTokenCount(usage.inputTokens) &&
69
+ isTokenCount(usage.outputTokens) &&
70
+ isTokenCount(usage.cacheReadTokens) &&
71
+ isTokenCount(usage.cacheWriteTokens)
72
+ );
73
+ }
74
+
36
75
  /**
37
76
  * Build a {@link ChatResponse} from what a provider returned: `text` and
38
- * `toolCalls` are derived from `content`, and missing usage counts are 0.
77
+ * `toolCalls` are derived from `content`.
39
78
  * Drivers build their responses with it, so the derived fields cannot drift
40
79
  * from the content they summarize.
80
+ *
81
+ * Usage the provider did not report, reported without its input or output
82
+ * count, or with a count that cannot be one (negative, fractional, not a
83
+ * number), is marked `usageUnknown`: the wrong count is 0, and the call is
84
+ * not priced from it. Cache counts left out are 0. A count of 0 would
85
+ * otherwise settle the call's budget as free.
41
86
  */
42
87
  export function createResponse(input: ResponseInput): ChatResponse {
43
88
  const text = input.content
@@ -55,11 +100,44 @@ export function createResponse(input: ResponseInput): ChatResponse {
55
100
  text,
56
101
  toolCalls,
57
102
  stopReason: input.stopReason,
58
- usage: {
59
- inputTokens: input.usage?.inputTokens ?? 0,
60
- outputTokens: input.usage?.outputTokens ?? 0,
61
- cacheReadTokens: input.usage?.cacheReadTokens ?? 0,
62
- cacheWriteTokens: input.usage?.cacheWriteTokens ?? 0,
63
- },
103
+ ...readUsage(input.usage),
104
+ ...(input.container !== undefined ? { container: input.container } : {}),
64
105
  };
65
106
  }
107
+
108
+ function readUsage(
109
+ reported: ResponseInput["usage"],
110
+ ): Pick<ChatResponse, "usage" | "usageUnknown"> {
111
+ let unknown = reported === undefined;
112
+ // Input and output are always reported by a provider that reports usage:
113
+ // one left out (a gateway's `usage: {}`) would price the call as free. The
114
+ // cache counts are left out by providers without a cache.
115
+ const count = (value: unknown, required: boolean): number => {
116
+ if (value === undefined && !required) return 0;
117
+ if (isTokenCount(value)) return value;
118
+ unknown = true;
119
+ return 0;
120
+ };
121
+ let usage: Usage = {
122
+ inputTokens: count(reported?.inputTokens, true),
123
+ outputTokens: count(reported?.outputTokens, true),
124
+ cacheReadTokens: count(reported?.cacheReadTokens, false),
125
+ cacheWriteTokens: count(reported?.cacheWriteTokens, false),
126
+ };
127
+ const serverToolUse = readCounters(reported?.serverToolUse);
128
+ if (serverToolUse !== undefined) usage = { ...usage, serverToolUse };
129
+ return unknown ? { usage, usageUnknown: true } : { usage };
130
+ }
131
+
132
+ /**
133
+ * The server tool counters that can be counts. They price nothing, so one
134
+ * that cannot be a count is left out rather than marking the usage unknown.
135
+ */
136
+ function readCounters(reported: unknown): Counters | undefined {
137
+ if (typeof reported !== "object" || reported === null) return undefined;
138
+ const counters: Record<string, number> = {};
139
+ for (const [counter, count] of Object.entries(reported)) {
140
+ if (isTokenCount(count)) counters[counter] = count;
141
+ }
142
+ return Object.keys(counters).length > 0 ? counters : undefined;
143
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The `data:` payloads of a server-sent event stream, lines rejoined across
3
+ * chunks. Linear in the stream's size: a line still open is kept in pieces,
4
+ * joined once its end arrives, and only the text just received is searched
5
+ * for a line end. An event longer than `maxLength` characters raises
6
+ * `tooLong()`: holding it would only feed a runaway or hostile stream.
7
+ */
8
+ export async function* serverSentData(
9
+ body: ReadableStream<Uint8Array>,
10
+ maxLength: number,
11
+ tooLong: () => Error,
12
+ ): AsyncGenerator<string> {
13
+ const reader = body.getReader();
14
+ const decoder = new TextDecoder();
15
+ let pending: string[] = [];
16
+ let data: string[] = [];
17
+ // Characters held for the event being read: its data lines and the open line.
18
+ let held = 0;
19
+ const hold = (length: number): void => {
20
+ held += length;
21
+ if (held > maxLength) throw tooLong();
22
+ };
23
+ // One whole line; the event's payload when the line ends it.
24
+ const line = (raw: string): string | undefined => {
25
+ const text = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
26
+ if (text === "") {
27
+ const event = data.length > 0 ? data.join("\n") : undefined;
28
+ data = [];
29
+ held = 0;
30
+ return event;
31
+ }
32
+ if (text.startsWith("data:")) {
33
+ data.push(text.slice(text.startsWith("data: ") ? 6 : 5));
34
+ } else {
35
+ // A comment or another field: not part of the event's payload.
36
+ held -= raw.length;
37
+ }
38
+ return undefined;
39
+ };
40
+ const read = function* (text: string): Generator<string> {
41
+ let start = 0;
42
+ let newline = text.indexOf("\n");
43
+ while (newline !== -1) {
44
+ hold(newline - start);
45
+ pending.push(text.slice(start, newline));
46
+ const event = line(pending.join(""));
47
+ pending = [];
48
+ if (event !== undefined) yield event;
49
+ start = newline + 1;
50
+ newline = text.indexOf("\n", start);
51
+ }
52
+ if (start < text.length) {
53
+ hold(text.length - start);
54
+ pending.push(text.slice(start));
55
+ }
56
+ };
57
+ try {
58
+ while (true) {
59
+ const { value, done } = await reader.read();
60
+ if (done) break;
61
+ yield* read(decoder.decode(value, { stream: true }));
62
+ }
63
+ yield* read(decoder.decode());
64
+ // The stream may end without the blank line that closes its last event.
65
+ if (pending.length > 0) line(pending.join(""));
66
+ if (data.length > 0) yield data.join("\n");
67
+ } finally {
68
+ await reader.cancel().catch(() => undefined);
69
+ }
70
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The checks every provider's server tools share: what a request's `server`
3
+ * must look like before a driver turns it into its own fields.
4
+ */
5
+
6
+ import type { ChatRequest, EmbedRequest, ServerTools } from "./types.js";
7
+
8
+ const REDACTED = "[redacted]";
9
+
10
+ /** What is wrong with `server`, or undefined when nothing is. */
11
+ export function serverToolsProblem(server: ServerTools): string | undefined {
12
+ if (server.container !== undefined && !isName(server.container)) {
13
+ return "`server.container` must be a container id";
14
+ }
15
+ for (const skill of server.skills ?? []) {
16
+ if (skill.source !== "anthropic" && skill.source !== "custom") {
17
+ return "a server skill's `source` must be 'anthropic' or 'custom'";
18
+ }
19
+ if (!isName(skill.id)) return "a server skill needs an `id`";
20
+ if (skill.version !== undefined && !isName(skill.version)) {
21
+ return `server skill '${skill.id}' has an empty \`version\``;
22
+ }
23
+ }
24
+ const names = new Set<string>();
25
+ for (const mcp of server.mcpServers ?? []) {
26
+ if (!isName(mcp.name)) return "an MCP server needs a `name`";
27
+ if (names.has(mcp.name)) return `two MCP servers are named '${mcp.name}'`;
28
+ names.add(mcp.name);
29
+ if (!isHttps(mcp.url)) {
30
+ return `MCP server '${mcp.name}' needs an https:// \`url\``;
31
+ }
32
+ if (mcp.tools !== undefined && !mcp.tools.every(isName)) {
33
+ return `MCP server '${mcp.name}' lists a tool without a name`;
34
+ }
35
+ }
36
+ return undefined;
37
+ }
38
+
39
+ /** The MCP tokens a request carries, to keep out of errors. */
40
+ export function serverSecrets(server: ServerTools | undefined): string[] {
41
+ return (server?.mcpServers ?? []).flatMap((mcp) =>
42
+ typeof mcp.authorizationToken === "string" ? [mcp.authorizationToken] : [],
43
+ );
44
+ }
45
+
46
+ /** `request` with its MCP tokens replaced, for a log. */
47
+ export function withoutServerSecrets(
48
+ request: ChatRequest | EmbedRequest,
49
+ ): ChatRequest | EmbedRequest {
50
+ if (!("messages" in request)) return request;
51
+ const server = request.server;
52
+ if (server?.mcpServers === undefined) return request;
53
+ return {
54
+ ...request,
55
+ server: {
56
+ ...server,
57
+ mcpServers: server.mcpServers.map((mcp) =>
58
+ mcp.authorizationToken === undefined
59
+ ? mcp
60
+ : { ...mcp, authorizationToken: REDACTED },
61
+ ),
62
+ },
63
+ };
64
+ }
65
+
66
+ function isName(value: unknown): value is string {
67
+ return typeof value === "string" && value.trim() !== "";
68
+ }
69
+
70
+ function isHttps(url: unknown): boolean {
71
+ if (typeof url !== "string") return false;
72
+ try {
73
+ return new URL(url).protocol === "https:";
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The application's tool and skill catalog, ready to import:
3
+ *
4
+ * import catalog from '@c9up/polaris/services/catalog'
5
+ *
6
+ * await polaris.run({ messages, tools: await catalog.tools(['canton_rate']) })
7
+ *
8
+ * Read from `polaris.json` by `PolarisProvider.boot()`.
9
+ */
10
+
11
+ import type { Catalog } from "../catalog/catalog.js";
12
+ import { E_POLARIS_NOT_BOOTED } from "../errors.js";
13
+
14
+ let instance: Catalog | undefined;
15
+
16
+ /** @internal Bind the catalog (called by PolarisProvider). */
17
+ export function setCatalog(value: Catalog): void {
18
+ instance = value;
19
+ }
20
+
21
+ /** @internal Read the catalog, or `undefined` before boot. */
22
+ export function getCatalog(): Catalog | undefined {
23
+ return instance;
24
+ }
25
+
26
+ /** @internal Release the catalog; the caller checks it still owns it. */
27
+ export function clearCatalog(): void {
28
+ instance = undefined;
29
+ }
30
+
31
+ // Never read through: every trap forwards to `instance`.
32
+ const target: Catalog = Object.create(null);
33
+
34
+ const catalog: Catalog = new Proxy(target, {
35
+ get(_target, prop) {
36
+ if (typeof prop === "symbol" || prop === "then") return undefined;
37
+ if (!instance) throw new E_POLARIS_NOT_BOOTED();
38
+ const value = Reflect.get(instance, prop, instance);
39
+ return typeof value === "function" ? value.bind(instance) : value;
40
+ },
41
+ });
42
+
43
+ export default catalog;