@charmland/pi-hyper-provider 0.1.0 → 0.1.1

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
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.1",
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": {
package/src/credits.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
- import { PROVIDER_NAME, hyperApiBaseUrl, hyperJsonHeaders } from "./hyper.js";
4
3
  import { fetchJson } from "./http.js";
4
+ import { hyperApiBaseUrl, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
5
5
  import { parseSchema } from "./schema.js";
6
6
  import {
7
7
  defaultHyperStatusItems,
@@ -93,6 +93,12 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
93
93
  }
94
94
  }
95
95
 
96
+ function refreshInBackground(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): void {
97
+ void refresh(ctx, selectedModel).catch((err) => {
98
+ console.error(`Failed to update Hyper status: ${String(err)}`);
99
+ });
100
+ }
101
+
96
102
  pi.registerCommand("hyper-status", {
97
103
  description: "Configure the Charm Hyper footer status",
98
104
  handler: async (args, ctx) => {
@@ -113,17 +119,17 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
113
119
  },
114
120
  });
115
121
 
116
- pi.on("session_start", async (_event, ctx) => {
117
- await refresh(ctx);
122
+ pi.on("session_start", (_event, ctx) => {
123
+ refreshInBackground(ctx);
118
124
  });
119
125
 
120
- pi.on("model_select", async (event, ctx) => {
121
- await refresh(ctx, event.model);
126
+ pi.on("model_select", (event, ctx) => {
127
+ refreshInBackground(ctx, event.model);
122
128
  });
123
129
 
124
- pi.on("message_end", async (event, ctx) => {
130
+ pi.on("message_end", (event, ctx) => {
125
131
  if (event.message.role === "assistant" && isHyperModel(ctx.model)) {
126
- await refresh(ctx);
132
+ refreshInBackground(ctx);
127
133
  }
128
134
  });
129
135
  }
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,27 @@
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
14
  const PI_THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const satisfies readonly ThinkingLevel[];
15
+ // Hyper models without reasoning levels are on/off-only. Use Pi's medium level
16
+ // as the single representative "on" state; it is not sent as reasoning_effort.
17
+ const ON_OFF_THINKING_LEVEL_MAP: ThinkingLevelMap = {
18
+ off: "off",
19
+ minimal: null,
20
+ low: null,
21
+ medium: "medium",
22
+ high: null,
23
+ xhigh: null,
24
+ };
13
25
 
14
26
  const HyperModelBaseFields = {
15
27
  id: Type.String({ minLength: 1 }),
@@ -33,14 +45,14 @@ const HyperModelSchema = Type.Union([
33
45
  }),
34
46
  default_reasoning_effort: Type.String({ minLength: 1 }),
35
47
  },
36
- { additionalProperties: false },
48
+ { additionalProperties: true },
37
49
  ),
38
50
  Type.Object(
39
51
  {
40
52
  ...HyperModelBaseFields,
41
53
  supports_reasoning_effort: Type.Literal(false),
42
54
  },
43
- { additionalProperties: false },
55
+ { additionalProperties: true },
44
56
  ),
45
57
  ]);
46
58
 
@@ -49,20 +61,102 @@ const ModelPayloadSchema = Type.Object(
49
61
  object: Type.Literal("list"),
50
62
  data: Type.Array(HyperModelSchema, { minItems: 1 }),
51
63
  },
64
+ { additionalProperties: true },
65
+ );
66
+
67
+ const ProviderModelSchema = Type.Object(
68
+ {
69
+ id: Type.String({ minLength: 1 }),
70
+ name: Type.String({ minLength: 1 }),
71
+ cost_per_1m_in: Type.Number({ minimum: 0 }),
72
+ cost_per_1m_out: Type.Number({ minimum: 0 }),
73
+ cost_per_1m_in_cached: Type.Number({ minimum: 0 }),
74
+ cost_per_1m_out_cached: Type.Optional(Type.Number({ minimum: 0 })),
75
+ context_window: Type.Integer({ minimum: 1 }),
76
+ default_max_tokens: Type.Integer({ minimum: 1 }),
77
+ can_reason: Type.Boolean(),
78
+ reasoning_levels: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
79
+ default_reasoning_effort: Type.Optional(Type.String({ minLength: 1 })),
80
+ supports_attachments: Type.Boolean(),
81
+ },
82
+ { additionalProperties: true },
83
+ );
84
+
85
+ const ProviderPayloadSchema = Type.Object(
86
+ {
87
+ models: Type.Array(ProviderModelSchema, { minItems: 1 }),
88
+ },
89
+ { additionalProperties: true },
90
+ );
91
+
92
+ const ModelCacheEnvelopeSchema = Type.Object(
93
+ {
94
+ version: Type.Literal(MODEL_CACHE_VERSION),
95
+ hyperApiBaseUrl: Type.String({ minLength: 1 }),
96
+ fetchedAt: Type.String({ minLength: 1 }),
97
+ payload: ProviderPayloadSchema,
98
+ },
52
99
  { additionalProperties: false },
53
100
  );
54
101
 
55
102
  type HyperModel = Static<typeof HyperModelSchema>;
103
+ type ProviderModel = Static<typeof ProviderModelSchema>;
104
+ type ProviderPayload = Static<typeof ProviderPayloadSchema>;
105
+ type LegacyModelPayload = Static<typeof ModelPayloadSchema>;
106
+ type ModelCacheEnvelope = Static<typeof ModelCacheEnvelopeSchema>;
107
+ type ModelCatalog = { kind: "provider"; payload: ProviderPayload } | { kind: "legacy"; payload: LegacyModelPayload };
108
+ type ModelCacheRead = { status: "hit"; catalog: ModelCatalog } | { status: "miss" } | { status: "blocked" };
56
109
 
57
110
  function modelCachePath(): string {
58
- return path.join(hyperExtensionDir(), "models.json");
111
+ return path.join(hyperProviderDir(), "models.json");
112
+ }
113
+
114
+ function legacyModelCachePath(): string {
115
+ return path.join(legacyHyperExtensionDir(), "models.json");
116
+ }
117
+
118
+ function toProviderModel(model: ProviderModel): ProviderModelConfig {
119
+ const input: ProviderModelConfig["input"] = model.supports_attachments ? ["text", "image"] : ["text"];
120
+ const reasoningLevels = model.reasoning_levels ?? [];
121
+ const supportsReasoningEffort = reasoningLevels.length > 0;
122
+ const thinkingLevelMap = supportsReasoningEffort
123
+ ? buildThinkingLevelMap(reasoningLevels)
124
+ : model.can_reason
125
+ ? ON_OFF_THINKING_LEVEL_MAP
126
+ : undefined;
127
+
128
+ return {
129
+ id: model.id,
130
+ name: model.name,
131
+ reasoning: model.can_reason,
132
+ thinkingLevelMap,
133
+ input,
134
+ cost: {
135
+ input: model.cost_per_1m_in,
136
+ output: model.cost_per_1m_out,
137
+ cacheRead: model.cost_per_1m_in_cached,
138
+ // Hyper exposes cached input/output prices, but Pi only models cached
139
+ // input reads and cache writes. Hyper does not expose a cache-write price.
140
+ cacheWrite: 0,
141
+ },
142
+ contextWindow: model.context_window,
143
+ maxTokens: model.default_max_tokens,
144
+ compat: {
145
+ supportsStore: false,
146
+ supportsReasoningEffort,
147
+ thinkingFormat: "deepseek",
148
+ maxTokensField: "max_tokens",
149
+ },
150
+ };
59
151
  }
60
152
 
61
- function toProviderModel(model: HyperModel): ProviderModelConfig {
153
+ function toLegacyProviderModel(model: HyperModel): ProviderModelConfig {
62
154
  const input: ProviderModelConfig["input"] = model.supports_attachments ? ["text", "image"] : ["text"];
63
155
  const thinkingLevelMap = model.supports_reasoning_effort
64
156
  ? buildThinkingLevelMap(model.reasoning_effort_levels)
65
- : undefined;
157
+ : model.supports_reasoning
158
+ ? ON_OFF_THINKING_LEVEL_MAP
159
+ : undefined;
66
160
 
67
161
  return {
68
162
  id: model.id,
@@ -76,11 +170,35 @@ function toProviderModel(model: HyperModel): ProviderModelConfig {
76
170
  compat: {
77
171
  supportsStore: false,
78
172
  supportsReasoningEffort: model.supports_reasoning_effort,
173
+ thinkingFormat: "deepseek",
79
174
  maxTokensField: "max_tokens",
80
175
  },
81
176
  };
82
177
  }
83
178
 
179
+ function modelsFromCatalog(catalog: ModelCatalog): ProviderModelConfig[] {
180
+ switch (catalog.kind) {
181
+ case "provider":
182
+ return catalog.payload.models.map(toProviderModel);
183
+ case "legacy":
184
+ return catalog.payload.data.map(toLegacyProviderModel);
185
+ }
186
+ }
187
+
188
+ function providerPayload(payload: unknown, source: string): ProviderPayload {
189
+ return parseSchema(ProviderPayloadSchema, payload, source);
190
+ }
191
+
192
+ function optionalModelCatalog(payload: unknown): ModelCatalog | undefined {
193
+ if (Value.Check(ProviderPayloadSchema, payload)) {
194
+ return { kind: "provider", payload: Value.Parse(ProviderPayloadSchema, payload) };
195
+ }
196
+ if (Value.Check(ModelPayloadSchema, payload)) {
197
+ return { kind: "legacy", payload: Value.Parse(ModelPayloadSchema, payload) };
198
+ }
199
+ return undefined;
200
+ }
201
+
84
202
  function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
85
203
  if (levels.length === 0) return undefined;
86
204
  const availableLevels = new Set<string>(levels);
@@ -94,42 +212,128 @@ function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
94
212
  }
95
213
 
96
214
  async function fetchModelPayload(): Promise<unknown> {
97
- return fetchJson(`${hyperApiBaseUrl()}/models`, {
215
+ return fetchJson(`${hyperApiBaseUrl()}/provider`, {
98
216
  timeoutMs: MODEL_FETCH_TIMEOUT_MS,
99
217
  });
100
218
  }
101
219
 
102
- function readCachedModelPayload(): unknown | undefined {
220
+ function readCachedModelCatalog(): ModelCatalog | undefined {
103
221
  const cachePath = modelCachePath();
222
+ const cache = readModelCache(cachePath, "Hyper model cache");
223
+ if (cache.status === "hit") return cache.catalog;
224
+ if (cache.status === "blocked") return undefined;
225
+
226
+ const legacyCache = readModelCache(legacyModelCachePath(), "legacy Hyper model cache");
227
+ return legacyCache.status === "hit" ? legacyCache.catalog : undefined;
228
+ }
229
+
230
+ function readJsonCache(cachePath: string, description: string): unknown | undefined {
104
231
  if (!existsSync(cachePath)) return undefined;
105
232
  try {
106
233
  return JSON.parse(readFileSync(cachePath, "utf-8"));
107
234
  } catch (err) {
108
- console.error(`Failed to read Hyper model cache at ${cachePath}: ${String(err)}`);
235
+ console.error(`Failed to read ${description} at ${cachePath}: ${String(err)}`);
109
236
  return undefined;
110
237
  }
111
238
  }
112
239
 
113
- function writeCachedModelPayload(payload: unknown): void {
240
+ function readModelCache(cachePath: string, description: string): ModelCacheRead {
241
+ const cache = readJsonCache(cachePath, description);
242
+ if (cache === undefined) return { status: "miss" };
243
+ return unwrapModelCache(cache, description);
244
+ }
245
+
246
+ function unwrapModelCache(cache: unknown, description: string): ModelCacheRead {
247
+ const envelopeBaseUrl = modelCacheEnvelopeBaseUrl(cache);
248
+ if (envelopeBaseUrl !== undefined) {
249
+ const expectedBaseUrl = hyperApiBaseUrl();
250
+ if (envelopeBaseUrl !== expectedBaseUrl) {
251
+ console.error(`Ignoring ${description} for ${envelopeBaseUrl}; current Hyper API base URL is ${expectedBaseUrl}`);
252
+ return { status: "blocked" };
253
+ }
254
+ }
255
+
256
+ if (Value.Check(ModelCacheEnvelopeSchema, cache)) {
257
+ const envelope = Value.Parse(ModelCacheEnvelopeSchema, cache);
258
+ return { status: "hit", catalog: { kind: "provider", payload: envelope.payload } };
259
+ }
260
+
261
+ if (isModelCacheEnvelopeLike(cache)) {
262
+ console.error(`Ignoring invalid ${description} metadata`);
263
+ return { status: "blocked" };
264
+ }
265
+
266
+ const catalog = optionalModelCatalog(cache);
267
+ if (catalog === undefined) {
268
+ console.error(`Ignoring invalid ${description}`);
269
+ return { status: "miss" };
270
+ }
271
+
272
+ return { status: "hit", catalog };
273
+ }
274
+
275
+ function isModelCacheEnvelopeLike(cache: unknown): boolean {
276
+ if (!isRecord(cache)) return false;
277
+ if (Object.hasOwn(cache, "hyperApiBaseUrl") || Object.hasOwn(cache, "fetchedAt")) return true;
278
+ if (Object.hasOwn(cache, "version") && Object.hasOwn(cache, "payload")) return true;
279
+ return false;
280
+ }
281
+
282
+ function modelCacheEnvelopeBaseUrl(cache: unknown): string | undefined {
283
+ if (!isRecord(cache)) return undefined;
284
+ const value = Object.getOwnPropertyDescriptor(cache, "hyperApiBaseUrl")?.value;
285
+ return typeof value === "string" && value.trim() ? value : undefined;
286
+ }
287
+
288
+ function modelCacheEnvelope(payload: ProviderPayload): ModelCacheEnvelope {
289
+ return {
290
+ version: MODEL_CACHE_VERSION,
291
+ hyperApiBaseUrl: hyperApiBaseUrl(),
292
+ fetchedAt: new Date().toISOString(),
293
+ payload,
294
+ };
295
+ }
296
+
297
+ function writeCachedModelPayload(payload: ProviderPayload): void {
114
298
  try {
115
- mkdirSync(hyperExtensionDir(), { recursive: true });
116
- writeFileSync(modelCachePath(), `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
299
+ mkdirSync(hyperProviderDir(), { recursive: true });
300
+ writeFileSync(modelCachePath(), `${JSON.stringify(modelCacheEnvelope(payload), null, 2)}\n`, "utf-8");
301
+ removeLegacyModelCache();
117
302
  } catch (err) {
118
303
  console.error(`Failed to write Hyper model cache: ${String(err)}`);
119
304
  }
120
305
  }
121
306
 
307
+ function removeLegacyModelCache(): void {
308
+ const cachePath = legacyModelCachePath();
309
+ try {
310
+ unlinkSync(cachePath);
311
+ } catch (err) {
312
+ if (errorCode(err) === "ENOENT") return;
313
+ console.error(`Failed to remove legacy Hyper model cache at ${cachePath}: ${String(err)}`);
314
+ }
315
+ }
316
+
317
+ function errorCode(err: unknown): string | undefined {
318
+ const code = err instanceof Error ? Object.getOwnPropertyDescriptor(err, "code")?.value : undefined;
319
+ return typeof code === "string" ? code : undefined;
320
+ }
321
+
322
+ function isRecord(value: unknown): value is Record<string, unknown> {
323
+ return typeof value === "object" && value !== null && !Array.isArray(value);
324
+ }
325
+
122
326
  export async function loadModels(): Promise<ProviderModelConfig[]> {
123
327
  try {
124
328
  const payload = await fetchModelPayload();
125
- const models = parseSchema(ModelPayloadSchema, payload, "Hyper /models response").data.map(toProviderModel);
126
- writeCachedModelPayload(payload);
127
- return models;
329
+ const providerCatalog = providerPayload(payload, "Hyper /provider response");
330
+ writeCachedModelPayload(providerCatalog);
331
+ return providerCatalog.models.map(toProviderModel);
128
332
  } 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);
333
+ const cachedCatalog = readCachedModelCatalog();
334
+ if (cachedCatalog !== undefined) {
335
+ console.error(`Failed to fetch Hyper /provider, using cached model list: ${String(err)}`);
336
+ return modelsFromCatalog(cachedCatalog);
133
337
  }
134
338
  throw err;
135
339
  }
package/src/oauth.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { hostname } from "node:os";
2
2
  import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
3
3
  import { pollOAuthDeviceCodeFlow } from "@earendil-works/pi-ai/oauth";
4
- import { Type, type Static } from "typebox";
4
+ import { type Static, Type } from "typebox";
5
5
  import { Value } from "typebox/value";
6
+ import { fetchJson, fetchJsonResponse } from "./http.js";
6
7
  import { hyperBaseUrl, hyperJsonHeaders } from "./hyper.js";
7
- import { fetchJson } from "./http.js";
8
8
  import { parseSchema } from "./schema.js";
9
9
 
10
10
  const DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;
@@ -82,10 +82,6 @@ type TokenExchangeResponse =
82
82
  | Static<typeof TokenExchangeWithExpiresInSchema>
83
83
  | Static<typeof TokenExchangeWithExpiresAtSchema>;
84
84
 
85
- type HyperOAuthCredentials = OAuthCredentials & {
86
- teamName?: string;
87
- };
88
-
89
85
  async function initiateDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthResponse> {
90
86
  const payload = await fetchJson(`${hyperBaseUrl()}/device/auth`, {
91
87
  method: "POST",
@@ -108,36 +104,42 @@ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSign
108
104
  expiresInSeconds: deviceAuth.expires_in,
109
105
  signal,
110
106
  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 };
107
+ const response = await fetchJsonResponse(
108
+ `${hyperBaseUrl()}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`,
109
+ {
110
+ headers: hyperJsonHeaders(),
111
+ signal,
112
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
113
+ allowHttpErrorPayload: true,
114
+ },
115
+ );
116
+ const pollResponse = parseDevicePollResponse(
117
+ response.payload,
118
+ `Hyper device token response (HTTP ${response.status})`,
119
+ );
120
+
121
+ if ("refresh_token" in pollResponse) {
122
+ return { status: "complete", value: pollResponse };
121
123
  }
122
- if (response.error === "authorization_pending") return { status: "pending" };
123
- if (response.error === "slow_down") return { status: "slow_down" };
124
+ if (pollResponse.error === "authorization_pending") return { status: "pending" };
125
+ if (pollResponse.error === "slow_down") return { status: "slow_down" };
124
126
 
125
127
  return {
126
128
  status: "failed",
127
- message: `Hyper device authorization failed: ${response.error_description ?? response.error}`,
129
+ message: `Hyper device authorization failed: ${pollResponse.error_description ?? pollResponse.error}`,
128
130
  };
129
131
  },
130
132
  });
131
133
  }
132
134
 
133
- function parseDevicePollResponse(payload: unknown): DevicePollResponse {
135
+ function parseDevicePollResponse(payload: unknown, source = "Hyper device token response"): DevicePollResponse {
134
136
  if (Value.Check(DevicePollSuccessSchema, payload)) {
135
137
  return Value.Parse(DevicePollSuccessSchema, payload);
136
138
  }
137
139
  if (Value.Check(DevicePollErrorSchema, payload)) {
138
140
  return Value.Parse(DevicePollErrorSchema, payload);
139
141
  }
140
- parseSchema(DevicePollResponseSchema, payload, "Hyper device token response");
142
+ parseSchema(DevicePollResponseSchema, payload, source);
141
143
  throw new Error("Hyper device token response is invalid");
142
144
  }
143
145
 
@@ -166,7 +168,7 @@ function parseTokenExchangeResponse(payload: unknown): TokenExchangeResponse {
166
168
  function tokenToCredentials(
167
169
  token: TokenExchangeResponse,
168
170
  fallbackRefreshToken: string,
169
- metadata?: Pick<HyperOAuthCredentials, "teamName">,
171
+ metadata?: { teamName?: string },
170
172
  ): OAuthCredentials {
171
173
  const expires = tokenExpiresAtMs(token);
172
174
  return {
@@ -212,6 +214,6 @@ export async function refreshHyperToken(credentials: OAuthCredentials): Promise<
212
214
  }
213
215
 
214
216
  function teamNameFromCredentials(credentials: OAuthCredentials): string | undefined {
215
- const teamName = (credentials as HyperOAuthCredentials).teamName;
217
+ const teamName = credentials.teamName;
216
218
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
217
219
  }
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
  }