@charmland/pi-hyper-provider 0.1.3 → 0.2.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
@@ -17,6 +17,12 @@ pi install npm:@charmland/pi-hyper-provider
17
17
  pi install git:github.com/charmbracelet/pi-hyper-provider
18
18
  ```
19
19
 
20
+ > [!IMPORTANT]
21
+ > As of v83, Pi only creates and updates provider extensions' model caches when
22
+ > launched interactively. If you mostly use Pi in headless or non-interactive
23
+ > environments, open the TUI whenever you want to get new models or updated
24
+ > metadata.
25
+
20
26
  ## Usage
21
27
 
22
28
  - To authenticate with OAuth, open `pi`, send `/login`, pick `Subscription`, and select the
@@ -27,10 +33,11 @@ pi install git:github.com/charmbracelet/pi-hyper-provider
27
33
  Pick a Hyper model by sending `/model` and filtering by either provider name
28
34
  `hyper` or `model-name` like `glm-5.1`.
29
35
 
30
- Model info is fetched at startup and cached locally; the cache is used as a
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.
36
+ After Hyper credentials are configured, Pi discovers available models and
37
+ persists the latest successful catalog in its standard model store. A previously
38
+ discovered catalog remains available when a later refresh fails. By default,
39
+ your remaining Hypercredit balance is shown in the status line while a Hyper
40
+ model is active.
34
41
 
35
42
  Use `/hyper-status` to configure the status line interactively and toggle things
36
43
  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.3",
3
+ "version": "0.2.1",
4
4
  "description": "Pi extension for Charm's Hyper inference provider",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -27,11 +27,10 @@
27
27
  "@earendil-works/pi-coding-agent": "*",
28
28
  "typebox": "*"
29
29
  },
30
- "dependencies": {},
31
30
  "devDependencies": {
32
31
  "@biomejs/biome": "^2.4.16",
33
- "@earendil-works/pi-ai": "^0.81.1",
34
- "@earendil-works/pi-coding-agent": "^0.81.1",
32
+ "@earendil-works/pi-ai": "^0.83.0",
33
+ "@earendil-works/pi-coding-agent": "^0.83.0",
35
34
  "typebox": "^1.1.38",
36
35
  "typescript": "^6.0.3"
37
36
  },
package/src/credits.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { readStoredCredential } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
- import { fetchJson } from "./http.js";
5
- import { hyperApiBaseUrl, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
4
+ import { fetchJson, HttpNetworkError, HttpResponseError, HttpTimeoutError } from "./http.js";
5
+ import { HYPER_API_BASE_URL, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
6
+ import type { WarningSink } from "./notify.js";
6
7
  import { parseSchema } from "./schema.js";
7
8
  import {
8
9
  defaultHyperStatusItems,
@@ -13,6 +14,9 @@ import {
13
14
 
14
15
  const HYPER_GEM = "\x1b[38;2;255;96;255m◆\x1b[39m";
15
16
  const CREDITS_FETCH_TIMEOUT_MS = 10_000;
17
+ const CREDITS_RETRY_DELAY_MS_INITIAL = 5_000;
18
+ const CREDITS_RETRY_DELAY_MS_MAX = 5 * 60_000;
19
+ const CREDITS_RETRY_EXPONENT_MAX = 6;
16
20
 
17
21
  const CreditsPayloadSchema = Type.Object(
18
22
  {
@@ -22,7 +26,7 @@ const CreditsPayloadSchema = Type.Object(
22
26
  );
23
27
 
24
28
  async function fetchCredits(apiKey: string): Promise<number> {
25
- const payload = await fetchJson(`${hyperApiBaseUrl()}/credits`, {
29
+ const payload = await fetchJson(`${HYPER_API_BASE_URL}/credits`, {
26
30
  headers: hyperJsonHeaders({ Authorization: `Bearer ${apiKey}` }),
27
31
  timeoutMs: CREDITS_FETCH_TIMEOUT_MS,
28
32
  });
@@ -56,49 +60,163 @@ function storedTeamName(): string | undefined {
56
60
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
57
61
  }
58
62
 
59
- export function registerCreditStatus(pi: ExtensionAPI): void {
60
- let refreshGeneration = 0;
61
-
62
- async function refresh(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): Promise<void> {
63
- const generation = refreshGeneration + 1;
64
- refreshGeneration = generation;
63
+ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void {
64
+ let invocationSequence = 0;
65
+ let committedInvocation = 0;
66
+ let credentialEpoch = 0;
67
+ let consecutiveFailures = 0;
68
+ let retryAfterMs = 0;
69
+ let currentApiKey: string | undefined;
70
+ let cachedBalance: number | undefined;
71
+ let inFlight: { apiKey: string; credentialEpoch: number; operation: Promise<void> } | undefined;
72
+ type CredentialLease = { apiKey: string; credentialEpoch: number };
73
+
74
+ function clearCreditState(): void {
75
+ cachedBalance = undefined;
76
+ consecutiveFailures = 0;
77
+ retryAfterMs = 0;
78
+ }
65
79
 
66
- if (!isHyperModel(selectedModel)) {
67
- ctx.ui.setStatus(PROVIDER_NAME, undefined);
80
+ function renderStatus(ctx: ExtensionContext): void {
81
+ const statusItems = readHyperStatusItems(warn);
82
+ const teamName = storedTeamName();
83
+ if (!statusItems.hypercredits || cachedBalance === undefined) {
84
+ ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
68
85
  return;
69
86
  }
87
+ ctx.ui.setStatus(PROVIDER_NAME, statusText(cachedBalance, statusItems, teamName));
88
+ }
70
89
 
71
- const statusItems = readHyperStatusItems();
72
- const teamName = storedTeamName();
73
- if (!statusItems.hypercredits) {
74
- ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
90
+ function ownsCredential(lease: CredentialLease): boolean {
91
+ return lease.apiKey === currentApiKey && lease.credentialEpoch === credentialEpoch;
92
+ }
93
+
94
+ function render(ctx: ExtensionContext, lease: CredentialLease): void {
95
+ if (!ownsCredential(lease)) return;
96
+ renderStatus(ctx);
97
+ }
98
+
99
+ async function fetchAndCache(apiKey: string, expectedCredentialEpoch: number): Promise<void> {
100
+ try {
101
+ const balance = await fetchCredits(apiKey);
102
+ if (credentialEpoch !== expectedCredentialEpoch || currentApiKey !== apiKey) return;
103
+ cachedBalance = balance;
104
+ consecutiveFailures = 0;
105
+ retryAfterMs = 0;
106
+ } catch (error) {
107
+ if (credentialEpoch !== expectedCredentialEpoch || currentApiKey !== apiKey) throw error;
108
+ const transient =
109
+ error instanceof HttpNetworkError ||
110
+ error instanceof HttpTimeoutError ||
111
+ (error instanceof HttpResponseError &&
112
+ (error.status === 408 || error.status === 429 || (error.status >= 500 && error.status <= 599)));
113
+ if (!transient) {
114
+ clearCreditState();
115
+ throw error;
116
+ }
117
+ consecutiveFailures += 1;
118
+ const retryDelayMs = Math.min(
119
+ CREDITS_RETRY_DELAY_MS_INITIAL * 2 ** Math.min(consecutiveFailures - 1, CREDITS_RETRY_EXPONENT_MAX),
120
+ CREDITS_RETRY_DELAY_MS_MAX,
121
+ );
122
+ retryAfterMs = Date.now() + retryDelayMs;
123
+ throw error;
124
+ }
125
+ }
126
+
127
+ async function shareFetch(apiKey: string, expectedCredentialEpoch: number): Promise<void> {
128
+ const active = inFlight;
129
+ if (active?.apiKey === apiKey && active.credentialEpoch === expectedCredentialEpoch) {
130
+ await active.operation;
75
131
  return;
76
132
  }
77
133
 
78
- const auth = await ctx.modelRegistry.getApiKeyAndHeaders(selectedModel);
79
- if (!auth.ok || !auth.apiKey) {
134
+ const operation = fetchAndCache(apiKey, expectedCredentialEpoch);
135
+ const started = { apiKey, credentialEpoch: expectedCredentialEpoch, operation };
136
+ inFlight = started;
137
+ try {
138
+ await operation;
139
+ } finally {
140
+ if (inFlight === started) {
141
+ inFlight = undefined;
142
+ }
143
+ }
144
+ }
145
+
146
+ async function refresh(
147
+ ctx: ExtensionContext,
148
+ selectedModel: ExtensionContext["model"] = ctx.model,
149
+ isUserRequested = false,
150
+ ): Promise<void> {
151
+ const invocation = invocationSequence + 1;
152
+ invocationSequence = invocation;
153
+ const forcedLease: CredentialLease | undefined =
154
+ isUserRequested && currentApiKey !== undefined ? { apiKey: currentApiKey, credentialEpoch } : undefined;
155
+ let failureLease: CredentialLease | undefined;
156
+ if (!isHyperModel(selectedModel)) {
157
+ committedInvocation = invocation;
158
+ credentialEpoch += 1;
80
159
  ctx.ui.setStatus(PROVIDER_NAME, undefined);
81
160
  return;
82
161
  }
83
162
 
163
+ const statusItems = readHyperStatusItems(warn);
164
+ if (!statusItems.hypercredits) {
165
+ committedInvocation = invocation;
166
+ credentialEpoch += 1;
167
+ renderStatus(ctx);
168
+ return;
169
+ }
170
+
171
+ // Settings and team metadata do not depend on auth. Re-render them now,
172
+ // retaining a balance only while it belongs to the committed credential.
173
+ renderStatus(ctx);
84
174
  try {
85
- const balance = await fetchCredits(auth.apiKey);
86
- if (generation === refreshGeneration) {
87
- ctx.ui.setStatus(PROVIDER_NAME, statusText(balance, statusItems, teamName));
175
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(selectedModel);
176
+ const forcedLeaseStillValid =
177
+ forcedLease !== undefined && auth.ok && auth.apiKey === forcedLease.apiKey && ownsCredential(forcedLease);
178
+ if (invocation < committedInvocation && !forcedLeaseStillValid) return;
179
+ if (!auth.ok || !auth.apiKey) {
180
+ committedInvocation = invocation;
181
+ credentialEpoch += 1;
182
+ currentApiKey = undefined;
183
+ clearCreditState();
184
+ renderStatus(ctx);
185
+ return;
186
+ }
187
+ if (invocation >= committedInvocation) committedInvocation = invocation;
188
+ if (!isUserRequested && currentApiKey === auth.apiKey && Date.now() < retryAfterMs) {
189
+ // This auth result supersedes older general state, but a same-credential
190
+ // forced refresh retains its independent fetch lease.
191
+ return;
88
192
  }
89
- } catch (err) {
90
- console.error(`Failed to fetch Hyper /credits: ${String(err)}`);
91
- if (generation === refreshGeneration) {
92
- ctx.ui.setStatus(PROVIDER_NAME, undefined);
193
+ if (currentApiKey !== auth.apiKey) {
194
+ currentApiKey = auth.apiKey;
195
+ credentialEpoch += 1;
196
+ clearCreditState();
197
+ // Never show the previous account while the replacement request runs.
198
+ renderStatus(ctx);
199
+ }
200
+ const expectedCredentialEpoch = credentialEpoch;
201
+ const lease = { apiKey: auth.apiKey, credentialEpoch: expectedCredentialEpoch };
202
+ failureLease = lease;
203
+ await shareFetch(auth.apiKey, expectedCredentialEpoch);
204
+ render(ctx, lease);
205
+ } catch {
206
+ const failedOperationStillOwnsCredential = failureLease !== undefined && ownsCredential(failureLease);
207
+ if (failureLease !== undefined && failedOperationStillOwnsCredential) render(ctx, failureLease);
208
+ if (
209
+ isUserRequested &&
210
+ (failedOperationStillOwnsCredential || (failureLease === undefined && invocation === invocationSequence))
211
+ ) {
212
+ ctx.ui.notify("Unable to refresh Hypercredit balance", "warning");
93
213
  }
94
214
  }
95
215
  }
96
216
 
97
217
  function refreshInBackground(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): void {
98
218
  if (!ctx.hasUI) return;
99
- void refresh(ctx, selectedModel).catch((err) => {
100
- console.error(`Failed to update Hyper status: ${String(err)}`);
101
- });
219
+ void refresh(ctx, selectedModel).catch(() => undefined);
102
220
  }
103
221
 
104
222
  pi.registerCommand("hyper-status", {
@@ -106,18 +224,18 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
106
224
  handler: async (args, ctx) => {
107
225
  if (!args.trim()) {
108
226
  if (!ctx.hasUI) {
109
- ctx.ui.notify(statusItemsSummary(readHyperStatusItems()), "info");
227
+ ctx.ui.notify(statusItemsSummary(readHyperStatusItems(warn)), "info");
110
228
  return;
111
229
  }
112
230
 
113
- const changed = await configureStatusItems(ctx);
114
- if (changed) await refresh(ctx);
231
+ const changed = await configureStatusItems(ctx, warn);
232
+ if (changed) await refresh(ctx, ctx.model, true);
115
233
  return;
116
234
  }
117
235
 
118
- const message = updateStatusItems(args);
119
- ctx.ui.notify(message, "info");
120
- await refresh(ctx);
236
+ const result = updateStatusItems(args, warn);
237
+ ctx.ui.notify(result.message, "info");
238
+ if (result.kind === "changed") await refresh(ctx, ctx.model, true);
121
239
  },
122
240
  });
123
241
 
@@ -136,8 +254,8 @@ export function registerCreditStatus(pi: ExtensionAPI): void {
136
254
  });
137
255
  }
138
256
 
139
- async function configureStatusItems(ctx: ExtensionContext): Promise<boolean> {
140
- const initial = readHyperStatusItems();
257
+ async function configureStatusItems(ctx: ExtensionContext, warn: (message: string) => void): Promise<boolean> {
258
+ const initial = readHyperStatusItems(warn);
141
259
  let draft: HyperStatusItems = { ...initial };
142
260
 
143
261
  for (;;) {
@@ -190,31 +308,44 @@ async function configureStatusItems(ctx: ExtensionContext): Promise<boolean> {
190
308
  }
191
309
  }
192
310
 
193
- function updateStatusItems(args: string): string {
311
+ type StatusItemsUpdate =
312
+ | { kind: "changed"; message: string }
313
+ | { kind: "unchanged"; message: string }
314
+ | { kind: "invalid"; message: string };
315
+
316
+ function updateStatusItems(args: string, warn?: (message: string) => void): StatusItemsUpdate {
194
317
  const tokens = args.trim().split(/\s+/).filter(Boolean);
195
318
  if (tokens.length === 0) {
196
- return statusItemsSummary(readHyperStatusItems());
319
+ return { kind: "unchanged", message: statusItemsSummary(readHyperStatusItems(warn)) };
197
320
  }
198
321
  if (tokens.length === 1 && tokens[0] === "reset") {
199
322
  const statusItems = defaultHyperStatusItems();
323
+ const previous = readHyperStatusItems(warn);
324
+ if (sameStatusItems(previous, statusItems)) {
325
+ return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
326
+ }
200
327
  writeHyperStatusItems(statusItems);
201
- return `Hyper status reset. ${statusItemsSummary(statusItems)}`;
328
+ return { kind: "changed", message: `Hyper status reset. ${statusItemsSummary(statusItems)}` };
202
329
  }
203
330
  if (tokens.length !== 2) {
204
- return "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]";
331
+ return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
205
332
  }
206
333
 
207
334
  const [key, rawValue] = tokens;
208
335
  if ((key !== "teamName" && key !== "hypercredits") || (rawValue !== "true" && rawValue !== "false")) {
209
- return "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]";
336
+ return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
210
337
  }
211
338
 
339
+ const previous = readHyperStatusItems(warn);
212
340
  const statusItems = {
213
- ...readHyperStatusItems(),
341
+ ...previous,
214
342
  [key]: rawValue === "true",
215
343
  };
344
+ if (sameStatusItems(previous, statusItems)) {
345
+ return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
346
+ }
216
347
  writeHyperStatusItems(statusItems);
217
- return `Hyper status updated. ${statusItemsSummary(statusItems)}`;
348
+ return { kind: "changed", message: `Hyper status updated. ${statusItemsSummary(statusItems)}` };
218
349
  }
219
350
 
220
351
  function onOff(value: boolean): "on" | "off" {
package/src/http.ts CHANGED
@@ -1,3 +1,25 @@
1
+ import { STATUS_CODES } from "node:http";
2
+ import { type TSchema, Type } from "typebox";
3
+ import { Value } from "typebox/value";
4
+
5
+ const OpenAIErrorPayloadSchema = Type.Object(
6
+ {
7
+ error: Type.Object(
8
+ {
9
+ message: Type.String({ minLength: 1 }),
10
+ type: Type.String({ minLength: 1 }),
11
+ code: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
12
+ },
13
+ { additionalProperties: false },
14
+ ),
15
+ },
16
+ { additionalProperties: false },
17
+ );
18
+
19
+ const MAX_ERROR_MESSAGE_CHARACTERS = 200;
20
+ const SAFE_ERROR_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
21
+ const UNSAFE_ERROR_MESSAGE = /[<>\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
22
+
1
23
  export interface FetchJsonOptions {
2
24
  method?: RequestInit["method"];
3
25
  headers?: RequestInit["headers"];
@@ -13,6 +35,69 @@ export interface FetchJsonResponse {
13
35
  payload: unknown;
14
36
  }
15
37
 
38
+ type HttpResponseJson = { kind: "parsed"; value: unknown } | { kind: "unavailable" };
39
+
40
+ export class HttpResponseError extends Error {
41
+ readonly kind = "http";
42
+ readonly #responseJson: HttpResponseJson;
43
+
44
+ constructor(
45
+ readonly status: number,
46
+ message: string,
47
+ responseJson: HttpResponseJson,
48
+ ) {
49
+ super(message);
50
+ this.name = "HttpResponseError";
51
+ this.#responseJson = responseJson;
52
+ }
53
+
54
+ matchesResponseJson(schema: TSchema): boolean {
55
+ return this.#responseJson.kind === "parsed" && Value.Check(schema, this.#responseJson.value);
56
+ }
57
+ }
58
+
59
+ export class HttpTimeoutError extends Error {
60
+ readonly kind = "timeout";
61
+
62
+ constructor(message: string, cause: unknown) {
63
+ super(message, { cause });
64
+ this.name = "HttpTimeoutError";
65
+ }
66
+ }
67
+
68
+ export class HttpResponseTimeoutError extends HttpTimeoutError {
69
+ constructor(
70
+ readonly status: number,
71
+ message: string,
72
+ cause: unknown,
73
+ ) {
74
+ super(message, cause);
75
+ this.name = "HttpResponseTimeoutError";
76
+ }
77
+ }
78
+
79
+ export class HttpNetworkError extends Error {
80
+ readonly kind = "network";
81
+
82
+ constructor(message: string, cause: unknown) {
83
+ super(message, { cause });
84
+ this.name = "HttpNetworkError";
85
+ }
86
+ }
87
+
88
+ export class HttpResponsePayloadError extends Error {
89
+ readonly kind = "response";
90
+
91
+ constructor(
92
+ readonly status: number,
93
+ message: string,
94
+ cause?: unknown,
95
+ ) {
96
+ super(message, cause === undefined ? undefined : { cause });
97
+ this.name = "HttpResponsePayloadError";
98
+ }
99
+ }
100
+
16
101
  export async function fetchJson(url: string, options: FetchJsonOptions): Promise<unknown> {
17
102
  return (await fetchJsonResponse(url, options)).payload;
18
103
  }
@@ -43,9 +128,37 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
43
128
  body: options.body,
44
129
  signal: controller.signal,
45
130
  });
46
- const body = await response.text();
131
+ let body: string;
132
+ try {
133
+ body = await response.text();
134
+ } catch (error) {
135
+ if (timedOut) {
136
+ throw new HttpResponseTimeoutError(
137
+ response.status,
138
+ `${url} timed out after ${options.timeoutMs}ms while reading HTTP ${response.status} response body`,
139
+ error,
140
+ );
141
+ }
142
+ if (callerAborted) throw error;
143
+ if (!response.ok && !options.allowHttpErrorPayload) {
144
+ throw new HttpResponseError(
145
+ response.status,
146
+ `${url} returned ${formatHttpStatus(response.status)}; response body could not be read`,
147
+ { kind: "unavailable" },
148
+ );
149
+ }
150
+ throw new HttpNetworkError(
151
+ `${url} returned ${formatHttpStatus(response.status)}; response body could not be read`,
152
+ error,
153
+ );
154
+ }
47
155
  if (!response.ok && !options.allowHttpErrorPayload) {
48
- throw new Error(`${url} returned HTTP ${response.status}: ${summarizeBody(body)}`);
156
+ const responseJson = parseHttpResponseJson(body);
157
+ throw new HttpResponseError(
158
+ response.status,
159
+ formatHttpResponseError(url, response.status, responseJson),
160
+ responseJson,
161
+ );
49
162
  }
50
163
  return {
51
164
  status: response.status,
@@ -53,13 +166,21 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
53
166
  payload: parseJsonBody(url, response.status, body),
54
167
  };
55
168
  } catch (err) {
169
+ if (
170
+ err instanceof HttpResponseError ||
171
+ err instanceof HttpResponsePayloadError ||
172
+ err instanceof HttpNetworkError ||
173
+ err instanceof HttpTimeoutError
174
+ ) {
175
+ throw err;
176
+ }
56
177
  if (timedOut) {
57
- throw new Error(`${url} timed out after ${options.timeoutMs}ms`, { cause: err });
178
+ throw new HttpTimeoutError(`${url} timed out after ${options.timeoutMs}ms`, err);
58
179
  }
59
180
  if (callerAborted) {
60
181
  throw new Error(`${url} request was aborted`, { cause: err });
61
182
  }
62
- throw err;
183
+ throw new HttpNetworkError(`${url} request failed`, err);
63
184
  } finally {
64
185
  clearTimeout(timeout);
65
186
  options.signal?.removeEventListener("abort", abortFromCaller);
@@ -68,19 +189,50 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
68
189
 
69
190
  function parseJsonBody(url: string, status: number, body: string): unknown {
70
191
  if (!body.trim()) {
71
- throw new Error(`${url} returned HTTP ${status} with an empty JSON body`);
192
+ throw new HttpResponsePayloadError(status, `${url} returned ${formatHttpStatus(status)} with an empty JSON body`);
72
193
  }
73
194
  try {
74
195
  return JSON.parse(body);
75
- } catch (err) {
76
- throw new Error(`${url} returned invalid JSON (HTTP ${status}): ${summarizeBody(body)}`, { cause: err });
196
+ } catch {
197
+ throw new HttpResponsePayloadError(status, `${url} returned invalid JSON (${formatHttpStatus(status)})`);
198
+ }
199
+ }
200
+
201
+ function parseHttpResponseJson(body: string): HttpResponseJson {
202
+ try {
203
+ return { kind: "parsed", value: JSON.parse(body) };
204
+ } catch {
205
+ return { kind: "unavailable" };
77
206
  }
78
207
  }
79
208
 
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)}…`;
209
+ function formatHttpResponseError(url: string, status: number, responseJson: HttpResponseJson): string {
210
+ const prefix = `${url} returned ${formatHttpStatus(status)}`;
211
+ const detail = responseJson.kind === "parsed" ? parseSafeOpenAIError(responseJson.value) : undefined;
212
+ return detail === undefined ? prefix : `${prefix}: ${detail}`;
213
+ }
214
+
215
+ function formatHttpStatus(status: number): string {
216
+ const reason = STATUS_CODES[status];
217
+ return reason === undefined ? `HTTP ${status}` : `HTTP ${status} ${reason}`;
218
+ }
219
+
220
+ function parseSafeOpenAIError(payload: unknown): string | undefined {
221
+ if (!Value.Check(OpenAIErrorPayloadSchema, payload)) return undefined;
222
+
223
+ const parsed = payload.error;
224
+ if (!SAFE_ERROR_TOKEN.test(parsed.type)) return undefined;
225
+ if (parsed.code !== null && !SAFE_ERROR_TOKEN.test(parsed.code)) return undefined;
226
+ if (!isSafeErrorMessage(parsed.message)) return undefined;
227
+
228
+ const identity = parsed.code === null ? parsed.type : `${parsed.type}/${parsed.code}`;
229
+ return `${identity}: ${parsed.message}`;
230
+ }
231
+
232
+ function isSafeErrorMessage(message: string): boolean {
233
+ return (
234
+ message === message.trim() &&
235
+ Array.from(message).length <= MAX_ERROR_MESSAGE_CHARACTERS &&
236
+ !UNSAFE_ERROR_MESSAGE.test(message)
237
+ );
86
238
  }
