@charmland/pi-hyper-provider 0.2.2 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@charmland/pi-hyper-provider",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "Pi extension for Charm's Hyper inference provider",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -29,8 +29,8 @@
29
29
  },
30
30
  "devDependencies": {
31
31
  "@biomejs/biome": "^2.4.16",
32
- "@earendil-works/pi-ai": "^0.83.0",
33
- "@earendil-works/pi-coding-agent": "^0.83.0",
32
+ "@earendil-works/pi-ai": "^0.84.1",
33
+ "@earendil-works/pi-coding-agent": "^0.84.1",
34
34
  "typebox": "^1.1.38",
35
35
  "typescript": "^6.0.3"
36
36
  },
package/src/credits.ts CHANGED
@@ -1,13 +1,15 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionCommandContext, 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, HttpNetworkError, HttpResponseError, HttpTimeoutError } from "./http.js";
4
+ import { Compile } from "typebox/compile";
5
+ import * as httpClient from "./http.js";
5
6
  import { HYPER_API_BASE_URL, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
6
7
  import type { WarningSink } from "./notify.js";
7
8
  import { parseSchema } from "./schema.js";
8
9
  import {
9
10
  defaultHyperStatusItems,
10
11
  type HyperStatusItems,
12
+ migrateHyperSettings,
11
13
  readHyperStatusItems,
12
14
  writeHyperStatusItems,
13
15
  } from "./settings.js";
@@ -18,19 +20,39 @@ const CREDITS_RETRY_DELAY_MS_INITIAL = 5_000;
18
20
  const CREDITS_RETRY_DELAY_MS_MAX = 5 * 60_000;
19
21
  const CREDITS_RETRY_EXPONENT_MAX = 6;
20
22
 
21
- const CreditsPayloadSchema = Type.Object(
22
- {
23
- balance: Type.Number(),
24
- },
25
- { additionalProperties: false },
26
- );
23
+ const CreditsPayloadSchema = Type.Union([
24
+ Type.Object(
25
+ {
26
+ balance: Type.Number(),
27
+ },
28
+ { additionalProperties: false },
29
+ ),
30
+ Type.Object(
31
+ {
32
+ balance_usd: Type.Number(),
33
+ },
34
+ { additionalProperties: false },
35
+ ),
36
+ ]);
37
+ const CreditsPayloadValidator = Compile(CreditsPayloadSchema);
27
38
 
28
- async function fetchCredits(apiKey: string): Promise<number> {
29
- const payload = await fetchJson(`${HYPER_API_BASE_URL}/credits`, {
39
+ async function fetchCredits(apiKey: string, signal: AbortSignal): Promise<number | undefined> {
40
+ const payload = await httpClient.fetchJson(`${HYPER_API_BASE_URL}/credits`, {
30
41
  headers: hyperJsonHeaders({ Authorization: `Bearer ${apiKey}` }),
42
+ signal,
31
43
  timeoutMs: CREDITS_FETCH_TIMEOUT_MS,
32
44
  });
33
- return parseSchema(CreditsPayloadSchema, payload, "Hyper /credits response").balance;
45
+ const credits = parseSchema(CreditsPayloadValidator, payload, "Hyper /credits response");
46
+ return "balance" in credits ? credits.balance : undefined;
47
+ }
48
+
49
+ function isTransientCreditError(error: unknown): boolean {
50
+ return (
51
+ error instanceof httpClient.HttpNetworkError ||
52
+ error instanceof httpClient.HttpTimeoutError ||
53
+ (error instanceof httpClient.HttpResponseError &&
54
+ (error.status === 408 || error.status === 429 || (error.status >= 500 && error.status <= 599)))
55
+ );
34
56
  }
35
57
 
36
58
  function formatCredits(balance: number): string {
@@ -60,25 +82,51 @@ function storedTeamName(): string | undefined {
60
82
  return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
61
83
  }
62
84
 
63
- export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void {
85
+ export interface CreditStatusRuntime {
86
+ handleCommand(args: string, ctx: ExtensionCommandContext): Promise<void>;
87
+ refresh(ctx: ExtensionContext, selectedModel: ExtensionContext["model"]): Promise<void>;
88
+ dispose(): void;
89
+ }
90
+
91
+ export function createCreditStatusRuntime(warn: WarningSink): CreditStatusRuntime {
92
+ try {
93
+ migrateHyperSettings(warn);
94
+ } catch (error) {
95
+ warn(`Failed to migrate Hyper settings: ${String(error)}`);
96
+ }
97
+
64
98
  let invocationSequence = 0;
65
99
  let committedInvocation = 0;
66
100
  let credentialEpoch = 0;
67
101
  let consecutiveFailures = 0;
68
- let retryAfterMs = 0;
102
+ let retryAtMs = 0;
69
103
  let currentApiKey: string | undefined;
70
104
  let cachedBalance: number | undefined;
71
- let inFlight: { apiKey: string; credentialEpoch: number; operation: Promise<void> } | undefined;
105
+ let statusItemsCache: HyperStatusItems | undefined;
106
+ let inFlight:
107
+ | { apiKey: string; credentialEpoch: number; controller: AbortController; operation: Promise<void> }
108
+ | undefined;
109
+ let disposed = false;
72
110
  type CredentialLease = { apiKey: string; credentialEpoch: number };
73
111
 
74
112
  function clearCreditState(): void {
75
113
  cachedBalance = undefined;
76
114
  consecutiveFailures = 0;
77
- retryAfterMs = 0;
115
+ retryAtMs = 0;
116
+ }
117
+
118
+ function invalidateCredential(): void {
119
+ credentialEpoch += 1;
120
+ inFlight?.controller.abort();
121
+ }
122
+
123
+ function getStatusItems(): HyperStatusItems {
124
+ if (statusItemsCache === undefined) statusItemsCache = readHyperStatusItems(warn);
125
+ return statusItemsCache;
78
126
  }
79
127
 
80
128
  function renderStatus(ctx: ExtensionContext): void {
81
- const statusItems = readHyperStatusItems(warn);
129
+ const statusItems = getStatusItems();
82
130
  const teamName = storedTeamName();
83
131
  if (!statusItems.hypercredits || cachedBalance === undefined) {
84
132
  ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
@@ -91,35 +139,37 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
91
139
  return lease.apiKey === currentApiKey && lease.credentialEpoch === credentialEpoch;
92
140
  }
93
141
 
142
+ function canRender(invocation: number, forcedLease: CredentialLease | undefined): boolean {
143
+ return invocation === invocationSequence || (forcedLease !== undefined && ownsCredential(forcedLease));
144
+ }
145
+
94
146
  function render(ctx: ExtensionContext, lease: CredentialLease): void {
95
147
  if (!ownsCredential(lease)) return;
96
148
  renderStatus(ctx);
97
149
  }
98
150
 
99
- async function fetchAndCache(apiKey: string, expectedCredentialEpoch: number): Promise<void> {
151
+ async function fetchAndCache(lease: CredentialLease, signal: AbortSignal): Promise<void> {
100
152
  try {
101
- const balance = await fetchCredits(apiKey);
102
- if (credentialEpoch !== expectedCredentialEpoch || currentApiKey !== apiKey) return;
153
+ const balance = await fetchCredits(lease.apiKey, signal);
154
+ if (disposed || !ownsCredential(lease)) return;
103
155
  cachedBalance = balance;
104
156
  consecutiveFailures = 0;
105
- retryAfterMs = 0;
157
+ retryAtMs = 0;
106
158
  } 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) {
159
+ if (disposed || !ownsCredential(lease)) throw error;
160
+ if (!isTransientCreditError(error)) {
114
161
  clearCreditState();
115
162
  throw error;
116
163
  }
117
164
  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;
165
+ const retryDelayMs =
166
+ error instanceof httpClient.HttpResponseError && error.retryAfterMs !== undefined
167
+ ? error.retryAfterMs
168
+ : Math.min(
169
+ CREDITS_RETRY_DELAY_MS_INITIAL * 2 ** Math.min(consecutiveFailures - 1, CREDITS_RETRY_EXPONENT_MAX),
170
+ CREDITS_RETRY_DELAY_MS_MAX,
171
+ );
172
+ retryAtMs = Date.now() + retryDelayMs;
123
173
  throw error;
124
174
  }
125
175
  }
@@ -131,8 +181,9 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
131
181
  return;
132
182
  }
133
183
 
134
- const operation = fetchAndCache(apiKey, expectedCredentialEpoch);
135
- const started = { apiKey, credentialEpoch: expectedCredentialEpoch, operation };
184
+ const controller = new AbortController();
185
+ const operation = fetchAndCache({ apiKey, credentialEpoch: expectedCredentialEpoch }, controller.signal);
186
+ const started = { apiKey, credentialEpoch: expectedCredentialEpoch, controller, operation };
136
187
  inFlight = started;
137
188
  try {
138
189
  await operation;
@@ -143,11 +194,12 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
143
194
  }
144
195
  }
145
196
 
146
- async function refresh(
197
+ async function refreshStatus(
147
198
  ctx: ExtensionContext,
148
199
  selectedModel: ExtensionContext["model"] = ctx.model,
149
200
  isUserRequested = false,
150
201
  ): Promise<void> {
202
+ if (disposed) return;
151
203
  const invocation = invocationSequence + 1;
152
204
  invocationSequence = invocation;
153
205
  const forcedLease: CredentialLease | undefined =
@@ -155,15 +207,15 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
155
207
  let failureLease: CredentialLease | undefined;
156
208
  if (!isHyperModel(selectedModel)) {
157
209
  committedInvocation = invocation;
158
- credentialEpoch += 1;
210
+ invalidateCredential();
159
211
  ctx.ui.setStatus(PROVIDER_NAME, undefined);
160
212
  return;
161
213
  }
162
214
 
163
- const statusItems = readHyperStatusItems(warn);
215
+ const statusItems = getStatusItems();
164
216
  if (!statusItems.hypercredits) {
165
217
  committedInvocation = invocation;
166
- credentialEpoch += 1;
218
+ invalidateCredential();
167
219
  renderStatus(ctx);
168
220
  return;
169
221
  }
@@ -173,26 +225,27 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
173
225
  renderStatus(ctx);
174
226
  try {
175
227
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(selectedModel);
228
+ if (disposed) return;
176
229
  const forcedLeaseStillValid =
177
230
  forcedLease !== undefined && auth.ok && auth.apiKey === forcedLease.apiKey && ownsCredential(forcedLease);
178
231
  if (invocation < committedInvocation && !forcedLeaseStillValid) return;
179
232
  if (!auth.ok || !auth.apiKey) {
180
233
  committedInvocation = invocation;
181
- credentialEpoch += 1;
234
+ invalidateCredential();
182
235
  currentApiKey = undefined;
183
236
  clearCreditState();
184
237
  renderStatus(ctx);
185
238
  return;
186
239
  }
187
240
  if (invocation >= committedInvocation) committedInvocation = invocation;
188
- if (!isUserRequested && currentApiKey === auth.apiKey && Date.now() < retryAfterMs) {
241
+ if (!isUserRequested && currentApiKey === auth.apiKey && Date.now() < retryAtMs) {
189
242
  // This auth result supersedes older general state, but a same-credential
190
243
  // forced refresh retains its independent fetch lease.
191
244
  return;
192
245
  }
193
246
  if (currentApiKey !== auth.apiKey) {
194
247
  currentApiKey = auth.apiKey;
195
- credentialEpoch += 1;
248
+ invalidateCredential();
196
249
  clearCreditState();
197
250
  // Never show the previous account while the replacement request runs.
198
251
  renderStatus(ctx);
@@ -201,8 +254,12 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
201
254
  const lease = { apiKey: auth.apiKey, credentialEpoch: expectedCredentialEpoch };
202
255
  failureLease = lease;
203
256
  await shareFetch(auth.apiKey, expectedCredentialEpoch);
257
+ if (disposed) return;
258
+ if (!canRender(invocation, forcedLease)) return;
204
259
  render(ctx, lease);
205
260
  } catch {
261
+ if (disposed) return;
262
+ if (!canRender(invocation, forcedLease)) return;
206
263
  const failedOperationStillOwnsCredential = failureLease !== undefined && ownsCredential(failureLease);
207
264
  if (failureLease !== undefined && failedOperationStillOwnsCredential) render(ctx, failureLease);
208
265
  if (
@@ -214,48 +271,54 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
214
271
  }
215
272
  }
216
273
 
217
- function refreshInBackground(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): void {
218
- if (!ctx.hasUI) return;
219
- void refresh(ctx, selectedModel).catch(() => undefined);
220
- }
221
-
222
- pi.registerCommand("hyper-status", {
223
- description: "Configure the Charm Hyper footer status",
224
- handler: async (args, ctx) => {
274
+ return {
275
+ async handleCommand(args, ctx) {
276
+ if (disposed) return;
225
277
  if (!args.trim()) {
226
278
  if (!ctx.hasUI) {
227
- ctx.ui.notify(statusItemsSummary(readHyperStatusItems(warn)), "info");
279
+ ctx.ui.notify(statusItemsSummary(getStatusItems()), "info");
228
280
  return;
229
281
  }
230
282
 
231
- const changed = await configureStatusItems(ctx, warn);
232
- if (changed) await refresh(ctx, ctx.model, true);
283
+ const statusItems = await configureStatusItems(ctx, getStatusItems(), () => disposed);
284
+ if (disposed) return;
285
+ if (statusItems) {
286
+ writeHyperStatusItems(statusItems);
287
+ statusItemsCache = statusItems;
288
+ ctx.ui.notify(`Hyper status updated. ${statusItemsSummary(statusItems)}`, "info");
289
+ await refreshStatus(ctx, ctx.model, true);
290
+ }
233
291
  return;
234
292
  }
235
293
 
236
- const result = updateStatusItems(args, warn);
294
+ const result = updateStatusItems(args, getStatusItems());
295
+ if (disposed) return;
296
+ if (result.kind === "changed") {
297
+ writeHyperStatusItems(result.statusItems);
298
+ statusItemsCache = result.statusItems;
299
+ }
237
300
  ctx.ui.notify(result.message, "info");
238
- if (result.kind === "changed") await refresh(ctx, ctx.model, true);
301
+ if (result.kind === "changed") await refreshStatus(ctx, ctx.model, true);
239
302
  },
240
- });
241
-
242
- pi.on("session_start", (_event, ctx) => {
243
- refreshInBackground(ctx);
244
- });
245
303
 
246
- pi.on("model_select", (event, ctx) => {
247
- refreshInBackground(ctx, event.model);
248
- });
304
+ refresh(ctx, selectedModel) {
305
+ return refreshStatus(ctx, selectedModel);
306
+ },
249
307
 
250
- pi.on("message_end", (event, ctx) => {
251
- if (event.message.role === "assistant" && isHyperModel(ctx.model)) {
252
- refreshInBackground(ctx);
253
- }
254
- });
308
+ dispose() {
309
+ if (disposed) return;
310
+ disposed = true;
311
+ committedInvocation = ++invocationSequence;
312
+ invalidateCredential();
313
+ },
314
+ };
255
315
  }
256
316
 
257
- async function configureStatusItems(ctx: ExtensionContext, warn: (message: string) => void): Promise<boolean> {
258
- const initial = readHyperStatusItems(warn);
317
+ async function configureStatusItems(
318
+ ctx: ExtensionContext,
319
+ initial: HyperStatusItems,
320
+ isDisposed: () => boolean,
321
+ ): Promise<HyperStatusItems | undefined> {
259
322
  let draft: HyperStatusItems = { ...initial };
260
323
 
261
324
  for (;;) {
@@ -272,10 +335,11 @@ async function configureStatusItems(ctx: ExtensionContext, warn: (message: strin
272
335
  saveOption,
273
336
  cancelOption,
274
337
  ]);
338
+ if (isDisposed()) return undefined;
275
339
 
276
340
  if (choice === undefined || choice === cancelOption) {
277
341
  ctx.ui.notify("Hyper status settings unchanged", "info");
278
- return false;
342
+ return undefined;
279
343
  }
280
344
  if (choice === teamOption) {
281
345
  draft = { ...draft, teamName: !draft.teamName };
@@ -292,40 +356,42 @@ async function configureStatusItems(ctx: ExtensionContext, warn: (message: strin
292
356
  if (choice === saveOption) {
293
357
  if (sameStatusItems(initial, draft)) {
294
358
  ctx.ui.notify(`Hyper status unchanged. ${statusItemsSummary(draft)}`, "info");
295
- return false;
359
+ return undefined;
296
360
  }
297
361
 
298
362
  const ok = await ctx.ui.confirm("Save Hyper status settings?", statusItemsSummary(draft));
363
+ if (isDisposed()) return undefined;
299
364
  if (!ok) {
300
365
  ctx.ui.notify("Hyper status settings unchanged", "info");
301
- return false;
366
+ return undefined;
302
367
  }
303
368
 
304
- writeHyperStatusItems(draft);
305
- ctx.ui.notify(`Hyper status updated. ${statusItemsSummary(draft)}`, "info");
306
- return true;
369
+ if (isDisposed()) return undefined;
370
+ return draft;
307
371
  }
308
372
  }
309
373
  }
310
374
 
311
375
  type StatusItemsUpdate =
312
- | { kind: "changed"; message: string }
376
+ | { kind: "changed"; message: string; statusItems: HyperStatusItems }
313
377
  | { kind: "unchanged"; message: string }
314
378
  | { kind: "invalid"; message: string };
315
379
 
316
- function updateStatusItems(args: string, warn?: (message: string) => void): StatusItemsUpdate {
380
+ function updateStatusItems(args: string, previous: HyperStatusItems): StatusItemsUpdate {
317
381
  const tokens = args.trim().split(/\s+/).filter(Boolean);
318
382
  if (tokens.length === 0) {
319
- return { kind: "unchanged", message: statusItemsSummary(readHyperStatusItems(warn)) };
383
+ return { kind: "unchanged", message: statusItemsSummary(previous) };
320
384
  }
321
385
  if (tokens.length === 1 && tokens[0] === "reset") {
322
386
  const statusItems = defaultHyperStatusItems();
323
- const previous = readHyperStatusItems(warn);
324
387
  if (sameStatusItems(previous, statusItems)) {
325
388
  return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
326
389
  }
327
- writeHyperStatusItems(statusItems);
328
- return { kind: "changed", message: `Hyper status reset. ${statusItemsSummary(statusItems)}` };
390
+ return {
391
+ kind: "changed",
392
+ message: `Hyper status reset. ${statusItemsSummary(statusItems)}`,
393
+ statusItems,
394
+ };
329
395
  }
330
396
  if (tokens.length !== 2) {
331
397
  return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
@@ -336,7 +402,6 @@ function updateStatusItems(args: string, warn?: (message: string) => void): Stat
336
402
  return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
337
403
  }
338
404
 
339
- const previous = readHyperStatusItems(warn);
340
405
  const statusItems = {
341
406
  ...previous,
342
407
  [key]: rawValue === "true",
@@ -344,8 +409,11 @@ function updateStatusItems(args: string, warn?: (message: string) => void): Stat
344
409
  if (sameStatusItems(previous, statusItems)) {
345
410
  return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
346
411
  }
347
- writeHyperStatusItems(statusItems);
348
- return { kind: "changed", message: `Hyper status updated. ${statusItemsSummary(statusItems)}` };
412
+ return {
413
+ kind: "changed",
414
+ message: `Hyper status updated. ${statusItemsSummary(statusItems)}`,
415
+ statusItems,
416
+ };
349
417
  }
350
418
 
351
419
  function onOff(value: boolean): "on" | "off" {
package/src/http.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { STATUS_CODES } from "node:http";
2
- import { type TSchema, Type } from "typebox";
3
- import { Value } from "typebox/value";
2
+ import { type TProperties, type TSchema, Type } from "typebox";
3
+ import { Compile, type Validator } from "typebox/compile";
4
4
 
5
5
  const OpenAIErrorPayloadSchema = Type.Object(
6
6
  {
@@ -15,8 +15,12 @@ const OpenAIErrorPayloadSchema = Type.Object(
15
15
  },
16
16
  { additionalProperties: false },
17
17
  );
18
+ const OpenAIErrorPayloadValidator = Compile(OpenAIErrorPayloadSchema);
18
19
 
19
20
  const MAX_ERROR_MESSAGE_CHARACTERS = 200;
21
+ const RETRY_AFTER_DELAY_MS_MAX = 24 * 60 * 60_000;
22
+ const RETRY_AFTER_HTTP_DATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
23
+ const RETRY_AFTER_SECONDS = /^\d+$/;
20
24
  const SAFE_ERROR_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
21
25
  const UNSAFE_ERROR_MESSAGE = /[<>\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
22
26
 
@@ -45,14 +49,17 @@ export class HttpResponseError extends Error {
45
49
  readonly status: number,
46
50
  message: string,
47
51
  responseJson: HttpResponseJson,
52
+ readonly retryAfterMs?: number,
48
53
  ) {
49
54
  super(message);
50
55
  this.name = "HttpResponseError";
51
56
  this.#responseJson = responseJson;
52
57
  }
53
58
 
54
- matchesResponseJson(schema: TSchema): boolean {
55
- return this.#responseJson.kind === "parsed" && Value.Check(schema, this.#responseJson.value);
59
+ matchesResponseJson<Context extends TProperties, const Schema extends TSchema>(
60
+ validator: Validator<Context, Schema>,
61
+ ): boolean {
62
+ return this.#responseJson.kind === "parsed" && validator.Check(this.#responseJson.value);
56
63
  }
57
64
  }
58
65
 
@@ -103,48 +110,34 @@ export async function fetchJson(url: string, options: FetchJsonOptions): Promise
103
110
  }
104
111
 
105
112
  export async function fetchJsonResponse(url: string, options: FetchJsonOptions): Promise<FetchJsonResponse> {
106
- const controller = new AbortController();
107
- let timedOut = false;
108
- let callerAborted = false;
109
- const timeout = setTimeout(() => {
110
- timedOut = true;
111
- controller.abort();
112
- }, options.timeoutMs);
113
- const abortFromCaller = () => {
114
- callerAborted = true;
115
- controller.abort();
116
- };
117
- if (options.signal?.aborted) {
118
- callerAborted = true;
119
- controller.abort();
120
- } else {
121
- options.signal?.addEventListener("abort", abortFromCaller, { once: true });
122
- }
113
+ const timeoutSignal = AbortSignal.timeout(options.timeoutMs);
114
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
123
115
 
124
116
  try {
125
117
  const response = await fetch(url, {
126
118
  method: options.method,
127
119
  headers: options.headers,
128
120
  body: options.body,
129
- signal: controller.signal,
121
+ signal,
130
122
  });
131
123
  let body: string;
132
124
  try {
133
125
  body = await response.text();
134
126
  } catch (error) {
135
- if (timedOut) {
127
+ if (abortedBy(signal, timeoutSignal)) {
136
128
  throw new HttpResponseTimeoutError(
137
129
  response.status,
138
130
  `${url} timed out after ${options.timeoutMs}ms while reading HTTP ${response.status} response body`,
139
131
  error,
140
132
  );
141
133
  }
142
- if (callerAborted) throw error;
134
+ if (options.signal && abortedBy(signal, options.signal)) throw error;
143
135
  if (!response.ok && !options.allowHttpErrorPayload) {
144
136
  throw new HttpResponseError(
145
137
  response.status,
146
138
  `${url} returned ${formatHttpStatus(response.status)}; response body could not be read`,
147
139
  { kind: "unavailable" },
140
+ parseRetryAfterMs(response.headers.get("Retry-After")),
148
141
  );
149
142
  }
150
143
  throw new HttpNetworkError(
@@ -158,6 +151,7 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
158
151
  response.status,
159
152
  formatHttpResponseError(url, response.status, responseJson),
160
153
  responseJson,
154
+ parseRetryAfterMs(response.headers.get("Retry-After")),
161
155
  );
162
156
  }
163
157
  return {
@@ -166,6 +160,9 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
166
160
  payload: parseJsonBody(url, response.status, body),
167
161
  };
168
162
  } catch (err) {
163
+ if (options.signal && abortedBy(signal, options.signal) && err === options.signal.reason) {
164
+ throw new Error(`${url} request was aborted`, { cause: err });
165
+ }
169
166
  if (
170
167
  err instanceof HttpResponseError ||
171
168
  err instanceof HttpResponsePayloadError ||
@@ -174,19 +171,37 @@ export async function fetchJsonResponse(url: string, options: FetchJsonOptions):
174
171
  ) {
175
172
  throw err;
176
173
  }
177
- if (timedOut) {
174
+ if (abortedBy(signal, timeoutSignal)) {
178
175
  throw new HttpTimeoutError(`${url} timed out after ${options.timeoutMs}ms`, err);
179
176
  }
180
- if (callerAborted) {
177
+ if (options.signal && abortedBy(signal, options.signal)) {
181
178
  throw new Error(`${url} request was aborted`, { cause: err });
182
179
  }
183
180
  throw new HttpNetworkError(`${url} request failed`, err);
184
- } finally {
185
- clearTimeout(timeout);
186
- options.signal?.removeEventListener("abort", abortFromCaller);
187
181
  }
188
182
  }
189
183
 
184
+ function abortedBy(signal: AbortSignal, source: AbortSignal): boolean {
185
+ return signal.aborted && source.aborted && signal.reason === source.reason;
186
+ }
187
+
188
+ function parseRetryAfterMs(value: string | null): number | undefined {
189
+ if (value === null) return undefined;
190
+ const normalized = value.trim();
191
+ let delayMs: number;
192
+ if (RETRY_AFTER_SECONDS.test(normalized)) {
193
+ delayMs = Number(normalized) * 1000;
194
+ } else if (RETRY_AFTER_HTTP_DATE.test(normalized)) {
195
+ const retryAtMs = Date.parse(normalized);
196
+ if (Number.isNaN(retryAtMs) || new Date(retryAtMs).toUTCString() !== normalized) return undefined;
197
+ delayMs = retryAtMs - Date.now();
198
+ } else {
199
+ return undefined;
200
+ }
201
+ if (Number.isNaN(delayMs)) return undefined;
202
+ return Math.min(Math.max(0, delayMs), RETRY_AFTER_DELAY_MS_MAX);
203
+ }
204
+
190
205
  function parseJsonBody(url: string, status: number, body: string): unknown {
191
206
  if (!body.trim()) {
192
207
  throw new HttpResponsePayloadError(status, `${url} returned ${formatHttpStatus(status)} with an empty JSON body`);
@@ -218,7 +233,7 @@ function formatHttpStatus(status: number): string {
218
233
  }
219
234
 
220
235
  function parseSafeOpenAIError(payload: unknown): string | undefined {
221
- if (!Value.Check(OpenAIErrorPayloadSchema, payload)) return undefined;
236
+ if (!OpenAIErrorPayloadValidator.Check(payload)) return undefined;
222
237
 
223
238
  const parsed = payload.error;
224
239
  if (!SAFE_ERROR_TOKEN.test(parsed.type)) return undefined;
package/src/index.ts CHANGED
@@ -1,44 +1,194 @@
1
- import { createProvider, envApiKeyAuth } from "@earendil-works/pi-ai";
1
+ import { envApiKeyAuth, lazyOAuth, type Model, type OAuthAuth } from "@earendil-works/pi-ai";
2
2
  import { openAICompletionsApi } from "@earendil-works/pi-ai/compat";
3
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { registerCreditStatus } from "./credits.js";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { CreditStatusRuntime } from "./credits.js";
5
5
  import { HYPER_API_BASE_URL, PROVIDER_DISPLAY_NAME, PROVIDER_NAME } from "./hyper.js";
6
- import { fetchHyperModels } from "./models.js";
7
6
  import { createNotifier } from "./notify.js";
8
- import { loginHyper, refreshHyperToken } from "./oauth.js";
9
- import { migrateHyperSettings } from "./settings.js";
7
+
8
+ type CreditStatusState =
9
+ | { kind: "idle" }
10
+ | { kind: "loading"; operation: Promise<CreditStatusRuntime> }
11
+ | { kind: "ready"; runtime: CreditStatusRuntime }
12
+ | { kind: "disposed" };
13
+
14
+ type PendingCreditStatusRefresh = {
15
+ ctx: ExtensionContext;
16
+ model: ExtensionContext["model"];
17
+ };
10
18
 
11
19
  export default function (pi: ExtensionAPI) {
12
20
  const notifier = createNotifier();
21
+ const hyperApi = openAICompletionsApi();
22
+ let hyperModels: readonly Model<"openai-completions">[] = [];
23
+ let creditStatusState: CreditStatusState = { kind: "idle" };
24
+ let pendingCreditStatusRefresh: PendingCreditStatusRefresh | undefined;
25
+ let creditStatusRefreshWork: ReturnType<typeof setImmediate> | undefined;
26
+
27
+ function loadCreditStatus(): Promise<CreditStatusRuntime> {
28
+ if (creditStatusState.kind === "ready") return Promise.resolve(creditStatusState.runtime);
29
+ if (creditStatusState.kind === "loading") return creditStatusState.operation;
30
+ if (creditStatusState.kind === "disposed") {
31
+ return Promise.reject(new Error("Hyper status support was disposed"));
32
+ }
33
+
34
+ const operation = import("./credits.js").then(({ createCreditStatusRuntime }) => {
35
+ const runtime = createCreditStatusRuntime(notifier.warn);
36
+ if (creditStatusState.kind === "disposed") {
37
+ runtime.dispose();
38
+ return runtime;
39
+ }
40
+ creditStatusState = { kind: "ready", runtime };
41
+ return runtime;
42
+ });
43
+ creditStatusState = { kind: "loading", operation };
44
+ void operation.catch(() => {
45
+ if (creditStatusState.kind === "loading" && creditStatusState.operation === operation) {
46
+ creditStatusState = { kind: "idle" };
47
+ }
48
+ });
49
+ return operation;
50
+ }
51
+
52
+ function schedulePendingCreditStatusRefresh(): void {
53
+ if (!pendingCreditStatusRefresh || creditStatusRefreshWork !== undefined) return;
54
+
55
+ // Jiti evaluates transformed modules synchronously once import starts. A
56
+ // macrotask lets Pi finish its awaited lifecycle dispatch before that work.
57
+ const scheduled = setImmediate(() => {
58
+ void loadCreditStatus()
59
+ .then((runtime) => {
60
+ if (creditStatusRefreshWork !== scheduled) return;
61
+ const refresh = pendingCreditStatusRefresh;
62
+ pendingCreditStatusRefresh = undefined;
63
+ creditStatusRefreshWork = undefined;
64
+ if (refresh) {
65
+ void runtime.refresh(refresh.ctx, refresh.model).catch((error: unknown) => {
66
+ if (creditStatusState.kind !== "disposed") {
67
+ notifier.warn(`Unable to refresh Hyper status: ${String(error)}`);
68
+ }
69
+ });
70
+ }
71
+ })
72
+ .catch((error: unknown) => {
73
+ if (creditStatusRefreshWork === scheduled && creditStatusState.kind !== "disposed") {
74
+ pendingCreditStatusRefresh = undefined;
75
+ notifier.warn(`Unable to load Hyper status support: ${String(error)}`);
76
+ }
77
+ })
78
+ .finally(() => {
79
+ if (creditStatusRefreshWork !== scheduled) return;
80
+ creditStatusRefreshWork = undefined;
81
+ schedulePendingCreditStatusRefresh();
82
+ });
83
+ });
84
+ creditStatusRefreshWork = scheduled;
85
+ }
86
+
87
+ function scheduleCreditStatusRefresh(ctx: ExtensionContext, model: ExtensionContext["model"]): void {
88
+ pendingCreditStatusRefresh = { ctx, model };
89
+ schedulePendingCreditStatusRefresh();
90
+ }
91
+
92
+ function deactivateCreditStatus(ctx: ExtensionContext, model: ExtensionContext["model"]): void {
93
+ pendingCreditStatusRefresh = undefined;
94
+ if (creditStatusRefreshWork !== undefined) {
95
+ clearImmediate(creditStatusRefreshWork);
96
+ creditStatusRefreshWork = undefined;
97
+ }
98
+ if (creditStatusState.kind === "ready") {
99
+ void creditStatusState.runtime.refresh(ctx, model);
100
+ }
101
+ ctx.ui.setStatus(PROVIDER_NAME, undefined);
102
+ }
103
+
13
104
  pi.on("session_start", (_event, ctx) => {
14
105
  notifier.activate(ctx);
106
+ if (!ctx.hasUI) return;
107
+ if (ctx.model?.provider !== PROVIDER_NAME) {
108
+ deactivateCreditStatus(ctx, ctx.model);
109
+ return;
110
+ }
111
+ scheduleCreditStatusRefresh(ctx, ctx.model);
15
112
  });
16
113
 
17
- try {
18
- migrateHyperSettings(notifier.warn);
19
- } catch (err) {
20
- notifier.warn(`Failed to migrate Hyper settings: ${String(err)}`);
21
- }
114
+ pi.registerProvider({
115
+ id: PROVIDER_NAME,
116
+ name: PROVIDER_DISPLAY_NAME,
117
+ baseUrl: HYPER_API_BASE_URL,
118
+ auth: {
119
+ apiKey: envApiKeyAuth("Hyper API key", ["HYPER_API_KEY"]),
120
+ oauth: lazyOAuth({
121
+ name: PROVIDER_DISPLAY_NAME,
122
+ load: async () => {
123
+ const { loginHyper, refreshHyperToken } = await import("./oauth.js");
124
+ return {
125
+ name: PROVIDER_DISPLAY_NAME,
126
+ login: loginHyper,
127
+ refresh: refreshHyperToken,
128
+ toAuth: async (credential) => ({ apiKey: credential.access }),
129
+ } satisfies OAuthAuth;
130
+ },
131
+ }),
132
+ },
133
+ getModels: () => hyperModels,
134
+ refreshModels: async ({ allowNetwork, credential, publish, signal, stored }) => {
135
+ const cleared = await publish({
136
+ update: () => {
137
+ hyperModels = [];
138
+ },
139
+ });
140
+ if (!cleared) return;
141
+ if (stored && !(await publish({ persist: null }))) return;
142
+ if (!allowNetwork || signal.aborted) return;
22
143
 
23
- pi.registerProvider(
24
- createProvider({
25
- id: PROVIDER_NAME,
26
- name: PROVIDER_DISPLAY_NAME,
27
- baseUrl: HYPER_API_BASE_URL,
28
- auth: {
29
- apiKey: envApiKeyAuth("Hyper API key", ["HYPER_API_KEY"]),
30
- oauth: {
31
- name: PROVIDER_DISPLAY_NAME,
32
- login: loginHyper,
33
- refresh: refreshHyperToken,
34
- toAuth: async (credential) => ({ apiKey: credential.access }),
144
+ const token = credential?.type === "oauth" ? credential.access : credential?.key;
145
+ const { fetchHyperModels } = await import("./models.js");
146
+ const refreshed = await fetchHyperModels({ signal, token });
147
+ if (signal.aborted) return;
148
+ await publish({
149
+ update: () => {
150
+ hyperModels = refreshed;
35
151
  },
36
- },
37
- models: [],
38
- fetchModels: ({ signal }) => fetchHyperModels(signal),
39
- api: openAICompletionsApi(),
40
- }),
41
- );
42
-
43
- registerCreditStatus(pi, notifier.warn);
152
+ });
153
+ },
154
+ stream: hyperApi.stream,
155
+ streamSimple: hyperApi.streamSimple,
156
+ });
157
+
158
+ pi.registerCommand("hyper-status", {
159
+ description: "Configure the Charm Hyper footer status",
160
+ handler: async (args, ctx) => {
161
+ try {
162
+ const runtime = await loadCreditStatus();
163
+ if (creditStatusState.kind === "disposed") return;
164
+ await runtime.handleCommand(args, ctx);
165
+ } catch (error) {
166
+ if (creditStatusState.kind === "disposed") return;
167
+ ctx.ui.notify(`Unable to load Hyper status support: ${String(error)}`, "warning");
168
+ }
169
+ },
170
+ });
171
+
172
+ pi.on("model_select", (event, ctx) => {
173
+ if (!ctx.hasUI) return;
174
+ if (event.model.provider !== PROVIDER_NAME) {
175
+ deactivateCreditStatus(ctx, event.model);
176
+ return;
177
+ }
178
+ scheduleCreditStatusRefresh(ctx, event.model);
179
+ });
180
+
181
+ pi.on("agent_settled", (_event, ctx) => {
182
+ if (creditStatusState.kind === "disposed" || !ctx.hasUI || ctx.model?.provider !== PROVIDER_NAME) return;
183
+ scheduleCreditStatusRefresh(ctx, ctx.model);
184
+ });
185
+
186
+ pi.on("session_shutdown", (_event, ctx) => {
187
+ pendingCreditStatusRefresh = undefined;
188
+ if (creditStatusRefreshWork !== undefined) clearImmediate(creditStatusRefreshWork);
189
+ creditStatusRefreshWork = undefined;
190
+ if (creditStatusState.kind === "ready") creditStatusState.runtime.dispose();
191
+ creditStatusState = { kind: "disposed" };
192
+ if (ctx.hasUI) ctx.ui.setStatus(PROVIDER_NAME, undefined);
193
+ });
44
194
  }
package/src/models.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { Model, ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai";
2
2
  import { type Static, Type } from "typebox";
3
+ import { Compile } from "typebox/compile";
3
4
  import { fetchJson } from "./http.js";
4
- import { HYPER_API_BASE_URL, HYPER_USER_AGENT, PROVIDER_NAME } from "./hyper.js";
5
+ import { HYPER_API_BASE_URL, HYPER_USER_AGENT, hyperJsonHeaders, PROVIDER_NAME } from "./hyper.js";
5
6
  import { parseSchema } from "./schema.js";
6
7
 
7
8
  const MODEL_FETCH_TIMEOUT_MS = 3_000;
@@ -52,6 +53,7 @@ const ProviderPayloadSchema = Type.Object(
52
53
  },
53
54
  { additionalProperties: true },
54
55
  );
56
+ const ProviderPayloadValidator = Compile(ProviderPayloadSchema);
55
57
 
56
58
  type ProviderModel = Static<typeof ProviderModelSchema>;
57
59
 
@@ -95,8 +97,9 @@ function toProviderModel(model: ProviderModel): Model<"openai-completions"> {
95
97
  function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
96
98
  if (levels.length === 0) return undefined;
97
99
  const availableLevels = new Set<string>(levels);
100
+ const disabledReasoningLevel = levels.find((level) => level === "off" || level === "none") ?? null;
98
101
  const result: ThinkingLevelMap = {
99
- off: availableLevels.has("off") ? "off" : null,
102
+ off: disabledReasoningLevel,
100
103
  };
101
104
  for (const level of PI_THINKING_LEVELS) {
102
105
  result[level] = availableLevels.has(level) ? level : null;
@@ -104,11 +107,18 @@ function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
104
107
  return result;
105
108
  }
106
109
 
107
- export async function fetchHyperModels(signal?: AbortSignal): Promise<Model<"openai-completions">[]> {
110
+ export async function fetchHyperModels({
111
+ signal,
112
+ token,
113
+ }: {
114
+ signal: AbortSignal;
115
+ token: string | undefined;
116
+ }): Promise<Model<"openai-completions">[]> {
108
117
  const payload = await fetchJson(`${HYPER_API_BASE_URL}/provider`, {
118
+ headers: token ? hyperJsonHeaders({ Authorization: `Bearer ${token}` }) : undefined,
109
119
  signal,
110
120
  timeoutMs: MODEL_FETCH_TIMEOUT_MS,
111
121
  });
112
- const provider = parseSchema(ProviderPayloadSchema, payload, "Hyper /provider response");
122
+ const provider = parseSchema(ProviderPayloadValidator, payload, "Hyper /provider response");
113
123
  return provider.models.map(toProviderModel);
114
124
  }
package/src/oauth.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  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
- import { Value } from "typebox/value";
5
- import { fetchJson, fetchJsonResponse, HttpResponseError } from "./http.js";
4
+ import { Compile } from "typebox/compile";
5
+ import { fetchJson, HttpResponseError } from "./http.js";
6
6
  import { HYPER_BASE_URL, hyperJsonHeaders } from "./hyper.js";
7
7
  import { parseSchema } from "./schema.js";
8
8
 
@@ -58,6 +58,10 @@ async function pollOAuthDeviceCodeFlow<T>(options: {
58
58
  );
59
59
 
60
60
  let slowDownResponses = 0;
61
+ const initialRemainingMs = deadline - Date.now();
62
+ if (initialRemainingMs > 0) {
63
+ await abortableSleep(Math.min(intervalMs, initialRemainingMs), options.signal, CANCEL_MESSAGE);
64
+ }
61
65
 
62
66
  while (Date.now() < deadline) {
63
67
  if (options.signal?.aborted) {
@@ -166,6 +170,14 @@ const RejectedRefreshTokenResponseSchema = Type.Object(
166
170
  },
167
171
  { additionalProperties: false },
168
172
  );
173
+ const DeviceAuthResponseValidator = Compile(DeviceAuthResponseSchema);
174
+ const DevicePollSuccessValidator = Compile(DevicePollSuccessSchema);
175
+ const DevicePollErrorValidator = Compile(DevicePollErrorSchema);
176
+ const DevicePollResponseValidator = Compile(DevicePollResponseSchema);
177
+ const TokenExchangeWithExpiresInValidator = Compile(TokenExchangeWithExpiresInSchema);
178
+ const TokenExchangeWithExpiresAtValidator = Compile(TokenExchangeWithExpiresAtSchema);
179
+ const TokenExchangeResponseValidator = Compile(TokenExchangeResponseSchema);
180
+ const RejectedRefreshTokenResponseValidator = Compile(RejectedRefreshTokenResponseSchema);
169
181
 
170
182
  type DeviceAuthResponse = Static<typeof DeviceAuthResponseSchema>;
171
183
  type DevicePollResponse = Static<typeof DevicePollSuccessSchema> | Static<typeof DevicePollErrorSchema>;
@@ -191,7 +203,7 @@ async function initiateDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthRespo
191
203
  signal,
192
204
  timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
193
205
  });
194
- return parseSchema(DeviceAuthResponseSchema, payload, "Hyper device auth response");
206
+ return parseSchema(DeviceAuthResponseValidator, payload, "Hyper device auth response");
195
207
  }
196
208
 
197
209
  function deviceName(): string {
@@ -205,19 +217,12 @@ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSign
205
217
  expiresInSeconds: deviceAuth.expires_in,
206
218
  signal,
207
219
  poll: async () => {
208
- const response = await fetchJsonResponse(
209
- `${HYPER_BASE_URL}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`,
210
- {
211
- headers: hyperJsonHeaders(),
212
- signal,
213
- timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
214
- allowHttpErrorPayload: true,
215
- },
216
- );
217
- const pollResponse = parseDevicePollResponse(
218
- response.payload,
219
- `Hyper device token response (HTTP ${response.status})`,
220
- );
220
+ const payload = await fetchJson(`${HYPER_BASE_URL}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`, {
221
+ headers: hyperJsonHeaders(),
222
+ signal,
223
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
224
+ });
225
+ const pollResponse = parseDevicePollResponse(payload);
221
226
 
222
227
  if ("refresh_token" in pollResponse) {
223
228
  return { status: "complete", value: pollResponse };
@@ -234,13 +239,9 @@ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSign
234
239
  }
235
240
 
236
241
  function parseDevicePollResponse(payload: unknown, source = "Hyper device token response"): DevicePollResponse {
237
- if (Value.Check(DevicePollSuccessSchema, payload)) {
238
- return Value.Parse(DevicePollSuccessSchema, payload);
239
- }
240
- if (Value.Check(DevicePollErrorSchema, payload)) {
241
- return Value.Parse(DevicePollErrorSchema, payload);
242
- }
243
- parseSchema(DevicePollResponseSchema, payload, source);
242
+ if (DevicePollSuccessValidator.Check(payload)) return payload;
243
+ if (DevicePollErrorValidator.Check(payload)) return payload;
244
+ parseSchema(DevicePollResponseValidator, payload, source);
244
245
  throw new Error("Hyper device token response is invalid");
245
246
  }
246
247
 
@@ -256,13 +257,9 @@ async function exchangeRefreshToken(refreshToken: string, signal?: AbortSignal):
256
257
  }
257
258
 
258
259
  function parseTokenExchangeResponse(payload: unknown): TokenExchangeResponse {
259
- if (Value.Check(TokenExchangeWithExpiresInSchema, payload)) {
260
- return Value.Parse(TokenExchangeWithExpiresInSchema, payload);
261
- }
262
- if (Value.Check(TokenExchangeWithExpiresAtSchema, payload)) {
263
- return Value.Parse(TokenExchangeWithExpiresAtSchema, payload);
264
- }
265
- parseSchema(TokenExchangeResponseSchema, payload, "Hyper token exchange response");
260
+ if (TokenExchangeWithExpiresInValidator.Check(payload)) return payload;
261
+ if (TokenExchangeWithExpiresAtValidator.Check(payload)) return payload;
262
+ parseSchema(TokenExchangeResponseValidator, payload, "Hyper token exchange response");
266
263
  throw new Error("Hyper token exchange response is invalid");
267
264
  }
268
265
 
@@ -328,7 +325,7 @@ function isRejectedRefreshTokenResponse(error: unknown): error is HttpResponseEr
328
325
  return (
329
326
  error instanceof HttpResponseError &&
330
327
  error.status === 401 &&
331
- error.matchesResponseJson(RejectedRefreshTokenResponseSchema)
328
+ error.matchesResponseJson(RejectedRefreshTokenResponseValidator)
332
329
  );
333
330
  }
334
331
 
package/src/schema.ts CHANGED
@@ -1,16 +1,15 @@
1
- import type { Static, TSchema } from "typebox";
2
- import { Value } from "typebox/value";
1
+ import type { Static, TProperties, TSchema } from "typebox";
2
+ import type { Validator } from "typebox/compile";
3
+ import { Errors } from "typebox/value";
3
4
 
4
- export function parseSchema<const Schema extends TSchema>(
5
- schema: Schema,
5
+ export function parseSchema<Context extends TProperties, const Schema extends TSchema>(
6
+ validator: Validator<Context, Schema>,
6
7
  payload: unknown,
7
8
  source: string,
8
- ): Static<Schema> {
9
- if (Value.Check(schema, payload)) {
10
- return Value.Parse(schema, payload);
11
- }
9
+ ): Static<Schema, Context> {
10
+ if (validator.Check(payload)) return payload;
12
11
 
13
- const details = [...Value.Errors(schema, payload)]
12
+ const details = Errors(validator.Context(), validator.Type(), payload)
14
13
  .slice(0, 3)
15
14
  .map((error) => `${formatErrorPath(source, error.instancePath)} ${error.message}`)
16
15
  .join("; ");
package/src/settings.ts CHANGED
@@ -2,7 +2,7 @@ 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
4
  import { type Static, Type } from "typebox";
5
- import { Value } from "typebox/value";
5
+ import { Compile } from "typebox/compile";
6
6
  import { hyperProviderDir } from "./hyper.js";
7
7
  import type { WarningSink } from "./notify.js";
8
8
 
@@ -13,6 +13,7 @@ const HyperStatusItemsSchema = Type.Object(
13
13
  },
14
14
  { additionalProperties: false },
15
15
  );
16
+ const HyperStatusItemsValidator = Compile(HyperStatusItemsSchema);
16
17
 
17
18
  export type HyperStatusItems = Required<Static<typeof HyperStatusItemsSchema>>;
18
19
 
@@ -113,14 +114,14 @@ function readLegacyHyperStatusItems(warn?: WarningSink): HyperStatusItems | unde
113
114
 
114
115
  function parseHyperStatusItems(value: unknown, source: string, warn?: WarningSink): HyperStatusItems | undefined {
115
116
  if (value === undefined) return undefined;
116
- if (!Value.Check(HyperStatusItemsSchema, value)) {
117
+ if (!HyperStatusItemsValidator.Check(value)) {
117
118
  warn?.(`Ignoring invalid ${source}`);
118
119
  return undefined;
119
120
  }
120
121
 
121
122
  return {
122
123
  ...DEFAULT_STATUS_ITEMS,
123
- ...Value.Parse(HyperStatusItemsSchema, value),
124
+ ...value,
124
125
  };
125
126
  }
126
127