@eduardo191labs/opencode-free-pi 0.3.22 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -0
- package/dist/plugin.js +36 -5
- package/dist/session/hooks.d.ts +3 -1
- package/dist/session/hooks.js +28 -1
- package/dist/state.d.ts +1 -0
- package/dist/state.js +1 -0
- package/dist/tools/account.d.ts +10 -0
- package/dist/tools/account.js +103 -0
- package/dist/tools/api.d.ts +54 -0
- package/dist/tools/api.js +120 -0
- package/dist/tools/fusion.d.ts +45 -0
- package/dist/tools/fusion.js +162 -0
- package/dist/tools/image-generate.d.ts +13 -0
- package/dist/tools/image-generate.js +143 -0
- package/dist/tools/usage.d.ts +12 -0
- package/dist/tools/usage.js +125 -0
- package/dist/tools/web.d.ts +12 -0
- package/dist/tools/web.js +165 -0
- package/dist/types.d.ts +4 -0
- package/package.json +2 -2
- package/src/plugin.ts +50 -5
- package/src/session/hooks.ts +39 -0
- package/src/state.ts +2 -0
- package/src/tools/account.ts +135 -0
- package/src/tools/api.ts +178 -0
- package/src/tools/fusion.ts +221 -0
- package/src/tools/image-generate.ts +195 -0
- package/src/tools/usage.ts +163 -0
- package/src/tools/web.ts +212 -0
- package/src/types.ts +1 -0
package/src/plugin.ts
CHANGED
|
@@ -23,7 +23,18 @@ import { subscribeEvents } from "./session/events.js";
|
|
|
23
23
|
import { registerSessionHooks } from "./session/hooks.js";
|
|
24
24
|
import { cancelAllFinalizeTimers } from "./session/track.js";
|
|
25
25
|
import { createRuntimeState } from "./state.js";
|
|
26
|
+
import { registerAccountTools } from "./tools/account.js";
|
|
27
|
+
import {
|
|
28
|
+
addFusionModel,
|
|
29
|
+
FUSION_PLANNER_ID,
|
|
30
|
+
premiumPlannerAvailable,
|
|
31
|
+
registerFusionTool,
|
|
32
|
+
resolveFusionIds,
|
|
33
|
+
} from "./tools/fusion.js";
|
|
34
|
+
import { registerGenerateImageTool } from "./tools/image-generate.js";
|
|
35
|
+
import { registerUsageTool } from "./tools/usage.js";
|
|
26
36
|
import { registerVisionTool } from "./tools/vision.js";
|
|
37
|
+
import { registerWebTools } from "./tools/web.js";
|
|
27
38
|
import { settle } from "./utils/async.js";
|
|
28
39
|
|
|
29
40
|
function activeCredentialResolver(ctx: Plugin.Context) {
|
|
@@ -68,6 +79,20 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
68
79
|
const buildOptions = { compact100: state.costExperimentArm === "compact100" };
|
|
69
80
|
const mainModels = buildModels(main, candidates, buildOptions);
|
|
70
81
|
const defenseModels = buildModels(defense, candidates, buildOptions);
|
|
82
|
+
const fusionIds = resolveFusionIds(
|
|
83
|
+
Object.keys(mainModels),
|
|
84
|
+
catalog?.default_model,
|
|
85
|
+
{
|
|
86
|
+
server: catalog?.fusion,
|
|
87
|
+
hasPremium:
|
|
88
|
+
!catalog?.fusion && mainModels[FUSION_PLANNER_ID]
|
|
89
|
+
? await premiumPlannerAvailable(deps)
|
|
90
|
+
: undefined,
|
|
91
|
+
},
|
|
92
|
+
);
|
|
93
|
+
if (fusionIds && addFusionModel(mainModels, fusionIds)) {
|
|
94
|
+
log.info("Registered the Fusion model", fusionIds);
|
|
95
|
+
}
|
|
71
96
|
|
|
72
97
|
for (const [id, model] of Object.entries(mainModels)) {
|
|
73
98
|
state.outputLimits.set(`${PROVIDER_ID}/${id}`, model.limit.output);
|
|
@@ -111,11 +136,31 @@ async function setup(ctx: Plugin.Context): Promise<() => Promise<void>> {
|
|
|
111
136
|
if (preferred) editor.default.set(PROVIDER_ID, preferred);
|
|
112
137
|
});
|
|
113
138
|
|
|
114
|
-
const registrations = await registerSessionHooks(ctx, deps
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
139
|
+
const registrations = await registerSessionHooks(ctx, deps, {
|
|
140
|
+
fusionExecutorID: fusionIds?.executor,
|
|
141
|
+
});
|
|
142
|
+
const tools: Array<{
|
|
143
|
+
name: string;
|
|
144
|
+
register: () => Promise<{ dispose: () => Promise<void> }>;
|
|
145
|
+
}> = [
|
|
146
|
+
{ name: "look_at_image", register: () => registerVisionTool(ctx, deps) },
|
|
147
|
+
{ name: "free_pi_usage", register: () => registerUsageTool(ctx, deps) },
|
|
148
|
+
{ name: "account", register: () => registerAccountTools(ctx, deps) },
|
|
149
|
+
{ name: "web", register: () => registerWebTools(ctx, deps) },
|
|
150
|
+
{ name: "generate_image", register: () => registerGenerateImageTool(ctx, deps) },
|
|
151
|
+
];
|
|
152
|
+
if (fusionIds) {
|
|
153
|
+
tools.push({
|
|
154
|
+
name: "fusion",
|
|
155
|
+
register: () => registerFusionTool(ctx, deps, fusionIds),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
for (const tool of tools) {
|
|
159
|
+
try {
|
|
160
|
+
registrations.push(await tool.register());
|
|
161
|
+
} catch (error) {
|
|
162
|
+
log.warn(`Could not register the ${tool.name} tools`, error);
|
|
163
|
+
}
|
|
119
164
|
}
|
|
120
165
|
const abort = new AbortController();
|
|
121
166
|
const eventTask = subscribeEvents(ctx, deps, abort.signal);
|
package/src/session/hooks.ts
CHANGED
|
@@ -50,6 +50,7 @@ import {
|
|
|
50
50
|
toolHeaders,
|
|
51
51
|
} from "./tools.js";
|
|
52
52
|
import { rememberTrackedModel } from "./usage.js";
|
|
53
|
+
import { FUSION_GUIDELINE, FUSION_ID } from "../tools/fusion.js";
|
|
53
54
|
|
|
54
55
|
type Registration = { dispose: () => Promise<void> };
|
|
55
56
|
type SessionHookName =
|
|
@@ -57,6 +58,7 @@ type SessionHookName =
|
|
|
57
58
|
| "compaction"
|
|
58
59
|
| "generate"
|
|
59
60
|
| "title"
|
|
61
|
+
| "experimental.model.resolve"
|
|
60
62
|
| "model.request"
|
|
61
63
|
| "http.request"
|
|
62
64
|
| "http.response"
|
|
@@ -132,6 +134,21 @@ async function applyGeneration(
|
|
|
132
134
|
}
|
|
133
135
|
}
|
|
134
136
|
|
|
137
|
+
// The virtual Fusion model routes its turns to the executor; the guideline
|
|
138
|
+
// lives here so it is sent with the resolved provider request, not with the
|
|
139
|
+
// model picker's name.
|
|
140
|
+
if (kind === "primary" && deps.state.fusionSessions.has(event.sessionID)) {
|
|
141
|
+
const system = Array.isArray(event.system) ? event.system : [];
|
|
142
|
+
if (
|
|
143
|
+
!system.some(
|
|
144
|
+
(part: any) => part?.type === "text" && part.text === FUSION_GUIDELINE,
|
|
145
|
+
)
|
|
146
|
+
) {
|
|
147
|
+
system.push({ type: "text", text: FUSION_GUIDELINE });
|
|
148
|
+
event.system = system;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
135
152
|
const agent = event.agent;
|
|
136
153
|
const turn = await resolveAdTurn(deps, {
|
|
137
154
|
sessionID: event.sessionID,
|
|
@@ -405,11 +422,33 @@ async function hookForProviders(
|
|
|
405
422
|
export async function registerSessionHooks(
|
|
406
423
|
ctx: Plugin.Context,
|
|
407
424
|
deps: Deps,
|
|
425
|
+
options: { readonly fusionExecutorID?: string } = {},
|
|
408
426
|
): Promise<Registration[]> {
|
|
409
427
|
const registrations: Registration[] = [];
|
|
410
428
|
const generation = (kind: RequestKind) => (event: any) =>
|
|
411
429
|
applyGeneration(deps, event, kind);
|
|
412
430
|
|
|
431
|
+
if (options.fusionExecutorID) {
|
|
432
|
+
await hookForProviders(
|
|
433
|
+
ctx,
|
|
434
|
+
"experimental.model.resolve",
|
|
435
|
+
(event: any) => {
|
|
436
|
+
if (event.model?.providerID !== PROVIDER_ID) return;
|
|
437
|
+
if (event.model?.id !== FUSION_ID) {
|
|
438
|
+
deps.state.fusionSessions.delete(event.sessionID);
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
deps.state.fusionSessions.add(event.sessionID);
|
|
442
|
+
// The picker says Fusion; the wire request uses the executor model.
|
|
443
|
+
event.model = {
|
|
444
|
+
...event.model,
|
|
445
|
+
id: options.fusionExecutorID,
|
|
446
|
+
};
|
|
447
|
+
},
|
|
448
|
+
registrations,
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
|
|
413
452
|
await hookForProviders(ctx, "context", generation("primary"), registrations);
|
|
414
453
|
await hookForProviders(
|
|
415
454
|
ctx,
|
package/src/state.ts
CHANGED
|
@@ -50,6 +50,7 @@ export type RuntimeState = {
|
|
|
50
50
|
lastSessionResetAt: number;
|
|
51
51
|
|
|
52
52
|
freePiSessions: Set<string>;
|
|
53
|
+
fusionSessions: Set<string>;
|
|
53
54
|
wireSessions: Map<string, string>;
|
|
54
55
|
replayBodies: Map<string, string>;
|
|
55
56
|
dirtySessions: Set<string>;
|
|
@@ -80,6 +81,7 @@ export function createRuntimeState(): RuntimeState {
|
|
|
80
81
|
sessionClosePromises: new Map(),
|
|
81
82
|
lastSessionResetAt: 0,
|
|
82
83
|
freePiSessions: new Set(),
|
|
84
|
+
fusionSessions: new Set(),
|
|
83
85
|
wireSessions: new Map(),
|
|
84
86
|
replayBodies: new Map(),
|
|
85
87
|
dirtySessions: new Set(),
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Account helpers that mirror the provider CLI: `free_pi_buy_credits` and the
|
|
3
|
+
* built-in `free_pi_docs` guide.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Plugin } from "@opencode/plugin";
|
|
7
|
+
import type { Deps } from "../deps.js";
|
|
8
|
+
import { browserAvailable, openBrowser } from "../utils/browser.js";
|
|
9
|
+
import { safeUrl } from "../utils/urls.js";
|
|
10
|
+
import {
|
|
11
|
+
done,
|
|
12
|
+
fail,
|
|
13
|
+
freePiRequest,
|
|
14
|
+
GATED_TEXT,
|
|
15
|
+
isGatedSession,
|
|
16
|
+
} from "./api.js";
|
|
17
|
+
|
|
18
|
+
const NO_INPUT = {
|
|
19
|
+
type: "object",
|
|
20
|
+
additionalProperties: false,
|
|
21
|
+
properties: {},
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
24
|
+
const BUY_NOT_AVAILABLE =
|
|
25
|
+
"Buying credits is not available on this server yet.";
|
|
26
|
+
|
|
27
|
+
function buyPageText(url: string): string {
|
|
28
|
+
return `Opening the buy page in your browser. If it did not open (for example over SSH), visit:
|
|
29
|
+
${url}
|
|
30
|
+
|
|
31
|
+
Packs: $5 = 50,000 credits, $10 = 100,000 credits. Card or USDC.`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function executeBuy(
|
|
35
|
+
deps: Deps,
|
|
36
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
37
|
+
) {
|
|
38
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
39
|
+
|
|
40
|
+
const result = await freePiRequest(deps, {
|
|
41
|
+
path: "/me",
|
|
42
|
+
timeoutMs: 5_000,
|
|
43
|
+
signal: context.signal,
|
|
44
|
+
audience: "model",
|
|
45
|
+
});
|
|
46
|
+
if (!result.ok) return fail(result.text);
|
|
47
|
+
|
|
48
|
+
const url = safeUrl(result.data?.buy_url);
|
|
49
|
+
if (!url) {
|
|
50
|
+
return done(BUY_NOT_AVAILABLE, { available: false });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const opened = browserAvailable() ? await openBrowser(url) : false;
|
|
54
|
+
deps.log.info("free_pi_buy_credits opened the buy page", {
|
|
55
|
+
opened,
|
|
56
|
+
url,
|
|
57
|
+
});
|
|
58
|
+
return done(buyPageText(url), { buy_url: url, opened });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const FREE_PI_DOCS = `# free-pi in OpenCode
|
|
62
|
+
|
|
63
|
+
free-pi is a free, ad-supported way to run coding models. You sign in with
|
|
64
|
+
GitHub, and ads shown in the session pay for the inference. You never handle a
|
|
65
|
+
model API key. The free daily allowance can change with supply and demand.
|
|
66
|
+
|
|
67
|
+
## Checking usage and credits
|
|
68
|
+
- \`free_pi_usage\` shows today's remaining allowance, purchased credits, token
|
|
69
|
+
counts and your account tier.
|
|
70
|
+
- \`free_pi_buy_credits\` opens the buy page. Purchased credits cover use beyond
|
|
71
|
+
the free allowance.
|
|
72
|
+
- The dashboard at https://freepi.ai/dashboard shows usage, credits and privacy.
|
|
73
|
+
|
|
74
|
+
## Tools that spend the daily allowance
|
|
75
|
+
- \`look_at_image\` asks a vision model about a PNG, JPEG or WebP inside the
|
|
76
|
+
project. free-pi models are text-only, so they cannot see images otherwise.
|
|
77
|
+
- \`generate_image\` draws one image from a prompt and saves it under \`images/\`.
|
|
78
|
+
- \`web_search\` searches the web for current information.
|
|
79
|
+
- \`docs_lookup\` looks up current library and framework documentation.
|
|
80
|
+
- \`free_pi_usage\`, \`free_pi_buy_credits\` and \`free_pi_docs\` are read-only.
|
|
81
|
+
|
|
82
|
+
## Agents and sessions
|
|
83
|
+
- The Fusion agent gathers context, asks a planning model for a step-by-step
|
|
84
|
+
plan, and then implements it. Fusion needs the planner model in the catalog;
|
|
85
|
+
otherwise it falls back to the default free-pi model.
|
|
86
|
+
- Subagents inherit the parent's free-pi allowance and count against the same
|
|
87
|
+
daily budget.
|
|
88
|
+
- A session's server slot is closed shortly after its last step. If another
|
|
89
|
+
terminal is stuck, close that session before starting a new one.
|
|
90
|
+
|
|
91
|
+
## Limits
|
|
92
|
+
- One image question can run at a time; \`look_at_image\` queues and waits.
|
|
93
|
+
- Usage limits (\`daily_cap\`, \`rolling_cap\`, concurrency) are terminal: the
|
|
94
|
+
agent is told to stop and continue without the tool rather than retrying.
|
|
95
|
+
`;
|
|
96
|
+
|
|
97
|
+
async function executeDocs(
|
|
98
|
+
deps: Deps,
|
|
99
|
+
context: { readonly sessionID: string },
|
|
100
|
+
raw: unknown,
|
|
101
|
+
) {
|
|
102
|
+
if (raw && typeof raw === "object" && Object.keys(raw as object).length > 0) {
|
|
103
|
+
return fail("free_pi_docs takes no arguments.");
|
|
104
|
+
}
|
|
105
|
+
if (!isGatedSession(deps, context.sessionID)) {
|
|
106
|
+
return fail(GATED_TEXT);
|
|
107
|
+
}
|
|
108
|
+
return done(FREE_PI_DOCS, { ok: true });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function registerAccountTools(
|
|
112
|
+
ctx: Plugin.Context,
|
|
113
|
+
deps: Deps,
|
|
114
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
115
|
+
return ctx.tool.transform((editor) => {
|
|
116
|
+
editor.add({
|
|
117
|
+
name: "free_pi_buy_credits",
|
|
118
|
+
description:
|
|
119
|
+
"Open the free-pi buy-credits page in the browser (and print the URL, for SSH sessions with no browser). Read-only against the server, takes no arguments.",
|
|
120
|
+
input: NO_INPUT,
|
|
121
|
+
options: { codemode: false },
|
|
122
|
+
execute: (_input: unknown, context: any) => executeBuy(deps, context),
|
|
123
|
+
} as any);
|
|
124
|
+
|
|
125
|
+
editor.add({
|
|
126
|
+
name: "free_pi_docs",
|
|
127
|
+
description:
|
|
128
|
+
"Return the built-in free-pi guide: what it is, how the free allowance, credits, ads and tools work. Read-only, takes no arguments, makes no network calls.",
|
|
129
|
+
input: NO_INPUT,
|
|
130
|
+
options: { codemode: false },
|
|
131
|
+
execute: (input: unknown, context: any) =>
|
|
132
|
+
executeDocs(deps, context, input),
|
|
133
|
+
} as any);
|
|
134
|
+
});
|
|
135
|
+
}
|
package/src/tools/api.ts
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared plumbing for the free-pi server tools.
|
|
3
|
+
*
|
|
4
|
+
* The provider CLI spends the user's daily allowance through a small set of
|
|
5
|
+
* `/tools/*` and `/me*` endpoints. This module keeps the token handling,
|
|
6
|
+
* timeouts and error wording identical across those tools.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { resolveToken } from "../auth/token.js";
|
|
10
|
+
import type { Deps } from "../deps.js";
|
|
11
|
+
import { isFreePiSession } from "../session/tools.js";
|
|
12
|
+
import { resolveBaseUrl } from "../utils/urls.js";
|
|
13
|
+
|
|
14
|
+
export type ToolOutput = {
|
|
15
|
+
readonly content: ReadonlyArray<{ readonly type: "text"; readonly text: string }>;
|
|
16
|
+
readonly metadata: Record<string, unknown>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function done(
|
|
20
|
+
text: string,
|
|
21
|
+
metadata: Record<string, unknown> = {},
|
|
22
|
+
): ToolOutput {
|
|
23
|
+
return { content: [{ type: "text", text }], metadata };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function fail(text: string): ToolOutput {
|
|
27
|
+
return done(text, { ok: false });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const GATED_TEXT =
|
|
31
|
+
"This tool is only available in free-pi sessions.";
|
|
32
|
+
|
|
33
|
+
/** Same wording as the provider CLI when the integration is not connected. */
|
|
34
|
+
export const NO_TOKEN_TEXT =
|
|
35
|
+
"This tool needs a free-pi sign-in. Do not retry; tell the user to connect the free-pi integration, and continue without this tool.";
|
|
36
|
+
|
|
37
|
+
export function isGatedSession(
|
|
38
|
+
deps: Deps,
|
|
39
|
+
sessionID: string | undefined,
|
|
40
|
+
): boolean {
|
|
41
|
+
return typeof sessionID === "string" && isFreePiSession(deps, sessionID);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function friendlyThrown(error: unknown): string {
|
|
45
|
+
const name = error instanceof Error ? error.name : "";
|
|
46
|
+
if (name === "TimeoutError") return "free-pi took too long to answer. Try again.";
|
|
47
|
+
if (name === "AbortError") return "Cancelled.";
|
|
48
|
+
if (name === "SyntaxError") return "free-pi sent an unexpected reply. Try again.";
|
|
49
|
+
return "Couldn't reach free-pi - check your connection.";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function friendlyStatus(
|
|
53
|
+
status: number,
|
|
54
|
+
message?: unknown,
|
|
55
|
+
audience: "model" | "user" = "model",
|
|
56
|
+
): string {
|
|
57
|
+
if (status === 401) {
|
|
58
|
+
return audience === "model"
|
|
59
|
+
? "The user's free-pi sign-in has expired; tell them to reconnect the free-pi integration."
|
|
60
|
+
: "Your free-pi sign-in has expired. Reconnect the free-pi integration.";
|
|
61
|
+
}
|
|
62
|
+
if (typeof message === "string" && message.trim()) return message.trim();
|
|
63
|
+
if (status >= 500) {
|
|
64
|
+
return `free-pi is having trouble right now (HTTP ${status}). Try again in a minute.`;
|
|
65
|
+
}
|
|
66
|
+
return `free-pi could not complete the request (HTTP ${status}).`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type ApiResult =
|
|
70
|
+
| { readonly ok: true; readonly data: any }
|
|
71
|
+
| {
|
|
72
|
+
readonly ok: false;
|
|
73
|
+
readonly status: number;
|
|
74
|
+
readonly code: string;
|
|
75
|
+
readonly text: string;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
type RequestOptions = {
|
|
79
|
+
readonly path: string;
|
|
80
|
+
readonly method?: "GET" | "POST";
|
|
81
|
+
readonly body?: unknown;
|
|
82
|
+
readonly timeoutMs?: number;
|
|
83
|
+
readonly signal?: AbortSignal;
|
|
84
|
+
/** Passed to `friendlyStatus` for non-mapped HTTP failures. */
|
|
85
|
+
readonly audience?: "model" | "user";
|
|
86
|
+
/** Prefix for timeout and transport errors, e.g. "The vision request". */
|
|
87
|
+
readonly label?: string;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Calls a free-pi endpoint with the current credential and never throws.
|
|
92
|
+
* Business error codes are returned intact so each tool can map them to the
|
|
93
|
+
* exact wording the provider CLI uses.
|
|
94
|
+
*/
|
|
95
|
+
export async function freePiRequest(
|
|
96
|
+
deps: Deps,
|
|
97
|
+
options: RequestOptions,
|
|
98
|
+
): Promise<ApiResult> {
|
|
99
|
+
const token = await resolveToken(deps);
|
|
100
|
+
if (!token) {
|
|
101
|
+
return { ok: false, status: 401, code: "no_token", text: NO_TOKEN_TEXT };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? 20_000);
|
|
105
|
+
const signal = options.signal
|
|
106
|
+
? AbortSignal.any([options.signal, timeout])
|
|
107
|
+
: timeout;
|
|
108
|
+
|
|
109
|
+
let response: Response;
|
|
110
|
+
try {
|
|
111
|
+
response = await fetch(`${resolveBaseUrl()}${options.path}`, {
|
|
112
|
+
method: options.method ?? "GET",
|
|
113
|
+
headers: {
|
|
114
|
+
authorization: `Bearer ${token}`,
|
|
115
|
+
...(options.body !== undefined
|
|
116
|
+
? { "content-type": "application/json" }
|
|
117
|
+
: {}),
|
|
118
|
+
},
|
|
119
|
+
...(options.body !== undefined
|
|
120
|
+
? { body: JSON.stringify(options.body) }
|
|
121
|
+
: {}),
|
|
122
|
+
signal,
|
|
123
|
+
});
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (options.signal?.aborted) {
|
|
126
|
+
return { ok: false, status: 0, code: "cancelled", text: "Cancelled." };
|
|
127
|
+
}
|
|
128
|
+
const timedOut =
|
|
129
|
+
error instanceof Error && error.name === "TimeoutError";
|
|
130
|
+
const prefix = options.label ? `${options.label} ` : "";
|
|
131
|
+
return {
|
|
132
|
+
ok: false,
|
|
133
|
+
status: 0,
|
|
134
|
+
code: timedOut ? "timeout" : "network",
|
|
135
|
+
text: timedOut
|
|
136
|
+
? `${prefix}timed out. Try again.`
|
|
137
|
+
: friendlyThrown(error),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (response.ok) {
|
|
142
|
+
const data = await response.json().catch(() => undefined);
|
|
143
|
+
if (data === undefined) {
|
|
144
|
+
return {
|
|
145
|
+
ok: false,
|
|
146
|
+
status: response.status,
|
|
147
|
+
code: "invalid_response",
|
|
148
|
+
text: "free-pi sent an unexpected reply. Try again.",
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
return { ok: true, data };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const body = (await response.json().catch(() => ({}))) as any;
|
|
155
|
+
const code = String(body?.error?.code ?? body?.code ?? "");
|
|
156
|
+
return {
|
|
157
|
+
ok: false,
|
|
158
|
+
status: response.status,
|
|
159
|
+
code,
|
|
160
|
+
text: friendlyStatus(
|
|
161
|
+
response.status,
|
|
162
|
+
body?.error?.message ?? body?.message,
|
|
163
|
+
options.audience,
|
|
164
|
+
),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Maps a business error code to the CLI's wording, or keeps the HTTP text. */
|
|
169
|
+
export function mappedText(
|
|
170
|
+
table: Record<string, string>,
|
|
171
|
+
result: Extract<ApiResult, { ok: false }>,
|
|
172
|
+
library?: string,
|
|
173
|
+
): string {
|
|
174
|
+
if (result.code === "no_token") return NO_TOKEN_TEXT;
|
|
175
|
+
const mapped = table[result.code];
|
|
176
|
+
if (mapped) return mapped;
|
|
177
|
+
return result.text;
|
|
178
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fusion: DeepSeek Pro plans, Flash builds.
|
|
3
|
+
*
|
|
4
|
+
* The provider CLI registers a virtual "fusion" model. OpenCode gets the same
|
|
5
|
+
* shape: a `fusion` model that routes its turns to the executor model, plus a
|
|
6
|
+
* `fusion_plan` tool that asks the planner model for a plan through the
|
|
7
|
+
* stateless generate API before any edit. The executor then carries the plan
|
|
8
|
+
* out, exactly like the CLI.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Plugin } from "@opencode/plugin";
|
|
12
|
+
import { PROVIDER_ID } from "../constants.js";
|
|
13
|
+
import type { Deps } from "../deps.js";
|
|
14
|
+
import type { ModelDefinition } from "../types.js";
|
|
15
|
+
import {
|
|
16
|
+
done,
|
|
17
|
+
fail,
|
|
18
|
+
freePiRequest,
|
|
19
|
+
GATED_TEXT,
|
|
20
|
+
isGatedSession,
|
|
21
|
+
} from "./api.js";
|
|
22
|
+
|
|
23
|
+
export const FUSION_ID = "fusion";
|
|
24
|
+
export const FUSION_PLANNER_ID = "deepseek-v4-pro";
|
|
25
|
+
export const FUSION_EXECUTOR_ID = "deepseek-v4-flash";
|
|
26
|
+
export const FUSION_FALLBACK_PLANNER_ID = "deepseek-v4-flash";
|
|
27
|
+
|
|
28
|
+
export const FUSION_GUIDELINE = `Fusion: if the task needs any file changes, first gather the context with read-only tools (read, grep, glob) and make no edits. Then call fusion_plan with a summary of what you found and what the task needs, BEFORE any edit or write; the planning model writes the plan and you carry it out. Once the plan exists, record it with the todo tool, then carry out the unfinished items yourself (edit, write tests, run them) and finish the user's task. Only a task that needs no file changes (a plain question) is answered directly without fusion_plan.`;
|
|
29
|
+
|
|
30
|
+
const PLAN_INPUT = {
|
|
31
|
+
type: "object",
|
|
32
|
+
additionalProperties: false,
|
|
33
|
+
required: ["summary"],
|
|
34
|
+
properties: {
|
|
35
|
+
summary: {
|
|
36
|
+
type: "string",
|
|
37
|
+
minLength: 1,
|
|
38
|
+
maxLength: 6_000,
|
|
39
|
+
description:
|
|
40
|
+
"What you found during read-only exploration and what the task needs",
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
export type FusionIds = {
|
|
46
|
+
readonly planner: string;
|
|
47
|
+
readonly executor: string;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Picks the planner and executor from the live catalog, like the CLI: prefer
|
|
52
|
+
* the server-provided pair, then Pro when the account has premium credits, then
|
|
53
|
+
* Flash for both roles.
|
|
54
|
+
*/
|
|
55
|
+
export function resolveFusionIds(
|
|
56
|
+
modelIDs: readonly string[],
|
|
57
|
+
defaultModelID?: string,
|
|
58
|
+
options: {
|
|
59
|
+
readonly server?: { planner?: string; executor?: string };
|
|
60
|
+
readonly hasPremium?: boolean;
|
|
61
|
+
} = {},
|
|
62
|
+
): FusionIds | undefined {
|
|
63
|
+
const has = (id: string | undefined): id is string =>
|
|
64
|
+
typeof id === "string" && modelIDs.includes(id);
|
|
65
|
+
const executor = has(FUSION_EXECUTOR_ID)
|
|
66
|
+
? FUSION_EXECUTOR_ID
|
|
67
|
+
: has(defaultModelID)
|
|
68
|
+
? defaultModelID
|
|
69
|
+
: undefined;
|
|
70
|
+
if (!executor) return undefined;
|
|
71
|
+
const server = options.server;
|
|
72
|
+
if (server && has(server.planner) && has(server.executor)) {
|
|
73
|
+
return { planner: server.planner, executor: server.executor };
|
|
74
|
+
}
|
|
75
|
+
const planner =
|
|
76
|
+
options.hasPremium !== false && has(FUSION_PLANNER_ID)
|
|
77
|
+
? FUSION_PLANNER_ID
|
|
78
|
+
: has(FUSION_FALLBACK_PLANNER_ID)
|
|
79
|
+
? FUSION_FALLBACK_PLANNER_ID
|
|
80
|
+
: executor;
|
|
81
|
+
return { planner, executor };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The CLI asks `/me` before offering the Pro planner: without premium credits
|
|
86
|
+
* the Pro model refuses the request, so Fusion plans with Flash instead. A
|
|
87
|
+
* failed check keeps Pro, matching the CLI.
|
|
88
|
+
*/
|
|
89
|
+
export async function premiumPlannerAvailable(deps: Deps): Promise<boolean> {
|
|
90
|
+
const result = await freePiRequest(deps, {
|
|
91
|
+
path: "/me",
|
|
92
|
+
timeoutMs: 5_000,
|
|
93
|
+
});
|
|
94
|
+
if (!result.ok) return true;
|
|
95
|
+
const premium = result.data?.premium_credits;
|
|
96
|
+
return typeof premium === "number" ? premium > 0 : true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function fusionName(ids: FusionIds): string {
|
|
100
|
+
if (ids.planner === FUSION_PLANNER_ID) {
|
|
101
|
+
return "🧬 Fusion · DeepSeek Pro plans, Flash builds";
|
|
102
|
+
}
|
|
103
|
+
if (ids.planner === FUSION_FALLBACK_PLANNER_ID) {
|
|
104
|
+
return "🧬 Fusion · DeepSeek Flash plans and builds";
|
|
105
|
+
}
|
|
106
|
+
return "🧬 Fusion";
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Adds the virtual model next to the catalog models. */
|
|
110
|
+
export function addFusionModel(
|
|
111
|
+
models: Record<string, ModelDefinition>,
|
|
112
|
+
ids: FusionIds,
|
|
113
|
+
): string | undefined {
|
|
114
|
+
const base = models[ids.executor];
|
|
115
|
+
if (!base) return undefined;
|
|
116
|
+
models[FUSION_ID] = {
|
|
117
|
+
...base,
|
|
118
|
+
id: FUSION_ID,
|
|
119
|
+
name: fusionName(ids),
|
|
120
|
+
release_date: base.release_date,
|
|
121
|
+
};
|
|
122
|
+
return FUSION_ID;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function plannerPrompt(summary: string): string {
|
|
126
|
+
return `You are the planning model in a two-model setup. Another model gathered the context below and will carry out the plan; it can edit files and run commands, but it cannot see this conversation.
|
|
127
|
+
|
|
128
|
+
Task context from the executor:
|
|
129
|
+
${summary}
|
|
130
|
+
|
|
131
|
+
Write a concrete step-by-step plan: the files to change, the exact changes, and the tests to add and run. Be specific enough that the executor does not need to re-explore. Do not edit files or run commands. Reply with the plan only.`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function plan(
|
|
135
|
+
ctx: Plugin.Context,
|
|
136
|
+
deps: Deps,
|
|
137
|
+
plannerID: string,
|
|
138
|
+
summary: string,
|
|
139
|
+
): Promise<string | undefined> {
|
|
140
|
+
const generate = (ctx as any).experimental?.generate?.text;
|
|
141
|
+
if (typeof generate !== "function") {
|
|
142
|
+
deps.log.warn("fusion_plan: this OpenCode build has no stateless generate");
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const result = await generate({
|
|
147
|
+
prompt: plannerPrompt(summary),
|
|
148
|
+
model: { providerID: PROVIDER_ID, id: plannerID },
|
|
149
|
+
});
|
|
150
|
+
const text = result?.text ?? result?.data?.text;
|
|
151
|
+
return typeof text === "string" && text.trim() ? text.trim() : undefined;
|
|
152
|
+
} catch (error: any) {
|
|
153
|
+
deps.log.warn("fusion_plan: the planner request failed", {
|
|
154
|
+
planner: plannerID,
|
|
155
|
+
message: String(error?.message ?? error),
|
|
156
|
+
});
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function executeFusionPlan(
|
|
162
|
+
ctx: Plugin.Context,
|
|
163
|
+
deps: Deps,
|
|
164
|
+
ids: FusionIds,
|
|
165
|
+
raw: unknown,
|
|
166
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
167
|
+
) {
|
|
168
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
169
|
+
const summary =
|
|
170
|
+
typeof (raw as any)?.summary === "string"
|
|
171
|
+
? (raw as any).summary.trim()
|
|
172
|
+
: "";
|
|
173
|
+
if (!summary) return fail("fusion_plan needs a summary of the task context.");
|
|
174
|
+
|
|
175
|
+
const startedAt = Date.now();
|
|
176
|
+
let usedPlanner = ids.planner;
|
|
177
|
+
let text = await plan(ctx, deps, ids.planner, summary);
|
|
178
|
+
if (!text && ids.planner !== FUSION_FALLBACK_PLANNER_ID) {
|
|
179
|
+
// Pro needs premium credits; without them it refuses the request, so let
|
|
180
|
+
// Flash plan instead of losing the turn.
|
|
181
|
+
usedPlanner = FUSION_FALLBACK_PLANNER_ID;
|
|
182
|
+
text = await plan(ctx, deps, usedPlanner, summary);
|
|
183
|
+
}
|
|
184
|
+
if (!text) {
|
|
185
|
+
deps.log.warn("fusion_plan could not reach the planner; planning locally", {
|
|
186
|
+
planner: ids.planner,
|
|
187
|
+
});
|
|
188
|
+
return done(
|
|
189
|
+
"The planner is unavailable, so write the step-by-step plan yourself with the todo tool, one item per step. Do not edit files until the plan is recorded, then carry it out.",
|
|
190
|
+
{ ok: false, planner: ids.planner },
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
deps.log.info("fusion_plan answered", {
|
|
195
|
+
planner: usedPlanner,
|
|
196
|
+
ms: Date.now() - startedAt,
|
|
197
|
+
chars: text.length,
|
|
198
|
+
});
|
|
199
|
+
return done(
|
|
200
|
+
`Plan from the Fusion planner (${usedPlanner}). Record it with the todo tool if it is not already there, then carry it out:\n\n${text}`,
|
|
201
|
+
{ ok: true, planner: usedPlanner, elapsed_ms: Date.now() - startedAt },
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function registerFusionTool(
|
|
206
|
+
ctx: Plugin.Context,
|
|
207
|
+
deps: Deps,
|
|
208
|
+
ids: FusionIds,
|
|
209
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
210
|
+
return ctx.tool.transform((editor) => {
|
|
211
|
+
editor.add({
|
|
212
|
+
name: "fusion_plan",
|
|
213
|
+
description:
|
|
214
|
+
"Fusion only: hand off to the planning model once you have gathered enough context. Takes a summary of what you found and what the task needs, and returns a step-by-step plan to carry out.",
|
|
215
|
+
input: PLAN_INPUT,
|
|
216
|
+
options: { codemode: false },
|
|
217
|
+
execute: (input: unknown, context: any) =>
|
|
218
|
+
executeFusionPlan(ctx, deps, ids, input, context),
|
|
219
|
+
} as any);
|
|
220
|
+
});
|
|
221
|
+
}
|