@richardgill/pi-speed 0.0.0-stage → 0.0.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 CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # pi-speed
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
+ Set per-request speed for matching Claude and OpenAI models.
4
+
5
+ ```sh
6
+ pi install npm:@richardgill/pi-speed
7
+ ```
8
+
9
+ To try it without saving it to your settings:
10
+
11
+ ```sh
12
+ pi -e npm:@richardgill/pi-speed --speed fast
13
+ ```
14
+
15
+ - `--speed off|flex|fast|ultrafast` overrides the default for every model family in this process.
16
+ - `/speed` opens a picker with only tiers configured for the current model and not blocked for its endpoint. `/speed fast` sets an override for this process, taking precedence over the flag. It survives session changes but is never saved. `/speed status` shows the selected and applied tiers.
17
+ - The footer shows the applied tier, a fallback (e.g. `⚡ ultrafast→fast`), or `n/a` if the model family doesn't offer the requested tier. No footer entry means `off`.
18
+
19
+ ## Configuration
20
+
21
+ Create `speed.jsonc` in `PI_EXTENSION_CONFIG_DIR`, or in Pi's agent directory (normally `~/.pi/agent`) if that variable is unset. The file is optional. These are the built-in defaults:
22
+
23
+ ```jsonc
24
+ {
25
+ "modelFamilies": {
26
+ "claude": {
27
+ "api": "anthropic-messages",
28
+ "models": ["claude-opus-5-5*", "claude-fable-5-2*"],
29
+ "default": "off",
30
+ "speeds": [
31
+ { "name": "fast", "patch": { "speed": "fast" }, "costMultiplier": 2 },
32
+ ],
33
+ },
34
+ "gpt": {
35
+ "api": "openai-responses",
36
+ "models": ["gpt-6.2-*", "gpt-6.1-sol*", "gpt-6.1-terra*"],
37
+ "default": "fast",
38
+ "speeds": [
39
+ { "name": "ultrafast", "patch": { "service_tier": "ultrafast" }, "costMultiplier": 6 },
40
+ { "name": "fast", "patch": { "service_tier": "priority" } },
41
+ { "name": "flex", "patch": { "service_tier": "flex" } },
42
+ ],
43
+ },
44
+ },
45
+ "unavailable": {},
46
+ }
47
+ ```
48
+
49
+ Each top-level setting replaces its built-in value wholesale when supplied. A family matches by API and a glob on the bare model ID (no provider prefix); a registered model must not match two families. The speed names across all families, plus `off`, can be requested with `--speed` or `/speed <name>`, even if the picker doesn't list them. List tiers fastest first: if the host blocks the requested tier (use a lowercase host, including any non-default port), the extension tries lower entries, ending at `off`. A tier the family doesn't offer goes straight to standard speed. For example, set `"unavailable": { "gateway.example.com": ["ultrafast"] }` to disable that tier on a gateway. Step-down uses this config; it does not retry provider errors.
50
+
51
+ `patch` replaces top-level request fields only. `costMultiplier` defaults to 1 and covers only surcharges Pi doesn't already apply. For example, Pi already prices OpenAI priority and flex. Compaction and summaries use standard speed; cache-warming requests can use the selected tier but do not receive the extension's cost correction.
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@richardgill/pi-speed",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.2",
4
+ "keywords": [
5
+ "pi-package"
6
+ ],
7
+ "homepage": "https://github.com/richardgill/pi-extensions/tree/main/extensions/speed",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/richardgill/pi-extensions",
11
+ "directory": "extensions/speed"
12
+ },
13
+ "files": [
14
+ "src"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ ".": "./src/index.ts"
19
+ },
20
+ "dependencies": {
21
+ "minimatch": "10.2.5",
22
+ "zod": "4.3.6",
23
+ "@richardgill/pi-config": "0.0.9"
24
+ },
25
+ "peerDependencies": {
26
+ "@earendil-works/pi-ai": "*",
27
+ "@earendil-works/pi-coding-agent": "*"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "@earendil-works/pi-ai": {
31
+ "optional": true
32
+ },
33
+ "@earendil-works/pi-coding-agent": {
34
+ "optional": true
35
+ }
36
+ },
37
+ "pi": {
38
+ "extensions": [
39
+ "./src/index.ts"
40
+ ]
41
+ },
42
+ "scripts": {
43
+ "tsc": "tsc -p tsconfig.json --noEmit"
44
+ }
6
45
  }
