@charmland/pi-hyper-provider 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/credits.ts +137 -78
- package/src/http.ts +45 -30
- package/src/index.ts +181 -31
- package/src/models.ts +14 -4
- package/src/oauth.ts +28 -31
- package/src/schema.ts +8 -9
- package/src/settings.ts +4 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@charmland/pi-hyper-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
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.
|
|
33
|
-
"@earendil-works/pi-coding-agent": "^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 {
|
|
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 {
|
|
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";
|
|
@@ -24,13 +26,24 @@ const CreditsPayloadSchema = Type.Object(
|
|
|
24
26
|
},
|
|
25
27
|
{ additionalProperties: false },
|
|
26
28
|
);
|
|
29
|
+
const CreditsPayloadValidator = Compile(CreditsPayloadSchema);
|
|
27
30
|
|
|
28
|
-
async function fetchCredits(apiKey: string): Promise<number> {
|
|
29
|
-
const payload = await fetchJson(`${HYPER_API_BASE_URL}/credits`, {
|
|
31
|
+
async function fetchCredits(apiKey: string, signal: AbortSignal): Promise<number> {
|
|
32
|
+
const payload = await httpClient.fetchJson(`${HYPER_API_BASE_URL}/credits`, {
|
|
30
33
|
headers: hyperJsonHeaders({ Authorization: `Bearer ${apiKey}` }),
|
|
34
|
+
signal,
|
|
31
35
|
timeoutMs: CREDITS_FETCH_TIMEOUT_MS,
|
|
32
36
|
});
|
|
33
|
-
return parseSchema(
|
|
37
|
+
return parseSchema(CreditsPayloadValidator, payload, "Hyper /credits response").balance;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isTransientCreditError(error: unknown): boolean {
|
|
41
|
+
return (
|
|
42
|
+
error instanceof httpClient.HttpNetworkError ||
|
|
43
|
+
error instanceof httpClient.HttpTimeoutError ||
|
|
44
|
+
(error instanceof httpClient.HttpResponseError &&
|
|
45
|
+
(error.status === 408 || error.status === 429 || (error.status >= 500 && error.status <= 599)))
|
|
46
|
+
);
|
|
34
47
|
}
|
|
35
48
|
|
|
36
49
|
function formatCredits(balance: number): string {
|
|
@@ -60,25 +73,51 @@ function storedTeamName(): string | undefined {
|
|
|
60
73
|
return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
|
|
61
74
|
}
|
|
62
75
|
|
|
63
|
-
export
|
|
76
|
+
export interface CreditStatusRuntime {
|
|
77
|
+
handleCommand(args: string, ctx: ExtensionCommandContext): Promise<void>;
|
|
78
|
+
refresh(ctx: ExtensionContext, selectedModel: ExtensionContext["model"]): Promise<void>;
|
|
79
|
+
dispose(): void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createCreditStatusRuntime(warn: WarningSink): CreditStatusRuntime {
|
|
83
|
+
try {
|
|
84
|
+
migrateHyperSettings(warn);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
warn(`Failed to migrate Hyper settings: ${String(error)}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
64
89
|
let invocationSequence = 0;
|
|
65
90
|
let committedInvocation = 0;
|
|
66
91
|
let credentialEpoch = 0;
|
|
67
92
|
let consecutiveFailures = 0;
|
|
68
|
-
let
|
|
93
|
+
let retryAtMs = 0;
|
|
69
94
|
let currentApiKey: string | undefined;
|
|
70
95
|
let cachedBalance: number | undefined;
|
|
71
|
-
let
|
|
96
|
+
let statusItemsCache: HyperStatusItems | undefined;
|
|
97
|
+
let inFlight:
|
|
98
|
+
| { apiKey: string; credentialEpoch: number; controller: AbortController; operation: Promise<void> }
|
|
99
|
+
| undefined;
|
|
100
|
+
let disposed = false;
|
|
72
101
|
type CredentialLease = { apiKey: string; credentialEpoch: number };
|
|
73
102
|
|
|
74
103
|
function clearCreditState(): void {
|
|
75
104
|
cachedBalance = undefined;
|
|
76
105
|
consecutiveFailures = 0;
|
|
77
|
-
|
|
106
|
+
retryAtMs = 0;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function invalidateCredential(): void {
|
|
110
|
+
credentialEpoch += 1;
|
|
111
|
+
inFlight?.controller.abort();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function getStatusItems(): HyperStatusItems {
|
|
115
|
+
if (statusItemsCache === undefined) statusItemsCache = readHyperStatusItems(warn);
|
|
116
|
+
return statusItemsCache;
|
|
78
117
|
}
|
|
79
118
|
|
|
80
119
|
function renderStatus(ctx: ExtensionContext): void {
|
|
81
|
-
const statusItems =
|
|
120
|
+
const statusItems = getStatusItems();
|
|
82
121
|
const teamName = storedTeamName();
|
|
83
122
|
if (!statusItems.hypercredits || cachedBalance === undefined) {
|
|
84
123
|
ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
|
|
@@ -91,35 +130,37 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
91
130
|
return lease.apiKey === currentApiKey && lease.credentialEpoch === credentialEpoch;
|
|
92
131
|
}
|
|
93
132
|
|
|
133
|
+
function canRender(invocation: number, forcedLease: CredentialLease | undefined): boolean {
|
|
134
|
+
return invocation === invocationSequence || (forcedLease !== undefined && ownsCredential(forcedLease));
|
|
135
|
+
}
|
|
136
|
+
|
|
94
137
|
function render(ctx: ExtensionContext, lease: CredentialLease): void {
|
|
95
138
|
if (!ownsCredential(lease)) return;
|
|
96
139
|
renderStatus(ctx);
|
|
97
140
|
}
|
|
98
141
|
|
|
99
|
-
async function fetchAndCache(
|
|
142
|
+
async function fetchAndCache(lease: CredentialLease, signal: AbortSignal): Promise<void> {
|
|
100
143
|
try {
|
|
101
|
-
const balance = await fetchCredits(apiKey);
|
|
102
|
-
if (
|
|
144
|
+
const balance = await fetchCredits(lease.apiKey, signal);
|
|
145
|
+
if (disposed || !ownsCredential(lease)) return;
|
|
103
146
|
cachedBalance = balance;
|
|
104
147
|
consecutiveFailures = 0;
|
|
105
|
-
|
|
148
|
+
retryAtMs = 0;
|
|
106
149
|
} catch (error) {
|
|
107
|
-
if (
|
|
108
|
-
|
|
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) {
|
|
150
|
+
if (disposed || !ownsCredential(lease)) throw error;
|
|
151
|
+
if (!isTransientCreditError(error)) {
|
|
114
152
|
clearCreditState();
|
|
115
153
|
throw error;
|
|
116
154
|
}
|
|
117
155
|
consecutiveFailures += 1;
|
|
118
|
-
const retryDelayMs =
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
156
|
+
const retryDelayMs =
|
|
157
|
+
error instanceof httpClient.HttpResponseError && error.retryAfterMs !== undefined
|
|
158
|
+
? error.retryAfterMs
|
|
159
|
+
: Math.min(
|
|
160
|
+
CREDITS_RETRY_DELAY_MS_INITIAL * 2 ** Math.min(consecutiveFailures - 1, CREDITS_RETRY_EXPONENT_MAX),
|
|
161
|
+
CREDITS_RETRY_DELAY_MS_MAX,
|
|
162
|
+
);
|
|
163
|
+
retryAtMs = Date.now() + retryDelayMs;
|
|
123
164
|
throw error;
|
|
124
165
|
}
|
|
125
166
|
}
|
|
@@ -131,8 +172,9 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
131
172
|
return;
|
|
132
173
|
}
|
|
133
174
|
|
|
134
|
-
const
|
|
135
|
-
const
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
const operation = fetchAndCache({ apiKey, credentialEpoch: expectedCredentialEpoch }, controller.signal);
|
|
177
|
+
const started = { apiKey, credentialEpoch: expectedCredentialEpoch, controller, operation };
|
|
136
178
|
inFlight = started;
|
|
137
179
|
try {
|
|
138
180
|
await operation;
|
|
@@ -143,11 +185,12 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
143
185
|
}
|
|
144
186
|
}
|
|
145
187
|
|
|
146
|
-
async function
|
|
188
|
+
async function refreshStatus(
|
|
147
189
|
ctx: ExtensionContext,
|
|
148
190
|
selectedModel: ExtensionContext["model"] = ctx.model,
|
|
149
191
|
isUserRequested = false,
|
|
150
192
|
): Promise<void> {
|
|
193
|
+
if (disposed) return;
|
|
151
194
|
const invocation = invocationSequence + 1;
|
|
152
195
|
invocationSequence = invocation;
|
|
153
196
|
const forcedLease: CredentialLease | undefined =
|
|
@@ -155,15 +198,15 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
155
198
|
let failureLease: CredentialLease | undefined;
|
|
156
199
|
if (!isHyperModel(selectedModel)) {
|
|
157
200
|
committedInvocation = invocation;
|
|
158
|
-
|
|
201
|
+
invalidateCredential();
|
|
159
202
|
ctx.ui.setStatus(PROVIDER_NAME, undefined);
|
|
160
203
|
return;
|
|
161
204
|
}
|
|
162
205
|
|
|
163
|
-
const statusItems =
|
|
206
|
+
const statusItems = getStatusItems();
|
|
164
207
|
if (!statusItems.hypercredits) {
|
|
165
208
|
committedInvocation = invocation;
|
|
166
|
-
|
|
209
|
+
invalidateCredential();
|
|
167
210
|
renderStatus(ctx);
|
|
168
211
|
return;
|
|
169
212
|
}
|
|
@@ -173,26 +216,27 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
173
216
|
renderStatus(ctx);
|
|
174
217
|
try {
|
|
175
218
|
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(selectedModel);
|
|
219
|
+
if (disposed) return;
|
|
176
220
|
const forcedLeaseStillValid =
|
|
177
221
|
forcedLease !== undefined && auth.ok && auth.apiKey === forcedLease.apiKey && ownsCredential(forcedLease);
|
|
178
222
|
if (invocation < committedInvocation && !forcedLeaseStillValid) return;
|
|
179
223
|
if (!auth.ok || !auth.apiKey) {
|
|
180
224
|
committedInvocation = invocation;
|
|
181
|
-
|
|
225
|
+
invalidateCredential();
|
|
182
226
|
currentApiKey = undefined;
|
|
183
227
|
clearCreditState();
|
|
184
228
|
renderStatus(ctx);
|
|
185
229
|
return;
|
|
186
230
|
}
|
|
187
231
|
if (invocation >= committedInvocation) committedInvocation = invocation;
|
|
188
|
-
if (!isUserRequested && currentApiKey === auth.apiKey && Date.now() <
|
|
232
|
+
if (!isUserRequested && currentApiKey === auth.apiKey && Date.now() < retryAtMs) {
|
|
189
233
|
// This auth result supersedes older general state, but a same-credential
|
|
190
234
|
// forced refresh retains its independent fetch lease.
|
|
191
235
|
return;
|
|
192
236
|
}
|
|
193
237
|
if (currentApiKey !== auth.apiKey) {
|
|
194
238
|
currentApiKey = auth.apiKey;
|
|
195
|
-
|
|
239
|
+
invalidateCredential();
|
|
196
240
|
clearCreditState();
|
|
197
241
|
// Never show the previous account while the replacement request runs.
|
|
198
242
|
renderStatus(ctx);
|
|
@@ -201,8 +245,12 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
201
245
|
const lease = { apiKey: auth.apiKey, credentialEpoch: expectedCredentialEpoch };
|
|
202
246
|
failureLease = lease;
|
|
203
247
|
await shareFetch(auth.apiKey, expectedCredentialEpoch);
|
|
248
|
+
if (disposed) return;
|
|
249
|
+
if (!canRender(invocation, forcedLease)) return;
|
|
204
250
|
render(ctx, lease);
|
|
205
251
|
} catch {
|
|
252
|
+
if (disposed) return;
|
|
253
|
+
if (!canRender(invocation, forcedLease)) return;
|
|
206
254
|
const failedOperationStillOwnsCredential = failureLease !== undefined && ownsCredential(failureLease);
|
|
207
255
|
if (failureLease !== undefined && failedOperationStillOwnsCredential) render(ctx, failureLease);
|
|
208
256
|
if (
|
|
@@ -214,48 +262,54 @@ export function registerCreditStatus(pi: ExtensionAPI, warn: WarningSink): void
|
|
|
214
262
|
}
|
|
215
263
|
}
|
|
216
264
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
pi.registerCommand("hyper-status", {
|
|
223
|
-
description: "Configure the Charm Hyper footer status",
|
|
224
|
-
handler: async (args, ctx) => {
|
|
265
|
+
return {
|
|
266
|
+
async handleCommand(args, ctx) {
|
|
267
|
+
if (disposed) return;
|
|
225
268
|
if (!args.trim()) {
|
|
226
269
|
if (!ctx.hasUI) {
|
|
227
|
-
ctx.ui.notify(statusItemsSummary(
|
|
270
|
+
ctx.ui.notify(statusItemsSummary(getStatusItems()), "info");
|
|
228
271
|
return;
|
|
229
272
|
}
|
|
230
273
|
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
274
|
+
const statusItems = await configureStatusItems(ctx, getStatusItems(), () => disposed);
|
|
275
|
+
if (disposed) return;
|
|
276
|
+
if (statusItems) {
|
|
277
|
+
writeHyperStatusItems(statusItems);
|
|
278
|
+
statusItemsCache = statusItems;
|
|
279
|
+
ctx.ui.notify(`Hyper status updated. ${statusItemsSummary(statusItems)}`, "info");
|
|
280
|
+
await refreshStatus(ctx, ctx.model, true);
|
|
281
|
+
}
|
|
233
282
|
return;
|
|
234
283
|
}
|
|
235
284
|
|
|
236
|
-
const result = updateStatusItems(args,
|
|
285
|
+
const result = updateStatusItems(args, getStatusItems());
|
|
286
|
+
if (disposed) return;
|
|
287
|
+
if (result.kind === "changed") {
|
|
288
|
+
writeHyperStatusItems(result.statusItems);
|
|
289
|
+
statusItemsCache = result.statusItems;
|
|
290
|
+
}
|
|
237
291
|
ctx.ui.notify(result.message, "info");
|
|
238
|
-
if (result.kind === "changed") await
|
|
292
|
+
if (result.kind === "changed") await refreshStatus(ctx, ctx.model, true);
|
|
239
293
|
},
|
|
240
|
-
});
|
|
241
294
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
pi.on("model_select", (event, ctx) => {
|
|
247
|
-
refreshInBackground(ctx, event.model);
|
|
248
|
-
});
|
|
295
|
+
refresh(ctx, selectedModel) {
|
|
296
|
+
return refreshStatus(ctx, selectedModel);
|
|
297
|
+
},
|
|
249
298
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
299
|
+
dispose() {
|
|
300
|
+
if (disposed) return;
|
|
301
|
+
disposed = true;
|
|
302
|
+
committedInvocation = ++invocationSequence;
|
|
303
|
+
invalidateCredential();
|
|
304
|
+
},
|
|
305
|
+
};
|
|
255
306
|
}
|
|
256
307
|
|
|
257
|
-
async function configureStatusItems(
|
|
258
|
-
|
|
308
|
+
async function configureStatusItems(
|
|
309
|
+
ctx: ExtensionContext,
|
|
310
|
+
initial: HyperStatusItems,
|
|
311
|
+
isDisposed: () => boolean,
|
|
312
|
+
): Promise<HyperStatusItems | undefined> {
|
|
259
313
|
let draft: HyperStatusItems = { ...initial };
|
|
260
314
|
|
|
261
315
|
for (;;) {
|
|
@@ -272,10 +326,11 @@ async function configureStatusItems(ctx: ExtensionContext, warn: (message: strin
|
|
|
272
326
|
saveOption,
|
|
273
327
|
cancelOption,
|
|
274
328
|
]);
|
|
329
|
+
if (isDisposed()) return undefined;
|
|
275
330
|
|
|
276
331
|
if (choice === undefined || choice === cancelOption) {
|
|
277
332
|
ctx.ui.notify("Hyper status settings unchanged", "info");
|
|
278
|
-
return
|
|
333
|
+
return undefined;
|
|
279
334
|
}
|
|
280
335
|
if (choice === teamOption) {
|
|
281
336
|
draft = { ...draft, teamName: !draft.teamName };
|
|
@@ -292,40 +347,42 @@ async function configureStatusItems(ctx: ExtensionContext, warn: (message: strin
|
|
|
292
347
|
if (choice === saveOption) {
|
|
293
348
|
if (sameStatusItems(initial, draft)) {
|
|
294
349
|
ctx.ui.notify(`Hyper status unchanged. ${statusItemsSummary(draft)}`, "info");
|
|
295
|
-
return
|
|
350
|
+
return undefined;
|
|
296
351
|
}
|
|
297
352
|
|
|
298
353
|
const ok = await ctx.ui.confirm("Save Hyper status settings?", statusItemsSummary(draft));
|
|
354
|
+
if (isDisposed()) return undefined;
|
|
299
355
|
if (!ok) {
|
|
300
356
|
ctx.ui.notify("Hyper status settings unchanged", "info");
|
|
301
|
-
return
|
|
357
|
+
return undefined;
|
|
302
358
|
}
|
|
303
359
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
return true;
|
|
360
|
+
if (isDisposed()) return undefined;
|
|
361
|
+
return draft;
|
|
307
362
|
}
|
|
308
363
|
}
|
|
309
364
|
}
|
|
310
365
|
|
|
311
366
|
type StatusItemsUpdate =
|
|
312
|
-
| { kind: "changed"; message: string }
|
|
367
|
+
| { kind: "changed"; message: string; statusItems: HyperStatusItems }
|
|
313
368
|
| { kind: "unchanged"; message: string }
|
|
314
369
|
| { kind: "invalid"; message: string };
|
|
315
370
|
|
|
316
|
-
function updateStatusItems(args: string,
|
|
371
|
+
function updateStatusItems(args: string, previous: HyperStatusItems): StatusItemsUpdate {
|
|
317
372
|
const tokens = args.trim().split(/\s+/).filter(Boolean);
|
|
318
373
|
if (tokens.length === 0) {
|
|
319
|
-
return { kind: "unchanged", message: statusItemsSummary(
|
|
374
|
+
return { kind: "unchanged", message: statusItemsSummary(previous) };
|
|
320
375
|
}
|
|
321
376
|
if (tokens.length === 1 && tokens[0] === "reset") {
|
|
322
377
|
const statusItems = defaultHyperStatusItems();
|
|
323
|
-
const previous = readHyperStatusItems(warn);
|
|
324
378
|
if (sameStatusItems(previous, statusItems)) {
|
|
325
379
|
return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
|
|
326
380
|
}
|
|
327
|
-
|
|
328
|
-
|
|
381
|
+
return {
|
|
382
|
+
kind: "changed",
|
|
383
|
+
message: `Hyper status reset. ${statusItemsSummary(statusItems)}`,
|
|
384
|
+
statusItems,
|
|
385
|
+
};
|
|
329
386
|
}
|
|
330
387
|
if (tokens.length !== 2) {
|
|
331
388
|
return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
|
|
@@ -336,7 +393,6 @@ function updateStatusItems(args: string, warn?: (message: string) => void): Stat
|
|
|
336
393
|
return { kind: "invalid", message: "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]" };
|
|
337
394
|
}
|
|
338
395
|
|
|
339
|
-
const previous = readHyperStatusItems(warn);
|
|
340
396
|
const statusItems = {
|
|
341
397
|
...previous,
|
|
342
398
|
[key]: rawValue === "true",
|
|
@@ -344,8 +400,11 @@ function updateStatusItems(args: string, warn?: (message: string) => void): Stat
|
|
|
344
400
|
if (sameStatusItems(previous, statusItems)) {
|
|
345
401
|
return { kind: "unchanged", message: `Hyper status unchanged. ${statusItemsSummary(statusItems)}` };
|
|
346
402
|
}
|
|
347
|
-
|
|
348
|
-
|
|
403
|
+
return {
|
|
404
|
+
kind: "changed",
|
|
405
|
+
message: `Hyper status updated. ${statusItemsSummary(statusItems)}`,
|
|
406
|
+
statusItems,
|
|
407
|
+
};
|
|
349
408
|
}
|
|
350
409
|
|
|
351
410
|
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 {
|
|
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
|
|
55
|
-
|
|
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
|
|
107
|
-
|
|
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
|
|
121
|
+
signal,
|
|
130
122
|
});
|
|
131
123
|
let body: string;
|
|
132
124
|
try {
|
|
133
125
|
body = await response.text();
|
|
134
126
|
} catch (error) {
|
|
135
|
-
if (
|
|
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 (
|
|
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 (
|
|
174
|
+
if (abortedBy(signal, timeoutSignal)) {
|
|
178
175
|
throw new HttpTimeoutError(`${url} timed out after ${options.timeoutMs}ms`, err);
|
|
179
176
|
}
|
|
180
|
-
if (
|
|
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 (!
|
|
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 {
|
|
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 {
|
|
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
|
-
|
|
9
|
-
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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:
|
|
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(
|
|
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(
|
|
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 {
|
|
5
|
-
import { fetchJson,
|
|
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(
|
|
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
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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 (
|
|
238
|
-
|
|
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 (
|
|
260
|
-
|
|
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(
|
|
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 {
|
|
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
|
-
|
|
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 (
|
|
10
|
-
return Value.Parse(schema, payload);
|
|
11
|
-
}
|
|
9
|
+
): Static<Schema, Context> {
|
|
10
|
+
if (validator.Check(payload)) return payload;
|
|
12
11
|
|
|
13
|
-
const details =
|
|
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 {
|
|
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 (!
|
|
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
|
-
...
|
|
124
|
+
...value,
|
|
124
125
|
};
|
|
125
126
|
}
|
|
126
127
|
|