package/src/hyper.ts CHANGED
@@ -9,27 +9,15 @@ const packageName = packageJson.name.split("/").at(-1) ?? "pi-hyper-provider";
9
9
 
10
10
  export const PROVIDER_NAME = "hyper";
11
11
  export const PROVIDER_DISPLAY_NAME = "Charm Hyper";
12
- export const DEFAULT_HYPER_URL = "https://hyper.charm.land";
12
+ export const HYPER_BASE_URL = "https://hyper.charm.land";
13
+ export const HYPER_API_BASE_URL = `${HYPER_BASE_URL}/v1`;
13
14
  export const HYPER_API_KEY = "$HYPER_API_KEY";
14
15
  export const HYPER_USER_AGENT = `${packageName}/${packageJson.version}`;
15
16
 
16
- export function hyperBaseUrl(): string {
17
- const raw = process.env.HYPER_URL?.trim() || DEFAULT_HYPER_URL;
18
- return raw.replace(/\/+$/, "");
19
- }
20
-
21
- export function hyperApiBaseUrl(): string {
22
- return `${hyperBaseUrl()}/v1`;
23
- }
24
-
25
17
  export function hyperProviderDir(): string {
26
18
  return path.join(getAgentDir(), "hyper-provider");
27
19
  }
28
20
 
