@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.
Files changed (128) hide show
  1. package/README.md +118 -157
  2. package/dist/ads/context.d.ts +18 -0
  3. package/dist/ads/context.js +125 -0
  4. package/dist/ads/impression.d.ts +7 -0
  5. package/dist/ads/impression.js +85 -0
  6. package/dist/ads/resolve.d.ts +11 -0
  7. package/dist/ads/resolve.js +35 -0
  8. package/dist/ads/turns.d.ts +6 -0
  9. package/dist/ads/turns.js +14 -0
  10. package/dist/api/quota.d.ts +8 -0
  11. package/dist/api/quota.js +90 -0
  12. package/dist/api/session.d.ts +9 -0
  13. package/dist/api/session.js +69 -0
  14. package/dist/auth/authorize.d.ts +14 -0
  15. package/dist/auth/authorize.js +60 -0
  16. package/dist/auth/connect.d.ts +7 -0
  17. package/dist/auth/connect.js +117 -0
  18. package/dist/auth/credential.d.ts +5 -0
  19. package/dist/auth/credential.js +34 -0
  20. package/dist/auth/credentials.d.ts +7 -0
  21. package/dist/auth/credentials.js +56 -0
  22. package/dist/auth/jwt.d.ts +7 -0
  23. package/dist/auth/jwt.js +60 -0
  24. package/dist/auth/token.d.ts +14 -0
  25. package/dist/auth/token.js +28 -0
  26. package/dist/catalog/catalog.d.ts +4 -0
  27. package/dist/catalog/catalog.js +43 -0
  28. package/dist/catalog/models.d.ts +15 -0
  29. package/dist/catalog/models.js +206 -0
  30. package/dist/catalog/registry.d.ts +4 -0
  31. package/dist/catalog/registry.js +46 -0
  32. package/dist/catalog/v2.d.ts +18 -0
  33. package/dist/catalog/v2.js +93 -0
  34. package/dist/constants.d.ts +40 -0
  35. package/dist/constants.js +40 -0
  36. package/dist/deps.d.ts +11 -0
  37. package/dist/deps.js +2 -0
  38. package/dist/errors/handle.d.ts +5 -0
  39. package/dist/errors/handle.js +64 -0
  40. package/dist/errors/invalid.d.ts +3 -0
  41. package/dist/errors/invalid.js +8 -0
  42. package/dist/errors/limit.d.ts +10 -0
  43. package/dist/errors/limit.js +110 -0
  44. package/dist/errors/messages.d.ts +6 -0
  45. package/dist/errors/messages.js +119 -0
  46. package/dist/errors/parse.d.ts +4 -0
  47. package/dist/errors/parse.js +153 -0
  48. package/dist/index.d.ts +9 -9
  49. package/dist/index.js +7 -3376
  50. package/dist/integration/setup.d.ts +4 -0
  51. package/dist/integration/setup.js +49 -0
  52. package/dist/logging.d.ts +9 -0
  53. package/dist/logging.js +19 -0
  54. package/dist/plugin.d.ts +4 -0
  55. package/dist/plugin.js +106 -0
  56. package/dist/session/events.d.ts +4 -0
  57. package/dist/session/events.js +96 -0
  58. package/dist/session/hooks.d.ts +8 -0
  59. package/dist/session/hooks.js +114 -0
  60. package/dist/session/track.d.ts +21 -0
  61. package/dist/session/track.js +107 -0
  62. package/dist/session/usage.d.ts +5 -0
  63. package/dist/session/usage.js +32 -0
  64. package/dist/state.d.ts +43 -0
  65. package/dist/state.js +26 -0
  66. package/dist/types.d.ts +272 -0
  67. package/dist/types.js +2 -0
  68. package/dist/utils/async.d.ts +8 -0
  69. package/dist/utils/async.js +29 -0
  70. package/dist/utils/browser.d.ts +3 -0
  71. package/dist/utils/browser.js +55 -0
  72. package/dist/utils/device.d.ts +6 -0
  73. package/dist/utils/device.js +29 -0
  74. package/dist/utils/http.d.ts +4 -0
  75. package/dist/utils/http.js +42 -0
  76. package/dist/utils/json.d.ts +2 -0
  77. package/dist/utils/json.js +9 -0
  78. package/dist/utils/numbers.d.ts +6 -0
  79. package/dist/utils/numbers.js +49 -0
  80. package/dist/utils/text.d.ts +2 -0
  81. package/dist/utils/text.js +6 -0
  82. package/dist/utils/urls.d.ts +6 -0
  83. package/dist/utils/urls.js +41 -0
  84. package/install.ps1 +82 -46
  85. package/install.sh +98 -40
  86. package/package.json +4 -3
  87. package/scripts/postinstall.mjs +68 -34
  88. package/src/ads/context.ts +156 -0
  89. package/src/ads/impression.ts +111 -0
  90. package/src/ads/resolve.ts +62 -0
  91. package/src/ads/turns.ts +24 -0
  92. package/src/api/quota.ts +110 -0
  93. package/src/api/session.ts +76 -0
  94. package/src/auth/authorize.ts +104 -0
  95. package/src/auth/connect.ts +144 -0
  96. package/src/auth/credential.ts +39 -0
  97. package/src/auth/credentials.ts +60 -0
  98. package/src/auth/jwt.ts +75 -0
  99. package/src/auth/token.ts +52 -0
  100. package/src/catalog/catalog.ts +42 -0
  101. package/src/catalog/models.ts +291 -0
  102. package/src/catalog/registry.ts +51 -0
  103. package/src/catalog/v2.ts +124 -0
  104. package/src/constants.ts +55 -0
  105. package/src/deps.ts +13 -0
  106. package/src/errors/handle.ts +79 -0
  107. package/src/errors/invalid.ts +15 -0
  108. package/src/errors/limit.ts +114 -0
  109. package/src/errors/messages.ts +151 -0
  110. package/src/errors/parse.ts +156 -0
  111. package/src/index.ts +23 -4042
  112. package/src/integration/setup.ts +59 -0
  113. package/src/logging.ts +26 -0
  114. package/src/plugin.ts +140 -0
  115. package/src/session/events.ts +117 -0
  116. package/src/session/hooks.ts +192 -0
  117. package/src/session/track.ts +124 -0
  118. package/src/session/usage.ts +46 -0
  119. package/src/state.ts +82 -0
  120. package/src/types.ts +259 -0
  121. package/src/utils/async.ts +35 -0
  122. package/src/utils/browser.ts +61 -0
  123. package/src/utils/device.ts +25 -0
  124. package/src/utils/http.ts +56 -0
  125. package/src/utils/json.ts +9 -0
  126. package/src/utils/numbers.ts +52 -0
  127. package/src/utils/text.ts +7 -0
  128. package/src/utils/urls.ts +47 -0