package/src/config.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { loadConfigOrDefault } from "@richardgill/pi-config";
2
+ import { z } from "zod";
3
+
4
+ const nonEmpty = z.string().trim().min(1);
5
+ const host = z
6
+ .string()
7
+ .min(1)
8
+ .refine((value) => value === value.trim().toLowerCase(), "Use a lowercase host");
9
+ const speedEntry = z.strictObject({
10
+ name: nonEmpty.refine((speed) => speed !== "off" && speed !== "status", "Reserved speed name"),
11
+ patch: z.record(z.string(), z.unknown()),
12
+ costMultiplier: z.number().positive().default(1),
13
+ });
14
+
15
+ const modelFamily = z
16
+ .strictObject({
17
+ api: nonEmpty,
18
+ models: z.array(nonEmpty).min(1),
19
+ default: nonEmpty.default("off"),
20
+ speeds: z.array(speedEntry).min(1),
21
+ })
22
+ .refine(({ speeds }) => new Set(speeds.map(({ name }) => name)).size === speeds.length, {
23
+ path: ["speeds"],
24
+ message: "Duplicate speed names",
25
+ })
26
+ .refine(
27
+ (family) =>
28
+ family.default === "off" || family.speeds.some(({ name }) => name === family.default),
29
+ { path: ["default"], message: "Default must be off or a speed in this family" },
30
+ );
31
+
32
+ export const configSchema = z.strictObject({
33
+ modelFamilies: z.record(z.string().min(1), modelFamily).prefault({
34
+ claude: {
35
+ api: "anthropic-messages",
36
+ models: ["claude-opus-5-5*", "claude-fable-5-2*"],
37
+ default: "off",
38
+ speeds: [{ name: "fast", patch: { speed: "fast" }, costMultiplier: 2 }],
39
+ },
40
+ gpt: {
41
+ api: "openai-responses",
42
+ models: ["gpt-6.2-*", "gpt-6.1-sol*", "gpt-6.1-terra*"],
43
+ default: "fast",
44
+ speeds: [
45
+ { name: "ultrafast", patch: { service_tier: "ultrafast" }, costMultiplier: 6 },
46
+ { name: "fast", patch: { service_tier: "priority" } },
47
+ { name: "flex", patch: { service_tier: "flex" } },
48
+ ],
49
+ },
50
+ }),
51
+ unavailable: z.record(host, z.array(nonEmpty)).default({}),
52
+ });
53
+
54
+ export type SpeedConfig = z.infer<typeof configSchema>;
55
+
56
+ // Template preprocessing drops unknown fields before strict validation can reject them.
57
+ export const loadSpeedConfig = () =>
58
+ loadConfigOrDefault({ filename: "speed.jsonc", schema: configSchema, renderTemplates: false });
package/src/index.ts ADDED
@@ -0,0 +1,173 @@
1
+ import { writeSync } from "node:fs";
2
+ import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ import { loadSpeedConfig } from "./config";
6
+ import { findFamily, pickerSpeedNames, resolveSpeed, servedOtherTier, speedNames } from "./speed";
7
+
8
+ type Resolution = ReturnType<typeof resolveSpeed>;
9
+ type RequestIdentity = Pick<AssistantMessage, "api" | "provider" | "model">;
10
+ // The repo pins Pi types from before this 1.6.1 hook was available.
11
+ type SpeedExtensionAPI = ExtensionAPI & {
12
+ on(
13
+ event: "provider_stream_event",
14
+ handler: (event: RequestIdentity & { data: unknown }) => void,
15
+ ): void;
16
+ };
17
+
18
+ const liveKey = Symbol.for("@richardgill/pi-speed/live");
19
+ const processState = globalThis as typeof globalThis & { [liveKey]?: string };
20
+
21
+ const footer = (speed: Resolution) => {
22
+ if (speed.requested === "off") return undefined;
23
+ if (speed.blockedHost) return `⚡ ${speed.requested}→${speed.applied}`;
24
+ if (speed.unsupported) return `⚡ ${speed.requested} n/a`;
25
+ return speed.applied === "flex" ? "🐢 flex" : `⚡ ${speed.applied}`;
26
+ };
27
+
28
+ const status = (speed: Resolution, model: ExtensionContext["model"]) => {
29
+ const { requested, source, family, familyName, tier, blockedHost, unsupported, applied } = speed;
30
+ const selection = `Speed: ${requested}${source ? ` (from ${source})` : ""}`;
31
+ const familyDefault = family ? ` · ${familyName} default: ${family.default}` : "";
32
+ const modelLabel = model ? `${model.provider}/${model.id}` : "none";
33
+ const familyLabel = familyName ? ` (${familyName})` : "";
34
+ const cost = tier && tier.costMultiplier !== 1 ? ` · ${tier.costMultiplier}x cost` : "";
35
+ const reason = blockedHost ? ` (${requested} unavailable on ${blockedHost})` : "";
36
+ const unavailable = unsupported ? ` (${requested} n/a)` : "";
37
+ return `${selection}${familyDefault}\nModel: ${modelLabel}${familyLabel} → ${applied}${cost}${reason}${unavailable}`;
38
+ };
39
+
40
+ const fail = (message: string): never => {
41
+ // Pi restores the terminal on exit; print after that so the TUI does not erase the error.
42
+ process.once("exit", () => writeSync(2, `pi-speed: ${message}\n`));
43
+ process.exit(1);
44
+ };
45
+
46
+ const isModelPayload = (payload: unknown, model: Model<Api>): payload is Record<string, unknown> =>
47
+ Object.prototype.toString.call(payload) === "[object Object]" &&
48
+ (payload as Record<string, unknown>).model === model.id;
49
+
50
+ const matchesRequest = (event: RequestIdentity, model: Model<Api>) =>
51
+ event.api === model.api && event.provider === model.provider && event.model === model.id;
52
+
53
+ const usedServerFallback = (message: AssistantMessage, model: Model<Api>) => {
54
+ if (!message.responseModel || model.api !== "anthropic-messages") return false;
55
+ const compat = model.compat as
56
+ | { allowedFallbackModels?: { provider: string; model: string }[] }
57
+ | undefined;
58
+ return compat?.allowedFallbackModels?.some(
59
+ (fallback) => fallback.provider === model.provider && fallback.model === message.responseModel,
60
+ );
61
+ };
62
+
63
+ const scaleCost = (message: AssistantMessage, multiplier: number) => {
64
+ const { usage } = message;
65
+ const cost: AssistantMessage["usage"]["cost"] & { totalFromProvider?: boolean } = usage.cost;
66
+ if (cost.totalFromProvider) return;
67
+
68
+ return {
69
+ message: {
70
+ ...message,
71
+ usage: {
72
+ ...usage,
73
+ cost: {
74
+ ...cost,
75
+ input: cost.input * multiplier,
76
+ output: cost.output * multiplier,
77
+ cacheRead: cost.cacheRead * multiplier,
78
+ cacheWrite: cost.cacheWrite * multiplier,
79
+ total: cost.total * multiplier,
80
+ },
81
+ },
82
+ },
83
+ };
84
+ };
85
+
86
+ export default (pi: SpeedExtensionAPI) => {
87
+ const config = loadSpeedConfig();
88
+ const names = speedNames(config);
89
+ const choices = `Use one of: ${names.join(", ")}`;
90
+ let pending: { model: Model<Api>; tier: NonNullable<Resolution["tier"]> } | undefined;
91
+
92
+ const current = (ctx: ExtensionContext) => {
93
+ const flag = pi.getFlag("speed");
94
+ return resolveSpeed({
95
+ config,
96
+ model: ctx.model,
97
+ live: processState[liveKey],
98
+ flag: typeof flag === "string" ? flag : undefined,
99
+ });
100
+ };
101
+ const refreshFooter = (ctx: ExtensionContext) =>
102
+ ctx.ui.setStatus("pi-speed", footer(current(ctx)));
103
+
104
+ pi.registerFlag("speed", { type: "string", description: `Set request speed. ${choices}` });
105
+ pi.on("session_start", (_event, ctx) => {
106
+ const value = pi.getFlag("speed");
107
+ if (typeof value === "string" && !names.includes(value)) {
108
+ fail(`invalid --speed ${JSON.stringify(value)}. ${choices}`);
109
+ }
110
+
111
+ try {
112
+ for (const model of ctx.modelRegistry.getAll()) findFamily(config, model);
113
+ refreshFooter(ctx);
114
+ } catch (error) {
115
+ fail(error instanceof Error ? error.message : String(error));
116
+ }
117
+ });
118
+ pi.on("model_select", (_event, ctx) => refreshFooter(ctx));
119
+
120
+ pi.registerCommand("speed", {
121
+ description: "Choose request speed for this process, or show /speed status",
122
+ handler: async (args, ctx) => {
123
+ const arg = args.trim();
124
+ if (arg === "status") {
125
+ ctx.ui.notify(status(current(ctx), ctx.model), "info");
126
+ return;
127
+ }
128
+
129
+ const selected =
130
+ arg || (await ctx.ui.select("Speed for this process", pickerSpeedNames(config, ctx.model)));
131
+ if (selected === undefined) return;
132
+ if (!names.includes(selected)) {
133
+ ctx.ui.notify(`Invalid speed ${JSON.stringify(selected)}. ${choices}`, "error");
134
+ return;
135
+ }
136
+
137
+ processState[liveKey] = selected;
138
+ const speed = current(ctx);
139
+ ctx.ui.setStatus("pi-speed", footer(speed));
140
+ ctx.ui.notify(status(speed, ctx.model), "info");
141
+ },
142
+ });
143
+
144
+ pi.on("before_provider_request", ({ payload }, ctx) => {
145
+ pending = undefined;
146
+ const { model } = ctx;
147
+ if (!model || !isModelPayload(payload, model)) return;
148
+
149
+ const { tier } = current(ctx);
150
+ if (!tier) return;
151
+ if (tier.costMultiplier !== 1) pending = { model, tier };
152
+ return { ...payload, ...tier.patch };
153
+ });
154
+
155
+ pi.on("provider_stream_event", (event) => {
156
+ if (!pending || !matchesRequest(event, pending.model)) return;
157
+
158
+ const requested = pending.tier.patch.service_tier;
159
+ if (typeof requested === "string" && servedOtherTier(event.data, requested))
160
+ pending = undefined;
161
+ });
162
+
163
+ pi.on("message_end", ({ message }) => {
164
+ if (message.role !== "assistant") return;
165
+ // Cache warming has no message_end; every main request overwrites its pending correction.
166
+ const request = pending;
167
+ pending = undefined;
168
+ if (!request || !matchesRequest(message, request.model)) return;
169
+ if (usedServerFallback(message, request.model)) return;
170
+
171
+ return scaleCost(message, request.tier.costMultiplier);
172
+ });
173
+ };
package/src/speed.ts ADDED
@@ -0,0 +1,85 @@
1
+ import { minimatch } from "minimatch";
2
+
3
+ import type { SpeedConfig } from "./config";
4
+
5
+ type Model = { api: string; id: string; provider: string; baseUrl: string };
6
+ type Family = SpeedConfig["modelFamilies"][string];
7
+
8
+ const matchesFamily = (model: Pick<Model, "api" | "id">, family: Family) =>
9
+ family.api === model.api &&
10
+ family.models.some((pattern) => minimatch(model.id, pattern, { nocase: true }));
11
+
12
+ export const findFamily = (config: SpeedConfig, model: Model | undefined) => {
13
+ if (!model) return undefined;
14
+
15
+ const matches = Object.entries(config.modelFamilies).filter(([, family]) =>
16
+ matchesFamily(model, family),
17
+ );
18
+ if (matches.length > 1) {
19
+ const names = matches.map(([name]) => JSON.stringify(name)).join(", ");
20
+ throw new Error(
21
+ `speed.jsonc: ${model.provider}/${model.id} matches multiple families: ${names}`,
22
+ );
23
+ }
24
+
25
+ return matches[0];
26
+ };
27
+
28
+ const canonicalTier = (tier: string) => (tier === "fast" ? "priority" : tier);
29
+
30
+ export const servedOtherTier = (data: unknown, requested: string) => {
31
+ const event = data as { type?: string; response?: { service_tier?: unknown } } | null;
32
+ if (event?.type !== "response.completed" && event?.type !== "response.incomplete") return false;
33
+
34
+ const served = event.response?.service_tier;
35
+ return typeof served === "string" && canonicalTier(served) !== canonicalTier(requested);
36
+ };
37
+
38
+ // Display slower entries first; each family declares its entries fastest first.
39
+ export const speedNames = (config: SpeedConfig) => [
40
+ "off",
41
+ ...new Set(
42
+ Object.values(config.modelFamilies)
43
+ .flatMap(({ speeds }) => speeds.map(({ name }) => name))
44
+ .reverse(),
45
+ ),
46
+ ];
47
+
48
+ export const resolveSpeed = ({
49
+ config,
50
+ model,
51
+ live,
52
+ flag,
53
+ }: {
54
+ config: SpeedConfig;
55
+ model?: Model;
56
+ live?: string;
57
+ flag?: string;
58
+ }) => {
59
+ const [familyName, family] = findFamily(config, model) ?? [];
60
+ const requested = live ?? flag ?? family?.default ?? "off";
61
+ let source: string | undefined;
62
+ if (live !== undefined) source = "/speed";
63
+ else if (flag !== undefined) source = "--speed";
64
+
65
+ const speeds = family?.speeds ?? [];
66
+ const index = speeds.findIndex(({ name }) => name === requested);
67
+ const host = model && index >= 0 ? URL.parse(model.baseUrl)?.host : undefined;
68
+ const blocked = host && Object.hasOwn(config.unavailable, host) ? config.unavailable[host] : [];
69
+ const tier =
70
+ index >= 0 ? speeds.slice(index).find(({ name }) => !blocked.includes(name)) : undefined;
71
+
72
+ return {
73
+ requested,
74
+ source,
75
+ familyName,
76
+ family,
77
+ tier,
78
+ applied: tier?.name ?? "off",
79
+ unsupported: index < 0 && requested !== "off",
80
+ blockedHost: index >= 0 && tier?.name !== requested ? host : undefined,
81
+ };
82
+ };
83
+
84
+ export const pickerSpeedNames = (config: SpeedConfig, model: Model | undefined) =>
85
+ speedNames(config).filter((live) => resolveSpeed({ config, model, live }).applied === live);