@charmland/pi-hyper-provider 0.1.0 → 0.1.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
@@ -24,12 +24,13 @@ pi install git:github.com/charmbracelet/pi-hyper-provider
24
24
  - To authenticate with an API key, set the `HYPER_API_KEY` environment variable
25
25
  then open `pi`.
26
26
 
27
- Pick a Hyper model by sending `/models` and filtering by either provider name
27
+ Pick a Hyper model by sending `/model` and filtering by either provider name
28
28
  `hyper` or `model-name` like `glm-5.1`.
29
29
 
30
30
  Model info is fetched at startup and cached locally; the cache is used as a
31
- fallback when the `/models` endpoint is unreachable. By default, your remaining
32
- Hypercredit balance is shown in the status line while a Hyper model is active.
31
+ fallback when the Hyper provider catalog is unreachable. By default, your
32
+ remaining Hypercredit balance is shown in the status line while a Hyper model is
33
+ active.
33
34
 
34
35
  Use `/hyper-status` to configure the status line interactively and toggle things
35
36
  on/off or reset to the defaults. `teamName` defaults to `false` and
@@ -47,9 +48,8 @@ See the [contributing guide](https://github.com/charmbracelet/pi-hyper-provider?
47
48
 
48
49
  ## Releasing
49
50
 
50
- 1. `mise run release:bump
51
- <patch|minor|major|prepatch|preminor|premajor|prerelease>` to increment the
52
- version
51
+ 1. `mise run release:bump <patch|minor|major|prepatch|preminor|premajor|prerelease>`
52
+ to increment the version
53
53
  2. `mise run release:pack` to dry-run build the release tarball
54
54
  3. `mise run release:publish` to publish
55
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@charmland/pi-hyper-provider",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Pi extension for Charm's Hyper inference provider",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -19,6 +19,7 @@
19
19
  "scripts": {
20
20
  "fmt": "biome format --write .",
21
21
  "lint": "biome lint .",
22
+ "check:biome": "biome check --write .",
22
23
  "typecheck": "tsc --noEmit"
23
24
  },
24
25
  "peerDependencies": {
@@ -29,8 +30,8 @@
29
30
  "dependencies": {},
30
31
  "devDependencies": {
31
32
  "@biomejs/biome": "^2.4.16",
32
- "@earendil-works/pi-ai": "^0.80.1",
33
- "@earendil-works/pi-coding-agent": "^0.80.1",
33
+ "@earendil-works/pi-ai": "^0.80.10",
34
+ "@earendil-works/pi-coding-agent": "^0.80.10",
34
35
  "typebox": "^1.1.38",
35
36
  "typescript": "^6.0.3"
36
37
  },
package/src/credits.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { readStoredCredential } from "@earendil-works/pi-coding-agent";
2
3
  import { Type } from "typebox";
3
- import { PROVIDER_NAME, hyperApiBaseUrl, hyperJsonHeaders } from "./hyper.js";
4
4
  import { fetchJson } from "./http.js";
5
+ import { hyperApiBaseUrl, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
5
6
  import { parseSchema } from "./schema.js";
6
7
  import {
7
8
  defaultHyperStatusItems,
@@ -48,8 +49,8 @@ function teamNameStatusText(statusItems: HyperStatusItems, teamName: string | un
48
49
  return `${HYPER_GEM} ${teamName}`;
49
50
  }
50
51
 
51
- function storedTeamName(ctx: ExtensionContext): string | undefined {
52
- const credential = ctx.modelRegistry.authStorage.get(PROVIDER_NAME);
52
+ function storedTeamName(): string | undefined {
53
+ const credential = readStoredCredential(PROVIDER_NAME);
53
54
  if (credential?.type !== "oauth") return undefined;
54
55
  const teamName = credential.teamName;
55
56
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
@@ -68,7 +69,7 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
68
69
  }
69
70
 
70
71
  const statusItems = readHyperStatusItems();
71
- const teamName = storedTeamName(ctx);
72
+ const teamName = storedTeamName();
72
73
  if (!statusItems.hypercredits) {
73
74
  ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
74
75
  return;
@@ -93,6 +94,12 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
93
94
  }
94
95
  }
95
96
 
97
+ function refreshInBackground(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): void {
98
+ void refresh(ctx, selectedModel).catch((err) => {
99
+ console.error(`Failed to update Hyper status: ${String(err)}`);
100
+ });
101
+ }
102
+
96
103
  pi.registerCommand("hyper-status", {
97
104
  description: "Configure the Charm Hyper footer status",
98
105
  handler: async (args, ctx) => {
@@ -113,17 +120,17 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
113
120
  },
114
121
  });
115
122
 
116
- pi.on("session_start", async (_event, ctx) => {
117
- await refresh(ctx);
123
+ pi.on("session_start", (_event, ctx) => {
124
+ refreshInBackground(ctx);
118
125
  });
119
126
 
120
- pi.on("model_select", async (event, ctx) => {
121
- await refresh(ctx, event.model);
127
+ pi.on("model_select", (event, ctx) => {
128
+ refreshInBackground(ctx, event.model);
122
129
  });
123
130
 
124
- pi.on("message_end", async (event, ctx) => {
131
+ pi.on("message_end", (event, ctx) => {
125
132
  if (event.message.role === "assistant" && isHyperModel(ctx.model)) {
126
- await refresh(ctx);
133
+ refreshInBackground(ctx);
127
134
  }
128
135
  });
129
136
  }
package/src/http.ts CHANGED
@@ -7,11 +7,30 @@ export interface FetchJsonOptions {
7
7
  allowHttpErrorPayload?: boolean;
8
8
  }
9
9
 
10
+ export interface FetchJsonResponse {
11
+ status: number;
12
+ ok: boolean;
13
+ payload: unknown;
14
+ }
15
+
10
16
  export async function fetchJson(url: string, options: FetchJsonOptions): Promise<unknown> {
17
+ return (await fetchJsonResponse(url, options)).payload;
18
+ }
19
+
20
+ export async function fetchJsonResponse(url: string, options: FetchJsonOptions): Promise<FetchJsonResponse> {
11
21
  const controller = new AbortController();
12
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
13
- const abortFromCaller = () => controller.abort();
22
+ let timedOut = false;
23
+ let callerAborted = false;
24
+ const timeout = setTimeout(() => {
25
+ timedOut = true;
26
+ controller.abort();
27
+ }, options.timeoutMs);
28
+ const abortFromCaller = () => {
29
+ callerAborted = true;
30
+ controller.abort();
31
+ };
14
32
  if (options.signal?.aborted) {
33
+ callerAborted = true;
15
34
  controller.abort();
16
35
  } else {
17
36
  options.signal?.addEventListener("abort", abortFromCaller, { once: true });
@@ -24,13 +43,44 @@ export async function fetchJson(url: string, options: FetchJsonOptions): Promise
24
43
  body: options.body,
25
44
  signal: controller.signal,
26
45
  });
46
+ const body = await response.text();
27
47
  if (!response.ok && !options.allowHttpErrorPayload) {
28
- const body = await response.text();
29
- throw new Error(`${url} returned ${response.status}: ${body}`);
48
+ throw new Error(`${url} returned HTTP ${response.status}: ${summarizeBody(body)}`);
49
+ }
50
+ return {
51
+ status: response.status,
52
+ ok: response.ok,
53
+ payload: parseJsonBody(url, response.status, body),
54
+ };
55
+ } catch (err) {
56
+ if (timedOut) {
57
+ throw new Error(`${url} timed out after ${options.timeoutMs}ms`, { cause: err });
58
+ }
59
+ if (callerAborted) {
60
+ throw new Error(`${url} request was aborted`, { cause: err });
30
61
  }
31
- return response.json();
62
+ throw err;
32
63
  } finally {
33
64
  clearTimeout(timeout);
34
65
  options.signal?.removeEventListener("abort", abortFromCaller);
35
66
  }
36
67
  }
68
+
69
+ function parseJsonBody(url: string, status: number, body: string): unknown {
70
+ if (!body.trim()) {
71
+ throw new Error(`${url} returned HTTP ${status} with an empty JSON body`);
72
+ }
73
+ try {
74
+ return JSON.parse(body);
75
+ } catch (err) {
76
+ throw new Error(`${url} returned invalid JSON (HTTP ${status}): ${summarizeBody(body)}`, { cause: err });
77
+ }
78
+ }
79
+
80
+ function summarizeBody(body: string): string {
81
+ const trimmed = body.trim();
82
+ if (!trimmed) return "empty response body";
83
+ const maxBodyCharacters = 2_000;
84
+ if (trimmed.length <= maxBodyCharacters) return trimmed;
85
+ return `${trimmed.slice(0, maxBodyCharacters)}…`;
86
+ }
package/src/hyper.ts CHANGED
@@ -3,10 +3,8 @@ import * as path from "node:path";
3
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
4
 
5
5
  const require = createRequire(import.meta.url);
6
- const packageJson = require("../package.json") as {
7
- name: string;
8
- version: string;
9
- };
6
+ const packageJsonPayload: unknown = require("../package.json");
7
+ const packageJson = parsePackageJson(packageJsonPayload);
10
8
  const packageName = packageJson.name.split("/").at(-1) ?? "pi-hyper-provider";
11
9
 
12
10
  export const PROVIDER_NAME = "hyper";
@@ -24,7 +22,11 @@ export function hyperApiBaseUrl(): string {
24
22
  return `${hyperBaseUrl()}/v1`;
25
23
  }
26
24
 
27
- export function hyperExtensionDir(): string {
25
+ export function hyperProviderDir(): string {
26
+ return path.join(getAgentDir(), "hyper-provider");
27
+ }
28
+
29
+ export function legacyHyperExtensionDir(): string {
28
30
  return path.join(getAgentDir(), "extensions", "hyper-provider");
29
31
  }
30
32
 
@@ -35,3 +37,20 @@ export function hyperJsonHeaders(headers: Record<string, string> = {}): Record<s
35
37
  ...headers,
36
38
  };
37
39
  }
40
+
41
+ function parsePackageJson(payload: unknown): { name: string; version: string } {
42
+ if (!isRecord(payload)) throw new Error("package.json must contain a JSON object");
43
+ const name = property(payload, "name");
44
+ const version = property(payload, "version");
45
+ if (typeof name !== "string" || !name.trim()) throw new Error("package.json must contain a name");
46
+ if (typeof version !== "string" || !version.trim()) throw new Error("package.json must contain a version");
47
+ return { name, version };
48
+ }
49
+
50
+ function property(source: Record<string, unknown>, key: string): unknown {
51
+ return Object.getOwnPropertyDescriptor(source, key)?.value;
52
+ }
53
+
54
+ function isRecord(value: unknown): value is Record<string, unknown> {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
package/src/index.ts CHANGED
@@ -1,16 +1,25 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { registerCreditStatus } from "./credits.js";
3
- import { HYPER_API_KEY, PROVIDER_DISPLAY_NAME, PROVIDER_NAME, hyperApiBaseUrl } from "./hyper.js";
3
+ import { HYPER_API_KEY, HYPER_USER_AGENT, hyperApiBaseUrl, PROVIDER_DISPLAY_NAME, PROVIDER_NAME } from "./hyper.js";
4
4
  import { loadModels } from "./models.js";
5
5
  import { loginHyper, refreshHyperToken } from "./oauth.js";
6
+ import { migrateHyperSettings } from "./settings.js";
6
7
 
7
8
  export default async function (pi: ExtensionAPI) {
9
+ try {
10
+ migrateHyperSettings();
11
+ } catch (err) {
12
+ console.error(`Failed to migrate Hyper settings: ${String(err)}`);
13
+ }
8
14
  const models = await loadModels();
9
15
 
10
16
  pi.registerProvider(PROVIDER_NAME, {
11
17
  name: PROVIDER_DISPLAY_NAME,
12
18
  baseUrl: hyperApiBaseUrl(),
13
19
  apiKey: HYPER_API_KEY,
20
+ headers: {
21
+ "User-Agent": HYPER_USER_AGENT,
22
+ },
14
23
  api: "openai-completions",
15
24
  models,
16
25
  oauth: {
package/src/models.ts CHANGED
@@ -1,15 +1,34 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
4
4
  import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
5
- import { Type, type Static } from "typebox";
6
- import { hyperApiBaseUrl, hyperExtensionDir } from "./hyper.js";
5
+ import { type Static, Type } from "typebox";
6
+ import { Value } from "typebox/value";
7
7
  import { fetchJson } from "./http.js";
8
+ import { hyperApiBaseUrl, hyperProviderDir, legacyHyperExtensionDir } from "./hyper.js";
8
9
  import { parseSchema } from "./schema.js";
9
10
 
10
- const MODEL_FETCH_TIMEOUT_MS = 10_000;
11
+ const MODEL_FETCH_TIMEOUT_MS = 3_000;
12
+ const MODEL_CACHE_VERSION = 1;
11
13
 
12
- const PI_THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const satisfies readonly ThinkingLevel[];
14
+ const PI_THINKING_LEVELS = [
15
+ "minimal",
16
+ "low",
17
+ "medium",
18
+ "high",
19
+ "xhigh",
20
+ "max",
21
+ ] as const satisfies readonly ThinkingLevel[];
22
+ // Hyper models without reasoning levels are on/off-only. Use Pi's medium level
23
+ // as the single representative "on" state; it is not sent as reasoning_effort.
24
+ const ON_OFF_THINKING_LEVEL_MAP: ThinkingLevelMap = {
25
+ off: "off",
26
+ minimal: null,
27
+ low: null,
28
+ medium: "medium",
29
+ high: null,
30
+ xhigh: null,
31
+ };
13
32
 
14
33
  const HyperModelBaseFields = {
15
34
  id: Type.String({ minLength: 1 }),
@@ -33,14 +52,14 @@ const HyperModelSchema = Type.Union([
33
52
  }),
34
53
  default_reasoning_effort: Type.String({ minLength: 1 }),
35
54
  },
36
- { additionalProperties: false },
55
+ { additionalProperties: true },
37
56
  ),
38
57
  Type.Object(
39
58
  {
40
59
  ...HyperModelBaseFields,
41
60
  supports_reasoning_effort: Type.Literal(false),
42
61
  },
43
- { additionalProperties: false },
62
+ { additionalProperties: true },
44
63
  ),
45
64
  ]);
46
65
 
@@ -49,20 +68,102 @@ const ModelPayloadSchema = Type.Object(
49
68
  object: Type.Literal("list"),
50
69
  data: Type.Array(HyperModelSchema, { minItems: 1 }),
51
70
  },
71
+ { additionalProperties: true },
72
+ );
73
+
74
+ const ProviderModelSchema = Type.Object(
75
+ {
76
+ id: Type.String({ minLength: 1 }),
77
+ name: Type.String({ minLength: 1 }),
78
+ cost_per_1m_in: Type.Number({ minimum: 0 }),
79
+ cost_per_1m_out: Type.Number({ minimum: 0 }),
80
+ cost_per_1m_in_cached: Type.Number({ minimum: 0 }),
81
+ cost_per_1m_out_cached: Type.Optional(Type.Number({ minimum: 0 })),
82
+ context_window: Type.Integer({ minimum: 1 }),
83
+ default_max_tokens: Type.Integer({ minimum: 1 }),
84
+ can_reason: Type.Boolean(),
85
+ reasoning_levels: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
86
+ default_reasoning_effort: Type.Optional(Type.String({ minLength: 1 })),
87
+ supports_attachments: Type.Boolean(),
88
+ },
89
+ { additionalProperties: true },
90
+ );
91
+
92
+ const ProviderPayloadSchema = Type.Object(
93
+ {
94
+ models: Type.Array(ProviderModelSchema, { minItems: 1 }),
95
+ },
96
+ { additionalProperties: true },
97
+ );
98
+
99
+ const ModelCacheEnvelopeSchema = Type.Object(
100
+ {
101
+ version: Type.Literal(MODEL_CACHE_VERSION),
102
+ hyperApiBaseUrl: Type.String({ minLength: 1 }),
103
+ fetchedAt: Type.String({ minLength: 1 }),
104
+ payload: ProviderPayloadSchema,
105
+ },
52
106
  { additionalProperties: false },
53
107
  );
54
108
 
55
109
  type HyperModel = Static<typeof HyperModelSchema>;
110
+ type ProviderModel = Static<typeof ProviderModelSchema>;
111
+ type ProviderPayload = Static<typeof ProviderPayloadSchema>;
112
+ type LegacyModelPayload = Static<typeof ModelPayloadSchema>;
113
+ type ModelCacheEnvelope = Static<typeof ModelCacheEnvelopeSchema>;
114
+ type ModelCatalog = { kind: "provider"; payload: ProviderPayload } | { kind: "legacy"; payload: LegacyModelPayload };
115
+ type ModelCacheRead = { status: "hit"; catalog: ModelCatalog } | { status: "miss" } | { status: "blocked" };
56
116
 
57
117
  function modelCachePath(): string {
58
- return path.join(hyperExtensionDir(), "models.json");
118
+ return path.join(hyperProviderDir(), "models.json");
119
+ }
120
+
121
+ function legacyModelCachePath(): string {
122
+ return path.join(legacyHyperExtensionDir(), "models.json");
123
+ }
124
+
125
+ function toProviderModel(model: ProviderModel): ProviderModelConfig {
126
+ const input: ProviderModelConfig["input"] = model.supports_attachments ? ["text", "image"] : ["text"];
127
+ const reasoningLevels = model.reasoning_levels ?? [];
128
+ const supportsReasoningEffort = reasoningLevels.length > 0;
129
+ const thinkingLevelMap = supportsReasoningEffort
130
+ ? buildThinkingLevelMap(reasoningLevels)
131
+ : model.can_reason
132
+ ? ON_OFF_THINKING_LEVEL_MAP
133
+ : undefined;
134
+
135
+ return {
136
+ id: model.id,
137
+ name: model.name,
138
+ reasoning: model.can_reason,
139
+ thinkingLevelMap,
140
+ input,
141
+ cost: {
142
+ input: model.cost_per_1m_in,
143
+ output: model.cost_per_1m_out,
144
+ cacheRead: model.cost_per_1m_in_cached,
145
+ // Hyper exposes cached input/output prices, but Pi only models cached
146
+ // input reads and cache writes. Hyper does not expose a cache-write price.
147
+ cacheWrite: 0,
148
+ },
149
+ contextWindow: model.context_window,
150
+ maxTokens: model.default_max_tokens,
151
+ compat: {
152
+ supportsStore: false,
153
+ supportsReasoningEffort,
154
+ thinkingFormat: "deepseek",
155
+ maxTokensField: "max_tokens",
156
+ },
157
+ };
59
158
  }
60
159
 
61
- function toProviderModel(model: HyperModel): ProviderModelConfig {
160
+ function toLegacyProviderModel(model: HyperModel): ProviderModelConfig {
62
161
  const input: ProviderModelConfig["input"] = model.supports_attachments ? ["text", "image"] : ["text"];
63
162
  const thinkingLevelMap = model.supports_reasoning_effort
64
163
  ? buildThinkingLevelMap(model.reasoning_effort_levels)
65
- : undefined;
164
+ : model.supports_reasoning
165
+ ? ON_OFF_THINKING_LEVEL_MAP
166
+ : undefined;
66
167
 
67
168
  return {
68
169
  id: model.id,
@@ -76,11 +177,35 @@ function toProviderModel(model: HyperModel): ProviderModelConfig {
76
177
  compat: {
77
178
  supportsStore: false,
78
179
  supportsReasoningEffort: model.supports_reasoning_effort,
180
+ thinkingFormat: "deepseek",
79
181
  maxTokensField: "max_tokens",
80
182
  },
81
183
  };
82
184
  }
83
185
 
186
+ function modelsFromCatalog(catalog: ModelCatalog): ProviderModelConfig[] {
187
+ switch (catalog.kind) {
188
+ case "provider":
189
+ return catalog.payload.models.map(toProviderModel);
190
+ case "legacy":
191
+ return catalog.payload.data.map(toLegacyProviderModel);
192
+ }
193
+ }
194
+
195
+ function providerPayload(payload: unknown, source: string): ProviderPayload {
196
+ return parseSchema(ProviderPayloadSchema, payload, source);
197
+ }
198
+
199
+ function optionalModelCatalog(payload: unknown): ModelCatalog | undefined {
200
+ if (Value.Check(ProviderPayloadSchema, payload)) {
201
+ return { kind: "provider", payload: Value.Parse(ProviderPayloadSchema, payload) };
202
+ }
203
+ if (Value.Check(ModelPayloadSchema, payload)) {
204
+ return { kind: "legacy", payload: Value.Parse(ModelPayloadSchema, payload) };
205
+ }
206
+ return undefined;
207
+ }
208
+
84
209
  function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
85
210
  if (levels.length === 0) return undefined;
86
211
  const availableLevels = new Set<string>(levels);
@@ -94,42 +219,128 @@ function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
94
219
  }
95
220
 
96
221
  async function fetchModelPayload(): Promise<unknown> {
97
- return fetchJson(`${hyperApiBaseUrl()}/models`, {
222
+ return fetchJson(`${hyperApiBaseUrl()}/provider`, {
98
223
  timeoutMs: MODEL_FETCH_TIMEOUT_MS,
99
224
  });
100
225
  }
101
226
 
102
- function readCachedModelPayload(): unknown | undefined {
227
+ function readCachedModelCatalog(): ModelCatalog | undefined {
103
228
  const cachePath = modelCachePath();
229
+ const cache = readModelCache(cachePath, "Hyper model cache");
230
+ if (cache.status === "hit") return cache.catalog;
231
+ if (cache.status === "blocked") return undefined;
232
+
233
+ const legacyCache = readModelCache(legacyModelCachePath(), "legacy Hyper model cache");
234
+ return legacyCache.status === "hit" ? legacyCache.catalog : undefined;
235
+ }
236
+
237
+ function readJsonCache(cachePath: string, description: string): unknown | undefined {
104
238
  if (!existsSync(cachePath)) return undefined;
105
239
  try {
106
240
  return JSON.parse(readFileSync(cachePath, "utf-8"));
107
241
  } catch (err) {
108
- console.error(`Failed to read Hyper model cache at ${cachePath}: ${String(err)}`);
242
+ console.error(`Failed to read ${description} at ${cachePath}: ${String(err)}`);
109
243
  return undefined;
110
244
  }
111
245
  }
112
246
 
113
- function writeCachedModelPayload(payload: unknown): void {
247
+ function readModelCache(cachePath: string, description: string): ModelCacheRead {
248
+ const cache = readJsonCache(cachePath, description);
249
+ if (cache === undefined) return { status: "miss" };
250
+ return unwrapModelCache(cache, description);
251
+ }
252
+
253
+ function unwrapModelCache(cache: unknown, description: string): ModelCacheRead {
254
+ const envelopeBaseUrl = modelCacheEnvelopeBaseUrl(cache);
255
+ if (envelopeBaseUrl !== undefined) {
256
+ const expectedBaseUrl = hyperApiBaseUrl();
257
+ if (envelopeBaseUrl !== expectedBaseUrl) {
258
+ console.error(`Ignoring ${description} for ${envelopeBaseUrl}; current Hyper API base URL is ${expectedBaseUrl}`);
259
+ return { status: "blocked" };
260
+ }
261
+ }
262
+
263
+ if (Value.Check(ModelCacheEnvelopeSchema, cache)) {
264
+ const envelope = Value.Parse(ModelCacheEnvelopeSchema, cache);
265
+ return { status: "hit", catalog: { kind: "provider", payload: envelope.payload } };
266
+ }
267
+
268
+ if (isModelCacheEnvelopeLike(cache)) {
269
+ console.error(`Ignoring invalid ${description} metadata`);
270
+ return { status: "blocked" };
271
+ }
272
+
273
+ const catalog = optionalModelCatalog(cache);
274
+ if (catalog === undefined) {
275
+ console.error(`Ignoring invalid ${description}`);
276
+ return { status: "miss" };
277
+ }
278
+
279
+ return { status: "hit", catalog };
280
+ }
281
+
282
+ function isModelCacheEnvelopeLike(cache: unknown): boolean {
283
+ if (!isRecord(cache)) return false;
284
+ if (Object.hasOwn(cache, "hyperApiBaseUrl") || Object.hasOwn(cache, "fetchedAt")) return true;
285
+ if (Object.hasOwn(cache, "version") && Object.hasOwn(cache, "payload")) return true;
286
+ return false;
287
+ }
288
+
289
+ function modelCacheEnvelopeBaseUrl(cache: unknown): string | undefined {
290
+ if (!isRecord(cache)) return undefined;
291
+ const value = Object.getOwnPropertyDescriptor(cache, "hyperApiBaseUrl")?.value;
292
+ return typeof value === "string" && value.trim() ? value : undefined;
293
+ }
294
+
295
+ function modelCacheEnvelope(payload: ProviderPayload): ModelCacheEnvelope {
296
+ return {
297
+ version: MODEL_CACHE_VERSION,
298
+ hyperApiBaseUrl: hyperApiBaseUrl(),
299
+ fetchedAt: new Date().toISOString(),
300
+ payload,
301
+ };
302
+ }
303
+
304
+ function writeCachedModelPayload(payload: ProviderPayload): void {
114
305
  try {
115
- mkdirSync(hyperExtensionDir(), { recursive: true });
116
- writeFileSync(modelCachePath(), `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
306
+ mkdirSync(hyperProviderDir(), { recursive: true });
307
+ writeFileSync(modelCachePath(), `${JSON.stringify(modelCacheEnvelope(payload), null, 2)}\n`, "utf-8");
308
+ removeLegacyModelCache();
117
309
  } catch (err) {
118
310
  console.error(`Failed to write Hyper model cache: ${String(err)}`);
119
311
  }
120
312
  }
121
313
 
314
+ function removeLegacyModelCache(): void {
315
+ const cachePath = legacyModelCachePath();
316
+ try {
317
+ unlinkSync(cachePath);
318
+ } catch (err) {
319
+ if (errorCode(err) === "ENOENT") return;
320
+ console.error(`Failed to remove legacy Hyper model cache at ${cachePath}: ${String(err)}`);
321
+ }
322
+ }
323
+
324
+ function errorCode(err: unknown): string | undefined {
325
+ const code = err instanceof Error ? Object.getOwnPropertyDescriptor(err, "code")?.value : undefined;
326
+ return typeof code === "string" ? code : undefined;
327
+ }
328
+
329
+ function isRecord(value: unknown): value is Record<string, unknown> {
330
+ return typeof value === "object" && value !== null && !Array.isArray(value);
331
+ }
332
+
122
333
  export async function loadModels(): Promise<ProviderModelConfig[]> {
123
334
  try {
124
335
  const payload = await fetchModelPayload();
125
- const models = parseSchema(ModelPayloadSchema, payload, "Hyper /models response").data.map(toProviderModel);
126
- writeCachedModelPayload(payload);
127
- return models;
336
+ const providerCatalog = providerPayload(payload, "Hyper /provider response");
337
+ writeCachedModelPayload(providerCatalog);
338
+ return providerCatalog.models.map(toProviderModel);
128
339
  } catch (err) {
129
- const cachedPayload = readCachedModelPayload();
130
- if (cachedPayload !== undefined) {
131
- console.error(`Failed to fetch Hyper /models, using cached model list: ${String(err)}`);
132
- return parseSchema(ModelPayloadSchema, cachedPayload, "Hyper model cache").data.map(toProviderModel);
340
+ const cachedCatalog = readCachedModelCatalog();
341
+ if (cachedCatalog !== undefined) {
342
+ console.error(`Failed to fetch Hyper /provider, using cached model list: ${String(err)}`);
343
+ return modelsFromCatalog(cachedCatalog);
133
344
  }
134
345
  throw err;
135
346
  }
package/src/oauth.ts CHANGED
@@ -1,12 +1,97 @@
1
1
  import { hostname } from "node:os";
2
2
  import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
3
- import { pollOAuthDeviceCodeFlow } from "@earendil-works/pi-ai/oauth";
4
- import { Type, type Static } from "typebox";
3
+ import { type Static, Type } from "typebox";
5
4
  import { Value } from "typebox/value";
5
+ import { fetchJson, fetchJsonResponse } from "./http.js";
6
6
  import { hyperBaseUrl, hyperJsonHeaders } from "./hyper.js";
7
- import { fetchJson } from "./http.js";
8
7
  import { parseSchema } from "./schema.js";
9
8
 
9
+ // Inlined from pi-ai (no longer publicly exported)
10
+ const CANCEL_MESSAGE = "Login cancelled";
11
+ const TIMEOUT_MESSAGE = "Device flow timed out";
12
+ const SLOW_DOWN_TIMEOUT_MESSAGE =
13
+ "Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";
14
+ const MINIMUM_INTERVAL_MS = 1000;
15
+ const POLL_DEFAULT_INTERVAL_SECONDS = 5;
16
+ const SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;
17
+
18
+ type OAuthDeviceCodeIncompletePollResult =
19
+ | { status: "pending" }
20
+ | { status: "slow_down"; intervalSeconds?: number }
21
+ | { status: "failed"; message: string };
22
+
23
+ type OAuthDeviceCodePollResult<T> = OAuthDeviceCodeIncompletePollResult | { status: "complete"; value: T };
24
+
25
+ function abortableSleep(ms: number, signal: AbortSignal | undefined, cancelMessage: string): Promise<void> {
26
+ return new Promise((resolve, reject) => {
27
+ if (signal?.aborted) {
28
+ reject(new Error(cancelMessage));
29
+ return;
30
+ }
31
+
32
+ const onAbort = () => {
33
+ clearTimeout(timeout);
34
+ reject(new Error(cancelMessage));
35
+ };
36
+ const timeout = setTimeout(() => {
37
+ signal?.removeEventListener("abort", onAbort);
38
+ resolve();
39
+ }, ms);
40
+
41
+ signal?.addEventListener("abort", onAbort, { once: true });
42
+ });
43
+ }
44
+
45
+ async function pollOAuthDeviceCodeFlow<T>(options: {
46
+ intervalSeconds?: number;
47
+ expiresInSeconds?: number;
48
+ poll: () => Promise<OAuthDeviceCodePollResult<T>>;
49
+ signal?: AbortSignal;
50
+ }): Promise<T> {
51
+ const deadline =
52
+ typeof options.expiresInSeconds === "number"
53
+ ? Date.now() + options.expiresInSeconds * 1000
54
+ : Number.POSITIVE_INFINITY;
55
+ let intervalMs = Math.max(
56
+ MINIMUM_INTERVAL_MS,
57
+ Math.floor((options.intervalSeconds ?? POLL_DEFAULT_INTERVAL_SECONDS) * 1000),
58
+ );
59
+
60
+ let slowDownResponses = 0;
61
+
62
+ while (Date.now() < deadline) {
63
+ if (options.signal?.aborted) {
64
+ throw new Error(CANCEL_MESSAGE);
65
+ }
66
+
67
+ const result = await options.poll();
68
+ if (result.status === "complete") {
69
+ return result.value;
70
+ }
71
+ if (result.status === "failed") {
72
+ throw new Error(result.message);
73
+ }
74
+ if (result.status === "slow_down") {
75
+ slowDownResponses += 1;
76
+ intervalMs =
77
+ typeof result.intervalSeconds === "number" &&
78
+ Number.isFinite(result.intervalSeconds) &&
79
+ result.intervalSeconds > 0
80
+ ? Math.max(MINIMUM_INTERVAL_MS, Math.floor(result.intervalSeconds * 1000))
81
+ : Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);
82
+ }
83
+
84
+ const remainingMs = deadline - Date.now();
85
+ if (remainingMs <= 0) {
86
+ break;
87
+ }
88
+
89
+ await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
90
+ }
91
+
92
+ throw new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);
93
+ }
94
+
10
95
  const DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;
11
96
  const TOKEN_EXPIRY_BUFFER_MS = 30_000;
12
97
  const OAUTH_FETCH_TIMEOUT_MS = 30_000;
@@ -82,10 +167,6 @@ type TokenExchangeResponse =
82
167
  | Static<typeof TokenExchangeWithExpiresInSchema>
83
168
  | Static<typeof TokenExchangeWithExpiresAtSchema>;
84
169
 
85
- type HyperOAuthCredentials = OAuthCredentials & {
86
- teamName?: string;
87
- };
88
-
89
170
  async function initiateDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthResponse> {
90
171
  const payload = await fetchJson(`${hyperBaseUrl()}/device/auth`, {
91
172
  method: "POST",
@@ -108,36 +189,42 @@ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSign
108
189
  expiresInSeconds: deviceAuth.expires_in,
109
190
  signal,
110
191
  poll: async () => {
111
- const payload = await fetchJson(`${hyperBaseUrl()}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`, {
112
- headers: hyperJsonHeaders(),
113
- signal,
114
- timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
115
- allowHttpErrorPayload: true,
116
- });
117
- const response = parseDevicePollResponse(payload);
118
-
119
- if ("refresh_token" in response) {
120
- return { status: "complete", value: response };
192
+ const response = await fetchJsonResponse(
193
+ `${hyperBaseUrl()}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`,
194
+ {
195
+ headers: hyperJsonHeaders(),
196
+ signal,
197
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
198
+ allowHttpErrorPayload: true,
199
+ },
200
+ );
201
+ const pollResponse = parseDevicePollResponse(
202
+ response.payload,
203
+ `Hyper device token response (HTTP ${response.status})`,
204
+ );
205
+
206
+ if ("refresh_token" in pollResponse) {
207
+ return { status: "complete", value: pollResponse };
121
208
  }
122
- if (response.error === "authorization_pending") return { status: "pending" };
123
- if (response.error === "slow_down") return { status: "slow_down" };
209
+ if (pollResponse.error === "authorization_pending") return { status: "pending" };
210
+ if (pollResponse.error === "slow_down") return { status: "slow_down" };
124
211
 
125
212
  return {
126
213
  status: "failed",
127
- message: `Hyper device authorization failed: ${response.error_description ?? response.error}`,
214
+ message: `Hyper device authorization failed: ${pollResponse.error_description ?? pollResponse.error}`,
128
215
  };
129
216
  },
130
217
  });
131
218
  }
132
219
 
133
- function parseDevicePollResponse(payload: unknown): DevicePollResponse {
220
+ function parseDevicePollResponse(payload: unknown, source = "Hyper device token response"): DevicePollResponse {
134
221
  if (Value.Check(DevicePollSuccessSchema, payload)) {
135
222
  return Value.Parse(DevicePollSuccessSchema, payload);
136
223
  }
137
224
  if (Value.Check(DevicePollErrorSchema, payload)) {
138
225
  return Value.Parse(DevicePollErrorSchema, payload);
139
226
  }
140
- parseSchema(DevicePollResponseSchema, payload, "Hyper device token response");
227
+ parseSchema(DevicePollResponseSchema, payload, source);
141
228
  throw new Error("Hyper device token response is invalid");
142
229
  }
143
230
 
@@ -166,7 +253,7 @@ function parseTokenExchangeResponse(payload: unknown): TokenExchangeResponse {
166
253
  function tokenToCredentials(
167
254
  token: TokenExchangeResponse,
168
255
  fallbackRefreshToken: string,
169
- metadata?: Pick<HyperOAuthCredentials, "teamName">,
256
+ metadata?: { teamName?: string },
170
257
  ): OAuthCredentials {
171
258
  const expires = tokenExpiresAtMs(token);
172
259
  return {
@@ -212,6 +299,6 @@ export async function refreshHyperToken(credentials: OAuthCredentials): Promise<
212
299
  }
213
300
 
214
301
  function teamNameFromCredentials(credentials: OAuthCredentials): string | undefined {
215
- const teamName = (credentials as HyperOAuthCredentials).teamName;
302
+ const teamName = credentials.teamName;
216
303
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
217
304
  }
package/src/settings.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
- import { Type, type Static } from "typebox";
4
+ import { type Static, Type } from "typebox";
5
5
  import { Value } from "typebox/value";
6
+ import { hyperProviderDir } from "./hyper.js";
6
7
 
7
8
  const HyperStatusItemsSchema = Type.Object(
8
9
  {
@@ -20,49 +21,107 @@ const DEFAULT_STATUS_ITEMS: HyperStatusItems = {
20
21
  };
21
22
 
22
23
  function settingsPath(): string {
24
+ return path.join(hyperProviderDir(), "settings.json");
25
+ }
26
+
27
+ function legacySettingsPath(): string {
23
28
  return path.join(getAgentDir(), "settings.json");
24
29
  }
25
30
 
26
31
  export function readHyperStatusItems(): HyperStatusItems {
27
32
  const settings = readSettingsObject();
28
- const hyper = propertyObject(settings, "hyper");
29
- const statusItems = hyper ? property(hyper, "statusItems") : undefined;
30
- if (statusItems === undefined) return { ...DEFAULT_STATUS_ITEMS };
31
- if (!Value.Check(HyperStatusItemsSchema, statusItems)) {
32
- console.error("Ignoring invalid hyper.statusItems in settings.json");
33
- return { ...DEFAULT_STATUS_ITEMS };
33
+ const statusItems = property(settings, "statusItems");
34
+ if (statusItems !== undefined) {
35
+ return (
36
+ parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json") ??
37
+ readLegacyHyperStatusItems() ?? { ...DEFAULT_STATUS_ITEMS }
38
+ );
34
39
  }
35
40
 
36
- return {
37
- ...DEFAULT_STATUS_ITEMS,
38
- ...Value.Parse(HyperStatusItemsSchema, statusItems),
39
- };
41
+ return readLegacyHyperStatusItems() ?? { ...DEFAULT_STATUS_ITEMS };
40
42
  }
41
43
 
42
44
  export function writeHyperStatusItems(statusItems: HyperStatusItems): void {
43
45
  const settings = readSettingsObject();
44
- const existingHyper = propertyObject(settings, "hyper") ?? {};
45
- settings.hyper = {
46
- ...existingHyper,
47
- statusItems,
48
- };
46
+ settings.statusItems = statusItems;
49
47
 
50
- mkdirSync(getAgentDir(), { recursive: true });
48
+ mkdirSync(hyperProviderDir(), { recursive: true });
51
49
  writeFileSync(settingsPath(), `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
52
50
  }
53
51
 
52
+ export function migrateHyperSettings(): void {
53
+ const legacySettings = readSettingsObject(legacySettingsPath());
54
+ const legacyHyper = propertyObject(legacySettings, "hyper");
55
+ if (!legacyHyper) return;
56
+
57
+ const legacyStatusItems = parseHyperStatusItems(
58
+ property(legacyHyper, "statusItems"),
59
+ "hyper.statusItems in settings.json",
60
+ );
61
+ const settings = readSettingsObject();
62
+ const statusItems = property(settings, "statusItems");
63
+ let hasUsableStatusItems =
64
+ parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json") !== undefined;
65
+
66
+ if (statusItems === undefined && legacyStatusItems !== undefined) {
67
+ settings.statusItems = legacyStatusItems;
68
+ writeSettingsObject(settingsPath(), settings);
69
+ hasUsableStatusItems = true;
70
+ }
71
+ if (!hasUsableStatusItems) return;
72
+
73
+ removeLegacyHyperStatusItems();
74
+ }
75
+
54
76
  export function defaultHyperStatusItems(): HyperStatusItems {
55
77
  return { ...DEFAULT_STATUS_ITEMS };
56
78
  }
57
79
 
58
- function readSettingsObject(): Record<string, unknown> {
59
- const filePath = settingsPath();
80
+ function readSettingsObject(filePath = settingsPath()): Record<string, unknown> {
60
81
  if (!existsSync(filePath)) return {};
61
82
  const payload = JSON.parse(readFileSync(filePath, "utf-8"));
62
83
  if (!isRecord(payload)) throw new Error(`${filePath} must contain a JSON object`);
63
84
  return payload;
64
85
  }
65
86
 
87
+ function writeSettingsObject(filePath: string, settings: Record<string, unknown>): void {
88
+ mkdirSync(path.dirname(filePath), { recursive: true });
89
+ writeFileSync(filePath, `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
90
+ }
91
+
92
+ function removeLegacyHyperStatusItems(): void {
93
+ const legacySettings = readSettingsObject(legacySettingsPath());
94
+ const legacyHyper = propertyObject(legacySettings, "hyper");
95
+ if (!legacyHyper || property(legacyHyper, "statusItems") === undefined) return;
96
+
97
+ delete legacyHyper.statusItems;
98
+ if (Object.keys(legacyHyper).length === 0) {
99
+ delete legacySettings.hyper;
100
+ }
101
+ writeSettingsObject(legacySettingsPath(), legacySettings);
102
+ }
103
+
104
+ function readLegacyHyperStatusItems(): HyperStatusItems | undefined {
105
+ const legacySettings = readSettingsObject(legacySettingsPath());
106
+ const legacyHyper = propertyObject(legacySettings, "hyper");
107
+ return legacyHyper
108
+ ? parseHyperStatusItems(property(legacyHyper, "statusItems"), "hyper.statusItems in settings.json")
109
+ : undefined;
110
+ }
111
+
112
+ function parseHyperStatusItems(value: unknown, source: string): HyperStatusItems | undefined {
113
+ if (value === undefined) return undefined;
114
+ if (!Value.Check(HyperStatusItemsSchema, value)) {
115
+ console.error(`Ignoring invalid ${source}`);
116
+ return undefined;
117
+ }
118
+
119
+ return {
120
+ ...DEFAULT_STATUS_ITEMS,
121
+ ...Value.Parse(HyperStatusItemsSchema, value),
122
+ };
123
+ }
124
+
66
125
  function property(source: Record<string, unknown>, key: string): unknown {
67
126
  return Object.getOwnPropertyDescriptor(source, key)?.value;
68
127
  }