@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -157
- package/dist/ads/context.d.ts +18 -0
- package/dist/ads/context.js +125 -0
- package/dist/ads/impression.d.ts +7 -0
- package/dist/ads/impression.js +85 -0
- package/dist/ads/resolve.d.ts +11 -0
- package/dist/ads/resolve.js +35 -0
- package/dist/ads/turns.d.ts +6 -0
- package/dist/ads/turns.js +14 -0
- package/dist/api/quota.d.ts +8 -0
- package/dist/api/quota.js +90 -0
- package/dist/api/session.d.ts +9 -0
- package/dist/api/session.js +69 -0
- package/dist/auth/authorize.d.ts +14 -0
- package/dist/auth/authorize.js +60 -0
- package/dist/auth/connect.d.ts +7 -0
- package/dist/auth/connect.js +117 -0
- package/dist/auth/credential.d.ts +5 -0
- package/dist/auth/credential.js +34 -0
- package/dist/auth/credentials.d.ts +7 -0
- package/dist/auth/credentials.js +56 -0
- package/dist/auth/jwt.d.ts +7 -0
- package/dist/auth/jwt.js +60 -0
- package/dist/auth/token.d.ts +14 -0
- package/dist/auth/token.js +28 -0
- package/dist/catalog/catalog.d.ts +6 -0
- package/dist/catalog/catalog.js +80 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +9 -0
- package/dist/catalog/registry.js +96 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +46 -0
- package/dist/constants.js +46 -0
- package/dist/deps.d.ts +11 -0
- package/dist/deps.js +2 -0
- package/dist/errors/handle.d.ts +5 -0
- package/dist/errors/handle.js +64 -0
- package/dist/errors/invalid.d.ts +3 -0
- package/dist/errors/invalid.js +8 -0
- package/dist/errors/limit.d.ts +10 -0
- package/dist/errors/limit.js +110 -0
- package/dist/errors/messages.d.ts +6 -0
- package/dist/errors/messages.js +119 -0
- package/dist/errors/parse.d.ts +4 -0
- package/dist/errors/parse.js +153 -0
- package/dist/index.d.ts +9 -9
- package/dist/index.js +7 -3376
- package/dist/integration/setup.d.ts +4 -0
- package/dist/integration/setup.js +49 -0
- package/dist/logging.d.ts +9 -0
- package/dist/logging.js +62 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +109 -0
- package/dist/session/events.d.ts +4 -0
- package/dist/session/events.js +96 -0
- package/dist/session/hooks.d.ts +8 -0
- package/dist/session/hooks.js +114 -0
- package/dist/session/track.d.ts +21 -0
- package/dist/session/track.js +107 -0
- package/dist/session/usage.d.ts +5 -0
- package/dist/session/usage.js +32 -0
- package/dist/state.d.ts +43 -0
- package/dist/state.js +26 -0
- package/dist/types.d.ts +272 -0
- package/dist/types.js +2 -0
- package/dist/utils/async.d.ts +8 -0
- package/dist/utils/async.js +29 -0
- package/dist/utils/browser.d.ts +3 -0
- package/dist/utils/browser.js +55 -0
- package/dist/utils/cache.d.ts +7 -0
- package/dist/utils/cache.js +45 -0
- package/dist/utils/device.d.ts +6 -0
- package/dist/utils/device.js +29 -0
- package/dist/utils/http.d.ts +4 -0
- package/dist/utils/http.js +42 -0
- package/dist/utils/json.d.ts +2 -0
- package/dist/utils/json.js +9 -0
- package/dist/utils/numbers.d.ts +6 -0
- package/dist/utils/numbers.js +49 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.js +6 -0
- package/dist/utils/urls.d.ts +6 -0
- package/dist/utils/urls.js +41 -0
- package/install.ps1 +82 -46
- package/install.sh +98 -40
- package/package.json +5 -4
- package/scripts/postinstall.mjs +68 -34
- package/src/ads/context.ts +156 -0
- package/src/ads/impression.ts +111 -0
- package/src/ads/resolve.ts +62 -0
- package/src/ads/turns.ts +24 -0
- package/src/api/quota.ts +110 -0
- package/src/api/session.ts +76 -0
- package/src/auth/authorize.ts +104 -0
- package/src/auth/connect.ts +144 -0
- package/src/auth/credential.ts +39 -0
- package/src/auth/credentials.ts +60 -0
- package/src/auth/jwt.ts +75 -0
- package/src/auth/token.ts +52 -0
- package/src/catalog/catalog.ts +94 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +122 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +61 -0
- package/src/deps.ts +13 -0
- package/src/errors/handle.ts +79 -0
- package/src/errors/invalid.ts +15 -0
- package/src/errors/limit.ts +114 -0
- package/src/errors/messages.ts +151 -0
- package/src/errors/parse.ts +156 -0
- package/src/index.ts +23 -4042
- package/src/integration/setup.ts +59 -0
- package/src/logging.ts +70 -0
- package/src/plugin.ts +143 -0
- package/src/session/events.ts +117 -0
- package/src/session/hooks.ts +192 -0
- package/src/session/track.ts +124 -0
- package/src/session/usage.ts +46 -0
- package/src/state.ts +82 -0
- package/src/types.ts +259 -0
- package/src/utils/async.ts +35 -0
- package/src/utils/browser.ts +61 -0
- package/src/utils/cache.ts +49 -0
- package/src/utils/device.ts +25 -0
- package/src/utils/http.ts +56 -0
- package/src/utils/json.ts +9 -0
- package/src/utils/numbers.ts +52 -0
- package/src/utils/text.ts +7 -0
- package/src/utils/urls.ts +47 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/** free-pi sign-in flows: browser connect and GitHub device code. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
AUTH_NETWORK_FAILURES,
|
|
5
|
+
AUTH_TIMEOUT_MS,
|
|
6
|
+
CONSENT_VERSION,
|
|
7
|
+
} from "../constants.js";
|
|
8
|
+
import type { ConnectSession, DeviceSession } from "../types.js";
|
|
9
|
+
import { sleep } from "../utils/async.js";
|
|
10
|
+
import { failureText, postJsonRetry } from "../utils/http.js";
|
|
11
|
+
import { readJson } from "../utils/json.js";
|
|
12
|
+
import { duplicateNumber } from "../utils/numbers.js";
|
|
13
|
+
import { cleanText } from "../utils/text.js";
|
|
14
|
+
import { safeUrl } from "../utils/urls.js";
|
|
15
|
+
|
|
16
|
+
export async function startConnect(
|
|
17
|
+
clientVersion: string,
|
|
18
|
+
): Promise<ConnectSession> {
|
|
19
|
+
const response = await postJsonRetry(
|
|
20
|
+
"/auth/connect/start",
|
|
21
|
+
{
|
|
22
|
+
consent_version: CONSENT_VERSION,
|
|
23
|
+
client: { os: process.platform, cli_version: clientVersion },
|
|
24
|
+
},
|
|
25
|
+
{ "x-freepi-signin-exp": "1" },
|
|
26
|
+
);
|
|
27
|
+
const body = await readJson(response);
|
|
28
|
+
if (!response.ok) throw new Error(failureText(response.status, body));
|
|
29
|
+
const url = safeUrl(body?.connect_url);
|
|
30
|
+
if (
|
|
31
|
+
typeof body?.session_id !== "string" ||
|
|
32
|
+
typeof body?.poll_secret !== "string" ||
|
|
33
|
+
!url ||
|
|
34
|
+
typeof body?.confirm_code !== "string"
|
|
35
|
+
) {
|
|
36
|
+
throw new Error("free-pi returned an invalid browser sign-in response.");
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
session_id: body.session_id,
|
|
40
|
+
poll_secret: body.poll_secret,
|
|
41
|
+
token: typeof body.token === "string" ? body.token : undefined,
|
|
42
|
+
confirm_code: cleanText(body.confirm_code),
|
|
43
|
+
connect_url: url,
|
|
44
|
+
expires_in: duplicateNumber(body.expires_in) ?? 900,
|
|
45
|
+
interval: duplicateNumber(body.interval) ?? 5,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function startDevice(): Promise<DeviceSession> {
|
|
50
|
+
const response = await postJsonRetry("/auth/github/device", {});
|
|
51
|
+
const body = await readJson(response);
|
|
52
|
+
if (!response.ok) throw new Error(failureText(response.status, body));
|
|
53
|
+
if (
|
|
54
|
+
typeof body?.session_id !== "string" ||
|
|
55
|
+
typeof body?.user_code !== "string" ||
|
|
56
|
+
typeof body?.verification_uri !== "string"
|
|
57
|
+
) {
|
|
58
|
+
throw new Error("free-pi returned an invalid GitHub device response.");
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
session_id: body.session_id,
|
|
62
|
+
user_code: cleanText(body.user_code),
|
|
63
|
+
verification_uri: body.verification_uri,
|
|
64
|
+
verification_uri_complete:
|
|
65
|
+
typeof body.verification_uri_complete === "string"
|
|
66
|
+
? body.verification_uri_complete
|
|
67
|
+
: undefined,
|
|
68
|
+
interval: duplicateNumber(body.interval) ?? 5,
|
|
69
|
+
expires_in: duplicateNumber(body.expires_in) ?? 900,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function submitConsent(sessionId: string): Promise<void> {
|
|
74
|
+
const response = await postJsonRetry("/auth/consent", {
|
|
75
|
+
session_id: sessionId,
|
|
76
|
+
consent_version: CONSENT_VERSION,
|
|
77
|
+
});
|
|
78
|
+
if (!response.ok) {
|
|
79
|
+
throw new Error(failureText(response.status, await readJson(response)));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function pollForToken(
|
|
84
|
+
request: () => Promise<Response>,
|
|
85
|
+
interval: number,
|
|
86
|
+
expiresIn: number,
|
|
87
|
+
): Promise<string> {
|
|
88
|
+
let waitSeconds = Math.max(1, interval || 1);
|
|
89
|
+
let networkFailures = 0;
|
|
90
|
+
const deadline =
|
|
91
|
+
Date.now() +
|
|
92
|
+
Math.min(AUTH_TIMEOUT_MS, Math.max(1, expiresIn || 900) * 1000);
|
|
93
|
+
|
|
94
|
+
while (Date.now() < deadline) {
|
|
95
|
+
await sleep(waitSeconds * 1000);
|
|
96
|
+
if (Date.now() >= deadline) break;
|
|
97
|
+
|
|
98
|
+
let response: Response;
|
|
99
|
+
try {
|
|
100
|
+
response = await request();
|
|
101
|
+
networkFailures = 0;
|
|
102
|
+
} catch {
|
|
103
|
+
networkFailures += 1;
|
|
104
|
+
if (networkFailures >= AUTH_NETWORK_FAILURES) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
"Can't reach free-pi. Check your internet connection and try again.",
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
waitSeconds = Math.max(waitSeconds, 5);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const body = await readJson(response);
|
|
114
|
+
if (!response.ok) {
|
|
115
|
+
if (response.status === 403 && body?.code === "denied") {
|
|
116
|
+
throw new Error("Sign-in was cancelled in the browser.");
|
|
117
|
+
}
|
|
118
|
+
if (response.status === 410 || body?.message === "expired_token") {
|
|
119
|
+
throw new Error("GitHub sign-in timed out.");
|
|
120
|
+
}
|
|
121
|
+
if (response.status === 403 && body?.code === "consent_required") {
|
|
122
|
+
throw new Error("free-pi did not record consent before polling.");
|
|
123
|
+
}
|
|
124
|
+
throw new Error(failureText(response.status, body));
|
|
125
|
+
}
|
|
126
|
+
if (typeof body?.token === "string" && body.token.length > 0)
|
|
127
|
+
return body.token;
|
|
128
|
+
const retryAfter = duplicateNumber(body?.retry_after);
|
|
129
|
+
waitSeconds = retryAfter ?? Math.max(waitSeconds, 5);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
throw new Error("GitHub sign-in timed out. Run the login again to retry.");
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function deviceUrl(session: DeviceSession): string {
|
|
136
|
+
const complete = safeUrl(session.verification_uri_complete);
|
|
137
|
+
if (complete) return complete;
|
|
138
|
+
const base = safeUrl(session.verification_uri);
|
|
139
|
+
if (!base) throw new Error("GitHub sign-in did not return a valid link.");
|
|
140
|
+
const url = new URL(base);
|
|
141
|
+
if (!url.searchParams.has("user_code"))
|
|
142
|
+
url.searchParams.set("user_code", session.user_code);
|
|
143
|
+
return url.toString();
|
|
144
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Translates OpenCode V2 credentials into free-pi tokens. */
|
|
2
|
+
|
|
3
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
4
|
+
import { decodeRefreshToken, tokenExpiry } from "./jwt.js";
|
|
5
|
+
import { normalizeIssuer } from "../utils/urls.js";
|
|
6
|
+
|
|
7
|
+
export function tokenFromCredential(
|
|
8
|
+
credential: Credential.Value | undefined,
|
|
9
|
+
): string | undefined {
|
|
10
|
+
if (!credential) return undefined;
|
|
11
|
+
if (credential.type === "oauth") return credential.access;
|
|
12
|
+
if (credential.type === "key") return credential.key;
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function expiryFromCredential(
|
|
17
|
+
credential: Credential.Value | undefined,
|
|
18
|
+
): number | undefined {
|
|
19
|
+
if (!credential) return undefined;
|
|
20
|
+
if (credential.type === "oauth" && credential.expires > 0)
|
|
21
|
+
return credential.expires;
|
|
22
|
+
if (credential.type === "key" && credential.metadata?.expires) {
|
|
23
|
+
const parsed = Number(credential.metadata.expires);
|
|
24
|
+
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
|
25
|
+
}
|
|
26
|
+
const token = tokenFromCredential(credential);
|
|
27
|
+
return token ? tokenExpiry(token) : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function issuerFromCredential(
|
|
31
|
+
credential: Credential.Value | undefined,
|
|
32
|
+
): string | undefined {
|
|
33
|
+
if (!credential) return undefined;
|
|
34
|
+
if (credential.type === "oauth")
|
|
35
|
+
return decodeRefreshToken(credential.refresh)?.issuer;
|
|
36
|
+
if (credential.type === "key")
|
|
37
|
+
return normalizeIssuer(credential.metadata?.issuer);
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** The free-pi credential file written by the free-pi CLI. */
|
|
2
|
+
|
|
3
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import type { Credentials } from "../types.js";
|
|
7
|
+
import { normalizeIssuer, resolveBaseUrl } from "../utils/urls.js";
|
|
8
|
+
|
|
9
|
+
export function credentialsPath(): string {
|
|
10
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
11
|
+
if (override) return resolve(override);
|
|
12
|
+
return join(homedir(), ".free-pi", "agent", "credentials.json");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function credentialsDisplayPath(): string {
|
|
16
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
17
|
+
if (override) return override;
|
|
18
|
+
return process.platform === "win32"
|
|
19
|
+
? join("%USERPROFILE%", ".free-pi", "agent", "credentials.json")
|
|
20
|
+
: "~/.free-pi/agent/credentials.json";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function readCredentials(): Promise<Credentials | undefined> {
|
|
24
|
+
const envToken = process.env.FREEPI_JWT?.trim();
|
|
25
|
+
if (envToken) return { token: envToken, issuer: resolveBaseUrl() };
|
|
26
|
+
try {
|
|
27
|
+
const raw = await readFile(credentialsPath(), "utf8");
|
|
28
|
+
const parsed = JSON.parse(raw) as { token?: unknown; issuer?: unknown };
|
|
29
|
+
if (typeof parsed.token !== "string" || parsed.token.length === 0)
|
|
30
|
+
return undefined;
|
|
31
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
32
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
33
|
+
} catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function readCredentialsToken(): Promise<string | undefined> {
|
|
39
|
+
return (await readCredentials())?.token;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function writeCredentials(
|
|
43
|
+
token: string,
|
|
44
|
+
issuer?: string,
|
|
45
|
+
): Promise<void> {
|
|
46
|
+
const path = credentialsPath();
|
|
47
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
48
|
+
const record = issuer
|
|
49
|
+
? { token, issuer: normalizeIssuer(issuer) ?? issuer }
|
|
50
|
+
: { token };
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
await writeFile(temporary, JSON.stringify(record), { mode: 0o600 });
|
|
53
|
+
try {
|
|
54
|
+
await rename(temporary, path);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (process.platform !== "win32") throw error;
|
|
57
|
+
await rm(path, { force: true });
|
|
58
|
+
await rename(temporary, path);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/auth/jwt.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** JWT and refresh-token encoding helpers. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
AUTH_SKEW_MS,
|
|
5
|
+
REFRESH_PREFIX,
|
|
6
|
+
} from "../constants.js";
|
|
7
|
+
import type { Credentials, JwtClaims } from "../types.js";
|
|
8
|
+
import { normalizeIssuer } from "../utils/urls.js";
|
|
9
|
+
|
|
10
|
+
export function parseJwtClaims(token: string): JwtClaims | undefined {
|
|
11
|
+
const payload = token.split(".")[1];
|
|
12
|
+
if (!payload) return undefined;
|
|
13
|
+
try {
|
|
14
|
+
const parsed = JSON.parse(
|
|
15
|
+
Buffer.from(payload, "base64url").toString("utf8"),
|
|
16
|
+
);
|
|
17
|
+
return parsed && typeof parsed === "object"
|
|
18
|
+
? (parsed as JwtClaims)
|
|
19
|
+
: undefined;
|
|
20
|
+
} catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function tokenExpiry(token: string): number | undefined {
|
|
26
|
+
const exp = parseJwtClaims(token)?.exp;
|
|
27
|
+
return typeof exp === "number" && Number.isFinite(exp) && exp > 0
|
|
28
|
+
? exp * 1000
|
|
29
|
+
: undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function tokenNeedsRefresh(token: string, expires?: number): boolean {
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const jwtExpiry = tokenExpiry(token);
|
|
35
|
+
return (
|
|
36
|
+
(jwtExpiry !== undefined && jwtExpiry - now <= AUTH_SKEW_MS) ||
|
|
37
|
+
(typeof expires === "number" &&
|
|
38
|
+
expires > 0 &&
|
|
39
|
+
expires - now <= AUTH_SKEW_MS)
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function encodeRefreshToken(token: string, issuer?: string): string {
|
|
44
|
+
const payload = JSON.stringify(issuer ? { token, issuer } : { token });
|
|
45
|
+
return `${REFRESH_PREFIX}${Buffer.from(payload).toString("base64url")}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function decodeRefreshToken(
|
|
49
|
+
value: string | undefined,
|
|
50
|
+
): Credentials | undefined {
|
|
51
|
+
if (!value) return undefined;
|
|
52
|
+
if (value.startsWith(REFRESH_PREFIX)) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(
|
|
55
|
+
Buffer.from(value.slice(REFRESH_PREFIX.length), "base64url").toString(
|
|
56
|
+
"utf8",
|
|
57
|
+
),
|
|
58
|
+
) as { token?: unknown; issuer?: unknown };
|
|
59
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
60
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
61
|
+
return issuer
|
|
62
|
+
? { token: parsed.token, issuer }
|
|
63
|
+
: { token: parsed.token };
|
|
64
|
+
}
|
|
65
|
+
} catch {}
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(value) as { token?: unknown; issuer?: unknown };
|
|
69
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
70
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
71
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
72
|
+
}
|
|
73
|
+
} catch {}
|
|
74
|
+
return { token: value };
|
|
75
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Resolves the token used for free-pi HTTP requests. */
|
|
2
|
+
|
|
3
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
4
|
+
import type { Logger } from "../logging.js";
|
|
5
|
+
import type { RuntimeState } from "../state.js";
|
|
6
|
+
import { readCredentials } from "./credentials.js";
|
|
7
|
+
import {
|
|
8
|
+
expiryFromCredential,
|
|
9
|
+
tokenFromCredential,
|
|
10
|
+
} from "./credential.js";
|
|
11
|
+
import { tokenNeedsRefresh } from "./jwt.js";
|
|
12
|
+
|
|
13
|
+
export type TokenSource = {
|
|
14
|
+
readonly state: RuntimeState;
|
|
15
|
+
readonly log: Logger;
|
|
16
|
+
activeCredential: () => Promise<Credential.Value | undefined>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Prefers the active OpenCode credential. The free-pi CLI credential file is a
|
|
21
|
+
* fallback for users who have not connected the integration yet.
|
|
22
|
+
*/
|
|
23
|
+
export async function resolveToken(
|
|
24
|
+
source: TokenSource,
|
|
25
|
+
): Promise<string | undefined> {
|
|
26
|
+
const credential = await source.activeCredential();
|
|
27
|
+
const current = tokenFromCredential(credential);
|
|
28
|
+
const stored = await readCredentials();
|
|
29
|
+
|
|
30
|
+
if (current && !tokenNeedsRefresh(current, expiryFromCredential(credential)))
|
|
31
|
+
return current;
|
|
32
|
+
|
|
33
|
+
if (
|
|
34
|
+
stored?.token &&
|
|
35
|
+
stored.token !== current &&
|
|
36
|
+
!tokenNeedsRefresh(stored.token)
|
|
37
|
+
) {
|
|
38
|
+
return stored.token;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (current) {
|
|
42
|
+
if (source.state.lastExpiredToken !== current) {
|
|
43
|
+
source.state.lastExpiredToken = current;
|
|
44
|
+
source.log.warn(
|
|
45
|
+
"free-pi token is expired. free-pi does not expose a refresh endpoint; sign in again from the free-pi integration.",
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return current;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return stored?.token;
|
|
52
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Fetches the live free-pi model catalog. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
CATALOG_DISK_TTL_MS,
|
|
5
|
+
CATALOG_TIMEOUT_MS,
|
|
6
|
+
CATALOG_TTL_MS,
|
|
7
|
+
} from "../constants.js";
|
|
8
|
+
import type { Deps } from "../deps.js";
|
|
9
|
+
import type { Catalog } from "../types.js";
|
|
10
|
+
import { readCache, writeCache } from "../utils/cache.js";
|
|
11
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
12
|
+
|
|
13
|
+
const CACHE_FILE = "catalog.json";
|
|
14
|
+
|
|
15
|
+
function isCatalog(value: unknown): value is Catalog {
|
|
16
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function reasonText(error: unknown): string {
|
|
20
|
+
if (error instanceof Error) {
|
|
21
|
+
return error.name === "TimeoutError" ? "request timed out" : error.message;
|
|
22
|
+
}
|
|
23
|
+
return "request failed";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
|
|
27
|
+
const state = deps.state;
|
|
28
|
+
if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
|
|
29
|
+
state.latestClientVersion = catalog.latest;
|
|
30
|
+
}
|
|
31
|
+
const arm = catalog.cost_experiment?.arm;
|
|
32
|
+
state.costExperimentArm =
|
|
33
|
+
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
34
|
+
? arm
|
|
35
|
+
: undefined;
|
|
36
|
+
state.cachedCatalog = catalog;
|
|
37
|
+
state.cachedCatalogAt = Date.now();
|
|
38
|
+
return catalog;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Refreshes the catalog without blocking callers that already have data. */
|
|
42
|
+
export function refreshCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
43
|
+
const state = deps.state;
|
|
44
|
+
if (state.catalogPromise) return state.catalogPromise;
|
|
45
|
+
const pending = (async () => {
|
|
46
|
+
try {
|
|
47
|
+
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
48
|
+
headers: { accept: "application/json" },
|
|
49
|
+
signal: AbortSignal.timeout(CATALOG_TIMEOUT_MS),
|
|
50
|
+
});
|
|
51
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
52
|
+
const catalog = (await response.json()) as Catalog;
|
|
53
|
+
if (!isCatalog(catalog)) {
|
|
54
|
+
throw new Error("free-pi returned an unexpected catalog payload");
|
|
55
|
+
}
|
|
56
|
+
applyCatalog(deps, catalog);
|
|
57
|
+
void writeCache(CACHE_FILE, catalog);
|
|
58
|
+
return catalog;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
const cached = state.cachedCatalog;
|
|
61
|
+
deps.log.warn(
|
|
62
|
+
cached
|
|
63
|
+
? "free-pi catalog is unreachable; using the cached model list"
|
|
64
|
+
: "free-pi catalog is unreachable; no free-pi models were registered",
|
|
65
|
+
{ reason: reasonText(error) },
|
|
66
|
+
);
|
|
67
|
+
return cached;
|
|
68
|
+
}
|
|
69
|
+
})();
|
|
70
|
+
state.catalogPromise = pending;
|
|
71
|
+
void pending.finally(() => {
|
|
72
|
+
if (state.catalogPromise === pending) state.catalogPromise = undefined;
|
|
73
|
+
});
|
|
74
|
+
return pending;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function fetchCatalog(deps: Deps): Promise<Catalog | undefined> {
|
|
78
|
+
const state = deps.state;
|
|
79
|
+
if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
|
|
80
|
+
return state.cachedCatalog;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (!state.cachedCatalog) {
|
|
84
|
+
const disk = await readCache<Catalog>(CACHE_FILE, CATALOG_DISK_TTL_MS);
|
|
85
|
+
if (isCatalog(disk)) {
|
|
86
|
+
applyCatalog(deps, disk);
|
|
87
|
+
// Serve the cached copy immediately and refresh it in the background.
|
|
88
|
+
void refreshCatalog(deps);
|
|
89
|
+
return disk;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return refreshCatalog(deps);
|
|
94
|
+
}
|