@eduardo191labs/opencode-free-pi 0.7.27 → 0.7.30
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 +48 -108
- package/dist/constants.d.ts +0 -22
- package/dist/constants.js +0 -22
- package/dist/deps.d.ts +1 -4
- package/dist/index.d.ts +1 -1
- package/dist/legacy.d.ts +17 -0
- package/dist/legacy.js +58 -0
- package/dist/plugin.js +7 -84
- package/dist/session/events.js +5 -12
- package/dist/session/hooks.js +9 -185
- package/dist/session/tools.d.ts +1 -1
- package/dist/session/tools.js +0 -1
- package/dist/session/track.d.ts +2 -0
- package/dist/session/track.js +5 -0
- package/dist/state.d.ts +1 -3
- package/dist/types.d.ts +0 -11
- package/package.json +2 -2
- package/src/constants.ts +0 -25
- package/src/deps.ts +1 -8
- package/src/index.ts +0 -1
- package/src/legacy.ts +62 -0
- package/src/plugin.ts +8 -97
- package/src/session/events.ts +5 -12
- package/src/session/hooks.ts +8 -224
- package/src/session/tools.ts +0 -1
- package/src/session/track.ts +11 -0
- package/src/state.ts +0 -3
- package/src/types.ts +0 -18
- package/dist/agents/definitions.d.ts +0 -56
- package/dist/agents/definitions.js +0 -317
- package/dist/session/title.d.ts +0 -18
- package/dist/session/title.js +0 -81
- package/dist/session/usage.d.ts +0 -5
- package/dist/session/usage.js +0 -32
- package/dist/tools/subagent.d.ts +0 -29
- package/dist/tools/subagent.js +0 -197
- package/src/agents/definitions.ts +0 -354
- package/src/session/title.ts +0 -90
- package/src/session/usage.ts +0 -46
- package/src/tools/subagent.ts +0 -271
package/dist/session/hooks.js
CHANGED
|
@@ -2,20 +2,17 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
|
-
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT,
|
|
5
|
+
import { AD_CONTEXT_HEADER, AD_CONTEXT_OPT_OUT, CONTEXT_WINDOW, DEFENSE_PROVIDER_ID, PROVIDER_ID, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
6
|
import { currentLiveLimits, noteRejectedPrompt } from "../catalog/live.js";
|
|
7
7
|
import { closeFreePiSession } from "../api/session.js";
|
|
8
8
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
9
|
-
import { parseFreePiError } from "../errors/parse.js";
|
|
10
9
|
import { trimMap } from "../utils/async.js";
|
|
11
10
|
import { watchFreePiNotice } from "./notices.js";
|
|
12
11
|
import { noteSpuriousOverflow, overflowingSpuriously, profileRequest, SPURIOUS_OVERFLOW_SHARE, spuriousOverflowResponse, } from "./overflow.js";
|
|
13
12
|
import { rememberReplayBody, storedBody } from "./replay.js";
|
|
14
|
-
import {
|
|
15
|
-
import { rememberFreePiSession } from "./track.js";
|
|
13
|
+
import { rememberFreePiSession, rememberTrackedModel } from "./track.js";
|
|
16
14
|
import { hydrateWireSessionID, markWireSessionDirty, rotateWireSessionID, takeWireSessionDirty, wireSessionID, } from "./wire.js";
|
|
17
15
|
import { FREE_PI_TOOL_NAMES, isFreePiSession, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
18
|
-
import { rememberTrackedModel } from "./usage.js";
|
|
19
16
|
const PENDING_LIMIT = 400;
|
|
20
17
|
/** Each agent gets its own ad turn, so a subagent never reuses the parent's. */
|
|
21
18
|
function pendingKeyOf(sessionID, agent, kind) {
|
|
@@ -33,14 +30,6 @@ async function applyGeneration(deps, event, kind) {
|
|
|
33
30
|
if (!isFreePiProvider(event.model?.providerID))
|
|
34
31
|
return;
|
|
35
32
|
rememberFreePiSession(deps, event.sessionID);
|
|
36
|
-
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
37
|
-
// from the first user message: no free-pi request, no ad impression, and the
|
|
38
|
-
// session leaves the "New session" state immediately.
|
|
39
|
-
if (kind === "title") {
|
|
40
|
-
event.result = localTitle(event.messages);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
// The title agent gets a local answer, so no free-pi request is made.
|
|
44
33
|
const modelID = event.model?.id;
|
|
45
34
|
// Remember the choice so a `model_requires_credits` failure can hide exactly
|
|
46
35
|
// the model that was rejected instead of the whole provider.
|
|
@@ -129,181 +118,17 @@ async function applyModelRequest(deps, event) {
|
|
|
129
118
|
await ensureAdImpression(deps, token, event.sessionID, turn).catch(() => undefined);
|
|
130
119
|
}
|
|
131
120
|
}
|
|
132
|
-
/** `concurrent` is free-pi's per-session 429 ("one request at a time"). */
|
|
133
|
-
function isConcurrentFailure(error) {
|
|
134
|
-
if (!error)
|
|
135
|
-
return false;
|
|
136
|
-
const body = typeof error.response?.body === "string" ? error.response.body : "";
|
|
137
|
-
const message = typeof error.message === "string" ? error.message : "";
|
|
138
|
-
return (/one request at a time/i.test(message) ||
|
|
139
|
-
/one request at a time/i.test(body) ||
|
|
140
|
-
/"concurrent"/.test(body));
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Limits and account blocks do not recover by retrying. pi's own retry helper
|
|
144
|
-
* treats them as terminal (`NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN`), but
|
|
145
|
-
* OpenCode retries every 429 by default, which surfaces as an endless
|
|
146
|
-
* "Retrying…". The response rewrite turns most of these into a 400; this guard
|
|
147
|
-
* covers the rest and keeps the CLI's behavior.
|
|
148
|
-
*/
|
|
149
|
-
const TERMINAL_RETRY_CODES = new Set([
|
|
150
|
-
"daily_cap",
|
|
151
|
-
"hourly_ceiling",
|
|
152
|
-
"rolling_cap",
|
|
153
|
-
"global_cap",
|
|
154
|
-
"account_ceiling",
|
|
155
|
-
"free_usage_limit",
|
|
156
|
-
"premium_allowance",
|
|
157
|
-
"guest_allowance",
|
|
158
|
-
"model_requires_credits",
|
|
159
|
-
"insufficient_credits",
|
|
160
|
-
"ads_required",
|
|
161
|
-
"account_review",
|
|
162
|
-
"region_unavailable",
|
|
163
|
-
"unauthorized",
|
|
164
|
-
"expired_token",
|
|
165
|
-
"guest_login_required",
|
|
166
|
-
"consent_required",
|
|
167
|
-
"upgrade_required",
|
|
168
|
-
"reward_required",
|
|
169
|
-
"content_filter",
|
|
170
|
-
"subagents_unavailable",
|
|
171
|
-
]);
|
|
172
|
-
const TERMINAL_RETRY_PATTERN = /free usage limit|monthly usage limit|available balance|insufficient_quota|out of budget|quota exceeded|billing|subscription_sharing_usage_limit_exceeded/i;
|
|
173
|
-
/**
|
|
174
|
-
* A request that never reached the gateway. `provider.transport` covers the
|
|
175
|
-
* typed path, while the pattern catches bare fetch errors. These are worth
|
|
176
|
-
* retrying beyond the usual budget: a brief offline moment or a background
|
|
177
|
-
* service restart is not a provider limit.
|
|
178
|
-
*/
|
|
179
|
-
const TRANSPORT_RETRY_PATTERN = /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|EHOSTUNREACH|ENETUNREACH|EAI_AGAIN|EPIPE|socket hang up|fetch failed|Unable to connect|connection (?:refused|reset)/i;
|
|
180
|
-
function isTransportFailure(error) {
|
|
181
|
-
const type = typeof error?.type === "string" ? error.type : "";
|
|
182
|
-
if (/transport|network|connection/i.test(type))
|
|
183
|
-
return true;
|
|
184
|
-
const message = `${error?.message ?? ""}\n${error?.cause?.message ?? ""}`;
|
|
185
|
-
return TRANSPORT_RETRY_PATTERN.test(message);
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* A 5xx the gateway itself returned: the request was valid but the server had
|
|
189
|
-
* a bad moment. Measured live: image input on every free model answered 503
|
|
190
|
-
* `image_screen_unavailable` for minutes at a stretch. Retrying is the only
|
|
191
|
-
* useful response, and the wire id rotates because the failed attempt may
|
|
192
|
-
* have left the session slot marked busy.
|
|
193
|
-
*/
|
|
194
|
-
function isServerFailure(error) {
|
|
195
|
-
const status = error?.response?.status ??
|
|
196
|
-
(typeof error?.status === "number" ? error.status : undefined);
|
|
197
|
-
if (typeof status === "number" && status >= 500 && status <= 599) {
|
|
198
|
-
return true;
|
|
199
|
-
}
|
|
200
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
201
|
-
return /server error|temporarily unavailable|try again later|image_screen_unavailable/i.test(message);
|
|
202
|
-
}
|
|
203
|
-
function isTerminalFailure(error) {
|
|
204
|
-
if (error?.type === "aborted" ||
|
|
205
|
-
/aborted|cancelled|canceled|interrupted|AbortError/i.test(`${error?.message ?? ""}`)) {
|
|
206
|
-
return true;
|
|
207
|
-
}
|
|
208
|
-
const parsed = parseFreePiError(error, true);
|
|
209
|
-
if (parsed?.code && TERMINAL_RETRY_CODES.has(parsed.code))
|
|
210
|
-
return true;
|
|
211
|
-
const body = typeof error?.response?.body === "string" ? error.response.body : "";
|
|
212
|
-
const message = typeof error?.message === "string" ? error.message : "";
|
|
213
|
-
return TERMINAL_RETRY_PATTERN.test(`${message}\n${body}`);
|
|
214
|
-
}
|
|
215
121
|
/**
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* and the server can leave a per-session lock behind that resets do not clear.
|
|
222
|
-
* Rotating the wire session id and retrying turns that into a normal retry.
|
|
122
|
+
* Retries belong to OpenCode's session runner: it decides whether an error is
|
|
123
|
+
* retryable, how many times, and the delay. The one thing the runner cannot
|
|
124
|
+
* know is that free-pi holds a per-session request slot and that a failed
|
|
125
|
+
* attempt can leave it marked busy, so the next attempt must use a fresh wire
|
|
126
|
+
* id. This hook only arms that rotation and never touches `decision`.
|
|
223
127
|
*/
|
|
224
128
|
function applyRetryPolicy(deps, event) {
|
|
225
|
-
if (
|
|
226
|
-
if (event.attempt > CONCURRENT_RETRY_MAX) {
|
|
227
|
-
event.decision = { retry: false };
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
const previous = wireSessionID(deps, event.sessionID);
|
|
231
|
-
const next = rotateWireSessionID(deps, event.sessionID);
|
|
232
|
-
// Releasing the old id cleans up an orphaned slot; a leaked live lock
|
|
233
|
-
// ignores reset, which is exactly why the next request uses a fresh id.
|
|
234
|
-
void closeFreePiSession(deps, previous).catch(() => undefined);
|
|
235
|
-
deps.log.info("free-pi session busy; retrying with a fresh session id", {
|
|
236
|
-
sessionID: event.sessionID,
|
|
237
|
-
from: previous,
|
|
238
|
-
to: next,
|
|
239
|
-
attempt: event.attempt,
|
|
240
|
-
});
|
|
241
|
-
event.decision = {
|
|
242
|
-
retry: true,
|
|
243
|
-
delay: Math.min(CONCURRENT_RETRY_BASE_MS * 2 ** (event.attempt - 1), CONCURRENT_RETRY_MAX_DELAY_MS),
|
|
244
|
-
};
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
if (isTerminalFailure(event.error)) {
|
|
248
|
-
// Remember the broken stream too, so the next turn rotates its wire id
|
|
249
|
-
// instead of running into the stale per-session lock.
|
|
250
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
251
|
-
event.decision = { retry: false };
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (isTransportFailure(event.error)) {
|
|
255
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
256
|
-
event.decision = { retry: false };
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
// A connection that dropped mid-turn can leave the gateway's per-session
|
|
260
|
-
// slot marked busy, so the next attempt should not reuse the wire id.
|
|
261
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
262
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
263
|
-
event.decision = {
|
|
264
|
-
retry: true,
|
|
265
|
-
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
266
|
-
};
|
|
267
|
-
deps.log.warn("free-pi could not be reached; retrying", {
|
|
268
|
-
sessionID: event.sessionID,
|
|
269
|
-
attempt: event.attempt,
|
|
270
|
-
delay: event.decision.delay,
|
|
271
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
272
|
-
});
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
// A 5xx from the gateway (`image_screen_unavailable` was measured live as a
|
|
276
|
-
// 503) is the server having a bad moment, not the request being wrong. The
|
|
277
|
-
// default retry would stop after three attempts even though the outage
|
|
278
|
-
// usually clears in seconds, so treat it like a transport failure: rotate
|
|
279
|
-
// the wire id and keep trying within the transport budget.
|
|
280
|
-
if (isServerFailure(event.error)) {
|
|
281
|
-
if (event.attempt > TRANSPORT_RETRY_MAX + 1) {
|
|
282
|
-
event.decision = { retry: false };
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
markWireSessionDirty(deps, event.sessionID);
|
|
286
|
-
const attempt = Math.max(1, event.attempt - 1);
|
|
287
|
-
event.decision = {
|
|
288
|
-
retry: true,
|
|
289
|
-
delay: Math.min(TRANSPORT_RETRY_BASE_MS * 2 ** (attempt - 1), TRANSPORT_RETRY_MAX_DELAY_MS),
|
|
290
|
-
};
|
|
291
|
-
deps.log.warn("free-pi returned a server error; retrying", {
|
|
292
|
-
sessionID: event.sessionID,
|
|
293
|
-
attempt: event.attempt,
|
|
294
|
-
delay: event.decision.delay,
|
|
295
|
-
error: typeof event.error?.message === "string" ? event.error.message : undefined,
|
|
296
|
-
});
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
if (event.attempt > RETRY_MAX_RETRIES + 1) {
|
|
300
|
-
event.decision = { retry: false };
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
if (!event.decision?.retry)
|
|
129
|
+
if (event.decision?.retry !== true)
|
|
304
130
|
return;
|
|
305
|
-
|
|
306
|
-
event.decision.delay = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), RETRY_MAX_DELAY_MS);
|
|
131
|
+
markWireSessionDirty(deps, event.sessionID);
|
|
307
132
|
}
|
|
308
133
|
/**
|
|
309
134
|
* Removes this plugin's tools from a request served by another provider. The
|
|
@@ -497,7 +322,6 @@ export async function registerSessionHooks(ctx, deps) {
|
|
|
497
322
|
await hookForProviders(ctx, "context", generation("primary"), registrations);
|
|
498
323
|
await hookForProviders(ctx, "compaction", generation("compaction"), registrations);
|
|
499
324
|
await hookForProviders(ctx, "generate", generation("generate"), registrations);
|
|
500
|
-
await hookForProviders(ctx, "title", generation("title"), registrations);
|
|
501
325
|
// The generation hooks above only run for free-pi providers. These unscoped
|
|
502
326
|
// ones strip the plugin's tools from every other provider's requests.
|
|
503
327
|
for (const name of ["context", "compaction", "generate"]) {
|
package/dist/session/tools.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ import type { Deps } from "../deps.js";
|
|
|
12
12
|
* served by another provider (see `hideFreePiTools`) and refuses to run them
|
|
13
13
|
* outside a free-pi session.
|
|
14
14
|
*/
|
|
15
|
-
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "
|
|
15
|
+
export declare const FREE_PI_TOOL_NAMES: readonly ["look_at_image", "free_pi_usage", "web_search", "docs_lookup", "generate_image"];
|
|
16
16
|
type ToolResultLike = {
|
|
17
17
|
metadata?: Record<string, unknown>;
|
|
18
18
|
};
|
package/dist/session/tools.js
CHANGED
package/dist/session/track.d.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* later activity instead of running inline with the execution event.
|
|
9
9
|
*/
|
|
10
10
|
import type { Deps } from "../deps.js";
|
|
11
|
+
/** The model a session asked for, used by the tool gate and image handling. */
|
|
12
|
+
export declare function rememberTrackedModel(deps: Deps, sessionID: string, providerID: string, modelID: string): void;
|
|
11
13
|
export declare function rememberFreePiSession(deps: Deps, sessionID: string): void;
|
|
12
14
|
/** Records free-pi activity so a pending close waits for the request to settle. */
|
|
13
15
|
export declare function touchSessionActivity(deps: Deps, sessionID: string): void;
|
package/dist/session/track.js
CHANGED
|
@@ -11,6 +11,11 @@ import { closeFreePiSession } from "../api/session.js";
|
|
|
11
11
|
import { SESSION_FINALIZE_DELAY_MS, SESSION_TRACK_LIMIT, } from "../constants.js";
|
|
12
12
|
import { trimMap, trimSet } from "../utils/async.js";
|
|
13
13
|
import { forgetWireSessionID, wireSessionID } from "./wire.js";
|
|
14
|
+
/** The model a session asked for, used by the tool gate and image handling. */
|
|
15
|
+
export function rememberTrackedModel(deps, sessionID, providerID, modelID) {
|
|
16
|
+
trimMap(deps.state.trackedModels, 200);
|
|
17
|
+
deps.state.trackedModels.set(sessionID, { providerID, modelID });
|
|
18
|
+
}
|
|
14
19
|
export function rememberFreePiSession(deps, sessionID) {
|
|
15
20
|
if (!sessionID)
|
|
16
21
|
return;
|
package/dist/state.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Per-plugin-instance mutable state. */
|
|
2
|
-
import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot,
|
|
2
|
+
import type { AdTurn, Catalog, FreePiError, ModelRegistry, QuotaSnapshot, SessionResetOutcome, TokenCheckState, ToolStats, TrackedModel } from "./types.js";
|
|
3
3
|
export type RuntimeState = {
|
|
4
4
|
latestClientVersion: string;
|
|
5
5
|
providerToken?: string;
|
|
@@ -18,8 +18,6 @@ export type RuntimeState = {
|
|
|
18
18
|
quotaCache?: QuotaSnapshot;
|
|
19
19
|
quotaPromise?: Promise<QuotaSnapshot>;
|
|
20
20
|
lastQuotaRefreshAt: number;
|
|
21
|
-
lastUsage?: RequestUsage;
|
|
22
|
-
lastUsageMessageID?: string;
|
|
23
21
|
lastFreePiError?: FreePiError;
|
|
24
22
|
lastErrorLogKey?: string;
|
|
25
23
|
lastErrorLogAt: number;
|
package/dist/types.d.ts
CHANGED
|
@@ -298,14 +298,3 @@ export type SessionMessageInfo = {
|
|
|
298
298
|
[key: string]: unknown;
|
|
299
299
|
};
|
|
300
300
|
export type ReadContext = (sessionID: string) => Promise<readonly SessionMessageInfo[]>;
|
|
301
|
-
/** Minimal view of an OpenCode V2 session header. */
|
|
302
|
-
export type SubagentSessionInfo = {
|
|
303
|
-
id: string;
|
|
304
|
-
parentID?: string;
|
|
305
|
-
title?: string;
|
|
306
|
-
agent?: string;
|
|
307
|
-
outcome?: string;
|
|
308
|
-
updated?: number;
|
|
309
|
-
};
|
|
310
|
-
export type ReadSessionInfo = (sessionID: string) => Promise<SubagentSessionInfo | undefined>;
|
|
311
|
-
export type ListSubagentSessions = (parentID: string) => Promise<readonly SubagentSessionInfo[]>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.30",
|
|
4
4
|
"description": "Ad-supported free-pi provider plugin for OpenCode on Windows, Linux, macOS and Termux",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
|
|
26
26
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
-
"test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/
|
|
27
|
+
"test": "npm run build && node test/catalog.mjs && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/live.mjs && node test/hooks.mjs && node test/errors.mjs && node test/overflow.mjs && node test/vision.mjs && node test/legacy.mjs && node test/wire.mjs && node test/network.mjs && node test/tools.mjs && node test/slots.mjs",
|
|
28
28
|
"prepublishOnly": "npm run build",
|
|
29
29
|
"postinstall": "node scripts/postinstall.mjs"
|
|
30
30
|
},
|
package/src/constants.ts
CHANGED
|
@@ -83,30 +83,6 @@ export const DEFAULT_THINKING_LEVELS = [
|
|
|
83
83
|
export const HEADER_TIMEOUT_MS = 300_000;
|
|
84
84
|
export const CHUNK_TIMEOUT_MS = 300_000;
|
|
85
85
|
|
|
86
|
-
/** pi's retry policy: 3 retries, 2s base, 60s cap. */
|
|
87
|
-
export const RETRY_MAX_RETRIES = 3;
|
|
88
|
-
export const RETRY_BASE_DELAY_MS = 2_000;
|
|
89
|
-
export const RETRY_MAX_DELAY_MS = 60_000;
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Transport failures (a refused or dropped connection, DNS blips) usually
|
|
93
|
-
* clear on their own. OpenCode stops after its own retries, which can end a
|
|
94
|
-
* turn during a brief local network or service restart, so the plugin gives
|
|
95
|
-
* them a longer budget before giving up.
|
|
96
|
-
*/
|
|
97
|
-
export const TRANSPORT_RETRY_MAX = 5;
|
|
98
|
-
export const TRANSPORT_RETRY_BASE_MS = 2_000;
|
|
99
|
-
export const TRANSPORT_RETRY_MAX_DELAY_MS = 30_000;
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* free-pi allows one in-flight request per `x-session-id` and answers a second
|
|
103
|
-
* one with `429 concurrent`. OpenCode does not retry that itself, and a slot
|
|
104
|
-
* can leak server-side, so the plugin rotates the wire session id and retries.
|
|
105
|
-
*/
|
|
106
|
-
export const CONCURRENT_RETRY_MAX = 6;
|
|
107
|
-
export const CONCURRENT_RETRY_BASE_MS = 1_000;
|
|
108
|
-
export const CONCURRENT_RETRY_MAX_DELAY_MS = 15_000;
|
|
109
|
-
|
|
110
86
|
/** Tool outcome headers emitted by the free-pi provider CLI. */
|
|
111
87
|
export const TOOL_META_HEADER = "x-freepi-tool-meta";
|
|
112
88
|
export const TOOL_ERRORS_HEADER = "x-freepi-tool-errors";
|
|
@@ -163,7 +139,6 @@ export const DEFAULT_MODELS_REGISTRY_URL = "https://models.opencode.ai";
|
|
|
163
139
|
|
|
164
140
|
export const QUOTA_TTL_MS = 30_000;
|
|
165
141
|
export const QUOTA_HTTP_TIMEOUT_MS = 5_000;
|
|
166
|
-
export const QUOTA_REFRESH_DEBOUNCE_MS = 1_000;
|
|
167
142
|
|
|
168
143
|
export const SESSION_RESET_COOLDOWN_MS = 15_000;
|
|
169
144
|
/**
|
package/src/deps.ts
CHANGED
|
@@ -4,20 +4,13 @@ import type { Credential } from "@opencode/schema/credential";
|
|
|
4
4
|
import type { Plugin } from "@opencode/plugin";
|
|
5
5
|
import type { Logger } from "./logging.js";
|
|
6
6
|
import type { RuntimeState } from "./state.js";
|
|
7
|
-
import type {
|
|
8
|
-
ListSubagentSessions,
|
|
9
|
-
ReadContext,
|
|
10
|
-
ReadSessionInfo,
|
|
11
|
-
} from "./types.js";
|
|
7
|
+
import type { ReadContext } from "./types.js";
|
|
12
8
|
|
|
13
9
|
export type Deps = {
|
|
14
10
|
readonly state: RuntimeState;
|
|
15
11
|
readonly log: Logger;
|
|
16
12
|
readonly activeCredential: () => Promise<Credential.Value | undefined>;
|
|
17
13
|
readonly readContext: ReadContext;
|
|
18
|
-
/** Session headers, used to prove a session is really this session's child. */
|
|
19
|
-
readonly readSession?: ReadSessionInfo;
|
|
20
|
-
readonly listSubagentSessions?: ListSubagentSessions;
|
|
21
14
|
/** Plugin-scoped durable storage, used to reconnect provider sessions. */
|
|
22
15
|
readonly storage?: Plugin.Context["storage"];
|
|
23
16
|
};
|
package/src/index.ts
CHANGED
package/src/legacy.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time cleanup for files older plugin versions wrote into OpenCode's config
|
|
3
|
+
* directory.
|
|
4
|
+
*
|
|
5
|
+
* Agents, skills and their prompts belong to OpenCode. Earlier releases seeded
|
|
6
|
+
* a free-pi skill and four Markdown agents next to the user's own files, which
|
|
7
|
+
* kept those prompts active after the plugin stopped owning them. This removes
|
|
8
|
+
* only files that still carry the old management marker; anything the user
|
|
9
|
+
* edited or replaced is left untouched.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFile, rm, rmdir } from "node:fs/promises";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
|
|
16
|
+
const MARKER =
|
|
17
|
+
"<!-- managed by @eduardo191labs/opencode-free-pi; delete this line to keep your own copy -->";
|
|
18
|
+
|
|
19
|
+
const LEGACY_FILES = [
|
|
20
|
+
["agents", "free-pi", "scout.md"],
|
|
21
|
+
["agents", "free-pi", "planner.md"],
|
|
22
|
+
["agents", "free-pi", "worker.md"],
|
|
23
|
+
["agents", "free-pi", "reviewer.md"],
|
|
24
|
+
["skills", "free-pi", "SKILL.md"],
|
|
25
|
+
] as const;
|
|
26
|
+
|
|
27
|
+
/** OpenCode's user-wide config directory. */
|
|
28
|
+
export function openCodeConfigDir(): string {
|
|
29
|
+
const explicit = process.env.OPENCODE_CONFIG_DIR?.trim();
|
|
30
|
+
if (explicit) return explicit;
|
|
31
|
+
const xdg = process.env.XDG_CONFIG_HOME?.trim();
|
|
32
|
+
if (xdg) return join(xdg, "opencode");
|
|
33
|
+
return join(homedir(), ".config", "opencode");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Deletes the plugin-managed agent and skill files from previous versions and
|
|
38
|
+
* returns their paths. User-owned files are never touched.
|
|
39
|
+
*/
|
|
40
|
+
export async function removeLegacyFreePiFiles(
|
|
41
|
+
configDir = openCodeConfigDir(),
|
|
42
|
+
): Promise<string[]> {
|
|
43
|
+
const removed: string[] = [];
|
|
44
|
+
for (const parts of LEGACY_FILES) {
|
|
45
|
+
const path = join(configDir, ...parts);
|
|
46
|
+
try {
|
|
47
|
+
const current = await readFile(path, "utf8");
|
|
48
|
+
if (!current.slice(0, 1024).includes(MARKER)) continue;
|
|
49
|
+
await rm(path, { force: true });
|
|
50
|
+
removed.push(path);
|
|
51
|
+
} catch {
|
|
52
|
+
// Missing or unreadable: nothing to clean up.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (removed.length > 0) {
|
|
56
|
+
// Drop the now-empty plugin folders without touching user-owned entries.
|
|
57
|
+
for (const parts of [["agents", "free-pi"], ["skills", "free-pi"]]) {
|
|
58
|
+
await rmdir(join(configDir, ...parts)).catch(() => undefined);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return removed;
|
|
62
|
+
}
|
package/src/plugin.ts
CHANGED
|
@@ -1,16 +1,6 @@
|
|
|
1
1
|
/** OpenCode V2 plugin entry point for free-pi. */
|
|
2
2
|
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
|
-
import {
|
|
5
|
-
FREE_PI_SKILL,
|
|
6
|
-
FREE_PI_SKILL_DESCRIPTION,
|
|
7
|
-
FREE_PI_SKILL_ID,
|
|
8
|
-
FREE_PI_SKILL_NAME,
|
|
9
|
-
freePiSkillPath,
|
|
10
|
-
installFreePiAgents,
|
|
11
|
-
installFreePiSkill,
|
|
12
|
-
openCodeConfigDir,
|
|
13
|
-
} from "./agents/definitions.js";
|
|
14
4
|
import { fetchQuota } from "./api/quota.js";
|
|
15
5
|
import { closeFreePiSession } from "./api/session.js";
|
|
16
6
|
import { readCredentialsToken } from "./auth/credentials.js";
|
|
@@ -38,6 +28,7 @@ import type { Deps } from "./deps.js";
|
|
|
38
28
|
import type { ModelMap } from "./types.js";
|
|
39
29
|
import { registerIntegration } from "./integration/setup.js";
|
|
40
30
|
import { createLogger } from "./logging.js";
|
|
31
|
+
import { removeLegacyFreePiFiles } from "./legacy.js";
|
|
41
32
|
import { applyDirectNetwork } from "./network/direct.js";
|
|
42
33
|
import { subscribeEvents } from "./session/events.js";
|
|
43
34
|
import { registerSessionHooks } from "./session/hooks.js";
|
|
@@ -45,7 +36,6 @@ import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
|
45
36
|
import { createRuntimeState } from "./state.js";
|
|
46
37
|
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
47
38
|
import { registerUsageTool } from "./tools/usage.js";
|
|
48
|
-
import { registerSubagentTool } from "./tools/subagent.js";
|
|
49
39
|
import { registerVisionTool } from "./tools/vision.js";
|
|
50
40
|
import { registerWebTools } from "./tools/web.js";
|
|
51
41
|
import { settle } from "./utils/async.js";
|
|
@@ -82,95 +72,21 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
82
72
|
return [];
|
|
83
73
|
}
|
|
84
74
|
},
|
|
85
|
-
readSession: async (sessionID) => {
|
|
86
|
-
try {
|
|
87
|
-
const info = await ctx.session.get({ sessionID });
|
|
88
|
-
return {
|
|
89
|
-
id: info.id,
|
|
90
|
-
parentID: info.parentID,
|
|
91
|
-
title: info.title,
|
|
92
|
-
agent: info.agent,
|
|
93
|
-
outcome: info.outcome,
|
|
94
|
-
updated: info.time?.updated,
|
|
95
|
-
};
|
|
96
|
-
} catch {
|
|
97
|
-
return undefined;
|
|
98
|
-
}
|
|
99
|
-
},
|
|
100
|
-
listSubagentSessions: async (parentID) => {
|
|
101
|
-
try {
|
|
102
|
-
const result = await ctx.session.list({ parentID, limit: 50 });
|
|
103
|
-
return (result.data ?? []).map((info) => ({
|
|
104
|
-
id: info.id,
|
|
105
|
-
parentID: info.parentID,
|
|
106
|
-
title: info.title,
|
|
107
|
-
agent: info.agent,
|
|
108
|
-
outcome: info.outcome,
|
|
109
|
-
updated: info.time?.updated,
|
|
110
|
-
}));
|
|
111
|
-
} catch {
|
|
112
|
-
return [];
|
|
113
|
-
}
|
|
114
|
-
},
|
|
115
75
|
storage: ctx.storage,
|
|
116
76
|
};
|
|
117
77
|
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
// so the picker, the subagent tool, permissions and reloads stay native.
|
|
121
|
-
const nativeRegistrations: Array<{ dispose: () => Promise<void> }> = [];
|
|
78
|
+
// Agents, skills and their prompts are OpenCode's. Remove the files earlier
|
|
79
|
+
// releases seeded so their prompts stop applying; user-owned files stay.
|
|
122
80
|
try {
|
|
123
|
-
const
|
|
124
|
-
if (
|
|
125
|
-
await ctx.agent.reload();
|
|
81
|
+
const removed = await removeLegacyFreePiFiles();
|
|
82
|
+
if (removed.length > 0) {
|
|
126
83
|
log.info(
|
|
127
|
-
`
|
|
128
|
-
|
|
129
|
-
);
|
|
130
|
-
}
|
|
131
|
-
if (agents.skipped.length > 0) {
|
|
132
|
-
log.warn(
|
|
133
|
-
"Left user-owned free-pi agent files untouched",
|
|
134
|
-
agents.skipped,
|
|
84
|
+
`Removed ${removed.length} legacy free-pi agent/skill file(s); OpenCode now owns them`,
|
|
85
|
+
removed,
|
|
135
86
|
);
|
|
136
87
|
}
|
|
137
88
|
} catch (error) {
|
|
138
|
-
log.warn("Could not
|
|
139
|
-
}
|
|
140
|
-
// OpenCode's own skill loader reads `skills/free-pi/SKILL.md`. Install the
|
|
141
|
-
// file first so the skill has a real path, supporting files and permissions
|
|
142
|
-
// like any other native skill; the transform below only fills the gap when
|
|
143
|
-
// the config directory is not writable.
|
|
144
|
-
try {
|
|
145
|
-
const skill = await installFreePiSkill();
|
|
146
|
-
if (skill.changed) {
|
|
147
|
-
await ctx.skill.reload();
|
|
148
|
-
log.info("Installed the native free-pi skill");
|
|
149
|
-
}
|
|
150
|
-
if (skill.skipped) {
|
|
151
|
-
log.warn(
|
|
152
|
-
"Left the user-owned free-pi skill file untouched",
|
|
153
|
-
freePiSkillPath(openCodeConfigDir()),
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
} catch (error) {
|
|
157
|
-
log.warn("Could not install the free-pi skill file", error);
|
|
158
|
-
}
|
|
159
|
-
try {
|
|
160
|
-
nativeRegistrations.push(
|
|
161
|
-
await ctx.skill.transform((editor) => {
|
|
162
|
-
if (editor.get(FREE_PI_SKILL_ID)) return;
|
|
163
|
-
editor.add({
|
|
164
|
-
id: FREE_PI_SKILL_ID,
|
|
165
|
-
name: FREE_PI_SKILL_NAME,
|
|
166
|
-
description: FREE_PI_SKILL_DESCRIPTION,
|
|
167
|
-
path: freePiSkillPath(openCodeConfigDir()),
|
|
168
|
-
content: FREE_PI_SKILL,
|
|
169
|
-
} as any);
|
|
170
|
-
}),
|
|
171
|
-
);
|
|
172
|
-
} catch (error) {
|
|
173
|
-
log.warn("Could not register the free-pi skill", error);
|
|
89
|
+
log.warn("Could not remove the legacy free-pi agent/skill files", error);
|
|
174
90
|
}
|
|
175
91
|
|
|
176
92
|
const [catalogResult, registryResult, quotaResult] = await Promise.all([
|
|
@@ -287,17 +203,12 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
287
203
|
});
|
|
288
204
|
|
|
289
205
|
const registrations = await registerSessionHooks(ctx, deps);
|
|
290
|
-
registrations.push(...nativeRegistrations);
|
|
291
206
|
const tools: Array<{
|
|
292
207
|
name: string;
|
|
293
208
|
register: () => Promise<{ dispose: () => Promise<void> }>;
|
|
294
209
|
}> = [
|
|
295
210
|
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
296
211
|
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
297
|
-
{
|
|
298
|
-
name: "free_pi_subagent_read",
|
|
299
|
-
register: () => registerSubagentTool(ctx, deps),
|
|
300
|
-
},
|
|
301
212
|
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
302
213
|
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
303
214
|
];
|