pi-service-tier 0.3.0 โ†’ 0.4.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # โšก pi-service-tier
2
2
 
3
- A [pi](https://github.com/earendil-works/pi-mono/tree/main/packages/coding-agent)
4
- extension that toggles fast mode and applies provider service tiers.
3
+ A [Pi](https://pi.dev) extension that toggles fast mode and applies provider
4
+ service tiers.
5
5
 
6
6
  ## ๐Ÿš€ Installation
7
7
 
@@ -14,22 +14,39 @@ pi install npm:pi-service-tier
14
14
  - Adds service tier parameters to supported provider requests when a tier is
15
15
  configured
16
16
  - Adds `/fast` to toggle the current model provider between fast mode and off
17
- - Adds `/service-tier` to configure all supported providers from an interactive
18
- modal
17
+ for this session only
18
+ - Adds `/service-tier` to configure global defaults for all supported providers
19
+ from an interactive modal
19
20
  - Adds an optional service tier widget when `pi-fancy-footer` is installed
20
21
 
21
22
  ## ๐Ÿš€ Commands
22
23
 
23
- - `/fast`: toggles the current model provider between its fast tier and off. The
24
- supported providers all use `priority` as the fast tier.
24
+ - `/fast`: toggles the current model provider between its fast tier and off
25
+ **in this session**, without changing other sessions or your global defaults.
26
+ The supported providers all use `priority` as the fast tier.
25
27
 
26
- - `/service-tier`: opens an interactive editor. The current model provider
27
- appears first, followed by the remaining supported providers. Press Enter or
28
- Space to cycle through `off` and the provider-specific tiers.
28
+ - `/service-tier`: opens an interactive editor for **global defaults**. The
29
+ current model provider appears first, followed by the remaining supported
30
+ providers. Press Enter or Space to cycle through `off` and the provider-specific
31
+ tiers. Session overrides take precedence over these defaults.
32
+
33
+ ### Session scope
34
+
35
+ Run `/fast` in the session you want to speed up, then run it again to turn fast
36
+ mode off. Each provider has its own override, so switching models preserves your
37
+ choices. Turning fast mode off also overrides a globally configured tier; it
38
+ leaves that provider's request parameters unchanged rather than restoring `flex`
39
+ or `standard`.
40
+
41
+ Overrides are saved with the session and restored on resume or extension reload.
42
+ They follow the active conversation branch: `/tree` restores the choices at the
43
+ selected point, and `/fork` or `/clone` inherits the choices on the copied branch.
44
+ Later toggles in a fork do not affect its parent. `/new` starts without overrides
45
+ and uses your global defaults.
29
46
 
30
47
  ## โš™๏ธ Configuration
31
48
 
32
- Run `/service-tier` or create `~/.pi/agent/service-tier.json`:
49
+ Run `/service-tier` or create `~/.pi/agent/service-tier.json` to set global defaults:
33
50
 
34
51
  ```json
35
52
  {
@@ -51,7 +68,10 @@ Run `/service-tier` or create `~/.pi/agent/service-tier.json`:
51
68
  | `google` | `flex`, `priority` | `priority` |
52
69
  | `google-vertex` | `flex`, `priority` | `priority` |
53
70
 
54
- To turn a provider off, omit its key. Only the values listed above are accepted.
71
+ To turn a provider off by default, omit its key. Only the values listed above are
72
+ accepted. Providers without a session override continue to pick up global changes.
73
+ Existing global settings, including those saved by earlier versions of `/fast`,
74
+ remain in effect. Use `/service-tier` to change them.
55
75
  Batch APIs are separate asynchronous APIs and are not configured by this
56
76
  extension.
57
77
 
@@ -59,8 +79,8 @@ extension.
59
79
 
60
80
  When [pi-fancy-footer](https://github.com/mavam/pi-fancy-footer) is installed,
61
81
  the widget appears only when the active model uses a supported provider/API pair
62
- and that provider has a configured tier. It shows a single `โšก` without the tier
63
- name to keep the footer compact.
82
+ and that provider has an effective tier after applying session overrides. It shows
83
+ a single `โšก` without the tier name to keep the footer compact.
64
84
 
65
85
  The widget id is `pi-service-tier.service-tier`. It uses the current
66
86
  `pi-fancy-footer` event protocol, with row `1`, position `8`, right alignment,
@@ -76,12 +96,6 @@ when the footer announces that it is ready.
76
96
  first-class extension path for that option, displayed usage costs can omit
77
97
  flex or priority multipliers.
78
98
 
79
- ## ๐Ÿงน Uninstall
80
-
81
- ```sh
82
- pi remove npm:pi-service-tier
83
- ```
84
-
85
99
  ## ๐Ÿ“„ License
86
100
 
87
101
  [MIT](LICENSE)
package/config.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { Type } from "typebox";
5
+ import { Compile } from "typebox/compile";
6
+
7
+ import {
8
+ DEFAULT_SERVICE_TIER_CONFIG,
9
+ SERVICE_TIER_PROVIDERS,
10
+ SERVICE_TIER_PROVIDER_DEFINITIONS,
11
+ isRecord,
12
+ type ServiceTierConfigSnapshot,
13
+ type ServiceTierName,
14
+ type ServiceTierProvider,
15
+ } from "./domain.ts";
16
+
17
+ export const SERVICE_TIER_CONFIG_FILE = "service-tier.json";
18
+
19
+ function serviceTierNames(provider: ServiceTierProvider): ServiceTierName[] {
20
+ return SERVICE_TIER_PROVIDER_DEFINITIONS[provider].tiers.map(
21
+ (serviceTier) => serviceTier.name,
22
+ );
23
+ }
24
+
25
+ function literalUnion(values: readonly ServiceTierName[]) {
26
+ return Type.Union(values.map((value) => Type.Literal(value)));
27
+ }
28
+
29
+ const serviceTierConfigSchema = Type.Object(
30
+ {
31
+ openai: Type.Optional(literalUnion(serviceTierNames("openai"))),
32
+ "openai-codex": Type.Optional(
33
+ literalUnion(serviceTierNames("openai-codex")),
34
+ ),
35
+ anthropic: Type.Optional(literalUnion(serviceTierNames("anthropic"))),
36
+ google: Type.Optional(literalUnion(serviceTierNames("google"))),
37
+ "google-vertex": Type.Optional(
38
+ literalUnion(serviceTierNames("google-vertex")),
39
+ ),
40
+ },
41
+ { additionalProperties: false },
42
+ );
43
+ const validateServiceTierConfig = Compile(serviceTierConfigSchema);
44
+
45
+ function formatValidationErrors(filePath: string, value: unknown): string {
46
+ const errors = Array.from(validateServiceTierConfig.Errors(value));
47
+ const unknownKeys = isRecord(value)
48
+ ? Object.keys(value).filter(
49
+ (key) =>
50
+ !(SERVICE_TIER_PROVIDERS as readonly string[]).includes(key),
51
+ )
52
+ : [];
53
+ if (unknownKeys.length > 0) {
54
+ return `Invalid ${filePath}: unknown setting ${unknownKeys.map((key) => `"${key}"`).join(", ")}`;
55
+ }
56
+ return `Invalid ${filePath}: ${errors
57
+ .map((error) => `${error.instancePath || "/"} ${error.message}`)
58
+ .join(", ")}`;
59
+ }
60
+
61
+ export function getDefaultAgentDir(): string {
62
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
63
+ }
64
+
65
+ export function getServiceTierConfigPath(
66
+ agentDir = getDefaultAgentDir(),
67
+ ): string {
68
+ return join(agentDir, SERVICE_TIER_CONFIG_FILE);
69
+ }
70
+
71
+ export function parseServiceTierConfigValue(
72
+ filePath: string,
73
+ value: unknown,
74
+ ): ServiceTierConfigSnapshot {
75
+ if (value === undefined) return { ...DEFAULT_SERVICE_TIER_CONFIG };
76
+ if (!validateServiceTierConfig.Check(value)) {
77
+ throw new Error(formatValidationErrors(filePath, value));
78
+ }
79
+
80
+ const config = value as ServiceTierConfigSnapshot;
81
+ const result: ServiceTierConfigSnapshot = {};
82
+ for (const provider of SERVICE_TIER_PROVIDERS) {
83
+ const serviceTier = config[provider];
84
+ if (serviceTier !== undefined) result[provider] = serviceTier;
85
+ }
86
+ return result;
87
+ }
88
+
89
+ export function loadServiceTierConfig(
90
+ configPath = getServiceTierConfigPath(),
91
+ ): ServiceTierConfigSnapshot {
92
+ if (!existsSync(configPath)) return { ...DEFAULT_SERVICE_TIER_CONFIG };
93
+
94
+ let parsed: unknown;
95
+ try {
96
+ parsed = JSON.parse(readFileSync(configPath, "utf8"));
97
+ } catch (error) {
98
+ const message = error instanceof Error ? error.message : String(error);
99
+ throw new Error(`Failed to parse ${configPath}: ${message}`);
100
+ }
101
+
102
+ return parseServiceTierConfigValue(configPath, parsed);
103
+ }
104
+
105
+ export function writeServiceTierConfigSnapshot(
106
+ config: ServiceTierConfigSnapshot,
107
+ configPath = getServiceTierConfigPath(),
108
+ ): void {
109
+ mkdirSync(dirname(configPath), { recursive: true });
110
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
111
+ }
package/domain.ts ADDED
@@ -0,0 +1,203 @@
1
+ export const SERVICE_TIER_PROVIDERS = [
2
+ "openai",
3
+ "openai-codex",
4
+ "anthropic",
5
+ "google",
6
+ "google-vertex",
7
+ ] as const;
8
+ export type ServiceTierProvider = (typeof SERVICE_TIER_PROVIDERS)[number];
9
+
10
+ export type ServiceTierName = "flex" | "priority" | "standard";
11
+ /** An omitted provider leaves the provider's default behavior unchanged. */
12
+ export type ServiceTierConfigSnapshot = Partial<
13
+ Record<ServiceTierProvider, ServiceTierName>
14
+ >;
15
+
16
+ export type ServiceTierSelection = ServiceTierName | "";
17
+
18
+ /** Read-only policy input, independent of where settings are stored. */
19
+ export type ServiceTierSettings = Readonly<
20
+ Partial<Record<ServiceTierProvider, ServiceTierSelection>>
21
+ >;
22
+
23
+ /** Only the model fields this extension needs, including untrusted inputs. */
24
+ export interface ServiceTierModel {
25
+ readonly provider?: unknown;
26
+ readonly api?: unknown;
27
+ readonly id?: unknown;
28
+ readonly name?: unknown;
29
+ }
30
+
31
+ export interface ServiceTier {
32
+ name: ServiceTierName;
33
+ value: string;
34
+ }
35
+
36
+ export const DEFAULT_SERVICE_TIER_CONFIG: ServiceTierConfigSnapshot = {};
37
+
38
+ export interface ServiceTierProviderDefinition {
39
+ label: string;
40
+ api: string;
41
+ tiers: readonly ServiceTier[];
42
+ fastTier?: ServiceTierName;
43
+ }
44
+
45
+ function tier(name: ServiceTierName, value: string = name): ServiceTier {
46
+ return { name, value };
47
+ }
48
+
49
+ export const SERVICE_TIER_PROVIDER_DEFINITIONS: Record<
50
+ ServiceTierProvider,
51
+ ServiceTierProviderDefinition
52
+ > = {
53
+ openai: {
54
+ label: "OpenAI",
55
+ api: "openai-responses",
56
+ tiers: [tier("flex"), tier("priority")],
57
+ fastTier: "priority",
58
+ },
59
+ "openai-codex": {
60
+ label: "OpenAI Codex",
61
+ api: "openai-codex-responses",
62
+ tiers: [tier("flex"), tier("priority")],
63
+ fastTier: "priority",
64
+ },
65
+ anthropic: {
66
+ label: "Anthropic",
67
+ api: "anthropic-messages",
68
+ tiers: [tier("priority", "auto"), tier("standard", "standard_only")],
69
+ fastTier: "priority",
70
+ },
71
+ google: {
72
+ label: "Google Gemini",
73
+ api: "google-generative-ai",
74
+ tiers: [tier("flex"), tier("priority")],
75
+ fastTier: "priority",
76
+ },
77
+ "google-vertex": {
78
+ label: "Google Vertex AI",
79
+ api: "google-vertex",
80
+ tiers: [tier("flex"), tier("priority")],
81
+ fastTier: "priority",
82
+ },
83
+ };
84
+
85
+ export function isRecord(value: unknown): value is Record<string, unknown> {
86
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
87
+ }
88
+
89
+ export function isServiceTierProvider(
90
+ value: unknown,
91
+ ): value is ServiceTierProvider {
92
+ return (
93
+ typeof value === "string" &&
94
+ (SERVICE_TIER_PROVIDERS as readonly string[]).includes(value)
95
+ );
96
+ }
97
+
98
+ export function modelSupportsServiceTier(
99
+ model: ServiceTierModel | undefined,
100
+ ): boolean {
101
+ return getServiceTierProviderForModel(model) !== undefined;
102
+ }
103
+
104
+ export function getServiceTierProviderForModel(
105
+ model: ServiceTierModel | undefined,
106
+ ): ServiceTierProvider | undefined {
107
+ if (!model || !isServiceTierProvider(model.provider)) return undefined;
108
+ const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[model.provider];
109
+ return model.api === definition.api ? model.provider : undefined;
110
+ }
111
+
112
+ export function getConfiguredServiceTier(
113
+ config: ServiceTierSettings,
114
+ provider: ServiceTierProvider | undefined,
115
+ ): ServiceTierSelection {
116
+ return provider ? (config[provider] ?? "") : "";
117
+ }
118
+
119
+ export function resolveEffectiveServiceTier(
120
+ config: ServiceTierSettings,
121
+ model: ServiceTierModel | undefined,
122
+ ): ServiceTierSelection {
123
+ return getConfiguredServiceTier(config, getServiceTierProviderForModel(model));
124
+ }
125
+
126
+ function getTier(
127
+ provider: ServiceTierProvider,
128
+ serviceTierName: ServiceTierName,
129
+ ): ServiceTier | undefined {
130
+ return SERVICE_TIER_PROVIDER_DEFINITIONS[provider].tiers.find(
131
+ (serviceTier) => serviceTier.name === serviceTierName,
132
+ );
133
+ }
134
+
135
+ function applyPayloadServiceTier(
136
+ payload: Record<string, unknown>,
137
+ provider: ServiceTierProvider,
138
+ value: string,
139
+ ): Record<string, unknown> {
140
+ if (provider === "google" || provider === "google-vertex") {
141
+ return {
142
+ ...payload,
143
+ config: {
144
+ ...(isRecord(payload.config) ? payload.config : {}),
145
+ serviceTier: value,
146
+ },
147
+ };
148
+ }
149
+
150
+ return { ...payload, service_tier: value };
151
+ }
152
+
153
+ export function applyServiceTierToPayload(
154
+ payload: unknown,
155
+ config: ServiceTierSettings,
156
+ model: ServiceTierModel | undefined,
157
+ ): unknown | undefined {
158
+ const provider = getServiceTierProviderForModel(model);
159
+ const serviceTierName = getConfiguredServiceTier(config, provider);
160
+ if (!provider || !serviceTierName || !isRecord(payload)) return undefined;
161
+
162
+ const serviceTier = getTier(provider, serviceTierName);
163
+ if (!serviceTier) return undefined;
164
+
165
+ return applyPayloadServiceTier(payload, provider, serviceTier.value);
166
+ }
167
+
168
+ export interface FastToggleResult {
169
+ provider: ServiceTierProvider;
170
+ serviceTier: ServiceTierSelection;
171
+ fast: boolean;
172
+ }
173
+
174
+ export function toggleFastServiceTier(
175
+ config: ServiceTierSettings,
176
+ model: ServiceTierModel | undefined,
177
+ ): FastToggleResult | undefined {
178
+ const provider = getServiceTierProviderForModel(model);
179
+ if (!provider) return undefined;
180
+
181
+ const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[provider];
182
+ if (!definition.fastTier) return undefined;
183
+
184
+ const current = getConfiguredServiceTier(config, provider);
185
+ const fast = current !== definition.fastTier;
186
+ const serviceTier = fast ? definition.fastTier : "";
187
+ return {
188
+ provider,
189
+ serviceTier,
190
+ fast,
191
+ };
192
+ }
193
+
194
+ export function setProviderServiceTier(
195
+ config: ServiceTierConfigSnapshot,
196
+ provider: ServiceTierProvider,
197
+ value: ServiceTierSelection,
198
+ ): ServiceTierConfigSnapshot {
199
+ const next = { ...config };
200
+ if (value === "") delete next[provider];
201
+ else next[provider] = value;
202
+ return next;
203
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-service-tier",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Fast mode and provider service-tier controls for pi",
5
5
  "type": "module",
6
6
  "peerDependencies": {
@@ -11,6 +11,10 @@
11
11
  "files": [
12
12
  "service-tier.ts",
13
13
  "shared.ts",
14
+ "domain.ts",
15
+ "config.ts",
16
+ "settings.ts",
17
+ "session-state.ts",
14
18
  "README.md",
15
19
  "screenshot.png",
16
20
  "LICENSE"
package/service-tier.ts CHANGED
@@ -14,17 +14,28 @@ import {
14
14
  DEFAULT_SERVICE_TIER_CONFIG,
15
15
  SERVICE_TIER_PROVIDER_DEFINITIONS,
16
16
  applyServiceTierToPayload,
17
- createServiceTierSections,
18
- getServiceTierConfigPath,
19
17
  isServiceTierProvider,
20
- loadServiceTierConfig,
21
18
  resolveEffectiveServiceTier,
22
19
  setProviderServiceTier,
23
20
  toggleFastServiceTier,
24
- writeServiceTierConfigSnapshot,
25
- type ServiceTierName,
21
+ type ServiceTierSelection,
22
+ type ServiceTierSettings,
26
23
  type ServiceTierConfigSnapshot,
27
- } from "./shared.ts";
24
+ type ServiceTierName,
25
+ } from "./domain.ts";
26
+ import {
27
+ getServiceTierConfigPath,
28
+ loadServiceTierConfig,
29
+ writeServiceTierConfigSnapshot,
30
+ } from "./config.ts";
31
+ import { createServiceTierSections } from "./settings.ts";
32
+ import {
33
+ SERVICE_TIER_SESSION_ENTRY,
34
+ mergeServiceTierSettings,
35
+ restoreServiceTierOverrides,
36
+ type ServiceTierSessionState,
37
+ type SessionServiceTierOverrides,
38
+ } from "./session-state.ts";
28
39
 
29
40
  export const SERVICE_TIER_WIDGET_ID = "pi-service-tier.service-tier";
30
41
 
@@ -63,8 +74,9 @@ function createServiceTierSettingItems(
63
74
  }
64
75
 
65
76
  export default function (pi: ExtensionAPI) {
66
- let currentServiceTier: ServiceTierName | "" = "";
77
+ let currentServiceTier: ServiceTierSelection = "";
67
78
  let lastConfigWarning = "";
79
+ let sessionOverrides: SessionServiceTierOverrides = {};
68
80
 
69
81
  const publishFancyFooterWidget = (): void => {
70
82
  pi.events.emit(FANCY_FOOTER_WIDGET_EVENT, {
@@ -132,11 +144,15 @@ export default function (pi: ExtensionAPI) {
132
144
  }
133
145
  };
134
146
 
147
+ const effectiveSettings = (
148
+ defaults = loadConfigOrDefault(),
149
+ ): ServiceTierSettings => mergeServiceTierSettings(defaults, sessionOverrides);
150
+
135
151
  const refreshServiceTier = (
136
152
  ctx: ExtensionContext,
137
- config = loadConfigOrDefault(),
153
+ config = effectiveSettings(),
138
154
  forceRefresh = false,
139
- ): ServiceTierName | "" => {
155
+ ): ServiceTierSelection => {
140
156
  const nextServiceTier = resolveEffectiveServiceTier(config, ctx.model);
141
157
  if (currentServiceTier === nextServiceTier && !forceRefresh) {
142
158
  return currentServiceTier;
@@ -153,7 +169,7 @@ export default function (pi: ExtensionAPI) {
153
169
  ): boolean => {
154
170
  try {
155
171
  writeServiceTierConfigSnapshot(config);
156
- refreshServiceTier(ctx, config, true);
172
+ refreshServiceTier(ctx, effectiveSettings(config), true);
157
173
  return true;
158
174
  } catch (error) {
159
175
  notifyConfigWriteError(ctx, error);
@@ -162,12 +178,12 @@ export default function (pi: ExtensionAPI) {
162
178
  };
163
179
 
164
180
  pi.registerCommand("fast", {
165
- description: "Toggle fast service tier for the current model provider.",
181
+ description: "Toggle fast service tier for the current provider in this session.",
166
182
  handler: async (_args, ctx) => {
167
183
  const config = loadConfigForCommand(ctx);
168
184
  if (!config) return;
169
185
 
170
- const result = toggleFastServiceTier(config, ctx.model);
186
+ const result = toggleFastServiceTier(effectiveSettings(config), ctx.model);
171
187
  if (!result) {
172
188
  ctx.ui.notify(
173
189
  `Service tier is not supported for ${formatModel(ctx.model)}.`,
@@ -176,19 +192,31 @@ export default function (pi: ExtensionAPI) {
176
192
  return;
177
193
  }
178
194
 
179
- if (!writeAndRefresh(ctx, result.config)) return;
195
+ const state: ServiceTierSessionState = {
196
+ version: 1,
197
+ overrides: { ...sessionOverrides, [result.provider]: result.serviceTier },
198
+ };
199
+ try {
200
+ pi.appendEntry(SERVICE_TIER_SESSION_ENTRY, state);
201
+ } catch (error) {
202
+ const message = error instanceof Error ? error.message : String(error);
203
+ ctx.ui.notify(`Failed to save session service tier: ${message}`, "error");
204
+ return;
205
+ }
206
+ sessionOverrides = state.overrides;
207
+ refreshServiceTier(ctx, effectiveSettings(config), true);
180
208
 
181
209
  const providerLabel =
182
210
  SERVICE_TIER_PROVIDER_DEFINITIONS[result.provider].label;
183
211
  ctx.ui.notify(
184
- `${providerLabel} service tier: ${result.serviceTier || "off"}`,
212
+ `${providerLabel} service tier for this session: ${result.serviceTier || "off"}`,
185
213
  "info",
186
214
  );
187
215
  },
188
216
  });
189
217
 
190
218
  pi.registerCommand("service-tier", {
191
- description: "Configure provider service tiers.",
219
+ description: "Configure global provider service tier defaults.",
192
220
  handler: async (_args, ctx) => {
193
221
  if (!ctx.hasUI) {
194
222
  ctx.ui.notify("/service-tier requires interactive UI mode", "warning");
@@ -204,9 +232,9 @@ export default function (pi: ExtensionAPI) {
204
232
  const container = new Container();
205
233
  container.addChild(
206
234
  new Text(
207
- `${theme.fg("accent", theme.bold("Service Tier"))}\n${theme.fg(
235
+ `${theme.fg("accent", theme.bold("Global service tier defaults"))}\n${theme.fg(
208
236
  "dim",
209
- getServiceTierConfigPath(),
237
+ `${getServiceTierConfigPath()}\nSession /fast overrides take precedence.`,
210
238
  )}`,
211
239
  0,
212
240
  0,
@@ -251,7 +279,13 @@ export default function (pi: ExtensionAPI) {
251
279
  });
252
280
 
253
281
  pi.on("session_start", async (_event, ctx) => {
254
- refreshServiceTier(ctx);
282
+ sessionOverrides = restoreServiceTierOverrides(ctx.sessionManager.getBranch());
283
+ refreshServiceTier(ctx, effectiveSettings(), true);
284
+ });
285
+
286
+ pi.on("session_tree", async (_event, ctx) => {
287
+ sessionOverrides = restoreServiceTierOverrides(ctx.sessionManager.getBranch());
288
+ refreshServiceTier(ctx, effectiveSettings(), true);
255
289
  });
256
290
 
257
291
  pi.on("model_select", async (_event, ctx) => {
@@ -259,7 +293,7 @@ export default function (pi: ExtensionAPI) {
259
293
  });
260
294
 
261
295
  pi.on("before_provider_request", async (event, ctx) => {
262
- const config = loadConfigOrDefault();
296
+ const config = effectiveSettings();
263
297
  refreshServiceTier(ctx, config);
264
298
  return applyServiceTierToPayload(event.payload, config, ctx.model);
265
299
  });
@@ -0,0 +1,61 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ SERVICE_TIER_PROVIDER_DEFINITIONS,
4
+ isRecord,
5
+ isServiceTierProvider,
6
+ type ServiceTierConfigSnapshot,
7
+ type ServiceTierSettings,
8
+ } from "./domain.ts";
9
+
10
+ export const SERVICE_TIER_SESSION_ENTRY = "pi-service-tier";
11
+
12
+ /** Missing means inherit the global default; an empty string explicitly disables it. */
13
+ export type SessionServiceTierOverrides = ServiceTierSettings;
14
+
15
+ export interface ServiceTierSessionState {
16
+ version: 1;
17
+ overrides: SessionServiceTierOverrides;
18
+ }
19
+
20
+ export function mergeServiceTierSettings(
21
+ defaults: ServiceTierConfigSnapshot,
22
+ overrides: SessionServiceTierOverrides,
23
+ ): ServiceTierSettings {
24
+ return { ...defaults, ...overrides };
25
+ }
26
+
27
+ function parseSessionState(data: unknown): ServiceTierSessionState | undefined {
28
+ if (!isRecord(data) || data.version !== 1 || !isRecord(data.overrides)) {
29
+ return undefined;
30
+ }
31
+ for (const [provider, value] of Object.entries(data.overrides)) {
32
+ if (!isServiceTierProvider(provider)) return undefined;
33
+ if (
34
+ value !== "" &&
35
+ !SERVICE_TIER_PROVIDER_DEFINITIONS[provider].tiers.some(
36
+ (tier) => tier.name === value,
37
+ )
38
+ ) {
39
+ return undefined;
40
+ }
41
+ }
42
+ return {
43
+ version: 1,
44
+ overrides: { ...data.overrides } as SessionServiceTierOverrides,
45
+ };
46
+ }
47
+
48
+ /** Read the full active branch, not compacted context or abandoned branches. */
49
+ export function restoreServiceTierOverrides(
50
+ branch: readonly SessionEntry[],
51
+ ): SessionServiceTierOverrides {
52
+ for (let i = branch.length - 1; i >= 0; i--) {
53
+ const entry = branch[i];
54
+ if (entry.type !== "custom" || entry.customType !== SERVICE_TIER_SESSION_ENTRY) {
55
+ continue;
56
+ }
57
+ const state = parseSessionState(entry.data);
58
+ if (state) return state.overrides;
59
+ }
60
+ return {};
61
+ }
package/settings.ts ADDED
@@ -0,0 +1,80 @@
1
+ import {
2
+ SERVICE_TIER_PROVIDERS,
3
+ SERVICE_TIER_PROVIDER_DEFINITIONS,
4
+ getConfiguredServiceTier,
5
+ getServiceTierProviderForModel,
6
+ type ServiceTierConfigSnapshot,
7
+ type ServiceTierModel,
8
+ type ServiceTierName,
9
+ type ServiceTierProvider,
10
+ } from "./domain.ts";
11
+
12
+ export type ServiceTierSectionId = "current" | "providers";
13
+
14
+ export interface ServiceTierSectionItem {
15
+ id: ServiceTierProvider;
16
+ label: string;
17
+ currentValue: ServiceTierName | "off";
18
+ values: readonly (ServiceTierName | "off")[];
19
+ description: string;
20
+ }
21
+
22
+ export interface ServiceTierSection {
23
+ id: ServiceTierSectionId;
24
+ title: string;
25
+ items: ServiceTierSectionItem[];
26
+ }
27
+
28
+ function buildSectionItem(
29
+ provider: ServiceTierProvider,
30
+ config: ServiceTierConfigSnapshot,
31
+ currentModel?: ServiceTierModel,
32
+ ): ServiceTierSectionItem {
33
+ const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[provider];
34
+ const modelLabel =
35
+ typeof currentModel?.name === "string" && currentModel.name
36
+ ? currentModel.name
37
+ : typeof currentModel?.id === "string" && currentModel.id
38
+ ? currentModel.id
39
+ : "";
40
+ const label = modelLabel
41
+ ? `${definition.label} (${modelLabel})`
42
+ : definition.label;
43
+ const configuredValue = getConfiguredServiceTier(config, provider);
44
+ const currentValue = configuredValue || "off";
45
+ const tierNames = definition.tiers.map((serviceTier) => serviceTier.name);
46
+ return {
47
+ id: provider,
48
+ label,
49
+ currentValue,
50
+ values: ["off", ...tierNames],
51
+ description: `${definition.label} supports ${tierNames.join(", ")}.`,
52
+ };
53
+ }
54
+
55
+ export function createServiceTierSections(
56
+ config: ServiceTierConfigSnapshot,
57
+ model: ServiceTierModel | undefined,
58
+ ): ServiceTierSection[] {
59
+ const currentProvider = getServiceTierProviderForModel(model);
60
+ const otherProviders = SERVICE_TIER_PROVIDERS.filter(
61
+ (provider) => provider !== currentProvider,
62
+ );
63
+ const sections: ServiceTierSection[] = [];
64
+
65
+ if (currentProvider) {
66
+ sections.push({
67
+ id: "current",
68
+ title: "Current Model",
69
+ items: [buildSectionItem(currentProvider, config, model)],
70
+ });
71
+ }
72
+
73
+ sections.push({
74
+ id: "providers",
75
+ title: currentProvider ? "Other Providers" : "Providers",
76
+ items: otherProviders.map((provider) => buildSectionItem(provider, config)),
77
+ });
78
+
79
+ return sections;
80
+ }
package/shared.ts CHANGED
@@ -1,361 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
4
- import { Type } from "typebox";
5
- import { Compile } from "typebox/compile";
6
-
7
- export const SERVICE_TIER_CONFIG_FILE = "service-tier.json";
8
-
9
- export const SERVICE_TIER_PROVIDERS = [
10
- "openai",
11
- "openai-codex",
12
- "anthropic",
13
- "google",
14
- "google-vertex",
15
- ] as const;
16
- export type ServiceTierProvider = (typeof SERVICE_TIER_PROVIDERS)[number];
17
-
18
- export type ServiceTierName = "flex" | "priority" | "standard";
19
- export type ServiceTierConfigSnapshot = Partial<
20
- Record<ServiceTierProvider, ServiceTierName>
21
- >;
22
-
23
- export interface ServiceTier {
24
- name: ServiceTierName;
25
- value: string;
26
- }
27
-
28
- export const DEFAULT_SERVICE_TIER_CONFIG: ServiceTierConfigSnapshot = {};
29
-
30
- export interface ServiceTierProviderDefinition {
31
- label: string;
32
- api: string;
33
- tiers: readonly ServiceTier[];
34
- fastTier?: ServiceTierName;
35
- }
36
-
37
- function tier(name: ServiceTierName, value = name): ServiceTier {
38
- return { name, value };
39
- }
40
-
41
- export const SERVICE_TIER_PROVIDER_DEFINITIONS: Record<
42
- ServiceTierProvider,
43
- ServiceTierProviderDefinition
44
- > = {
45
- openai: {
46
- label: "OpenAI",
47
- api: "openai-responses",
48
- tiers: [tier("flex"), tier("priority")],
49
- fastTier: "priority",
50
- },
51
- "openai-codex": {
52
- label: "OpenAI Codex",
53
- api: "openai-codex-responses",
54
- tiers: [tier("flex"), tier("priority")],
55
- fastTier: "priority",
56
- },
57
- anthropic: {
58
- label: "Anthropic",
59
- api: "anthropic-messages",
60
- tiers: [tier("priority", "auto"), tier("standard", "standard_only")],
61
- fastTier: "priority",
62
- },
63
- google: {
64
- label: "Google Gemini",
65
- api: "google-generative-ai",
66
- tiers: [tier("flex"), tier("priority")],
67
- fastTier: "priority",
68
- },
69
- "google-vertex": {
70
- label: "Google Vertex AI",
71
- api: "google-vertex",
72
- tiers: [tier("flex"), tier("priority")],
73
- fastTier: "priority",
74
- },
75
- };
76
-
77
- function serviceTierNames(provider: ServiceTierProvider): ServiceTierName[] {
78
- return SERVICE_TIER_PROVIDER_DEFINITIONS[provider].tiers.map(
79
- (serviceTier) => serviceTier.name,
80
- );
81
- }
82
-
83
- function literalUnion(values: readonly ServiceTierName[]) {
84
- return Type.Union(values.map((value) => Type.Literal(value)));
85
- }
86
-
87
- const serviceTierConfigSchema = Type.Object(
88
- {
89
- openai: Type.Optional(literalUnion(serviceTierNames("openai"))),
90
- "openai-codex": Type.Optional(
91
- literalUnion(serviceTierNames("openai-codex")),
92
- ),
93
- anthropic: Type.Optional(literalUnion(serviceTierNames("anthropic"))),
94
- google: Type.Optional(literalUnion(serviceTierNames("google"))),
95
- "google-vertex": Type.Optional(
96
- literalUnion(serviceTierNames("google-vertex")),
97
- ),
98
- },
99
- { additionalProperties: false },
100
- );
101
- const validateServiceTierConfig = Compile(serviceTierConfigSchema);
102
-
103
- function isRecord(value: unknown): value is Record<string, unknown> {
104
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
105
- }
106
-
107
- function formatValidationErrors(filePath: string, value: unknown): string {
108
- const errors = Array.from(validateServiceTierConfig.Errors(value));
109
- const unknownKeys = isRecord(value)
110
- ? Object.keys(value).filter(
111
- (key) =>
112
- !(SERVICE_TIER_PROVIDERS as readonly string[]).includes(key),
113
- )
114
- : [];
115
- if (unknownKeys.length > 0) {
116
- return `Invalid ${filePath}: unknown setting ${unknownKeys.map((key) => `"${key}"`).join(", ")}`;
117
- }
118
- return `Invalid ${filePath}: ${errors
119
- .map((error) => `${error.path || "/"} ${error.message}`)
120
- .join(", ")}`;
121
- }
122
-
123
- export function getDefaultAgentDir(): string {
124
- return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
125
- }
126
-
127
- export function getServiceTierConfigPath(
128
- agentDir = getDefaultAgentDir(),
129
- ): string {
130
- return join(agentDir, SERVICE_TIER_CONFIG_FILE);
131
- }
132
-
133
- export function isServiceTierProvider(
134
- value: unknown,
135
- ): value is ServiceTierProvider {
136
- return (
137
- typeof value === "string" &&
138
- (SERVICE_TIER_PROVIDERS as readonly string[]).includes(value)
139
- );
140
- }
141
-
142
- export function parseServiceTierConfigValue(
143
- filePath: string,
144
- value: unknown,
145
- ): ServiceTierConfigSnapshot {
146
- if (value === undefined) return { ...DEFAULT_SERVICE_TIER_CONFIG };
147
- if (!validateServiceTierConfig.Check(value)) {
148
- throw new Error(formatValidationErrors(filePath, value));
149
- }
150
-
151
- const config = value as ServiceTierConfigSnapshot;
152
- const result: ServiceTierConfigSnapshot = {};
153
- for (const provider of SERVICE_TIER_PROVIDERS) {
154
- const serviceTier = config[provider];
155
- if (serviceTier !== undefined) result[provider] = serviceTier;
156
- }
157
- return result;
158
- }
159
-
160
- export function loadServiceTierConfig(
161
- configPath = getServiceTierConfigPath(),
162
- ): ServiceTierConfigSnapshot {
163
- if (!existsSync(configPath)) return { ...DEFAULT_SERVICE_TIER_CONFIG };
164
-
165
- let parsed: unknown;
166
- try {
167
- parsed = JSON.parse(readFileSync(configPath, "utf8"));
168
- } catch (error) {
169
- const message = error instanceof Error ? error.message : String(error);
170
- throw new Error(`Failed to parse ${configPath}: ${message}`);
171
- }
172
-
173
- return parseServiceTierConfigValue(configPath, parsed);
174
- }
175
-
176
- export function writeServiceTierConfigSnapshot(
177
- config: ServiceTierConfigSnapshot,
178
- configPath = getServiceTierConfigPath(),
179
- ): void {
180
- mkdirSync(dirname(configPath), { recursive: true });
181
- writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
182
- }
183
-
184
- export function modelSupportsServiceTier(
185
- model: { api?: unknown; provider?: unknown } | undefined,
186
- ): boolean {
187
- return getServiceTierProviderForModel(model) !== undefined;
188
- }
189
-
190
- export function getServiceTierProviderForModel(
191
- model: { api?: unknown; provider?: unknown } | undefined,
192
- ): ServiceTierProvider | undefined {
193
- if (!model || !isServiceTierProvider(model.provider)) return undefined;
194
- const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[model.provider];
195
- return model.api === definition.api ? model.provider : undefined;
196
- }
197
-
198
- export function getConfiguredServiceTier(
199
- config: ServiceTierConfigSnapshot,
200
- provider: ServiceTierProvider | undefined,
201
- ): ServiceTierName | "" {
202
- return provider ? (config[provider] ?? "") : "";
203
- }
204
-
205
- export function resolveEffectiveServiceTier(
206
- config: ServiceTierConfigSnapshot,
207
- model: { api?: unknown; provider?: unknown } | undefined,
208
- ): ServiceTierName | "" {
209
- return getConfiguredServiceTier(config, getServiceTierProviderForModel(model));
210
- }
211
-
212
- function getTier(
213
- provider: ServiceTierProvider,
214
- serviceTierName: ServiceTierName,
215
- ): ServiceTier | undefined {
216
- return SERVICE_TIER_PROVIDER_DEFINITIONS[provider].tiers.find(
217
- (serviceTier) => serviceTier.name === serviceTierName,
218
- );
219
- }
220
-
221
- function applyPayloadServiceTier(
222
- payload: Record<string, unknown>,
223
- provider: ServiceTierProvider,
224
- value: string,
225
- ): Record<string, unknown> {
226
- if (provider === "google" || provider === "google-vertex") {
227
- return {
228
- ...payload,
229
- config: {
230
- ...(isRecord(payload.config) ? payload.config : {}),
231
- serviceTier: value,
232
- },
233
- };
234
- }
235
-
236
- return { ...payload, service_tier: value };
237
- }
238
-
239
- export function applyServiceTierToPayload(
240
- payload: unknown,
241
- config: ServiceTierConfigSnapshot,
242
- model: { api?: unknown; provider?: unknown } | undefined,
243
- ): unknown | undefined {
244
- const provider = getServiceTierProviderForModel(model);
245
- const serviceTierName = getConfiguredServiceTier(config, provider);
246
- if (!provider || !serviceTierName || !isRecord(payload)) return undefined;
247
-
248
- const serviceTier = getTier(provider, serviceTierName);
249
- if (!serviceTier) return undefined;
250
-
251
- return applyPayloadServiceTier(payload, provider, serviceTier.value);
252
- }
253
-
254
- export interface FastToggleResult {
255
- config: ServiceTierConfigSnapshot;
256
- provider: ServiceTierProvider;
257
- serviceTier: ServiceTierName | "";
258
- fast: boolean;
259
- }
260
-
261
- export function toggleFastServiceTier(
262
- config: ServiceTierConfigSnapshot,
263
- model: { api?: unknown; provider?: unknown } | undefined,
264
- ): FastToggleResult | undefined {
265
- const provider = getServiceTierProviderForModel(model);
266
- if (!provider) return undefined;
267
-
268
- const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[provider];
269
- if (!definition.fastTier) return undefined;
270
-
271
- const current = getConfiguredServiceTier(config, provider);
272
- const fast = current !== definition.fastTier;
273
- const serviceTier = fast ? definition.fastTier : "";
274
- return {
275
- config: setProviderServiceTier(config, provider, serviceTier),
276
- provider,
277
- serviceTier,
278
- fast,
279
- };
280
- }
281
-
282
- export function setProviderServiceTier(
283
- config: ServiceTierConfigSnapshot,
284
- provider: ServiceTierProvider,
285
- value: ServiceTierName | "",
286
- ): ServiceTierConfigSnapshot {
287
- const next = { ...config };
288
- if (value === "") delete next[provider];
289
- else next[provider] = value;
290
- return next;
291
- }
292
-
293
- export type ServiceTierSectionId = "current" | "providers";
294
-
295
- export interface ServiceTierSectionItem {
296
- id: ServiceTierProvider;
297
- label: string;
298
- currentValue: ServiceTierName | "off";
299
- values: readonly (ServiceTierName | "off")[];
300
- description: string;
301
- }
302
-
303
- export interface ServiceTierSection {
304
- id: ServiceTierSectionId;
305
- title: string;
306
- items: ServiceTierSectionItem[];
307
- }
308
-
309
- function buildSectionItem(
310
- provider: ServiceTierProvider,
311
- config: ServiceTierConfigSnapshot,
312
- currentModel?: { id?: unknown; name?: unknown },
313
- ): ServiceTierSectionItem {
314
- const definition = SERVICE_TIER_PROVIDER_DEFINITIONS[provider];
315
- const modelLabel =
316
- typeof currentModel?.name === "string" && currentModel.name
317
- ? currentModel.name
318
- : typeof currentModel?.id === "string" && currentModel.id
319
- ? currentModel.id
320
- : "";
321
- const label = modelLabel
322
- ? `${definition.label} (${modelLabel})`
323
- : definition.label;
324
- const configuredValue = getConfiguredServiceTier(config, provider);
325
- const currentValue = configuredValue || "off";
326
- const tierNames = definition.tiers.map((serviceTier) => serviceTier.name);
327
- return {
328
- id: provider,
329
- label,
330
- currentValue,
331
- values: ["off", ...tierNames],
332
- description: `${definition.label} supports ${tierNames.join(", ")}.`,
333
- };
334
- }
335
-
336
- export function createServiceTierSections(
337
- config: ServiceTierConfigSnapshot,
338
- model: { api?: unknown; provider?: unknown; id?: unknown; name?: unknown } | undefined,
339
- ): ServiceTierSection[] {
340
- const currentProvider = getServiceTierProviderForModel(model);
341
- const otherProviders = SERVICE_TIER_PROVIDERS.filter(
342
- (provider) => provider !== currentProvider,
343
- );
344
- const sections: ServiceTierSection[] = [];
345
-
346
- if (currentProvider) {
347
- sections.push({
348
- id: "current",
349
- title: "Current Model",
350
- items: [buildSectionItem(currentProvider, config, model)],
351
- });
352
- }
353
-
354
- sections.push({
355
- id: "providers",
356
- title: currentProvider ? "Other Providers" : "Providers",
357
- items: otherProviders.map((provider) => buildSectionItem(provider, config)),
358
- });
359
-
360
- return sections;
361
- }
1
+ // Compatibility exports. Implementation modules depend on their own layer.
2
+ export * from "./domain.ts";
3
+ export * from "./config.ts";
4
+ export * from "./settings.ts";