@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
|
@@ -0,0 +1,195 @@
|
|
|
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
|
+
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import { mkdir, open } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import type { Plugin } from "@opencode/plugin";
|
|
13
|
+
import type { Deps } from "../deps.js";
|
|
14
|
+
import {
|
|
15
|
+
done,
|
|
16
|
+
fail,
|
|
17
|
+
freePiRequest,
|
|
18
|
+
GATED_TEXT,
|
|
19
|
+
isGatedSession,
|
|
20
|
+
mappedText,
|
|
21
|
+
} from "./api.js";
|
|
22
|
+
|
|
23
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
24
|
+
const TIMEOUT_MS = 120_000;
|
|
25
|
+
|
|
26
|
+
const EXT: Record<string, string> = {
|
|
27
|
+
"image/png": "png",
|
|
28
|
+
"image/jpeg": "jpg",
|
|
29
|
+
"image/webp": "webp",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const ERRORS: Record<string, string> = {
|
|
33
|
+
guest_login_required:
|
|
34
|
+
"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.",
|
|
35
|
+
guest_unavailable:
|
|
36
|
+
"The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
|
|
37
|
+
daily_cap:
|
|
38
|
+
"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.",
|
|
39
|
+
rolling_cap:
|
|
40
|
+
"The user's short-term usage limit is reached. Do not retry; continue without this tool.",
|
|
41
|
+
rate_limited:
|
|
42
|
+
"Too many image requests right now. Do not call generate_image again in this turn unless the user asks.",
|
|
43
|
+
not_configured:
|
|
44
|
+
"Image generation is not available on this server. Do not call generate_image again in this session.",
|
|
45
|
+
upstream_error: "The image provider failed. You may retry once.",
|
|
46
|
+
account_review:
|
|
47
|
+
"This account is under review, so image generation is disabled. Do not retry; tell the user and continue without it.",
|
|
48
|
+
content_rejected:
|
|
49
|
+
"The image provider rejected this prompt. Do not retry the same prompt; tell the user and offer to reword it.",
|
|
50
|
+
invalid_request:
|
|
51
|
+
"The server rejected this request. Do not retry it unchanged.",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const IMAGE_INPUT = {
|
|
55
|
+
type: "object",
|
|
56
|
+
additionalProperties: false,
|
|
57
|
+
required: ["prompt"],
|
|
58
|
+
properties: {
|
|
59
|
+
prompt: {
|
|
60
|
+
type: "string",
|
|
61
|
+
minLength: 1,
|
|
62
|
+
maxLength: 1_000,
|
|
63
|
+
description:
|
|
64
|
+
"What to draw: subject, style, any exact text to render, and composition",
|
|
65
|
+
},
|
|
66
|
+
aspect_ratio: {
|
|
67
|
+
type: "string",
|
|
68
|
+
enum: ["1:1", "16:9", "9:16", "4:3", "3:2"],
|
|
69
|
+
description: "Default 1:1",
|
|
70
|
+
},
|
|
71
|
+
name: {
|
|
72
|
+
type: "string",
|
|
73
|
+
maxLength: 60,
|
|
74
|
+
description:
|
|
75
|
+
"Short file name hint, e.g. hero-banner; used only for the saved file's name",
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
} as const;
|
|
79
|
+
|
|
80
|
+
export function slug(value: string): string {
|
|
81
|
+
return (
|
|
82
|
+
value
|
|
83
|
+
.toLowerCase()
|
|
84
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
85
|
+
.replace(/^-+/, "")
|
|
86
|
+
.slice(0, 40)
|
|
87
|
+
.replace(/-+$/, "") || "image"
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function saveImage(
|
|
92
|
+
directory: string,
|
|
93
|
+
relative: string,
|
|
94
|
+
bytes: Buffer,
|
|
95
|
+
): Promise<string | undefined> {
|
|
96
|
+
try {
|
|
97
|
+
await mkdir(join(directory, "images"), { recursive: true });
|
|
98
|
+
const handle = await open(join(directory, relative), "wx");
|
|
99
|
+
try {
|
|
100
|
+
await handle.writeFile(bytes);
|
|
101
|
+
} finally {
|
|
102
|
+
await handle.close();
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
} catch (error: any) {
|
|
106
|
+
const reasons: Record<string, string> = {
|
|
107
|
+
EACCES: "permission denied",
|
|
108
|
+
EPERM: "permission denied",
|
|
109
|
+
ENOSPC: "the disk is full",
|
|
110
|
+
ENOENT: "the folder does not exist",
|
|
111
|
+
};
|
|
112
|
+
const why = reasons[error?.code ?? ""] ?? "it could not be written";
|
|
113
|
+
return why;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function executeGenerateImage(
|
|
118
|
+
ctx: Plugin.Context,
|
|
119
|
+
deps: Deps,
|
|
120
|
+
raw: unknown,
|
|
121
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
122
|
+
) {
|
|
123
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
124
|
+
const input = raw as any;
|
|
125
|
+
const prompt =
|
|
126
|
+
typeof input?.prompt === "string" ? input.prompt.trim() : "";
|
|
127
|
+
if (!prompt) return fail("generate_image needs a prompt.");
|
|
128
|
+
const aspectRatio =
|
|
129
|
+
typeof input?.aspect_ratio === "string" ? input.aspect_ratio : undefined;
|
|
130
|
+
const name = typeof input?.name === "string" ? input.name : undefined;
|
|
131
|
+
|
|
132
|
+
const result = await freePiRequest(deps, {
|
|
133
|
+
path: "/tools/image",
|
|
134
|
+
method: "POST",
|
|
135
|
+
body: { prompt, ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}) },
|
|
136
|
+
timeoutMs: TIMEOUT_MS,
|
|
137
|
+
signal: context.signal,
|
|
138
|
+
label: "The image request",
|
|
139
|
+
});
|
|
140
|
+
if (!result.ok) return fail(mappedText(ERRORS, result));
|
|
141
|
+
|
|
142
|
+
const data = result.data ?? {};
|
|
143
|
+
const ext = EXT[data.media_type];
|
|
144
|
+
if (!ext) {
|
|
145
|
+
return fail(
|
|
146
|
+
`The server returned an unsupported image type (${data.media_type}). Nothing was saved.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const bytes = Buffer.from(data.image_b64 ?? "", "base64");
|
|
150
|
+
if (bytes.length === 0) {
|
|
151
|
+
return fail("The server returned an empty image. Nothing was saved.");
|
|
152
|
+
}
|
|
153
|
+
if (bytes.length > MAX_BYTES) {
|
|
154
|
+
return fail(
|
|
155
|
+
"The generated image was too large to save (over 8 MB). Nothing was saved.",
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const relative = `images/${slug(name ?? prompt)}-${randomBytes(3).toString("hex")}.${ext}`;
|
|
160
|
+
const failure = await saveImage(ctx.location.directory, relative, bytes);
|
|
161
|
+
if (failure) return fail(`Couldn't save the image to images: ${failure}.`);
|
|
162
|
+
|
|
163
|
+
deps.log.info("generate_image saved an image", {
|
|
164
|
+
path: relative,
|
|
165
|
+
bytes: bytes.length,
|
|
166
|
+
mediaType: data.media_type,
|
|
167
|
+
model: data.model,
|
|
168
|
+
});
|
|
169
|
+
return done(
|
|
170
|
+
`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.`,
|
|
171
|
+
{
|
|
172
|
+
ok: true,
|
|
173
|
+
path: relative,
|
|
174
|
+
...(typeof data.cost_usd === "number" ? { cost_usd: data.cost_usd } : {}),
|
|
175
|
+
...(typeof data.model === "string" ? { model: data.model } : {}),
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function registerGenerateImageTool(
|
|
181
|
+
ctx: Plugin.Context,
|
|
182
|
+
deps: Deps,
|
|
183
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
184
|
+
return ctx.tool.transform((editor) => {
|
|
185
|
+
editor.add({
|
|
186
|
+
name: "generate_image",
|
|
187
|
+
description:
|
|
188
|
+
"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.",
|
|
189
|
+
input: IMAGE_INPUT,
|
|
190
|
+
options: { codemode: false },
|
|
191
|
+
execute: (input: unknown, context: any) =>
|
|
192
|
+
executeGenerateImage(ctx, deps, input, context),
|
|
193
|
+
} as any);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
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
|
+
|
|
8
|
+
import type { Plugin } from "@opencode/plugin";
|
|
9
|
+
import type { Deps } from "../deps.js";
|
|
10
|
+
import {
|
|
11
|
+
done,
|
|
12
|
+
fail,
|
|
13
|
+
freePiRequest,
|
|
14
|
+
friendlyStatus,
|
|
15
|
+
GATED_TEXT,
|
|
16
|
+
isGatedSession,
|
|
17
|
+
} from "./api.js";
|
|
18
|
+
|
|
19
|
+
const NO_INPUT = {
|
|
20
|
+
type: "object",
|
|
21
|
+
additionalProperties: false,
|
|
22
|
+
properties: {},
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
const NO_ARGUMENTS = "free_pi_usage takes no arguments.";
|
|
26
|
+
|
|
27
|
+
const SLOW_LANE_NOTICE =
|
|
28
|
+
"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.";
|
|
29
|
+
|
|
30
|
+
const number = (value: number) => value.toLocaleString("en-US");
|
|
31
|
+
|
|
32
|
+
function formatRefillEt(date: Date): string {
|
|
33
|
+
const formatted = new Intl.DateTimeFormat("en-US", {
|
|
34
|
+
timeZone: "America/New_York",
|
|
35
|
+
hour: "numeric",
|
|
36
|
+
minute: "2-digit",
|
|
37
|
+
hour12: true,
|
|
38
|
+
}).format(date);
|
|
39
|
+
return `${formatted} ET`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function percentUsed(spentUsd: number, capUsd: number): number {
|
|
43
|
+
if (!(capUsd > 0)) return 100;
|
|
44
|
+
return Math.min(100, Math.max(0, Math.round((spentUsd / capUsd) * 100)));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function creditsLeftLine(
|
|
48
|
+
remaining: number,
|
|
49
|
+
allowance: number,
|
|
50
|
+
refillAt: Date,
|
|
51
|
+
): string {
|
|
52
|
+
return `${number(remaining)} / ${number(allowance)} credits left today - refills ${formatRefillEt(refillAt)}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function formatUsage(stats: any): string {
|
|
56
|
+
const t = stats ?? {};
|
|
57
|
+
const remaining = t.remaining_credits_today;
|
|
58
|
+
const allowance = t.allowance_credits;
|
|
59
|
+
const refillAt = t.refill_at;
|
|
60
|
+
const tiered =
|
|
61
|
+
t.credit_tiers === true &&
|
|
62
|
+
typeof t.premium_credits === "number" &&
|
|
63
|
+
typeof remaining === "number" &&
|
|
64
|
+
typeof allowance === "number" &&
|
|
65
|
+
typeof refillAt === "string";
|
|
66
|
+
|
|
67
|
+
const todayLine =
|
|
68
|
+
typeof remaining === "number" &&
|
|
69
|
+
typeof allowance === "number" &&
|
|
70
|
+
typeof refillAt === "string"
|
|
71
|
+
? creditsLeftLine(remaining, allowance, new Date(refillAt))
|
|
72
|
+
: `today: ${percentUsed(t.spent_usd_today ?? 0, t.cap_usd_today ?? 0)}% of your free daily allowance used`;
|
|
73
|
+
|
|
74
|
+
const tieredLines = tiered
|
|
75
|
+
? [
|
|
76
|
+
creditsLeftLine(remaining, allowance, new Date(refillAt)),
|
|
77
|
+
`premium credits: ${number(t.premium_credits)} (bought ${number(t.premium_bought_credits ?? 0)} - gifted ${number(t.premium_gifted_credits ?? 0)})`,
|
|
78
|
+
...(typeof t.regular_wallet_credits === "number" &&
|
|
79
|
+
t.regular_wallet_credits > 0
|
|
80
|
+
? [`referral credits: ${number(t.regular_wallet_credits)}`]
|
|
81
|
+
: []),
|
|
82
|
+
`Premium credits do not reset.${t.premium_get_line ? ` ${t.premium_get_line}` : ""}`,
|
|
83
|
+
]
|
|
84
|
+
: [];
|
|
85
|
+
|
|
86
|
+
return [
|
|
87
|
+
`tier: ${t.tier ?? "unknown"}`,
|
|
88
|
+
...(tiered ? [tieredLines[0]!] : [todayLine]),
|
|
89
|
+
...(t.lane === "fallback" ? [SLOW_LANE_NOTICE] : []),
|
|
90
|
+
...(tiered
|
|
91
|
+
? tieredLines.slice(1)
|
|
92
|
+
: [
|
|
93
|
+
...(typeof t.credit_credits === "number"
|
|
94
|
+
? [`credit: ${number(t.credit_credits)} credits remaining`]
|
|
95
|
+
: []),
|
|
96
|
+
...(typeof t.bonus_wallet_credits === "number" &&
|
|
97
|
+
t.bonus_wallet_credits > 0
|
|
98
|
+
? [`bonus: ${number(t.bonus_wallet_credits)} credits remaining`]
|
|
99
|
+
: []),
|
|
100
|
+
]),
|
|
101
|
+
...(typeof t.streak?.message === "string" && t.streak.message
|
|
102
|
+
? [t.streak.message]
|
|
103
|
+
: []),
|
|
104
|
+
`today tokens: ${t.prompt_tokens_today ?? 0} prompt / ${t.completion_tokens_today ?? 0} completion`,
|
|
105
|
+
`lifetime: ${t.lifetime?.prompt_tokens ?? 0} prompt / ${t.lifetime?.completion_tokens ?? 0} completion tokens`,
|
|
106
|
+
...(tiered ? [] : ["buy more credits: free_pi_buy_credits"]),
|
|
107
|
+
...(t.guest
|
|
108
|
+
? [
|
|
109
|
+
"guest trial: sign in with GitHub for up to 15,000 free credits a day",
|
|
110
|
+
]
|
|
111
|
+
: []),
|
|
112
|
+
"see details at freepi.ai/dashboard",
|
|
113
|
+
].join("\n");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function executeUsage(
|
|
117
|
+
deps: Deps,
|
|
118
|
+
raw: unknown,
|
|
119
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
120
|
+
) {
|
|
121
|
+
if (raw && typeof raw === "object" && Object.keys(raw as object).length > 0) {
|
|
122
|
+
return fail(NO_ARGUMENTS);
|
|
123
|
+
}
|
|
124
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
125
|
+
|
|
126
|
+
const result = await freePiRequest(deps, {
|
|
127
|
+
path: "/me/stats",
|
|
128
|
+
timeoutMs: 5_000,
|
|
129
|
+
signal: context.signal,
|
|
130
|
+
audience: "user",
|
|
131
|
+
});
|
|
132
|
+
if (!result.ok) return fail(result.text);
|
|
133
|
+
|
|
134
|
+
const stats = result.data;
|
|
135
|
+
deps.log.info("free_pi_usage answered", {
|
|
136
|
+
tier: stats?.tier,
|
|
137
|
+
lane: stats?.lane,
|
|
138
|
+
});
|
|
139
|
+
return done(formatUsage(stats), {
|
|
140
|
+
ok: true,
|
|
141
|
+
tier: stats?.tier,
|
|
142
|
+
lane: stats?.lane,
|
|
143
|
+
remaining_credits_today: stats?.remaining_credits_today,
|
|
144
|
+
allowance_credits: stats?.allowance_credits,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function registerUsageTool(
|
|
149
|
+
ctx: Plugin.Context,
|
|
150
|
+
deps: Deps,
|
|
151
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
152
|
+
return ctx.tool.transform((editor) => {
|
|
153
|
+
editor.add({
|
|
154
|
+
name: "free_pi_usage",
|
|
155
|
+
description:
|
|
156
|
+
"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.",
|
|
157
|
+
input: NO_INPUT,
|
|
158
|
+
options: { codemode: false },
|
|
159
|
+
execute: (input: unknown, context: any) =>
|
|
160
|
+
executeUsage(deps, input, context),
|
|
161
|
+
} as any);
|
|
162
|
+
});
|
|
163
|
+
}
|
package/src/tools/web.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
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
|
+
|
|
8
|
+
import type { Plugin } from "@opencode/plugin";
|
|
9
|
+
import type { Deps } from "../deps.js";
|
|
10
|
+
import {
|
|
11
|
+
done,
|
|
12
|
+
fail,
|
|
13
|
+
freePiRequest,
|
|
14
|
+
GATED_TEXT,
|
|
15
|
+
isGatedSession,
|
|
16
|
+
mappedText,
|
|
17
|
+
} from "./api.js";
|
|
18
|
+
|
|
19
|
+
const ERRORS: Record<string, string> = {
|
|
20
|
+
daily_cap:
|
|
21
|
+
"The user's daily free usage is used up. Do not retry; tell the user and continue without this tool.",
|
|
22
|
+
rolling_cap:
|
|
23
|
+
"The user's short-term usage limit is reached. Do not retry; continue without this tool.",
|
|
24
|
+
rate_limited:
|
|
25
|
+
"Too many calls right now. Wait for the current call to finish, and do not call again in this turn unless needed.",
|
|
26
|
+
not_found:
|
|
27
|
+
'No documentation library matched the requested name. Retry once with the package\'s exact name, or use web_search.',
|
|
28
|
+
not_configured:
|
|
29
|
+
"This tool is not available on this server. Do not call it again in this session.",
|
|
30
|
+
upstream_error: "The search provider failed. You may retry once.",
|
|
31
|
+
guest_login_required:
|
|
32
|
+
"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.",
|
|
33
|
+
guest_unavailable:
|
|
34
|
+
"The guest trial is not available right now. Do not retry; tell the user to sign in with GitHub, and continue without this tool.",
|
|
35
|
+
invalid_request:
|
|
36
|
+
"The server rejected this request. Do not retry it unchanged.",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const WEB_INPUT = {
|
|
40
|
+
type: "object",
|
|
41
|
+
additionalProperties: false,
|
|
42
|
+
required: ["query"],
|
|
43
|
+
properties: {
|
|
44
|
+
query: {
|
|
45
|
+
type: "string",
|
|
46
|
+
minLength: 1,
|
|
47
|
+
maxLength: 500,
|
|
48
|
+
description:
|
|
49
|
+
'Specific query as you would type it into a search engine, e.g. "vite 6 release notes breaking changes"',
|
|
50
|
+
},
|
|
51
|
+
num_results: {
|
|
52
|
+
type: "integer",
|
|
53
|
+
minimum: 1,
|
|
54
|
+
maximum: 10,
|
|
55
|
+
description: "1-10, default 5; use 3 for a quick fact, 8-10 for a survey",
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
} as const;
|
|
59
|
+
|
|
60
|
+
const DOCS_INPUT = {
|
|
61
|
+
type: "object",
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
required: ["library", "query"],
|
|
64
|
+
properties: {
|
|
65
|
+
library: {
|
|
66
|
+
type: "string",
|
|
67
|
+
minLength: 1,
|
|
68
|
+
maxLength: 200,
|
|
69
|
+
description:
|
|
70
|
+
'Package or library name, e.g. "next.js", "prisma", "@tanstack/react-query"',
|
|
71
|
+
},
|
|
72
|
+
query: {
|
|
73
|
+
type: "string",
|
|
74
|
+
minLength: 1,
|
|
75
|
+
maxLength: 500,
|
|
76
|
+
description:
|
|
77
|
+
'One specific question, e.g. "configure middleware matcher for API routes"',
|
|
78
|
+
},
|
|
79
|
+
library_id: {
|
|
80
|
+
type: "string",
|
|
81
|
+
description:
|
|
82
|
+
"The library_id printed by an earlier docs_lookup, e.g. /vercel/next.js; skips the name search",
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
} as const;
|
|
86
|
+
|
|
87
|
+
function text(value: unknown): string {
|
|
88
|
+
return typeof value === "string" ? value.trim() : "";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function formatWebResults(query: string, results: any[]): string {
|
|
92
|
+
if (!Array.isArray(results) || results.length === 0) {
|
|
93
|
+
return `No results for "${query}". Try a broader or differently worded query.`;
|
|
94
|
+
}
|
|
95
|
+
return `Web results for "${query}":\n\n${results
|
|
96
|
+
.map((item, index) => {
|
|
97
|
+
const published = item?.published_date
|
|
98
|
+
? `\nPublished: ${item.published_date}`
|
|
99
|
+
: "";
|
|
100
|
+
return `${index + 1}. ${item?.title ?? ""}\n${item?.url ?? ""}${published}\n${item?.text ?? item?.content ?? ""}`;
|
|
101
|
+
})
|
|
102
|
+
.join("\n\n")}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function executeWebSearch(
|
|
106
|
+
deps: Deps,
|
|
107
|
+
raw: unknown,
|
|
108
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
109
|
+
) {
|
|
110
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
111
|
+
const input = raw as any;
|
|
112
|
+
const query = text(input?.query);
|
|
113
|
+
if (!query) return fail("web_search needs a query.");
|
|
114
|
+
const num =
|
|
115
|
+
typeof input?.num_results === "number" ? input.num_results : undefined;
|
|
116
|
+
|
|
117
|
+
const result = await freePiRequest(deps, {
|
|
118
|
+
path: "/tools/web-search",
|
|
119
|
+
method: "POST",
|
|
120
|
+
body: { query, ...(num !== undefined ? { num_results: num } : {}) },
|
|
121
|
+
timeoutMs: 30_000,
|
|
122
|
+
signal: context.signal,
|
|
123
|
+
label: "The web search",
|
|
124
|
+
});
|
|
125
|
+
if (!result.ok) return fail(mappedText(ERRORS, result));
|
|
126
|
+
|
|
127
|
+
deps.log.info("web_search answered", {
|
|
128
|
+
query,
|
|
129
|
+
results: Array.isArray(result.data?.results)
|
|
130
|
+
? result.data.results.length
|
|
131
|
+
: 0,
|
|
132
|
+
costUsd: result.data?.cost_usd,
|
|
133
|
+
});
|
|
134
|
+
return done(formatWebResults(query, result.data?.results ?? []), {
|
|
135
|
+
ok: true,
|
|
136
|
+
...(typeof result.data?.cost_usd === "number"
|
|
137
|
+
? { cost_usd: result.data.cost_usd }
|
|
138
|
+
: {}),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function executeDocsLookup(
|
|
143
|
+
deps: Deps,
|
|
144
|
+
raw: unknown,
|
|
145
|
+
context: { readonly sessionID: string; readonly signal: AbortSignal },
|
|
146
|
+
) {
|
|
147
|
+
if (!isGatedSession(deps, context.sessionID)) return fail(GATED_TEXT);
|
|
148
|
+
const input = raw as any;
|
|
149
|
+
const library = text(input?.library);
|
|
150
|
+
const query = text(input?.query);
|
|
151
|
+
const libraryId = text(input?.library_id);
|
|
152
|
+
if (!library) return fail("docs_lookup needs a library name.");
|
|
153
|
+
if (!query) return fail("docs_lookup needs a specific question.");
|
|
154
|
+
|
|
155
|
+
const result = await freePiRequest(deps, {
|
|
156
|
+
path: "/tools/docs",
|
|
157
|
+
method: "POST",
|
|
158
|
+
body: {
|
|
159
|
+
library,
|
|
160
|
+
query,
|
|
161
|
+
...(libraryId ? { library_id: libraryId } : {}),
|
|
162
|
+
},
|
|
163
|
+
timeoutMs: 30_000,
|
|
164
|
+
signal: context.signal,
|
|
165
|
+
label: "The documentation lookup",
|
|
166
|
+
});
|
|
167
|
+
if (!result.ok) return fail(mappedText(ERRORS, result, library));
|
|
168
|
+
|
|
169
|
+
const data = result.data ?? {};
|
|
170
|
+
deps.log.info("docs_lookup answered", {
|
|
171
|
+
library,
|
|
172
|
+
libraryID: data.library_id,
|
|
173
|
+
costUsd: data.cost_usd,
|
|
174
|
+
});
|
|
175
|
+
return done(
|
|
176
|
+
`${data.title ?? library} (library_id: ${data.library_id ?? "unknown"})\n\n${data.docs ?? ""}`,
|
|
177
|
+
{
|
|
178
|
+
ok: true,
|
|
179
|
+
library_id: data.library_id,
|
|
180
|
+
...(typeof data.cost_usd === "number"
|
|
181
|
+
? { cost_usd: data.cost_usd }
|
|
182
|
+
: {}),
|
|
183
|
+
},
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function registerWebTools(
|
|
188
|
+
ctx: Plugin.Context,
|
|
189
|
+
deps: Deps,
|
|
190
|
+
): Promise<{ dispose: () => Promise<void> }> {
|
|
191
|
+
return ctx.tool.transform((editor) => {
|
|
192
|
+
editor.add({
|
|
193
|
+
name: "web_search",
|
|
194
|
+
description:
|
|
195
|
+
"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.",
|
|
196
|
+
input: WEB_INPUT,
|
|
197
|
+
options: { codemode: false },
|
|
198
|
+
execute: (input: unknown, context: any) =>
|
|
199
|
+
executeWebSearch(deps, input, context),
|
|
200
|
+
} as any);
|
|
201
|
+
|
|
202
|
+
editor.add({
|
|
203
|
+
name: "docs_lookup",
|
|
204
|
+
description:
|
|
205
|
+
"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.",
|
|
206
|
+
input: DOCS_INPUT,
|
|
207
|
+
options: { codemode: false },
|
|
208
|
+
execute: (input: unknown, context: any) =>
|
|
209
|
+
executeDocsLookup(deps, input, context),
|
|
210
|
+
} as any);
|
|
211
|
+
});
|
|
212
|
+
}
|
package/src/types.ts
CHANGED