@sference/pi 0.0.0-stage → 0.10.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/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.9.0 - 2026-12-05
4
+
5
+ - Initial npm release. The sference pi extension: a `sference` provider with the
6
+ live `/v1/models` catalog (chat and System One decision models), SSO login via
7
+ `/login sference`, `max_queue_wait_s` request tuning, `/sference-tier` (flex,
8
+ priority) and `/sference-refresh`, and cost accounting recomputed with flex,
9
+ priority and off-peak rates.
10
+ - A load guard keeps a leftover pre-npm local copy (the directory
11
+ `~/.pi/agent/extensions/sference/`) from double-registering the provider and
12
+ commands; the npm package takes precedence.
13
+ - Versions track the sference CLI release that ships the same code. The CLI
14
+ installs this package without a version pin, so `pi update --extensions`
15
+ can update the extension independently of the CLI.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @sference/pi
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
+ [sference](https://sference.com) as a first-class provider for the [pi coding agent](https://pi.dev): the full live model catalog — chat and System One decision models — straight from `/v1/models`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:@sference/pi
9
+ ```
10
+
11
+ Then sign in inside pi:
12
+
13
+ ```
14
+ /login sference
15
+ ```
16
+
17
+ Single sign-on runs in the browser and gives pi its own rotating credential. Alternatively set `SFERENCE_API_KEY` in the environment. After signing in, pick sference models with `/model` (or scope the picker with `pi --models 'sference/**'`).
18
+
19
+ If you use the [sference CLI](https://pypi.org/project/sference-cli/), none of this is manual: `sference launch pi` installs the package if it is missing and retires the pre-npm local copy.
20
+
21
+ ## What it adds
22
+
23
+ - **A `sference` provider** with the live catalog: new models appear without extension updates, and `max_queue_wait_s` is tuned per request.
24
+ - **System One decision models** (`sference/Cloudflare/clef` and friends) registered as classifiers, so pi's `codemode` `models.classify()` answers structured decisions with them.
25
+ - **`/sference-tier [flex|priority|off]`** — request scheduling tiers: `flex` for discounted tokens at lower priority, `priority` to be scheduled ahead of default traffic at a premium. Omit the argument to cycle.
26
+ - **`/sference-refresh`** — re-fetch the catalog on demand.
27
+ - **Cost accounting that matches the bill**: flex discounts, priority premiums and off-peak windows are applied to the usage pi reports, including for interleaved streams.
28
+
29
+ ## Requirements
30
+
31
+ - pi ≥ 1.8 (this extension compiles against the 1.8 APIs; `import.meta.url` is used to avoid double-registration when a leftover local copy exists)
32
+ - Node.js ≥ 22.19 (pi 1.8's own floor)
33
+ - A sference account — sign up at [sference.com](https://sference.com)
34
+
35
+ ## Development
36
+
37
+ The source lives in the [sference repository](https://github.com/s-ference/sference) under `cli/sference_cli/pi_extension`. Tests and typecheck need the devDependencies installed (`npm install`); the versions of the pi packages are pinned deliberately and bumped together with the extension's APIs.
38
+
39
+ ```bash
40
+ npm install
41
+ npm test # node --test with module mocks
42
+ npm run typecheck # tsc --noEmit
43
+ ```
44
+
45
+ To try local changes in pi without publishing, install the directory directly:
46
+
47
+ ```bash
48
+ pi install ./cli/sference_cli/pi_extension
49
+ ```
50
+
51
+ ## Versioning
52
+
53
+ `@sference/pi` is released in lockstep with the sference CLI: version `X.Y.Z` of the package ships the same extension code as CLI `X.Y.Z`. The CLI installs the package unpinned, so `pi update --extensions` can move the extension forward independently. The changelog below lists each release.
54
+
55
+ ## License
56
+
57
+ Apache-2.0
package/index.ts ADDED
@@ -0,0 +1,394 @@
1
+ /**
2
+ * sference provider for pi, installed and kept current by `sference launch pi`.
3
+ *
4
+ * - Chat models on `/v1/responses` and decision models through pi's native
5
+ * System One classifier adapter, both discovered from `GET /v1/models`.
6
+ * The catalog persists to pi's models store for instant, offline-safe
7
+ * startup, is re-fetched once per process (then at most every 4h), and
8
+ * `/sference-refresh` forces a fetch.
9
+ * - SSO: `/login sference` runs the device flow `sference auth login` uses;
10
+ * pi stores and refreshes the grant. `SFERENCE_API_KEY` works too.
11
+ * - Request tuning: `max_queue_wait_s` on every chat request; `/sference-tier`
12
+ * (flex, priority) or `SFERENCE_SERVICE_TIER` for the service tier.
13
+ * - Cost: recomputed with sference's flex, priority and off-peak rates.
14
+ *
15
+ * Values already in a payload are never overwritten, so models.json
16
+ * `modelOverrides` -> `samplingParams` still win.
17
+ */
18
+
19
+ import { hostname } from "node:os";
20
+
21
+ import type { AnyModel, ProviderClassifier } from "@earendil-works/pi-ai";
22
+ import type {
23
+ ExtensionAPI,
24
+ ExtensionContext,
25
+ ProviderConfig,
26
+ ProviderModelConfig,
27
+ } from "@earendil-works/pi-coding-agent";
28
+
29
+ import { loginWithDeviceFlow, refreshDeviceGrant } from "./lib/auth.ts";
30
+ import { fromCatalog, type OffPeak, seedModels, usableEntries } from "./lib/catalog.ts";
31
+ import {
32
+ BASE_URL,
33
+ CATALOG_TIMEOUT_S,
34
+ CHAT_API,
35
+ CLASSIFIER_API,
36
+ DEFAULT_SERVICE_TIER,
37
+ MAX_QUEUE_WAIT_S,
38
+ PROVIDER_ID,
39
+ REFRESH_INTERVAL_MS,
40
+ } from "./lib/config.ts";
41
+ import { costFor, priceFactor } from "./lib/pricing.ts";
42
+
43
+ type RefreshContext = Parameters<NonNullable<ProviderConfig["refreshModels"]>>[0];
44
+
45
+ /** Session tier shown in pi's status line while one is selected. */
46
+ const TIER_STATUS_KEY = "sference-tier";
47
+
48
+ /**
49
+ * A leftover pre-npm local copy (or a manual git checkout) can coexist with
50
+ * the installed npm package: pi identifies local extensions by path and npm
51
+ * packages by name, so both load. They run as separate module roots but
52
+ * share the JS realm, and registering the provider and commands twice would
53
+ * duplicate them in the UI. The first module evaluation claims a global slot
54
+ * keyed by its own source URL; a copy whose URL differs steps aside, while
55
+ * /reload — which re-evaluates the same URL — keeps working.
56
+ */
57
+ const LOAD_GUARD_SLOT = "__sferencePiExtensionUrl";
58
+ const realm = globalThis as typeof globalThis & { [LOAD_GUARD_SLOT]?: string };
59
+ const priorSferenceCopy = realm[LOAD_GUARD_SLOT];
60
+ realm[LOAD_GUARD_SLOT] = import.meta.url;
61
+
62
+ /** Cap on remembered response tiers; aborted/error streams leave stale entries behind. */
63
+ const MAX_TRACKED_RESPONSE_TIERS = 128;
64
+
65
+ /**
66
+ * How long a failed /v1/models attempt holds off further non-forced fetches,
67
+ * so a struggling API is not hammered by every refresh; /sference-refresh
68
+ * (force) ignores it.
69
+ */
70
+ const FETCH_FAILURE_BACKOFF_MS = 60_000;
71
+
72
+ /**
73
+ * pi's System One classifier, or undefined on a pi without classifier
74
+ * support (chat still works; decision models are hidden). Extensions cannot
75
+ * resolve pi-ai's `./api/*` subpaths (pi 1.7), so take it from the built-in
76
+ * TypeSafe provider.
77
+ */
78
+ async function loadSystemOne(): Promise<ProviderClassifier | undefined> {
79
+ try {
80
+ const { builtinProviders } = await import("@earendil-works/pi-ai/providers/all");
81
+ const typesafe = builtinProviders().find((provider) => provider.id === "typesafe");
82
+ const classify = typesafe?.classify?.bind(typesafe);
83
+ if (classify) return { classify };
84
+ } catch {
85
+ // Fall through: no classifier support in this pi.
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ export default async function sferenceProvider(pi: ExtensionAPI): Promise<void> {
91
+ if (priorSferenceCopy !== undefined && priorSferenceCopy !== import.meta.url) {
92
+ // Another copy of this extension is already registered (see
93
+ // LOAD_GUARD_SLOT); this one is redundant.
94
+ return;
95
+ }
96
+ const systemOne = await loadSystemOne();
97
+
98
+ // Session state. pi re-runs the factory on /reload, which resets it.
99
+ let serviceTier: "flex" | "priority" | undefined = DEFAULT_SERVICE_TIER;
100
+ // Served tier per response id. Streams interleave (background compaction,
101
+ // codemode), so a single "last tier" would price one message with
102
+ // another's; `lastServedTier` is only the fallback for a message that
103
+ // carries no response id.
104
+ const servedTierByResponseId = new Map<string, string>();
105
+ let lastServedTier: string | undefined;
106
+ let fetchedThisProcess = false;
107
+ let lastFetchFailedAt: number | undefined;
108
+ let warnedUnauthorized = false;
109
+ // Off-peak windows come from the live catalog only (pi's persisted models
110
+ // keep pi's own fields). session_start fetches it in the background; until
111
+ // that lands, cost stays at list price, the safe direction.
112
+ const offPeakById = new Map<string, OffPeak>();
113
+
114
+ const keepUsable = (models: ProviderModelConfig[]) =>
115
+ systemOne ? models : models.filter((model) => model.type !== "classifier");
116
+
117
+ async function refreshCatalog(context: RefreshContext): Promise<ProviderModelConfig[]> {
118
+ const stored = context.stored ? keepUsable(context.stored.models.map(restamp)) : undefined;
119
+ if (!context.allowNetwork) return stored ?? seedModels();
120
+
121
+ const checkedAt = context.stored?.checkedAt;
122
+ const fresh = checkedAt !== undefined && Date.now() - checkedAt < REFRESH_INTERVAL_MS;
123
+ if (!context.force && fresh && fetchedThisProcess && stored) return stored;
124
+ // A recent attempt failed: serve the previous catalog (or the seed)
125
+ // instead of re-fetching. Like pi's own catalog client, which moves its
126
+ // freshness window on a transient failure, this paces the retries.
127
+ if (
128
+ !context.force &&
129
+ lastFetchFailedAt !== undefined &&
130
+ Date.now() - lastFetchFailedAt < FETCH_FAILURE_BACKOFF_MS
131
+ ) {
132
+ return stored ?? seedModels();
133
+ }
134
+
135
+ // /v1/models is public, but an account can see models (custom
136
+ // deployments) that anonymous callers do not.
137
+ const token =
138
+ context.credential?.type === "api_key"
139
+ ? context.credential.key
140
+ : context.credential?.type === "oauth"
141
+ ? context.credential.access
142
+ : undefined;
143
+ try {
144
+ // Bound the fetch on its own timer: a hung /v1/models must not
145
+ // stall the refresh until pi aborts the shared signal.
146
+ let response: Response;
147
+ try {
148
+ response = await fetch(`${BASE_URL}/models`, {
149
+ signal: AbortSignal.any([context.signal, AbortSignal.timeout(CATALOG_TIMEOUT_S * 1000)]),
150
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined,
151
+ });
152
+ } catch (error) {
153
+ // pi-initiated cancellation passes through untouched; only the
154
+ // timeout leg of the combined signal gets a message naming it.
155
+ // AbortSignal.timeout rejects with a TimeoutError DOMException.
156
+ if (context.signal.aborted) throw error;
157
+ throw error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")
158
+ ? new Error(`sference: GET /v1/models timed out after ${CATALOG_TIMEOUT_S}s`)
159
+ : error;
160
+ }
161
+ if (!response.ok) {
162
+ // Throwing keeps the previous catalog; the backoff above paces the retry.
163
+ throw new Error(`sference: GET /v1/models failed: ${response.status} ${response.statusText}`);
164
+ }
165
+ const entries = usableEntries((await response.json()) as { data?: unknown });
166
+ offPeakById.clear();
167
+ for (const entry of entries) {
168
+ if (entry.pricing?.off_peak) offPeakById.set(entry.id, entry.pricing.off_peak);
169
+ }
170
+ const models = keepUsable(entries.map((entry) => restamp(fromCatalog(entry))));
171
+ fetchedThisProcess = true;
172
+ lastFetchFailedAt = undefined;
173
+ // restamp() stamps provider/api at runtime; the config type it returns
174
+ // legitimately lacks them, so the store entry needs the model-side view.
175
+ await context.publish({
176
+ persist: { models: models as unknown as readonly AnyModel[], checkedAt: Date.now() },
177
+ });
178
+ return models;
179
+ } catch (error) {
180
+ // pi-initiated cancellation is not an API failure; don't back off on it.
181
+ if (!context.signal.aborted) lastFetchFailedAt = Date.now();
182
+ throw error;
183
+ }
184
+ }
185
+
186
+ pi.registerProvider(PROVIDER_ID, {
187
+ name: "sference",
188
+ baseUrl: BASE_URL,
189
+ apiKey: "$SFERENCE_API_KEY",
190
+ api: CHAT_API,
191
+ models: keepUsable(seedModels()),
192
+ ...(systemOne ? { classifiers: { [CLASSIFIER_API]: systemOne } } : {}),
193
+ refreshModels: refreshCatalog,
194
+ oauth: {
195
+ name: "sference",
196
+ login: (callbacks) =>
197
+ loginWithDeviceFlow(BASE_URL, callbacks, { deviceLabel: `pi on ${safeHostname()}` }),
198
+ refreshToken: (credentials, signal) => refreshDeviceGrant(BASE_URL, credentials, signal),
199
+ getApiKey: (credentials) => credentials.access,
200
+ },
201
+ });
202
+
203
+ pi.on("before_provider_request", (event, ctx) => {
204
+ if (!isSferenceModel(ctx)) return;
205
+ const body = event.payload;
206
+ // Responses bodies only. Decisions bodies (`state`/`questions`) reject
207
+ // unknown fields with a 400.
208
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return;
209
+ const payload = body as Record<string, unknown>;
210
+ if (!("input" in payload) || "questions" in payload) return;
211
+
212
+ const patch: Record<string, unknown> = {};
213
+ // The API rejects max_queue_wait_s on background requests, which queue by design.
214
+ if (payload.max_queue_wait_s === undefined && payload.background !== true) {
215
+ patch.max_queue_wait_s = MAX_QUEUE_WAIT_S;
216
+ }
217
+ if (serviceTier && payload.service_tier === undefined) patch.service_tier = serviceTier;
218
+ return Object.keys(patch).length > 0 ? { ...payload, ...patch } : undefined;
219
+ });
220
+
221
+ // The served tier is only in the Responses events, and it can differ from
222
+ // the requested one (flex on an account without flex runs at default).
223
+ // Track it per response id: streams interleave, and message_end correlates
224
+ // its message by the same id pi records on the assistant message.
225
+ pi.on("provider_stream_event", (event) => {
226
+ if (event.provider !== PROVIDER_ID) return;
227
+ const data = event.data as {
228
+ type?: unknown;
229
+ response?: { id?: unknown; service_tier?: unknown };
230
+ } | undefined;
231
+ if (typeof data?.type !== "string" || !data.type.startsWith("response.")) return;
232
+ const tier = data.response?.service_tier;
233
+ if (typeof tier !== "string") return;
234
+ lastServedTier = tier;
235
+ const id = data.response?.id;
236
+ if (typeof id === "string") {
237
+ if (servedTierByResponseId.size >= MAX_TRACKED_RESPONSE_TIERS) {
238
+ servedTierByResponseId.clear();
239
+ }
240
+ servedTierByResponseId.set(id, tier);
241
+ }
242
+ });
243
+
244
+ pi.on("message_end", (event, ctx) => {
245
+ const message = event.message;
246
+ if (message.role !== "assistant" || message.provider !== PROVIDER_ID) return;
247
+ if (message.api !== CHAT_API || !message.usage) return;
248
+ const model = ctx.modelRegistry.find(PROVIDER_ID, message.model);
249
+ if (!model) return;
250
+ const servedTier =
251
+ message.responseId !== undefined
252
+ ? servedTierByResponseId.get(message.responseId)
253
+ : lastServedTier;
254
+ if (message.responseId !== undefined) {
255
+ servedTierByResponseId.delete(message.responseId);
256
+ }
257
+ const cost = costFor(
258
+ message.usage,
259
+ model.cost,
260
+ priceFactor({
261
+ servedTier,
262
+ offPeak: offPeakById.get(message.model),
263
+ requestedAt: message.timestamp,
264
+ }),
265
+ );
266
+ if (Math.abs(cost.total - message.usage.cost.total) < 1e-12) return;
267
+ return { message: { ...message, usage: { ...message.usage, cost } } };
268
+ });
269
+
270
+ pi.on("after_provider_response", (event, ctx) => {
271
+ if (event.status !== 401 || !isSferenceModel(ctx) || warnedUnauthorized) return;
272
+ warnedUnauthorized = true;
273
+ ctx.ui.notify(
274
+ "sference rejected the credential. Run /login sference to sign in, or set SFERENCE_API_KEY.",
275
+ "error",
276
+ );
277
+ });
278
+
279
+ pi.on("session_start", (_event, ctx) => {
280
+ if (serviceTier) ctx.ui.setStatus(TIER_STATUS_KEY, serviceTier);
281
+ // pi's own startup refresh does not always run before the first request
282
+ // (not in print mode), so fetch once per process here too: the catalog
283
+ // stays live and the off-peak windows are known.
284
+ if (!fetchedThisProcess && !process.env.PI_OFFLINE) {
285
+ void ctx.modelRegistry
286
+ .refresh({ allowNetwork: true, providers: [PROVIDER_ID] })
287
+ .catch(() => undefined);
288
+ }
289
+ if (isSferenceModel(ctx) && !ctx.modelRegistry.getProviderAuthStatus(PROVIDER_ID).configured) {
290
+ ctx.ui.notify(
291
+ "sference: not signed in. Run /login sference (SSO), or set SFERENCE_API_KEY.",
292
+ "warning",
293
+ );
294
+ }
295
+ });
296
+
297
+ // The two tiers that change behaviour (auto/default/scale are served at
298
+ // default). No argument cycles off → flex → priority → off.
299
+ pi.registerCommand("sference-tier", {
300
+ description:
301
+ "Set the sference service tier for this session: flex, priority, or off (cycles when omitted)",
302
+ handler: async (args, ctx) => {
303
+ const arg = args.trim().toLowerCase();
304
+ serviceTier =
305
+ arg === "flex" || arg === "priority"
306
+ ? arg
307
+ : arg === "off" || arg === "default"
308
+ ? undefined
309
+ : serviceTier === undefined
310
+ ? "flex"
311
+ : serviceTier === "flex"
312
+ ? "priority"
313
+ : undefined;
314
+ ctx.ui.setStatus(TIER_STATUS_KEY, serviceTier);
315
+ ctx.ui.notify(
316
+ serviceTier === "flex"
317
+ ? "sference flex tier on: discounted tokens, lower scheduling priority"
318
+ : serviceTier === "priority"
319
+ ? "sference priority tier on: scheduled ahead of default traffic, billed at a premium"
320
+ : "sference service tier off",
321
+ "info",
322
+ );
323
+ },
324
+ });
325
+
326
+ // pi's `update --models` only refreshes models.json providers, not extension ones.
327
+ pi.registerCommand("sference-refresh", {
328
+ description: "Re-fetch the sference model catalog from /v1/models",
329
+ handler: async (_args, ctx) => {
330
+ try {
331
+ const result = await ctx.modelRegistry.refresh({
332
+ allowNetwork: true,
333
+ force: true,
334
+ providers: [PROVIDER_ID],
335
+ });
336
+ const error = result.errors.get(PROVIDER_ID);
337
+ if (result.aborted || error) {
338
+ ctx.ui.notify(`sference catalog refresh failed: ${error?.message ?? "aborted"}`, "error");
339
+ return;
340
+ }
341
+ const chat = ctx.modelRegistry.getModelsOfType("chat", PROVIDER_ID).length;
342
+ const classifiers = ctx.modelRegistry.getModelsOfType("classifier", PROVIDER_ID).length;
343
+ ctx.ui.notify(
344
+ `sference catalog refreshed: ${chat} chat, ${classifiers} decision models`,
345
+ "info",
346
+ );
347
+ } catch (error) {
348
+ ctx.ui.notify(
349
+ `sference catalog refresh failed: ${error instanceof Error ? error.message : String(error)}`,
350
+ "error",
351
+ );
352
+ }
353
+ },
354
+ });
355
+ }
356
+
357
+ /**
358
+ * The provider/api/baseUrl fields pi stores per model. Restored entries are
359
+ * re-stamped too, so a changed SFERENCE_BASE_URL never serves a stale host.
360
+ */
361
+ function restamp(model: ProviderModelConfig): ProviderModelConfig {
362
+ // sference's image format is a fact of the API, not of the stored entry,
363
+ // so restored classifiers get it even when an older extension stored
364
+ // them without it (until the next /v1/models fetch replaces the list).
365
+ const classifierCompat = {
366
+ ...(model as { compat?: object }).compat,
367
+ imageInput: "images",
368
+ sendImageOptInHeader: false,
369
+ };
370
+ if (model.type === "classifier") {
371
+ return {
372
+ ...model,
373
+ compat: classifierCompat,
374
+ provider: PROVIDER_ID,
375
+ api: CLASSIFIER_API,
376
+ baseUrl: BASE_URL,
377
+ } as unknown as ProviderModelConfig;
378
+ }
379
+ // Entries stored by an older extension lack the compat fromCatalog sets now.
380
+ const compat = { ...(model as { compat?: object }).compat, supportsMaxOutputTokens: false };
381
+ return { ...model, compat, provider: PROVIDER_ID, api: CHAT_API, baseUrl: BASE_URL } as unknown as ProviderModelConfig;
382
+ }
383
+
384
+ function isSferenceModel(ctx: ExtensionContext): boolean {
385
+ return ctx.model?.provider === PROVIDER_ID;
386
+ }
387
+
388
+ function safeHostname(): string {
389
+ try {
390
+ return hostname() || "this device";
391
+ } catch {
392
+ return "this device";
393
+ }
394
+ }
package/lib/auth.ts ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * sference SSO for pi: the RFC 8628 device flow `sference auth login` uses,
3
+ * exposed through pi's `/login sference`.
4
+ *
5
+ * pi stores the grant in its own auth.json and refreshes it under its
6
+ * credential-store lock. That matters: the platform rotates the refresh token
7
+ * on every refresh and revokes the whole grant when a rotated-out token is
8
+ * presented again. Sharing `~/.sference/credentials.json` with the CLI would
9
+ * let the two race each other into a revoked grant, so pi gets a grant of its
10
+ * own.
11
+ *
12
+ * Pure apart from `fetch` (injectable) so it is testable without pi.
13
+ */
14
+
15
+ import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
16
+
17
+ import { OAUTH_CLIENT_ID } from "./config.ts";
18
+
19
+ /** Refresh this long before expiry so a token never dies mid-request. */
20
+ const EXPIRY_SKEW_MS = 60_000;
21
+ /** RFC 8628: `slow_down` adds 5 seconds to the polling interval. */
22
+ const SLOW_DOWN_STEP_S = 5;
23
+
24
+ type Fetch = typeof fetch;
25
+
26
+ export interface DeviceFlowDeps {
27
+ fetch?: Fetch;
28
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
29
+ now?: () => number;
30
+ deviceLabel?: string;
31
+ }
32
+
33
+ interface TokenResponse {
34
+ access_token: string;
35
+ refresh_token: string;
36
+ expires_in: number;
37
+ }
38
+
39
+ export class SferenceAuthError extends Error {
40
+ readonly code: string;
41
+
42
+ constructor(code: string, description: string, hint?: string) {
43
+ super(`${description} (${code})${hint ? `. ${hint}` : ""}`);
44
+ this.code = code;
45
+ }
46
+ }
47
+
48
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
49
+ return new Promise((resolve, reject) => {
50
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
51
+ const timer = setTimeout(() => {
52
+ signal?.removeEventListener("abort", onAbort);
53
+ resolve();
54
+ }, ms);
55
+ const onAbort = () => {
56
+ clearTimeout(timer);
57
+ reject(signal?.reason ?? new Error("aborted"));
58
+ };
59
+ signal?.addEventListener("abort", onAbort, { once: true });
60
+ });
61
+ }
62
+
63
+ /** POST JSON; HTTP error statuses are data (the device flow signals state through 400 bodies). */
64
+ async function postJson(
65
+ fetchImpl: Fetch,
66
+ url: string,
67
+ body: Record<string, unknown>,
68
+ signal?: AbortSignal,
69
+ ): Promise<{ status: number; body: Record<string, unknown> }> {
70
+ const response = await fetchImpl(url, {
71
+ method: "POST",
72
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
73
+ body: JSON.stringify(body),
74
+ signal,
75
+ });
76
+ const text = await response.text();
77
+ let parsed: unknown = {};
78
+ try {
79
+ parsed = text ? JSON.parse(text) : {};
80
+ } catch {
81
+ parsed = {};
82
+ }
83
+ return {
84
+ status: response.status,
85
+ body: typeof parsed === "object" && parsed !== null ? (parsed as Record<string, unknown>) : {},
86
+ };
87
+ }
88
+
89
+ function errorFrom(
90
+ status: number,
91
+ body: Record<string, unknown>,
92
+ fallback: string,
93
+ hint?: string,
94
+ ): SferenceAuthError {
95
+ const code = typeof body.error === "string" ? body.error : `http_${status}`;
96
+ const description = typeof body.error_description === "string" ? body.error_description : fallback;
97
+ return new SferenceAuthError(code, description, hint);
98
+ }
99
+
100
+ function toCredentials(tokens: Record<string, unknown>, now: number): OAuthCredentials {
101
+ const { access_token, refresh_token, expires_in } = tokens as Partial<TokenResponse>;
102
+ if (typeof access_token !== "string" || typeof refresh_token !== "string") {
103
+ throw new SferenceAuthError("invalid_response", "token response is missing tokens");
104
+ }
105
+ const lifetimeMs = (typeof expires_in === "number" ? expires_in : 0) * 1000;
106
+ return { access: access_token, refresh: refresh_token, expires: now + lifetimeMs - EXPIRY_SKEW_MS };
107
+ }
108
+
109
+ /** Run the device flow: show the code, wait for approval in the console, return the grant. */
110
+ export async function loginWithDeviceFlow(
111
+ baseUrl: string,
112
+ callbacks: OAuthLoginCallbacks,
113
+ deps: DeviceFlowDeps = {},
114
+ ): Promise<OAuthCredentials> {
115
+ const fetchImpl = deps.fetch ?? fetch;
116
+ const sleep = deps.sleep ?? abortableSleep;
117
+ const now = deps.now ?? Date.now;
118
+ const signal = callbacks.signal;
119
+
120
+ const start = await postJson(
121
+ fetchImpl,
122
+ `${baseUrl}/oauth/device_code`,
123
+ {
124
+ client_id: OAUTH_CLIENT_ID,
125
+ ...(deps.deviceLabel ? { device_label: deps.deviceLabel } : {}),
126
+ },
127
+ signal,
128
+ );
129
+ if (start.status !== 200) throw errorFrom(start.status, start.body, "could not start device login");
130
+ const userCode = String(start.body.user_code ?? "");
131
+ const deviceCode = String(start.body.device_code ?? "");
132
+ const verificationUri = String(start.body.verification_uri ?? "");
133
+ if (!userCode || !deviceCode || !verificationUri) {
134
+ throw new SferenceAuthError("invalid_response", "device_code response is incomplete");
135
+ }
136
+ let intervalS = Number(start.body.interval) || 5;
137
+ const expiresInS = Number(start.body.expires_in) || 600;
138
+
139
+ callbacks.onDeviceCode({
140
+ userCode,
141
+ // The console pre-fills the code from the query string, as `sference auth login` opens it.
142
+ verificationUri: `${verificationUri}?code=${encodeURIComponent(userCode)}`,
143
+ intervalSeconds: intervalS,
144
+ expiresInSeconds: expiresInS,
145
+ });
146
+ callbacks.onProgress?.("Waiting for approval in the sference console...");
147
+
148
+ const deadline = now() + expiresInS * 1000;
149
+ while (true) {
150
+ if (now() + intervalS * 1000 > deadline) {
151
+ throw new SferenceAuthError("expired_token", "device code expired before approval");
152
+ }
153
+ await sleep(intervalS * 1000, signal);
154
+ const poll = await postJson(
155
+ fetchImpl,
156
+ `${baseUrl}/oauth/token`,
157
+ {
158
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
159
+ client_id: OAUTH_CLIENT_ID,
160
+ device_code: deviceCode,
161
+ },
162
+ signal,
163
+ );
164
+ if (poll.status === 200) return toCredentials(poll.body, now());
165
+ const code = typeof poll.body.error === "string" ? poll.body.error : "";
166
+ if (code === "authorization_pending") continue;
167
+ if (code === "slow_down") {
168
+ intervalS += SLOW_DOWN_STEP_S;
169
+ continue;
170
+ }
171
+ throw errorFrom(poll.status, poll.body, "device login failed");
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Exchange the refresh token. The server rotates it: the returned pair
177
+ * replaces the old one, which pi persists before anything else can reuse it.
178
+ */
179
+ export async function refreshDeviceGrant(
180
+ baseUrl: string,
181
+ credentials: OAuthCredentials,
182
+ signal: AbortSignal,
183
+ deps: Pick<DeviceFlowDeps, "fetch" | "now"> = {},
184
+ ): Promise<OAuthCredentials> {
185
+ const fetchImpl = deps.fetch ?? fetch;
186
+ const now = deps.now ?? Date.now;
187
+ const result = await postJson(
188
+ fetchImpl,
189
+ `${baseUrl}/oauth/token`,
190
+ { grant_type: "refresh_token", client_id: OAUTH_CLIENT_ID, refresh_token: credentials.refresh },
191
+ signal,
192
+ );
193
+ if (result.status !== 200) {
194
+ throw errorFrom(
195
+ result.status,
196
+ result.body,
197
+ "token refresh failed",
198
+ "Run /login sference to sign in again.",
199
+ );
200
+ }
201
+ return toCredentials(result.body, now());
202
+ }
package/lib/catalog.ts ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Mapping from sference's `GET /v1/models` catalog to pi model configs.
3
+ *
4
+ * Pure (type-only imports) so `node --test` runs it without pi installed.
5
+ */
6
+
7
+ import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
8
+
9
+ import { CHAT_API, CLASSIFIER_API, DEFAULT_MODEL, MAX_OUTPUT_TOKENS } from "./config.ts";
10
+
11
+ export interface OffPeak {
12
+ /** "HH:MM" local to `timezone`; the window may wrap midnight. */
13
+ start: string;
14
+ end: string;
15
+ timezone: string;
16
+ price_factor: number;
17
+ }
18
+
19
+ /** One entry of the `GET /v1/models` response (the fields this extension reads). */
20
+ export interface SferenceCatalogModel {
21
+ id: string;
22
+ display_name?: string;
23
+ /** `text_generation` (default), `decisions`, `embeddings`, ... */
24
+ modality?: string;
25
+ alias_of?: string | null;
26
+ context_tokens?: number | null;
27
+ /** Not published today; honoured if the catalog starts to. */
28
+ max_output_tokens?: number | null;
29
+ capabilities?: {
30
+ image_input?: { supported?: boolean };
31
+ thinking?: { supported?: boolean };
32
+ };
33
+ pricing?: {
34
+ input_per_million_usd?: number | null;
35
+ output_per_million_usd?: number | null;
36
+ cached_input_per_million_usd?: number | null;
37
+ off_peak?: OffPeak | null;
38
+ };
39
+ /** ISO date the model is retired; retired models are skipped. */
40
+ retires_on?: string | null;
41
+ }
42
+
43
+ const FALLBACK_CONTEXT_WINDOW = 131072;
44
+
45
+ /**
46
+ * Levels the API accepts beyond pi's defaults. pi only offers `xhigh`/`max`
47
+ * when the map names them; both are valid `reasoning.effort` values.
48
+ */
49
+ const THINKING_LEVELS = { xhigh: "xhigh", max: "max" } as const;
50
+
51
+ /**
52
+ * The GLM-5.3 family always reasons and the API answers `reasoning.effort:
53
+ * "none"` with a 400. /v1/models has no field for it yet, so mirror the API's
54
+ * rule: the id, or the id an alias dispatches to (GLM-5.2 is served by 5.3
55
+ * weights).
56
+ * TODO: switch to a catalog capability once /v1/models publishes one
57
+ * (s-ference/sference-platform#1380); this rule silently misses any new
58
+ * always-reasoning family.
59
+ */
60
+ export function alwaysReasons(model: SferenceCatalogModel): boolean {
61
+ return [model.id, model.alias_of ?? ""].some((id) => id.toLowerCase().includes("glm-5.3"));
62
+ }
63
+
64
+ export function isRetired(model: SferenceCatalogModel, now: number = Date.now()): boolean {
65
+ if (!model.retires_on) return false;
66
+ const retiredAt = Date.parse(model.retires_on);
67
+ return Number.isFinite(retiredAt) && retiredAt <= now;
68
+ }
69
+
70
+ /** Whether pi can use the entry: chat and decisions models only. */
71
+ export function isSupported(model: SferenceCatalogModel): boolean {
72
+ const modality = model.modality ?? "text_generation";
73
+ return Boolean(model.id) && (modality === "text_generation" || modality === "decisions");
74
+ }
75
+
76
+ function imageInput(model: SferenceCatalogModel): ("text" | "image")[] {
77
+ return model.capabilities?.image_input?.supported ? ["text", "image"] : ["text"];
78
+ }
79
+
80
+ /** Map one catalog entry to a pi model config (chat or classifier). */
81
+ export function fromCatalog(model: SferenceCatalogModel): ProviderModelConfig {
82
+ const contextWindow = model.context_tokens ?? FALLBACK_CONTEXT_WINDOW;
83
+ const pricing = model.pricing ?? {};
84
+ const name = model.display_name || model.id;
85
+
86
+ if (model.modality === "decisions") {
87
+ return {
88
+ type: "classifier",
89
+ id: model.id,
90
+ name,
91
+ api: CLASSIFIER_API,
92
+ input: imageInput(model),
93
+ cost: {
94
+ input: pricing.input_per_million_usd ?? 0,
95
+ output: 0,
96
+ cacheRead: 0,
97
+ cacheWrite: 0,
98
+ },
99
+ contextWindow,
100
+ // Without this pi assumes TypeSafe: images as `assets` plus an
101
+ // opt-in header. sference takes data URLs in a top-level `images`.
102
+ compat: { imageInput: "images", sendImageOptInHeader: false },
103
+ } as ProviderModelConfig;
104
+ }
105
+
106
+ const reasoning = model.capabilities?.thinking?.supported ?? false;
107
+ return {
108
+ id: model.id,
109
+ name,
110
+ api: CHAT_API,
111
+ reasoning,
112
+ ...(reasoning
113
+ ? {
114
+ thinkingLevelMap: alwaysReasons(model)
115
+ ? // null marks "off" unsupported, so pi clamps it up to the
116
+ // lowest level instead of sending effort "none".
117
+ { ...THINKING_LEVELS, off: null }
118
+ : { ...THINKING_LEVELS },
119
+ }
120
+ : {}),
121
+ input: imageInput(model),
122
+ cost: {
123
+ input: pricing.input_per_million_usd ?? 0,
124
+ output: pricing.output_per_million_usd ?? 0,
125
+ cacheRead: pricing.cached_input_per_million_usd ?? 0,
126
+ cacheWrite: 0,
127
+ },
128
+ contextWindow,
129
+ // Prompt and output share the window, so a larger cap is never valid.
130
+ maxTokens: Math.min(model.max_output_tokens ?? MAX_OUTPUT_TOKENS, contextWindow),
131
+ // Leave the cap to the server (see MAX_OUTPUT_TOKENS).
132
+ compat: { supportsMaxOutputTokens: false },
133
+ };
134
+ }
135
+
136
+ /** The live, non-retired, pi-usable entries of a `/v1/models` payload. */
137
+ export function usableEntries(
138
+ payload: { data?: unknown },
139
+ now: number = Date.now(),
140
+ ): SferenceCatalogModel[] {
141
+ const data = Array.isArray(payload.data) ? payload.data : [];
142
+ return data.filter(
143
+ (entry): entry is SferenceCatalogModel =>
144
+ typeof entry === "object" &&
145
+ entry !== null &&
146
+ typeof (entry as SferenceCatalogModel).id === "string" &&
147
+ isSupported(entry as SferenceCatalogModel) &&
148
+ !isRetired(entry as SferenceCatalogModel, now),
149
+ );
150
+ }
151
+
152
+ /**
153
+ * Day-0 catalog, used only until the first /v1/models fetch is persisted.
154
+ * Holds the default model plus `SFERENCE_MODEL` (which `sference launch pi`
155
+ * sets), so `--model` resolves on a first, offline start.
156
+ */
157
+ export function seedModels(selected: string | undefined = process.env.SFERENCE_MODEL): ProviderModelConfig[] {
158
+ const seed: ProviderModelConfig[] = [
159
+ fromCatalog({
160
+ id: DEFAULT_MODEL,
161
+ display_name: "DeepSeek V4.1 Flash (1017)",
162
+ context_tokens: 1048576,
163
+ capabilities: { image_input: { supported: true }, thinking: { supported: true } },
164
+ pricing: {
165
+ input_per_million_usd: 0.35,
166
+ output_per_million_usd: 1.32,
167
+ cached_input_per_million_usd: 0.03,
168
+ },
169
+ }),
170
+ ];
171
+ const id = selected?.trim();
172
+ if (id && id !== DEFAULT_MODEL) {
173
+ // Metadata is unknown until the first fetch; assume a reasoning model so
174
+ // thinking levels stay available.
175
+ seed.push(fromCatalog({ id, capabilities: { thinking: { supported: true } } }));
176
+ }
177
+ return seed;
178
+ }
package/lib/config.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Environment-driven configuration. Read once at load; pi re-runs the factory
3
+ * on `/reload`, so env changes apply on the next reload or launch.
4
+ */
5
+
6
+ function positiveIntFromEnv(name: string, fallback: number): number {
7
+ const parsed = Number.parseInt(process.env[name] ?? "", 10);
8
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
9
+ }
10
+
11
+ function positiveFloatFromEnv(name: string, fallback: number): number {
12
+ const parsed = Number.parseFloat(process.env[name] ?? "");
13
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
14
+ }
15
+
16
+ /**
17
+ * `SFERENCE_BASE_URL` follows the CLI's convention (the API origin), but a
18
+ * value that already ends in `/v1` is accepted too.
19
+ */
20
+ export function normalizeBaseUrl(raw: string | undefined): string {
21
+ const base = (raw?.trim() || "https://api.sference.com").replace(/\/+$/u, "");
22
+ return base.endsWith("/v1") ? base : `${base}/v1`;
23
+ }
24
+
25
+ export const BASE_URL = normalizeBaseUrl(process.env.SFERENCE_BASE_URL);
26
+
27
+ export const PROVIDER_ID = "sference";
28
+
29
+ /** Chat runs on `/v1/responses`: one native reasoning knob, and pi sends `prompt_cache_key` for worker affinity. */
30
+ export const CHAT_API = "openai-responses";
31
+
32
+ /** sference's `/v1/decisions` speaks System One; pi's adapter posts to the `/v1/systemone` alias. */
33
+ export const CLASSIFIER_API = "typesafe-system-one";
34
+
35
+ /** Same default as `sference launch` (a pinned snapshot, not the retiring alias). */
36
+ export const DEFAULT_MODEL = "deepseek-ai/DeepSeek-V4.1-Flash-1017";
37
+
38
+ /**
39
+ * Queue admission ceiling, injected as `max_queue_wait_s` (API range 5–300).
40
+ * Without it streaming requests fail once the queue projects past 60s.
41
+ */
42
+ export const MAX_QUEUE_WAIT_S = Math.min(
43
+ Math.max(positiveIntFromEnv("SFERENCE_MAX_QUEUE_WAIT_S", 300), 5),
44
+ 300,
45
+ );
46
+
47
+ /**
48
+ * pi's own output budget (compaction reserve, context math). Not sent: the
49
+ * server applies the same 32768 to every streaming request and clamps it to
50
+ * the window with the real prompt length, which pi can only estimate.
51
+ */
52
+ export const MAX_OUTPUT_TOKENS = 32768;
53
+
54
+ /**
55
+ * Flex bills every token component at this factor of list price: the
56
+ * catalog-wide default, which every live model uses today.
57
+ * TODO: read it from /v1/models, or use the billed cost, once the API exposes
58
+ * either (s-ference/sference-platform#1381); a per-model or per-user override
59
+ * makes this constant wrong.
60
+ */
61
+ export const FLEX_PRICE_FACTOR = positiveFloatFromEnv("SFERENCE_FLEX_PRICE_FACTOR", 0.7);
62
+
63
+ /**
64
+ * Priority bills every token component at this factor of list price (a
65
+ * premium, for being scheduled ahead of default traffic): the platform's
66
+ * DEFAULT_PRIORITY_PRICE_FACTOR, applied when no per-user or per-model
67
+ * override exists. The tier is org-gated: an account without it gets a 400,
68
+ * not a silent downgrade.
69
+ * TODO: read it from /v1/models, or use the billed cost, once the API exposes
70
+ * either (s-ference/sference-platform#1381); a per-model or per-user override
71
+ * makes this constant wrong.
72
+ */
73
+ export const PRIORITY_PRICE_FACTOR = positiveFloatFromEnv("SFERENCE_PRIORITY_PRICE_FACTOR", 1.3);
74
+
75
+ /** Re-check /v1/models at most this often within one process (pi's built-in catalogs use the same). */
76
+ export const REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;
77
+
78
+ /**
79
+ * How long a single /v1/models fetch may hang before the refresh gives up on
80
+ * it (pi's own catalog client uses a 4s per-attempt timeout with retries;
81
+ * we make one attempt and let the next refresh retry).
82
+ */
83
+ export const CATALOG_TIMEOUT_S = positiveIntFromEnv("SFERENCE_CATALOG_TIMEOUT_S", 10);
84
+
85
+ /**
86
+ * Only `flex` and `priority` change behaviour; `auto`/`default`/`scale` are
87
+ * served at the default tier. Priority is rejected (400) on accounts
88
+ * without the tier enabled.
89
+ */
90
+ const requestedServiceTier = process.env.SFERENCE_SERVICE_TIER;
91
+ export const DEFAULT_SERVICE_TIER: "flex" | "priority" | undefined =
92
+ requestedServiceTier === "flex" || requestedServiceTier === "priority"
93
+ ? requestedServiceTier
94
+ : undefined;
95
+
96
+ /**
97
+ * Device-flow client. The platform registers `sference-cli` and
98
+ * `sference-switch` only; pi logs in as `sference-cli` but gets its own grant,
99
+ * so its rotating refresh token never races the CLI's.
100
+ */
101
+ export const OAUTH_CLIENT_ID = "sference-cli";
package/lib/pricing.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Cost accounting for chat requests.
3
+ *
4
+ * pi prices a message at list rates, and its Responses adapter applies
5
+ * OpenAI's own tier multipliers whenever the response echoes a tier (flex
6
+ * 0.5x, priority 2x). sference bills differently:
7
+ * - flex at `FLEX_PRICE_FACTOR` (0.7x) of list price;
8
+ * - priority at `PRIORITY_PRICE_FACTOR` (1.3x), a premium for being
9
+ * scheduled ahead of default traffic;
10
+ * - off-peak at the catalog's `off_peak.price_factor` for requests that
11
+ * arrive inside the window;
12
+ * - flex and off-peak do not stack: the lower factor wins. Priority is a
13
+ * premium, not a discount, so it multiplies with the off-peak factor.
14
+ * So the cost is recomputed from token counts rather than scaled from pi's.
15
+ */
16
+
17
+ import { FLEX_PRICE_FACTOR, PRIORITY_PRICE_FACTOR } from "./config.ts";
18
+ import type { OffPeak } from "./catalog.ts";
19
+
20
+ export interface UsageCost {
21
+ input: number;
22
+ output: number;
23
+ cacheRead: number;
24
+ cacheWrite: number;
25
+ total: number;
26
+ }
27
+
28
+ export interface UsageTokens {
29
+ input: number;
30
+ output: number;
31
+ cacheRead: number;
32
+ cacheWrite: number;
33
+ }
34
+
35
+ /** Per-million-token list rates, as pi stores them on a model. */
36
+ export interface Rates {
37
+ input: number;
38
+ output: number;
39
+ cacheRead: number;
40
+ cacheWrite: number;
41
+ }
42
+
43
+ function minutesOfDay(hhmm: string): number | undefined {
44
+ const match = /^(\d{1,2}):(\d{2})$/u.exec(hhmm.trim());
45
+ if (!match) return undefined;
46
+ return Number(match[1]) * 60 + Number(match[2]);
47
+ }
48
+
49
+ /** Whether `at` falls in the off-peak window, evaluated in the window's own timezone. */
50
+ export function inOffPeakWindow(offPeak: OffPeak, at: number): boolean {
51
+ const start = minutesOfDay(offPeak.start);
52
+ const end = minutesOfDay(offPeak.end);
53
+ if (start === undefined || end === undefined || start === end) return false;
54
+ let parts: Intl.DateTimeFormatPart[];
55
+ try {
56
+ parts = new Intl.DateTimeFormat("en-GB", {
57
+ timeZone: offPeak.timezone,
58
+ hour: "2-digit",
59
+ minute: "2-digit",
60
+ hourCycle: "h23",
61
+ }).formatToParts(new Date(at));
62
+ } catch {
63
+ return false; // unknown timezone: bill at list price rather than guess
64
+ }
65
+ const hour = Number(parts.find((part) => part.type === "hour")?.value);
66
+ const minute = Number(parts.find((part) => part.type === "minute")?.value);
67
+ if (!Number.isFinite(hour) || !Number.isFinite(minute)) return false;
68
+ const now = hour * 60 + minute;
69
+ return start < end ? now >= start && now < end : now >= start || now < end;
70
+ }
71
+
72
+ /**
73
+ * The multiplier sference applies to list price. `servedTier` is what the
74
+ * response says was served (a flex request on an account without flex is
75
+ * served, and billed, at the default tier; priority is never downgraded —
76
+ * an account without it rejects the request). `requestedAt` is when the
77
+ * request arrived: the server prices by arrival time.
78
+ */
79
+ export function priceFactor(options: {
80
+ servedTier?: string;
81
+ offPeak?: OffPeak | null;
82
+ requestedAt: number;
83
+ flexFactor?: number;
84
+ priorityFactor?: number;
85
+ }): number {
86
+ const tier =
87
+ options.servedTier === "flex"
88
+ ? (options.flexFactor ?? FLEX_PRICE_FACTOR)
89
+ : options.servedTier === "priority"
90
+ ? (options.priorityFactor ?? PRIORITY_PRICE_FACTOR)
91
+ : 1;
92
+ const offPeakFactor =
93
+ options.offPeak &&
94
+ options.offPeak.price_factor > 0 &&
95
+ options.offPeak.price_factor < 1 &&
96
+ inOffPeakWindow(options.offPeak, options.requestedAt)
97
+ ? options.offPeak.price_factor
98
+ : 1;
99
+ // Flex and off-peak are both discounts: the lower one wins. Priority is a
100
+ // premium, so it multiplies with the off-peak discount instead.
101
+ return options.servedTier === "priority" ? tier * offPeakFactor : Math.min(tier, offPeakFactor);
102
+ }
103
+
104
+ /** Cost of `tokens` at `rates` (per million) scaled by `factor`. */
105
+ export function costFor(tokens: UsageTokens, rates: Rates, factor: number): UsageCost {
106
+ const input = ((tokens.input * rates.input) / 1e6) * factor;
107
+ const output = ((tokens.output * rates.output) / 1e6) * factor;
108
+ const cacheRead = ((tokens.cacheRead * rates.cacheRead) / 1e6) * factor;
109
+ const cacheWrite = ((tokens.cacheWrite * rates.cacheWrite) / 1e6) * factor;
110
+ return { input, output, cacheRead, cacheWrite, total: input + output + cacheRead + cacheWrite };
111
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
- "name": "@sference/pi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@sference/pi",
3
+ "version": "0.10.0",
4
+ "description": "sference provider for pi: live /v1/models catalog (chat and decision models), SSO login, queue-wait tuning, flex/priority tiers and off-peak cost accounting. Published in lockstep with the sference CLI, which pins this package on `sference launch pi`.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "keywords": ["pi-package", "pi-extension", "sference"],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/s-ference/sference.git",
11
+ "directory": "cli/sference_cli/pi_extension"
12
+ },
13
+ "homepage": "https://sference.com",
14
+ "bugs": "https://github.com/s-ference/sference/issues",
15
+ "engines": {
16
+ "node": ">=22.19"
17
+ },
18
+ "files": ["index.ts", "lib", "README.md", "CHANGELOG.md"],
19
+ "pi": {
20
+ "extensions": ["./index.ts"]
21
+ },
22
+ "scripts": {
23
+ "test": "node --experimental-test-module-mocks --test \"test/*.test.ts\"",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "@earendil-works/pi-ai": "*",
28
+ "@earendil-works/pi-coding-agent": "*"
29
+ },
30
+ "devDependencies": {
31
+ "@earendil-works/pi-ai": "1.8.0",
32
+ "@earendil-works/pi-coding-agent": "1.8.0",
33
+ "@types/node": "^22.18.0",
34
+ "typescript": "~5.9.0"
35
+ }
36
+ }