pi-dent-purse 0.2.0 → 0.2.2
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/README.md +63 -5
- package/index.ts +5 -5
- package/lib/adapter.ts +30 -30
- package/lib/adapters/amd.ts +19 -19
- package/lib/adapters/anthropic.ts +38 -38
- package/lib/adapters/antigravity.ts +15 -16
- package/lib/adapters/deepseek.ts +20 -20
- package/lib/adapters/exa.ts +25 -25
- package/lib/adapters/google.ts +64 -64
- package/lib/adapters/headers.ts +1 -1
- package/lib/adapters/index.ts +1 -1
- package/lib/adapters/openai-codex.ts +6 -6
- package/lib/adapters/zai.ts +23 -23
- package/lib/config.ts +45 -45
- package/lib/guidance.ts +1 -1
- package/lib/prices.ts +14 -14
- package/lib/protocol.ts +13 -13
- package/lib/refresh.ts +24 -24
- package/lib/state.ts +43 -44
- package/lib/transport.ts +12 -13
- package/lib/ui.ts +15 -13
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The OpenAI Codex adapter (specs/adapter-openai-codex.md): the ChatGPT subscription usage
|
|
3
3
|
* endpoint read with the OAuth credential. The module performs no I/O; transport, credentials,
|
|
4
|
-
* and clock arrive as dependencies (adapter-contract.md
|
|
4
|
+
* and clock arrive as dependencies (specs/adapter-contract.md#boundary). `run` never rejects.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type { Adapter, AdapterDependencies, TransportOutcome } from "../adapter.ts";
|
|
@@ -14,17 +14,17 @@ import {
|
|
|
14
14
|
type LimitWindowCapture,
|
|
15
15
|
} from "../state.ts";
|
|
16
16
|
|
|
17
|
-
/** Provider origin and host allowlist (
|
|
17
|
+
/** Provider origin and host allowlist (specs/adapter-openai-codex.md#constants). */
|
|
18
18
|
const PROVIDER_ORIGIN = "https://chatgpt.com";
|
|
19
19
|
const HOST_ALLOWLIST: readonly string[] = [PROVIDER_ORIGIN];
|
|
20
20
|
|
|
21
|
-
/** The usage endpoint (
|
|
21
|
+
/** The usage endpoint (specs/adapter-openai-codex.md#usage-request). */
|
|
22
22
|
const USAGE_URL = `${PROVIDER_ORIGIN}/backend-api/wham/usage`;
|
|
23
23
|
|
|
24
|
-
/** Body cap, 16 KiB (
|
|
24
|
+
/** Body cap, 16 KiB (specs/adapter-openai-codex.md#constants). */
|
|
25
25
|
const BODY_CAP = 16 * 1024;
|
|
26
26
|
|
|
27
|
-
/** The `rate_limit` windows, in order (
|
|
27
|
+
/** The `rate_limit` windows, in order (specs/adapter-openai-codex.md#limits). */
|
|
28
28
|
const WINDOW_MAPPINGS = [
|
|
29
29
|
{ key: "primary_window", id: "five-hour", label: "5h", windowSeconds: 18000 },
|
|
30
30
|
{ key: "secondary_window", id: "weekly", label: "7d", windowSeconds: 604800 },
|
|
@@ -44,7 +44,7 @@ function parseBody(body: string): Record<string, unknown> | null {
|
|
|
44
44
|
return isObject(parsed) ? parsed : null;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
/** The windows of `rate_limit` (
|
|
47
|
+
/** The windows of `rate_limit` (specs/adapter-openai-codex.md#limits). */
|
|
48
48
|
function windows(body: Record<string, unknown>): LimitWindowCapture[] {
|
|
49
49
|
const rateLimit = body["rate_limit"];
|
|
50
50
|
if (!isObject(rateLimit)) return [];
|
package/lib/adapters/zai.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Z.ai adapter for provider `zai` (specs/adapter-zai.md): the GLM Coding Plan quota windows
|
|
3
|
-
* (
|
|
3
|
+
* (specs/adapter-zai.md#limits), the subscription plan (specs/adapter-zai.md#plan), and the account balance (specs/adapter-zai.md#balance). The
|
|
4
4
|
* adapter performs no I/O of its own; transport, credentials, and clock arrive in
|
|
5
5
|
* `AdapterDependencies`. Vendor data is untrusted and `run` never rejects.
|
|
6
6
|
*/
|
|
@@ -24,33 +24,33 @@ import {
|
|
|
24
24
|
type Unit,
|
|
25
25
|
} from "../state.ts";
|
|
26
26
|
|
|
27
|
-
/** Provider origin and host allowlist (
|
|
27
|
+
/** Provider origin and host allowlist (specs/adapter-zai.md#constants). */
|
|
28
28
|
const PROVIDER_ORIGIN = "https://api.z.ai";
|
|
29
29
|
|
|
30
|
-
/** Host allowlist of the adapter (
|
|
30
|
+
/** Host allowlist of the adapter (specs/adapter-zai.md#constants). */
|
|
31
31
|
const HOST_ALLOWLIST: readonly string[] = [PROVIDER_ORIGIN];
|
|
32
32
|
|
|
33
|
-
/** Body cap of one response, 64 KiB (
|
|
33
|
+
/** Body cap of one response, 64 KiB (specs/adapter-zai.md#constants). */
|
|
34
34
|
const BODY_CAP = 64 * 1024;
|
|
35
35
|
|
|
36
|
-
/** Freshness period, 300 seconds (
|
|
36
|
+
/** Freshness period, 300 seconds (specs/adapter-zai.md#constants). */
|
|
37
37
|
const FRESHNESS_SECONDS = 300;
|
|
38
38
|
|
|
39
|
-
/** The three endpoints of
|
|
39
|
+
/** The three endpoints of specs/adapter-zai.md#requests. */
|
|
40
40
|
const QUOTA_URL = `${PROVIDER_ORIGIN}/api/monitor/usage/quota/limit`;
|
|
41
41
|
const PLAN_URL = `${PROVIDER_ORIGIN}/api/biz/subscription/list`;
|
|
42
42
|
const BALANCE_URL = `${PROVIDER_ORIGIN}/api/biz/account/query-customer-account-report`;
|
|
43
43
|
|
|
44
|
-
/** The five-hour window default when the quota entry carries no numeric `number` (
|
|
44
|
+
/** The five-hour window default when the quota entry carries no numeric `number` (specs/adapter-zai.md#limits). */
|
|
45
45
|
const FIVE_HOUR_DEFAULT_SECONDS = 18000;
|
|
46
46
|
|
|
47
|
-
/** The weekly window length (
|
|
47
|
+
/** The weekly window length (specs/adapter-zai.md#limits). */
|
|
48
48
|
const WEEKLY_SECONDS = 604800;
|
|
49
49
|
|
|
50
|
-
/** Outcome of one request that passed the
|
|
50
|
+
/** Outcome of one request that passed the specs/adapter-zai.md#requests envelope; `data` is unread. */
|
|
51
51
|
type EndpointOutcome = { ok: true; data: unknown } | { ok: false; failure: AdapterFailure };
|
|
52
52
|
|
|
53
|
-
/** A limit window's fixed identification and window length (
|
|
53
|
+
/** A limit window's fixed identification and window length (specs/adapter-zai.md#limits). */
|
|
54
54
|
interface WindowMapping {
|
|
55
55
|
id: string;
|
|
56
56
|
label: string;
|
|
@@ -59,7 +59,7 @@ interface WindowMapping {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
/**
|
|
62
|
-
* The `authorization` value every request sends (
|
|
62
|
+
* The `authorization` value every request sends (specs/adapter-zai.md#requests). specs/adapter-zai.md#gaps records as `live check`
|
|
63
63
|
* whether the key is accepted with this `Bearer` prefix or raw; the choice is made here only.
|
|
64
64
|
*/
|
|
65
65
|
function authorizationHeader(apiKey: string): string {
|
|
@@ -81,7 +81,7 @@ function asArray(value: unknown): readonly unknown[] | null {
|
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
/**
|
|
84
|
-
* Reads the
|
|
84
|
+
* Reads the specs/adapter-zai.md#requests envelope: the body must be an object; unless `success` is `true` and
|
|
85
85
|
* `code` is `200` the request fails with `vendor-error`.
|
|
86
86
|
*/
|
|
87
87
|
function readEnvelope(body: string): EndpointOutcome {
|
|
@@ -98,7 +98,7 @@ function readEnvelope(body: string): EndpointOutcome {
|
|
|
98
98
|
return { ok: true, data: parsed.data };
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
/** One GET of
|
|
101
|
+
/** One GET of specs/adapter-zai.md#requests under the transport contract (specs/adapter-contract.md#transport). */
|
|
102
102
|
async function requestEnvelope(
|
|
103
103
|
deps: AdapterDependencies,
|
|
104
104
|
url: string,
|
|
@@ -117,7 +117,7 @@ async function requestEnvelope(
|
|
|
117
117
|
return readEnvelope(outcome.body);
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
/** The fixed identification and window length of one quota element, else `null` (
|
|
120
|
+
/** The fixed identification and window length of one quota element, else `null` (specs/adapter-zai.md#limits). */
|
|
121
121
|
function windowMapping(element: Record<string, unknown>): WindowMapping | null {
|
|
122
122
|
const type = element.type;
|
|
123
123
|
if (type === "CREDIT_LIMIT" || type === "TOKENS_LIMIT") {
|
|
@@ -141,7 +141,7 @@ function windowMapping(element: Record<string, unknown>): WindowMapping | null {
|
|
|
141
141
|
return null;
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
/** First instant of the next calendar month in UTC (
|
|
144
|
+
/** First instant of the next calendar month in UTC (specs/adapter-zai.md#limits). */
|
|
145
145
|
function firstOfNextMonthUtc(now: number): number | null {
|
|
146
146
|
if (!Number.isFinite(now)) return null;
|
|
147
147
|
const date = new Date(now);
|
|
@@ -149,7 +149,7 @@ function firstOfNextMonthUtc(now: number): number | null {
|
|
|
149
149
|
return Number.isFinite(first) ? first : null;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
/** A window's reset time: `nextResetTime`, else the monthly fallback (
|
|
152
|
+
/** A window's reset time: `nextResetTime`, else the monthly fallback (specs/adapter-zai.md#limits). */
|
|
153
153
|
function resetTime(id: string, value: unknown, now: number): number | null {
|
|
154
154
|
const reported = finiteNumber(value);
|
|
155
155
|
if (reported !== null) return reported;
|
|
@@ -157,7 +157,7 @@ function resetTime(id: string, value: unknown, now: number): number | null {
|
|
|
157
157
|
return firstOfNextMonthUtc(now);
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
-
/** One quota element as a window, else `null` when the element is skipped (
|
|
160
|
+
/** One quota element as a window, else `null` when the element is skipped (specs/adapter-zai.md#limits). */
|
|
161
161
|
function quotaWindow(value: unknown, now: number): LimitWindowCapture | null {
|
|
162
162
|
if (!isRecord(value)) return null;
|
|
163
163
|
const mapping = windowMapping(value);
|
|
@@ -192,7 +192,7 @@ function quotaWindows(quotaData: unknown, now: number): LimitWindowCapture[] {
|
|
|
192
192
|
return windows;
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
/** The `limits` facet (
|
|
195
|
+
/** The `limits` facet (specs/adapter-zai.md#limits). */
|
|
196
196
|
function limitsFacet(quota: EndpointOutcome, now: number): Facet<LimitWindowCapture[]> {
|
|
197
197
|
if (!quota.ok) return { state: "unavailable", reason: quota.failure.reason };
|
|
198
198
|
const windows = quotaWindows(quota.data, now);
|
|
@@ -200,7 +200,7 @@ function limitsFacet(quota: EndpointOutcome, now: number): Facet<LimitWindowCapt
|
|
|
200
200
|
return { state: "known", value: windows };
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
-
/** The `productName` of the first `VALID` plan object, else `null` (
|
|
203
|
+
/** The `productName` of the first `VALID` plan object, else `null` (specs/adapter-zai.md#plan). */
|
|
204
204
|
function validPlanName(planData: unknown): string | null {
|
|
205
205
|
const plans = asArray(planData);
|
|
206
206
|
if (plans === null) return null;
|
|
@@ -211,13 +211,13 @@ function validPlanName(planData: unknown): string | null {
|
|
|
211
211
|
return null;
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
-
/** The quota body's `data.level`, else `null` (
|
|
214
|
+
/** The quota body's `data.level`, else `null` (specs/adapter-zai.md#plan). */
|
|
215
215
|
function quotaLevel(quotaData: unknown): string | null {
|
|
216
216
|
const data = isRecord(quotaData) ? quotaData : null;
|
|
217
217
|
return data === null ? null : cleanVendorString(data.level);
|
|
218
218
|
}
|
|
219
219
|
|
|
220
|
-
/** The `plan` facet (
|
|
220
|
+
/** The `plan` facet (specs/adapter-zai.md#plan). */
|
|
221
221
|
function planFacet(plan: EndpointOutcome, quota: EndpointOutcome): Facet<string> {
|
|
222
222
|
const fromPlan = plan.ok ? validPlanName(plan.data) : null;
|
|
223
223
|
if (fromPlan !== null) return { state: "known", value: fromPlan };
|
|
@@ -227,7 +227,7 @@ function planFacet(plan: EndpointOutcome, quota: EndpointOutcome): Facet<string>
|
|
|
227
227
|
return { state: "unavailable", reason: "empty-response" };
|
|
228
228
|
}
|
|
229
229
|
|
|
230
|
-
/** The `balance` facet (
|
|
230
|
+
/** The `balance` facet (specs/adapter-zai.md#balance). */
|
|
231
231
|
function balanceFacet(balance: EndpointOutcome): Facet<BalanceItemCapture[]> {
|
|
232
232
|
if (!balance.ok) return { state: "unavailable", reason: balance.failure.reason };
|
|
233
233
|
const data = isRecord(balance.data) ? balance.data : null;
|
|
@@ -239,7 +239,7 @@ function balanceFacet(balance: EndpointOutcome): Facet<BalanceItemCapture[]> {
|
|
|
239
239
|
};
|
|
240
240
|
}
|
|
241
241
|
|
|
242
|
-
/** One refresh: the three concurrent requests and the facets (adapter-contract.md
|
|
242
|
+
/** One refresh: the three concurrent requests and the facets (specs/adapter-contract.md#credentials ran before). */
|
|
243
243
|
async function refresh(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult> {
|
|
244
244
|
const credentials = await deps.credentials();
|
|
245
245
|
if (credentials === undefined) return { reason: "no-credentials" };
|
package/lib/config.ts
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
* `parseConfiguration` is pure: file text, path, and environment values in; the loaded
|
|
6
6
|
* configuration and its diagnostics out. `loadConfiguration` adds the one effect, reading the
|
|
7
7
|
* file, through an injectable reader so tests need no home directory. The caller keeps the
|
|
8
|
-
* result as the boot window's image; the file is read once there (
|
|
8
|
+
* result as the boot window's image; the file is read once there (specs/config-file.md#file).
|
|
9
9
|
*
|
|
10
10
|
* Not fixed by the spec: the shape of a diagnostic and the message texts; here a diagnostic
|
|
11
|
-
* carries the file path and the key path it names (
|
|
11
|
+
* carries the file path and the key path it names (specs/config-file.md#diagnostics), and its `message` is
|
|
12
12
|
* `"<file>: <key path>: <problem>"`, ready to be reported as `purse: <message>`.
|
|
13
13
|
*/
|
|
14
14
|
|
|
@@ -32,58 +32,58 @@ import {
|
|
|
32
32
|
type SeverityThresholds,
|
|
33
33
|
} from "./state.ts";
|
|
34
34
|
|
|
35
|
-
/** One rate field's override: a number ≥ 0, or `null` for unknown (
|
|
35
|
+
/** One rate field's override: a number ≥ 0, or `null` for unknown (specs/config-file.md#keys, specs/prices.md#derivation). */
|
|
36
36
|
export type RateOverrides = { [Field in keyof Rates]?: number | null };
|
|
37
37
|
|
|
38
|
-
/** A price schedule without its computed fields (
|
|
38
|
+
/** A price schedule without its computed fields (specs/config-file.md#keys, specs/prices.md#schedule). */
|
|
39
39
|
export type ScheduleConfig = Omit<Schedule, "active" | "changesAt">;
|
|
40
40
|
|
|
41
41
|
/**
|
|
42
|
-
* One provider's configuration entry (
|
|
42
|
+
* One provider's configuration entry (specs/config-file.md#keys): the adapter's `ProviderConfiguration`
|
|
43
43
|
* (entry-derivation settings plus `project`) and the price keys.
|
|
44
44
|
*/
|
|
45
45
|
export interface ProviderConfig extends ProviderConfiguration {
|
|
46
|
-
/** Rate overrides keyed by model id (prices.md
|
|
46
|
+
/** Rate overrides keyed by model id (specs/prices.md#derivation). */
|
|
47
47
|
prices?: Record<string, RateOverrides>;
|
|
48
|
-
/** The price schedule, or `null` to disable the built-in one (prices.md
|
|
48
|
+
/** The price schedule, or `null` to disable the built-in one (specs/prices.md#schedule). */
|
|
49
49
|
schedule?: ScheduleConfig | null;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
/** A problem reported to the user about the configuration file or environment (
|
|
52
|
+
/** A problem reported to the user about the configuration file or environment (specs/config-file.md#diagnostics). */
|
|
53
53
|
export interface Diagnostic {
|
|
54
54
|
/** The path the diagnostic names: the configuration file, or the offending `PURSE_CONF` value. */
|
|
55
55
|
file: string;
|
|
56
56
|
/** The key path it names, e.g. `providers.zai.ttlSeconds`; `""` when there is no key. */
|
|
57
57
|
keyPath: string;
|
|
58
|
-
/** The message, reported as `purse: <message>` (
|
|
58
|
+
/** The message, reported as `purse: <message>` (specs/config-file.md#diagnostics). */
|
|
59
59
|
message: string;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
/** The environment values configuration reads (
|
|
62
|
+
/** The environment values configuration reads (specs/config-file.md#environment). */
|
|
63
63
|
export interface ConfigurationEnv {
|
|
64
64
|
PURSE_CONF?: string | undefined;
|
|
65
65
|
PURSE_OFFLINE?: string | undefined;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
/** The configuration file's path, with any diagnostic about `PURSE_CONF` (
|
|
68
|
+
/** The configuration file's path, with any diagnostic about `PURSE_CONF` (specs/config-file.md#file, specs/config-file.md#environment). */
|
|
69
69
|
export interface ConfigurationLocation {
|
|
70
70
|
path: string;
|
|
71
71
|
diagnostics: Diagnostic[];
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
/** The configuration loaded for a boot window (
|
|
74
|
+
/** The configuration loaded for a boot window (specs/config-file.md#file, specs/config-file.md#keys, specs/config-file.md#environment). */
|
|
75
75
|
export interface LoadedConfiguration {
|
|
76
|
-
/** The file the values came from; read once per boot window (
|
|
76
|
+
/** The file the values came from; read once per boot window (specs/config-file.md#file). */
|
|
77
77
|
path: string;
|
|
78
|
-
/** Per-provider settings; `{}` when absent (
|
|
78
|
+
/** Per-provider settings; `{}` when absent (specs/config-file.md#keys). */
|
|
79
79
|
providers: Record<string, ProviderConfig>;
|
|
80
|
-
/** Percent thresholds; the defaults when absent or invalid (
|
|
80
|
+
/** Percent thresholds; the defaults when absent or invalid (specs/config-file.md#keys). */
|
|
81
81
|
severity: SeverityThresholds;
|
|
82
|
-
/** Whether the status line is enabled (
|
|
82
|
+
/** Whether the status line is enabled (specs/config-file.md#keys). */
|
|
83
83
|
statusLine: boolean;
|
|
84
|
-
/** `PURSE_OFFLINE` is `1`: refreshes are disabled (
|
|
84
|
+
/** `PURSE_OFFLINE` is `1`: refreshes are disabled (specs/config-file.md#environment, specs/refresh.md#refresh). */
|
|
85
85
|
offline: boolean;
|
|
86
|
-
/** One per problem, in the order found (
|
|
86
|
+
/** One per problem, in the order found (specs/config-file.md#keys, specs/config-file.md#diagnostics). */
|
|
87
87
|
diagnostics: Diagnostic[];
|
|
88
88
|
}
|
|
89
89
|
|
|
@@ -95,23 +95,23 @@ export interface ConfigurationDependencies {
|
|
|
95
95
|
readFile?: (path: string) => string | null;
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
-
/** The configuration file's path below the home directory (
|
|
98
|
+
/** The configuration file's path below the home directory (specs/config-file.md#file). */
|
|
99
99
|
const CONFIG_FILE_SEGMENTS: readonly string[] = [".pi", "purse", "purse.conf"];
|
|
100
100
|
|
|
101
|
-
/** `ttlSeconds` bounds (
|
|
101
|
+
/** `ttlSeconds` bounds (specs/config-file.md#keys). */
|
|
102
102
|
const TTL_SECONDS_MIN = 60;
|
|
103
103
|
const TTL_SECONDS_MAX = 86400;
|
|
104
104
|
|
|
105
|
-
/** `statusLine`'s default (
|
|
105
|
+
/** `statusLine`'s default (specs/config-file.md#keys). */
|
|
106
106
|
const DEFAULT_STATUS_LINE = true;
|
|
107
107
|
|
|
108
|
-
/** The provider-id pattern (query-protocol.md
|
|
108
|
+
/** The provider-id pattern (specs/query-protocol.md#request). */
|
|
109
109
|
const PROVIDER_ID = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/;
|
|
110
110
|
|
|
111
|
-
/** Root keys (
|
|
111
|
+
/** Root keys (specs/config-file.md#keys). */
|
|
112
112
|
const ROOT_KEYS: readonly string[] = ["providers", "severity", "statusLine"];
|
|
113
113
|
|
|
114
|
-
/** Provider keys (
|
|
114
|
+
/** Provider keys (specs/config-file.md#keys); `project` is allowed on `google` only. */
|
|
115
115
|
const PROVIDER_KEYS: readonly string[] = [
|
|
116
116
|
"free",
|
|
117
117
|
"adapter",
|
|
@@ -121,7 +121,7 @@ const PROVIDER_KEYS: readonly string[] = [
|
|
|
121
121
|
"schedule",
|
|
122
122
|
];
|
|
123
123
|
|
|
124
|
-
/** Provider keys that are ignored, each with a diagnostic, on a free provider (
|
|
124
|
+
/** Provider keys that are ignored, each with a diagnostic, on a free provider (specs/config-file.md#keys). */
|
|
125
125
|
const FREE_IGNORED_KEYS: readonly string[] = [
|
|
126
126
|
"adapter",
|
|
127
127
|
"ttlSeconds",
|
|
@@ -131,25 +131,25 @@ const FREE_IGNORED_KEYS: readonly string[] = [
|
|
|
131
131
|
"project",
|
|
132
132
|
];
|
|
133
133
|
|
|
134
|
-
/** A cloud project id or number (
|
|
134
|
+
/** A cloud project id or number (specs/config-file.md#keys, `project`). */
|
|
135
135
|
const PROJECT = /^(?:[a-z][a-z0-9-]{4,28}[a-z0-9]|[0-9]{1,20})$/;
|
|
136
136
|
|
|
137
|
-
/** Rate fields of a `prices` entry (
|
|
137
|
+
/** Rate fields of a `prices` entry (specs/config-file.md#keys). */
|
|
138
138
|
const RATE_KEYS: readonly (keyof Rates)[] = ["input", "output", "cacheRead", "cacheWrite"];
|
|
139
139
|
|
|
140
|
-
/** Schedule keys (
|
|
140
|
+
/** Schedule keys (specs/config-file.md#keys). */
|
|
141
141
|
const SCHEDULE_KEYS: readonly string[] = ["multiplier", "timeZone", "windows"];
|
|
142
142
|
|
|
143
|
-
/** Schedule window keys (prices.md
|
|
143
|
+
/** Schedule window keys (specs/prices.md#schedule). */
|
|
144
144
|
const WINDOW_KEYS: readonly string[] = ["days", "from", "to"];
|
|
145
145
|
|
|
146
|
-
/** Severity keys (
|
|
146
|
+
/** Severity keys (specs/config-file.md#keys). */
|
|
147
147
|
const SEVERITY_KEYS: readonly string[] = ["low", "critical"];
|
|
148
148
|
|
|
149
|
-
/** `from` of a schedule window: `HH:MM`, 00:00–23:59 (prices.md
|
|
149
|
+
/** `from` of a schedule window: `HH:MM`, 00:00–23:59 (specs/prices.md#schedule). */
|
|
150
150
|
const FROM_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
151
151
|
|
|
152
|
-
/** `to` of a schedule window: `HH:MM` up to `24:00` (prices.md
|
|
152
|
+
/** `to` of a schedule window: `HH:MM` up to `24:00` (specs/prices.md#schedule). */
|
|
153
153
|
const TO_TIME = /^(?:[01]\d|2[0-3]):[0-5]\d$|^24:00$/;
|
|
154
154
|
|
|
155
155
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
@@ -169,7 +169,7 @@ function diagnostic(file: string, keyPath: string, problem: string): Diagnostic
|
|
|
169
169
|
return { file, keyPath, message: `${where}: ${problem}` };
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
-
/** Report one diagnostic per key not in `allowed` (
|
|
172
|
+
/** Report one diagnostic per key not in `allowed` (specs/config-file.md#keys: unknown keys). */
|
|
173
173
|
function reportUnknownKeys(
|
|
174
174
|
value: Record<string, unknown>,
|
|
175
175
|
allowed: readonly string[],
|
|
@@ -212,7 +212,7 @@ function localTimeMinutes(value: string, allowEnd: boolean): number | null {
|
|
|
212
212
|
return Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5));
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
/** One `prices` entry's overrides (
|
|
215
|
+
/** One `prices` entry's overrides (specs/config-file.md#keys); violated fields are omitted. */
|
|
216
216
|
function parseRateOverrides(
|
|
217
217
|
value: unknown,
|
|
218
218
|
keyPath: string,
|
|
@@ -240,7 +240,7 @@ function parseRateOverrides(
|
|
|
240
240
|
return overrides;
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
-
/** `prices`: overrides keyed by model id (
|
|
243
|
+
/** `prices`: overrides keyed by model id (specs/config-file.md#keys). */
|
|
244
244
|
function parsePrices(
|
|
245
245
|
value: unknown,
|
|
246
246
|
keyPath: string,
|
|
@@ -264,7 +264,7 @@ function parsePrices(
|
|
|
264
264
|
return prices;
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
-
/** One schedule window (prices.md
|
|
267
|
+
/** One schedule window (specs/prices.md#schedule); `null` when it violates its contract. */
|
|
268
268
|
function parseScheduleWindow(
|
|
269
269
|
value: unknown,
|
|
270
270
|
keyPath: string,
|
|
@@ -316,7 +316,7 @@ function parseScheduleWindow(
|
|
|
316
316
|
return { days, from: fromText, to: toText };
|
|
317
317
|
}
|
|
318
318
|
|
|
319
|
-
/** `schedule` (
|
|
319
|
+
/** `schedule` (specs/config-file.md#keys): its value, `null` for a disabled schedule, `undefined` when invalid. */
|
|
320
320
|
function parseSchedule(
|
|
321
321
|
value: unknown,
|
|
322
322
|
keyPath: string,
|
|
@@ -370,7 +370,7 @@ function parseSchedule(
|
|
|
370
370
|
return { multiplier, timeZone, windows };
|
|
371
371
|
}
|
|
372
372
|
|
|
373
|
-
/** One provider's entry (
|
|
373
|
+
/** One provider's entry (specs/config-file.md#keys); violated keys are omitted, a non-object entry is `null`. */
|
|
374
374
|
function parseProvider(
|
|
375
375
|
value: unknown,
|
|
376
376
|
providerId: string,
|
|
@@ -464,7 +464,7 @@ function parseProvider(
|
|
|
464
464
|
return config;
|
|
465
465
|
}
|
|
466
466
|
|
|
467
|
-
/** `providers` (
|
|
467
|
+
/** `providers` (specs/config-file.md#keys); entries with an invalid provider id are ignored. */
|
|
468
468
|
function parseProviders(
|
|
469
469
|
value: unknown,
|
|
470
470
|
file: string,
|
|
@@ -492,7 +492,7 @@ function parseProviders(
|
|
|
492
492
|
return providers;
|
|
493
493
|
}
|
|
494
494
|
|
|
495
|
-
/** `severity` (
|
|
495
|
+
/** `severity` (specs/config-file.md#keys): each invalid field defaults; an invalid order defaults both. */
|
|
496
496
|
function parseSeverity(
|
|
497
497
|
value: unknown,
|
|
498
498
|
file: string,
|
|
@@ -527,7 +527,7 @@ function parseSeverity(
|
|
|
527
527
|
|
|
528
528
|
/**
|
|
529
529
|
* The configuration file's path: `PURSE_CONF` when it is absolute, else
|
|
530
|
-
* `~/.pi/purse/purse.conf` (
|
|
530
|
+
* `~/.pi/purse/purse.conf` (specs/config-file.md#file, specs/config-file.md#environment).
|
|
531
531
|
*/
|
|
532
532
|
export function configurationPath(env: ConfigurationEnv, homeDir: string): ConfigurationLocation {
|
|
533
533
|
const configured = env.PURSE_CONF;
|
|
@@ -543,7 +543,7 @@ export function configurationPath(env: ConfigurationEnv, homeDir: string): Confi
|
|
|
543
543
|
|
|
544
544
|
/**
|
|
545
545
|
* The configuration from the file text (`null` for a missing file), its path, and the
|
|
546
|
-
* environment (
|
|
546
|
+
* environment (specs/config-file.md#file, specs/config-file.md#keys, specs/config-file.md#environment). Pure: no file is read, no clock, no host API.
|
|
547
547
|
*/
|
|
548
548
|
export function parseConfiguration(
|
|
549
549
|
text: string | null,
|
|
@@ -560,7 +560,7 @@ export function parseConfiguration(
|
|
|
560
560
|
diagnostics,
|
|
561
561
|
};
|
|
562
562
|
|
|
563
|
-
// A missing file, or one holding no JSON value, is an empty configuration, silently (
|
|
563
|
+
// A missing file, or one holding no JSON value, is an empty configuration, silently (specs/config-file.md#file).
|
|
564
564
|
if (text === null || stripComments(text).trim() === "") return configuration;
|
|
565
565
|
|
|
566
566
|
const errors: ParseError[] = [];
|
|
@@ -609,7 +609,7 @@ function messageOf(error: unknown): string {
|
|
|
609
609
|
return error instanceof Error ? error.message : String(error);
|
|
610
610
|
}
|
|
611
611
|
|
|
612
|
-
/** `readFileSync` with a missing file as `null` and every other failure thrown (
|
|
612
|
+
/** `readFileSync` with a missing file as `null` and every other failure thrown (specs/config-file.md#file). */
|
|
613
613
|
function readFileText(path: string): string | null {
|
|
614
614
|
try {
|
|
615
615
|
return readFileSync(path, "utf8");
|
|
@@ -620,7 +620,7 @@ function readFileText(path: string): string | null {
|
|
|
620
620
|
}
|
|
621
621
|
|
|
622
622
|
/**
|
|
623
|
-
* Resolve the path, read the file once, and parse it (
|
|
623
|
+
* Resolve the path, read the file once, and parse it (specs/config-file.md#file, specs/config-file.md#keys, specs/config-file.md#environment). A read failure other
|
|
624
624
|
* than a missing file is one diagnostic and an empty configuration. Call it once per boot
|
|
625
625
|
* window, at the first `session_start`, and keep the result.
|
|
626
626
|
*/
|
package/lib/guidance.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Guided models (user-interface.md
|
|
2
|
+
* Guided models (specs/user-interface.md#purse-command): the provider and model ids the session
|
|
3
3
|
* branch's model guidance names. The module is pure — it reads no host API, network, file,
|
|
4
4
|
* or clock — and parses the message text, so it needs no other extension.
|
|
5
5
|
*/
|
package/lib/prices.ts
CHANGED
|
@@ -23,38 +23,38 @@ import type {
|
|
|
23
23
|
ScheduleWindow,
|
|
24
24
|
} from "./state.ts";
|
|
25
25
|
|
|
26
|
-
/** An inventory model's cost, USD per million tokens (prices.md
|
|
26
|
+
/** An inventory model's cost, USD per million tokens (specs/prices.md#derivation). */
|
|
27
27
|
export type InventoryCost = AdapterInventoryCost;
|
|
28
28
|
|
|
29
|
-
/** One tier of an inventory cost (prices.md
|
|
29
|
+
/** One tier of an inventory cost (specs/prices.md#derivation). */
|
|
30
30
|
export type InventoryCostTier = NonNullable<InventoryCost["tiers"]>[number];
|
|
31
31
|
|
|
32
|
-
/** The inventory fields price derivation reads (prices.md
|
|
32
|
+
/** The inventory fields price derivation reads (specs/prices.md#derivation). */
|
|
33
33
|
export type InventoryModel = Pick<AdapterInventoryModel, "id" | "cost">;
|
|
34
34
|
|
|
35
|
-
/** A provider's `prices.<model id>` rate overrides (config-file.md
|
|
35
|
+
/** A provider's `prices.<model id>` rate overrides (specs/config-file.md#keys). */
|
|
36
36
|
export type RateOverride = RateOverrides;
|
|
37
37
|
|
|
38
|
-
/** A price schedule without its computed fields (config-file.md
|
|
38
|
+
/** A price schedule without its computed fields (specs/config-file.md#keys). */
|
|
39
39
|
export type ScheduleConfiguration = ScheduleConfig;
|
|
40
40
|
|
|
41
|
-
/** The provider configuration fields price derivation reads (config-file.md
|
|
41
|
+
/** The provider configuration fields price derivation reads (specs/config-file.md#keys). */
|
|
42
42
|
export type PriceSettings = Pick<ProviderConfig, "free" | "adapter" | "prices" | "schedule">;
|
|
43
43
|
|
|
44
|
-
/** What one model's price derivation reads (prices.md
|
|
44
|
+
/** What one model's price derivation reads (specs/prices.md#derivation). */
|
|
45
45
|
export interface PriceInput {
|
|
46
46
|
provider: string;
|
|
47
47
|
settings: PriceSettings;
|
|
48
48
|
now: number;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/** What a provider's model prices derivation reads (prices.md
|
|
51
|
+
/** What a provider's model prices derivation reads (specs/prices.md#derivation). */
|
|
52
52
|
export interface ModelPricesInput extends PriceInput {
|
|
53
53
|
models: readonly InventoryModel[];
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
|
-
* DeepSeek's built-in off-peak discount (adapter-deepseek.md
|
|
57
|
+
* DeepSeek's built-in off-peak discount (specs/adapter-deepseek.md#price-schedule, specs/prices.md#schedule):
|
|
58
58
|
* multiplier 0.5 in UTC on the windows below.
|
|
59
59
|
*/
|
|
60
60
|
export const DEEPSEEK_SCHEDULE: ScheduleConfiguration = {
|
|
@@ -68,7 +68,7 @@ export const DEEPSEEK_SCHEDULE: ScheduleConfiguration = {
|
|
|
68
68
|
],
|
|
69
69
|
};
|
|
70
70
|
|
|
71
|
-
/** Built-in schedules by adapter id; an adapter spec gives at most one (prices.md
|
|
71
|
+
/** Built-in schedules by adapter id; an adapter spec gives at most one (specs/prices.md#derivation). */
|
|
72
72
|
export const BUILT_IN_SCHEDULES: Readonly<Record<string, ScheduleConfiguration>> = {
|
|
73
73
|
deepseek: DEEPSEEK_SCHEDULE,
|
|
74
74
|
};
|
|
@@ -302,7 +302,7 @@ function nextChange(
|
|
|
302
302
|
return null;
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
-
/** Derive a schedule's computed `active` and `changesAt` at `now` (prices.md
|
|
305
|
+
/** Derive a schedule's computed `active` and `changesAt` at `now` (specs/prices.md#schedule). */
|
|
306
306
|
export function computeSchedule(configuration: ScheduleConfiguration, now: number): Schedule {
|
|
307
307
|
const windows: ScheduleWindow[] = configuration.windows.map((window) => ({
|
|
308
308
|
days: [...window.days],
|
|
@@ -361,7 +361,7 @@ function derivedSchedule(provider: string, settings: PriceSettings, now: number)
|
|
|
361
361
|
return configuration === null ? null : computeSchedule(configuration, now);
|
|
362
362
|
}
|
|
363
363
|
|
|
364
|
-
/** One model's price: free, inventory cost, rate overrides, then the schedule (
|
|
364
|
+
/** One model's price: free, inventory cost, rate overrides, then the schedule (specs/prices.md#derivation). */
|
|
365
365
|
function priceFor(
|
|
366
366
|
model: InventoryModel,
|
|
367
367
|
settings: PriceSettings,
|
|
@@ -406,7 +406,7 @@ function priceFor(
|
|
|
406
406
|
return { rates, tiers, source, schedule };
|
|
407
407
|
}
|
|
408
408
|
|
|
409
|
-
/** Derive one inventory model's price (prices.md
|
|
409
|
+
/** Derive one inventory model's price (specs/prices.md#derivation). */
|
|
410
410
|
export function derivePrice(model: InventoryModel, input: PriceInput): Price {
|
|
411
411
|
return priceFor(
|
|
412
412
|
model,
|
|
@@ -415,7 +415,7 @@ export function derivePrice(model: InventoryModel, input: PriceInput): Price {
|
|
|
415
415
|
);
|
|
416
416
|
}
|
|
417
417
|
|
|
418
|
-
/** Derive the prices of a provider's inventory models, in inventory order (prices.md
|
|
418
|
+
/** Derive the prices of a provider's inventory models, in inventory order (specs/prices.md#derivation). */
|
|
419
419
|
export function deriveModelPrices(input: ModelPricesInput): ModelPrice[] {
|
|
420
420
|
const schedule = derivedSchedule(input.provider, input.settings, input.now);
|
|
421
421
|
return input.models.map((model) => ({
|