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