@@ -0,0 +1,46 @@
1
+ /** Tracks the last request's model and token usage and refreshes quota. */
2
+
3
+ import { fetchQuota } from "../api/quota.js";
4
+ import { QUOTA_REFRESH_DEBOUNCE_MS } from "../constants.js";
5
+ import type { Deps } from "../deps.js";
6
+ import type { TokenUsageLike } from "../types.js";
7
+ import { trimMap } from "../utils/async.js";
8
+ import { touchSessionActivity } from "./track.js";
9
+
10
+ export function rememberTrackedModel(
11
+ deps: Deps,
12
+ sessionID: string,
13
+ providerID: string,
14
+ modelID: string,
15
+ ): void {
16
+ trimMap(deps.state.trackedModels, 200);
17
+ deps.state.trackedModels.set(sessionID, { providerID, modelID });
18
+ }
19
+
20
+ export function recordUsage(
21
+ deps: Deps,
22
+ sessionID: string,
23
+ cost: number,
24
+ tokens: TokenUsageLike | undefined,
25
+ ): void {
26
+ if (typeof sessionID !== "string" || !sessionID) return;
27
+ touchSessionActivity(deps, sessionID);
28
+ const tracked = deps.state.trackedModels.get(sessionID);
29
+ deps.state.lastUsage = {
30
+ at: Date.now(),
31
+ messageID: "",
32
+ providerID: tracked?.providerID ?? "",
33
+ modelID: tracked?.modelID ?? "",
34
+ cost: typeof cost === "number" ? cost : 0,
35
+ input: tokens?.input ?? 0,
36
+ output: tokens?.output ?? 0,
37
+ reasoning: tokens?.reasoning ?? 0,
38
+ cacheRead: tokens?.cache?.read ?? 0,
39
+ cacheWrite: tokens?.cache?.write ?? 0,
40
+ };
41
+
42
+ const now = Date.now();
43
+ if (now - deps.state.lastQuotaRefreshAt < QUOTA_REFRESH_DEBOUNCE_MS) return;
44
+ deps.state.lastQuotaRefreshAt = now;
45
+ void fetchQuota(deps, { force: true }).catch(() => undefined);
46
+ }
package/src/state.ts ADDED
@@ -0,0 +1,82 @@
1
+ /** Per-plugin-instance mutable state. */
2
+
3
+ import { DEFAULT_CLIENT_VERSION } from "./constants.js";
4
+ import type {
5
+ AdTurn,
6
+ Catalog,
7
+ FreePiError,
8
+ ModelRegistry,
9
+ QuotaSnapshot,
10
+ RequestUsage,
11
+ SessionResetOutcome,
12
+ TokenCheckState,
13
+ TrackedModel,
14
+ } from "./types.js";
15
+
16
+ export type RuntimeState = {
17
+ latestClientVersion: string;
18
+ providerToken?: string;
19
+
20
+ cachedCatalog?: Catalog;
21
+ cachedCatalogAt: number;
22
+ catalogPromise?: Promise<Catalog | undefined>;
23
+ cachedRegistry?: ModelRegistry;
24
+ cachedRegistryAt: number;
25
+ registryAttemptAt: number;
26
+ registryPromise?: Promise<ModelRegistry | undefined>;
27
+ costExperimentArm?: string;
28
+ catalogModels: Catalog;
29
+ outputLimits: Map<string, number>;
30
+
31
+ quotaCache?: QuotaSnapshot;
32
+ quotaPromise?: Promise<QuotaSnapshot>;
33
+ lastQuotaRefreshAt: number;
34
+
35
+ lastUsage?: RequestUsage;
36
+ lastUsageMessageID?: string;
37
+ lastFreePiError?: FreePiError;
38
+ lastErrorLogKey?: string;
39
+ lastErrorLogAt: number;
40
+ lastInvalidToken?: string;
41
+ tokenChecks: Map<string, { at: number; state: TokenCheckState }>;
42
+ lastExpiredToken?: string;
43
+
44
+ sessionClosePromises: Map<string, Promise<void>>;
45
+ sessionResetPromise?: Promise<SessionResetOutcome>;
46
+ lastSessionResetAt: number;
47
+
48
+ freePiSessions: Set<string>;
49
+ finalizedSessions: Set<string>;
50
+ activeExecutions: Set<string>;
51
+ sessionActivity: Map<string, number>;
52
+ finalizeTimers: Map<string, ReturnType<typeof setTimeout>>;
53
+ adTurns: Map<string, AdTurn>;
54
+ pendingAdTurns: Map<string, AdTurn>;
55
+ adImpressions: Map<string, Promise<void>>;
56
+ trackedModels: Map<string, TrackedModel>;
57
+ };
58
+
59
+ export function createRuntimeState(): RuntimeState {
60
+ return {
61
+ latestClientVersion: DEFAULT_CLIENT_VERSION,
62
+ cachedCatalogAt: 0,
63
+ cachedRegistryAt: 0,
64
+ registryAttemptAt: 0,
65
+ catalogModels: {},
66
+ outputLimits: new Map(),
67
+ lastQuotaRefreshAt: 0,
68
+ lastErrorLogAt: 0,
69
+ tokenChecks: new Map(),
70
+ sessionClosePromises: new Map(),
71
+ lastSessionResetAt: 0,
72
+ freePiSessions: new Set(),
73
+ finalizedSessions: new Set(),
74
+ activeExecutions: new Set(),
75
+ sessionActivity: new Map(),
76
+ finalizeTimers: new Map(),
77
+ adTurns: new Map(),
78
+ pendingAdTurns: new Map(),
79
+ adImpressions: new Map(),
80
+ trackedModels: new Map(),
81
+ };
82
+ }
package/src/types.ts ADDED
@@ -0,0 +1,259 @@
1
+ /** Domain types shared by the plugin modules. */
2
+
3
+ export type ReasoningOption =
4
+ | { type: "effort"; values: string[] }
5
+ | { type: "toggle" }
6
+ | { type: "budget_tokens"; min?: number; max?: number };
7
+
8
+ export type CatalogModel = {
9
+ id?: string;
10
+ name?: string;
11
+ display_name?: string;
12
+ section?: string;
13
+ tier?: "regular" | "premium";
14
+ input_credits_per_mtok?: number;
15
+ output_credits_per_mtok?: number;
16
+ cache_read_credits_per_mtok?: number;
17
+ cache_write_credits_per_mtok?: number;
18
+ free?: boolean;
19
+ usage_x?: string | null;
20
+ note?: string | null;
21
+ unavailable?: boolean;
22
+ stats_id?: string;
23
+ release_date?: string;
24
+ family?: string;
25
+ reasoning?: boolean;
26
+ reasoning_options?: ReasoningOption[];
27
+ temperature?: boolean;
28
+ tool_call?: boolean;
29
+ attachment?: boolean;
30
+ interleaved?: boolean | string | { field: string };
31
+ context_window?: number;
32
+ contextWindow?: number;
33
+ max_tokens?: number;
34
+ maxTokens?: number;
35
+ max_output_tokens?: number;
36
+ limit?: { context?: number; output?: number };
37
+ modalities?: { input?: string[]; output?: string[] };
38
+ };
39
+
40
+ export type ModelsDevModel = {
41
+ id?: string;
42
+ name?: string;
43
+ family?: string;
44
+ release_date?: string;
45
+ reasoning?: boolean;
46
+ reasoning_options?: ReasoningOption[];
47
+ tool_call?: boolean;
48
+ temperature?: boolean;
49
+ attachment?: boolean;
50
+ interleaved?: boolean | string | { field: string };
51
+ limit?: { context?: number; input?: number; output?: number };
52
+ modalities?: { input?: string[]; output?: string[] };
53
+ cost?: {
54
+ input?: number;
55
+ output?: number;
56
+ cache_read?: number;
57
+ cache_write?: number;
58
+ };
59
+ };
60
+
61
+ export type ModelsDevProvider = {
62
+ models?: Record<string, ModelsDevModel>;
63
+ };
64
+
65
+ export type ModelRegistry = Record<string, ModelsDevProvider>;
66
+
67
+ export type RegistryCandidate = {
68
+ providerID: string;
69
+ modelID: string;
70
+ model: ModelsDevModel;
71
+ };
72
+
73
+ export type Catalog = {
74
+ latest?: string;
75
+ default_model?: string;
76
+ models?: CatalogModel[];
77
+ cost_experiment?: { arm?: string };
78
+ };
79
+
80
+ /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
81
+ export type ModelDefinition = {
82
+ id: string;
83
+ name: string;
84
+ family?: string;
85
+ release_date?: string;
86
+ reasoning: boolean;
87
+ reasoning_options?: ReasoningOption[];
88
+ variants: Record<string, Record<string, unknown>>;
89
+ temperature: boolean;
90
+ tool_call: boolean;
91
+ attachment: boolean;
92
+ interleaved?: boolean | string | { field: string };
93
+ cost: {
94
+ input: number;
95
+ output: number;
96
+ cache_read: number;
97
+ cache_write: number;
98
+ };
99
+ limit: { context: number; output: number };
100
+ modalities: { input: string[]; output: string[] };
101
+ status: "active" | "deprecated";
102
+ };
103
+
104
+ export type ModelMap = Record<string, ModelDefinition>;
105
+
106
+ export type FreePiOptions = {
107
+ includeDefense?: boolean;
108
+ };
109
+
110
+ export type MeResponse = {
111
+ handle?: string;
112
+ tier?: string;
113
+ remaining_usd_today?: number;
114
+ cap_usd_today?: number;
115
+ credit_usd?: number;
116
+ consent_version?: string | null;
117
+ notice?: string;
118
+ buy_url?: string;
119
+ allowance_credits?: number;
120
+ remaining_credits_today?: number;
121
+ refill_at?: string;
122
+ lane?: "standard" | "fallback" | "wait" | string;
123
+ bonus_credits?: number;
124
+ bonus_wallet_credits?: number;
125
+ premium_credits?: number;
126
+ premium_bought_credits?: number;
127
+ premium_gifted_credits?: number;
128
+ premium_expiring_credits?: number;
129
+ regular_wallet_credits?: number;
130
+ premium_expires_at?: string;
131
+ credit_tiers?: boolean;
132
+ premium_get_line?: string;
133
+ guest?: boolean;
134
+ visible_allowance?: boolean;
135
+ earn_reward?: Record<string, unknown> | null;
136
+ slow_tier?: Record<string, unknown>;
137
+ };
138
+
139
+ export type MeStatsResponse = MeResponse & {
140
+ credit_credits?: number;
141
+ spent_usd_today?: number;
142
+ request_count_today?: number;
143
+ prompt_tokens_today?: number;
144
+ completion_tokens_today?: number;
145
+ lifetime?: {
146
+ spent_usd?: number;
147
+ prompt_tokens?: number;
148
+ completion_tokens?: number;
149
+ request_count?: number;
150
+ };
151
+ };
152
+
153
+ export type QuotaSnapshot = {
154
+ fetchedAt: number;
155
+ token?: string;
156
+ me?: MeResponse;
157
+ stats?: MeStatsResponse;
158
+ error?: string;
159
+ tokenInvalid?: boolean;
160
+ };
161
+
162
+ export type FreePiError = {
163
+ status?: number;
164
+ code: string;
165
+ message?: string;
166
+ limit?: string;
167
+ retry_after_seconds?: number;
168
+ clears_at?: string;
169
+ remaining_credits_today?: number;
170
+ allowance_credits?: number;
171
+ };
172
+
173
+ export type TokenCheckState = "ok" | "invalid" | "unknown";
174
+
175
+ export type RequestUsage = {
176
+ at: number;
177
+ messageID: string;
178
+ providerID: string;
179
+ modelID: string;
180
+ cost: number;
181
+ input: number;
182
+ output: number;
183
+ reasoning: number;
184
+ cacheRead: number;
185
+ cacheWrite: number;
186
+ };
187
+
188
+ export type Credentials = {
189
+ token: string;
190
+ issuer?: string;
191
+ };
192
+
193
+ export type JwtClaims = {
194
+ exp?: number;
195
+ guest?: boolean;
196
+ iss?: string;
197
+ };
198
+
199
+ export type ConnectSession = {
200
+ session_id: string;
201
+ poll_secret: string;
202
+ token?: string;
203
+ confirm_code: string;
204
+ connect_url: string;
205
+ expires_in: number;
206
+ interval: number;
207
+ };
208
+
209
+ export type DeviceSession = {
210
+ session_id: string;
211
+ user_code: string;
212
+ verification_uri: string;
213
+ verification_uri_complete?: string;
214
+ interval: number;
215
+ expires_in?: number;
216
+ };
217
+
218
+ export type SessionResetOutcome =
219
+ | "released"
220
+ | "none"
221
+ | "failed"
222
+ | "unavailable"
223
+ | "cooldown";
224
+
225
+ export type AdTurn = {
226
+ turnId: string;
227
+ context?: string;
228
+ impression?: Promise<void>;
229
+ };
230
+
231
+ export type TrackedModel = {
232
+ providerID: string;
233
+ modelID: string;
234
+ };
235
+
236
+ export type TokenUsageLike = {
237
+ input?: number;
238
+ output?: number;
239
+ reasoning?: number;
240
+ cache?: { read?: number; write?: number };
241
+ };
242
+
243
+ /** Minimal view of an OpenCode V2 session message. */
244
+ export type MessageContentPart = { type: string; text?: string };
245
+
246
+ export type SessionMessageInfo =
247
+ | { type: "user"; id: string; text: string }
248
+ | {
249
+ type: "assistant";
250
+ id: string;
251
+ agent?: string;
252
+ model?: { providerID: string; id: string };
253
+ content: MessageContentPart[];
254
+ }
255
+ | { type: string; id?: string; [key: string]: unknown };
256
+
257
+ export type ReadContext = (
258
+ sessionID: string,
259
+ ) => Promise<readonly SessionMessageInfo[]>;
@@ -0,0 +1,35 @@
1
+ /** Small async helpers. */
2
+
3
+ export function sleep(ms: number): Promise<void> {
4
+ return new Promise((resolve) => setTimeout(resolve, ms));
5
+ }
6
+
7
+ /** Resolves with `fallback` if `promise` does not settle within `ms`. */
8
+ export function settle<T>(
9
+ promise: Promise<T>,
10
+ fallback: T,
11
+ ms = 6_000,
12
+ ): Promise<T> {
13
+ return Promise.race([
14
+ promise,
15
+ new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms)),
16
+ ]);
17
+ }
18
+
19
+ /** Adds an LRU-ish cap to a `Map` keyed by insertion order. */
20
+ export function trimMap<K, V>(map: Map<K, V>, limit: number): void {
21
+ while (map.size > limit) {
22
+ const oldest = map.keys().next().value;
23
+ if (oldest === undefined) return;
24
+ map.delete(oldest);
25
+ }
26
+ }
27
+
28
+ /** Adds an LRU-ish cap to a `Set` ordered by insertion. */
29
+ export function trimSet<T>(set: Set<T>, limit: number): void {
30
+ while (set.size > limit) {
31
+ const oldest = set.values().next().value;
32
+ if (oldest === undefined) return;
33
+ set.delete(oldest);
34
+ }
35
+ }
@@ -0,0 +1,61 @@
1
+ /** Browser availability and opening links on every supported platform. */
2
+
3
+ import { spawn } from "node:child_process";
4
+ import { safeUrl } from "./urls.js";
5
+
6
+ export function browserAvailable(): boolean {
7
+ if (
8
+ process.env.FREEPI_DEVICE_LOGIN === "1" ||
9
+ process.env.FREEPI_DEVICE_LOGIN === "true"
10
+ ) {
11
+ return false;
12
+ }
13
+ if (process.env.OPENCODE_HEADLESS) return false;
14
+ if (
15
+ process.env.SSH_CONNECTION ||
16
+ process.env.SSH_CLIENT ||
17
+ process.env.SSH_TTY
18
+ )
19
+ return false;
20
+ if (process.env.TERMUX_VERSION || process.env.PREFIX?.includes("com.termux"))
21
+ return true;
22
+ if (
23
+ process.platform === "linux" &&
24
+ !process.env.DISPLAY &&
25
+ !process.env.WAYLAND_DISPLAY
26
+ ) {
27
+ return false;
28
+ }
29
+ return true;
30
+ }
31
+
32
+ export function openBrowser(url: string): Promise<boolean> {
33
+ return new Promise((resolve) => {
34
+ const target = safeUrl(url);
35
+ if (!target) return resolve(false);
36
+ const command =
37
+ process.env.TERMUX_VERSION || process.env.PREFIX?.includes("com.termux")
38
+ ? "termux-open-url"
39
+ : process.platform === "darwin"
40
+ ? "open"
41
+ : process.platform === "win32"
42
+ ? "cmd"
43
+ : "xdg-open";
44
+ const args = command === "cmd" ? ["/c", "start", "", target] : [target];
45
+ try {
46
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
47
+ let settled = false;
48
+ const finish = (ok: boolean) => {
49
+ if (settled) return;
50
+ settled = true;
51
+ resolve(ok);
52
+ };
53
+ child.once("error", () => finish(false));
54
+ child.once("spawn", () => setTimeout(() => finish(true), 2_000));
55
+ child.once("exit", (code) => finish(code === 0));
56
+ child.unref();
57
+ } catch {
58
+ resolve(false);
59
+ }
60
+ });
61
+ }
@@ -0,0 +1,25 @@
1
+ /** Device metadata reported to free-pi during sign-in. */
2
+
3
+ export function deviceReport(): { timezone?: string; locale?: string } {
4
+ try {
5
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions();
6
+ return {
7
+ ...(timeZone ? { timezone: timeZone } : {}),
8
+ ...(locale ? { locale } : {}),
9
+ };
10
+ } catch {
11
+ return {};
12
+ }
13
+ }
14
+
15
+ export function adClientHeaders(): Record<string, string> {
16
+ const headers: Record<string, string> = {};
17
+ if (process.platform) headers["x-client-os"] = process.platform;
18
+ if (process.arch) headers["x-client-arch"] = process.arch;
19
+ try {
20
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions();
21
+ if (timeZone) headers["x-client-timezone"] = timeZone;
22
+ if (locale) headers["x-client-locale"] = locale;
23
+ } catch {}
24
+ return headers;
25
+ }
@@ -0,0 +1,56 @@
1
+ /** JSON request helpers for the free-pi HTTP API. */
2
+
3
+ import { sleep } from "./async.js";
4
+ import { resolveBaseUrl } from "./urls.js";
5
+
6
+ export async function postJson(
7
+ path: string,
8
+ body: unknown,
9
+ headers: Record<string, string> = {},
10
+ ): Promise<Response> {
11
+ return fetch(new URL(path, resolveBaseUrl()), {
12
+ method: "POST",
13
+ headers: { "content-type": "application/json", ...headers },
14
+ body: JSON.stringify(body),
15
+ signal: AbortSignal.timeout(20_000),
16
+ });
17
+ }
18
+
19
+ export async function postJsonRetry(
20
+ path: string,
21
+ body: unknown,
22
+ headers: Record<string, string> = {},
23
+ ): Promise<Response> {
24
+ let lastError: unknown;
25
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
26
+ try {
27
+ return await postJson(path, body, headers);
28
+ } catch (error) {
29
+ lastError = error;
30
+ if (attempt < 3) await sleep(1_500 * attempt);
31
+ }
32
+ }
33
+ throw lastError instanceof Error
34
+ ? lastError
35
+ : new Error(
36
+ "Can't reach free-pi. Check your internet connection and try again.",
37
+ );
38
+ }
39
+
40
+ export function failureText(status: number, body: any): string {
41
+ if (status === 429) {
42
+ return "Too many sign-in attempts from your network. Wait a minute and try again.";
43
+ }
44
+ if (
45
+ status >= 400 &&
46
+ status < 500 &&
47
+ typeof body?.message === "string" &&
48
+ body.message.trim()
49
+ ) {
50
+ return body.message.trim();
51
+ }
52
+ if (status >= 500) {
53
+ return `free-pi is having trouble right now (HTTP ${status}). Try again in a minute.`;
54
+ }
55
+ return `free-pi could not complete sign-in (HTTP ${status}). Try again in a minute.`;
56
+ }
@@ -0,0 +1,9 @@
1
+ /** Safe JSON response parsing. */
2
+
3
+ export async function readJson(response: Response): Promise<any> {
4
+ try {
5
+ return await response.json();
6
+ } catch {
7
+ return undefined;
8
+ }
9
+ }
@@ -0,0 +1,52 @@
1
+ /** Numeric and human-readable formatting helpers. */
2
+
3
+ import { CREDITS_PER_USD } from "../constants.js";
4
+
5
+ export function duplicateNumber(value: unknown): number | undefined {
6
+ return typeof value === "number" && Number.isFinite(value) && value > 0
7
+ ? value
8
+ : undefined;
9
+ }
10
+
11
+ export function positiveNumber(
12
+ ...values: Array<number | undefined>
13
+ ): number | undefined {
14
+ for (const value of values) {
15
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
16
+ return value;
17
+ }
18
+ }
19
+ return undefined;
20
+ }
21
+
22
+ export function creditsToUsd(credits: number | undefined): number {
23
+ return typeof credits === "number" && Number.isFinite(credits) && credits > 0
24
+ ? credits / CREDITS_PER_USD
25
+ : 0;
26
+ }
27
+
28
+ export function formatRefillTime(value: string | undefined): string {
29
+ if (!value) return "unknown";
30
+ const date = new Date(value);
31
+ if (Number.isNaN(date.getTime())) return "unknown";
32
+ try {
33
+ return date.toLocaleString("en-US", {
34
+ hour: "numeric",
35
+ minute: "2-digit",
36
+ timeZoneName: "short",
37
+ });
38
+ } catch {
39
+ return date.toISOString();
40
+ }
41
+ }
42
+
43
+ export function formatWait(seconds: number | undefined): string | undefined {
44
+ if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0)
45
+ return undefined;
46
+ const minutes = Math.ceil(seconds / 60);
47
+ if (minutes <= 1) return "about a minute";
48
+ if (minutes < 60) return `about ${minutes}m`;
49
+ const hours = Math.floor(minutes / 60);
50
+ const rest = minutes % 60;
51
+ return rest ? `about ${hours}h ${rest}m` : `about ${hours}h`;
52
+ }
@@ -0,0 +1,7 @@
1
+ /** Text helpers shared by ads and sign-in. */
2
+
3
+ export function cleanText(value: unknown): string {
4
+ return typeof value === "string"
5
+ ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim()
6
+ : "";
7
+ }
@@ -0,0 +1,47 @@
1
+ /** URL resolution and validation. */
2
+
3
+ import {
4
+ DEFAULT_BASE_URL,
5
+ DEFAULT_MODELS_REGISTRY_URL,
6
+ } from "../constants.js";
7
+
8
+ export function resolveBaseUrl(): string {
9
+ const configured = process.env.FREEPI_BASE_URL?.trim();
10
+ return (configured || DEFAULT_BASE_URL).replace(/\/+$/, "");
11
+ }
12
+
13
+ export function completionsBaseUrl(): string {
14
+ const base = resolveBaseUrl();
15
+ return base.endsWith("/v1") ? base : `${base}/v1`;
16
+ }
17
+
18
+ export function modelsRegistryUrl(): string {
19
+ const configured =
20
+ process.env.FREEPI_MODELS_URL?.trim() ||
21
+ process.env.OPENCODE_MODELS_URL?.trim();
22
+ return (configured || DEFAULT_MODELS_REGISTRY_URL).replace(/\/+$/, "");
23
+ }
24
+
25
+ export function normalizeIssuer(value: unknown): string | undefined {
26
+ if (typeof value !== "string") return undefined;
27
+ try {
28
+ const parsed = new URL(value);
29
+ return parsed.protocol === "https:" || parsed.protocol === "http:"
30
+ ? parsed.origin
31
+ : undefined;
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ export function safeUrl(value: unknown): string | undefined {
38
+ if (typeof value !== "string") return undefined;
39
+ try {
40
+ const parsed = new URL(value.trim());
41
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
42
+ return undefined;
43
+ return parsed.toString();
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }