@c9up/polaris 0.0.0-stage → 0.1.0
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 +542 -2
- package/dist/Polaris.d.ts +76 -0
- package/dist/Polaris.d.ts.map +1 -0
- package/dist/Polaris.js +194 -0
- package/dist/Polaris.js.map +1 -0
- package/dist/PolarisClient.d.ts +136 -0
- package/dist/PolarisClient.d.ts.map +1 -0
- package/dist/PolarisClient.js +408 -0
- package/dist/PolarisClient.js.map +1 -0
- package/dist/PolarisProvider.d.ts +35 -0
- package/dist/PolarisProvider.d.ts.map +1 -0
- package/dist/PolarisProvider.js +47 -0
- package/dist/PolarisProvider.js.map +1 -0
- package/dist/augmentations.d.ts +15 -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 +44 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +67 -0
- package/dist/budget.js.map +1 -0
- package/dist/cost.d.ts +48 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +126 -0
- package/dist/cost.js.map +1 -0
- package/dist/drivers/anthropic.d.ts +39 -0
- package/dist/drivers/anthropic.d.ts.map +1 -0
- package/dist/drivers/anthropic.js +394 -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 +663 -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 +55 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +62 -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 +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/log.d.ts +47 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +33 -0
- package/dist/log.js.map +1 -0
- package/dist/meter.d.ts +57 -0
- package/dist/meter.d.ts.map +1 -0
- package/dist/meter.js +91 -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 +11 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +76 -0
- package/dist/redact.js.map +1 -0
- package/dist/response.d.ts +21 -0
- package/dist/response.d.ts.map +1 -0
- package/dist/response.js +45 -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/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/sse.d.ts +58 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +91 -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 +213 -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/tools.d.ts +68 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +107 -0
- package/dist/tools.js.map +1 -0
- package/dist/transport.d.ts +18 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +68 -0
- package/dist/transport.js.map +1 -0
- package/dist/types.d.ts +293 -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 +76 -3
- package/src/Polaris.ts +280 -0
- package/src/PolarisClient.ts +591 -0
- package/src/PolarisProvider.ts +73 -0
- package/src/augmentations.ts +17 -0
- package/src/budget.ts +101 -0
- package/src/cost.ts +170 -0
- package/src/drivers/anthropic.ts +520 -0
- package/src/drivers/openai-compatible.ts +840 -0
- package/src/drivers/status.ts +30 -0
- package/src/errors.ts +161 -0
- package/src/extract.ts +214 -0
- package/src/index.ts +69 -0
- package/src/log.ts +84 -0
- package/src/meter.ts +188 -0
- package/src/providers.ts +25 -0
- package/src/redact.ts +78 -0
- package/src/response.ts +65 -0
- package/src/schema.ts +88 -0
- package/src/services/main.ts +49 -0
- package/src/sse.ts +128 -0
- package/src/testing/FakeProvider.ts +321 -0
- package/src/testing/index.ts +12 -0
- package/src/tools.ts +166 -0
- package/src/transport.ts +85 -0
- package/src/types.ts +328 -0
package/src/meter.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prices, budgets and the exchange log, around each provider call.
|
|
3
|
+
*
|
|
4
|
+
* Before the call: its price is found, the request's own ceiling (`maxCost`)
|
|
5
|
+
* checked, and its estimated cost reserved on the scope's budget; a refusal
|
|
6
|
+
* sends nothing. After it: the reservation is replaced by the real cost, the
|
|
7
|
+
* cost is put on the response, and the exchange is logged.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
type BudgetConfig,
|
|
12
|
+
type BudgetStore,
|
|
13
|
+
limitOf,
|
|
14
|
+
type Reservation,
|
|
15
|
+
reserve,
|
|
16
|
+
} from "./budget.js";
|
|
17
|
+
import {
|
|
18
|
+
add,
|
|
19
|
+
type Cost,
|
|
20
|
+
costOf,
|
|
21
|
+
exceeds,
|
|
22
|
+
type ModelPrice,
|
|
23
|
+
type Pricing,
|
|
24
|
+
priceFor,
|
|
25
|
+
} from "./cost.js";
|
|
26
|
+
import {
|
|
27
|
+
E_POLARIS_BUDGET_EXCEEDED,
|
|
28
|
+
E_POLARIS_INVALID_REQUEST,
|
|
29
|
+
E_POLARIS_UNKNOWN_PRICE,
|
|
30
|
+
} from "./errors.js";
|
|
31
|
+
import {
|
|
32
|
+
codeOf,
|
|
33
|
+
type ExchangeEntry,
|
|
34
|
+
type ExchangeLog,
|
|
35
|
+
writeLog,
|
|
36
|
+
} from "./log.js";
|
|
37
|
+
import type {
|
|
38
|
+
ChatRequest,
|
|
39
|
+
ChatResponse,
|
|
40
|
+
EmbedRequest,
|
|
41
|
+
EmbedResponse,
|
|
42
|
+
StopReason,
|
|
43
|
+
Usage,
|
|
44
|
+
} from "./types.js";
|
|
45
|
+
|
|
46
|
+
export interface MeterConfig {
|
|
47
|
+
readonly pricing?: Pricing;
|
|
48
|
+
readonly budget?: BudgetConfig & { readonly store: BudgetStore };
|
|
49
|
+
readonly log?: ExchangeLog;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** What polaris needs to meter one call. */
|
|
53
|
+
export interface MeterInput {
|
|
54
|
+
readonly operation: ExchangeEntry["operation"];
|
|
55
|
+
readonly provider: string;
|
|
56
|
+
readonly request: ChatRequest | EmbedRequest;
|
|
57
|
+
/** The model the call is expected to run on: the request's, or the driver's default. */
|
|
58
|
+
readonly model: string | undefined;
|
|
59
|
+
/** Estimate the call's most expensive outcome at `price`, for a budget. */
|
|
60
|
+
estimate(price: ModelPrice): string;
|
|
61
|
+
readonly scope?: string;
|
|
62
|
+
readonly maxCost?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** How a metered call ended. */
|
|
66
|
+
export interface MeterOutcome {
|
|
67
|
+
readonly model: string;
|
|
68
|
+
readonly usage: Usage;
|
|
69
|
+
readonly responseId?: string;
|
|
70
|
+
readonly stopReason?: StopReason;
|
|
71
|
+
readonly response: ChatResponse | EmbedResponse;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** One metered call, opened before it is sent and closed once. */
|
|
75
|
+
export interface Ticket {
|
|
76
|
+
/** The call answered: settle the budget, log, and answer its cost. */
|
|
77
|
+
finish(outcome: MeterOutcome): Promise<Cost | undefined>;
|
|
78
|
+
/**
|
|
79
|
+
* The call failed. `spent` says whether the provider may have billed it
|
|
80
|
+
* (a stream cut after it started): its estimate is then kept on the budget.
|
|
81
|
+
*/
|
|
82
|
+
fail(
|
|
83
|
+
error: unknown,
|
|
84
|
+
options: { cancelled: boolean; spent: boolean },
|
|
85
|
+
): Promise<void>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Open the meter of one call. Throws, before anything is sent, when its budget refuses it. */
|
|
89
|
+
export async function openTicket(
|
|
90
|
+
config: MeterConfig,
|
|
91
|
+
input: MeterInput,
|
|
92
|
+
): Promise<Ticket> {
|
|
93
|
+
const started = Date.now();
|
|
94
|
+
const price = priceFor(config.pricing, input.model);
|
|
95
|
+
const limit =
|
|
96
|
+
input.scope !== undefined && config.budget !== undefined
|
|
97
|
+
? await limitOf(config.budget, input.scope)
|
|
98
|
+
: undefined;
|
|
99
|
+
if (input.scope !== undefined && config.budget === undefined) {
|
|
100
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
101
|
+
"`scope` was given, but the config declares no `budget`",
|
|
102
|
+
]);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let reservation: Reservation | undefined;
|
|
106
|
+
if (limit !== undefined || input.maxCost !== undefined) {
|
|
107
|
+
// A budget cannot be kept without knowing what the model costs: refuse
|
|
108
|
+
// rather than let the call through unmetered.
|
|
109
|
+
if (price === undefined) {
|
|
110
|
+
throw new E_POLARIS_UNKNOWN_PRICE([input.model ?? "(no model)"]);
|
|
111
|
+
}
|
|
112
|
+
const estimate = input.estimate(price);
|
|
113
|
+
if (input.maxCost !== undefined && exceeds(estimate, input.maxCost)) {
|
|
114
|
+
throw new E_POLARIS_BUDGET_EXCEEDED(["this request", input.maxCost]);
|
|
115
|
+
}
|
|
116
|
+
if (input.scope !== undefined && config.budget !== undefined) {
|
|
117
|
+
reservation = await reserve(
|
|
118
|
+
config.budget.store,
|
|
119
|
+
input.scope,
|
|
120
|
+
limit,
|
|
121
|
+
estimate,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const entry = (status: ExchangeEntry["status"]): ExchangeEntry => ({
|
|
127
|
+
provider: input.provider,
|
|
128
|
+
model: input.model,
|
|
129
|
+
operation: input.operation,
|
|
130
|
+
status,
|
|
131
|
+
durationMs: Date.now() - started,
|
|
132
|
+
...(input.scope !== undefined ? { scope: input.scope } : {}),
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
async finish(outcome) {
|
|
137
|
+
const answered = priceFor(config.pricing, outcome.model) ?? price;
|
|
138
|
+
const amount = answered ? costOf(answered, outcome.usage) : undefined;
|
|
139
|
+
const cost =
|
|
140
|
+
amount !== undefined && config.pricing !== undefined
|
|
141
|
+
? { amount, currency: config.pricing.currency }
|
|
142
|
+
: undefined;
|
|
143
|
+
// Without a price for the model that answered, the estimate stays.
|
|
144
|
+
if (reservation !== undefined && amount !== undefined) {
|
|
145
|
+
await reservation.settle(amount);
|
|
146
|
+
}
|
|
147
|
+
await writeLog(
|
|
148
|
+
config.log,
|
|
149
|
+
{
|
|
150
|
+
...entry("ok"),
|
|
151
|
+
model: outcome.model,
|
|
152
|
+
usage: outcome.usage,
|
|
153
|
+
...(cost !== undefined ? { cost } : {}),
|
|
154
|
+
...(outcome.responseId !== undefined
|
|
155
|
+
? { responseId: outcome.responseId }
|
|
156
|
+
: {}),
|
|
157
|
+
...(outcome.stopReason !== undefined
|
|
158
|
+
? { stopReason: outcome.stopReason }
|
|
159
|
+
: {}),
|
|
160
|
+
},
|
|
161
|
+
{ request: input.request, response: outcome.response },
|
|
162
|
+
);
|
|
163
|
+
return cost;
|
|
164
|
+
},
|
|
165
|
+
async fail(error, options) {
|
|
166
|
+
if (reservation !== undefined && !options.spent)
|
|
167
|
+
await reservation.release();
|
|
168
|
+
await writeLog(
|
|
169
|
+
config.log,
|
|
170
|
+
{
|
|
171
|
+
...entry(options.cancelled ? "cancelled" : "error"),
|
|
172
|
+
errorCode: codeOf(error),
|
|
173
|
+
},
|
|
174
|
+
{ request: input.request },
|
|
175
|
+
);
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Two costs added up, exactly, when both are known and in one currency. */
|
|
181
|
+
export function addCost(
|
|
182
|
+
a: Cost | undefined,
|
|
183
|
+
b: Cost | undefined,
|
|
184
|
+
): Cost | undefined {
|
|
185
|
+
if (a === undefined) return b;
|
|
186
|
+
if (b === undefined || a.currency !== b.currency) return a;
|
|
187
|
+
return { amount: add(a.amount, b.amount), currency: a.currency };
|
|
188
|
+
}
|
package/src/providers.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One helper per provider polaris ships, as @adonisjs/mail's `transports`:
|
|
3
|
+
*
|
|
4
|
+
* defineConfig({
|
|
5
|
+
* default: 'claude',
|
|
6
|
+
* providers: {
|
|
7
|
+
* claude: providers.anthropic({ model: 'claude-opus-5-5' }),
|
|
8
|
+
* local: providers.openaiCompatible({ baseURL: 'http://localhost:11434/v1', model: 'qwen3' }),
|
|
9
|
+
* },
|
|
10
|
+
* })
|
|
11
|
+
*
|
|
12
|
+
* A helper returns a factory; the driver is built, and its SDK loaded, the
|
|
13
|
+
* first time the provider is used.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { anthropic } from "./drivers/anthropic.js";
|
|
17
|
+
import { openaiCompatible } from "./drivers/openai-compatible.js";
|
|
18
|
+
|
|
19
|
+
export const providers = {
|
|
20
|
+
anthropic,
|
|
21
|
+
openaiCompatible,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type { AnthropicConfig } from "./drivers/anthropic.js";
|
|
25
|
+
export type { OpenAICompatibleConfig } from "./drivers/openai-compatible.js";
|
package/src/redact.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { E_POLARIS_PROVIDER_FAILED } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
const REDACTED = "[redacted]";
|
|
4
|
+
/** How many values the scan visits before it assumes the worst. */
|
|
5
|
+
const MAX_VISITS = 2_000;
|
|
6
|
+
const MAX_DEPTH = 8;
|
|
7
|
+
|
|
8
|
+
/** Replace every occurrence of each secret in `text`. */
|
|
9
|
+
export function redact(text: string, secrets: readonly string[]): string {
|
|
10
|
+
let out = text;
|
|
11
|
+
for (const secret of secrets) out = out.split(secret).join(REDACTED);
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether `value` holds one of `secrets` anywhere a logger or an error report
|
|
17
|
+
* could reach: its message, stack, cause, own properties, nested objects,
|
|
18
|
+
* arrays and `Headers`.
|
|
19
|
+
*
|
|
20
|
+
* A value too large or too deep to scan in full counts as holding one: the
|
|
21
|
+
* error it came from is then replaced, which loses detail but leaks nothing.
|
|
22
|
+
*/
|
|
23
|
+
function holdsSecret(value: unknown, secrets: readonly string[]): boolean {
|
|
24
|
+
const seen = new Set<object>();
|
|
25
|
+
let visits = 0;
|
|
26
|
+
|
|
27
|
+
const visit = (current: unknown, depth: number): boolean => {
|
|
28
|
+
visits += 1;
|
|
29
|
+
if (visits > MAX_VISITS || depth > MAX_DEPTH) return true;
|
|
30
|
+
if (typeof current === "string") {
|
|
31
|
+
return secrets.some((secret) => current.includes(secret));
|
|
32
|
+
}
|
|
33
|
+
if (typeof current !== "object" || current === null) return false;
|
|
34
|
+
if (seen.has(current)) return false;
|
|
35
|
+
seen.add(current);
|
|
36
|
+
|
|
37
|
+
if (current instanceof Headers) {
|
|
38
|
+
for (const [, header] of current) {
|
|
39
|
+
if (visit(header, depth + 1)) return true;
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (current instanceof Error) {
|
|
44
|
+
if (visit(current.message, depth + 1)) return true;
|
|
45
|
+
if (visit(current.stack, depth + 1)) return true;
|
|
46
|
+
if (visit(current.cause, depth + 1)) return true;
|
|
47
|
+
}
|
|
48
|
+
if (Array.isArray(current)) {
|
|
49
|
+
return current.some((item) => visit(item, depth + 1));
|
|
50
|
+
}
|
|
51
|
+
for (const key of Object.keys(current)) {
|
|
52
|
+
if (visit(Reflect.get(current, key), depth + 1)) return true;
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
return visit(value, 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The error to raise for a failed call that was given `secrets`.
|
|
62
|
+
*
|
|
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.
|
|
66
|
+
*/
|
|
67
|
+
export function scrub(
|
|
68
|
+
error: unknown,
|
|
69
|
+
provider: string,
|
|
70
|
+
secrets: readonly (string | undefined)[],
|
|
71
|
+
): unknown {
|
|
72
|
+
const live = secrets.filter(
|
|
73
|
+
(secret): secret is string => typeof secret === "string" && secret !== "",
|
|
74
|
+
);
|
|
75
|
+
if (live.length === 0 || !holdsSecret(error, live)) return error;
|
|
76
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
77
|
+
return new E_POLARIS_PROVIDER_FAILED([provider, redact(message, live)]);
|
|
78
|
+
}
|
package/src/response.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AssistantPart,
|
|
3
|
+
ChatResponse,
|
|
4
|
+
StopReason,
|
|
5
|
+
ToolCallPart,
|
|
6
|
+
Usage,
|
|
7
|
+
} from "./types.js";
|
|
8
|
+
|
|
9
|
+
export interface ResponseInput {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly provider: string;
|
|
12
|
+
readonly model: string;
|
|
13
|
+
readonly content: readonly AssistantPart[];
|
|
14
|
+
readonly stopReason: StopReason;
|
|
15
|
+
readonly usage?: Partial<Usage>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Usage of nothing yet: what a sum of usages starts from. */
|
|
19
|
+
export const NO_USAGE: Usage = {
|
|
20
|
+
inputTokens: 0,
|
|
21
|
+
outputTokens: 0,
|
|
22
|
+
cacheReadTokens: 0,
|
|
23
|
+
cacheWriteTokens: 0,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Two usages added up: the cost of a run or of several attempts. */
|
|
27
|
+
export function addUsage(a: Usage, b: Usage): Usage {
|
|
28
|
+
return {
|
|
29
|
+
inputTokens: a.inputTokens + b.inputTokens,
|
|
30
|
+
outputTokens: a.outputTokens + b.outputTokens,
|
|
31
|
+
cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,
|
|
32
|
+
cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build a {@link ChatResponse} from what a provider returned: `text` and
|
|
38
|
+
* `toolCalls` are derived from `content`, and missing usage counts are 0.
|
|
39
|
+
* Drivers build their responses with it, so the derived fields cannot drift
|
|
40
|
+
* from the content they summarize.
|
|
41
|
+
*/
|
|
42
|
+
export function createResponse(input: ResponseInput): ChatResponse {
|
|
43
|
+
const text = input.content
|
|
44
|
+
.filter((part) => part.type === "text")
|
|
45
|
+
.map((part) => part.text)
|
|
46
|
+
.join("");
|
|
47
|
+
const toolCalls = input.content.filter(
|
|
48
|
+
(part): part is ToolCallPart => part.type === "tool_call",
|
|
49
|
+
);
|
|
50
|
+
return {
|
|
51
|
+
id: input.id,
|
|
52
|
+
provider: input.provider,
|
|
53
|
+
model: input.model,
|
|
54
|
+
message: { role: "assistant", content: input.content },
|
|
55
|
+
text,
|
|
56
|
+
toolCalls,
|
|
57
|
+
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
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schemas polaris takes, for a tool's input and for a structured answer:
|
|
3
|
+
* anything that implements Standard Schema v1 (validation) and Standard JSON
|
|
4
|
+
* Schema v1 (its JSON Schema), as rune's validators do. polaris imports no
|
|
5
|
+
* validation library.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { E_POLARIS_INVALID_REQUEST } from "./errors.js";
|
|
9
|
+
import type { JsonSchema } from "./types.js";
|
|
10
|
+
|
|
11
|
+
/** One problem a schema found in a value. */
|
|
12
|
+
export interface SchemaIssue {
|
|
13
|
+
readonly message: string;
|
|
14
|
+
readonly path?: readonly unknown[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What a Standard Schema's `validate` answers. */
|
|
18
|
+
export type SchemaResult<Output> =
|
|
19
|
+
| { readonly value: Output; readonly issues?: undefined }
|
|
20
|
+
| { readonly issues: readonly SchemaIssue[] };
|
|
21
|
+
|
|
22
|
+
/** The slice of Standard Schema v1 and Standard JSON Schema v1 polaris uses. */
|
|
23
|
+
export interface StandardSchema<Output = unknown> {
|
|
24
|
+
readonly "~standard": {
|
|
25
|
+
readonly version: 1;
|
|
26
|
+
readonly vendor: string;
|
|
27
|
+
validate(
|
|
28
|
+
value: unknown,
|
|
29
|
+
): SchemaResult<Output> | Promise<SchemaResult<Output>>;
|
|
30
|
+
readonly jsonSchema: {
|
|
31
|
+
input(options?: { readonly target?: string }): Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The value a schema hands back once it accepted the input. */
|
|
37
|
+
export type SchemaOutput<S extends StandardSchema> = Extract<
|
|
38
|
+
Awaited<ReturnType<S["~standard"]["validate"]>>,
|
|
39
|
+
{ readonly value: unknown }
|
|
40
|
+
>["value"];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The JSON Schema of what `schema` accepts, checked to describe an object
|
|
44
|
+
* (what providers take for a tool's input and a structured answer), without
|
|
45
|
+
* its `$schema` key, which some providers refuse.
|
|
46
|
+
*/
|
|
47
|
+
export function objectJsonSchema(
|
|
48
|
+
schema: StandardSchema,
|
|
49
|
+
label: string,
|
|
50
|
+
): JsonSchema {
|
|
51
|
+
const standard = schema["~standard"];
|
|
52
|
+
if (
|
|
53
|
+
standard?.version !== 1 ||
|
|
54
|
+
typeof standard.validate !== "function" ||
|
|
55
|
+
typeof standard.jsonSchema?.input !== "function"
|
|
56
|
+
) {
|
|
57
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
58
|
+
`the schema of ${label} must implement Standard Schema v1 and Standard JSON Schema v1 (a rune schema does)`,
|
|
59
|
+
]);
|
|
60
|
+
}
|
|
61
|
+
const jsonSchema: JsonSchema = Object.fromEntries(
|
|
62
|
+
Object.entries(standard.jsonSchema.input()).filter(
|
|
63
|
+
([key]) => key !== "$schema",
|
|
64
|
+
),
|
|
65
|
+
);
|
|
66
|
+
if (jsonSchema.type !== "object") {
|
|
67
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
68
|
+
`the schema of ${label} must describe an object`,
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
return jsonSchema;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `canton: too short; age: not a number`: issues as one line a model can act on. */
|
|
75
|
+
export function describeIssues(issues: readonly SchemaIssue[]): string {
|
|
76
|
+
return issues
|
|
77
|
+
.map((issue) => {
|
|
78
|
+
const path = (issue.path ?? [])
|
|
79
|
+
.map((segment) =>
|
|
80
|
+
typeof segment === "object" && segment !== null && "key" in segment
|
|
81
|
+
? String(segment.key)
|
|
82
|
+
: String(segment),
|
|
83
|
+
)
|
|
84
|
+
.join(".");
|
|
85
|
+
return path === "" ? issue.message : `${path}: ${issue.message}`;
|
|
86
|
+
})
|
|
87
|
+
.join("; ");
|
|
88
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The application's polaris manager, ready to import:
|
|
3
|
+
*
|
|
4
|
+
* import polaris from '@c9up/polaris/services/main'
|
|
5
|
+
*
|
|
6
|
+
* const reply = await polaris.use('claude').chat({ messages })
|
|
7
|
+
*
|
|
8
|
+
* Bound by `PolarisProvider.boot()`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { E_POLARIS_NOT_BOOTED } from "../errors.js";
|
|
12
|
+
import type { PolarisService } from "../Polaris.js";
|
|
13
|
+
|
|
14
|
+
let instance: PolarisService | undefined;
|
|
15
|
+
|
|
16
|
+
/** @internal Bind the singleton (called by PolarisProvider). */
|
|
17
|
+
export function setPolaris(value: PolarisService): void {
|
|
18
|
+
instance = value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @internal Read the singleton, or `undefined` before boot. */
|
|
22
|
+
export function getPolaris(): PolarisService | undefined {
|
|
23
|
+
return instance;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @internal Release the singleton, so a stopped application leaves no manager
|
|
28
|
+
* reachable here. The caller checks it still owns it: two applications share
|
|
29
|
+
* this module in one process.
|
|
30
|
+
*/
|
|
31
|
+
export function clearPolaris(): void {
|
|
32
|
+
instance = undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Never read through: every trap forwards to `instance`.
|
|
36
|
+
const target: PolarisService = Object.create(null);
|
|
37
|
+
|
|
38
|
+
const polaris: PolarisService = new Proxy(target, {
|
|
39
|
+
get(_target, prop) {
|
|
40
|
+
// A module loader reads `then` and a few symbols on what it imports,
|
|
41
|
+
// before anyone uses it. Throwing there would crash the import itself.
|
|
42
|
+
if (typeof prop === "symbol" || prop === "then") return undefined;
|
|
43
|
+
if (!instance) throw new E_POLARIS_NOT_BOOTED();
|
|
44
|
+
const value = Reflect.get(instance, prop, instance);
|
|
45
|
+
return typeof value === "function" ? value.bind(instance) : value;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export default polaris;
|
package/src/sse.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A reply streamed to the browser as Server-Sent Events, over the response of
|
|
3
|
+
* the request that asked for it (ream's `ctx.response.sse()`).
|
|
4
|
+
*
|
|
5
|
+
* That stream, not a relay channel, is the transport here: it belongs to the
|
|
6
|
+
* one client waiting for this reply, and its close is a sure sign the client
|
|
7
|
+
* left, on every instance, which is what lets the provider request be
|
|
8
|
+
* cancelled. A relay channel reaches whoever subscribed, wherever they are,
|
|
9
|
+
* but cannot tell polaris that nobody listens any more.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { codeOf } from "./log.js";
|
|
13
|
+
import type { ChatResponse, StreamEvent, Usage } from "./types.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What polaris needs of an SSE stream: ream's `SseStream` fits as it is, and
|
|
17
|
+
* so does relay's.
|
|
18
|
+
*/
|
|
19
|
+
export interface SseSink {
|
|
20
|
+
/** Send one named event. Answers `false` once the stream is closed. */
|
|
21
|
+
send(event: string, data: unknown): Promise<boolean> | boolean;
|
|
22
|
+
/** Called once when the stream closes, whoever closed it. */
|
|
23
|
+
onClose(callback: () => void): void;
|
|
24
|
+
/** Close the stream from the server. */
|
|
25
|
+
end(): Promise<void> | void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** How a streamed reply ended. */
|
|
29
|
+
export type StreamToResult =
|
|
30
|
+
| { readonly status: "done"; readonly response: ChatResponse }
|
|
31
|
+
/** The client went away; the provider request was cancelled. */
|
|
32
|
+
| { readonly status: "client_left" }
|
|
33
|
+
/** The call failed; the client was sent an `error` event with its code. */
|
|
34
|
+
| { readonly status: "failed"; readonly error: unknown };
|
|
35
|
+
|
|
36
|
+
/** The `done` event's data: what a page needs, none of the provider's raw blocks. */
|
|
37
|
+
export interface DoneEventData {
|
|
38
|
+
readonly id: string;
|
|
39
|
+
readonly provider: string;
|
|
40
|
+
readonly model: string;
|
|
41
|
+
readonly text: string;
|
|
42
|
+
readonly stopReason: ChatResponse["stopReason"];
|
|
43
|
+
readonly usage: Usage;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Why polaris cancelled the provider request: the client closed the stream. */
|
|
47
|
+
export class ClientLeft extends Error {
|
|
48
|
+
constructor() {
|
|
49
|
+
super("the client closed the stream");
|
|
50
|
+
this.name = "ClientLeft";
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Forward `events` to `sink` as named events (`text`, `reasoning`,
|
|
56
|
+
* `tool_call`, `done`, `error`, after `prefix`), and end the stream when the
|
|
57
|
+
* reply is complete. `leave` is aborted when the client closes the stream.
|
|
58
|
+
* Never rejects: every outcome is in the result.
|
|
59
|
+
*/
|
|
60
|
+
export async function pipeToSse(
|
|
61
|
+
events: AsyncIterable<StreamEvent>,
|
|
62
|
+
sink: SseSink,
|
|
63
|
+
leave: AbortController,
|
|
64
|
+
prefix: string,
|
|
65
|
+
): Promise<StreamToResult> {
|
|
66
|
+
try {
|
|
67
|
+
for await (const event of events) {
|
|
68
|
+
if (leave.signal.aborted) break;
|
|
69
|
+
const sent = await sink.send(`${prefix}${event.type}`, dataOf(event));
|
|
70
|
+
if (!sent) {
|
|
71
|
+
leave.abort(new ClientLeft());
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
if (event.type === "done") {
|
|
75
|
+
await settle(() => sink.end());
|
|
76
|
+
return { status: "done", response: event.response };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Leaving the loop early cancels the provider request.
|
|
80
|
+
return { status: "client_left" };
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (leave.signal.aborted) return { status: "client_left" };
|
|
83
|
+
// Only the code goes to the page: a message can carry the provider's
|
|
84
|
+
// details, or the application's.
|
|
85
|
+
await settle(() => sink.send(`${prefix}error`, { code: codeOf(error) }));
|
|
86
|
+
await settle(() => sink.end());
|
|
87
|
+
return { status: "failed", error };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Run `step` and swallow its failure: the stream is already closing, and the
|
|
93
|
+
* caller of `streamTo()` usually does not await it (a ream route must return
|
|
94
|
+
* before its stream starts), so a rejection would go unhandled.
|
|
95
|
+
*/
|
|
96
|
+
async function settle(step: () => unknown): Promise<void> {
|
|
97
|
+
try {
|
|
98
|
+
await step();
|
|
99
|
+
} catch {
|
|
100
|
+
// The stream is gone; there is nobody left to tell.
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function dataOf(event: StreamEvent): unknown {
|
|
105
|
+
switch (event.type) {
|
|
106
|
+
case "text":
|
|
107
|
+
case "reasoning":
|
|
108
|
+
return { text: event.text };
|
|
109
|
+
case "tool_call":
|
|
110
|
+
return {
|
|
111
|
+
id: event.call.id,
|
|
112
|
+
name: event.call.name,
|
|
113
|
+
input: event.call.input,
|
|
114
|
+
};
|
|
115
|
+
case "done": {
|
|
116
|
+
const { id, provider, model, text, stopReason, usage } = event.response;
|
|
117
|
+
const data: DoneEventData = {
|
|
118
|
+
id,
|
|
119
|
+
provider,
|
|
120
|
+
model,
|
|
121
|
+
text,
|
|
122
|
+
stopReason,
|
|
123
|
+
usage,
|
|
124
|
+
};
|
|
125
|
+
return data;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|