@eduardo191labs/opencode-free-pi 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -8
- package/dist/index.js +188 -58
- package/package.json +1 -1
- package/scripts/postinstall.mjs +28 -3
- package/src/index.ts +196 -63
package/README.md
CHANGED
|
@@ -33,16 +33,47 @@ OpenCode 2 usa la entrada `plugins` (plural) y carga el paquete desde su
|
|
|
33
33
|
`exports`. Este paquete exporta las dos formas: el `server` de OpenCode 1.x y
|
|
34
34
|
el `setup` de OpenCode 2, así que el mismo paquete funciona en ambos.
|
|
35
35
|
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}
|
|
36
|
+
```bash
|
|
37
|
+
opencode plugin add @eduardo191labs/opencode-free-pi@latest
|
|
38
|
+
opencode plugin list
|
|
40
39
|
```
|
|
41
40
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
+
`opencode plugin add` acumula versiones exactas en `plugins`. Si antes
|
|
46
|
+
instalaste otra versión, la entrada vieja queda como `failed` y no muestra
|
|
47
|
+
`id` ni `version`. Elimínala y deja solo una:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
opencode plugin remove @eduardo191labs/opencode-free-pi@0.2.3
|
|
51
|
+
opencode plugin list
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
El `postinstall` antiguo copiaba `dist/index.js` a
|
|
55
|
+
`~/.config/opencode/plugins/opencode-free-pi.ts`. Ese archivo local no tiene
|
|
56
|
+
versión de paquete y puede quedar desactualizado; en OpenCode 2 bórralo para
|
|
57
|
+
que no compita con el paquete:
|
|
58
|
+
|
|
59
|
+
```powershell
|
|
60
|
+
Remove-Item "$env:USERPROFILE\.config\opencode\plugins\opencode-free-pi.ts" -Force -ErrorAction SilentlyContinue
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
rm -f ~/.config/opencode/plugins/opencode-free-pi.ts
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
En OpenCode 2 el proveedor y las herramientas se registran igual. El plugin
|
|
68
|
+
también registra la integración `free-pi`, así que el inicio de sesión
|
|
69
|
+
interactivo funciona en OpenCode 2:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
opencode auth login free-pi
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Puedes elegir GitHub o pegar un JWT. Las credenciales también se leen de
|
|
76
|
+
`FREEPI_JWT` o de `~/.free-pi/agent/credentials.json`.
|
|
46
77
|
|
|
47
78
|
## Instalación rápida con script
|
|
48
79
|
|
|
@@ -81,6 +112,15 @@ pkg install curl
|
|
|
81
112
|
|
|
82
113
|
## Después de instalar
|
|
83
114
|
|
|
115
|
+
OpenCode 2:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
opencode auth login free-pi
|
|
119
|
+
opencode
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
OpenCode 1.x:
|
|
123
|
+
|
|
84
124
|
```bash
|
|
85
125
|
opencode auth login -p free-pi
|
|
86
126
|
opencode
|
package/dist/index.js
CHANGED
|
@@ -3103,6 +3103,7 @@ function v2Provider(providerID, name, models, token) {
|
|
|
3103
3103
|
id: providerID,
|
|
3104
3104
|
name,
|
|
3105
3105
|
activation: "enabled",
|
|
3106
|
+
integrationID: PROVIDER_ID,
|
|
3106
3107
|
package: "@opencode/ai/providers/openai-compatible",
|
|
3107
3108
|
settings: {
|
|
3108
3109
|
baseURL: completionsBaseUrl(),
|
|
@@ -3112,6 +3113,31 @@ function v2Provider(providerID, name, models, token) {
|
|
|
3112
3113
|
models: v2Models(providerID, models),
|
|
3113
3114
|
};
|
|
3114
3115
|
}
|
|
3116
|
+
async function v2ConnectionAuth(ctx) {
|
|
3117
|
+
try {
|
|
3118
|
+
const connection = await ctx.integration.connection.active(PROVIDER_ID);
|
|
3119
|
+
if (!connection)
|
|
3120
|
+
return undefined;
|
|
3121
|
+
const credential = await ctx.integration.connection.resolve(connection);
|
|
3122
|
+
if (!credential)
|
|
3123
|
+
return undefined;
|
|
3124
|
+
if (credential.type === "oauth")
|
|
3125
|
+
return {
|
|
3126
|
+
type: "oauth",
|
|
3127
|
+
refresh: credential.refresh,
|
|
3128
|
+
access: credential.access,
|
|
3129
|
+
expires: credential.expires,
|
|
3130
|
+
};
|
|
3131
|
+
if (credential.type === "key")
|
|
3132
|
+
return {
|
|
3133
|
+
type: "api",
|
|
3134
|
+
key: credential.key,
|
|
3135
|
+
metadata: credential.metadata,
|
|
3136
|
+
};
|
|
3137
|
+
}
|
|
3138
|
+
catch { }
|
|
3139
|
+
return undefined;
|
|
3140
|
+
}
|
|
3115
3141
|
function v2Client(ctx) {
|
|
3116
3142
|
const context = async (sessionID) => {
|
|
3117
3143
|
try {
|
|
@@ -3136,53 +3162,146 @@ function v2Client(ctx) {
|
|
|
3136
3162
|
},
|
|
3137
3163
|
};
|
|
3138
3164
|
}
|
|
3165
|
+
function settle(promise, fallback) {
|
|
3166
|
+
return Promise.race([
|
|
3167
|
+
promise,
|
|
3168
|
+
new Promise((resolve) => setTimeout(() => resolve(fallback), 6000)),
|
|
3169
|
+
]);
|
|
3170
|
+
}
|
|
3139
3171
|
async function FreePiV2Setup(ctx) {
|
|
3140
3172
|
const includeDefense = ctx.options?.includeDefense !== false;
|
|
3141
3173
|
const [catalog, registry] = await Promise.all([
|
|
3142
|
-
fetchCatalog(),
|
|
3143
|
-
fetchModelsRegistry(),
|
|
3174
|
+
settle(fetchCatalog(), undefined),
|
|
3175
|
+
settle(fetchModelsRegistry(), undefined),
|
|
3144
3176
|
]);
|
|
3145
3177
|
const { main, defense } = partitionModels(catalog);
|
|
3146
3178
|
const candidates = modelRegistryCandidates(registry);
|
|
3147
|
-
const token = await readCredentialsToken();
|
|
3148
3179
|
const client = v2Client(ctx);
|
|
3180
|
+
const connectionAuth = await v2ConnectionAuth(ctx);
|
|
3181
|
+
let token = tokenFromAuth(connectionAuth) ?? (await readCredentialsToken());
|
|
3182
|
+
authResolver = async () => (await v2ConnectionAuth(ctx)) ?? undefined;
|
|
3149
3183
|
const hooks = await FreePiPlugin({ client }, ctx.options);
|
|
3150
3184
|
const registrations = [];
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3185
|
+
const credentialsAbort = new AbortController();
|
|
3186
|
+
void (async () => {
|
|
3187
|
+
try {
|
|
3188
|
+
for await (const _event of ctx.event.subscribe({
|
|
3189
|
+
types: ["credential.updated", "credential.switched"],
|
|
3190
|
+
signal: credentialsAbort.signal,
|
|
3191
|
+
})) {
|
|
3192
|
+
const next = tokenFromAuth(await v2ConnectionAuth(ctx)) ??
|
|
3193
|
+
(await readCredentialsToken());
|
|
3194
|
+
if (next === token)
|
|
3195
|
+
continue;
|
|
3196
|
+
token = next;
|
|
3197
|
+
await ctx.provider.reload().catch(() => undefined);
|
|
3198
|
+
}
|
|
3155
3199
|
}
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
directory: ctx.location?.directory ?? process.cwd(),
|
|
3175
|
-
worktree: ctx.location?.directory ?? process.cwd(),
|
|
3176
|
-
abort: context.signal,
|
|
3177
|
-
});
|
|
3200
|
+
catch { }
|
|
3201
|
+
})();
|
|
3202
|
+
try {
|
|
3203
|
+
registrations.push(await ctx.integration.transform((editor) => {
|
|
3204
|
+
editor.update(PROVIDER_ID, (integration) => {
|
|
3205
|
+
integration.name = "Free Pi";
|
|
3206
|
+
});
|
|
3207
|
+
editor.method.update({
|
|
3208
|
+
integrationID: PROVIDER_ID,
|
|
3209
|
+
method: {
|
|
3210
|
+
id: "github",
|
|
3211
|
+
type: "oauth",
|
|
3212
|
+
label: "Sign in with GitHub (free-pi)",
|
|
3213
|
+
},
|
|
3214
|
+
authorize: async () => {
|
|
3215
|
+
const result = await authorizeFreePi(client);
|
|
3216
|
+
if (result.method !== "auto")
|
|
3217
|
+
throw new Error("free-pi sign-in did not start.");
|
|
3178
3218
|
return {
|
|
3179
|
-
|
|
3180
|
-
|
|
3219
|
+
url: result.url,
|
|
3220
|
+
instructions: result.instructions,
|
|
3221
|
+
mode: "auto",
|
|
3222
|
+
callback: (async () => {
|
|
3223
|
+
const value = await result.callback();
|
|
3224
|
+
if (value.type !== "success")
|
|
3225
|
+
throw new Error("free-pi sign-in failed.");
|
|
3226
|
+
if ("key" in value)
|
|
3227
|
+
return {
|
|
3228
|
+
type: "key",
|
|
3229
|
+
key: value.key,
|
|
3230
|
+
metadata: value.metadata,
|
|
3231
|
+
};
|
|
3232
|
+
return {
|
|
3233
|
+
type: "oauth",
|
|
3234
|
+
methodID: "github",
|
|
3235
|
+
refresh: value.refresh,
|
|
3236
|
+
access: value.access,
|
|
3237
|
+
expires: value.expires,
|
|
3238
|
+
};
|
|
3239
|
+
})(),
|
|
3181
3240
|
};
|
|
3182
3241
|
},
|
|
3183
3242
|
});
|
|
3243
|
+
editor.method.update({
|
|
3244
|
+
integrationID: PROVIDER_ID,
|
|
3245
|
+
method: {
|
|
3246
|
+
type: "key",
|
|
3247
|
+
label: "Paste a free-pi JWT",
|
|
3248
|
+
},
|
|
3249
|
+
});
|
|
3250
|
+
}));
|
|
3251
|
+
}
|
|
3252
|
+
catch (error) {
|
|
3253
|
+
console.error("[free-pi] could not register the OpenCode 2 integration", error);
|
|
3254
|
+
}
|
|
3255
|
+
await ctx.provider.transform((editor) => {
|
|
3256
|
+
editor.add(v2Provider(PROVIDER_ID, "Free Pi", buildModels(main, candidates), token));
|
|
3257
|
+
if (includeDefense && defense.length > 0) {
|
|
3258
|
+
editor.add(v2Provider(DEFENSE_PROVIDER_ID, "Free Pi Defense", buildModels(defense, candidates), token));
|
|
3184
3259
|
}
|
|
3185
3260
|
});
|
|
3261
|
+
try {
|
|
3262
|
+
await ctx.tool.transform((editor) => {
|
|
3263
|
+
for (const [name, definition] of Object.entries(hooks.tool ?? {})) {
|
|
3264
|
+
const args = definition.args && typeof definition.args === "object"
|
|
3265
|
+
? definition.args
|
|
3266
|
+
: {};
|
|
3267
|
+
let input = {
|
|
3268
|
+
type: "object",
|
|
3269
|
+
properties: {},
|
|
3270
|
+
additionalProperties: true,
|
|
3271
|
+
};
|
|
3272
|
+
try {
|
|
3273
|
+
input = tool.schema.toJSONSchema(tool.schema.object(args));
|
|
3274
|
+
delete input.$schema;
|
|
3275
|
+
}
|
|
3276
|
+
catch (error) {
|
|
3277
|
+
console.error(`[free-pi] could not build the schema for ${name}; using a permissive schema`, error);
|
|
3278
|
+
}
|
|
3279
|
+
editor.add({
|
|
3280
|
+
name,
|
|
3281
|
+
description: definition.description ?? name,
|
|
3282
|
+
input,
|
|
3283
|
+
execute: async (value, context) => {
|
|
3284
|
+
const result = await definition.execute(value, {
|
|
3285
|
+
sessionID: context.sessionID,
|
|
3286
|
+
messageID: context.messageID,
|
|
3287
|
+
agent: context.agent,
|
|
3288
|
+
id: context.id,
|
|
3289
|
+
directory: ctx.location?.directory ?? process.cwd(),
|
|
3290
|
+
worktree: ctx.location?.directory ?? process.cwd(),
|
|
3291
|
+
abort: context.signal,
|
|
3292
|
+
});
|
|
3293
|
+
return {
|
|
3294
|
+
content: result?.output ?? result?.title ?? "",
|
|
3295
|
+
metadata: result?.metadata,
|
|
3296
|
+
};
|
|
3297
|
+
},
|
|
3298
|
+
});
|
|
3299
|
+
}
|
|
3300
|
+
});
|
|
3301
|
+
}
|
|
3302
|
+
catch (error) {
|
|
3303
|
+
console.error("[free-pi] could not register tools in OpenCode 2", error);
|
|
3304
|
+
}
|
|
3186
3305
|
const applyRequest = async (event) => {
|
|
3187
3306
|
const providerID = event.model?.providerID;
|
|
3188
3307
|
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
@@ -3204,35 +3323,46 @@ async function FreePiV2Setup(ctx) {
|
|
|
3204
3323
|
}
|
|
3205
3324
|
};
|
|
3206
3325
|
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
3207
|
-
|
|
3326
|
+
try {
|
|
3327
|
+
registrations.push(await ctx.session.hook(kind, applyRequest));
|
|
3328
|
+
}
|
|
3329
|
+
catch (error) {
|
|
3330
|
+
console.error(`[free-pi] could not register the ${kind} hook`, error);
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
try {
|
|
3334
|
+
registrations.push(await ctx.session.hook("model.request", async (event) => {
|
|
3335
|
+
const providerID = event.model?.providerID;
|
|
3336
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3337
|
+
return;
|
|
3338
|
+
event.headers ??= {};
|
|
3339
|
+
const current = await resolveToken(client);
|
|
3340
|
+
if (current)
|
|
3341
|
+
event.headers.authorization = `Bearer ${current}`;
|
|
3342
|
+
event.headers["x-session-id"] = event.sessionID;
|
|
3343
|
+
event.headers["x-client-version"] = latestClientVersion;
|
|
3344
|
+
if (costExperimentArm)
|
|
3345
|
+
event.headers[COST_EXPERIMENT_HEADER] = costExperimentArm;
|
|
3346
|
+
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
3347
|
+
const lastUser = [...messages]
|
|
3348
|
+
.reverse()
|
|
3349
|
+
.find((message) => (message?.info?.role ?? message?.role) === "user");
|
|
3350
|
+
const messageID = lastUser?.info?.id ?? lastUser?.id;
|
|
3351
|
+
const input = {
|
|
3352
|
+
sessionID: event.sessionID,
|
|
3353
|
+
model: event.model,
|
|
3354
|
+
agent: event.agent,
|
|
3355
|
+
message: messageID ? { id: messageID } : undefined,
|
|
3356
|
+
};
|
|
3357
|
+
const output = { headers: event.headers };
|
|
3358
|
+
await hooks["chat.headers"]?.(input, output);
|
|
3359
|
+
}));
|
|
3360
|
+
}
|
|
3361
|
+
catch (error) {
|
|
3362
|
+
console.error("[free-pi] could not register the request hook", error);
|
|
3208
3363
|
}
|
|
3209
|
-
registrations.push(await ctx.session.hook("model.request", async (event) => {
|
|
3210
|
-
const providerID = event.model?.providerID;
|
|
3211
|
-
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
3212
|
-
return;
|
|
3213
|
-
event.headers ??= {};
|
|
3214
|
-
const current = await resolveToken(client);
|
|
3215
|
-
if (current)
|
|
3216
|
-
event.headers.authorization = `Bearer ${current}`;
|
|
3217
|
-
event.headers["x-session-id"] = event.sessionID;
|
|
3218
|
-
event.headers["x-client-version"] = latestClientVersion;
|
|
3219
|
-
if (costExperimentArm)
|
|
3220
|
-
event.headers[COST_EXPERIMENT_HEADER] = costExperimentArm;
|
|
3221
|
-
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
3222
|
-
const lastUser = [...messages]
|
|
3223
|
-
.reverse()
|
|
3224
|
-
.find((message) => (message?.info?.role ?? message?.role) === "user");
|
|
3225
|
-
const messageID = lastUser?.info?.id ?? lastUser?.id;
|
|
3226
|
-
const input = {
|
|
3227
|
-
sessionID: event.sessionID,
|
|
3228
|
-
model: event.model,
|
|
3229
|
-
agent: event.agent,
|
|
3230
|
-
message: messageID ? { id: messageID } : undefined,
|
|
3231
|
-
};
|
|
3232
|
-
const output = { headers: event.headers };
|
|
3233
|
-
await hooks["chat.headers"]?.(input, output);
|
|
3234
|
-
}));
|
|
3235
3364
|
return async () => {
|
|
3365
|
+
credentialsAbort.abort();
|
|
3236
3366
|
for (const registration of registrations.reverse()) {
|
|
3237
3367
|
await registration.dispose?.().catch(() => undefined);
|
|
3238
3368
|
}
|
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
|
@@ -3736,6 +3736,7 @@ function v2Provider(
|
|
|
3736
3736
|
id: providerID,
|
|
3737
3737
|
name,
|
|
3738
3738
|
activation: "enabled",
|
|
3739
|
+
integrationID: PROVIDER_ID,
|
|
3739
3740
|
package: "@opencode/ai/providers/openai-compatible",
|
|
3740
3741
|
settings: {
|
|
3741
3742
|
baseURL: completionsBaseUrl(),
|
|
@@ -3746,6 +3747,29 @@ function v2Provider(
|
|
|
3746
3747
|
};
|
|
3747
3748
|
}
|
|
3748
3749
|
|
|
3750
|
+
async function v2ConnectionAuth(ctx: any): Promise<any | undefined> {
|
|
3751
|
+
try {
|
|
3752
|
+
const connection = await ctx.integration.connection.active(PROVIDER_ID);
|
|
3753
|
+
if (!connection) return undefined;
|
|
3754
|
+
const credential = await ctx.integration.connection.resolve(connection);
|
|
3755
|
+
if (!credential) return undefined;
|
|
3756
|
+
if (credential.type === "oauth")
|
|
3757
|
+
return {
|
|
3758
|
+
type: "oauth",
|
|
3759
|
+
refresh: credential.refresh,
|
|
3760
|
+
access: credential.access,
|
|
3761
|
+
expires: credential.expires,
|
|
3762
|
+
};
|
|
3763
|
+
if (credential.type === "key")
|
|
3764
|
+
return {
|
|
3765
|
+
type: "api",
|
|
3766
|
+
key: credential.key,
|
|
3767
|
+
metadata: credential.metadata,
|
|
3768
|
+
};
|
|
3769
|
+
} catch {}
|
|
3770
|
+
return undefined;
|
|
3771
|
+
}
|
|
3772
|
+
|
|
3749
3773
|
function v2Client(ctx: any): any {
|
|
3750
3774
|
const context = async (sessionID: string) => {
|
|
3751
3775
|
try {
|
|
@@ -3772,18 +3796,102 @@ function v2Client(ctx: any): any {
|
|
|
3772
3796
|
};
|
|
3773
3797
|
}
|
|
3774
3798
|
|
|
3799
|
+
function settle<T>(promise: Promise<T>, fallback: T): Promise<T> {
|
|
3800
|
+
return Promise.race([
|
|
3801
|
+
promise,
|
|
3802
|
+
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), 6000)),
|
|
3803
|
+
]);
|
|
3804
|
+
}
|
|
3805
|
+
|
|
3775
3806
|
async function FreePiV2Setup(ctx: any): Promise<() => Promise<void>> {
|
|
3776
3807
|
const includeDefense = ctx.options?.includeDefense !== false;
|
|
3777
3808
|
const [catalog, registry] = await Promise.all([
|
|
3778
|
-
fetchCatalog(),
|
|
3779
|
-
fetchModelsRegistry(),
|
|
3809
|
+
settle(fetchCatalog(), undefined),
|
|
3810
|
+
settle(fetchModelsRegistry(), undefined),
|
|
3780
3811
|
]);
|
|
3781
3812
|
const { main, defense } = partitionModels(catalog);
|
|
3782
3813
|
const candidates = modelRegistryCandidates(registry);
|
|
3783
|
-
const token = await readCredentialsToken();
|
|
3784
3814
|
const client = v2Client(ctx);
|
|
3815
|
+
const connectionAuth = await v2ConnectionAuth(ctx);
|
|
3816
|
+
let token = tokenFromAuth(connectionAuth) ?? (await readCredentialsToken());
|
|
3817
|
+
authResolver = async () => (await v2ConnectionAuth(ctx)) ?? undefined;
|
|
3785
3818
|
const hooks: any = await (FreePiPlugin as any)({ client }, ctx.options);
|
|
3786
3819
|
const registrations: any[] = [];
|
|
3820
|
+
const credentialsAbort = new AbortController();
|
|
3821
|
+
|
|
3822
|
+
void (async () => {
|
|
3823
|
+
try {
|
|
3824
|
+
for await (const _event of ctx.event.subscribe({
|
|
3825
|
+
types: ["credential.updated", "credential.switched"],
|
|
3826
|
+
signal: credentialsAbort.signal,
|
|
3827
|
+
})) {
|
|
3828
|
+
const next =
|
|
3829
|
+
tokenFromAuth(await v2ConnectionAuth(ctx)) ??
|
|
3830
|
+
(await readCredentialsToken());
|
|
3831
|
+
if (next === token) continue;
|
|
3832
|
+
token = next;
|
|
3833
|
+
await ctx.provider.reload().catch(() => undefined);
|
|
3834
|
+
}
|
|
3835
|
+
} catch {}
|
|
3836
|
+
})();
|
|
3837
|
+
|
|
3838
|
+
try {
|
|
3839
|
+
registrations.push(
|
|
3840
|
+
await ctx.integration.transform((editor: any) => {
|
|
3841
|
+
editor.update(PROVIDER_ID, (integration: any) => {
|
|
3842
|
+
integration.name = "Free Pi";
|
|
3843
|
+
});
|
|
3844
|
+
editor.method.update({
|
|
3845
|
+
integrationID: PROVIDER_ID,
|
|
3846
|
+
method: {
|
|
3847
|
+
id: "github",
|
|
3848
|
+
type: "oauth",
|
|
3849
|
+
label: "Sign in with GitHub (free-pi)",
|
|
3850
|
+
},
|
|
3851
|
+
authorize: async () => {
|
|
3852
|
+
const result = await authorizeFreePi(client);
|
|
3853
|
+
if (result.method !== "auto")
|
|
3854
|
+
throw new Error("free-pi sign-in did not start.");
|
|
3855
|
+
return {
|
|
3856
|
+
url: result.url,
|
|
3857
|
+
instructions: result.instructions,
|
|
3858
|
+
mode: "auto",
|
|
3859
|
+
callback: (async () => {
|
|
3860
|
+
const value = await result.callback();
|
|
3861
|
+
if (value.type !== "success")
|
|
3862
|
+
throw new Error("free-pi sign-in failed.");
|
|
3863
|
+
if ("key" in value)
|
|
3864
|
+
return {
|
|
3865
|
+
type: "key",
|
|
3866
|
+
key: value.key,
|
|
3867
|
+
metadata: value.metadata,
|
|
3868
|
+
};
|
|
3869
|
+
return {
|
|
3870
|
+
type: "oauth",
|
|
3871
|
+
methodID: "github",
|
|
3872
|
+
refresh: value.refresh,
|
|
3873
|
+
access: value.access,
|
|
3874
|
+
expires: value.expires,
|
|
3875
|
+
};
|
|
3876
|
+
})(),
|
|
3877
|
+
};
|
|
3878
|
+
},
|
|
3879
|
+
});
|
|
3880
|
+
editor.method.update({
|
|
3881
|
+
integrationID: PROVIDER_ID,
|
|
3882
|
+
method: {
|
|
3883
|
+
type: "key",
|
|
3884
|
+
label: "Paste a free-pi JWT",
|
|
3885
|
+
},
|
|
3886
|
+
});
|
|
3887
|
+
}),
|
|
3888
|
+
);
|
|
3889
|
+
} catch (error) {
|
|
3890
|
+
console.error(
|
|
3891
|
+
"[free-pi] could not register the OpenCode 2 integration",
|
|
3892
|
+
error,
|
|
3893
|
+
);
|
|
3894
|
+
}
|
|
3787
3895
|
|
|
3788
3896
|
await ctx.provider.transform((editor: any) => {
|
|
3789
3897
|
editor.add(
|
|
@@ -3801,36 +3909,52 @@ async function FreePiV2Setup(ctx: any): Promise<() => Promise<void>> {
|
|
|
3801
3909
|
}
|
|
3802
3910
|
});
|
|
3803
3911
|
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
const
|
|
3807
|
-
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3912
|
+
try {
|
|
3913
|
+
await ctx.tool.transform((editor: any) => {
|
|
3914
|
+
for (const [name, definition] of Object.entries<any>(hooks.tool ?? {})) {
|
|
3915
|
+
const args =
|
|
3916
|
+
definition.args && typeof definition.args === "object"
|
|
3917
|
+
? definition.args
|
|
3918
|
+
: {};
|
|
3919
|
+
let input: any = {
|
|
3920
|
+
type: "object",
|
|
3921
|
+
properties: {},
|
|
3922
|
+
additionalProperties: true,
|
|
3923
|
+
};
|
|
3924
|
+
try {
|
|
3925
|
+
input = (tool.schema as any).toJSONSchema(tool.schema.object(args));
|
|
3926
|
+
delete input.$schema;
|
|
3927
|
+
} catch (error) {
|
|
3928
|
+
console.error(
|
|
3929
|
+
`[free-pi] could not build the schema for ${name}; using a permissive schema`,
|
|
3930
|
+
error,
|
|
3931
|
+
);
|
|
3932
|
+
}
|
|
3933
|
+
editor.add({
|
|
3934
|
+
name,
|
|
3935
|
+
description: definition.description ?? name,
|
|
3936
|
+
input,
|
|
3937
|
+
execute: async (value: any, context: any) => {
|
|
3938
|
+
const result = await definition.execute(value, {
|
|
3939
|
+
sessionID: context.sessionID,
|
|
3940
|
+
messageID: context.messageID,
|
|
3941
|
+
agent: context.agent,
|
|
3942
|
+
id: context.id,
|
|
3943
|
+
directory: ctx.location?.directory ?? process.cwd(),
|
|
3944
|
+
worktree: ctx.location?.directory ?? process.cwd(),
|
|
3945
|
+
abort: context.signal,
|
|
3946
|
+
});
|
|
3947
|
+
return {
|
|
3948
|
+
content: result?.output ?? result?.title ?? "",
|
|
3949
|
+
metadata: result?.metadata,
|
|
3950
|
+
};
|
|
3951
|
+
},
|
|
3952
|
+
});
|
|
3953
|
+
}
|
|
3954
|
+
});
|
|
3955
|
+
} catch (error) {
|
|
3956
|
+
console.error("[free-pi] could not register tools in OpenCode 2", error);
|
|
3957
|
+
}
|
|
3834
3958
|
|
|
3835
3959
|
const applyRequest = async (event: any) => {
|
|
3836
3960
|
const providerID = event.model?.providerID;
|
|
@@ -3861,40 +3985,49 @@ async function FreePiV2Setup(ctx: any): Promise<() => Promise<void>> {
|
|
|
3861
3985
|
};
|
|
3862
3986
|
|
|
3863
3987
|
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
3864
|
-
|
|
3988
|
+
try {
|
|
3989
|
+
registrations.push(await ctx.session.hook(kind, applyRequest));
|
|
3990
|
+
} catch (error) {
|
|
3991
|
+
console.error(`[free-pi] could not register the ${kind} hook`, error);
|
|
3992
|
+
}
|
|
3865
3993
|
}
|
|
3866
3994
|
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
|
|
3871
|
-
|
|
3872
|
-
|
|
3873
|
-
|
|
3874
|
-
|
|
3875
|
-
|
|
3876
|
-
|
|
3877
|
-
|
|
3878
|
-
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
(
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3995
|
+
try {
|
|
3996
|
+
registrations.push(
|
|
3997
|
+
await ctx.session.hook("model.request", async (event: any) => {
|
|
3998
|
+
const providerID = event.model?.providerID;
|
|
3999
|
+
if (providerID !== PROVIDER_ID && providerID !== DEFENSE_PROVIDER_ID)
|
|
4000
|
+
return;
|
|
4001
|
+
event.headers ??= {};
|
|
4002
|
+
const current = await resolveToken(client);
|
|
4003
|
+
if (current) event.headers.authorization = `Bearer ${current}`;
|
|
4004
|
+
event.headers["x-session-id"] = event.sessionID;
|
|
4005
|
+
event.headers["x-client-version"] = latestClientVersion;
|
|
4006
|
+
if (costExperimentArm)
|
|
4007
|
+
event.headers[COST_EXPERIMENT_HEADER] = costExperimentArm;
|
|
4008
|
+
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
4009
|
+
const lastUser = [...messages]
|
|
4010
|
+
.reverse()
|
|
4011
|
+
.find(
|
|
4012
|
+
(message: any) => (message?.info?.role ?? message?.role) === "user",
|
|
4013
|
+
);
|
|
4014
|
+
const messageID = lastUser?.info?.id ?? lastUser?.id;
|
|
4015
|
+
const input = {
|
|
4016
|
+
sessionID: event.sessionID,
|
|
4017
|
+
model: event.model,
|
|
4018
|
+
agent: event.agent,
|
|
4019
|
+
message: messageID ? { id: messageID } : undefined,
|
|
4020
|
+
};
|
|
4021
|
+
const output = { headers: event.headers };
|
|
4022
|
+
await hooks["chat.headers"]?.(input, output);
|
|
4023
|
+
}),
|
|
4024
|
+
);
|
|
4025
|
+
} catch (error) {
|
|
4026
|
+
console.error("[free-pi] could not register the request hook", error);
|
|
4027
|
+
}
|
|
3896
4028
|
|
|
3897
4029
|
return async () => {
|
|
4030
|
+
credentialsAbort.abort();
|
|
3898
4031
|
for (const registration of registrations.reverse()) {
|
|
3899
4032
|
await registration.dispose?.().catch(() => undefined);
|
|
3900
4033
|
}
|