@eduardo191labs/opencode-free-pi 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +118 -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 +4 -0
- package/dist/catalog/catalog.js +43 -0
- package/dist/catalog/models.d.ts +15 -0
- package/dist/catalog/models.js +206 -0
- package/dist/catalog/registry.d.ts +4 -0
- package/dist/catalog/registry.js +46 -0
- package/dist/catalog/v2.d.ts +18 -0
- package/dist/catalog/v2.js +93 -0
- package/dist/constants.d.ts +40 -0
- package/dist/constants.js +40 -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 +19 -0
- package/dist/plugin.d.ts +4 -0
- package/dist/plugin.js +106 -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/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 +4 -3
- 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 +42 -0
- package/src/catalog/models.ts +291 -0
- package/src/catalog/registry.ts +51 -0
- package/src/catalog/v2.ts +124 -0
- package/src/constants.ts +55 -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 +26 -0
- package/src/plugin.ts +140 -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/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,14 @@
|
|
|
1
|
+
/** Per-turn ad bookkeeping keyed by user message and agent. */
|
|
2
|
+
import { AD_TURN_LIMIT } from "../constants.js";
|
|
3
|
+
import { trimMap } from "../utils/async.js";
|
|
4
|
+
export function adTurnKey(messageId, agent) {
|
|
5
|
+
return agent ? `${messageId}\u0000${agent}` : messageId;
|
|
6
|
+
}
|
|
7
|
+
export function rememberAdTurn(deps, key, turn) {
|
|
8
|
+
trimMap(deps.state.adTurns, AD_TURN_LIMIT);
|
|
9
|
+
deps.state.adTurns.set(key, turn);
|
|
10
|
+
return turn;
|
|
11
|
+
}
|
|
12
|
+
export function getAdTurn(deps, key) {
|
|
13
|
+
return deps.state.adTurns.get(key);
|
|
14
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Account quota fetching shared by error handling and usage tracking. */
|
|
2
|
+
import type { Deps } from "../deps.js";
|
|
3
|
+
import type { QuotaSnapshot, TokenCheckState } from "../types.js";
|
|
4
|
+
export declare function rememberTokenCheck(deps: Deps, token: string, state: TokenCheckState): void;
|
|
5
|
+
export declare function fetchQuota(deps: Deps, opts?: {
|
|
6
|
+
force?: boolean;
|
|
7
|
+
stats?: boolean;
|
|
8
|
+
}): Promise<QuotaSnapshot>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Account quota fetching shared by error handling and usage tracking. */
|
|
2
|
+
import { resolveToken } from "../auth/token.js";
|
|
3
|
+
import { QUOTA_HTTP_TIMEOUT_MS, QUOTA_TTL_MS } from "../constants.js";
|
|
4
|
+
import { logInvalidToken } from "../errors/invalid.js";
|
|
5
|
+
import { trimMap } from "../utils/async.js";
|
|
6
|
+
import { readJson } from "../utils/json.js";
|
|
7
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
8
|
+
export function rememberTokenCheck(deps, token, state) {
|
|
9
|
+
trimMap(deps.state.tokenChecks, 100);
|
|
10
|
+
deps.state.tokenChecks.set(token, { at: Date.now(), state });
|
|
11
|
+
}
|
|
12
|
+
export async function fetchQuota(deps, opts = {}) {
|
|
13
|
+
const current = deps.state.quotaCache;
|
|
14
|
+
if (!opts.force &&
|
|
15
|
+
current &&
|
|
16
|
+
Date.now() - current.fetchedAt < QUOTA_TTL_MS &&
|
|
17
|
+
(!opts.stats || current.stats)) {
|
|
18
|
+
return current;
|
|
19
|
+
}
|
|
20
|
+
if (deps.state.quotaPromise)
|
|
21
|
+
return deps.state.quotaPromise;
|
|
22
|
+
const pending = (async () => {
|
|
23
|
+
const token = await resolveToken(deps);
|
|
24
|
+
if (!token) {
|
|
25
|
+
const missing = {
|
|
26
|
+
fetchedAt: Date.now(),
|
|
27
|
+
error: "No free-pi sign-in found. Run `opencode auth login -p free-pi`.",
|
|
28
|
+
tokenInvalid: true,
|
|
29
|
+
};
|
|
30
|
+
deps.state.quotaCache = missing;
|
|
31
|
+
return missing;
|
|
32
|
+
}
|
|
33
|
+
const headers = { authorization: `Bearer ${token}` };
|
|
34
|
+
const meRequest = fetch(new URL("/me", resolveBaseUrl()), {
|
|
35
|
+
headers,
|
|
36
|
+
signal: AbortSignal.timeout(QUOTA_HTTP_TIMEOUT_MS),
|
|
37
|
+
}).catch(() => undefined);
|
|
38
|
+
const statsRequest = opts.stats
|
|
39
|
+
? fetch(new URL("/me/stats", resolveBaseUrl()), {
|
|
40
|
+
headers,
|
|
41
|
+
signal: AbortSignal.timeout(QUOTA_HTTP_TIMEOUT_MS),
|
|
42
|
+
}).catch(() => undefined)
|
|
43
|
+
: Promise.resolve(undefined);
|
|
44
|
+
const [meResponse, statsResponse] = await Promise.all([
|
|
45
|
+
meRequest,
|
|
46
|
+
statsRequest,
|
|
47
|
+
]);
|
|
48
|
+
if (meResponse?.status === 401 || statsResponse?.status === 401) {
|
|
49
|
+
rememberTokenCheck(deps, token, "invalid");
|
|
50
|
+
await logInvalidToken(deps, token);
|
|
51
|
+
const invalid = {
|
|
52
|
+
fetchedAt: Date.now(),
|
|
53
|
+
token,
|
|
54
|
+
tokenInvalid: true,
|
|
55
|
+
error: "free-pi sign-in is invalid or expired. Run `opencode auth login -p free-pi`.",
|
|
56
|
+
};
|
|
57
|
+
deps.state.quotaCache = invalid;
|
|
58
|
+
return invalid;
|
|
59
|
+
}
|
|
60
|
+
const me = meResponse?.ok
|
|
61
|
+
? (await readJson(meResponse))
|
|
62
|
+
: undefined;
|
|
63
|
+
const stats = statsResponse?.ok
|
|
64
|
+
? (await readJson(statsResponse))
|
|
65
|
+
: undefined;
|
|
66
|
+
if (meResponse?.ok || statsResponse?.ok)
|
|
67
|
+
rememberTokenCheck(deps, token, "ok");
|
|
68
|
+
const snapshot = {
|
|
69
|
+
fetchedAt: Date.now(),
|
|
70
|
+
token,
|
|
71
|
+
me: me ?? current?.me,
|
|
72
|
+
stats: stats ?? current?.stats,
|
|
73
|
+
...(meResponse
|
|
74
|
+
? meResponse.ok
|
|
75
|
+
? {}
|
|
76
|
+
: { error: `free-pi /me returned HTTP ${meResponse.status}` }
|
|
77
|
+
: { error: "Could not reach free-pi /me" }),
|
|
78
|
+
};
|
|
79
|
+
deps.state.quotaCache = snapshot;
|
|
80
|
+
return snapshot;
|
|
81
|
+
})();
|
|
82
|
+
deps.state.quotaPromise = pending;
|
|
83
|
+
try {
|
|
84
|
+
return await pending;
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
if (deps.state.quotaPromise === pending)
|
|
88
|
+
deps.state.quotaPromise = undefined;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Releases free-pi server-side session slots. */
|
|
2
|
+
import type { Deps } from "../deps.js";
|
|
3
|
+
import type { SessionResetOutcome } from "../types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Finalizes the provider session so the account does not stay at its
|
|
6
|
+
* four-session limit. Scoped to `sessionID` when the server honors it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function closeFreePiSession(deps: Deps, sessionID?: string): Promise<void>;
|
|
9
|
+
export declare function resetFreePiSessions(deps: Deps): Promise<SessionResetOutcome>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Releases free-pi server-side session slots. */
|
|
2
|
+
import { resolveToken } from "../auth/token.js";
|
|
3
|
+
import { SESSION_RESET_COOLDOWN_MS } from "../constants.js";
|
|
4
|
+
import { trimMap } from "../utils/async.js";
|
|
5
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
6
|
+
const CLOSE_LIMIT = 200;
|
|
7
|
+
function resetRequest(deps, token, sessionID) {
|
|
8
|
+
const headers = {
|
|
9
|
+
authorization: `Bearer ${token}`,
|
|
10
|
+
"x-client-version": deps.state.latestClientVersion,
|
|
11
|
+
};
|
|
12
|
+
if (sessionID)
|
|
13
|
+
headers["x-session-id"] = sessionID;
|
|
14
|
+
return fetch(new URL("/session/reset", resolveBaseUrl()), {
|
|
15
|
+
method: "POST",
|
|
16
|
+
headers,
|
|
17
|
+
signal: AbortSignal.timeout(3000),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Finalizes the provider session so the account does not stay at its
|
|
22
|
+
* four-session limit. Scoped to `sessionID` when the server honors it.
|
|
23
|
+
*/
|
|
24
|
+
export async function closeFreePiSession(deps, sessionID) {
|
|
25
|
+
const key = sessionID ?? "";
|
|
26
|
+
const existing = deps.state.sessionClosePromises.get(key);
|
|
27
|
+
if (existing)
|
|
28
|
+
return existing;
|
|
29
|
+
const pending = (async () => {
|
|
30
|
+
try {
|
|
31
|
+
const token = await resolveToken(deps);
|
|
32
|
+
if (!token)
|
|
33
|
+
return;
|
|
34
|
+
await resetRequest(deps, token, sessionID).catch(() => undefined);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
deps.state.sessionClosePromises.delete(key);
|
|
38
|
+
}
|
|
39
|
+
})();
|
|
40
|
+
trimMap(deps.state.sessionClosePromises, CLOSE_LIMIT);
|
|
41
|
+
deps.state.sessionClosePromises.set(key, pending);
|
|
42
|
+
return pending;
|
|
43
|
+
}
|
|
44
|
+
export async function resetFreePiSessions(deps) {
|
|
45
|
+
if (Date.now() - deps.state.lastSessionResetAt < SESSION_RESET_COOLDOWN_MS)
|
|
46
|
+
return "cooldown";
|
|
47
|
+
if (deps.state.sessionResetPromise)
|
|
48
|
+
return deps.state.sessionResetPromise;
|
|
49
|
+
deps.state.sessionResetPromise = (async () => {
|
|
50
|
+
try {
|
|
51
|
+
const token = await resolveToken(deps);
|
|
52
|
+
if (!token)
|
|
53
|
+
return "unavailable";
|
|
54
|
+
const response = await resetRequest(deps, token);
|
|
55
|
+
if (!response.ok)
|
|
56
|
+
return "failed";
|
|
57
|
+
const data = (await response.json().catch(() => undefined));
|
|
58
|
+
return data?.released === true ? "released" : "none";
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return "failed";
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
deps.state.lastSessionResetAt = Date.now();
|
|
65
|
+
deps.state.sessionResetPromise = undefined;
|
|
66
|
+
}
|
|
67
|
+
})();
|
|
68
|
+
return deps.state.sessionResetPromise;
|
|
69
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Starts a free-pi sign-in and returns the V2 authorization payload. */
|
|
2
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
3
|
+
import type { Logger } from "../logging.js";
|
|
4
|
+
export type FreePiAuthorization = {
|
|
5
|
+
url: string;
|
|
6
|
+
instructions: string;
|
|
7
|
+
callback: Promise<Credential.OAuth>;
|
|
8
|
+
};
|
|
9
|
+
export type AuthorizeDeps = {
|
|
10
|
+
log: Logger;
|
|
11
|
+
clientVersion: string;
|
|
12
|
+
warmCatalog?: () => Promise<unknown>;
|
|
13
|
+
};
|
|
14
|
+
export declare function authorizeFreePi(deps: AuthorizeDeps): Promise<FreePiAuthorization>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** Starts a free-pi sign-in and returns the V2 authorization payload. */
|
|
2
|
+
import { DEFAULT_TOKEN_LIFETIME_MS, } from "../constants.js";
|
|
3
|
+
import { browserAvailable, openBrowser, } from "../utils/browser.js";
|
|
4
|
+
import { deviceReport } from "../utils/device.js";
|
|
5
|
+
import { postJson } from "../utils/http.js";
|
|
6
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
7
|
+
import { deviceUrl, pollForToken, startConnect, startDevice, submitConsent, } from "./connect.js";
|
|
8
|
+
import { writeCredentials } from "./credentials.js";
|
|
9
|
+
import { encodeRefreshToken, tokenExpiry } from "./jwt.js";
|
|
10
|
+
function oauthCredential(token, issuer) {
|
|
11
|
+
return {
|
|
12
|
+
type: "oauth",
|
|
13
|
+
methodID: "github",
|
|
14
|
+
refresh: encodeRefreshToken(token, issuer),
|
|
15
|
+
access: token,
|
|
16
|
+
expires: tokenExpiry(token) ?? Date.now() + DEFAULT_TOKEN_LIFETIME_MS,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export async function authorizeFreePi(deps) {
|
|
20
|
+
await deps.warmCatalog?.().catch(() => undefined);
|
|
21
|
+
const base = resolveBaseUrl();
|
|
22
|
+
if (browserAvailable()) {
|
|
23
|
+
try {
|
|
24
|
+
const session = await startConnect(deps.clientVersion);
|
|
25
|
+
const opened = await openBrowser(session.connect_url);
|
|
26
|
+
return {
|
|
27
|
+
url: session.connect_url,
|
|
28
|
+
instructions: `${opened ? "Browser opened." : "Open the URL below."} Confirm code ${session.confirm_code} in your browser, then approve the connection.`,
|
|
29
|
+
callback: (async () => {
|
|
30
|
+
const token = await pollForToken(() => postJson("/auth/connect/poll", {
|
|
31
|
+
session_id: session.session_id,
|
|
32
|
+
poll_secret: session.poll_secret,
|
|
33
|
+
...deviceReport(),
|
|
34
|
+
}), session.interval, session.expires_in);
|
|
35
|
+
await writeCredentials(token, base).catch(() => undefined);
|
|
36
|
+
return oauthCredential(token, base);
|
|
37
|
+
})(),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
deps.log.warn("Browser sign-in could not start; falling back to GitHub device code.", { error: error instanceof Error ? error.message : String(error) });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const session = await startDevice();
|
|
45
|
+
const url = deviceUrl(session);
|
|
46
|
+
const opened = await openBrowser(url);
|
|
47
|
+
return {
|
|
48
|
+
url,
|
|
49
|
+
instructions: `${opened ? "Browser opened." : "Open the URL below."} Enter code ${session.user_code} on GitHub, then approve the connection.`,
|
|
50
|
+
callback: (async () => {
|
|
51
|
+
await submitConsent(session.session_id);
|
|
52
|
+
const token = await pollForToken(() => postJson("/auth/token", {
|
|
53
|
+
session_id: session.session_id,
|
|
54
|
+
...deviceReport(),
|
|
55
|
+
}), session.interval, session.expires_in ?? 900);
|
|
56
|
+
await writeCredentials(token, base).catch(() => undefined);
|
|
57
|
+
return oauthCredential(token, base);
|
|
58
|
+
})(),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** free-pi sign-in flows: browser connect and GitHub device code. */
|
|
2
|
+
import type { ConnectSession, DeviceSession } from "../types.js";
|
|
3
|
+
export declare function startConnect(clientVersion: string): Promise<ConnectSession>;
|
|
4
|
+
export declare function startDevice(): Promise<DeviceSession>;
|
|
5
|
+
export declare function submitConsent(sessionId: string): Promise<void>;
|
|
6
|
+
export declare function pollForToken(request: () => Promise<Response>, interval: number, expiresIn: number): Promise<string>;
|
|
7
|
+
export declare function deviceUrl(session: DeviceSession): string;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/** free-pi sign-in flows: browser connect and GitHub device code. */
|
|
2
|
+
import { AUTH_NETWORK_FAILURES, AUTH_TIMEOUT_MS, CONSENT_VERSION, } from "../constants.js";
|
|
3
|
+
import { sleep } from "../utils/async.js";
|
|
4
|
+
import { failureText, postJsonRetry } from "../utils/http.js";
|
|
5
|
+
import { readJson } from "../utils/json.js";
|
|
6
|
+
import { duplicateNumber } from "../utils/numbers.js";
|
|
7
|
+
import { cleanText } from "../utils/text.js";
|
|
8
|
+
import { safeUrl } from "../utils/urls.js";
|
|
9
|
+
export async function startConnect(clientVersion) {
|
|
10
|
+
const response = await postJsonRetry("/auth/connect/start", {
|
|
11
|
+
consent_version: CONSENT_VERSION,
|
|
12
|
+
client: { os: process.platform, cli_version: clientVersion },
|
|
13
|
+
}, { "x-freepi-signin-exp": "1" });
|
|
14
|
+
const body = await readJson(response);
|
|
15
|
+
if (!response.ok)
|
|
16
|
+
throw new Error(failureText(response.status, body));
|
|
17
|
+
const url = safeUrl(body?.connect_url);
|
|
18
|
+
if (typeof body?.session_id !== "string" ||
|
|
19
|
+
typeof body?.poll_secret !== "string" ||
|
|
20
|
+
!url ||
|
|
21
|
+
typeof body?.confirm_code !== "string") {
|
|
22
|
+
throw new Error("free-pi returned an invalid browser sign-in response.");
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
session_id: body.session_id,
|
|
26
|
+
poll_secret: body.poll_secret,
|
|
27
|
+
token: typeof body.token === "string" ? body.token : undefined,
|
|
28
|
+
confirm_code: cleanText(body.confirm_code),
|
|
29
|
+
connect_url: url,
|
|
30
|
+
expires_in: duplicateNumber(body.expires_in) ?? 900,
|
|
31
|
+
interval: duplicateNumber(body.interval) ?? 5,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export async function startDevice() {
|
|
35
|
+
const response = await postJsonRetry("/auth/github/device", {});
|
|
36
|
+
const body = await readJson(response);
|
|
37
|
+
if (!response.ok)
|
|
38
|
+
throw new Error(failureText(response.status, body));
|
|
39
|
+
if (typeof body?.session_id !== "string" ||
|
|
40
|
+
typeof body?.user_code !== "string" ||
|
|
41
|
+
typeof body?.verification_uri !== "string") {
|
|
42
|
+
throw new Error("free-pi returned an invalid GitHub device response.");
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
session_id: body.session_id,
|
|
46
|
+
user_code: cleanText(body.user_code),
|
|
47
|
+
verification_uri: body.verification_uri,
|
|
48
|
+
verification_uri_complete: typeof body.verification_uri_complete === "string"
|
|
49
|
+
? body.verification_uri_complete
|
|
50
|
+
: undefined,
|
|
51
|
+
interval: duplicateNumber(body.interval) ?? 5,
|
|
52
|
+
expires_in: duplicateNumber(body.expires_in) ?? 900,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export async function submitConsent(sessionId) {
|
|
56
|
+
const response = await postJsonRetry("/auth/consent", {
|
|
57
|
+
session_id: sessionId,
|
|
58
|
+
consent_version: CONSENT_VERSION,
|
|
59
|
+
});
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
throw new Error(failureText(response.status, await readJson(response)));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export async function pollForToken(request, interval, expiresIn) {
|
|
65
|
+
let waitSeconds = Math.max(1, interval || 1);
|
|
66
|
+
let networkFailures = 0;
|
|
67
|
+
const deadline = Date.now() +
|
|
68
|
+
Math.min(AUTH_TIMEOUT_MS, Math.max(1, expiresIn || 900) * 1000);
|
|
69
|
+
while (Date.now() < deadline) {
|
|
70
|
+
await sleep(waitSeconds * 1000);
|
|
71
|
+
if (Date.now() >= deadline)
|
|
72
|
+
break;
|
|
73
|
+
let response;
|
|
74
|
+
try {
|
|
75
|
+
response = await request();
|
|
76
|
+
networkFailures = 0;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
networkFailures += 1;
|
|
80
|
+
if (networkFailures >= AUTH_NETWORK_FAILURES) {
|
|
81
|
+
throw new Error("Can't reach free-pi. Check your internet connection and try again.");
|
|
82
|
+
}
|
|
83
|
+
waitSeconds = Math.max(waitSeconds, 5);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const body = await readJson(response);
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
if (response.status === 403 && body?.code === "denied") {
|
|
89
|
+
throw new Error("Sign-in was cancelled in the browser.");
|
|
90
|
+
}
|
|
91
|
+
if (response.status === 410 || body?.message === "expired_token") {
|
|
92
|
+
throw new Error("GitHub sign-in timed out.");
|
|
93
|
+
}
|
|
94
|
+
if (response.status === 403 && body?.code === "consent_required") {
|
|
95
|
+
throw new Error("free-pi did not record consent before polling.");
|
|
96
|
+
}
|
|
97
|
+
throw new Error(failureText(response.status, body));
|
|
98
|
+
}
|
|
99
|
+
if (typeof body?.token === "string" && body.token.length > 0)
|
|
100
|
+
return body.token;
|
|
101
|
+
const retryAfter = duplicateNumber(body?.retry_after);
|
|
102
|
+
waitSeconds = retryAfter ?? Math.max(waitSeconds, 5);
|
|
103
|
+
}
|
|
104
|
+
throw new Error("GitHub sign-in timed out. Run the login again to retry.");
|
|
105
|
+
}
|
|
106
|
+
export function deviceUrl(session) {
|
|
107
|
+
const complete = safeUrl(session.verification_uri_complete);
|
|
108
|
+
if (complete)
|
|
109
|
+
return complete;
|
|
110
|
+
const base = safeUrl(session.verification_uri);
|
|
111
|
+
if (!base)
|
|
112
|
+
throw new Error("GitHub sign-in did not return a valid link.");
|
|
113
|
+
const url = new URL(base);
|
|
114
|
+
if (!url.searchParams.has("user_code"))
|
|
115
|
+
url.searchParams.set("user_code", session.user_code);
|
|
116
|
+
return url.toString();
|
|
117
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Translates OpenCode V2 credentials into free-pi tokens. */
|
|
2
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
3
|
+
export declare function tokenFromCredential(credential: Credential.Value | undefined): string | undefined;
|
|
4
|
+
export declare function expiryFromCredential(credential: Credential.Value | undefined): number | undefined;
|
|
5
|
+
export declare function issuerFromCredential(credential: Credential.Value | undefined): string | undefined;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Translates OpenCode V2 credentials into free-pi tokens. */
|
|
2
|
+
import { decodeRefreshToken, tokenExpiry } from "./jwt.js";
|
|
3
|
+
import { normalizeIssuer } from "../utils/urls.js";
|
|
4
|
+
export function tokenFromCredential(credential) {
|
|
5
|
+
if (!credential)
|
|
6
|
+
return undefined;
|
|
7
|
+
if (credential.type === "oauth")
|
|
8
|
+
return credential.access;
|
|
9
|
+
if (credential.type === "key")
|
|
10
|
+
return credential.key;
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
export function expiryFromCredential(credential) {
|
|
14
|
+
if (!credential)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (credential.type === "oauth" && credential.expires > 0)
|
|
17
|
+
return credential.expires;
|
|
18
|
+
if (credential.type === "key" && credential.metadata?.expires) {
|
|
19
|
+
const parsed = Number(credential.metadata.expires);
|
|
20
|
+
if (Number.isFinite(parsed) && parsed > 0)
|
|
21
|
+
return parsed;
|
|
22
|
+
}
|
|
23
|
+
const token = tokenFromCredential(credential);
|
|
24
|
+
return token ? tokenExpiry(token) : undefined;
|
|
25
|
+
}
|
|
26
|
+
export function issuerFromCredential(credential) {
|
|
27
|
+
if (!credential)
|
|
28
|
+
return undefined;
|
|
29
|
+
if (credential.type === "oauth")
|
|
30
|
+
return decodeRefreshToken(credential.refresh)?.issuer;
|
|
31
|
+
if (credential.type === "key")
|
|
32
|
+
return normalizeIssuer(credential.metadata?.issuer);
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** The free-pi credential file written by the free-pi CLI. */
|
|
2
|
+
import type { Credentials } from "../types.js";
|
|
3
|
+
export declare function credentialsPath(): string;
|
|
4
|
+
export declare function credentialsDisplayPath(): string;
|
|
5
|
+
export declare function readCredentials(): Promise<Credentials | undefined>;
|
|
6
|
+
export declare function readCredentialsToken(): Promise<string | undefined>;
|
|
7
|
+
export declare function writeCredentials(token: string, issuer?: string): Promise<void>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** The free-pi credential file written by the free-pi CLI. */
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { normalizeIssuer, resolveBaseUrl } from "../utils/urls.js";
|
|
6
|
+
export function credentialsPath() {
|
|
7
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
8
|
+
if (override)
|
|
9
|
+
return resolve(override);
|
|
10
|
+
return join(homedir(), ".free-pi", "agent", "credentials.json");
|
|
11
|
+
}
|
|
12
|
+
export function credentialsDisplayPath() {
|
|
13
|
+
const override = process.env.FREEPI_CREDENTIALS_PATH?.trim();
|
|
14
|
+
if (override)
|
|
15
|
+
return override;
|
|
16
|
+
return process.platform === "win32"
|
|
17
|
+
? join("%USERPROFILE%", ".free-pi", "agent", "credentials.json")
|
|
18
|
+
: "~/.free-pi/agent/credentials.json";
|
|
19
|
+
}
|
|
20
|
+
export async function readCredentials() {
|
|
21
|
+
const envToken = process.env.FREEPI_JWT?.trim();
|
|
22
|
+
if (envToken)
|
|
23
|
+
return { token: envToken, issuer: resolveBaseUrl() };
|
|
24
|
+
try {
|
|
25
|
+
const raw = await readFile(credentialsPath(), "utf8");
|
|
26
|
+
const parsed = JSON.parse(raw);
|
|
27
|
+
if (typeof parsed.token !== "string" || parsed.token.length === 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
30
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export async function readCredentialsToken() {
|
|
37
|
+
return (await readCredentials())?.token;
|
|
38
|
+
}
|
|
39
|
+
export async function writeCredentials(token, issuer) {
|
|
40
|
+
const path = credentialsPath();
|
|
41
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
42
|
+
const record = issuer
|
|
43
|
+
? { token, issuer: normalizeIssuer(issuer) ?? issuer }
|
|
44
|
+
: { token };
|
|
45
|
+
await mkdir(dirname(path), { recursive: true });
|
|
46
|
+
await writeFile(temporary, JSON.stringify(record), { mode: 0o600 });
|
|
47
|
+
try {
|
|
48
|
+
await rename(temporary, path);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (process.platform !== "win32")
|
|
52
|
+
throw error;
|
|
53
|
+
await rm(path, { force: true });
|
|
54
|
+
await rename(temporary, path);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** JWT and refresh-token encoding helpers. */
|
|
2
|
+
import type { Credentials, JwtClaims } from "../types.js";
|
|
3
|
+
export declare function parseJwtClaims(token: string): JwtClaims | undefined;
|
|
4
|
+
export declare function tokenExpiry(token: string): number | undefined;
|
|
5
|
+
export declare function tokenNeedsRefresh(token: string, expires?: number): boolean;
|
|
6
|
+
export declare function encodeRefreshToken(token: string, issuer?: string): string;
|
|
7
|
+
export declare function decodeRefreshToken(value: string | undefined): Credentials | undefined;
|
package/dist/auth/jwt.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** JWT and refresh-token encoding helpers. */
|
|
2
|
+
import { AUTH_SKEW_MS, REFRESH_PREFIX, } from "../constants.js";
|
|
3
|
+
import { normalizeIssuer } from "../utils/urls.js";
|
|
4
|
+
export function parseJwtClaims(token) {
|
|
5
|
+
const payload = token.split(".")[1];
|
|
6
|
+
if (!payload)
|
|
7
|
+
return undefined;
|
|
8
|
+
try {
|
|
9
|
+
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
10
|
+
return parsed && typeof parsed === "object"
|
|
11
|
+
? parsed
|
|
12
|
+
: undefined;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function tokenExpiry(token) {
|
|
19
|
+
const exp = parseJwtClaims(token)?.exp;
|
|
20
|
+
return typeof exp === "number" && Number.isFinite(exp) && exp > 0
|
|
21
|
+
? exp * 1000
|
|
22
|
+
: undefined;
|
|
23
|
+
}
|
|
24
|
+
export function tokenNeedsRefresh(token, expires) {
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
const jwtExpiry = tokenExpiry(token);
|
|
27
|
+
return ((jwtExpiry !== undefined && jwtExpiry - now <= AUTH_SKEW_MS) ||
|
|
28
|
+
(typeof expires === "number" &&
|
|
29
|
+
expires > 0 &&
|
|
30
|
+
expires - now <= AUTH_SKEW_MS));
|
|
31
|
+
}
|
|
32
|
+
export function encodeRefreshToken(token, issuer) {
|
|
33
|
+
const payload = JSON.stringify(issuer ? { token, issuer } : { token });
|
|
34
|
+
return `${REFRESH_PREFIX}${Buffer.from(payload).toString("base64url")}`;
|
|
35
|
+
}
|
|
36
|
+
export function decodeRefreshToken(value) {
|
|
37
|
+
if (!value)
|
|
38
|
+
return undefined;
|
|
39
|
+
if (value.startsWith(REFRESH_PREFIX)) {
|
|
40
|
+
try {
|
|
41
|
+
const parsed = JSON.parse(Buffer.from(value.slice(REFRESH_PREFIX.length), "base64url").toString("utf8"));
|
|
42
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
43
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
44
|
+
return issuer
|
|
45
|
+
? { token: parsed.token, issuer }
|
|
46
|
+
: { token: parsed.token };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch { }
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(value);
|
|
53
|
+
if (typeof parsed.token === "string" && parsed.token.length > 0) {
|
|
54
|
+
const issuer = normalizeIssuer(parsed.issuer);
|
|
55
|
+
return issuer ? { token: parsed.token, issuer } : { token: parsed.token };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch { }
|
|
59
|
+
return { token: value };
|
|
60
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Resolves the token used for free-pi HTTP requests. */
|
|
2
|
+
import type { Credential } from "@opencode/schema/credential";
|
|
3
|
+
import type { Logger } from "../logging.js";
|
|
4
|
+
import type { RuntimeState } from "../state.js";
|
|
5
|
+
export type TokenSource = {
|
|
6
|
+
readonly state: RuntimeState;
|
|
7
|
+
readonly log: Logger;
|
|
8
|
+
activeCredential: () => Promise<Credential.Value | undefined>;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Prefers the active OpenCode credential. The free-pi CLI credential file is a
|
|
12
|
+
* fallback for users who have not connected the integration yet.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveToken(source: TokenSource): Promise<string | undefined>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Resolves the token used for free-pi HTTP requests. */
|
|
2
|
+
import { readCredentials } from "./credentials.js";
|
|
3
|
+
import { expiryFromCredential, tokenFromCredential, } from "./credential.js";
|
|
4
|
+
import { tokenNeedsRefresh } from "./jwt.js";
|
|
5
|
+
/**
|
|
6
|
+
* Prefers the active OpenCode credential. The free-pi CLI credential file is a
|
|
7
|
+
* fallback for users who have not connected the integration yet.
|
|
8
|
+
*/
|
|
9
|
+
export async function resolveToken(source) {
|
|
10
|
+
const credential = await source.activeCredential();
|
|
11
|
+
const current = tokenFromCredential(credential);
|
|
12
|
+
const stored = await readCredentials();
|
|
13
|
+
if (current && !tokenNeedsRefresh(current, expiryFromCredential(credential)))
|
|
14
|
+
return current;
|
|
15
|
+
if (stored?.token &&
|
|
16
|
+
stored.token !== current &&
|
|
17
|
+
!tokenNeedsRefresh(stored.token)) {
|
|
18
|
+
return stored.token;
|
|
19
|
+
}
|
|
20
|
+
if (current) {
|
|
21
|
+
if (source.state.lastExpiredToken !== current) {
|
|
22
|
+
source.state.lastExpiredToken = current;
|
|
23
|
+
source.log.warn("free-pi token is expired. free-pi does not expose a refresh endpoint; sign in again from the free-pi integration.");
|
|
24
|
+
}
|
|
25
|
+
return current;
|
|
26
|
+
}
|
|
27
|
+
return stored?.token;
|
|
28
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Fetches the live free-pi model catalog. */
|
|
2
|
+
import { CATALOG_TTL_MS } from "../constants.js";
|
|
3
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
4
|
+
export async function fetchCatalog(deps) {
|
|
5
|
+
const state = deps.state;
|
|
6
|
+
if (state.cachedCatalog && Date.now() - state.cachedCatalogAt < CATALOG_TTL_MS) {
|
|
7
|
+
return state.cachedCatalog;
|
|
8
|
+
}
|
|
9
|
+
if (state.catalogPromise)
|
|
10
|
+
return state.catalogPromise;
|
|
11
|
+
const pending = (async () => {
|
|
12
|
+
try {
|
|
13
|
+
const response = await fetch(`${resolveBaseUrl()}/client-version`, {
|
|
14
|
+
signal: AbortSignal.timeout(8000),
|
|
15
|
+
});
|
|
16
|
+
if (!response.ok)
|
|
17
|
+
return state.cachedCatalog;
|
|
18
|
+
const catalog = (await response.json());
|
|
19
|
+
if (typeof catalog.latest === "string" && catalog.latest.length > 0) {
|
|
20
|
+
state.latestClientVersion = catalog.latest;
|
|
21
|
+
}
|
|
22
|
+
const arm = catalog.cost_experiment?.arm;
|
|
23
|
+
state.costExperimentArm =
|
|
24
|
+
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
25
|
+
? arm
|
|
26
|
+
: undefined;
|
|
27
|
+
state.cachedCatalog = catalog;
|
|
28
|
+
state.cachedCatalogAt = Date.now();
|
|
29
|
+
return catalog;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return state.cachedCatalog;
|
|
33
|
+
}
|
|
34
|
+
})();
|
|
35
|
+
state.catalogPromise = pending;
|
|
36
|
+
try {
|
|
37
|
+
return await pending;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
if (state.catalogPromise === pending)
|
|
41
|
+
state.catalogPromise = undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|