@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.
- package/LICENSE +21 -0
- package/README.md +1146 -2
- package/dist/Polaris.d.ts +80 -0
- package/dist/Polaris.d.ts.map +1 -0
- package/dist/Polaris.js +208 -0
- package/dist/Polaris.js.map +1 -0
- package/dist/PolarisClient.d.ts +184 -0
- package/dist/PolarisClient.d.ts.map +1 -0
- package/dist/PolarisClient.js +576 -0
- package/dist/PolarisClient.js.map +1 -0
- package/dist/PolarisProvider.d.ts +40 -0
- package/dist/PolarisProvider.d.ts.map +1 -0
- package/dist/PolarisProvider.js +79 -0
- package/dist/PolarisProvider.js.map +1 -0
- package/dist/augmentations.d.ts +18 -0
- package/dist/augmentations.d.ts.map +1 -0
- package/dist/augmentations.js +9 -0
- package/dist/augmentations.js.map +1 -0
- package/dist/budget.d.ts +77 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +134 -0
- package/dist/budget.js.map +1 -0
- package/dist/catalog/catalog.d.ts +37 -0
- package/dist/catalog/catalog.d.ts.map +1 -0
- package/dist/catalog/catalog.js +145 -0
- package/dist/catalog/catalog.js.map +1 -0
- package/dist/catalog/discover.d.ts +64 -0
- package/dist/catalog/discover.d.ts.map +1 -0
- package/dist/catalog/discover.js +148 -0
- package/dist/catalog/discover.js.map +1 -0
- package/dist/catalog/index.d.ts +8 -0
- package/dist/catalog/index.d.ts.map +1 -0
- package/dist/catalog/index.js +8 -0
- package/dist/catalog/index.js.map +1 -0
- package/dist/commands/index.d.ts +82 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +278 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/cost.d.ts +50 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +131 -0
- package/dist/cost.js.map +1 -0
- package/dist/drivers/anthropic.d.ts +44 -0
- package/dist/drivers/anthropic.d.ts.map +1 -0
- package/dist/drivers/anthropic.js +539 -0
- package/dist/drivers/anthropic.js.map +1 -0
- package/dist/drivers/openai-compatible.d.ts +54 -0
- package/dist/drivers/openai-compatible.d.ts.map +1 -0
- package/dist/drivers/openai-compatible.js +699 -0
- package/dist/drivers/openai-compatible.js.map +1 -0
- package/dist/drivers/status.d.ts +8 -0
- package/dist/drivers/status.d.ts.map +1 -0
- package/dist/drivers/status.js +21 -0
- package/dist/drivers/status.js.map +1 -0
- package/dist/errors.d.ts +79 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +86 -0
- package/dist/errors.js.map +1 -0
- package/dist/extract.d.ts +38 -0
- package/dist/extract.d.ts.map +1 -0
- package/dist/extract.js +144 -0
- package/dist/extract.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/json-schema.d.ts +33 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +508 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/log.d.ts +47 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +35 -0
- package/dist/log.js.map +1 -0
- package/dist/mcp/client.d.ts +81 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +401 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/endpoint.d.ts +54 -0
- package/dist/mcp/endpoint.d.ts.map +1 -0
- package/dist/mcp/endpoint.js +158 -0
- package/dist/mcp/endpoint.js.map +1 -0
- package/dist/mcp/host.d.ts +42 -0
- package/dist/mcp/host.d.ts.map +1 -0
- package/dist/mcp/host.js +111 -0
- package/dist/mcp/host.js.map +1 -0
- package/dist/mcp/http.d.ts +32 -0
- package/dist/mcp/http.d.ts.map +1 -0
- package/dist/mcp/http.js +190 -0
- package/dist/mcp/http.js.map +1 -0
- package/dist/mcp/index.d.ts +23 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +21 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manifest.d.ts +36 -0
- package/dist/mcp/manifest.d.ts.map +1 -0
- package/dist/mcp/manifest.js +40 -0
- package/dist/mcp/manifest.js.map +1 -0
- package/dist/mcp/rpc.d.ts +39 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +149 -0
- package/dist/mcp/rpc.js.map +1 -0
- package/dist/mcp/stdio.d.ts +24 -0
- package/dist/mcp/stdio.d.ts.map +1 -0
- package/dist/mcp/stdio.js +157 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/worker-main.d.ts +6 -0
- package/dist/mcp/worker-main.d.ts.map +1 -0
- package/dist/mcp/worker-main.js +17 -0
- package/dist/mcp/worker-main.js.map +1 -0
- package/dist/mcp/worker.d.ts +54 -0
- package/dist/mcp/worker.d.ts.map +1 -0
- package/dist/mcp/worker.js +166 -0
- package/dist/mcp/worker.js.map +1 -0
- package/dist/meter.d.ts +63 -0
- package/dist/meter.d.ts.map +1 -0
- package/dist/meter.js +94 -0
- package/dist/meter.js.map +1 -0
- package/dist/providers.d.ts +23 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +21 -0
- package/dist/providers.js.map +1 -0
- package/dist/redact.d.ts +12 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +77 -0
- package/dist/redact.js.map +1 -0
- package/dist/redis-budget.d.ts +45 -0
- package/dist/redis-budget.d.ts.map +1 -0
- package/dist/redis-budget.js +56 -0
- package/dist/redis-budget.js.map +1 -0
- package/dist/response.d.ts +39 -0
- package/dist/response.d.ts.map +1 -0
- package/dist/response.js +109 -0
- package/dist/response.js.map +1 -0
- package/dist/schema.d.ts +45 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +43 -0
- package/dist/schema.js.map +1 -0
- package/dist/server-sent.d.ts +9 -0
- package/dist/server-sent.d.ts.map +1 -0
- package/dist/server-sent.js +74 -0
- package/dist/server-sent.js.map +1 -0
- package/dist/server-tools.d.ts +12 -0
- package/dist/server-tools.d.ts.map +1 -0
- package/dist/server-tools.js +71 -0
- package/dist/server-tools.js.map +1 -0
- package/dist/services/catalog.d.ts +19 -0
- package/dist/services/catalog.d.ts.map +1 -0
- package/dist/services/catalog.js +37 -0
- package/dist/services/catalog.js.map +1 -0
- package/dist/services/main.d.ts +23 -0
- package/dist/services/main.d.ts.map +1 -0
- package/dist/services/main.js +43 -0
- package/dist/services/main.js.map +1 -0
- package/dist/skills/folder.d.ts +32 -0
- package/dist/skills/folder.d.ts.map +1 -0
- package/dist/skills/folder.js +170 -0
- package/dist/skills/folder.js.map +1 -0
- package/dist/skills/frontmatter.d.ts +15 -0
- package/dist/skills/frontmatter.d.ts.map +1 -0
- package/dist/skills/frontmatter.js +92 -0
- package/dist/skills/frontmatter.js.map +1 -0
- package/dist/skills/index.d.ts +18 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +18 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/skills/kit.d.ts +39 -0
- package/dist/skills/kit.d.ts.map +1 -0
- package/dist/skills/kit.js +124 -0
- package/dist/skills/kit.js.map +1 -0
- package/dist/skills/skill.d.ts +67 -0
- package/dist/skills/skill.d.ts.map +1 -0
- package/dist/skills/skill.js +114 -0
- package/dist/skills/skill.js.map +1 -0
- package/dist/sse.d.ts +95 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +117 -0
- package/dist/sse.js.map +1 -0
- package/dist/testing/FakeProvider.d.ts +85 -0
- package/dist/testing/FakeProvider.d.ts.map +1 -0
- package/dist/testing/FakeProvider.js +214 -0
- package/dist/testing/FakeProvider.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/tool-modules.d.ts +17 -0
- package/dist/tool-modules.d.ts.map +1 -0
- package/dist/tool-modules.js +43 -0
- package/dist/tool-modules.js.map +1 -0
- package/dist/tools.d.ts +132 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +250 -0
- package/dist/tools.js.map +1 -0
- package/dist/transport.d.ts +23 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +83 -0
- package/dist/transport.js.map +1 -0
- package/dist/types.d.ts +397 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +97 -3
- package/src/Polaris.ts +304 -0
- package/src/PolarisClient.ts +828 -0
- package/src/PolarisProvider.ts +111 -0
- package/src/augmentations.ts +20 -0
- package/src/budget.ts +201 -0
- package/src/catalog/catalog.ts +180 -0
- package/src/catalog/discover.ts +234 -0
- package/src/catalog/index.ts +19 -0
- package/src/commands/index.ts +412 -0
- package/src/cost.ts +176 -0
- package/src/drivers/anthropic.ts +703 -0
- package/src/drivers/openai-compatible.ts +907 -0
- package/src/drivers/status.ts +30 -0
- package/src/errors.ts +202 -0
- package/src/extract.ts +214 -0
- package/src/index.ts +85 -0
- package/src/json-schema.ts +597 -0
- package/src/log.ts +86 -0
- package/src/mcp/client.ts +532 -0
- package/src/mcp/endpoint.ts +229 -0
- package/src/mcp/host.ts +140 -0
- package/src/mcp/http.ts +276 -0
- package/src/mcp/index.ts +51 -0
- package/src/mcp/manifest.ts +73 -0
- package/src/mcp/rpc.ts +197 -0
- package/src/mcp/stdio.ts +190 -0
- package/src/mcp/worker-main.ts +18 -0
- package/src/mcp/worker.ts +212 -0
- package/src/meter.ts +199 -0
- package/src/providers.ts +25 -0
- package/src/redact.ts +81 -0
- package/src/redis-budget.ts +85 -0
- package/src/response.ts +143 -0
- package/src/schema.ts +88 -0
- package/src/server-sent.ts +70 -0
- package/src/server-tools.ts +77 -0
- package/src/services/catalog.ts +43 -0
- package/src/services/main.ts +49 -0
- package/src/skills/folder.ts +231 -0
- package/src/skills/frontmatter.ts +92 -0
- package/src/skills/index.ts +38 -0
- package/src/skills/kit.ts +163 -0
- package/src/skills/skill.ts +171 -0
- package/src/sse.ts +194 -0
- package/src/testing/FakeProvider.ts +322 -0
- package/src/testing/index.ts +12 -0
- package/src/tool-modules.ts +49 -0
- package/src/tools.ts +399 -0
- package/src/transport.ts +107 -0
- package/src/types.ts +434 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PolarisProvider: binds the provider manager built from `config/polaris.ts`.
|
|
3
|
+
*
|
|
4
|
+
* register() binds `polaris.manager`, built on first resolve, unless the
|
|
5
|
+
* application bound its own first.
|
|
6
|
+
* boot() builds it and publishes it to `@c9up/polaris/services/main`;
|
|
7
|
+
* a missing or invalid config fails the boot here. Reads the
|
|
8
|
+
* tool catalog (`polaris.json`, written by `ream polaris:index`),
|
|
9
|
+
* binds it as `polaris.catalog` and publishes it to
|
|
10
|
+
* `@c9up/polaris/services/catalog`.
|
|
11
|
+
* shutdown() releases what it published, if it is still its own.
|
|
12
|
+
*
|
|
13
|
+
* Typed against the slice of ream's `AppContext` it uses rather than importing
|
|
14
|
+
* it, so ream stays an optional peer.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { resolve } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import "./augmentations.js";
|
|
20
|
+
import { Catalog } from "./catalog/catalog.js";
|
|
21
|
+
import { DEFAULT_MANIFEST } from "./catalog/discover.js";
|
|
22
|
+
import { E_POLARIS_MISSING_CONFIG } from "./errors.js";
|
|
23
|
+
import {
|
|
24
|
+
type DeclaredProviders,
|
|
25
|
+
Polaris,
|
|
26
|
+
type PolarisService,
|
|
27
|
+
} from "./Polaris.js";
|
|
28
|
+
import { clearCatalog, getCatalog, setCatalog } from "./services/catalog.js";
|
|
29
|
+
import { clearPolaris, getPolaris, setPolaris } from "./services/main.js";
|
|
30
|
+
import type { PolarisConfig } from "./types.js";
|
|
31
|
+
|
|
32
|
+
const TOKEN = "polaris.manager";
|
|
33
|
+
const CATALOG_TOKEN = "polaris.catalog";
|
|
34
|
+
|
|
35
|
+
interface ContainerLike {
|
|
36
|
+
singleton(token: string | symbol, factory: () => unknown): void;
|
|
37
|
+
/** Async, as in ream: a factory may be async. */
|
|
38
|
+
resolve<T = unknown>(token: string | symbol): Promise<T>;
|
|
39
|
+
has?(token: string | symbol): boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ConfigStoreLike {
|
|
43
|
+
get<T = unknown>(key: string): T | undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface PolarisAppContext {
|
|
47
|
+
container: ContainerLike;
|
|
48
|
+
config: ConfigStoreLike;
|
|
49
|
+
/** The application's root; the manifest's path is resolved from it. */
|
|
50
|
+
appRoot?: URL | undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export default class PolarisProvider {
|
|
54
|
+
readonly #app: PolarisAppContext;
|
|
55
|
+
#owned: PolarisService | undefined;
|
|
56
|
+
#ownedCatalog: Catalog | undefined;
|
|
57
|
+
|
|
58
|
+
constructor(app: PolarisAppContext) {
|
|
59
|
+
this.#app = app;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
register(): void {
|
|
63
|
+
const container = this.#app.container;
|
|
64
|
+
if (container.has?.(TOKEN)) return;
|
|
65
|
+
container.singleton(TOKEN, () => {
|
|
66
|
+
const config =
|
|
67
|
+
this.#app.config.get<PolarisConfig<DeclaredProviders>>("polaris");
|
|
68
|
+
if (config === undefined) throw new E_POLARIS_MISSING_CONFIG();
|
|
69
|
+
return new Polaris(config);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async boot(): Promise<void> {
|
|
74
|
+
const manager = await this.#app.container.resolve<PolarisService>(TOKEN);
|
|
75
|
+
this.#owned = manager;
|
|
76
|
+
setPolaris(manager);
|
|
77
|
+
|
|
78
|
+
const config = this.#app.config.get<{ catalog?: unknown }>("polaris");
|
|
79
|
+
const options = config?.catalog;
|
|
80
|
+
if (options === false) return;
|
|
81
|
+
const manifest =
|
|
82
|
+
typeof options === "object" &&
|
|
83
|
+
options !== null &&
|
|
84
|
+
"manifest" in options &&
|
|
85
|
+
typeof options.manifest === "string"
|
|
86
|
+
? options.manifest
|
|
87
|
+
: DEFAULT_MANIFEST;
|
|
88
|
+
const root =
|
|
89
|
+
this.#app.appRoot === undefined
|
|
90
|
+
? process.cwd()
|
|
91
|
+
: fileURLToPath(this.#app.appRoot);
|
|
92
|
+
const catalog = await Catalog.read(resolve(root, manifest));
|
|
93
|
+
this.#ownedCatalog = catalog;
|
|
94
|
+
this.#app.container.singleton(CATALOG_TOKEN, () => catalog);
|
|
95
|
+
setCatalog(catalog);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async shutdown(): Promise<void> {
|
|
99
|
+
if (this.#owned !== undefined && getPolaris() === this.#owned) {
|
|
100
|
+
clearPolaris();
|
|
101
|
+
}
|
|
102
|
+
this.#owned = undefined;
|
|
103
|
+
if (
|
|
104
|
+
this.#ownedCatalog !== undefined &&
|
|
105
|
+
getCatalog() === this.#ownedCatalog
|
|
106
|
+
) {
|
|
107
|
+
clearCatalog();
|
|
108
|
+
}
|
|
109
|
+
this.#ownedCatalog = undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tell ream's `ContainerBindings` what `container.resolve('polaris.manager')`
|
|
3
|
+
* and `container.resolve('polaris.catalog')` return. Loaded from the package barrel and from the provider, so an
|
|
4
|
+
* application writes no `declare module` of its own for it.
|
|
5
|
+
*
|
|
6
|
+
* Type-only: ream stays an optional peer.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {} from "@c9up/ream/types";
|
|
10
|
+
import type { Catalog } from "./catalog/catalog.js";
|
|
11
|
+
import type { PolarisService } from "./Polaris.js";
|
|
12
|
+
|
|
13
|
+
declare module "@c9up/ream/types" {
|
|
14
|
+
interface ContainerBindings {
|
|
15
|
+
/** The provider manager, bound by `PolarisProvider`. */
|
|
16
|
+
"polaris.manager": PolarisService;
|
|
17
|
+
/** The tool and skill catalog, read from `polaris.json` by `PolarisProvider`. */
|
|
18
|
+
"polaris.catalog": Catalog;
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/budget.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spending limits per scope (a user, a tenant), enforced before a request is
|
|
3
|
+
* sent.
|
|
4
|
+
*
|
|
5
|
+
* A request reserves its estimated cost first: the reservation is added to
|
|
6
|
+
* the scope's spend, and if the total goes past the limit the reservation is
|
|
7
|
+
* taken back and the request refused, before anything leaves the server.
|
|
8
|
+
* Once the reply is in, the reservation is replaced by the real cost.
|
|
9
|
+
* Reserving rather than reading the spend is what keeps two requests sent at
|
|
10
|
+
* the same moment from passing the limit together.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { decimal } from "@c9up/atom";
|
|
14
|
+
import { add, exceeds, isZero, subtract } from "./cost.js";
|
|
15
|
+
import {
|
|
16
|
+
E_POLARIS_BUDGET_EXCEEDED,
|
|
17
|
+
E_POLARIS_INVALID_CONFIG,
|
|
18
|
+
} from "./errors.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Where spend is kept. `add` must be atomic (a Redis `INCRBY`, an SQL
|
|
22
|
+
* `UPDATE … SET spent = spent + ?`): it is what reservations rely on.
|
|
23
|
+
*/
|
|
24
|
+
export interface BudgetStore {
|
|
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;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** How long spend counts before it starts again at zero, in UTC. */
|
|
46
|
+
export type BudgetPeriod = "day" | "month";
|
|
47
|
+
|
|
48
|
+
export interface BudgetConfig {
|
|
49
|
+
/** The limit of a scope, as a decimal string in the pricing currency; `undefined` for none. */
|
|
50
|
+
readonly limit:
|
|
51
|
+
| { readonly [scope: string]: string }
|
|
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;
|
|
58
|
+
/** Where spend is kept. Default: in memory, for one process and its lifetime. */
|
|
59
|
+
readonly store?: BudgetStore;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A spend store in memory: one process, lost on restart. For tests and a single instance. */
|
|
63
|
+
export function memoryBudgetStore(): BudgetStore {
|
|
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;
|
|
67
|
+
return {
|
|
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);
|
|
84
|
+
return total;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
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
|
+
|
|
118
|
+
/** What a reservation hands back to settle it. */
|
|
119
|
+
export interface Reservation {
|
|
120
|
+
/** Replace the reservation by what the request really cost. */
|
|
121
|
+
settle(cost: string): Promise<void>;
|
|
122
|
+
/** Take the whole reservation back (the request was never answered). */
|
|
123
|
+
release(): Promise<void>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const NOTHING: Reservation = {
|
|
127
|
+
settle: async () => undefined,
|
|
128
|
+
release: async () => undefined,
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** Resolve the limit of `scope`. */
|
|
132
|
+
export async function limitOf(
|
|
133
|
+
config: BudgetConfig,
|
|
134
|
+
scope: string,
|
|
135
|
+
): Promise<string | undefined> {
|
|
136
|
+
return typeof config.limit === "function"
|
|
137
|
+
? config.limit(scope)
|
|
138
|
+
: Object.hasOwn(config.limit, scope)
|
|
139
|
+
? config.limit[scope]
|
|
140
|
+
: undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
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.
|
|
151
|
+
*/
|
|
152
|
+
export async function reserve(
|
|
153
|
+
store: BudgetStore,
|
|
154
|
+
scope: string,
|
|
155
|
+
limit: string | undefined,
|
|
156
|
+
estimate: string,
|
|
157
|
+
period?: BudgetPeriod,
|
|
158
|
+
): Promise<Reservation> {
|
|
159
|
+
if (limit === undefined) return NOTHING;
|
|
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);
|
|
168
|
+
if (exceeds(total, limit)) {
|
|
169
|
+
await move(negate(reserved));
|
|
170
|
+
throw new E_POLARIS_BUDGET_EXCEEDED([scope, limit]);
|
|
171
|
+
}
|
|
172
|
+
let open = true;
|
|
173
|
+
return {
|
|
174
|
+
async settle(cost) {
|
|
175
|
+
if (!open) return;
|
|
176
|
+
open = false;
|
|
177
|
+
const difference = subtract(round(cost), reserved);
|
|
178
|
+
if (!isZero(difference)) await move(difference);
|
|
179
|
+
},
|
|
180
|
+
async release() {
|
|
181
|
+
if (!open) return;
|
|
182
|
+
open = false;
|
|
183
|
+
await move(negate(reserved));
|
|
184
|
+
},
|
|
185
|
+
};
|
|
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
|
+
}
|