@eduardo191labs/opencode-free-pi 0.2.3 → 0.2.5
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 +33 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +220 -1
- package/package.json +1 -1
- package/scripts/postinstall.mjs +28 -3
- package/src/index.ts +256 -1
package/README.md
CHANGED
|
@@ -27,6 +27,39 @@ también `opencode plugin --global @eduardo191labs/opencode-free-pi` (o
|
|
|
27
27
|
Para una instalación local sin `-g`, fuerza el registro con
|
|
28
28
|
`FREEPI_CONFIGURE=1 npm install`.
|
|
29
29
|
|
|
30
|
+
### OpenCode 2
|
|
31
|
+
|
|
32
|
+
OpenCode 2 usa la entrada `plugins` (plural) y carga el paquete desde su
|
|
33
|
+
`exports`. Este paquete exporta las dos formas: el `server` de OpenCode 1.x y
|
|
34
|
+
el `setup` de OpenCode 2, así que el mismo paquete funciona en ambos.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
opencode plugin add @eduardo191labs/opencode-free-pi@latest
|
|
38
|
+
opencode plugin list
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
La lista debe mostrar `free-pi` como `active`, con la versión del paquete. Si
|
|
42
|
+
aparece `failed`, ejecuta `opencode --print-logs` y revisa el `cause=` del log;
|
|
43
|
+
el `ref=` solo no contiene el motivo.
|
|
44
|
+
|
|
45
|
+
El `postinstall` antiguo copiaba `dist/index.js` a
|
|
46
|
+
`~/.config/opencode/plugins/opencode-free-pi.ts`. Ese archivo local no tiene
|
|
47
|
+
versión de paquete y puede quedar desactualizado; en OpenCode 2 bórralo para
|
|
48
|
+
que no compita con el paquete:
|
|
49
|
+
|
|
50
|
+
```powershell
|
|
51
|
+
Remove-Item "$env:USERPROFILE\.config\opencode\plugins\opencode-free-pi.ts" -Force -ErrorAction SilentlyContinue
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
rm -f ~/.config/opencode/plugins/opencode-free-pi.ts
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
En OpenCode 2 el proveedor y las herramientas se registran igual. Las
|
|
59
|
+
credenciales se leen de `FREEPI_JWT` o de
|
|
60
|
+
`~/.free-pi/agent/credentials.json`; el flujo interactivo
|
|
61
|
+
`opencode auth login -p free-pi` corresponde a OpenCode 1.x.
|
|
62
|
+
|
|
30
63
|
## Instalación rápida con script
|
|
31
64
|
|
|
32
65
|
> Pasa el cursor por el bloque de comandos y usa el icono de copiar de GitHub.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { type Plugin } from "@opencode-ai/plugin";
|
|
2
2
|
export declare const FreePiPlugin: Plugin;
|
|
3
|
+
declare function FreePiV2Setup(ctx: any): Promise<() => Promise<void>>;
|
|
3
4
|
declare const _default: {
|
|
4
5
|
id: string;
|
|
6
|
+
setup: typeof FreePiV2Setup;
|
|
5
7
|
server: Plugin;
|
|
6
8
|
};
|
|
7
9
|
export default _default;
|
package/dist/index.js
CHANGED
|
@@ -3055,4 +3055,223 @@ export const FreePiPlugin = async ({ client }, options) => {
|
|
|
3055
3055
|
},
|
|
3056
3056
|
};
|
|
3057
3057
|
};
|
|
3058
|
-
|
|
3058
|
+
function v2Models(providerID, models) {
|
|
3059
|
+
return Object.values(models).map((model) => {
|
|
3060
|
+
const cost = model.cost ?? {};
|
|
3061
|
+
const released = Date.parse(model.release_date ?? "");
|
|
3062
|
+
return {
|
|
3063
|
+
id: model.id,
|
|
3064
|
+
modelID: model.id,
|
|
3065
|
+
providerID,
|
|
3066
|
+
name: model.name ?? model.id,
|
|
3067
|
+
...(model.family ? { family: model.family } : {}),
|
|
3068
|
+
capabilities: {
|
|
3069
|
+
tools: model.tool_call !== false,
|
|
3070
|
+
input: model.modalities?.input ?? ["text"],
|
|
3071
|
+
output: model.modalities?.output ?? ["text"],
|
|
3072
|
+
...(model.temperature === undefined
|
|
3073
|
+
? {}
|
|
3074
|
+
: { temperature: model.temperature }),
|
|
3075
|
+
},
|
|
3076
|
+
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
3077
|
+
id,
|
|
3078
|
+
settings,
|
|
3079
|
+
})),
|
|
3080
|
+
time: { released: Number.isFinite(released) ? released : 0 },
|
|
3081
|
+
cost: [
|
|
3082
|
+
{
|
|
3083
|
+
input: cost.input ?? 0,
|
|
3084
|
+
output: cost.output ?? 0,
|
|
3085
|
+
cache: {
|
|
3086
|
+
read: cost.cache_read ?? cost.input ?? 0,
|
|
3087
|
+
write: cost.cache_write ?? cost.input ?? 0,
|
|
3088
|
+
},
|
|
3089
|
+
},
|
|
3090
|
+
],
|
|
3091
|
+
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
3092
|
+
enabled: true,
|
|
3093
|
+
limit: {
|
|
3094
|
+
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
3095
|
+
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
3096
|
+
},
|
|
3097
|
+
};
|
|
3098
|
+
});
|
|
3099
|
+
}
|
|
3100
|
+
function v2Provider(providerID, name, models, token) {
|
|
3101
|
+
return {
|
|
3102
|
+
info: {
|
|
3103
|
+
id: providerID,
|
|
3104
|
+
name,
|
|
3105
|
+
activation: "enabled",
|
|
3106
|
+
package: "@opencode/ai/providers/openai-compatible",
|
|
3107
|
+
settings: {
|
|
3108
|
+
baseURL: completionsBaseUrl(),
|
|
3109
|
+
apiKey: token ?? "free-pi",
|
|
3110
|
+
},
|
|
3111
|
+
},
|
|
3112
|
+
models: v2Models(providerID, models),
|
|
3113
|
+
};
|
|
3114
|
+
}
|
|
3115
|
+
function v2Client(ctx) {
|
|
3116
|
+
const context = async (sessionID) => {
|
|
3117
|
+
try {
|
|
3118
|
+
return await ctx.session.context({ sessionID });
|
|
3119
|
+
}
|
|
3120
|
+
catch {
|
|
3121
|
+
return [];
|
|
3122
|
+
}
|
|
3123
|
+
};
|
|
3124
|
+
return {
|
|
3125
|
+
app: { log: async () => undefined },
|
|
3126
|
+
auth: { set: async () => undefined },
|
|
3127
|
+
tui: { showToast: async () => undefined },
|
|
3128
|
+
session: {
|
|
3129
|
+
messages: async ({ path }) => ({ data: await context(path.id) }),
|
|
3130
|
+
message: async ({ path }) => {
|
|
3131
|
+
const messages = await context(path.id);
|
|
3132
|
+
return {
|
|
3133
|
+
data: messages.find((message) => (message?.info?.id ?? message?.id) === path.messageID),
|
|
3134
|
+
};
|
|
3135
|
+
},
|
|
3136
|
+
},
|
|
3137
|
+
};
|
|
3138
|
+
}
|
|
3139
|
+
function settle(promise, fallback) {
|
|
3140
|
+
return Promise.race([
|
|
3141
|
+
promise,
|
|
3142
|
+
new Promise((resolve) => setTimeout(() => resolve(fallback), 6000)),
|
|
3143
|
+
]);
|
|
3144
|
+
}
|
|
3145
|
+
async function FreePiV2Setup(ctx) {
|
|
3146
|
+
const includeDefense = ctx.options?.includeDefense !== false;
|
|
3147
|
+
const [catalog, registry] = await Promise.all([
|
|
3148
|
+
settle(fetchCatalog(), undefined),
|
|
3149
|
+
settle(fetchModelsRegistry(), undefined),
|
|
3150
|
+
]);
|
|
3151
|
+
const { main, defense } = partitionModels(catalog);
|
|
3152
|
+
const candidates = modelRegistryCandidates(registry);
|
|
3153
|
+
const token = await readCredentialsToken();
|
|
3154
|
+
const client = v2Client(ctx);
|
|
3155
|
+
const hooks = await FreePiPlugin({ client }, ctx.options);
|
|
3156
|
+
const registrations = [];
|
|
3157
|
+
await ctx.provider.transform((editor) => {
|
|
3158
|
+
editor.add(v2Provider(PROVIDER_ID, "Free Pi", buildModels(main, candidates), token));
|
|
3159
|
+
if (includeDefense && defense.length > 0) {
|
|
3160
|
+
editor.add(v2Provider(DEFENSE_PROVIDER_ID, "Free Pi Defense", buildModels(defense, candidates), token));
|
|
3161
|
+
}
|
|
3162
|
+
});
|
|
3163
|
+
try {
|
|
3164
|
+
await ctx.tool.transform((editor) => {
|
|
3165
|
+
for (const [name, definition] of Object.entries(hooks.tool ?? {})) {
|
|
3166
|
+
const args = definition.args && typeof definition.args === "object"
|
|
3167
|
+
? definition.args
|
|
3168
|
+
: {};
|
|
3169
|
+
let input = {
|
|
3170
|
+
type: "object",
|
|
3171
|
+
properties: {},
|
|
3172
|
+
additionalProperties: true,
|
|
3173
|
+
};
|
|
3174
|
+
try {
|
|
3175
|
+
input = tool.schema.toJSONSchema(tool.schema.object(args));
|
|
3176
|
+
delete input.$schema;
|
|
3177
|
+
}
|
|
3178
|
+
catch (error) {
|
|
3179
|
+
console.error(`[free-pi] could not build the schema for ${name}; using a permissive schema`, error);
|
|
3180
|
+
}
|
|
3181
|
+
editor.add({
|
|
3182
|
+
name,
|
|
3183
|
+
description: definition.description ?? name,
|
|
3184
|
+
input,
|
|
3185
|
+
execute: async (value, context) => {
|
|
3186
|
+
const result = await definition.execute(value, {
|
|
3187
|
+
sessionID: context.sessionID,
|
|
3188
|
+
messageID: context.messageID,
|
|
3189
|
+
agent: context.agent,
|
|
3190
|
+
id: context.id,
|
|
3191
|
+
directory: ctx.location?.directory ?? process.cwd(),
|
|
3192
|
+
worktree: ctx.location?.directory ?? process.cwd(),
|
|
3193
|
+
abort: context.signal,
|
|
3194
|
+
});
|
|
3195
|
+
return {
|
|
3196
|
+
content: result?.output ?? result?.title ?? "",
|
|
3197
|
+
metadata: result?.metadata,
|
|
3198
|
+
};
|
|
3199
|
+
},
|
|
3200
|
+
});
|
|
3201
|
+
}
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
catch (error) {
|
|
3205
|
+
console.error("[free-pi] could not register tools in OpenCode 2", error);
|
|
3206
|
+
}
|
|
3207
|
+
const applyRequest = async (event) => {
|
|
3208
|
+
const providerID = event.model?.providerID;
|
|
3209
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3210
|
+
return;
|
|
3211
|
+
const output = {
|
|
3212
|
+
maxOutputTokens: event.options?.maxTokens,
|
|
3213
|
+
headers: event.headers ?? {},
|
|
3214
|
+
};
|
|
3215
|
+
await hooks["chat.params"]?.({ sessionID: event.sessionID, model: event.model }, output);
|
|
3216
|
+
if (output.maxOutputTokens !== undefined) {
|
|
3217
|
+
event.options = {
|
|
3218
|
+
...(event.options ?? {}),
|
|
3219
|
+
maxTokens: output.maxOutputTokens,
|
|
3220
|
+
};
|
|
3221
|
+
}
|
|
3222
|
+
if (costExperimentArm === "efficiency" &&
|
|
3223
|
+
!event.system?.some((part) => part.type === "text" && part.text === EFFICIENCY_RULE)) {
|
|
3224
|
+
event.system?.push({ type: "text", text: EFFICIENCY_RULE });
|
|
3225
|
+
}
|
|
3226
|
+
};
|
|
3227
|
+
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
3228
|
+
try {
|
|
3229
|
+
registrations.push(await ctx.session.hook(kind, applyRequest));
|
|
3230
|
+
}
|
|
3231
|
+
catch (error) {
|
|
3232
|
+
console.error(`[free-pi] could not register the ${kind} hook`, error);
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
try {
|
|
3236
|
+
registrations.push(await ctx.session.hook("model.request", async (event) => {
|
|
3237
|
+
const providerID = event.model?.providerID;
|
|
3238
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3239
|
+
return;
|
|
3240
|
+
event.headers ??= {};
|
|
3241
|
+
const current = await resolveToken(client);
|
|
3242
|
+
if (current)
|
|
3243
|
+
event.headers.authorization = `Bearer ${current}`;
|
|
3244
|
+
event.headers["x-session-id"] = event.sessionID;
|
|
3245
|
+
event.headers["x-client-version"] = latestClientVersion;
|
|
3246
|
+
if (costExperimentArm)
|
|
3247
|
+
event.headers[COST_EXPERIMENT_HEADER] = costExperimentArm;
|
|
3248
|
+
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
3249
|
+
const lastUser = [...messages]
|
|
3250
|
+
.reverse()
|
|
3251
|
+
.find((message) => (message?.info?.role ?? message?.role) === "user");
|
|
3252
|
+
const messageID = lastUser?.info?.id ?? lastUser?.id;
|
|
3253
|
+
const input = {
|
|
3254
|
+
sessionID: event.sessionID,
|
|
3255
|
+
model: event.model,
|
|
3256
|
+
agent: event.agent,
|
|
3257
|
+
message: messageID ? { id: messageID } : undefined,
|
|
3258
|
+
};
|
|
3259
|
+
const output = { headers: event.headers };
|
|
3260
|
+
await hooks["chat.headers"]?.(input, output);
|
|
3261
|
+
}));
|
|
3262
|
+
}
|
|
3263
|
+
catch (error) {
|
|
3264
|
+
console.error("[free-pi] could not register the request hook", error);
|
|
3265
|
+
}
|
|
3266
|
+
return async () => {
|
|
3267
|
+
for (const registration of registrations.reverse()) {
|
|
3268
|
+
await registration.dispose?.().catch(() => undefined);
|
|
3269
|
+
}
|
|
3270
|
+
await hooks.dispose?.().catch(() => undefined);
|
|
3271
|
+
};
|
|
3272
|
+
}
|
|
3273
|
+
export default {
|
|
3274
|
+
id: PROVIDER_ID,
|
|
3275
|
+
setup: FreePiV2Setup,
|
|
3276
|
+
server: FreePiPlugin,
|
|
3277
|
+
};
|
package/package.json
CHANGED
package/scripts/postinstall.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { copyFile, mkdir } from "node:fs/promises";
|
|
1
|
+
import { copyFile, mkdir, readFile, rm } from "node:fs/promises";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -9,7 +9,9 @@ const source = join(packageRoot, "dist", "index.js");
|
|
|
9
9
|
const isGlobal = process.env.npm_config_global === "true";
|
|
10
10
|
|
|
11
11
|
if (!isGlobal && process.env.FREEPI_CONFIGURE !== "1") {
|
|
12
|
-
console.log(
|
|
12
|
+
console.log(
|
|
13
|
+
"free-pi: instalación local; usa `npm i -g` o FREEPI_CONFIGURE=1 para registrar el plugin.",
|
|
14
|
+
);
|
|
13
15
|
process.exit(0);
|
|
14
16
|
}
|
|
15
17
|
|
|
@@ -32,8 +34,31 @@ function display(file) {
|
|
|
32
34
|
return file.replace(home, "~");
|
|
33
35
|
}
|
|
34
36
|
|
|
37
|
+
const configNames = ["opencode.json", "opencode.jsonc", "opencode.json5"];
|
|
38
|
+
let configured = false;
|
|
39
|
+
for (const name of configNames) {
|
|
40
|
+
const file = join(configDir, name);
|
|
41
|
+
if (!existsSync(file)) continue;
|
|
42
|
+
try {
|
|
43
|
+
const text = await readFile(file, "utf8");
|
|
44
|
+
configured = /@eduardo191labs\/opencode-free-pi/.test(text);
|
|
45
|
+
} catch {}
|
|
46
|
+
if (configured) break;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (configured) {
|
|
50
|
+
await rm(target, { force: true });
|
|
51
|
+
console.log(
|
|
52
|
+
"free-pi: el paquete ya está configurado en OpenCode; se omitió el plugin local.",
|
|
53
|
+
);
|
|
54
|
+
console.log("free-pi: reinicia OpenCode y ejecuta `opencode plugin list`.");
|
|
55
|
+
process.exit(0);
|
|
56
|
+
}
|
|
57
|
+
|
|
35
58
|
await mkdir(pluginDir, { recursive: true });
|
|
36
59
|
await copyFile(source, target);
|
|
37
60
|
|
|
38
61
|
console.log(`free-pi: plugin instalado en ${display(target)}`);
|
|
39
|
-
console.log(
|
|
62
|
+
console.log(
|
|
63
|
+
"free-pi: reinicia OpenCode y ejecuta `opencode auth login -p free-pi`.",
|
|
64
|
+
);
|
package/src/index.ts
CHANGED
|
@@ -3682,4 +3682,259 @@ export const FreePiPlugin: Plugin = async ({ client }, options) => {
|
|
|
3682
3682
|
};
|
|
3683
3683
|
};
|
|
3684
3684
|
|
|
3685
|
-
|
|
3685
|
+
function v2Models(providerID: string, models: ModelMap): any[] {
|
|
3686
|
+
return Object.values(models).map((model: any) => {
|
|
3687
|
+
const cost = model.cost ?? {};
|
|
3688
|
+
const released = Date.parse(model.release_date ?? "");
|
|
3689
|
+
return {
|
|
3690
|
+
id: model.id,
|
|
3691
|
+
modelID: model.id,
|
|
3692
|
+
providerID,
|
|
3693
|
+
name: model.name ?? model.id,
|
|
3694
|
+
...(model.family ? { family: model.family } : {}),
|
|
3695
|
+
capabilities: {
|
|
3696
|
+
tools: model.tool_call !== false,
|
|
3697
|
+
input: model.modalities?.input ?? ["text"],
|
|
3698
|
+
output: model.modalities?.output ?? ["text"],
|
|
3699
|
+
...(model.temperature === undefined
|
|
3700
|
+
? {}
|
|
3701
|
+
: { temperature: model.temperature }),
|
|
3702
|
+
},
|
|
3703
|
+
variants: Object.entries(model.variants ?? {}).map(([id, settings]) => ({
|
|
3704
|
+
id,
|
|
3705
|
+
settings,
|
|
3706
|
+
})),
|
|
3707
|
+
time: { released: Number.isFinite(released) ? released : 0 },
|
|
3708
|
+
cost: [
|
|
3709
|
+
{
|
|
3710
|
+
input: cost.input ?? 0,
|
|
3711
|
+
output: cost.output ?? 0,
|
|
3712
|
+
cache: {
|
|
3713
|
+
read: cost.cache_read ?? cost.input ?? 0,
|
|
3714
|
+
write: cost.cache_write ?? cost.input ?? 0,
|
|
3715
|
+
},
|
|
3716
|
+
},
|
|
3717
|
+
],
|
|
3718
|
+
status: model.status === "deprecated" ? "deprecated" : "active",
|
|
3719
|
+
enabled: true,
|
|
3720
|
+
limit: {
|
|
3721
|
+
context: model.limit?.context ?? CONTEXT_WINDOW,
|
|
3722
|
+
output: model.limit?.output ?? MAX_OUTPUT_TOKENS,
|
|
3723
|
+
},
|
|
3724
|
+
};
|
|
3725
|
+
});
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
function v2Provider(
|
|
3729
|
+
providerID: string,
|
|
3730
|
+
name: string,
|
|
3731
|
+
models: ModelMap,
|
|
3732
|
+
token: string | undefined,
|
|
3733
|
+
): any {
|
|
3734
|
+
return {
|
|
3735
|
+
info: {
|
|
3736
|
+
id: providerID,
|
|
3737
|
+
name,
|
|
3738
|
+
activation: "enabled",
|
|
3739
|
+
package: "@opencode/ai/providers/openai-compatible",
|
|
3740
|
+
settings: {
|
|
3741
|
+
baseURL: completionsBaseUrl(),
|
|
3742
|
+
apiKey: token ?? "free-pi",
|
|
3743
|
+
},
|
|
3744
|
+
},
|
|
3745
|
+
models: v2Models(providerID, models),
|
|
3746
|
+
};
|
|
3747
|
+
}
|
|
3748
|
+
|
|
3749
|
+
function v2Client(ctx: any): any {
|
|
3750
|
+
const context = async (sessionID: string) => {
|
|
3751
|
+
try {
|
|
3752
|
+
return await ctx.session.context({ sessionID });
|
|
3753
|
+
} catch {
|
|
3754
|
+
return [];
|
|
3755
|
+
}
|
|
3756
|
+
};
|
|
3757
|
+
return {
|
|
3758
|
+
app: { log: async () => undefined },
|
|
3759
|
+
auth: { set: async () => undefined },
|
|
3760
|
+
tui: { showToast: async () => undefined },
|
|
3761
|
+
session: {
|
|
3762
|
+
messages: async ({ path }: any) => ({ data: await context(path.id) }),
|
|
3763
|
+
message: async ({ path }: any) => {
|
|
3764
|
+
const messages = await context(path.id);
|
|
3765
|
+
return {
|
|
3766
|
+
data: (messages as any[]).find(
|
|
3767
|
+
(message) => (message?.info?.id ?? message?.id) === path.messageID,
|
|
3768
|
+
),
|
|
3769
|
+
};
|
|
3770
|
+
},
|
|
3771
|
+
},
|
|
3772
|
+
};
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
function settle<T>(promise: Promise<T>, fallback: T): Promise<T> {
|
|
3776
|
+
return Promise.race([
|
|
3777
|
+
promise,
|
|
3778
|
+
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), 6000)),
|
|
3779
|
+
]);
|
|
3780
|
+
}
|
|
3781
|
+
|
|
3782
|
+
async function FreePiV2Setup(ctx: any): Promise<() => Promise<void>> {
|
|
3783
|
+
const includeDefense = ctx.options?.includeDefense !== false;
|
|
3784
|
+
const [catalog, registry] = await Promise.all([
|
|
3785
|
+
settle(fetchCatalog(), undefined),
|
|
3786
|
+
settle(fetchModelsRegistry(), undefined),
|
|
3787
|
+
]);
|
|
3788
|
+
const { main, defense } = partitionModels(catalog);
|
|
3789
|
+
const candidates = modelRegistryCandidates(registry);
|
|
3790
|
+
const token = await readCredentialsToken();
|
|
3791
|
+
const client = v2Client(ctx);
|
|
3792
|
+
const hooks: any = await (FreePiPlugin as any)({ client }, ctx.options);
|
|
3793
|
+
const registrations: any[] = [];
|
|
3794
|
+
|
|
3795
|
+
await ctx.provider.transform((editor: any) => {
|
|
3796
|
+
editor.add(
|
|
3797
|
+
v2Provider(PROVIDER_ID, "Free Pi", buildModels(main, candidates), token),
|
|
3798
|
+
);
|
|
3799
|
+
if (includeDefense && defense.length > 0) {
|
|
3800
|
+
editor.add(
|
|
3801
|
+
v2Provider(
|
|
3802
|
+
DEFENSE_PROVIDER_ID,
|
|
3803
|
+
"Free Pi Defense",
|
|
3804
|
+
buildModels(defense, candidates),
|
|
3805
|
+
token,
|
|
3806
|
+
),
|
|
3807
|
+
);
|
|
3808
|
+
}
|
|
3809
|
+
});
|
|
3810
|
+
|
|
3811
|
+
try {
|
|
3812
|
+
await ctx.tool.transform((editor: any) => {
|
|
3813
|
+
for (const [name, definition] of Object.entries<any>(hooks.tool ?? {})) {
|
|
3814
|
+
const args =
|
|
3815
|
+
definition.args && typeof definition.args === "object"
|
|
3816
|
+
? definition.args
|
|
3817
|
+
: {};
|
|
3818
|
+
let input: any = {
|
|
3819
|
+
type: "object",
|
|
3820
|
+
properties: {},
|
|
3821
|
+
additionalProperties: true,
|
|
3822
|
+
};
|
|
3823
|
+
try {
|
|
3824
|
+
input = (tool.schema as any).toJSONSchema(tool.schema.object(args));
|
|
3825
|
+
delete input.$schema;
|
|
3826
|
+
} catch (error) {
|
|
3827
|
+
console.error(
|
|
3828
|
+
`[free-pi] could not build the schema for ${name}; using a permissive schema`,
|
|
3829
|
+
error,
|
|
3830
|
+
);
|
|
3831
|
+
}
|
|
3832
|
+
editor.add({
|
|
3833
|
+
name,
|
|
3834
|
+
description: definition.description ?? name,
|
|
3835
|
+
input,
|
|
3836
|
+
execute: async (value: any, context: any) => {
|
|
3837
|
+
const result = await definition.execute(value, {
|
|
3838
|
+
sessionID: context.sessionID,
|
|
3839
|
+
messageID: context.messageID,
|
|
3840
|
+
agent: context.agent,
|
|
3841
|
+
id: context.id,
|
|
3842
|
+
directory: ctx.location?.directory ?? process.cwd(),
|
|
3843
|
+
worktree: ctx.location?.directory ?? process.cwd(),
|
|
3844
|
+
abort: context.signal,
|
|
3845
|
+
});
|
|
3846
|
+
return {
|
|
3847
|
+
content: result?.output ?? result?.title ?? "",
|
|
3848
|
+
metadata: result?.metadata,
|
|
3849
|
+
};
|
|
3850
|
+
},
|
|
3851
|
+
});
|
|
3852
|
+
}
|
|
3853
|
+
});
|
|
3854
|
+
} catch (error) {
|
|
3855
|
+
console.error("[free-pi] could not register tools in OpenCode 2", error);
|
|
3856
|
+
}
|
|
3857
|
+
|
|
3858
|
+
const applyRequest = async (event: any) => {
|
|
3859
|
+
const providerID = event.model?.providerID;
|
|
3860
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3861
|
+
return;
|
|
3862
|
+
const output: any = {
|
|
3863
|
+
maxOutputTokens: event.options?.maxTokens,
|
|
3864
|
+
headers: event.headers ?? {},
|
|
3865
|
+
};
|
|
3866
|
+
await hooks["chat.params"]?.(
|
|
3867
|
+
{ sessionID: event.sessionID, model: event.model },
|
|
3868
|
+
output,
|
|
3869
|
+
);
|
|
3870
|
+
if (output.maxOutputTokens !== undefined) {
|
|
3871
|
+
event.options = {
|
|
3872
|
+
...(event.options ?? {}),
|
|
3873
|
+
maxTokens: output.maxOutputTokens,
|
|
3874
|
+
};
|
|
3875
|
+
}
|
|
3876
|
+
if (
|
|
3877
|
+
costExperimentArm === "efficiency" &&
|
|
3878
|
+
!event.system?.some(
|
|
3879
|
+
(part: any) => part.type === "text" && part.text === EFFICIENCY_RULE,
|
|
3880
|
+
)
|
|
3881
|
+
) {
|
|
3882
|
+
event.system?.push({ type: "text", text: EFFICIENCY_RULE });
|
|
3883
|
+
}
|
|
3884
|
+
};
|
|
3885
|
+
|
|
3886
|
+
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
3887
|
+
try {
|
|
3888
|
+
registrations.push(await ctx.session.hook(kind, applyRequest));
|
|
3889
|
+
} catch (error) {
|
|
3890
|
+
console.error(`[free-pi] could not register the ${kind} hook`, error);
|
|
3891
|
+
}
|
|
3892
|
+
}
|
|
3893
|
+
|
|
3894
|
+
try {
|
|
3895
|
+
registrations.push(
|
|
3896
|
+
await ctx.session.hook("model.request", async (event: any) => {
|
|
3897
|
+
const providerID = event.model?.providerID;
|
|
3898
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3899
|
+
return;
|
|
3900
|
+
event.headers ??= {};
|
|
3901
|
+
const current = await resolveToken(client);
|
|
3902
|
+
if (current) event.headers.authorization = `Bearer ${current}`;
|
|
3903
|
+
event.headers["x-session-id"] = event.sessionID;
|
|
3904
|
+
event.headers["x-client-version"] = latestClientVersion;
|
|
3905
|
+
if (costExperimentArm)
|
|
3906
|
+
event.headers[COST_EXPERIMENT_HEADER] = costExperimentArm;
|
|
3907
|
+
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
3908
|
+
const lastUser = [...messages]
|
|
3909
|
+
.reverse()
|
|
3910
|
+
.find(
|
|
3911
|
+
(message: any) => (message?.info?.role ?? message?.role) === "user",
|
|
3912
|
+
);
|
|
3913
|
+
const messageID = lastUser?.info?.id ?? lastUser?.id;
|
|
3914
|
+
const input = {
|
|
3915
|
+
sessionID: event.sessionID,
|
|
3916
|
+
model: event.model,
|
|
3917
|
+
agent: event.agent,
|
|
3918
|
+
message: messageID ? { id: messageID } : undefined,
|
|
3919
|
+
};
|
|
3920
|
+
const output = { headers: event.headers };
|
|
3921
|
+
await hooks["chat.headers"]?.(input, output);
|
|
3922
|
+
}),
|
|
3923
|
+
);
|
|
3924
|
+
} catch (error) {
|
|
3925
|
+
console.error("[free-pi] could not register the request hook", error);
|
|
3926
|
+
}
|
|
3927
|
+
|
|
3928
|
+
return async () => {
|
|
3929
|
+
for (const registration of registrations.reverse()) {
|
|
3930
|
+
await registration.dispose?.().catch(() => undefined);
|
|
3931
|
+
}
|
|
3932
|
+
await hooks.dispose?.().catch(() => undefined);
|
|
3933
|
+
};
|
|
3934
|
+
}
|
|
3935
|
+
|
|
3936
|
+
export default {
|
|
3937
|
+
id: PROVIDER_ID,
|
|
3938
|
+
setup: FreePiV2Setup,
|
|
3939
|
+
server: FreePiPlugin,
|
|
3940
|
+
};
|