@eduardo191labs/opencode-free-pi 0.2.6 → 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,55 @@
1
+ /** Identifiers and defaults shared by every part of the plugin. */
2
+
3
+ export const PROVIDER_ID = "free-pi";
4
+ export const DEFENSE_PROVIDER_ID = "free-pi-defense";
5
+ export const INTEGRATION_ID = PROVIDER_ID;
6
+
7
+ export const PROVIDER_NAME = "Free Pi";
8
+ export const DEFENSE_PROVIDER_NAME = "Free Pi Defense";
9
+
10
+ export const DEFAULT_BASE_URL = "https://api.freepi.ai";
11
+ export const DEFAULT_CLIENT_VERSION = "0.6.25";
12
+ export const CONSENT_VERSION = "4";
13
+
14
+ export const CONTEXT_WINDOW = 200_000;
15
+ export const MAX_OUTPUT_TOKENS = 32_768;
16
+
17
+ export const AD_CONTEXT_HEADER = "x-ad-context";
18
+ export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
19
+ export const EFFICIENCY_RULE =
20
+ "- When several independent reads or searches are needed, issue them in the same turn.";
21
+
22
+ export const SESSION_TRACK_LIMIT = 200;
23
+ export const AUTH_SKEW_MS = 60_000;
24
+ export const AUTH_TIMEOUT_MS = 15 * 60_000;
25
+ export const AUTH_NETWORK_FAILURES = 6;
26
+ export const DEFAULT_TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60_000;
27
+ export const REFRESH_PREFIX = "free-pi:v1:";
28
+
29
+ export const AD_CONTEXT_MAX_CHARS = 1_000;
30
+ export const AD_REQUEST_TIMEOUT_MS = 5_000;
31
+ export const AD_IMPRESSION_TIMEOUT_MS = 3_000;
32
+ export const AD_TURN_LIMIT = 200;
33
+ export const AD_IMPRESSION_LIMIT = 200;
34
+
35
+ export const CREDITS_PER_USD = 40_000 / 3;
36
+
37
+ export const CATALOG_TTL_MS = 10 * 60_000;
38
+ export const REGISTRY_TTL_MS = 5 * 60_000;
39
+ export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
40
+
41
+ export const QUOTA_TTL_MS = 30_000;
42
+ export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
43
+ export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
44
+
45
+ export const SESSION_RESET_COOLDOWN_MS = 15_000;
46
+
47
+ /**
48
+ * How long a free-pi session must stay quiet before its server slot is closed.
49
+ * Background compaction can start right after the last step, so closing on the
50
+ * execution event alone would race with it.
51
+ */
52
+ export const SESSION_FINALIZE_DELAY_MS = 2_000;
53
+
54
+ export const OPENAI_COMPATIBLE_PACKAGE =
55
+ "@opencode/ai/providers/openai-compatible";
package/src/deps.ts ADDED
@@ -0,0 +1,13 @@
1
+ /** Dependencies shared by the free-pi modules. */
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 type { ReadContext } from "./types.js";
7
+
8
+ export type Deps = {
9
+ readonly state: RuntimeState;
10
+ readonly log: Logger;
11
+ readonly activeCredential: () => Promise<Credential.Value | undefined>;
12
+ readonly readContext: ReadContext;
13
+ };
@@ -0,0 +1,79 @@
1
+ /** Central handling for free-pi failures reported by the provider or session. */
2
+
3
+ import { fetchQuota, rememberTokenCheck } from "../api/quota.js";
4
+ import { resetFreePiSessions } from "../api/session.js";
5
+ import type { Deps } from "../deps.js";
6
+ import type { SessionResetOutcome } from "../types.js";
7
+ import { logInvalidToken } from "./invalid.js";
8
+ import {
9
+ freePiErrorSeverity,
10
+ freePiErrorTitle,
11
+ friendlyFreePiError,
12
+ } from "./messages.js";
13
+ import { parseFreePiError } from "./parse.js";
14
+
15
+ export async function handleFreePiError(
16
+ deps: Deps,
17
+ error: any,
18
+ opts: { allowRaw?: boolean } = {},
19
+ ): Promise<void> {
20
+ const parsed = parseFreePiError(error, opts.allowRaw === true);
21
+ if (!parsed) return;
22
+ deps.state.lastFreePiError = parsed;
23
+
24
+ if (
25
+ parsed.status === 401 ||
26
+ parsed.code === "unauthorized" ||
27
+ parsed.code === "expired_token"
28
+ ) {
29
+ const token = deps.state.quotaCache?.token;
30
+ if (token) rememberTokenCheck(deps, token, "invalid");
31
+ await logInvalidToken(deps, token);
32
+ void fetchQuota(deps, { force: true }).catch(() => undefined);
33
+ return;
34
+ }
35
+
36
+ let message = friendlyFreePiError(parsed);
37
+ let resetOutcome: SessionResetOutcome | undefined;
38
+ if (parsed.code === "concurrent_session") {
39
+ resetOutcome = await resetFreePiSessions(deps);
40
+ if (resetOutcome === "released") {
41
+ message =
42
+ "free-pi was at its session limit; freed a stale slot automatically. Retry your request now.";
43
+ } else if (resetOutcome === "none") {
44
+ message =
45
+ "free-pi is at its session limit and no other session was running. Wait for a slot to free up and retry.";
46
+ } else if (resetOutcome === "failed" || resetOutcome === "unavailable") {
47
+ message =
48
+ "free-pi is at its session limit and the slot could not be freed automatically. Wait a moment and retry.";
49
+ } else {
50
+ message =
51
+ "free-pi session reset was just attempted; retry in a moment.";
52
+ }
53
+ }
54
+
55
+ const key = `${parsed.code}\u0000${parsed.message ?? ""}`;
56
+ const now = Date.now();
57
+ if (key !== deps.state.lastErrorLogKey || now - deps.state.lastErrorLogAt > 15_000) {
58
+ deps.state.lastErrorLogKey = key;
59
+ deps.state.lastErrorLogAt = now;
60
+ const level = freePiErrorSeverity(parsed);
61
+ deps.log.log(level, `${freePiErrorTitle(parsed)}: ${message}`, {
62
+ code: parsed.code,
63
+ status: parsed.status,
64
+ limit: parsed.limit,
65
+ retry_after_seconds: parsed.retry_after_seconds,
66
+ clears_at: parsed.clears_at,
67
+ reset: resetOutcome,
68
+ });
69
+ }
70
+
71
+ if (
72
+ parsed.status === 402 ||
73
+ parsed.status === 403 ||
74
+ parsed.status === 429 ||
75
+ parsed.limit !== undefined
76
+ ) {
77
+ void fetchQuota(deps, { force: true }).catch(() => undefined);
78
+ }
79
+ }
@@ -0,0 +1,15 @@
1
+ /** Warns once when the stored free-pi credential is rejected. */
2
+
3
+ import type { Deps } from "../deps.js";
4
+
5
+ export async function logInvalidToken(
6
+ deps: Deps,
7
+ token?: string,
8
+ ): Promise<void> {
9
+ const key = token ?? "(none)";
10
+ if (deps.state.lastInvalidToken === key) return;
11
+ deps.state.lastInvalidToken = key;
12
+ deps.log.warn(
13
+ "free-pi sign-in is invalid or expired. Run `opencode auth login -p free-pi` to sign in again.",
14
+ );
15
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Rewrites long-lived free-pi limit responses so the client shows the friendly
3
+ * message instead of a raw 429. Mirrors the fetch wrapper used by the V1 plugin.
4
+ */
5
+
6
+ import type { FreePiError } from "../types.js";
7
+ import { friendlyFreePiError } from "./messages.js";
8
+
9
+ const LONG_LIMIT_CODES = new Set([
10
+ "hourly_ceiling",
11
+ "daily_cap",
12
+ "rolling_cap",
13
+ "global_cap",
14
+ "premium_allowance",
15
+ "guest_allowance",
16
+ "concurrent_session",
17
+ "model_requires_credits",
18
+ "insufficient_credits",
19
+ "ads_required",
20
+ "account_review",
21
+ "account_ceiling",
22
+ "region_unavailable",
23
+ ]);
24
+
25
+ type LimitInfo = {
26
+ code?: string;
27
+ retryAfterSeconds?: number;
28
+ };
29
+
30
+ function retryAfterSeconds(response: Response): number | undefined {
31
+ const retryAfter = response.headers.get("retry-after");
32
+ if (retryAfter) {
33
+ const seconds = Number.parseFloat(retryAfter);
34
+ if (!Number.isNaN(seconds)) return seconds;
35
+ const at = Date.parse(retryAfter);
36
+ if (!Number.isNaN(at)) return Math.max(0, (at - Date.now()) / 1000);
37
+ }
38
+ const retryAfterMs = response.headers.get("retry-after-ms");
39
+ if (retryAfterMs) {
40
+ const ms = Number.parseFloat(retryAfterMs);
41
+ if (!Number.isNaN(ms)) return ms / 1000;
42
+ }
43
+ return undefined;
44
+ }
45
+
46
+ function limitInfo(body: string, response: Response): LimitInfo | undefined {
47
+ let code: string | undefined;
48
+ let seconds: number | undefined;
49
+ try {
50
+ const data = JSON.parse(body);
51
+ const rawCode = data?.code ?? data?.error?.code ?? data?.limit;
52
+ if (typeof rawCode === "string") code = rawCode;
53
+ if (typeof data?.retry_after_seconds === "number") {
54
+ seconds = data.retry_after_seconds;
55
+ }
56
+ } catch {}
57
+ seconds ??= retryAfterSeconds(response);
58
+ if (code && LONG_LIMIT_CODES.has(code)) return { code, retryAfterSeconds: seconds };
59
+ if (seconds !== undefined && seconds > 120) {
60
+ return { code, retryAfterSeconds: seconds };
61
+ }
62
+ return undefined;
63
+ }
64
+
65
+ function friendlyBody(body: string, info: LimitInfo): string {
66
+ try {
67
+ const data = JSON.parse(body);
68
+ if (!data || typeof data !== "object") return body;
69
+ const error: FreePiError = {
70
+ status: 429,
71
+ code: info.code ?? "unknown",
72
+ message: typeof data.message === "string" ? data.message : undefined,
73
+ retry_after_seconds: info.retryAfterSeconds,
74
+ clears_at: typeof data.clears_at === "string" ? data.clears_at : undefined,
75
+ limit: typeof data.limit === "string" ? data.limit : undefined,
76
+ };
77
+ const friendly = friendlyFreePiError(error);
78
+ data.message = friendly;
79
+ if (data.error && typeof data.error === "object") {
80
+ data.error.message = friendly;
81
+ }
82
+ return JSON.stringify(data);
83
+ } catch {
84
+ return body;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Returns a replacement response when `response` is a 429 that represents a
90
+ * long-lived limit. The replacement is a 400 with the same body but a friendly
91
+ * message, so the model error surface reads it like any other failure.
92
+ */
93
+ export async function rewriteLimitResponse(
94
+ response: Response,
95
+ ): Promise<Response | undefined> {
96
+ if (response.status !== 429) return undefined;
97
+ const body = await response
98
+ .clone()
99
+ .text()
100
+ .catch(() => "");
101
+ if (!body) return undefined;
102
+ const info = limitInfo(body, response);
103
+ if (!info) return undefined;
104
+
105
+ const headers = new Headers(response.headers);
106
+ headers.delete("retry-after");
107
+ headers.delete("retry-after-ms");
108
+ headers.set("x-free-pi-original-status", "429");
109
+ return new Response(friendlyBody(body, info), {
110
+ status: 400,
111
+ statusText: "Bad Request",
112
+ headers,
113
+ });
114
+ }
@@ -0,0 +1,151 @@
1
+ /** Human-readable copy for free-pi error codes. */
2
+
3
+ import type { FreePiError } from "../types.js";
4
+ import { formatRefillTime, formatWait } from "../utils/numbers.js";
5
+
6
+ const FREE_PI_ERROR_TEXT: Record<string, string> = {
7
+ daily_cap: "Out of free credits today; refills at UTC midnight.",
8
+ queue_wait: "free-pi is near its daily budget; wait and retry.",
9
+ rolling_cap:
10
+ "Over the rolling spend cap on the free tier; wait for the retry window.",
11
+ concurrent:
12
+ "Only one request at a time on the free tier; wait for the current one to finish.",
13
+ concurrent_session:
14
+ "This account is already at its free-pi session limit. Wait for a slot to free up and retry.",
15
+ context_ceiling:
16
+ "This conversation is too large for free-pi's context limit.",
17
+ upstream_error: "Upstream model provider had an issue; retry.",
18
+ global_cap: "free-pi is over its shared daily budget; back tomorrow.",
19
+ consent_required:
20
+ "Consent required. Run `opencode auth login -p free-pi` to review the terms.",
21
+ upgrade_required:
22
+ "The free-pi client is out of date; update the plugin or free-pi-cli.",
23
+ hourly_ceiling: "Daily allowance still applies; it refills at midnight UTC.",
24
+ account_review: "This account is under review; contact support.",
25
+ ads_required:
26
+ "Ads are not displaying for this account, so free completions are paused. Run `npx free-pi-cli@latest` so ads can show, then retry.",
27
+ guest_allowance:
28
+ "Guest trial used up; sign in with GitHub for a larger allowance.",
29
+ guest_unavailable: "Guest access is unavailable right now.",
30
+ guest_login_required: "This needs a GitHub sign-in.",
31
+ region_unavailable: "free-pi is not available in your region.",
32
+ model_requires_credits:
33
+ "This model needs purchased or premium credits. Switch to a free model.",
34
+ premium_allowance:
35
+ "Premium allowance used up; switch to a free model or add credits to your account.",
36
+ model_at_capacity: "This model is busy right now; retry or switch models.",
37
+ context_too_long_for_fallback:
38
+ "This conversation is too long for this model; compact it or switch models.",
39
+ context_too_long:
40
+ "This conversation is too long; compact it or start a new session.",
41
+ reward_required: "This model is only for reward holders.",
42
+ subagents_unavailable:
43
+ "Subagents need the free Particle model or purchased credits.",
44
+ unauthorized:
45
+ "free-pi sign-in is invalid or expired. Run `opencode auth login -p free-pi` to sign in again.",
46
+ expired_token:
47
+ "free-pi sign-in expired. Run `opencode auth login -p free-pi` to sign in again.",
48
+ insufficient_credits:
49
+ "This account does not have enough credits for the request. Add credits or switch to a free model.",
50
+ network_error:
51
+ "Cannot reach free-pi right now. Check your connection and retry.",
52
+ timeout: "The free-pi request timed out. Retry in a moment.",
53
+ rate_limited: "free-pi is rate limiting requests. Wait a moment and retry.",
54
+ content_filter:
55
+ "The model's reply was blocked by a content filter. Try rephrasing.",
56
+ };
57
+
58
+ const FREE_PI_ERROR_TITLE: Record<string, string> = {
59
+ daily_cap: "free-pi daily limit",
60
+ queue_wait: "free-pi budget",
61
+ rolling_cap: "free-pi budget",
62
+ global_cap: "free-pi budget",
63
+ hourly_ceiling: "free-pi allowance",
64
+ concurrent: "free-pi busy",
65
+ concurrent_session: "free-pi session limit",
66
+ ads_required: "free-pi ads",
67
+ unauthorized: "free-pi sign-in",
68
+ expired_token: "free-pi sign-in",
69
+ guest_allowance: "free-pi sign-in",
70
+ guest_login_required: "free-pi sign-in",
71
+ guest_unavailable: "free-pi sign-in",
72
+ consent_required: "free-pi consent",
73
+ upgrade_required: "free-pi update",
74
+ region_unavailable: "free-pi unavailable",
75
+ account_review: "free-pi account",
76
+ model_requires_credits: "free-pi credits",
77
+ premium_allowance: "free-pi credits",
78
+ insufficient_credits: "free-pi credits",
79
+ model_at_capacity: "free-pi model",
80
+ context_ceiling: "free-pi context",
81
+ context_too_long: "free-pi context",
82
+ context_too_long_for_fallback: "free-pi context",
83
+ reward_required: "free-pi model",
84
+ subagents_unavailable: "free-pi subagents",
85
+ network_error: "free-pi connection",
86
+ timeout: "free-pi timeout",
87
+ rate_limited: "free-pi busy",
88
+ content_filter: "free-pi response",
89
+ upstream_error: "free-pi upstream",
90
+ };
91
+
92
+ const ERROR_SEVERITY_CODES = new Set([
93
+ "unauthorized",
94
+ "expired_token",
95
+ "ads_required",
96
+ "account_review",
97
+ "region_unavailable",
98
+ "insufficient_credits",
99
+ "model_requires_credits",
100
+ "premium_allowance",
101
+ "guest_allowance",
102
+ "guest_login_required",
103
+ "subagents_unavailable",
104
+ "reward_required",
105
+ "content_filter",
106
+ ]);
107
+
108
+ export function freePiErrorTitle(error: FreePiError): string {
109
+ return FREE_PI_ERROR_TITLE[error.code] ?? "free-pi error";
110
+ }
111
+
112
+ export function freePiErrorSeverity(error: FreePiError): "warn" | "error" {
113
+ return ERROR_SEVERITY_CODES.has(error.code) ? "error" : "warn";
114
+ }
115
+
116
+ export function errorResetHint(error: FreePiError): string | undefined {
117
+ if (error.clears_at) {
118
+ const formatted = formatRefillTime(error.clears_at);
119
+ if (formatted !== "unknown") return `at ${formatted}`;
120
+ }
121
+ const wait = formatWait(error.retry_after_seconds);
122
+ return wait ? `in ${wait}` : undefined;
123
+ }
124
+
125
+ export function friendlyFreePiError(error: FreePiError): string {
126
+ const reset = errorResetHint(error);
127
+ if (error.code === "hourly_ceiling") {
128
+ return `This account hit its hourly limit; ${
129
+ reset ? `it resets ${reset}` : "wait for it to reset"
130
+ }. Switch models or retry later.`;
131
+ }
132
+ if (error.code === "daily_cap") {
133
+ return `Out of free credits today; ${
134
+ reset ? `it resets ${reset}` : "it refills at UTC midnight"
135
+ }.`;
136
+ }
137
+ if (error.code === "rolling_cap") {
138
+ return `Over the rolling spend cap; ${
139
+ reset ? `retry ${reset}` : "wait for the retry window"
140
+ }.`;
141
+ }
142
+ if (error.code === "queue_wait") {
143
+ return `free-pi is near its daily budget; ${reset ? `retry ${reset}` : "wait and retry"}.`;
144
+ }
145
+ const known = FREE_PI_ERROR_TEXT[error.code];
146
+ if (known) return known;
147
+ if (error.message?.trim()) return error.message.trim();
148
+ return `free-pi request failed${error.status ? ` (HTTP ${error.status})` : ""}${
149
+ error.code ? ` [${error.code}]` : ""
150
+ }.`;
151
+ }
@@ -0,0 +1,156 @@
1
+ /** Extracts a structured free-pi error from provider or session errors. */
2
+
3
+ import type { FreePiError } from "../types.js";
4
+
5
+ const RAW_FREE_PI_ERROR_PATTERNS: Array<[RegExp, string]> = [
6
+ [
7
+ /\b(?:econnreset|econnrefused|eai_again|eproto|enotfound|etimedout)\b|socket connection was closed|cannot connect to api|unable to connect|tls handshake failed|fetch failed|connection (?:error|reset|closed)/i,
8
+ "network_error",
9
+ ],
10
+ [/request timed out|timed out|timeout/i, "timeout"],
11
+ [
12
+ /already got \d+ free-pi cli sessions|free-pi cli sessions running|session limit|concurrent_session/i,
13
+ "concurrent_session",
14
+ ],
15
+ [
16
+ /\bads\b.*\b(?:pay|showing|paused|skipped)\b|free-pi is free because ads/i,
17
+ "ads_required",
18
+ ],
19
+ [
20
+ /model needs (?:premium|purchased) credits|needs premium credits|model_requires_credits/i,
21
+ "model_requires_credits",
22
+ ],
23
+ [
24
+ /premium allowance (?:used up|exhausted)|premium_allowance/i,
25
+ "premium_allowance",
26
+ ],
27
+ [
28
+ /insufficient credits|not enough credits|insufficient_credits/i,
29
+ "insufficient_credits",
30
+ ],
31
+ [/guest trial used up|guest_allowance/i, "guest_allowance"],
32
+ [
33
+ /needs a github sign-in|sign in with github|guest_login_required/i,
34
+ "guest_login_required",
35
+ ],
36
+ [/not available in your region|region_unavailable/i, "region_unavailable"],
37
+ [/account is under review|account_review/i, "account_review"],
38
+ [/consent required|consent_required/i, "consent_required"],
39
+ [
40
+ /(?:client|cli|version).*(?:out of date|upgrade)|upgrade required|upgrade_required/i,
41
+ "upgrade_required",
42
+ ],
43
+ [
44
+ /content filter|blocked by a content filter|content_filter/i,
45
+ "content_filter",
46
+ ],
47
+ [
48
+ /subagents? (?:need|run)|subagents unavailable|subagents_unavailable/i,
49
+ "subagents_unavailable",
50
+ ],
51
+ [/reward holders?|reward_required/i, "reward_required"],
52
+ [
53
+ /model (?:is )?busy|model at capacity|at capacity|model_at_capacity/i,
54
+ "model_at_capacity",
55
+ ],
56
+ [
57
+ /(?:conversation|context).*(?:too long|too large)|maximum context|context (?:window|length)|context_ceiling|context_too_long/i,
58
+ "context_too_long",
59
+ ],
60
+ [
61
+ /out of free credits|daily (?:free )?(?:credits|limit)|free allowance (?:is )?(?:used up|exhausted)|allowance used up|daily_cap/i,
62
+ "daily_cap",
63
+ ],
64
+ [/rate.?limit|too many requests|rate_limited/i, "rate_limited"],
65
+ [
66
+ /upstream .*error|provider is failing|upstream returned an error|upstream_error/i,
67
+ "upstream_error",
68
+ ],
69
+ [
70
+ /sign-in (?:is )?(?:invalid|expired)|invalid or expired|unauthorized|expired token|expired_token/i,
71
+ "unauthorized",
72
+ ],
73
+ ];
74
+
75
+ function statusOf(error: any): number | undefined {
76
+ if (typeof error?.status === "number") return error.status;
77
+ if (typeof error?.data?.statusCode === "number") return error.data.statusCode;
78
+ if (typeof error?.statusCode === "number") return error.statusCode;
79
+ return undefined;
80
+ }
81
+
82
+ export function parseRawFreePiError(error: any): FreePiError | undefined {
83
+ const raw = error?.data?.message ?? error?.message;
84
+ if (typeof raw !== "string" || !raw.trim()) return undefined;
85
+ const text = raw.trim();
86
+ if (/^\d{3}: \{/.test(text)) return undefined;
87
+ const status = statusOf(error);
88
+ for (const [pattern, code] of RAW_FREE_PI_ERROR_PATTERNS) {
89
+ if (pattern.test(text)) return { status, code, message: text };
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ export function parseFreePiError(
95
+ error: any,
96
+ allowRaw = false,
97
+ ): FreePiError | undefined {
98
+ const candidates = [
99
+ error?.response?.body,
100
+ error?.data?.responseBody,
101
+ error?.responseBody,
102
+ error?.data?.message,
103
+ error?.message,
104
+ ];
105
+ for (const raw of candidates) {
106
+ let status = statusOf(error);
107
+ let body: any;
108
+ if (raw && typeof raw === "object") {
109
+ body = raw;
110
+ } else if (typeof raw === "string") {
111
+ const text = raw.trim();
112
+ try {
113
+ body = JSON.parse(text);
114
+ } catch {
115
+ const match = /^(\d{3}): (\{[\s\S]*\})\s*$/.exec(text);
116
+ if (match) {
117
+ status = Number(match[1]);
118
+ try {
119
+ body = JSON.parse(match[2]);
120
+ } catch {}
121
+ }
122
+ }
123
+ }
124
+ if (!body || typeof body !== "object") continue;
125
+ const codeValue = body.code ?? body.error?.code;
126
+ const message = body.message ?? body.error?.message;
127
+ const code =
128
+ typeof codeValue === "string"
129
+ ? codeValue
130
+ : status === 401
131
+ ? "unauthorized"
132
+ : undefined;
133
+ if (!code && typeof message !== "string") continue;
134
+ return {
135
+ status: typeof body.status === "number" ? body.status : status,
136
+ code: code ?? "unknown",
137
+ message: typeof message === "string" ? message : undefined,
138
+ limit: typeof body.limit === "string" ? body.limit : undefined,
139
+ retry_after_seconds:
140
+ typeof body.retry_after_seconds === "number"
141
+ ? body.retry_after_seconds
142
+ : undefined,
143
+ clears_at:
144
+ typeof body.clears_at === "string" ? body.clears_at : undefined,
145
+ remaining_credits_today:
146
+ typeof body.remaining_credits_today === "number"
147
+ ? body.remaining_credits_today
148
+ : undefined,
149
+ allowance_credits:
150
+ typeof body.allowance_credits === "number"
151
+ ? body.allowance_credits
152
+ : undefined,
153
+ };
154
+ }
155
+ return allowRaw ? parseRawFreePiError(error) : undefined;
156
+ }