@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.
@@ -0,0 +1,162 @@
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
+ import { PROVIDER_ID } from "../constants.js";
11
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, } from "./api.js";
12
+ export const FUSION_ID = "fusion";
13
+ export const FUSION_PLANNER_ID = "deepseek-v4-pro";
14
+ export const FUSION_EXECUTOR_ID = "deepseek-v4-flash";
15
+ export const FUSION_FALLBACK_PLANNER_ID = "deepseek-v4-flash";
16
+ 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.`;
17
+ const PLAN_INPUT = {
18
+ type: "object",
19
+ additionalProperties: false,
20
+ required: ["summary"],
21
+ properties: {
22
+ summary: {
23
+ type: "string",
24
+ minLength: 1,
25
+ maxLength: 6_000,
26
+ description: "What you found during read-only exploration and what the task needs",
27
+ },
28
+ },
29
+ };
30
+ /**
31
+ * Picks the planner and executor from the live catalog, like the CLI: prefer
32
+ * the server-provided pair, then Pro when the account has premium credits, then
33
+ * Flash for both roles.
34
+ */
35
+ export function resolveFusionIds(modelIDs, defaultModelID, options = {}) {
36
+ const has = (id) => typeof id === "string" && modelIDs.includes(id);
37
+ const executor = has(FUSION_EXECUTOR_ID)
38
+ ? FUSION_EXECUTOR_ID
39
+ : has(defaultModelID)
40
+ ? defaultModelID
41
+ : undefined;
42
+ if (!executor)
43
+ return undefined;
44
+ const server = options.server;
45
+ if (server && has(server.planner) && has(server.executor)) {
46
+ return { planner: server.planner, executor: server.executor };
47
+ }
48
+ const planner = options.hasPremium !== false && has(FUSION_PLANNER_ID)
49
+ ? FUSION_PLANNER_ID
50
+ : has(FUSION_FALLBACK_PLANNER_ID)
51
+ ? FUSION_FALLBACK_PLANNER_ID
52
+ : executor;
53
+ return { planner, executor };
54
+ }
55
+ /**
56
+ * The CLI asks `/me` before offering the Pro planner: without premium credits
57
+ * the Pro model refuses the request, so Fusion plans with Flash instead. A
58
+ * failed check keeps Pro, matching the CLI.
59
+ */
60
+ export async function premiumPlannerAvailable(deps) {
61
+ const result = await freePiRequest(deps, {
62
+ path: "/me",
63
+ timeoutMs: 5_000,
64
+ });
65
+ if (!result.ok)
66
+ return true;
67
+ const premium = result.data?.premium_credits;
68
+ return typeof premium === "number" ? premium > 0 : true;
69
+ }
70
+ export function fusionName(ids) {
71
+ if (ids.planner === FUSION_PLANNER_ID) {
72
+ return "🧬 Fusion · DeepSeek Pro plans, Flash builds";
73
+ }
74
+ if (ids.planner === FUSION_FALLBACK_PLANNER_ID) {
75
+ return "🧬 Fusion · DeepSeek Flash plans and builds";
76
+ }
77
+ return "🧬 Fusion";
78
+ }
79
+ /** Adds the virtual model next to the catalog models. */
80
+ export function addFusionModel(models, ids) {
81
+ const base = models[ids.executor];
82
+ if (!base)
83
+ return undefined;
84
+ models[FUSION_ID] = {
85
+ ...base,
86
+ id: FUSION_ID,
87
+ name: fusionName(ids),
88
+ release_date: base.release_date,
89
+ };
90
+ return FUSION_ID;
91
+ }
92
+ function plannerPrompt(summary) {
93
+ 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.
94
+
95
+ Task context from the executor:
96
+ ${summary}
97
+
98
+ 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.`;
99
+ }
100
+ async function plan(ctx, deps, plannerID, summary) {
101
+ const generate = ctx.experimental?.generate?.text;
102
+ if (typeof generate !== "function") {
103
+ deps.log.warn("fusion_plan: this OpenCode build has no stateless generate");
104
+ return undefined;
105
+ }
106
+ try {
107
+ const result = await generate({
108
+ prompt: plannerPrompt(summary),
109
+ model: { providerID: PROVIDER_ID, id: plannerID },
110
+ });
111
+ const text = result?.text ?? result?.data?.text;
112
+ return typeof text === "string" && text.trim() ? text.trim() : undefined;
113
+ }
114
+ catch (error) {
115
+ deps.log.warn("fusion_plan: the planner request failed", {
116
+ planner: plannerID,
117
+ message: String(error?.message ?? error),
118
+ });
119
+ return undefined;
120
+ }
121
+ }
122
+ async function executeFusionPlan(ctx, deps, ids, raw, context) {
123
+ if (!isGatedSession(deps, context.sessionID))
124
+ return fail(GATED_TEXT);
125
+ const summary = typeof raw?.summary === "string"
126
+ ? raw.summary.trim()
127
+ : "";
128
+ if (!summary)
129
+ return fail("fusion_plan needs a summary of the task context.");
130
+ const startedAt = Date.now();
131
+ let usedPlanner = ids.planner;
132
+ let text = await plan(ctx, deps, ids.planner, summary);
133
+ if (!text && ids.planner !== FUSION_FALLBACK_PLANNER_ID) {
134
+ // Pro needs premium credits; without them it refuses the request, so let
135
+ // Flash plan instead of losing the turn.
136
+ usedPlanner = FUSION_FALLBACK_PLANNER_ID;
137
+ text = await plan(ctx, deps, usedPlanner, summary);
138
+ }
139
+ if (!text) {
140
+ deps.log.warn("fusion_plan could not reach the planner; planning locally", {
141
+ planner: ids.planner,
142
+ });
143
+ return done("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.", { ok: false, planner: ids.planner });
144
+ }
145
+ deps.log.info("fusion_plan answered", {
146
+ planner: usedPlanner,
147
+ ms: Date.now() - startedAt,
148
+ chars: text.length,
149
+ });
150
+ return done(`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}`, { ok: true, planner: usedPlanner, elapsed_ms: Date.now() - startedAt });
151
+ }
152
+ export async function registerFusionTool(ctx, deps, ids) {
153
+ return ctx.tool.transform((editor) => {
154
+ editor.add({
155
+ name: "fusion_plan",
156
+ description: "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.",
157
+ input: PLAN_INPUT,
158
+ options: { codemode: false },
159
+ execute: (input, context) => executeFusionPlan(ctx, deps, ids, input, context),
160
+ });
161
+ });
162
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `generate_image`, the free-pi text-to-image tool.
3
+ *
4
+ * The models cannot see images, so the tool writes the server's image into
5
+ * `images/` inside the project and returns the relative path. Same endpoint,
6
+ * limits and error wording as the provider CLI.
7
+ */
8
+ import type { Plugin } from "@opencode/plugin";
9
+ import type { Deps } from "../deps.js";
10
+ export declare function slug(value: string): string;
11
+ export declare function registerGenerateImageTool(ctx: Plugin.Context, deps: Deps): Promise<{
12
+ dispose: () => Promise<void>;
13
+ }>;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `generate_image`, the free-pi text-to-image tool.
3
+ *
4
+ * The models cannot see images, so the tool writes the server's image into
5
+ * `images/` inside the project and returns the relative path. Same endpoint,
6
+ * limits and error wording as the provider CLI.
7
+ */
8
+ import { randomBytes } from "node:crypto";
9
+ import { mkdir, open } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, mappedText, } from "./api.js";
12
+ const MAX_BYTES = 8 * 1024 * 1024;
13
+ const TIMEOUT_MS = 120_000;
14
+ const EXT = {
15
+ "image/png": "png",
16
+ "image/jpeg": "jpg",
17
+ "image/webp": "webp",
18
+ };
19
+ const ERRORS = {
20
+ guest_login_required: "This tool needs a GitHub sign-in; the guest trial cannot use it. Do not retry or work around it; tell the user to sign in, and continue without this tool.",
21
+ guest_unavailable: "The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
22
+ daily_cap: "The user's free allowance for today is used up. Do not retry. Tell the user they can get credits at freepi.ai/extra-credits, and continue without this tool.",
23
+ rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
24
+ rate_limited: "Too many image requests right now. Do not call generate_image again in this turn unless the user asks.",
25
+ not_configured: "Image generation is not available on this server. Do not call generate_image again in this session.",
26
+ upstream_error: "The image provider failed. You may retry once.",
27
+ account_review: "This account is under review, so image generation is disabled. Do not retry; tell the user and continue without it.",
28
+ content_rejected: "The image provider rejected this prompt. Do not retry the same prompt; tell the user and offer to reword it.",
29
+ invalid_request: "The server rejected this request. Do not retry it unchanged.",
30
+ };
31
+ const IMAGE_INPUT = {
32
+ type: "object",
33
+ additionalProperties: false,
34
+ required: ["prompt"],
35
+ properties: {
36
+ prompt: {
37
+ type: "string",
38
+ minLength: 1,
39
+ maxLength: 1_000,
40
+ description: "What to draw: subject, style, any exact text to render, and composition",
41
+ },
42
+ aspect_ratio: {
43
+ type: "string",
44
+ enum: ["1:1", "16:9", "9:16", "4:3", "3:2"],
45
+ description: "Default 1:1",
46
+ },
47
+ name: {
48
+ type: "string",
49
+ maxLength: 60,
50
+ description: "Short file name hint, e.g. hero-banner; used only for the saved file's name",
51
+ },
52
+ },
53
+ };
54
+ export function slug(value) {
55
+ return (value
56
+ .toLowerCase()
57
+ .replace(/[^a-z0-9]+/g, "-")
58
+ .replace(/^-+/, "")
59
+ .slice(0, 40)
60
+ .replace(/-+$/, "") || "image");
61
+ }
62
+ async function saveImage(directory, relative, bytes) {
63
+ try {
64
+ await mkdir(join(directory, "images"), { recursive: true });
65
+ const handle = await open(join(directory, relative), "wx");
66
+ try {
67
+ await handle.writeFile(bytes);
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ return undefined;
73
+ }
74
+ catch (error) {
75
+ const reasons = {
76
+ EACCES: "permission denied",
77
+ EPERM: "permission denied",
78
+ ENOSPC: "the disk is full",
79
+ ENOENT: "the folder does not exist",
80
+ };
81
+ const why = reasons[error?.code ?? ""] ?? "it could not be written";
82
+ return why;
83
+ }
84
+ }
85
+ async function executeGenerateImage(ctx, deps, raw, context) {
86
+ if (!isGatedSession(deps, context.sessionID))
87
+ return fail(GATED_TEXT);
88
+ const input = raw;
89
+ const prompt = typeof input?.prompt === "string" ? input.prompt.trim() : "";
90
+ if (!prompt)
91
+ return fail("generate_image needs a prompt.");
92
+ const aspectRatio = typeof input?.aspect_ratio === "string" ? input.aspect_ratio : undefined;
93
+ const name = typeof input?.name === "string" ? input.name : undefined;
94
+ const result = await freePiRequest(deps, {
95
+ path: "/tools/image",
96
+ method: "POST",
97
+ body: { prompt, ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}) },
98
+ timeoutMs: TIMEOUT_MS,
99
+ signal: context.signal,
100
+ label: "The image request",
101
+ });
102
+ if (!result.ok)
103
+ return fail(mappedText(ERRORS, result));
104
+ const data = result.data ?? {};
105
+ const ext = EXT[data.media_type];
106
+ if (!ext) {
107
+ return fail(`The server returned an unsupported image type (${data.media_type}). Nothing was saved.`);
108
+ }
109
+ const bytes = Buffer.from(data.image_b64 ?? "", "base64");
110
+ if (bytes.length === 0) {
111
+ return fail("The server returned an empty image. Nothing was saved.");
112
+ }
113
+ if (bytes.length > MAX_BYTES) {
114
+ return fail("The generated image was too large to save (over 8 MB). Nothing was saved.");
115
+ }
116
+ const relative = `images/${slug(name ?? prompt)}-${randomBytes(3).toString("hex")}.${ext}`;
117
+ const failure = await saveImage(ctx.location.directory, relative, bytes);
118
+ if (failure)
119
+ return fail(`Couldn't save the image to images: ${failure}.`);
120
+ deps.log.info("generate_image saved an image", {
121
+ path: relative,
122
+ bytes: bytes.length,
123
+ mediaType: data.media_type,
124
+ model: data.model,
125
+ });
126
+ return done(`Saved image to ${relative} (${ext}, ${bytes.length} bytes). You cannot see the image; reference this path in your answer or code, and tell the user you could not check how it looks.`, {
127
+ ok: true,
128
+ path: relative,
129
+ ...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
130
+ ...(typeof data.model === "string" ? { model: data.model } : {}),
131
+ });
132
+ }
133
+ export async function registerGenerateImageTool(ctx, deps) {
134
+ return ctx.tool.transform((editor) => {
135
+ editor.add({
136
+ name: "generate_image",
137
+ description: "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; you cannot see the image. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
138
+ input: IMAGE_INPUT,
139
+ options: { codemode: false },
140
+ execute: (input, context) => executeGenerateImage(ctx, deps, input, context),
141
+ });
142
+ });
143
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `free_pi_usage`, the free-pi allowance tool.
3
+ *
4
+ * Mirrors the provider CLI: `GET /me/stats` and a compact, human-readable
5
+ * summary. Read-only and gated to free-pi sessions.
6
+ */
7
+ import type { Plugin } from "@opencode/plugin";
8
+ import type { Deps } from "../deps.js";
9
+ export declare function formatUsage(stats: any): string;
10
+ export declare function registerUsageTool(ctx: Plugin.Context, deps: Deps): Promise<{
11
+ dispose: () => Promise<void>;
12
+ }>;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * `free_pi_usage`, the free-pi allowance tool.
3
+ *
4
+ * Mirrors the provider CLI: `GET /me/stats` and a compact, human-readable
5
+ * summary. Read-only and gated to free-pi sessions.
6
+ */
7
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, } from "./api.js";
8
+ const NO_INPUT = {
9
+ type: "object",
10
+ additionalProperties: false,
11
+ properties: {},
12
+ };
13
+ const NO_ARGUMENTS = "free_pi_usage takes no arguments.";
14
+ const SLOW_LANE_NOTICE = "You're out of free credits for today. You can keep working on our spare capacity while it lasts, or buy credits to keep going at full speed.";
15
+ const number = (value) => value.toLocaleString("en-US");
16
+ function formatRefillEt(date) {
17
+ const formatted = new Intl.DateTimeFormat("en-US", {
18
+ timeZone: "America/New_York",
19
+ hour: "numeric",
20
+ minute: "2-digit",
21
+ hour12: true,
22
+ }).format(date);
23
+ return `${formatted} ET`;
24
+ }
25
+ function percentUsed(spentUsd, capUsd) {
26
+ if (!(capUsd > 0))
27
+ return 100;
28
+ return Math.min(100, Math.max(0, Math.round((spentUsd / capUsd) * 100)));
29
+ }
30
+ function creditsLeftLine(remaining, allowance, refillAt) {
31
+ return `${number(remaining)} / ${number(allowance)} credits left today - refills ${formatRefillEt(refillAt)}`;
32
+ }
33
+ export function formatUsage(stats) {
34
+ const t = stats ?? {};
35
+ const remaining = t.remaining_credits_today;
36
+ const allowance = t.allowance_credits;
37
+ const refillAt = t.refill_at;
38
+ const tiered = t.credit_tiers === true &&
39
+ typeof t.premium_credits === "number" &&
40
+ typeof remaining === "number" &&
41
+ typeof allowance === "number" &&
42
+ typeof refillAt === "string";
43
+ const todayLine = typeof remaining === "number" &&
44
+ typeof allowance === "number" &&
45
+ typeof refillAt === "string"
46
+ ? creditsLeftLine(remaining, allowance, new Date(refillAt))
47
+ : `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
48
+ const tieredLines = tiered
49
+ ? [
50
+ creditsLeftLine(remaining, allowance, new Date(refillAt)),
51
+ `premium credits: ${number(t.premium_credits)} (bought ${number(t.premium_bought_credits ?? 0)} - gifted ${number(t.premium_gifted_credits ?? 0)})`,
52
+ ...(typeof t.regular_wallet_credits === "number" &&
53
+ t.regular_wallet_credits > 0
54
+ ? [`referral credits: ${number(t.regular_wallet_credits)}`]
55
+ : []),
56
+ `Premium credits do not reset.${t.premium_get_line ? ` ${t.premium_get_line}` : ""}`,
57
+ ]
58
+ : [];
59
+ return [
60
+ `tier: ${t.tier ?? "unknown"}`,
61
+ ...(tiered ? [tieredLines[0]] : [todayLine]),
62
+ ...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
63
+ ...(tiered
64
+ ? tieredLines.slice(1)
65
+ : [
66
+ ...(typeof t.credit_credits === "number"
67
+ ? [`credit: ${number(t.credit_credits)} credits remaining`]
68
+ : []),
69
+ ...(typeof t.bonus_wallet_credits === "number" &&
70
+ t.bonus_wallet_credits > 0
71
+ ? [`bonus: ${number(t.bonus_wallet_credits)} credits remaining`]
72
+ : []),
73
+ ]),
74
+ ...(typeof t.streak?.message === "string" && t.streak.message
75
+ ? [t.streak.message]
76
+ : []),
77
+ `today tokens: ${t.prompt_tokens_today ?? 0} prompt / ${t.completion_tokens_today ?? 0} completion`,
78
+ `lifetime: ${t.lifetime?.prompt_tokens ?? 0} prompt / ${t.lifetime?.completion_tokens ?? 0} completion tokens`,
79
+ ...(tiered ? [] : ["buy more credits: free_pi_buy_credits"]),
80
+ ...(t.guest
81
+ ? [
82
+ "guest trial: sign in with GitHub for up to 15,000 free credits a day",
83
+ ]
84
+ : []),
85
+ "see details at freepi.ai/dashboard",
86
+ ].join("\n");
87
+ }
88
+ async function executeUsage(deps, raw, context) {
89
+ if (raw && typeof raw === "object" && Object.keys(raw).length > 0) {
90
+ return fail(NO_ARGUMENTS);
91
+ }
92
+ if (!isGatedSession(deps, context.sessionID))
93
+ return fail(GATED_TEXT);
94
+ const result = await freePiRequest(deps, {
95
+ path: "/me/stats",
96
+ timeoutMs: 5_000,
97
+ signal: context.signal,
98
+ audience: "user",
99
+ });
100
+ if (!result.ok)
101
+ return fail(result.text);
102
+ const stats = result.data;
103
+ deps.log.info("free_pi_usage answered", {
104
+ tier: stats?.tier,
105
+ lane: stats?.lane,
106
+ });
107
+ return done(formatUsage(stats), {
108
+ ok: true,
109
+ tier: stats?.tier,
110
+ lane: stats?.lane,
111
+ remaining_credits_today: stats?.remaining_credits_today,
112
+ allowance_credits: stats?.allowance_credits,
113
+ });
114
+ }
115
+ export async function registerUsageTool(ctx, deps) {
116
+ return ctx.tool.transform((editor) => {
117
+ editor.add({
118
+ name: "free_pi_usage",
119
+ description: "Report how much of the caller's free daily allowance is used, remaining credits, token counts and account tier. Read-only, takes no arguments, makes no changes.",
120
+ input: NO_INPUT,
121
+ options: { codemode: false },
122
+ execute: (input, context) => executeUsage(deps, input, context),
123
+ });
124
+ });
125
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `web_search` and `docs_lookup`, backed by free-pi's `/tools/*` endpoints.
3
+ *
4
+ * Both spend part of the user's daily allowance, exactly like the provider
5
+ * CLI, and are only exposed inside free-pi sessions.
6
+ */
7
+ import type { Plugin } from "@opencode/plugin";
8
+ import type { Deps } from "../deps.js";
9
+ export declare function formatWebResults(query: string, results: any[]): string;
10
+ export declare function registerWebTools(ctx: Plugin.Context, deps: Deps): Promise<{
11
+ dispose: () => Promise<void>;
12
+ }>;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * `web_search` and `docs_lookup`, backed by free-pi's `/tools/*` endpoints.
3
+ *
4
+ * Both spend part of the user's daily allowance, exactly like the provider
5
+ * CLI, and are only exposed inside free-pi sessions.
6
+ */
7
+ import { done, fail, freePiRequest, GATED_TEXT, isGatedSession, mappedText, } from "./api.js";
8
+ const ERRORS = {
9
+ daily_cap: "The user's daily free usage is used up. Do not retry; tell the user and continue without this tool.",
10
+ rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
11
+ rate_limited: "Too many calls right now. Wait for the current call to finish, and do not call again in this turn unless needed.",
12
+ not_found: 'No documentation library matched the requested name. Retry once with the package\'s exact name, or use web_search.',
13
+ not_configured: "This tool is not available on this server. Do not call it again in this session.",
14
+ upstream_error: "The search provider failed. You may retry once.",
15
+ guest_login_required: "This tool needs a GitHub sign-in; the guest trial cannot use it. Do not retry; tell the user to sign in, and continue without this tool.",
16
+ guest_unavailable: "The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
17
+ invalid_request: "The server rejected this request. Do not retry it unchanged.",
18
+ };
19
+ const WEB_INPUT = {
20
+ type: "object",
21
+ additionalProperties: false,
22
+ required: ["query"],
23
+ properties: {
24
+ query: {
25
+ type: "string",
26
+ minLength: 1,
27
+ maxLength: 500,
28
+ description: 'Specific query as you would type it into a search engine, e.g. "vite 6 release notes breaking changes"',
29
+ },
30
+ num_results: {
31
+ type: "integer",
32
+ minimum: 1,
33
+ maximum: 10,
34
+ description: "1-10, default 5; use 3 for a quick fact, 8-10 for a survey",
35
+ },
36
+ },
37
+ };
38
+ const DOCS_INPUT = {
39
+ type: "object",
40
+ additionalProperties: false,
41
+ required: ["library", "query"],
42
+ properties: {
43
+ library: {
44
+ type: "string",
45
+ minLength: 1,
46
+ maxLength: 200,
47
+ description: 'Package or library name, e.g. "next.js", "prisma", "@tanstack/react-query"',
48
+ },
49
+ query: {
50
+ type: "string",
51
+ minLength: 1,
52
+ maxLength: 500,
53
+ description: 'One specific question, e.g. "configure middleware matcher for API routes"',
54
+ },
55
+ library_id: {
56
+ type: "string",
57
+ description: "The library_id printed by an earlier docs_lookup, e.g. /vercel/next.js; skips the name search",
58
+ },
59
+ },
60
+ };
61
+ function text(value) {
62
+ return typeof value === "string" ? value.trim() : "";
63
+ }
64
+ export function formatWebResults(query, results) {
65
+ if (!Array.isArray(results) || results.length === 0) {
66
+ return `No results for "${query}". Try a broader or differently worded query.`;
67
+ }
68
+ return `Web results for "${query}":\n\n${results
69
+ .map((item, index) => {
70
+ const published = item?.published_date
71
+ ? `\nPublished: ${item.published_date}`
72
+ : "";
73
+ return `${index + 1}. ${item?.title ?? ""}\n${item?.url ?? ""}${published}\n${item?.text ?? item?.content ?? ""}`;
74
+ })
75
+ .join("\n\n")}`;
76
+ }
77
+ async function executeWebSearch(deps, raw, context) {
78
+ if (!isGatedSession(deps, context.sessionID))
79
+ return fail(GATED_TEXT);
80
+ const input = raw;
81
+ const query = text(input?.query);
82
+ if (!query)
83
+ return fail("web_search needs a query.");
84
+ const num = typeof input?.num_results === "number" ? input.num_results : undefined;
85
+ const result = await freePiRequest(deps, {
86
+ path: "/tools/web-search",
87
+ method: "POST",
88
+ body: { query, ...(num !== undefined ? { num_results: num } : {}) },
89
+ timeoutMs: 30_000,
90
+ signal: context.signal,
91
+ label: "The web search",
92
+ });
93
+ if (!result.ok)
94
+ return fail(mappedText(ERRORS, result));
95
+ deps.log.info("web_search answered", {
96
+ query,
97
+ results: Array.isArray(result.data?.results)
98
+ ? result.data.results.length
99
+ : 0,
100
+ costUsd: result.data?.cost_usd,
101
+ });
102
+ return done(formatWebResults(query, result.data?.results ?? []), {
103
+ ok: true,
104
+ ...(typeof result.data?.cost_usd === "number"
105
+ ? { cost_usd: result.data.cost_usd }
106
+ : {}),
107
+ });
108
+ }
109
+ async function executeDocsLookup(deps, raw, context) {
110
+ if (!isGatedSession(deps, context.sessionID))
111
+ return fail(GATED_TEXT);
112
+ const input = raw;
113
+ const library = text(input?.library);
114
+ const query = text(input?.query);
115
+ const libraryId = text(input?.library_id);
116
+ if (!library)
117
+ return fail("docs_lookup needs a library name.");
118
+ if (!query)
119
+ return fail("docs_lookup needs a specific question.");
120
+ const result = await freePiRequest(deps, {
121
+ path: "/tools/docs",
122
+ method: "POST",
123
+ body: {
124
+ library,
125
+ query,
126
+ ...(libraryId ? { library_id: libraryId } : {}),
127
+ },
128
+ timeoutMs: 30_000,
129
+ signal: context.signal,
130
+ label: "The documentation lookup",
131
+ });
132
+ if (!result.ok)
133
+ return fail(mappedText(ERRORS, result, library));
134
+ const data = result.data ?? {};
135
+ deps.log.info("docs_lookup answered", {
136
+ library,
137
+ libraryID: data.library_id,
138
+ costUsd: data.cost_usd,
139
+ });
140
+ return done(`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`, {
141
+ ok: true,
142
+ library_id: data.library_id,
143
+ ...(typeof data.cost_usd === "number"
144
+ ? { cost_usd: data.cost_usd }
145
+ : {}),
146
+ });
147
+ }
148
+ export async function registerWebTools(ctx, deps) {
149
+ return ctx.tool.transform((editor) => {
150
+ editor.add({
151
+ name: "web_search",
152
+ description: "Search the web and return a numbered list of results, each with title, URL, publish date and page text. Use it for current or recent information that your training data may lack. Each call uses part of the user's daily allowance.",
153
+ input: WEB_INPUT,
154
+ options: { codemode: false },
155
+ execute: (input, context) => executeWebSearch(deps, input, context),
156
+ });
157
+ editor.add({
158
+ name: "docs_lookup",
159
+ description: "Look up current documentation for a third-party library, framework or API. Returns the matching library's title and library_id, then documentation text relevant to your query. Use it instead of relying on memory for exact signatures and options. Each call uses part of the user's daily allowance.",
160
+ input: DOCS_INPUT,
161
+ options: { codemode: false },
162
+ execute: (input, context) => executeDocsLookup(deps, input, context),
163
+ });
164
+ });
165
+ }
package/dist/types.d.ts CHANGED
@@ -95,6 +95,10 @@ export type Catalog = {
95
95
  cost_experiment?: {
96
96
  arm?: string;
97
97
  };
98
+ fusion?: {
99
+ planner?: string;
100
+ executor?: string;
101
+ };
98
102
  };
99
103
  /** Intermediate, SDK-agnostic model shape used while the catalog is built. */
100
104
  export type ModelDefinition = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.3.22",
3
+ "version": "0.4.0",
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": "tsc -p tsconfig.json",
26
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
27
- "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs",
27
+ "test": "npm run build && node test/smoke.mjs && node test/registry.mjs && node test/models.mjs && node test/hooks.mjs && node test/title.mjs && node test/errors.mjs && node test/vision.mjs && node test/tools.mjs",
28
28
  "prepublishOnly": "npm run build",
29
29
  "postinstall": "node scripts/postinstall.mjs"
30
30
  },