pi-dent-purse 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris B
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # pi-dent-purse
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A pi extension that collects per-provider LLM billing state (prices, balances, usage limits) and
4
+ serves it to other extensions and the user.
5
+
6
+ ```sh
7
+ pi install npm:pi-dent-purse # add it to pi's packages
8
+ pi -e npm:pi-dent-purse # or try it for one run
9
+ ```
10
+
11
+ [pi-dent-agent](https://www.npmjs.com/package/pi-dent-agent) bundles it: do not install both.
12
+
13
+ Requires Node 26 or later and a pi that provides the extension API.
14
+
15
+ ## License
16
+
17
+ MIT
package/index.ts ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * purse - per-vendor LLM billing state for pi; see specs/.
3
+ *
4
+ * Wiring only: every building block lives in lib/ (docs/development.md, Wiring).
5
+ */
6
+
7
+ import type {
8
+ ExtensionAPI,
9
+ ExtensionCommandContext,
10
+ ExtensionContext,
11
+ } from "@earendil-works/pi-coding-agent";
12
+ import type { Adapter, InventoryModel } from "./lib/adapter.ts";
13
+ import { ADAPTERS } from "./lib/adapters/index.ts";
14
+ import { observeAmdHeaders } from "./lib/adapters/amd.ts";
15
+ import { observeHeaders } from "./lib/adapters/anthropic.ts";
16
+ import { loadConfiguration, parseConfiguration, type LoadedConfiguration } from "./lib/config.ts";
17
+ import { guidedModels } from "./lib/guidance.ts";
18
+ import { QUERY_CHANNEL, createQueryHandler } from "./lib/protocol.ts";
19
+ import {
20
+ createRefresher,
21
+ type RefreshHost,
22
+ type Refresher,
23
+ type RefreshMode,
24
+ } from "./lib/refresh.ts";
25
+ import { createCommandRunner, createTransport, type FetchFunction } from "./lib/transport.ts";
26
+ import {
27
+ PURSE_COMMAND_NAME,
28
+ PURSE_MESSAGE_TYPE,
29
+ createPurseCommand,
30
+ createStatusLineUpdater,
31
+ statusLineActive,
32
+ type StatusLineUpdater,
33
+ } from "./lib/ui.ts";
34
+
35
+ /** The bus channel announcing a changed provider entry. */
36
+ export const CHANGED_CHANNEL = "purse:changed:v1";
37
+ export const OBSERVE_CHANNEL = "purse:observe:v1";
38
+
39
+ /** Replaceable dependencies; every field defaults to production. */
40
+ export interface WiringDependencies {
41
+ adapters?: ReadonlyMap<string, Adapter>;
42
+ clock?: () => number;
43
+ fetch?: FetchFunction;
44
+ loadConfiguration?: () => LoadedConfiguration;
45
+ /**
46
+ * A variable of the pi process's environment, read at each use; defaults to `process.env`.
47
+ * Only tool providers' credential variables are read (adapter-contract.md Section 3).
48
+ */
49
+ environment?: (variable: string) => string | undefined;
50
+ /** Where the boot window lives; a fresh one by default. */
51
+ boot?: Boot;
52
+ }
53
+
54
+ /** What exists once per boot window. */
55
+ interface Window {
56
+ configuration: LoadedConfiguration;
57
+ refresher: Refresher;
58
+ updateStatus: StatusLineUpdater;
59
+ }
60
+
61
+ /**
62
+ * State outliving one `wire` call. The host calls the extension factory again, with a new `pi`
63
+ * and bus, on session replacement; the boot window survives it (specs/refresh.md Section 1).
64
+ */
65
+ export interface Boot {
66
+ pi: ExtensionAPI | undefined;
67
+ live: ExtensionContext | undefined;
68
+ window: Window | undefined;
69
+ }
70
+
71
+ export function createBoot(): Boot {
72
+ return { pi: undefined, live: undefined, window: undefined };
73
+ }
74
+
75
+ const processBoot = createBoot();
76
+
77
+ /** The RefreshHost over a live context's model registry (docs/development.md, Wiring). */
78
+ function hostOver(ctx: ExtensionContext): RefreshHost {
79
+ const registry = ctx.modelRegistry;
80
+ const inventory = (provider: string): InventoryModel[] =>
81
+ registry
82
+ .getAll()
83
+ .filter((model) => model.provider === provider)
84
+ .map(({ id, baseUrl, cost }) => ({
85
+ id,
86
+ baseUrl,
87
+ cost: {
88
+ input: cost.input,
89
+ output: cost.output,
90
+ cacheRead: cost.cacheRead,
91
+ cacheWrite: cost.cacheWrite,
92
+ ...(cost.tiers === undefined ? {} : { tiers: cost.tiers }),
93
+ },
94
+ }));
95
+ return {
96
+ inventory,
97
+ availableProviders: () => registry.getAvailable().map((model) => model.provider),
98
+ async credentials(provider) {
99
+ const result = await registry.getProviderAuth(provider);
100
+ const first = registry.getAll().find((model) => model.provider === provider);
101
+ if (result === undefined || first === undefined) return;
102
+ const { apiKey, baseUrl } = result.auth;
103
+ return {
104
+ ...(apiKey === undefined ? {} : { apiKey }),
105
+ ...(baseUrl === undefined ? {} : { baseUrl }),
106
+ oauth: registry.isUsingOAuth(first),
107
+ };
108
+ },
109
+ };
110
+ }
111
+
112
+ /** Wires purse to the host `pi`. */
113
+ export function wire(pi: ExtensionAPI, dependencies: WiringDependencies = {}): void {
114
+ const clock = dependencies.clock ?? Date.now;
115
+ const adapters = dependencies.adapters ?? ADAPTERS;
116
+ const fetchFunction = dependencies.fetch ?? ((url, init) => globalThis.fetch(url, init));
117
+ const load = dependencies.loadConfiguration ?? (() => loadConfiguration());
118
+ const environment = dependencies.environment ?? ((variable: string) => process.env[variable]);
119
+
120
+ const boot = dependencies.boot ?? createBoot();
121
+ boot.pi = pi;
122
+
123
+ const newRefresher = (configuration: LoadedConfiguration): Refresher =>
124
+ createRefresher({
125
+ adapters,
126
+ clock,
127
+ configuration,
128
+ host: () => (boot.live === undefined ? undefined : hostOver(boot.live)),
129
+ environment,
130
+ transportFor: (allowlist) => createTransport(fetchFunction, allowlist),
131
+ commandRunner: createCommandRunner((command, args, options) =>
132
+ (boot.pi ?? pi).exec(command, args, options),
133
+ ),
134
+ onChanged: (provider) =>
135
+ (boot.pi ?? pi).events.emit(CHANGED_CHANNEL, { protocol: 1, providers: [provider] }),
136
+ });
137
+
138
+ // Before the first session_start and after a window ends, the query service and the command
139
+ // face a refresher without a live context: `ready()` is false, so queries answer `not-ready`.
140
+ const dormant = newRefresher(parseConfiguration(null, "", {}));
141
+ const current = (): Refresher => boot.window?.refresher ?? dormant;
142
+ const facade: Refresher = {
143
+ ready: () => current().ready(),
144
+ knownProviders: () => current().knownProviders(),
145
+ recordObservation: (provider, observation) =>
146
+ current().recordObservation(provider, observation),
147
+ entry: (provider) => current().entry(provider),
148
+ request: (provider, mode, options) => current().request(provider, mode, options),
149
+ clear: () => current().clear(),
150
+ };
151
+
152
+ const request = (provider: string, mode: RefreshMode): void => {
153
+ void boot.window?.refresher.request(provider, mode);
154
+ };
155
+
156
+ pi.events.on(QUERY_CHANNEL, createQueryHandler({ refresher: facade, clock }));
157
+
158
+ const command = createPurseCommand({
159
+ refresher: facade,
160
+ clock,
161
+ send: (message) => {
162
+ (boot.pi ?? pi).sendMessage(
163
+ { customType: PURSE_MESSAGE_TYPE, content: message.content, display: true },
164
+ { triggerTurn: false },
165
+ );
166
+ },
167
+ });
168
+ pi.registerCommand(PURSE_COMMAND_NAME, {
169
+ description: command.description,
170
+ getArgumentCompletions: (prefix) => command.getArgumentCompletions(prefix),
171
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
172
+ boot.live = ctx;
173
+ await command.handler(args, {
174
+ mode: ctx.mode,
175
+ hasUI: ctx.hasUI,
176
+ ui: {
177
+ notify: (message, type) => ctx.ui.notify(message, type),
178
+ setStatus: (key, text) => ctx.ui.setStatus(key, text),
179
+ },
180
+ guidance: guidedModels(ctx.sessionManager.getBranch()),
181
+ });
182
+ },
183
+ });
184
+
185
+ pi.on("session_start", (_event, ctx) => {
186
+ boot.live = ctx;
187
+ let window = boot.window;
188
+ if (window === undefined) {
189
+ const configuration = load();
190
+ if (ctx.hasUI) {
191
+ for (const diagnostic of configuration.diagnostics) {
192
+ ctx.ui.notify("purse: " + diagnostic.message, "warning");
193
+ }
194
+ }
195
+ const refresher = newRefresher(configuration);
196
+ boot.window = window = {
197
+ configuration,
198
+ refresher,
199
+ updateStatus: createStatusLineUpdater({
200
+ refresher,
201
+ statusLine: configuration.statusLine,
202
+ clock,
203
+ }),
204
+ };
205
+ }
206
+ // refresh.md Section 1: purse is ready; consumers answered `not-ready` may ask again.
207
+ // The status line renders through the `purse:changed:v1` listener below.
208
+ (boot.pi ?? pi).events.emit(CHANGED_CHANNEL, {
209
+ protocol: 1,
210
+ providers: window.refresher.knownProviders(),
211
+ });
212
+ if (ctx.model !== undefined && statusLineActive(window.configuration.statusLine, ctx)) {
213
+ request(ctx.model.provider, "auto");
214
+ }
215
+ });
216
+
217
+ pi.on("session_shutdown", (event, ctx) => {
218
+ boot.window?.updateStatus(ctx);
219
+ boot.live = undefined;
220
+ if (boot.window !== undefined && (event.reason === "reload" || event.reason === "quit")) {
221
+ boot.window.refresher.clear();
222
+ boot.window = undefined;
223
+ }
224
+ });
225
+
226
+ pi.on("model_select", (event, ctx) => {
227
+ if (boot.window === undefined) return;
228
+ boot.window.updateStatus(ctx, event.model);
229
+ if (statusLineActive(boot.window.configuration.statusLine, ctx)) {
230
+ request(event.model.provider, "auto");
231
+ }
232
+ });
233
+
234
+ pi.on("agent_settled", (_event, ctx) => {
235
+ if (boot.window === undefined || ctx.model === undefined) return;
236
+ if (statusLineActive(boot.window.configuration.statusLine, ctx)) {
237
+ request(ctx.model.provider, "auto");
238
+ }
239
+ });
240
+
241
+ pi.events.on(CHANGED_CHANNEL, () => {
242
+ const { window, live } = boot;
243
+ if (window !== undefined && live !== undefined) window.updateStatus(live, live.model);
244
+ });
245
+
246
+ /** Records a header observation of an inference response of `provider` (adapter specs). */
247
+ const observe = (
248
+ provider: string | undefined,
249
+ headers: Readonly<Record<string, string>>,
250
+ ): void => {
251
+ const { window } = boot;
252
+ if (window === undefined) return;
253
+ const now = Date.now();
254
+ if (provider === "anthropic") {
255
+ const observation = observeHeaders(headers, now);
256
+ if (observation !== undefined) window.refresher.recordObservation("anthropic", observation);
257
+ } else if (provider === "amd") {
258
+ const observation = observeAmdHeaders(headers, now);
259
+ if (observation !== undefined) window.refresher.recordObservation("amd", observation);
260
+ }
261
+ };
262
+
263
+ pi.on("after_provider_response", (event, ctx) => observe(ctx.model?.provider, event.headers));
264
+
265
+ // A forwarded response (query-protocol.md Section 7).
266
+ pi.events.on(OBSERVE_CHANNEL, (payload: unknown) => {
267
+ const forwarded = forwardedResponse(payload);
268
+ if (forwarded !== undefined) observe(forwarded.provider, forwarded.headers);
269
+ });
270
+ }
271
+
272
+ /** The forwarded response a payload is, or `undefined` (query-protocol.md Section 7). */
273
+ function forwardedResponse(
274
+ payload: unknown,
275
+ ): { provider: string; headers: Record<string, string> } | undefined {
276
+ if (typeof payload !== "object" || payload === null) return undefined;
277
+ const protocol: unknown = Reflect.get(payload, "protocol");
278
+ const provider: unknown = Reflect.get(payload, "provider");
279
+ const headers: unknown = Reflect.get(payload, "headers");
280
+ if (protocol !== 1 || typeof provider !== "string") return undefined;
281
+ if (typeof headers !== "object" || headers === null || Array.isArray(headers)) return undefined;
282
+ const record: Record<string, string> = {};
283
+ for (const [name, value] of Object.entries(headers)) {
284
+ if (typeof value !== "string") return undefined;
285
+ record[name] = value;
286
+ }
287
+ return { provider, headers: record };
288
+ }
289
+
290
+ export default function purse(pi: ExtensionAPI): void {
291
+ wire(pi, { boot: processBoot });
292
+ }
package/lib/adapter.ts ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The adapter interface and the dependencies an adapter receives (adapter-contract.md).
3
+ * Types and spec-fixed constants only; no logic.
4
+ */
5
+
6
+ import type {
7
+ AdapterFailure,
8
+ AdapterProfile,
9
+ AdapterResult,
10
+ ProviderSettings,
11
+ Rates,
12
+ } from "./state.ts";
13
+
14
+ /** Deadline of one request (Section 4); the refresh signal may stop it earlier. */
15
+ export const REQUEST_DEADLINE_MS = 8000;
16
+
17
+ /**
18
+ * An adapter (Sections 1–2): its id is its provider id; the constants come from its adapter
19
+ * spec. `exposedFacets`, `freshnessSeconds`, and `credentialVariable` come from
20
+ * `AdapterProfile`.
21
+ */
22
+ export interface Adapter extends AdapterProfile {
23
+ /** The provider id (Section 1). */
24
+ id: string;
25
+ /**
26
+ * The https origin the host sends the provider's inference requests to (Section 1); absent
27
+ * for a tool provider, which has none.
28
+ */
29
+ providerOrigin?: string;
30
+ /** The https origins the adapter may contact (Section 1). */
31
+ hostAllowlist: readonly string[];
32
+ /**
33
+ * Runs one refresh (Section 2). Must not throw across the boundary: an unexpected exception
34
+ * is a whole failure with `internal`. `signal` aborts at the refresh deadline.
35
+ */
36
+ run(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult>;
37
+ }
38
+
39
+ /**
40
+ * The only way an adapter reaches the outside (Section 2). The refresh layer builds it after
41
+ * the Section 3 checks passed: `transport` is bound to the adapter's `hostAllowlist`, and
42
+ * `credentials` resolves to checked credentials.
43
+ */
44
+ export interface AdapterDependencies {
45
+ transport: Transport;
46
+ commandRunner: CommandRunner;
47
+ credentials: Credentials;
48
+ /** The inventory models of the adapter's provider. */
49
+ inventory: readonly InventoryModel[];
50
+ clock: Clock;
51
+ configuration: ProviderConfiguration;
52
+ store: Store;
53
+ observations: Observations;
54
+ }
55
+
56
+ /**
57
+ * One request under Section 4: `accept: application/json` and `user-agent: pi-dent-purse`
58
+ * added by the transport; method `GET` unless the request names `POST` with its spec's
59
+ * verbatim `body`. The allowlist is bound into the transport.
60
+ */
61
+ export interface TransportRequest {
62
+ /** An `https:` URL without userinfo whose origin is in the bound allowlist, else `internal`. */
63
+ url: string;
64
+ /** Only the headers the adapter spec lists (Sections 3–4). */
65
+ headers?: Record<string, string>;
66
+ /** `POST` only, and only where the adapter spec states the request's body verbatim. */
67
+ method?: "POST";
68
+ /** The verbatim body of a `POST` request; a body without `method` is refused. */
69
+ body?: string;
70
+ /** Body cap in bytes of a 2xx body (Section 4). */
71
+ bodyCap: number;
72
+ /** The refresh's abort signal: aborted means `deadline`; the 8-second expiry is `timeout`. */
73
+ signal: AbortSignal;
74
+ }
75
+
76
+ /** A transport success (Section 2). */
77
+ export interface TransportSuccess {
78
+ status: number;
79
+ /** Lowercase-keyed. */
80
+ headers: Record<string, string>;
81
+ /** Body text. */
82
+ body: string;
83
+ }
84
+
85
+ /** A transport failure (Sections 2, 4): `status` is present when a response arrived. */
86
+ export interface TransportFailure extends AdapterFailure {
87
+ status?: number;
88
+ }
89
+
90
+ /**
91
+ * Outcome of one request: a failure is the outcome with a `reason` field (Section 2).
92
+ */
93
+ export type TransportOutcome = TransportSuccess | TransportFailure;
94
+
95
+ /**
96
+ * Performs one request (Section 2); never rejects.
97
+ */
98
+ export type Transport = (request: TransportRequest) => Promise<TransportOutcome>;
99
+
100
+ /** One command under Section 5: no shell, run in the user's home directory. */
101
+ export interface CommandRequest {
102
+ command: string;
103
+ /** The argument vector the adapter spec gives. */
104
+ args: readonly string[];
105
+ /** Deadline in milliseconds, from the adapter spec. */
106
+ deadlineMs: number;
107
+ /** Output cap in bytes, from the adapter spec. */
108
+ outputCap: number;
109
+ /** The refresh's abort signal; aborted means `deadline` (as for `TransportRequest`). */
110
+ signal: AbortSignal;
111
+ }
112
+
113
+ /**
114
+ * A command that ran to exit (Section 2). A missing executable arrives here with code 1 and
115
+ * `ENOENT` in `stderr` (docs/development.md, Exec).
116
+ */
117
+ export interface CommandSuccess {
118
+ code: number;
119
+ stdout: string;
120
+ stderr: string;
121
+ }
122
+
123
+ /** A command failure (Sections 2, 5): `timeout`, `deadline`, `response-too-large`, or `internal`. */
124
+ export interface CommandFailure {
125
+ reason: AdapterFailure["reason"];
126
+ }
127
+
128
+ /** Outcome of one command: a failure is the outcome with a `reason` field (Section 2). */
129
+ export type CommandOutcome = CommandSuccess | CommandFailure;
130
+
131
+ /** Runs one command (Section 2); never rejects. */
132
+ export type CommandRunner = (request: CommandRequest) => Promise<CommandOutcome>;
133
+
134
+ /** Credentials of a provider as the host resolves them (Section 3). */
135
+ export interface ProviderCredentials {
136
+ apiKey?: string;
137
+ oauth: boolean;
138
+ baseUrl?: string;
139
+ }
140
+
141
+ /** Credentials that passed the Section 3 checks: a non-empty `apiKey`. */
142
+ export interface CheckedCredentials {
143
+ apiKey: string;
144
+ oauth: boolean;
145
+ }
146
+
147
+ /**
148
+ * Credentials of the adapter's provider (Sections 2–3): the first call returns the credentials
149
+ * the refresh checked; each later call resolves and checks them afresh, `undefined` when the
150
+ * checks fail.
151
+ */
152
+ export type Credentials = () => Promise<CheckedCredentials | undefined>;
153
+
154
+ /** One tier of an inventory cost: rates above an input-token count, USD per million tokens. */
155
+ export interface InventoryCostTier {
156
+ inputTokensAbove: number;
157
+ input: number;
158
+ output: number;
159
+ cacheRead: number;
160
+ cacheWrite: number;
161
+ }
162
+
163
+ /** An inventory model's cost, USD per million tokens (Section 2). */
164
+ export interface InventoryCost {
165
+ input: number;
166
+ output: number;
167
+ cacheRead: number;
168
+ cacheWrite: number;
169
+ tiers?: readonly InventoryCostTier[];
170
+ }
171
+
172
+ /** An inventory model (Section 2): the one inventory shape of purse. */
173
+ export interface InventoryModel {
174
+ id: string;
175
+ baseUrl: string;
176
+ cost: InventoryCost;
177
+ }
178
+
179
+ /** Current epoch milliseconds (Section 2). */
180
+ export type Clock = () => number;
181
+
182
+ /**
183
+ * The provider's configuration section (Section 2, config-file.md Section 2): the keys
184
+ * entry derivation reads, `project` (`google` only), and the rate overrides.
185
+ */
186
+ export interface ProviderConfiguration extends ProviderSettings {
187
+ project?: string;
188
+ /** Rate overrides keyed by model id (prices.md Section 2). */
189
+ prices?: Record<string, { [Field in keyof Rates]?: number | null }>;
190
+ }
191
+
192
+ /**
193
+ * Adapter-private key-value state with per-item expiry, discarded with the cache (Section 2):
194
+ * synchronous, `undefined` for absent or expired, no `ttlSeconds` meaning no expiry.
195
+ */
196
+ export interface Store {
197
+ get(key: string): unknown;
198
+ set(key: string, value: unknown, ttlSeconds?: number): void;
199
+ }
200
+
201
+ /**
202
+ * Read access to the header observations of the adapter's provider (Section 2): `undefined`
203
+ * when none exists. The observation is in the shape the provider's adapter spec fixes, so it
204
+ * is `unknown` here and the adapter narrows it with a type guard.
205
+ */
206
+ export interface Observations {
207
+ latest(): unknown;
208
+ }