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