@eduardo191labs/opencode-free-pi 0.3.4 → 0.3.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 +11 -1
- package/dist/api/quota.js +6 -0
- package/dist/catalog/catalog.js +6 -0
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +1 -0
- package/dist/errors/messages.js +1 -0
- package/dist/errors/parse.js +20 -1
- package/dist/session/events.js +13 -0
- package/dist/session/hooks.js +9 -4
- package/dist/session/title.d.ts +18 -0
- package/dist/session/title.js +81 -0
- package/dist/state.d.ts +3 -0
- package/dist/state.js +1 -0
- package/dist/types.d.ts +2 -0
- package/package.json +2 -2
- package/src/api/quota.ts +8 -0
- package/src/catalog/catalog.ts +8 -0
- package/src/constants.ts +1 -0
- package/src/errors/messages.ts +1 -0
- package/src/errors/parse.ts +19 -1
- package/src/session/events.ts +12 -0
- package/src/session/hooks.ts +9 -3
- package/src/session/title.ts +90 -0
- package/src/state.ts +4 -0
- package/src/types.ts +2 -0
package/README.md
CHANGED
|
@@ -74,6 +74,13 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
74
74
|
- **Compactación integrada**: los errores `context_too_long` de free-pi se
|
|
75
75
|
reescriben para que OpenCode los reconozca como desbordamiento de contexto y
|
|
76
76
|
ejecute `/compact` automáticamente en vez de terminar el turno.
|
|
77
|
+
- **Títulos locales**: OpenCode pide un título al modelo al crear una sesión.
|
|
78
|
+
El plugin lo responde con la primera línea del primer mensaje, sin gastar
|
|
79
|
+
créditos, sin pedir un anuncio y sin dejar la sesión atascada en
|
|
80
|
+
«New session».
|
|
81
|
+
- **Subagentes identificados**: las sesiones hijas envían
|
|
82
|
+
`x-freepi-subagent: 1`, igual que los proveedores que el CLI crea para sus
|
|
83
|
+
subagentes.
|
|
77
84
|
- **Pensamiento como el CLI**: todos los modelos razonan y empiezan en `off`;
|
|
78
85
|
el selector ofrece `minimal`, `low`, `medium` y `high` mediante
|
|
79
86
|
`reasoning_effort`, igual que `pi-ai`. No se anuncian `thinking_budget` ni
|
|
@@ -94,7 +101,9 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
94
101
|
- Recuperación automática del límite de sesiones concurrentes.
|
|
95
102
|
- **Catálogo y metadatos resistentes**: el catálogo de free-pi y el registro de
|
|
96
103
|
models.dev se guardan en disco; si la red falla al arrancar se usan las copias
|
|
97
|
-
locales en vez de quedarse sin modelos o sin límites de contexto.
|
|
104
|
+
locales en vez de quedarse sin modelos o sin límites de contexto. Los avisos
|
|
105
|
+
que el servidor manda en el catálogo y en `/me` (`notice`) se registran una
|
|
106
|
+
vez en el log del plugin.
|
|
98
107
|
- Compatible con rutas, credenciales y navegador de cada sistema operativo.
|
|
99
108
|
|
|
100
109
|
No incluye herramientas personalizadas. Usa las herramientas integradas de
|
|
@@ -106,6 +115,7 @@ El plugin replica las cabeceras del plugin V1 de free-pi:
|
|
|
106
115
|
|
|
107
116
|
- **Modelo**: `authorization`, `x-session-id`, `x-client-version`,
|
|
108
117
|
`x-turn-id` y `x-freepi-cost-exp` (cuando el catálogo asigna un experimento).
|
|
118
|
+
Las sesiones hijas añaden `x-freepi-subagent: 1`.
|
|
109
119
|
- **Resultados de herramientas**: `x-freepi-tool-meta` (duración, código de
|
|
110
120
|
salida y truncado de las últimas llamadas), `x-freepi-tool-errors` (IDs de
|
|
111
121
|
herramientas fallidas) y `x-freepi-compacted` (mensajes plegados por la
|
package/dist/api/quota.js
CHANGED
|
@@ -65,6 +65,12 @@ export async function fetchQuota(deps, opts = {}) {
|
|
|
65
65
|
: undefined;
|
|
66
66
|
if (meResponse?.ok || statsResponse?.ok)
|
|
67
67
|
rememberTokenCheck(deps, token, "ok");
|
|
68
|
+
if (typeof me?.notice === "string" &&
|
|
69
|
+
me.notice &&
|
|
70
|
+
me.notice !== deps.state.lastQuotaNotice) {
|
|
71
|
+
deps.state.lastQuotaNotice = me.notice;
|
|
72
|
+
deps.log.info("free-pi account notice", { notice: me.notice });
|
|
73
|
+
}
|
|
68
74
|
const snapshot = {
|
|
69
75
|
fetchedAt: Date.now(),
|
|
70
76
|
token,
|
package/dist/catalog/catalog.js
CHANGED
|
@@ -23,6 +23,12 @@ function applyCatalog(deps, catalog) {
|
|
|
23
23
|
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
24
24
|
? arm
|
|
25
25
|
: undefined;
|
|
26
|
+
if (typeof catalog.notice === "string" &&
|
|
27
|
+
catalog.notice &&
|
|
28
|
+
catalog.notice !== state.lastCatalogNotice) {
|
|
29
|
+
state.lastCatalogNotice = catalog.notice;
|
|
30
|
+
deps.log.info("free-pi catalog notice", { notice: catalog.notice });
|
|
31
|
+
}
|
|
26
32
|
state.cachedCatalog = catalog;
|
|
27
33
|
state.cachedCatalogAt = Date.now();
|
|
28
34
|
return catalog;
|
package/dist/constants.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export declare const CONSENT_VERSION = "4";
|
|
|
10
10
|
export declare const CONTEXT_WINDOW = 200000;
|
|
11
11
|
export declare const MAX_OUTPUT_TOKENS = 32768;
|
|
12
12
|
export declare const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export declare const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
13
14
|
export declare const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
15
|
export declare const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
16
|
/**
|
package/dist/constants.js
CHANGED
|
@@ -10,6 +10,7 @@ export const CONSENT_VERSION = "4";
|
|
|
10
10
|
export const CONTEXT_WINDOW = 200_000;
|
|
11
11
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
12
12
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
13
|
+
export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
13
14
|
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
14
15
|
export const EFFICIENCY_RULE = "- When several independent reads or searches are needed, issue them in the same turn.";
|
|
15
16
|
/**
|
package/dist/errors/messages.js
CHANGED
|
@@ -45,6 +45,7 @@ const FREE_PI_ERROR_TITLE = {
|
|
|
45
45
|
unauthorized: "free-pi sign-in",
|
|
46
46
|
expired_token: "free-pi sign-in",
|
|
47
47
|
guest_allowance: "free-pi sign-in",
|
|
48
|
+
free_usage_limit: "free-pi free limit",
|
|
48
49
|
guest_login_required: "free-pi sign-in",
|
|
49
50
|
guest_unavailable: "free-pi sign-in",
|
|
50
51
|
consent_required: "free-pi consent",
|
package/dist/errors/parse.js
CHANGED
|
@@ -26,6 +26,10 @@ const RAW_FREE_PI_ERROR_PATTERNS = [
|
|
|
26
26
|
"insufficient_credits",
|
|
27
27
|
],
|
|
28
28
|
[/guest trial used up|guest_allowance/i, "guest_allowance"],
|
|
29
|
+
[
|
|
30
|
+
/free usage limit|monthly usage limit/i,
|
|
31
|
+
"free_usage_limit",
|
|
32
|
+
],
|
|
29
33
|
[
|
|
30
34
|
/needs a github sign-in|sign in with github|guest_login_required/i,
|
|
31
35
|
"guest_login_required",
|
|
@@ -91,11 +95,26 @@ export function parseRawFreePiError(error) {
|
|
|
91
95
|
}
|
|
92
96
|
return undefined;
|
|
93
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Recovers a code from the server's message text when the envelope carries no
|
|
100
|
+
* `code` field, for example the free-usage-limit 429 that only sends a message.
|
|
101
|
+
*/
|
|
102
|
+
function codeFromText(message) {
|
|
103
|
+
if (typeof message !== "string" || !message.trim())
|
|
104
|
+
return undefined;
|
|
105
|
+
const text = message.trim();
|
|
106
|
+
for (const [pattern, code] of RAW_FREE_PI_ERROR_PATTERNS) {
|
|
107
|
+
if (pattern.test(text))
|
|
108
|
+
return code;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
94
112
|
export function parseFreePiError(error, allowRaw = false) {
|
|
95
113
|
const candidates = [
|
|
96
114
|
error?.response?.body,
|
|
97
115
|
error?.data?.responseBody,
|
|
98
116
|
error?.responseBody,
|
|
117
|
+
error?.data,
|
|
99
118
|
error?.data?.message,
|
|
100
119
|
error?.message,
|
|
101
120
|
];
|
|
@@ -129,7 +148,7 @@ export function parseFreePiError(error, allowRaw = false) {
|
|
|
129
148
|
? codeValue
|
|
130
149
|
: status === 401
|
|
131
150
|
? "unauthorized"
|
|
132
|
-
:
|
|
151
|
+
: codeFromText(message);
|
|
133
152
|
if (!code && typeof message !== "string")
|
|
134
153
|
continue;
|
|
135
154
|
return {
|
package/dist/session/events.js
CHANGED
|
@@ -10,6 +10,7 @@ import { recordUsage } from "./usage.js";
|
|
|
10
10
|
const EVENT_TYPES = [
|
|
11
11
|
"credential.updated",
|
|
12
12
|
"credential.switched",
|
|
13
|
+
"session.created",
|
|
13
14
|
"session.execution.started",
|
|
14
15
|
"session.execution.succeeded",
|
|
15
16
|
"session.execution.failed",
|
|
@@ -31,6 +32,17 @@ async function handleEvent(ctx, deps, event) {
|
|
|
31
32
|
await ctx.provider.reload().catch(() => undefined);
|
|
32
33
|
return;
|
|
33
34
|
}
|
|
35
|
+
case "session.created": {
|
|
36
|
+
// The CLI marks requests from its own subagents so the server can bill
|
|
37
|
+
// and rate-limit them separately; OpenCode's children map the same way.
|
|
38
|
+
const sessionID = event.data?.sessionID;
|
|
39
|
+
if (typeof sessionID !== "string")
|
|
40
|
+
return;
|
|
41
|
+
if (typeof event.data?.parentID === "string") {
|
|
42
|
+
deps.state.subagentSessions.add(sessionID);
|
|
43
|
+
}
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
34
46
|
case "session.execution.started": {
|
|
35
47
|
beginExecution(deps, event.data?.sessionID);
|
|
36
48
|
return;
|
|
@@ -67,6 +79,7 @@ async function handleEvent(ctx, deps, event) {
|
|
|
67
79
|
forgetFreePiSession(deps, sessionID);
|
|
68
80
|
forgetCacheMiss(deps, sessionID);
|
|
69
81
|
forgetToolStats(deps, sessionID);
|
|
82
|
+
deps.state.subagentSessions.delete(sessionID);
|
|
70
83
|
return;
|
|
71
84
|
}
|
|
72
85
|
case "location.shutdown": {
|
package/dist/session/hooks.js
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
import { ensureAdImpression } from "../ads/impression.js";
|
|
3
3
|
import { resolveAdTurn } from "../ads/resolve.js";
|
|
4
4
|
import { resolveToken } from "../auth/token.js";
|
|
5
|
-
import { COST_EXPERIMENT_HEADER, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, } from "../constants.js";
|
|
5
|
+
import { COST_EXPERIMENT_HEADER, DEFENSE_PROVIDER_ID, EFFICIENCY_RULE, MAX_OUTPUT_TOKENS, PROVIDER_ID, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRY_MAX_RETRIES, SUBAGENT_HEADER, } from "../constants.js";
|
|
6
6
|
import { rewriteContextOverflowResponse, rewriteLimitResponse, } from "../errors/limit.js";
|
|
7
7
|
import { trimMap } from "../utils/async.js";
|
|
8
8
|
import { watchFreePiNotice } from "./notices.js";
|
|
9
|
+
import { localTitle } from "./title.js";
|
|
9
10
|
import { rememberFreePiSession } from "./track.js";
|
|
10
11
|
import { recordCompaction, recordToolEnd, recordToolStart, toolHeaders, } from "./tools.js";
|
|
11
12
|
import { rememberTrackedModel } from "./usage.js";
|
|
@@ -26,10 +27,11 @@ async function applyGeneration(deps, event, kind) {
|
|
|
26
27
|
if (!isFreePiProvider(event.model?.providerID))
|
|
27
28
|
return;
|
|
28
29
|
rememberFreePiSession(deps, event.sessionID);
|
|
29
|
-
// V1 disabled the title agent.
|
|
30
|
-
//
|
|
30
|
+
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
31
|
+
// from the first user message: no free-pi request, no ad impression, and the
|
|
32
|
+
// session leaves the "New session" state immediately.
|
|
31
33
|
if (kind === "title") {
|
|
32
|
-
event.result =
|
|
34
|
+
event.result = localTitle(event.messages);
|
|
33
35
|
return;
|
|
34
36
|
}
|
|
35
37
|
const modelID = event.model?.id;
|
|
@@ -77,6 +79,9 @@ async function applyModelRequest(deps, event) {
|
|
|
77
79
|
event.headers.authorization = `Bearer ${token}`;
|
|
78
80
|
event.headers["x-session-id"] = event.sessionID;
|
|
79
81
|
event.headers["x-client-version"] = deps.state.latestClientVersion;
|
|
82
|
+
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
83
|
+
event.headers[SUBAGENT_HEADER] = "1";
|
|
84
|
+
}
|
|
80
85
|
if (deps.state.costExperimentArm) {
|
|
81
86
|
event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
|
|
82
87
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds session titles locally.
|
|
3
|
+
*
|
|
4
|
+
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
+
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
+
* the title hook answers from the first user message instead: the session gets
|
|
7
|
+
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
+
* never leave the session stuck on "New session".
|
|
9
|
+
*/
|
|
10
|
+
type TitleMessage = {
|
|
11
|
+
role?: unknown;
|
|
12
|
+
type?: unknown;
|
|
13
|
+
text?: unknown;
|
|
14
|
+
content?: unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Derives a title from the first meaningful line of the title request. */
|
|
17
|
+
export declare function localTitle(messages: readonly TitleMessage[] | undefined): string;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds session titles locally.
|
|
3
|
+
*
|
|
4
|
+
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
+
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
+
* the title hook answers from the first user message instead: the session gets
|
|
7
|
+
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
+
* never leave the session stuck on "New session".
|
|
9
|
+
*/
|
|
10
|
+
const MAX_TITLE_LENGTH = 60;
|
|
11
|
+
const MAX_SOURCE_LENGTH = 4_000;
|
|
12
|
+
const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
|
|
13
|
+
const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
|
|
14
|
+
const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
|
|
15
|
+
const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
|
|
16
|
+
const XML_LINE = /^<\/?[a-z][^>]*>$/i;
|
|
17
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
|
|
18
|
+
function textOf(content) {
|
|
19
|
+
if (typeof content === "string")
|
|
20
|
+
return content;
|
|
21
|
+
if (!Array.isArray(content))
|
|
22
|
+
return "";
|
|
23
|
+
return content
|
|
24
|
+
.filter((part) => part?.type === "text" && typeof part.text === "string")
|
|
25
|
+
.map((part) => part.text)
|
|
26
|
+
.join("\n");
|
|
27
|
+
}
|
|
28
|
+
function latestUserText(messages) {
|
|
29
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
30
|
+
const message = messages[index];
|
|
31
|
+
const role = message?.role ?? message?.type;
|
|
32
|
+
if (role !== "user")
|
|
33
|
+
continue;
|
|
34
|
+
const text = typeof message?.text === "string"
|
|
35
|
+
? message.text
|
|
36
|
+
: textOf(message?.content);
|
|
37
|
+
if (text.trim())
|
|
38
|
+
return text;
|
|
39
|
+
}
|
|
40
|
+
return "";
|
|
41
|
+
}
|
|
42
|
+
/** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
|
|
43
|
+
function sourceText(messages) {
|
|
44
|
+
const raw = latestUserText(messages);
|
|
45
|
+
const block = MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
|
|
46
|
+
return block.slice(0, MAX_SOURCE_LENGTH);
|
|
47
|
+
}
|
|
48
|
+
function cleanLine(line) {
|
|
49
|
+
let value = line.replace(CONTROL, " ").trim();
|
|
50
|
+
if (!value)
|
|
51
|
+
return undefined;
|
|
52
|
+
value = value
|
|
53
|
+
.replace(/^#{1,6}\s+/, "")
|
|
54
|
+
.replace(/^[-*+>]\s+/, "")
|
|
55
|
+
.trim();
|
|
56
|
+
value = value.replace(PREFIX, "").trim();
|
|
57
|
+
if (!value || NOISE.test(value) || XML_LINE.test(value))
|
|
58
|
+
return undefined;
|
|
59
|
+
value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
|
|
60
|
+
return value || undefined;
|
|
61
|
+
}
|
|
62
|
+
function truncate(value) {
|
|
63
|
+
if (value.length <= MAX_TITLE_LENGTH)
|
|
64
|
+
return value;
|
|
65
|
+
const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
|
|
66
|
+
const space = cut.lastIndexOf(" ");
|
|
67
|
+
return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
|
|
68
|
+
}
|
|
69
|
+
/** Derives a title from the first meaningful line of the title request. */
|
|
70
|
+
export function localTitle(messages) {
|
|
71
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
72
|
+
return "Session";
|
|
73
|
+
const lines = sourceText(messages)
|
|
74
|
+
.split(/\r?\n/)
|
|
75
|
+
.map(cleanLine)
|
|
76
|
+
.filter((line) => Boolean(line));
|
|
77
|
+
const first = lines[0];
|
|
78
|
+
if (!first)
|
|
79
|
+
return "Session";
|
|
80
|
+
return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
|
|
81
|
+
}
|
package/dist/state.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export type RuntimeState = {
|
|
|
11
11
|
registryAttemptAt: number;
|
|
12
12
|
registryPromise?: Promise<ModelRegistry | undefined>;
|
|
13
13
|
costExperimentArm?: string;
|
|
14
|
+
lastCatalogNotice?: string;
|
|
15
|
+
lastQuotaNotice?: string;
|
|
14
16
|
catalogModels: Catalog;
|
|
15
17
|
outputLimits: Map<string, number>;
|
|
16
18
|
quotaCache?: QuotaSnapshot;
|
|
@@ -41,5 +43,6 @@ export type RuntimeState = {
|
|
|
41
43
|
trackedModels: Map<string, TrackedModel>;
|
|
42
44
|
cacheMisses: Map<string, CacheMissState>;
|
|
43
45
|
toolStats: Map<string, ToolStats>;
|
|
46
|
+
subagentSessions: Set<string>;
|
|
44
47
|
};
|
|
45
48
|
export declare function createRuntimeState(): RuntimeState;
|
package/dist/state.js
CHANGED
package/dist/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eduardo191labs/opencode-free-pi",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
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",
|
|
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",
|
|
28
28
|
"prepublishOnly": "npm run build",
|
|
29
29
|
"postinstall": "node scripts/postinstall.mjs"
|
|
30
30
|
},
|
package/src/api/quota.ts
CHANGED
|
@@ -86,6 +86,14 @@ export async function fetchQuota(
|
|
|
86
86
|
: undefined;
|
|
87
87
|
if (meResponse?.ok || statsResponse?.ok)
|
|
88
88
|
rememberTokenCheck(deps, token, "ok");
|
|
89
|
+
if (
|
|
90
|
+
typeof me?.notice === "string" &&
|
|
91
|
+
me.notice &&
|
|
92
|
+
me.notice !== deps.state.lastQuotaNotice
|
|
93
|
+
) {
|
|
94
|
+
deps.state.lastQuotaNotice = me.notice;
|
|
95
|
+
deps.log.info("free-pi account notice", { notice: me.notice });
|
|
96
|
+
}
|
|
89
97
|
const snapshot: QuotaSnapshot = {
|
|
90
98
|
fetchedAt: Date.now(),
|
|
91
99
|
token,
|
package/src/catalog/catalog.ts
CHANGED
|
@@ -35,6 +35,14 @@ function applyCatalog(deps: Deps, catalog: Catalog): Catalog {
|
|
|
35
35
|
typeof arm === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(arm)
|
|
36
36
|
? arm
|
|
37
37
|
: undefined;
|
|
38
|
+
if (
|
|
39
|
+
typeof catalog.notice === "string" &&
|
|
40
|
+
catalog.notice &&
|
|
41
|
+
catalog.notice !== state.lastCatalogNotice
|
|
42
|
+
) {
|
|
43
|
+
state.lastCatalogNotice = catalog.notice;
|
|
44
|
+
deps.log.info("free-pi catalog notice", { notice: catalog.notice });
|
|
45
|
+
}
|
|
38
46
|
state.cachedCatalog = catalog;
|
|
39
47
|
state.cachedCatalogAt = Date.now();
|
|
40
48
|
return catalog;
|
package/src/constants.ts
CHANGED
|
@@ -15,6 +15,7 @@ export const CONTEXT_WINDOW = 200_000;
|
|
|
15
15
|
export const MAX_OUTPUT_TOKENS = 32_768;
|
|
16
16
|
|
|
17
17
|
export const AD_CONTEXT_HEADER = "x-ad-context";
|
|
18
|
+
export const SUBAGENT_HEADER = "x-freepi-subagent";
|
|
18
19
|
export const COST_EXPERIMENT_HEADER = "x-freepi-cost-exp";
|
|
19
20
|
export const EFFICIENCY_RULE =
|
|
20
21
|
"- When several independent reads or searches are needed, issue them in the same turn.";
|
package/src/errors/messages.ts
CHANGED
|
@@ -67,6 +67,7 @@ const FREE_PI_ERROR_TITLE: Record<string, string> = {
|
|
|
67
67
|
unauthorized: "free-pi sign-in",
|
|
68
68
|
expired_token: "free-pi sign-in",
|
|
69
69
|
guest_allowance: "free-pi sign-in",
|
|
70
|
+
free_usage_limit: "free-pi free limit",
|
|
70
71
|
guest_login_required: "free-pi sign-in",
|
|
71
72
|
guest_unavailable: "free-pi sign-in",
|
|
72
73
|
consent_required: "free-pi consent",
|
package/src/errors/parse.ts
CHANGED
|
@@ -29,6 +29,10 @@ const RAW_FREE_PI_ERROR_PATTERNS: Array<[RegExp, string]> = [
|
|
|
29
29
|
"insufficient_credits",
|
|
30
30
|
],
|
|
31
31
|
[/guest trial used up|guest_allowance/i, "guest_allowance"],
|
|
32
|
+
[
|
|
33
|
+
/free usage limit|monthly usage limit/i,
|
|
34
|
+
"free_usage_limit",
|
|
35
|
+
],
|
|
32
36
|
[
|
|
33
37
|
/needs a github sign-in|sign in with github|guest_login_required/i,
|
|
34
38
|
"guest_login_required",
|
|
@@ -91,6 +95,19 @@ export function parseRawFreePiError(error: any): FreePiError | undefined {
|
|
|
91
95
|
return undefined;
|
|
92
96
|
}
|
|
93
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Recovers a code from the server's message text when the envelope carries no
|
|
100
|
+
* `code` field, for example the free-usage-limit 429 that only sends a message.
|
|
101
|
+
*/
|
|
102
|
+
function codeFromText(message: unknown): string | undefined {
|
|
103
|
+
if (typeof message !== "string" || !message.trim()) return undefined;
|
|
104
|
+
const text = message.trim();
|
|
105
|
+
for (const [pattern, code] of RAW_FREE_PI_ERROR_PATTERNS) {
|
|
106
|
+
if (pattern.test(text)) return code;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
94
111
|
export function parseFreePiError(
|
|
95
112
|
error: any,
|
|
96
113
|
allowRaw = false,
|
|
@@ -99,6 +116,7 @@ export function parseFreePiError(
|
|
|
99
116
|
error?.response?.body,
|
|
100
117
|
error?.data?.responseBody,
|
|
101
118
|
error?.responseBody,
|
|
119
|
+
error?.data,
|
|
102
120
|
error?.data?.message,
|
|
103
121
|
error?.message,
|
|
104
122
|
];
|
|
@@ -129,7 +147,7 @@ export function parseFreePiError(
|
|
|
129
147
|
? codeValue
|
|
130
148
|
: status === 401
|
|
131
149
|
? "unauthorized"
|
|
132
|
-
:
|
|
150
|
+
: codeFromText(message);
|
|
133
151
|
if (!code && typeof message !== "string") continue;
|
|
134
152
|
return {
|
|
135
153
|
status: typeof body.status === "number" ? body.status : status,
|
package/src/session/events.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { recordUsage } from "./usage.js";
|
|
|
20
20
|
const EVENT_TYPES = [
|
|
21
21
|
"credential.updated",
|
|
22
22
|
"credential.switched",
|
|
23
|
+
"session.created",
|
|
23
24
|
"session.execution.started",
|
|
24
25
|
"session.execution.succeeded",
|
|
25
26
|
"session.execution.failed",
|
|
@@ -46,6 +47,16 @@ async function handleEvent(
|
|
|
46
47
|
await ctx.provider.reload().catch(() => undefined);
|
|
47
48
|
return;
|
|
48
49
|
}
|
|
50
|
+
case "session.created": {
|
|
51
|
+
// The CLI marks requests from its own subagents so the server can bill
|
|
52
|
+
// and rate-limit them separately; OpenCode's children map the same way.
|
|
53
|
+
const sessionID = event.data?.sessionID;
|
|
54
|
+
if (typeof sessionID !== "string") return;
|
|
55
|
+
if (typeof event.data?.parentID === "string") {
|
|
56
|
+
deps.state.subagentSessions.add(sessionID);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
49
60
|
case "session.execution.started": {
|
|
50
61
|
beginExecution(deps, event.data?.sessionID);
|
|
51
62
|
return;
|
|
@@ -92,6 +103,7 @@ async function handleEvent(
|
|
|
92
103
|
forgetFreePiSession(deps, sessionID);
|
|
93
104
|
forgetCacheMiss(deps, sessionID);
|
|
94
105
|
forgetToolStats(deps, sessionID);
|
|
106
|
+
deps.state.subagentSessions.delete(sessionID);
|
|
95
107
|
return;
|
|
96
108
|
}
|
|
97
109
|
case "location.shutdown": {
|
package/src/session/hooks.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
RETRY_BASE_DELAY_MS,
|
|
15
15
|
RETRY_MAX_DELAY_MS,
|
|
16
16
|
RETRY_MAX_RETRIES,
|
|
17
|
+
SUBAGENT_HEADER,
|
|
17
18
|
} from "../constants.js";
|
|
18
19
|
import type { Deps } from "../deps.js";
|
|
19
20
|
import {
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
} from "../errors/limit.js";
|
|
23
24
|
import { trimMap } from "../utils/async.js";
|
|
24
25
|
import { watchFreePiNotice } from "./notices.js";
|
|
26
|
+
import { localTitle } from "./title.js";
|
|
25
27
|
import { rememberFreePiSession } from "./track.js";
|
|
26
28
|
import {
|
|
27
29
|
recordCompaction,
|
|
@@ -71,10 +73,11 @@ async function applyGeneration(
|
|
|
71
73
|
if (!isFreePiProvider(event.model?.providerID)) return;
|
|
72
74
|
rememberFreePiSession(deps, event.sessionID);
|
|
73
75
|
|
|
74
|
-
// V1 disabled the title agent.
|
|
75
|
-
//
|
|
76
|
+
// V1 disabled the title agent. OpenCode still asks for a title, so answer
|
|
77
|
+
// from the first user message: no free-pi request, no ad impression, and the
|
|
78
|
+
// session leaves the "New session" state immediately.
|
|
76
79
|
if (kind === "title") {
|
|
77
|
-
event.result =
|
|
80
|
+
event.result = localTitle(event.messages);
|
|
78
81
|
return;
|
|
79
82
|
}
|
|
80
83
|
|
|
@@ -135,6 +138,9 @@ async function applyModelRequest(deps: Deps, event: any): Promise<void> {
|
|
|
135
138
|
if (token) event.headers.authorization = `Bearer ${token}`;
|
|
136
139
|
event.headers["x-session-id"] = event.sessionID;
|
|
137
140
|
event.headers["x-client-version"] = deps.state.latestClientVersion;
|
|
141
|
+
if (deps.state.subagentSessions.has(event.sessionID)) {
|
|
142
|
+
event.headers[SUBAGENT_HEADER] = "1";
|
|
143
|
+
}
|
|
138
144
|
if (deps.state.costExperimentArm) {
|
|
139
145
|
event.headers[COST_EXPERIMENT_HEADER] = deps.state.costExperimentArm;
|
|
140
146
|
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds session titles locally.
|
|
3
|
+
*
|
|
4
|
+
* free-pi charges credits and shows ads per model request, and the CLI never
|
|
5
|
+
* spends a turn on a title. OpenCode asks the selected model for a title, so
|
|
6
|
+
* the title hook answers from the first user message instead: the session gets
|
|
7
|
+
* a real name immediately, no ad is fetched, and a failed title request can
|
|
8
|
+
* never leave the session stuck on "New session".
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const MAX_TITLE_LENGTH = 60;
|
|
12
|
+
const MAX_SOURCE_LENGTH = 4_000;
|
|
13
|
+
const MESSAGE_BLOCK = /<message>([\s\S]*?)<\/message>/i;
|
|
14
|
+
const CONVERSATION_BLOCK = /<conversation>([\s\S]*?)<\/conversation>/i;
|
|
15
|
+
const PREFIX = /^(?:original request|recent conversation|user|assistant)\s*:\s*/i;
|
|
16
|
+
const NOISE = /^(?:```[\w-]*|---+|===+|\*\*\*+)$/;
|
|
17
|
+
const XML_LINE = /^<\/?[a-z][^>]*>$/i;
|
|
18
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
|
|
19
|
+
|
|
20
|
+
type TitleMessage = {
|
|
21
|
+
role?: unknown;
|
|
22
|
+
type?: unknown;
|
|
23
|
+
text?: unknown;
|
|
24
|
+
content?: unknown;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function textOf(content: unknown): string {
|
|
28
|
+
if (typeof content === "string") return content;
|
|
29
|
+
if (!Array.isArray(content)) return "";
|
|
30
|
+
return content
|
|
31
|
+
.filter(
|
|
32
|
+
(part: any) => part?.type === "text" && typeof part.text === "string",
|
|
33
|
+
)
|
|
34
|
+
.map((part: any) => part.text)
|
|
35
|
+
.join("\n");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function latestUserText(messages: readonly TitleMessage[]): string {
|
|
39
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
40
|
+
const message = messages[index];
|
|
41
|
+
const role = message?.role ?? message?.type;
|
|
42
|
+
if (role !== "user") continue;
|
|
43
|
+
const text =
|
|
44
|
+
typeof message?.text === "string"
|
|
45
|
+
? message.text
|
|
46
|
+
: textOf(message?.content);
|
|
47
|
+
if (text.trim()) return text;
|
|
48
|
+
}
|
|
49
|
+
return "";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** OpenCode wraps the source in `<message>` or `<conversation>` tags. */
|
|
53
|
+
function sourceText(messages: readonly TitleMessage[]): string {
|
|
54
|
+
const raw = latestUserText(messages);
|
|
55
|
+
const block =
|
|
56
|
+
MESSAGE_BLOCK.exec(raw)?.[1] ?? CONVERSATION_BLOCK.exec(raw)?.[1] ?? raw;
|
|
57
|
+
return block.slice(0, MAX_SOURCE_LENGTH);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function cleanLine(line: string): string | undefined {
|
|
61
|
+
let value = line.replace(CONTROL, " ").trim();
|
|
62
|
+
if (!value) return undefined;
|
|
63
|
+
value = value
|
|
64
|
+
.replace(/^#{1,6}\s+/, "")
|
|
65
|
+
.replace(/^[-*+>]\s+/, "")
|
|
66
|
+
.trim();
|
|
67
|
+
value = value.replace(PREFIX, "").trim();
|
|
68
|
+
if (!value || NOISE.test(value) || XML_LINE.test(value)) return undefined;
|
|
69
|
+
value = value.replace(/^["'`]+|["'`]+$/g, "").trim();
|
|
70
|
+
return value || undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function truncate(value: string): string {
|
|
74
|
+
if (value.length <= MAX_TITLE_LENGTH) return value;
|
|
75
|
+
const cut = value.slice(0, MAX_TITLE_LENGTH - 3);
|
|
76
|
+
const space = cut.lastIndexOf(" ");
|
|
77
|
+
return `${(space >= 20 ? cut.slice(0, space) : cut).trimEnd()}...`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Derives a title from the first meaningful line of the title request. */
|
|
81
|
+
export function localTitle(messages: readonly TitleMessage[] | undefined): string {
|
|
82
|
+
if (!Array.isArray(messages) || messages.length === 0) return "Session";
|
|
83
|
+
const lines = sourceText(messages)
|
|
84
|
+
.split(/\r?\n/)
|
|
85
|
+
.map(cleanLine)
|
|
86
|
+
.filter((line): line is string => Boolean(line));
|
|
87
|
+
const first = lines[0];
|
|
88
|
+
if (!first) return "Session";
|
|
89
|
+
return truncate(first.replace(/[\s:;,\-]+$/g, "").trim()) || "Session";
|
|
90
|
+
}
|
package/src/state.ts
CHANGED
|
@@ -27,6 +27,8 @@ export type RuntimeState = {
|
|
|
27
27
|
registryAttemptAt: number;
|
|
28
28
|
registryPromise?: Promise<ModelRegistry | undefined>;
|
|
29
29
|
costExperimentArm?: string;
|
|
30
|
+
lastCatalogNotice?: string;
|
|
31
|
+
lastQuotaNotice?: string;
|
|
30
32
|
catalogModels: Catalog;
|
|
31
33
|
outputLimits: Map<string, number>;
|
|
32
34
|
|
|
@@ -58,6 +60,7 @@ export type RuntimeState = {
|
|
|
58
60
|
trackedModels: Map<string, TrackedModel>;
|
|
59
61
|
cacheMisses: Map<string, CacheMissState>;
|
|
60
62
|
toolStats: Map<string, ToolStats>;
|
|
63
|
+
subagentSessions: Set<string>;
|
|
61
64
|
};
|
|
62
65
|
|
|
63
66
|
export function createRuntimeState(): RuntimeState {
|
|
@@ -84,5 +87,6 @@ export function createRuntimeState(): RuntimeState {
|
|
|
84
87
|
trackedModels: new Map(),
|
|
85
88
|
cacheMisses: new Map(),
|
|
86
89
|
toolStats: new Map(),
|
|
90
|
+
subagentSessions: new Set(),
|
|
87
91
|
};
|
|
88
92
|
}
|
package/src/types.ts
CHANGED