29
- export function legacyHyperExtensionDir(): string {
30
- return path.join(getAgentDir(), "extensions", "hyper-provider");
31
- }
32
-
33
21
  export function hyperJsonHeaders(headers: Record<string, string> = {}): Record<string, string> {
34
22
  return {
35
23
  "Content-Type": "application/json",
package/src/index.ts CHANGED
@@ -2,23 +2,29 @@ import { createProvider, envApiKeyAuth } from "@earendil-works/pi-ai";
2
2
  import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { registerCreditStatus } from "./credits.js";
5
- import { hyperApiBaseUrl, PROVIDER_DISPLAY_NAME, PROVIDER_NAME } from "./hyper.js";
6
- import { loadModels } from "./models.js";
5
+ import { HYPER_API_BASE_URL, PROVIDER_DISPLAY_NAME, PROVIDER_NAME } from "./hyper.js";
6
+ import { fetchHyperModels } from "./models.js";
7
+ import { createNotifier } from "./notify.js";
7
8
  import { loginHyper, refreshHyperToken } from "./oauth.js";
8
9
  import { migrateHyperSettings } from "./settings.js";
9
- export default async function (pi: ExtensionAPI) {
10
+
11
+ export default function (pi: ExtensionAPI) {
12
+ const notifier = createNotifier();
13
+ pi.on("session_start", (_event, ctx) => {
14
+ notifier.activate(ctx);
15
+ });
16
+
10
17
  try {
11
- migrateHyperSettings();
18
+ migrateHyperSettings(notifier.warn);
12
19
  } catch (err) {
13
- console.error(`Failed to migrate Hyper settings: ${String(err)}`);
20
+ notifier.warn(`Failed to migrate Hyper settings: ${String(err)}`);
14
21
  }
15
- const models = await loadModels();
16
22
 
17
23
  pi.registerProvider(
18
24
  createProvider({
19
25
  id: PROVIDER_NAME,
20
26
  name: PROVIDER_DISPLAY_NAME,
21
- baseUrl: hyperApiBaseUrl(),
27
+ baseUrl: HYPER_API_BASE_URL,
22
28
  auth: {
23
29
  apiKey: envApiKeyAuth("Hyper API key", ["HYPER_API_KEY"]),
24
30
  oauth: {
@@ -28,10 +34,11 @@ export default async function (pi: ExtensionAPI) {
28
34
  toAuth: async (credential) => ({ apiKey: credential.access }),
29
35
  },
30
36
  },
31
- models,
37
+ models: [],
38
+ fetchModels: ({ signal }) => fetchHyperModels(signal),
32
39
  api: openAICompletionsApi(),
33
40
  }),
34
41
  );
35
42
 
36
- registerCreditStatus(pi);
43
+ registerCreditStatus(pi, notifier.warn);
37
44
  }
package/src/models.ts CHANGED
@@ -1,20 +1,10 @@
1
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
- import * as path from "node:path";
3
1
  import type { Model, ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
4
2
  import { type Static, Type } from "typebox";
5
- import { Value } from "typebox/value";
6
3
  import { fetchJson } from "./http.js";
7
- import {
8
- HYPER_USER_AGENT,
9
- hyperApiBaseUrl,
10
- hyperProviderDir,
11
- legacyHyperExtensionDir,
12
- PROVIDER_NAME,
13
- } from "./hyper.js";
4
+ import { HYPER_API_BASE_URL, HYPER_USER_AGENT, PROVIDER_NAME } from "./hyper.js";
14
5
  import { parseSchema } from "./schema.js";
15
6
 
16
7
  const MODEL_FETCH_TIMEOUT_MS = 3_000;
17
- const MODEL_CACHE_VERSION = 1;
18
8
 
19
9
  const PI_THINKING_LEVELS = [
20
10
  "minimal",
@@ -24,58 +14,20 @@ const PI_THINKING_LEVELS = [
24
14
  "xhigh",
25
15
  "max",
26
16
  ] as const satisfies readonly ThinkingLevel[];
27
- // Hyper models without reasoning levels are on/off-only. Use Pi's medium level
28
- // as the single representative "on" state; it is not sent as reasoning_effort.
17
+ // Hyper models without reasoning levels are on/off-only. Use Pi's max level as
18
+ // the single representative "on" state (boolean on means maximum effort); the
19
+ // deepseek compat switch we turn on later ends up dropping efforts and
20
+ // translating off as disabled and any other level as enabled.
29
21
  const ON_OFF_THINKING_LEVEL_MAP: ThinkingLevelMap = {
30
22
  off: "off",
31
23
  minimal: null,
32
24
  low: null,
33
- medium: "medium",
25
+ medium: null,
34
26
  high: null,
35
27
  xhigh: null,
28
+ max: "max",
36
29
  };
37
30
 
38
- const HyperModelBaseFields = {
39
- id: Type.String({ minLength: 1 }),
40
- object: Type.Literal("model"),
41
- created: Type.Integer({ minimum: 0 }),
42
- owned_by: Type.String({ minLength: 1 }),
43
- display_name: Type.String({ minLength: 1 }),
44
- supports_reasoning: Type.Boolean(),
45
- supports_attachments: Type.Boolean(),
46
- context_window: Type.Integer({ minimum: 1 }),
47
- max_output_tokens: Type.Integer({ minimum: 1 }),
48
- };
49
-
50
- const HyperModelSchema = Type.Union([
51
- Type.Object(
52
- {
53
- ...HyperModelBaseFields,
54
- supports_reasoning_effort: Type.Literal(true),
55
- reasoning_effort_levels: Type.Array(Type.String({ minLength: 1 }), {
56
- minItems: 1,
57
- }),
58
- default_reasoning_effort: Type.String({ minLength: 1 }),
59
- },
60
- { additionalProperties: true },
61
- ),
62
- Type.Object(
63
- {
64
- ...HyperModelBaseFields,
65
- supports_reasoning_effort: Type.Literal(false),
66
- },
67
- { additionalProperties: true },
68
- ),
69
- ]);
70
-
71
- const ModelPayloadSchema = Type.Object(
72
- {
73
- object: Type.Literal("list"),
74
- data: Type.Array(HyperModelSchema, { minItems: 1 }),
75
- },
76
- { additionalProperties: true },
77
- );
78
-
79
31
  const ProviderModelSchema = Type.Object(
80
32
  {
81
33
  id: Type.String({ minLength: 1 }),
@@ -101,31 +53,7 @@ const ProviderPayloadSchema = Type.Object(
101
53
  { additionalProperties: true },
102
54
  );
103
55
 
104
- const ModelCacheEnvelopeSchema = Type.Object(
105
- {
106
- version: Type.Literal(MODEL_CACHE_VERSION),
107
- hyperApiBaseUrl: Type.String({ minLength: 1 }),
108
- fetchedAt: Type.String({ minLength: 1 }),
109
- payload: ProviderPayloadSchema,
110
- },
111
- { additionalProperties: false },
112
- );
113
-
114
- type HyperModel = Static<typeof HyperModelSchema>;
115
56
  type ProviderModel = Static<typeof ProviderModelSchema>;
116
- type ProviderPayload = Static<typeof ProviderPayloadSchema>;
117
- type LegacyModelPayload = Static<typeof ModelPayloadSchema>;
118
- type ModelCacheEnvelope = Static<typeof ModelCacheEnvelopeSchema>;
119
- type ModelCatalog = { kind: "provider"; payload: ProviderPayload } | { kind: "legacy"; payload: LegacyModelPayload };
120
- type ModelCacheRead = { status: "hit"; catalog: ModelCatalog } | { status: "miss" } | { status: "blocked" };
121
-
122
- function modelCachePath(): string {
123
- return path.join(hyperProviderDir(), "models.json");
124
- }
125
-
126
- function legacyModelCachePath(): string {
127
- return path.join(legacyHyperExtensionDir(), "models.json");
128
- }
129
57
 
130
58
  function toProviderModel(model: ProviderModel): Model<"openai-completions"> {
131
59
  const input: ("text" | "image")[] = model.supports_attachments ? ["text", "image"] : ["text"];
@@ -142,7 +70,7 @@ function toProviderModel(model: ProviderModel): Model<"openai-completions"> {
142
70
  name: model.name,
143
71
  api: "openai-completions",
144
72
  provider: PROVIDER_NAME,
145
- baseUrl: hyperApiBaseUrl(),
73
+ baseUrl: HYPER_API_BASE_URL,
146
74
  headers: { "User-Agent": HYPER_USER_AGENT },
147
75
  reasoning: model.can_reason,
148
76
  thinkingLevelMap,
@@ -150,10 +78,8 @@ function toProviderModel(model: ProviderModel): Model<"openai-completions"> {
150
78
  cost: {
151
79
  input: model.cost_per_1m_in,
152
80
  output: model.cost_per_1m_out,
153
- cacheRead: model.cost_per_1m_in_cached,
154
- // Hyper exposes cached input/output prices, but Pi only models cached
155
- // input reads and cache writes. Hyper does not expose a cache-write price.
156
- cacheWrite: 0,
81
+ cacheRead: model.cost_per_1m_out_cached ?? 0,
82
+ cacheWrite: model.cost_per_1m_in_cached,
157
83
  },
158
84
  contextWindow: model.context_window,
159
85
  maxTokens: model.default_max_tokens,
@@ -166,59 +92,6 @@ function toProviderModel(model: ProviderModel): Model<"openai-completions"> {
166
92
  };
167
93
  }
168
94
 
169
- function toLegacyProviderModel(model: HyperModel): Model<"openai-completions"> {
170
- const input: ("text" | "image")[] = model.supports_attachments ? ["text", "image"] : ["text"];
171
- const thinkingLevelMap = model.supports_reasoning_effort
172
- ? buildThinkingLevelMap(model.reasoning_effort_levels)
173
- : model.supports_reasoning
174
- ? ON_OFF_THINKING_LEVEL_MAP
175
- : undefined;
176
-
177
- return {
178
- id: model.id,
179
- name: model.display_name,
180
- api: "openai-completions",
181
- provider: PROVIDER_NAME,
182
- baseUrl: hyperApiBaseUrl(),
183
- headers: { "User-Agent": HYPER_USER_AGENT },
184
- reasoning: model.supports_reasoning,
185
- thinkingLevelMap,
186
- input,
187
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
188
- contextWindow: model.context_window,
189
- maxTokens: model.max_output_tokens,
190
- compat: {
191
- supportsStore: false,
192
- supportsReasoningEffort: model.supports_reasoning_effort,
193
- thinkingFormat: "deepseek",
194
- maxTokensField: "max_tokens",
195
- },
196
- };
197
- }
198
-
199
- function modelsFromCatalog(catalog: ModelCatalog): Model<"openai-completions">[] {
200
- switch (catalog.kind) {
201
- case "provider":
202
- return catalog.payload.models.map(toProviderModel);
203
- case "legacy":
204
- return catalog.payload.data.map(toLegacyProviderModel);
205
- }
206
- }
207
-
208
- function providerPayload(payload: unknown, source: string): ProviderPayload {
209
- return parseSchema(ProviderPayloadSchema, payload, source);
210
- }
211
-
212
- function optionalModelCatalog(payload: unknown): ModelCatalog | undefined {
213
- if (Value.Check(ProviderPayloadSchema, payload)) {
214
- return { kind: "provider", payload: Value.Parse(ProviderPayloadSchema, payload) };
215
- }
216
- if (Value.Check(ModelPayloadSchema, payload)) {
217
- return { kind: "legacy", payload: Value.Parse(ModelPayloadSchema, payload) };
218
- }
219
- return undefined;
220
- }
221
-
222
95
  function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
223
96
  if (levels.length === 0) return undefined;
224
97
  const availableLevels = new Set<string>(levels);
@@ -231,130 +104,11 @@ function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
231
104
  return result;
232
105
  }
233
106
 
234
- async function fetchModelPayload(): Promise<unknown> {
235
- return fetchJson(`${hyperApiBaseUrl()}/provider`, {
107
+ export async function fetchHyperModels(signal?: AbortSignal): Promise<Model<"openai-completions">[]> {
108
+ const payload = await fetchJson(`${HYPER_API_BASE_URL}/models`, {
109
+ signal,
236
110
  timeoutMs: MODEL_FETCH_TIMEOUT_MS,
237
111
  });
238
- }
239
-
240
- function readCachedModelCatalog(): ModelCatalog | undefined {
241
- const cachePath = modelCachePath();
242
- const cache = readModelCache(cachePath, "Hyper model cache");
243
- if (cache.status === "hit") return cache.catalog;
244
- if (cache.status === "blocked") return undefined;
245
-
246
- const legacyCache = readModelCache(legacyModelCachePath(), "legacy Hyper model cache");
247
- return legacyCache.status === "hit" ? legacyCache.catalog : undefined;
248
- }
249
-
250
- function readJsonCache(cachePath: string, description: string): unknown | undefined {
251
- if (!existsSync(cachePath)) return undefined;
252
- try {
253
- return JSON.parse(readFileSync(cachePath, "utf-8"));
254
- } catch (err) {
255
- console.error(`Failed to read ${description} at ${cachePath}: ${String(err)}`);
256
- return undefined;
257
- }
258
- }
259
-
260
- function readModelCache(cachePath: string, description: string): ModelCacheRead {
261
- const cache = readJsonCache(cachePath, description);
262
- if (cache === undefined) return { status: "miss" };
263
- return unwrapModelCache(cache, description);
264
- }
265
-
266
- function unwrapModelCache(cache: unknown, description: string): ModelCacheRead {
267
- const envelopeBaseUrl = modelCacheEnvelopeBaseUrl(cache);
268
- if (envelopeBaseUrl !== undefined) {
269
- const expectedBaseUrl = hyperApiBaseUrl();
270
- if (envelopeBaseUrl !== expectedBaseUrl) {
271
- console.error(`Ignoring ${description} for ${envelopeBaseUrl}; current Hyper API base URL is ${expectedBaseUrl}`);
272
- return { status: "blocked" };
273
- }
274
- }
275
-
276
- if (Value.Check(ModelCacheEnvelopeSchema, cache)) {
277
- const envelope = Value.Parse(ModelCacheEnvelopeSchema, cache);
278
- return { status: "hit", catalog: { kind: "provider", payload: envelope.payload } };
279
- }
280
-
281
- if (isModelCacheEnvelopeLike(cache)) {
282
- console.error(`Ignoring invalid ${description} metadata`);
283
- return { status: "blocked" };
284
- }
285
-
286
- const catalog = optionalModelCatalog(cache);
287
- if (catalog === undefined) {
288
- console.error(`Ignoring invalid ${description}`);
289
- return { status: "miss" };
290
- }
291
-
292
- return { status: "hit", catalog };
293
- }
294
-
295
- function isModelCacheEnvelopeLike(cache: unknown): boolean {
296
- if (!isRecord(cache)) return false;
297
- if (Object.hasOwn(cache, "hyperApiBaseUrl") || Object.hasOwn(cache, "fetchedAt")) return true;
298
- if (Object.hasOwn(cache, "version") && Object.hasOwn(cache, "payload")) return true;
299
- return false;
300
- }
301
-
302
- function modelCacheEnvelopeBaseUrl(cache: unknown): string | undefined {
303
- if (!isRecord(cache)) return undefined;
304
- const value = Object.getOwnPropertyDescriptor(cache, "hyperApiBaseUrl")?.value;
305
- return typeof value === "string" && value.trim() ? value : undefined;
306
- }
307
-
308
- function modelCacheEnvelope(payload: ProviderPayload): ModelCacheEnvelope {
309
- return {
310
- version: MODEL_CACHE_VERSION,
311
- hyperApiBaseUrl: hyperApiBaseUrl(),
312
- fetchedAt: new Date().toISOString(),
313
- payload,
314
- };
315
- }
316
-
317
- function writeCachedModelPayload(payload: ProviderPayload): void {
318
- try {
319
- mkdirSync(hyperProviderDir(), { recursive: true });
320
- writeFileSync(modelCachePath(), `${JSON.stringify(modelCacheEnvelope(payload), null, 2)}\n`, "utf-8");
321
- removeLegacyModelCache();
322
- } catch (err) {
323
- console.error(`Failed to write Hyper model cache: ${String(err)}`);
324
- }
325
- }
326
-
327
- function removeLegacyModelCache(): void {
328
- const cachePath = legacyModelCachePath();
329
- try {
330
- unlinkSync(cachePath);
331
- } catch (err) {
332
- if (errorCode(err) === "ENOENT") return;
333
- console.error(`Failed to remove legacy Hyper model cache at ${cachePath}: ${String(err)}`);
334
- }
335
- }
336
-
337
- function errorCode(err: unknown): string | undefined {
338
- const code = err instanceof Error ? Object.getOwnPropertyDescriptor(err, "code")?.value : undefined;
339
- return typeof code === "string" ? code : undefined;
340
- }
341
-
342
- function isRecord(value: unknown): value is Record<string, unknown> {
343
- return typeof value === "object" && value !== null && !Array.isArray(value);
344
- }
345
-
346
- export async function loadModels(): Promise<Model<"openai-completions">[]> {
347
- try {
348
- const payload = await fetchModelPayload();
349
- const providerCatalog = providerPayload(payload, "Hyper /provider response");
350
- writeCachedModelPayload(providerCatalog);
351
- return providerCatalog.models.map(toProviderModel);
352
- } catch (err) {
353
- const cachedCatalog = readCachedModelCatalog();
354
- if (cachedCatalog !== undefined) {
355
- console.error(`Failed to fetch Hyper /provider, using cached model list: ${String(err)}`);
356
- return modelsFromCatalog(cachedCatalog);
357
- }
358
- throw err;
359
- }
112
+ const provider = parseSchema(ProviderPayloadSchema, payload, "Hyper /models response");
113
+ return provider.models.map(toProviderModel);
360
114
  }
package/src/notify.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export type WarningSink = (message: string) => void;
4
+
5
+ export interface Notifier {
6
+ /** Emit a deduplicated warning through the currently available output. */
7
+ warn: WarningSink;
8
+ /** Emit future warnings through the session's output mode. */
9
+ activate(ctx: ExtensionContext): void;
10
+ }
11
+
12
+ export function createNotifier(): Notifier {
13
+ const seenWarnings = new Set<string>();
14
+ const emitToStderr: WarningSink = (message) => process.stderr.write(`Hyper warning: ${message}\n`);
15
+ let emit: WarningSink = emitToStderr;
16
+ let activated = false;
17
+
18
+ return {
19
+ warn(message) {
20
+ if (seenWarnings.has(message)) return;
21
+ seenWarnings.add(message);
22
+ emit(message);
23
+ },
24
+
25
+ activate(ctx) {
26
+ if (activated) return;
27
+ activated = true;
28
+ if (ctx.hasUI) emit = (message) => ctx.ui.notify(message, "warning");
29
+ },
30
+ };
31
+ }
package/src/oauth.ts CHANGED
@@ -2,8 +2,8 @@ import { hostname } from "node:os";
2
2
  import type { AuthInteraction, OAuthCredential } from "@earendil-works/pi-ai";
3
3
  import { type Static, Type } from "typebox";
4
4
  import { Value } from "typebox/value";
5
- import { fetchJson, fetchJsonResponse } from "./http.js";
6
- import { hyperBaseUrl, hyperJsonHeaders } from "./hyper.js";
5
+ import { fetchJson, fetchJsonResponse, HttpResponseError } from "./http.js";
6
+ import { HYPER_BASE_URL, hyperJsonHeaders } from "./hyper.js";
7
7
  import { parseSchema } from "./schema.js";
8
8
 
9
9
  // Inlined from pi-ai (no longer publicly exported)
@@ -160,6 +160,13 @@ const TokenExchangeWithExpiresAtSchema = Type.Object(
160
160
 
161
161
  const TokenExchangeResponseSchema = Type.Union([TokenExchangeWithExpiresInSchema, TokenExchangeWithExpiresAtSchema]);
162
162
 
163
+ const RejectedRefreshTokenResponseSchema = Type.Object(
164
+ {
165
+ error: Type.Literal("could not get refresh token: not found"),
166
+ },
167
+ { additionalProperties: false },
168
+ );
169
+
163
170
  type DeviceAuthResponse = Static<typeof DeviceAuthResponseSchema>;
164
171
  type DevicePollResponse = Static<typeof DevicePollSuccessSchema> | Static<typeof DevicePollErrorSchema>;
165
172
  type DevicePollSuccess = Static<typeof DevicePollSuccessSchema>;
@@ -167,8 +174,17 @@ type TokenExchangeResponse =
167
174
  | Static<typeof TokenExchangeWithExpiresInSchema>
168
175
  | Static<typeof TokenExchangeWithExpiresAtSchema>;
169
176
 
177
+ class HyperRefreshTokenRejectedError extends Error {
178
+ readonly kind = "refresh_token_rejected";
179
+
180
+ constructor(cause: HttpResponseError) {
181
+ super("Your Hyper session is no longer valid. Run /login hyper to re-authenticate.", { cause });
182
+ this.name = "HyperRefreshTokenRejectedError";
183
+ }
184
+ }
185
+
170
186
  async function initiateDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthResponse> {
171
- const payload = await fetchJson(`${hyperBaseUrl()}/device/auth`, {
187
+ const payload = await fetchJson(`${HYPER_BASE_URL}/device/auth`, {
172
188
  method: "POST",
173
189
  headers: hyperJsonHeaders(),
174
190
  body: JSON.stringify({ device_name: deviceName() }),
@@ -190,7 +206,7 @@ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSign
190
206
  signal,
191
207
  poll: async () => {
192
208
  const response = await fetchJsonResponse(
193
- `${hyperBaseUrl()}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`,
209
+ `${HYPER_BASE_URL}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`,
194
210
  {
195
211
  headers: hyperJsonHeaders(),
196
212
  signal,
@@ -229,7 +245,7 @@ function parseDevicePollResponse(payload: unknown, source = "Hyper device token
229
245
  }
230
246
 
231
247
  async function exchangeRefreshToken(refreshToken: string, signal?: AbortSignal): Promise<TokenExchangeResponse> {
232
- const payload = await fetchJson(`${hyperBaseUrl()}/token/exchange`, {
248
+ const payload = await fetchJson(`${HYPER_BASE_URL}/token/exchange`, {
233
249
  method: "POST",
234
250
  headers: hyperJsonHeaders(),
235
251
  body: JSON.stringify({ refresh_token: refreshToken }),
@@ -294,12 +310,28 @@ export async function loginHyper(interaction: AuthInteraction): Promise<OAuthCre
294
310
  }
295
311
 
296
312
  export async function refreshHyperToken(credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredential> {
297
- const token = await exchangeRefreshToken(credential.refresh, signal);
313
+ let token: TokenExchangeResponse;
314
+ try {
315
+ token = await exchangeRefreshToken(credential.refresh, signal);
316
+ } catch (error) {
317
+ if (isRejectedRefreshTokenResponse(error)) {
318
+ throw new HyperRefreshTokenRejectedError(error);
319
+ }
320
+ throw error;
321
+ }
298
322
  return tokenToCredentials(token, credential.refresh, {
299
323
  teamName: teamNameFromCredentials(credential),
300
324
  });
301
325
  }
302
326
 
327
+ function isRejectedRefreshTokenResponse(error: unknown): error is HttpResponseError {
328
+ return (
329
+ error instanceof HttpResponseError &&
330
+ error.status === 401 &&
331
+ error.matchesResponseJson(RejectedRefreshTokenResponseSchema)
332
+ );
333
+ }
334
+
303
335
  function teamNameFromCredentials(credential: OAuthCredential): string | undefined {
304
336
  const teamName = credential.teamName;
305
337
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
package/src/settings.ts CHANGED
@@ -4,6 +4,7 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
4
  import { type Static, Type } from "typebox";
5
5
  import { Value } from "typebox/value";
6
6
  import { hyperProviderDir } from "./hyper.js";
7
+ import type { WarningSink } from "./notify.js";
7
8
 
8
9
  const HyperStatusItemsSchema = Type.Object(
9
10
  {
@@ -28,17 +29,17 @@ function legacySettingsPath(): string {
28
29
  return path.join(getAgentDir(), "settings.json");
29
30
  }
30
31
 
31
- export function readHyperStatusItems(): HyperStatusItems {
32
+ export function readHyperStatusItems(warn?: WarningSink): HyperStatusItems {
32
33
  const settings = readSettingsObject();
33
34
  const statusItems = property(settings, "statusItems");
34
35
  if (statusItems !== undefined) {
35
36
  return (
36
- parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json") ??
37
- readLegacyHyperStatusItems() ?? { ...DEFAULT_STATUS_ITEMS }
37
+ parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json", warn) ??
38
+ readLegacyHyperStatusItems(warn) ?? { ...DEFAULT_STATUS_ITEMS }
38
39
  );
39
40
  }
40
41
 
41
- return readLegacyHyperStatusItems() ?? { ...DEFAULT_STATUS_ITEMS };
42
+ return readLegacyHyperStatusItems(warn) ?? { ...DEFAULT_STATUS_ITEMS };
42
43
  }
43
44
 
44
45
  export function writeHyperStatusItems(statusItems: HyperStatusItems): void {
@@ -49,7 +50,7 @@ export function writeHyperStatusItems(statusItems: HyperStatusItems): void {
49
50
  writeFileSync(settingsPath(), `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
50
51
  }
51
52
 
52
- export function migrateHyperSettings(): void {
53
+ export function migrateHyperSettings(warn?: WarningSink): void {
53
54
  const legacySettings = readSettingsObject(legacySettingsPath());
54
55
  const legacyHyper = propertyObject(legacySettings, "hyper");
55
56
  if (!legacyHyper) return;
@@ -57,11 +58,12 @@ export function migrateHyperSettings(): void {
57
58
  const legacyStatusItems = parseHyperStatusItems(
58
59
  property(legacyHyper, "statusItems"),
59
60
  "hyper.statusItems in settings.json",
61
+ warn,
60
62
  );
61
63
  const settings = readSettingsObject();
62
64
  const statusItems = property(settings, "statusItems");
63
65
  let hasUsableStatusItems =
64
- parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json") !== undefined;
66
+ parseHyperStatusItems(statusItems, "statusItems in hyper-provider/settings.json", warn) !== undefined;
65
67
 
66
68
  if (statusItems === undefined && legacyStatusItems !== undefined) {
67
69
  settings.statusItems = legacyStatusItems;
@@ -101,18 +103,18 @@ function removeLegacyHyperStatusItems(): void {
101
103
  writeSettingsObject(legacySettingsPath(), legacySettings);
102
104
  }
103
105
 
104
- function readLegacyHyperStatusItems(): HyperStatusItems | undefined {
106
+ function readLegacyHyperStatusItems(warn?: WarningSink): HyperStatusItems | undefined {
105
107
  const legacySettings = readSettingsObject(legacySettingsPath());
106
108
  const legacyHyper = propertyObject(legacySettings, "hyper");
107
109
  return legacyHyper
108
- ? parseHyperStatusItems(property(legacyHyper, "statusItems"), "hyper.statusItems in settings.json")
110
+ ? parseHyperStatusItems(property(legacyHyper, "statusItems"), "hyper.statusItems in settings.json", warn)
109
111
  : undefined;
110
112
  }
111
113
 
112
- function parseHyperStatusItems(value: unknown, source: string): HyperStatusItems | undefined {
114
+ function parseHyperStatusItems(value: unknown, source: string, warn?: WarningSink): HyperStatusItems | undefined {
113
115
  if (value === undefined) return undefined;
114
116
  if (!Value.Check(HyperStatusItemsSchema, value)) {
115
- console.error(`Ignoring invalid ${source}`);
117
+ warn?.(`Ignoring invalid ${source}`);
116
118
  return undefined;
117
119
  }
118
120