@charmland/pi-hyper-provider 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Charmbracelet, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # @charmland/pi-hyper-provider
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@charmland/pi-hyper-provider.svg)](https://www.npmjs.com/package/@charmland/pi-hyper-provider)
4
+
5
+ A [Pi] extension that registers Charm's [Hyper] inference provider with Pi,
6
+ supporting API keys or OAuth, dynamic model discovery, and optionally showing
7
+ your team name and Hypercredit balance in the status line.
8
+
9
+ [Pi]: https://pi.dev
10
+ [Hyper]: https://hyper.charm.land
11
+
12
+ ```sh
13
+ # via NPM
14
+ pi install npm:@charmland/pi-hyper-provider
15
+
16
+ # via git
17
+ pi install git:github.com/charmbracelet/pi-hyper-provider
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ - To authenticate with OAuth, open `pi`, send `/login`, pick `Subscription`, and select the
23
+ `Charm Hyper` provider.
24
+ - To authenticate with an API key, set the `HYPER_API_KEY` environment variable
25
+ then open `pi`.
26
+
27
+ Pick a Hyper model by sending `/models` and filtering by either provider name
28
+ `hyper` or `model-name` like `glm-5.1`.
29
+
30
+ Model info is fetched at startup and cached locally; the cache is used as a
31
+ fallback when the `/models` endpoint is unreachable. By default, your remaining
32
+ Hypercredit balance is shown in the status line while a Hyper model is active.
33
+
34
+ Use `/hyper-status` to configure the status line interactively and toggle things
35
+ on/off or reset to the defaults. `teamName` defaults to `false` and
36
+ `hypercredits` defaults to `true`. You can also set values directly:
37
+
38
+ ```sh
39
+ /hyper-status teamName true
40
+ /hyper-status hypercredits false
41
+ /hyper-status reset
42
+ ```
43
+
44
+ ## Contributing
45
+
46
+ See the [contributing guide](https://github.com/charmbracelet/pi-hyper-provider?tab=contributing-ov-file#contributing).
47
+
48
+ ## Releasing
49
+
50
+ 1. `mise run release:bump
51
+ <patch|minor|major|prepatch|preminor|premajor|prerelease>` to increment the
52
+ version
53
+ 2. `mise run release:pack` to dry-run build the release tarball
54
+ 3. `mise run release:publish` to publish
55
+
56
+ ## Whatcha think?
57
+
58
+ We’d love to hear your thoughts on this project. Need help? We gotchu. You can
59
+ find us on:
60
+
61
+ - [Twitter](https://twitter.com/charmcli)
62
+ - [Slack][slack]
63
+ - [Discord][discord]
64
+ - [The Fediverse](https://mastodon.social/@charmcli)
65
+ - [Bluesky](https://bsky.app/profile/charm.land)
66
+
67
+ [slack]: https://charm.land/slack
68
+ [discord]: https://charm.land/discord
69
+
70
+ ## License
71
+
72
+ [MIT](https://github.com/charmbracelet/pi-hyper-provider/raw/main/LICENSE)
73
+
74
+ ---
75
+
76
+ Part of [Charm](https://charm.land).
77
+
78
+ <a href="https://charm.land/"><img alt="The Charm logo" width="400" src="https://stuff.charm.sh/charm-banner-softy.jpg" /></a>
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@charmland/pi-hyper-provider",
3
+ "version": "0.1.0",
4
+ "description": "Pi extension for Charm's Hyper inference provider",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "pi-package"
8
+ ],
9
+ "files": [
10
+ "src",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "pi": {
15
+ "extensions": [
16
+ "./src/index.ts"
17
+ ]
18
+ },
19
+ "scripts": {
20
+ "fmt": "biome format --write .",
21
+ "lint": "biome lint .",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "peerDependencies": {
25
+ "@earendil-works/pi-ai": "*",
26
+ "@earendil-works/pi-coding-agent": "*",
27
+ "typebox": "*"
28
+ },
29
+ "dependencies": {},
30
+ "devDependencies": {
31
+ "@biomejs/biome": "^2.4.16",
32
+ "@earendil-works/pi-ai": "^0.80.1",
33
+ "@earendil-works/pi-coding-agent": "^0.80.1",
34
+ "typebox": "^1.1.38",
35
+ "typescript": "^6.0.3"
36
+ },
37
+ "type": "module",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "https://github.com/charmbracelet/pi-hyper-provider"
41
+ }
42
+ }
package/src/credits.ts ADDED
@@ -0,0 +1,222 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { PROVIDER_NAME, hyperApiBaseUrl, hyperJsonHeaders } from "./hyper.js";
4
+ import { fetchJson } from "./http.js";
5
+ import { parseSchema } from "./schema.js";
6
+ import {
7
+ defaultHyperStatusItems,
8
+ type HyperStatusItems,
9
+ readHyperStatusItems,
10
+ writeHyperStatusItems,
11
+ } from "./settings.js";
12
+
13
+ const HYPER_GEM = "\x1b[38;2;255;96;255m◆\x1b[39m";
14
+ const CREDITS_FETCH_TIMEOUT_MS = 10_000;
15
+
16
+ const CreditsPayloadSchema = Type.Object(
17
+ {
18
+ balance: Type.Number(),
19
+ },
20
+ { additionalProperties: false },
21
+ );
22
+
23
+ async function fetchCredits(apiKey: string): Promise<number> {
24
+ const payload = await fetchJson(`${hyperApiBaseUrl()}/credits`, {
25
+ headers: hyperJsonHeaders({ Authorization: `Bearer ${apiKey}` }),
26
+ timeoutMs: CREDITS_FETCH_TIMEOUT_MS,
27
+ });
28
+ return parseSchema(CreditsPayloadSchema, payload, "Hyper /credits response").balance;
29
+ }
30
+
31
+ function formatCredits(balance: number): string {
32
+ if (Number.isInteger(balance)) return balance.toLocaleString("en-US");
33
+ return balance.toLocaleString("en-US", { maximumFractionDigits: 2 });
34
+ }
35
+
36
+ function isHyperModel(model: ExtensionContext["model"]): model is NonNullable<ExtensionContext["model"]> {
37
+ return model?.provider === PROVIDER_NAME;
38
+ }
39
+
40
+ function statusText(balance: number, statusItems: HyperStatusItems, teamName: string | undefined): string {
41
+ const credits = `${HYPER_GEM} ${formatCredits(balance)} hc`;
42
+ if (statusItems.teamName && teamName) return `${teamName}: ${credits}`;
43
+ return credits;
44
+ }
45
+
46
+ function teamNameStatusText(statusItems: HyperStatusItems, teamName: string | undefined): string | undefined {
47
+ if (!statusItems.teamName || !teamName) return undefined;
48
+ return `${HYPER_GEM} ${teamName}`;
49
+ }
50
+
51
+ function storedTeamName(ctx: ExtensionContext): string | undefined {
52
+ const credential = ctx.modelRegistry.authStorage.get(PROVIDER_NAME);
53
+ if (credential?.type !== "oauth") return undefined;
54
+ const teamName = credential.teamName;
55
+ return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
56
+ }
57
+
58
+ export function registerCreditStatus(pi: ExtensionAPI): void {
59
+ let refreshGeneration = 0;
60
+
61
+ async function refresh(ctx: ExtensionContext, selectedModel: ExtensionContext["model"] = ctx.model): Promise<void> {
62
+ const generation = refreshGeneration + 1;
63
+ refreshGeneration = generation;
64
+
65
+ if (!isHyperModel(selectedModel)) {
66
+ ctx.ui.setStatus(PROVIDER_NAME, undefined);
67
+ return;
68
+ }
69
+
70
+ const statusItems = readHyperStatusItems();
71
+ const teamName = storedTeamName(ctx);
72
+ if (!statusItems.hypercredits) {
73
+ ctx.ui.setStatus(PROVIDER_NAME, teamNameStatusText(statusItems, teamName));
74
+ return;
75
+ }
76
+
77
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(selectedModel);
78
+ if (!auth.ok || !auth.apiKey) {
79
+ ctx.ui.setStatus(PROVIDER_NAME, undefined);
80
+ return;
81
+ }
82
+
83
+ try {
84
+ const balance = await fetchCredits(auth.apiKey);
85
+ if (generation === refreshGeneration) {
86
+ ctx.ui.setStatus(PROVIDER_NAME, statusText(balance, statusItems, teamName));
87
+ }
88
+ } catch (err) {
89
+ console.error(`Failed to fetch Hyper /credits: ${String(err)}`);
90
+ if (generation === refreshGeneration) {
91
+ ctx.ui.setStatus(PROVIDER_NAME, undefined);
92
+ }
93
+ }
94
+ }
95
+
96
+ pi.registerCommand("hyper-status", {
97
+ description: "Configure the Charm Hyper footer status",
98
+ handler: async (args, ctx) => {
99
+ if (!args.trim()) {
100
+ if (!ctx.hasUI) {
101
+ ctx.ui.notify(statusItemsSummary(readHyperStatusItems()), "info");
102
+ return;
103
+ }
104
+
105
+ const changed = await configureStatusItems(ctx);
106
+ if (changed) await refresh(ctx);
107
+ return;
108
+ }
109
+
110
+ const message = updateStatusItems(args);
111
+ ctx.ui.notify(message, "info");
112
+ await refresh(ctx);
113
+ },
114
+ });
115
+
116
+ pi.on("session_start", async (_event, ctx) => {
117
+ await refresh(ctx);
118
+ });
119
+
120
+ pi.on("model_select", async (event, ctx) => {
121
+ await refresh(ctx, event.model);
122
+ });
123
+
124
+ pi.on("message_end", async (event, ctx) => {
125
+ if (event.message.role === "assistant" && isHyperModel(ctx.model)) {
126
+ await refresh(ctx);
127
+ }
128
+ });
129
+ }
130
+
131
+ async function configureStatusItems(ctx: ExtensionContext): Promise<boolean> {
132
+ const initial = readHyperStatusItems();
133
+ let draft: HyperStatusItems = { ...initial };
134
+
135
+ for (;;) {
136
+ const teamOption = `Team name: ${onOff(draft.teamName)}`;
137
+ const creditsOption = `Hypercredit balance: ${onOff(draft.hypercredits)}`;
138
+ const resetOption = "Reset to defaults";
139
+ const saveOption = "Save changes";
140
+ const cancelOption = "Cancel";
141
+
142
+ const choice = await ctx.ui.select("Hyper status settings", [
143
+ teamOption,
144
+ creditsOption,
145
+ resetOption,
146
+ saveOption,
147
+ cancelOption,
148
+ ]);
149
+
150
+ if (choice === undefined || choice === cancelOption) {
151
+ ctx.ui.notify("Hyper status settings unchanged", "info");
152
+ return false;
153
+ }
154
+ if (choice === teamOption) {
155
+ draft = { ...draft, teamName: !draft.teamName };
156
+ continue;
157
+ }
158
+ if (choice === creditsOption) {
159
+ draft = { ...draft, hypercredits: !draft.hypercredits };
160
+ continue;
161
+ }
162
+ if (choice === resetOption) {
163
+ draft = defaultHyperStatusItems();
164
+ continue;
165
+ }
166
+ if (choice === saveOption) {
167
+ if (sameStatusItems(initial, draft)) {
168
+ ctx.ui.notify(`Hyper status unchanged. ${statusItemsSummary(draft)}`, "info");
169
+ return false;
170
+ }
171
+
172
+ const ok = await ctx.ui.confirm("Save Hyper status settings?", statusItemsSummary(draft));
173
+ if (!ok) {
174
+ ctx.ui.notify("Hyper status settings unchanged", "info");
175
+ return false;
176
+ }
177
+
178
+ writeHyperStatusItems(draft);
179
+ ctx.ui.notify(`Hyper status updated. ${statusItemsSummary(draft)}`, "info");
180
+ return true;
181
+ }
182
+ }
183
+ }
184
+
185
+ function updateStatusItems(args: string): string {
186
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
187
+ if (tokens.length === 0) {
188
+ return statusItemsSummary(readHyperStatusItems());
189
+ }
190
+ if (tokens.length === 1 && tokens[0] === "reset") {
191
+ const statusItems = defaultHyperStatusItems();
192
+ writeHyperStatusItems(statusItems);
193
+ return `Hyper status reset. ${statusItemsSummary(statusItems)}`;
194
+ }
195
+ if (tokens.length !== 2) {
196
+ return "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]";
197
+ }
198
+
199
+ const [key, rawValue] = tokens;
200
+ if ((key !== "teamName" && key !== "hypercredits") || (rawValue !== "true" && rawValue !== "false")) {
201
+ return "Usage: /hyper-status [teamName true|false | hypercredits true|false | reset]";
202
+ }
203
+
204
+ const statusItems = {
205
+ ...readHyperStatusItems(),
206
+ [key]: rawValue === "true",
207
+ };
208
+ writeHyperStatusItems(statusItems);
209
+ return `Hyper status updated. ${statusItemsSummary(statusItems)}`;
210
+ }
211
+
212
+ function onOff(value: boolean): "on" | "off" {
213
+ return value ? "on" : "off";
214
+ }
215
+
216
+ function sameStatusItems(a: HyperStatusItems, b: HyperStatusItems): boolean {
217
+ return a.teamName === b.teamName && a.hypercredits === b.hypercredits;
218
+ }
219
+
220
+ function statusItemsSummary(statusItems: HyperStatusItems): string {
221
+ return `teamName=${statusItems.teamName}, hypercredits=${statusItems.hypercredits}`;
222
+ }
package/src/http.ts ADDED
@@ -0,0 +1,36 @@
1
+ export interface FetchJsonOptions {
2
+ method?: RequestInit["method"];
3
+ headers?: RequestInit["headers"];
4
+ body?: RequestInit["body"];
5
+ signal?: AbortSignal;
6
+ timeoutMs: number;
7
+ allowHttpErrorPayload?: boolean;
8
+ }
9
+
10
+ export async function fetchJson(url: string, options: FetchJsonOptions): Promise<unknown> {
11
+ const controller = new AbortController();
12
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
13
+ const abortFromCaller = () => controller.abort();
14
+ if (options.signal?.aborted) {
15
+ controller.abort();
16
+ } else {
17
+ options.signal?.addEventListener("abort", abortFromCaller, { once: true });
18
+ }
19
+
20
+ try {
21
+ const response = await fetch(url, {
22
+ method: options.method,
23
+ headers: options.headers,
24
+ body: options.body,
25
+ signal: controller.signal,
26
+ });
27
+ if (!response.ok && !options.allowHttpErrorPayload) {
28
+ const body = await response.text();
29
+ throw new Error(`${url} returned ${response.status}: ${body}`);
30
+ }
31
+ return response.json();
32
+ } finally {
33
+ clearTimeout(timeout);
34
+ options.signal?.removeEventListener("abort", abortFromCaller);
35
+ }
36
+ }
package/src/hyper.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { createRequire } from "node:module";
2
+ import * as path from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const packageJson = require("../package.json") as {
7
+ name: string;
8
+ version: string;
9
+ };
10
+ const packageName = packageJson.name.split("/").at(-1) ?? "pi-hyper-provider";
11
+
12
+ export const PROVIDER_NAME = "hyper";
13
+ export const PROVIDER_DISPLAY_NAME = "Charm Hyper";
14
+ export const DEFAULT_HYPER_URL = "https://hyper.charm.land";
15
+ export const HYPER_API_KEY = "$HYPER_API_KEY";
16
+ export const HYPER_USER_AGENT = `${packageName}/${packageJson.version}`;
17
+
18
+ export function hyperBaseUrl(): string {
19
+ const raw = process.env.HYPER_URL?.trim() || DEFAULT_HYPER_URL;
20
+ return raw.replace(/\/+$/, "");
21
+ }
22
+
23
+ export function hyperApiBaseUrl(): string {
24
+ return `${hyperBaseUrl()}/v1`;
25
+ }
26
+
27
+ export function hyperExtensionDir(): string {
28
+ return path.join(getAgentDir(), "extensions", "hyper-provider");
29
+ }
30
+
31
+ export function hyperJsonHeaders(headers: Record<string, string> = {}): Record<string, string> {
32
+ return {
33
+ "Content-Type": "application/json",
34
+ "User-Agent": HYPER_USER_AGENT,
35
+ ...headers,
36
+ };
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { registerCreditStatus } from "./credits.js";
3
+ import { HYPER_API_KEY, PROVIDER_DISPLAY_NAME, PROVIDER_NAME, hyperApiBaseUrl } from "./hyper.js";
4
+ import { loadModels } from "./models.js";
5
+ import { loginHyper, refreshHyperToken } from "./oauth.js";
6
+
7
+ export default async function (pi: ExtensionAPI) {
8
+ const models = await loadModels();
9
+
10
+ pi.registerProvider(PROVIDER_NAME, {
11
+ name: PROVIDER_DISPLAY_NAME,
12
+ baseUrl: hyperApiBaseUrl(),
13
+ apiKey: HYPER_API_KEY,
14
+ api: "openai-completions",
15
+ models,
16
+ oauth: {
17
+ name: PROVIDER_DISPLAY_NAME,
18
+ login: loginHyper,
19
+ refreshToken: refreshHyperToken,
20
+ getApiKey: (credentials) => credentials.access,
21
+ },
22
+ });
23
+
24
+ registerCreditStatus(pi);
25
+ }
package/src/models.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
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";
5
+ import { Type, type Static } from "typebox";
6
+ import { hyperApiBaseUrl, hyperExtensionDir } from "./hyper.js";
7
+ import { fetchJson } from "./http.js";
8
+ import { parseSchema } from "./schema.js";
9
+
10
+ const MODEL_FETCH_TIMEOUT_MS = 10_000;
11
+
12
+ const PI_THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const satisfies readonly ThinkingLevel[];
13
+
14
+ const HyperModelBaseFields = {
15
+ id: Type.String({ minLength: 1 }),
16
+ object: Type.Literal("model"),
17
+ created: Type.Integer({ minimum: 0 }),
18
+ owned_by: Type.String({ minLength: 1 }),
19
+ display_name: Type.String({ minLength: 1 }),
20
+ supports_reasoning: Type.Boolean(),
21
+ supports_attachments: Type.Boolean(),
22
+ context_window: Type.Integer({ minimum: 1 }),
23
+ max_output_tokens: Type.Integer({ minimum: 1 }),
24
+ };
25
+
26
+ const HyperModelSchema = Type.Union([
27
+ Type.Object(
28
+ {
29
+ ...HyperModelBaseFields,
30
+ supports_reasoning_effort: Type.Literal(true),
31
+ reasoning_effort_levels: Type.Array(Type.String({ minLength: 1 }), {
32
+ minItems: 1,
33
+ }),
34
+ default_reasoning_effort: Type.String({ minLength: 1 }),
35
+ },
36
+ { additionalProperties: false },
37
+ ),
38
+ Type.Object(
39
+ {
40
+ ...HyperModelBaseFields,
41
+ supports_reasoning_effort: Type.Literal(false),
42
+ },
43
+ { additionalProperties: false },
44
+ ),
45
+ ]);
46
+
47
+ const ModelPayloadSchema = Type.Object(
48
+ {
49
+ object: Type.Literal("list"),
50
+ data: Type.Array(HyperModelSchema, { minItems: 1 }),
51
+ },
52
+ { additionalProperties: false },
53
+ );
54
+
55
+ type HyperModel = Static<typeof HyperModelSchema>;
56
+
57
+ function modelCachePath(): string {
58
+ return path.join(hyperExtensionDir(), "models.json");
59
+ }
60
+
61
+ function toProviderModel(model: HyperModel): ProviderModelConfig {
62
+ const input: ProviderModelConfig["input"] = model.supports_attachments ? ["text", "image"] : ["text"];
63
+ const thinkingLevelMap = model.supports_reasoning_effort
64
+ ? buildThinkingLevelMap(model.reasoning_effort_levels)
65
+ : undefined;
66
+
67
+ return {
68
+ id: model.id,
69
+ name: model.display_name,
70
+ reasoning: model.supports_reasoning,
71
+ thinkingLevelMap,
72
+ input,
73
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
74
+ contextWindow: model.context_window,
75
+ maxTokens: model.max_output_tokens,
76
+ compat: {
77
+ supportsStore: false,
78
+ supportsReasoningEffort: model.supports_reasoning_effort,
79
+ maxTokensField: "max_tokens",
80
+ },
81
+ };
82
+ }
83
+
84
+ function buildThinkingLevelMap(levels: string[]): ThinkingLevelMap | undefined {
85
+ if (levels.length === 0) return undefined;
86
+ const availableLevels = new Set<string>(levels);
87
+ const result: ThinkingLevelMap = {
88
+ off: availableLevels.has("off") ? "off" : null,
89
+ };
90
+ for (const level of PI_THINKING_LEVELS) {
91
+ result[level] = availableLevels.has(level) ? level : null;
92
+ }
93
+ return result;
94
+ }
95
+
96
+ async function fetchModelPayload(): Promise<unknown> {
97
+ return fetchJson(`${hyperApiBaseUrl()}/models`, {
98
+ timeoutMs: MODEL_FETCH_TIMEOUT_MS,
99
+ });
100
+ }
101
+
102
+ function readCachedModelPayload(): unknown | undefined {
103
+ const cachePath = modelCachePath();
104
+ if (!existsSync(cachePath)) return undefined;
105
+ try {
106
+ return JSON.parse(readFileSync(cachePath, "utf-8"));
107
+ } catch (err) {
108
+ console.error(`Failed to read Hyper model cache at ${cachePath}: ${String(err)}`);
109
+ return undefined;
110
+ }
111
+ }
112
+
113
+ function writeCachedModelPayload(payload: unknown): void {
114
+ try {
115
+ mkdirSync(hyperExtensionDir(), { recursive: true });
116
+ writeFileSync(modelCachePath(), `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
117
+ } catch (err) {
118
+ console.error(`Failed to write Hyper model cache: ${String(err)}`);
119
+ }
120
+ }
121
+
122
+ export async function loadModels(): Promise<ProviderModelConfig[]> {
123
+ try {
124
+ const payload = await fetchModelPayload();
125
+ const models = parseSchema(ModelPayloadSchema, payload, "Hyper /models response").data.map(toProviderModel);
126
+ writeCachedModelPayload(payload);
127
+ return models;
128
+ } catch (err) {
129
+ const cachedPayload = readCachedModelPayload();
130
+ if (cachedPayload !== undefined) {
131
+ console.error(`Failed to fetch Hyper /models, using cached model list: ${String(err)}`);
132
+ return parseSchema(ModelPayloadSchema, cachedPayload, "Hyper model cache").data.map(toProviderModel);
133
+ }
134
+ throw err;
135
+ }
136
+ }
package/src/oauth.ts ADDED
@@ -0,0 +1,217 @@
1
+ import { hostname } from "node:os";
2
+ import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
3
+ import { pollOAuthDeviceCodeFlow } from "@earendil-works/pi-ai/oauth";
4
+ import { Type, type Static } from "typebox";
5
+ import { Value } from "typebox/value";
6
+ import { hyperBaseUrl, hyperJsonHeaders } from "./hyper.js";
7
+ import { fetchJson } from "./http.js";
8
+ import { parseSchema } from "./schema.js";
9
+
10
+ const DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;
11
+ const TOKEN_EXPIRY_BUFFER_MS = 30_000;
12
+ const OAUTH_FETCH_TIMEOUT_MS = 30_000;
13
+
14
+ const DeviceAuthResponseSchema = Type.Object(
15
+ {
16
+ device_code: Type.String({ minLength: 1 }),
17
+ expires_in: Type.Integer({ minimum: 1 }),
18
+ user_code: Type.String({ minLength: 1 }),
19
+ verification_url: Type.String({ minLength: 1 }),
20
+ interval: Type.Optional(Type.Integer({ minimum: 1 })),
21
+ },
22
+ { additionalProperties: false },
23
+ );
24
+
25
+ const DevicePollSuccessSchema = Type.Object(
26
+ {
27
+ refresh_token: Type.String({ minLength: 1 }),
28
+ team_id: Type.String({ minLength: 1 }),
29
+ team_name: Type.String({ minLength: 1 }),
30
+ user_id: Type.String({ minLength: 1 }),
31
+ },
32
+ { additionalProperties: false },
33
+ );
34
+
35
+ const DevicePollErrorCodeSchema = Type.Union([
36
+ Type.Literal("authorization_pending"),
37
+ Type.Literal("slow_down"),
38
+ Type.Literal("access_denied"),
39
+ Type.Literal("expired_token"),
40
+ Type.Literal("invalid_request"),
41
+ Type.Literal("invalid_grant"),
42
+ ]);
43
+
44
+ const DevicePollErrorSchema = Type.Object(
45
+ {
46
+ error: DevicePollErrorCodeSchema,
47
+ error_description: Type.Optional(Type.String({ minLength: 1 })),
48
+ },
49
+ { additionalProperties: false },
50
+ );
51
+
52
+ const DevicePollResponseSchema = Type.Union([DevicePollSuccessSchema, DevicePollErrorSchema]);
53
+
54
+ const TokenExchangeWithExpiresInSchema = Type.Object(
55
+ {
56
+ access_token: Type.String({ minLength: 1 }),
57
+ token_type: Type.String({ minLength: 1 }),
58
+ refresh_token: Type.String({ minLength: 1 }),
59
+ expiry: Type.String({ minLength: 1 }),
60
+ expires_in: Type.Integer({ minimum: 1 }),
61
+ },
62
+ { additionalProperties: false },
63
+ );
64
+
65
+ const TokenExchangeWithExpiresAtSchema = Type.Object(
66
+ {
67
+ access_token: Type.String({ minLength: 1 }),
68
+ token_type: Type.String({ minLength: 1 }),
69
+ refresh_token: Type.String({ minLength: 1 }),
70
+ expiry: Type.String({ minLength: 1 }),
71
+ expires_at: Type.Integer({ minimum: 1 }),
72
+ },
73
+ { additionalProperties: false },
74
+ );
75
+
76
+ const TokenExchangeResponseSchema = Type.Union([TokenExchangeWithExpiresInSchema, TokenExchangeWithExpiresAtSchema]);
77
+
78
+ type DeviceAuthResponse = Static<typeof DeviceAuthResponseSchema>;
79
+ type DevicePollResponse = Static<typeof DevicePollSuccessSchema> | Static<typeof DevicePollErrorSchema>;
80
+ type DevicePollSuccess = Static<typeof DevicePollSuccessSchema>;
81
+ type TokenExchangeResponse =
82
+ | Static<typeof TokenExchangeWithExpiresInSchema>
83
+ | Static<typeof TokenExchangeWithExpiresAtSchema>;
84
+
85
+ type HyperOAuthCredentials = OAuthCredentials & {
86
+ teamName?: string;
87
+ };
88
+
89
+ async function initiateDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthResponse> {
90
+ const payload = await fetchJson(`${hyperBaseUrl()}/device/auth`, {
91
+ method: "POST",
92
+ headers: hyperJsonHeaders(),
93
+ body: JSON.stringify({ device_name: deviceName() }),
94
+ signal,
95
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
96
+ });
97
+ return parseSchema(DeviceAuthResponseSchema, payload, "Hyper device auth response");
98
+ }
99
+
100
+ function deviceName(): string {
101
+ const host = hostname();
102
+ return host ? `Pi (${host})` : "Pi";
103
+ }
104
+
105
+ async function pollDeviceAuth(deviceAuth: DeviceAuthResponse, signal?: AbortSignal): Promise<DevicePollSuccess> {
106
+ return pollOAuthDeviceCodeFlow<DevicePollSuccess>({
107
+ intervalSeconds: deviceAuth.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_SECONDS,
108
+ expiresInSeconds: deviceAuth.expires_in,
109
+ signal,
110
+ poll: async () => {
111
+ const payload = await fetchJson(`${hyperBaseUrl()}/device/auth/${encodeURIComponent(deviceAuth.device_code)}`, {
112
+ headers: hyperJsonHeaders(),
113
+ signal,
114
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
115
+ allowHttpErrorPayload: true,
116
+ });
117
+ const response = parseDevicePollResponse(payload);
118
+
119
+ if ("refresh_token" in response) {
120
+ return { status: "complete", value: response };
121
+ }
122
+ if (response.error === "authorization_pending") return { status: "pending" };
123
+ if (response.error === "slow_down") return { status: "slow_down" };
124
+
125
+ return {
126
+ status: "failed",
127
+ message: `Hyper device authorization failed: ${response.error_description ?? response.error}`,
128
+ };
129
+ },
130
+ });
131
+ }
132
+
133
+ function parseDevicePollResponse(payload: unknown): DevicePollResponse {
134
+ if (Value.Check(DevicePollSuccessSchema, payload)) {
135
+ return Value.Parse(DevicePollSuccessSchema, payload);
136
+ }
137
+ if (Value.Check(DevicePollErrorSchema, payload)) {
138
+ return Value.Parse(DevicePollErrorSchema, payload);
139
+ }
140
+ parseSchema(DevicePollResponseSchema, payload, "Hyper device token response");
141
+ throw new Error("Hyper device token response is invalid");
142
+ }
143
+
144
+ async function exchangeRefreshToken(refreshToken: string, signal?: AbortSignal): Promise<TokenExchangeResponse> {
145
+ const payload = await fetchJson(`${hyperBaseUrl()}/token/exchange`, {
146
+ method: "POST",
147
+ headers: hyperJsonHeaders(),
148
+ body: JSON.stringify({ refresh_token: refreshToken }),
149
+ signal,
150
+ timeoutMs: OAUTH_FETCH_TIMEOUT_MS,
151
+ });
152
+ return parseTokenExchangeResponse(payload);
153
+ }
154
+
155
+ function parseTokenExchangeResponse(payload: unknown): TokenExchangeResponse {
156
+ if (Value.Check(TokenExchangeWithExpiresInSchema, payload)) {
157
+ return Value.Parse(TokenExchangeWithExpiresInSchema, payload);
158
+ }
159
+ if (Value.Check(TokenExchangeWithExpiresAtSchema, payload)) {
160
+ return Value.Parse(TokenExchangeWithExpiresAtSchema, payload);
161
+ }
162
+ parseSchema(TokenExchangeResponseSchema, payload, "Hyper token exchange response");
163
+ throw new Error("Hyper token exchange response is invalid");
164
+ }
165
+
166
+ function tokenToCredentials(
167
+ token: TokenExchangeResponse,
168
+ fallbackRefreshToken: string,
169
+ metadata?: Pick<HyperOAuthCredentials, "teamName">,
170
+ ): OAuthCredentials {
171
+ const expires = tokenExpiresAtMs(token);
172
+ return {
173
+ refresh: token.refresh_token || fallbackRefreshToken,
174
+ access: token.access_token,
175
+ expires,
176
+ ...metadata,
177
+ };
178
+ }
179
+
180
+ function tokenExpiresAtMs(token: TokenExchangeResponse): number {
181
+ const now = Date.now();
182
+ const expiresAt = "expires_in" in token ? now + token.expires_in * 1000 : token.expires_at * 1000;
183
+ if (expiresAt <= now) {
184
+ throw new Error("Hyper token exchange response contains an expired token expiry");
185
+ }
186
+
187
+ const bufferMs = Math.min(TOKEN_EXPIRY_BUFFER_MS, Math.floor((expiresAt - now) / 2));
188
+ return expiresAt - bufferMs;
189
+ }
190
+
191
+ export async function loginHyper(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
192
+ const deviceAuth = await initiateDeviceAuth(callbacks.signal);
193
+ callbacks.onDeviceCode({
194
+ userCode: deviceAuth.user_code,
195
+ verificationUri: deviceAuth.verification_url,
196
+ intervalSeconds: deviceAuth.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_SECONDS,
197
+ expiresInSeconds: deviceAuth.expires_in,
198
+ });
199
+
200
+ const deviceToken = await pollDeviceAuth(deviceAuth, callbacks.signal);
201
+ const token = await exchangeRefreshToken(deviceToken.refresh_token, callbacks.signal);
202
+ return tokenToCredentials(token, deviceToken.refresh_token, {
203
+ teamName: deviceToken.team_name,
204
+ });
205
+ }
206
+
207
+ export async function refreshHyperToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
208
+ const token = await exchangeRefreshToken(credentials.refresh);
209
+ return tokenToCredentials(token, credentials.refresh, {
210
+ teamName: teamNameFromCredentials(credentials),
211
+ });
212
+ }
213
+
214
+ function teamNameFromCredentials(credentials: OAuthCredentials): string | undefined {
215
+ const teamName = (credentials as HyperOAuthCredentials).teamName;
216
+ return typeof teamName === "string" && teamName.trim() ? teamName : undefined;
217
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { Static, TSchema } from "typebox";
2
+ import { Value } from "typebox/value";
3
+
4
+ export function parseSchema<const Schema extends TSchema>(
5
+ schema: Schema,
6
+ payload: unknown,
7
+ source: string,
8
+ ): Static<Schema> {
9
+ if (Value.Check(schema, payload)) {
10
+ return Value.Parse(schema, payload);
11
+ }
12
+
13
+ const details = [...Value.Errors(schema, payload)]
14
+ .slice(0, 3)
15
+ .map((error) => `${formatErrorPath(source, error.instancePath)} ${error.message}`)
16
+ .join("; ");
17
+ throw new Error(`${source} is invalid: ${details || "unknown validation error"}`);
18
+ }
19
+
20
+ function formatErrorPath(source: string, instancePath: string): string {
21
+ if (!instancePath) return source;
22
+ return `${source}${instancePath}`;
23
+ }
@@ -0,0 +1,77 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import * as path from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { Type, type Static } from "typebox";
5
+ import { Value } from "typebox/value";
6
+
7
+ const HyperStatusItemsSchema = Type.Object(
8
+ {
9
+ teamName: Type.Optional(Type.Boolean()),
10
+ hypercredits: Type.Optional(Type.Boolean()),
11
+ },
12
+ { additionalProperties: false },
13
+ );
14
+
15
+ export type HyperStatusItems = Required<Static<typeof HyperStatusItemsSchema>>;
16
+
17
+ const DEFAULT_STATUS_ITEMS: HyperStatusItems = {
18
+ teamName: false,
19
+ hypercredits: true,
20
+ };
21
+
22
+ function settingsPath(): string {
23
+ return path.join(getAgentDir(), "settings.json");
24
+ }
25
+
26
+ export function readHyperStatusItems(): HyperStatusItems {
27
+ const settings = readSettingsObject();
28
+ const hyper = propertyObject(settings, "hyper");
29
+ const statusItems = hyper ? property(hyper, "statusItems") : undefined;
30
+ if (statusItems === undefined) return { ...DEFAULT_STATUS_ITEMS };
31
+ if (!Value.Check(HyperStatusItemsSchema, statusItems)) {
32
+ console.error("Ignoring invalid hyper.statusItems in settings.json");
33
+ return { ...DEFAULT_STATUS_ITEMS };
34
+ }
35
+
36
+ return {
37
+ ...DEFAULT_STATUS_ITEMS,
38
+ ...Value.Parse(HyperStatusItemsSchema, statusItems),
39
+ };
40
+ }
41
+
42
+ export function writeHyperStatusItems(statusItems: HyperStatusItems): void {
43
+ const settings = readSettingsObject();
44
+ const existingHyper = propertyObject(settings, "hyper") ?? {};
45
+ settings.hyper = {
46
+ ...existingHyper,
47
+ statusItems,
48
+ };
49
+
50
+ mkdirSync(getAgentDir(), { recursive: true });
51
+ writeFileSync(settingsPath(), `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
52
+ }
53
+
54
+ export function defaultHyperStatusItems(): HyperStatusItems {
55
+ return { ...DEFAULT_STATUS_ITEMS };
56
+ }
57
+
58
+ function readSettingsObject(): Record<string, unknown> {
59
+ const filePath = settingsPath();
60
+ if (!existsSync(filePath)) return {};
61
+ const payload = JSON.parse(readFileSync(filePath, "utf-8"));
62
+ if (!isRecord(payload)) throw new Error(`${filePath} must contain a JSON object`);
63
+ return payload;
64
+ }
65
+
66
+ function property(source: Record<string, unknown>, key: string): unknown {
67
+ return Object.getOwnPropertyDescriptor(source, key)?.value;
68
+ }
69
+
70
+ function propertyObject(source: Record<string, unknown>, key: string): Record<string, unknown> | undefined {
71
+ const value = property(source, key);
72
+ return isRecord(value) ? value : undefined;
73
+ }
74
+
75
+ function isRecord(value: unknown): value is Record<string, unknown> {
76
+ return typeof value === "object" && value !== null && !Array.isArray(value);
77
+ }