@eduardo191labs/opencode-free-pi 0.7.6 → 0.7.8
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 +10 -1
- package/dist/ads/context.d.ts +2 -0
- package/dist/ads/context.js +46 -2
- package/dist/ads/resolve.js +3 -12
- package/dist/session/hooks.js +46 -0
- package/dist/session/replay.js +1 -1
- package/dist/session/trace.d.ts +1 -1
- package/dist/session/trace.js +45 -1
- package/package.json +1 -1
- package/src/ads/context.ts +51 -4
- package/src/ads/resolve.ts +3 -11
- package/src/session/hooks.ts +38 -0
- package/src/session/replay.ts +1 -1
- package/src/session/trace.ts +50 -0
package/README.md
CHANGED
|
@@ -168,6 +168,10 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
168
168
|
omitir: leer antes de editar, ejecutar las comprobaciones de verdad, no
|
|
169
169
|
afirmar que algo pasó si no se ejecutó, reutilizar las decisiones y rutas ya
|
|
170
170
|
establecidas en la conversación y no fingir que se compactó el contexto.
|
|
171
|
+
Además, cuando una herramienta falla por un motivo que el modelo repite (un
|
|
172
|
+
heredoc rechazado por el scanner del shell, un `edit` con cadenas idénticas o
|
|
173
|
+
con un `oldString` ambiguo), el error que recibe añade el siguiente paso
|
|
174
|
+
concreto en lugar de dejar solo el mensaje técnico.
|
|
171
175
|
- **Compactación con instrucciones**: el resumen de compactación recibe además
|
|
172
176
|
un bloque que le pide conservar requisitos sin resolver, decisiones y sus
|
|
173
177
|
motivos, rutas y símbolos exactos, comandos con su resultado, errores y
|
|
@@ -182,7 +186,12 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
|
|
|
182
186
|
free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
|
|
183
187
|
- **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
|
|
184
188
|
respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
|
|
185
|
-
- Anuncios e impresiones asociados al turno correcto.
|
|
189
|
+
- Anuncios e impresiones asociados al turno correcto. El contexto del anuncio se
|
|
190
|
+
construye solo con el último mensaje real del usuario: se ignoran el
|
|
191
|
+
recordatorio del plugin y los mensajes sintéticos que OpenCode inserta en el
|
|
192
|
+
mismo turno (resultado de un subagente, salida de un shell en segundo plano,
|
|
193
|
+
AGENTS.md, reinicio del servidor o respuesta interrumpida), que antes
|
|
194
|
+
rotaban el anuncio a mitad de turno y enviaban ids internos como contexto.
|
|
186
195
|
- Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
|
|
187
196
|
de anuncios; nunca reutiliza los del agente principal.
|
|
188
197
|
- **Cierre de sesión**: free-pi limita la cuenta a 4 sesiones simultáneas. El
|
package/dist/ads/context.d.ts
CHANGED
|
@@ -14,5 +14,7 @@ export type AdMessage = {
|
|
|
14
14
|
export declare function latestAssistantText(messages: readonly AdMessage[]): string;
|
|
15
15
|
/** Latest user text from a message list. */
|
|
16
16
|
export declare function latestUserText(messages: readonly AdMessage[]): string;
|
|
17
|
+
/** Number of real user turns; synthetic messages do not start a new one. */
|
|
18
|
+
export declare function countUserTurns(messages: readonly AdMessage[]): number;
|
|
17
19
|
/** Latest user message id from a message list. */
|
|
18
20
|
export declare function latestUserMessageID(messages: readonly AdMessage[]): string | undefined;
|
package/dist/ads/context.js
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
/** Builds and redacts the ad context sent with a user turn. */
|
|
2
2
|
import { AD_CONTEXT_MAX_CHARS, TURN_REMINDER_MARKER } from "../constants.js";
|
|
3
3
|
import { cleanText } from "../utils/text.js";
|
|
4
|
+
/** Start of the synthetic user message OpenCode creates for a finished subagent. */
|
|
5
|
+
const SUBAGENT_RESULT_PREFIX = "<subagent ";
|
|
6
|
+
/**
|
|
7
|
+
* User-role messages OpenCode injects on its own. They are stored as
|
|
8
|
+
* `type: "synthetic"` but lowered to `user` on the wire, so the prefix is the
|
|
9
|
+
* only signal the ad context can use.
|
|
10
|
+
*/
|
|
11
|
+
const SYNTHETIC_USER_PREFIXES = [
|
|
12
|
+
SUBAGENT_RESULT_PREFIX,
|
|
13
|
+
"<shell ",
|
|
14
|
+
"Instructions from: ",
|
|
15
|
+
"The server restarted while you were working.",
|
|
16
|
+
"The previous response was interrupted.",
|
|
17
|
+
"User requested that active blocking work be moved to the background.",
|
|
18
|
+
];
|
|
4
19
|
const AD_SECRET_PATTERNS = [
|
|
5
20
|
[
|
|
6
21
|
"private_key",
|
|
@@ -106,20 +121,49 @@ export function latestUserText(messages) {
|
|
|
106
121
|
const message = messages[index];
|
|
107
122
|
if (roleOf(message) !== "user")
|
|
108
123
|
continue;
|
|
109
|
-
const text =
|
|
124
|
+
const text = messageText(message);
|
|
110
125
|
// The plugin appends this after the ad turn is resolved; ignore it if the
|
|
111
126
|
// event is reused so the next ad never describes the reminder itself.
|
|
112
|
-
if (text
|
|
127
|
+
if (isRealUserTurn(text))
|
|
113
128
|
return text;
|
|
114
129
|
}
|
|
115
130
|
return "";
|
|
116
131
|
}
|
|
132
|
+
function messageText(message) {
|
|
133
|
+
return cleanText(typeof message.text === "string" ? message.text : contentText(message.content));
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* A user-role message that is not the user's own turn.
|
|
137
|
+
*
|
|
138
|
+
* OpenCode lowers a finished subagent into a `user` message that starts with
|
|
139
|
+
* `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
|
|
140
|
+
* also a `user` message. Treating either as a new turn rotated the ad in the
|
|
141
|
+
* middle of one user request and sent its internal ids as the ad context.
|
|
142
|
+
*/
|
|
143
|
+
function isRealUserTurn(text) {
|
|
144
|
+
return (text.length > 0 &&
|
|
145
|
+
!text.startsWith(TURN_REMINDER_MARKER) &&
|
|
146
|
+
!SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix)));
|
|
147
|
+
}
|
|
148
|
+
/** Number of real user turns; synthetic messages do not start a new one. */
|
|
149
|
+
export function countUserTurns(messages) {
|
|
150
|
+
let count = 0;
|
|
151
|
+
for (const message of messages) {
|
|
152
|
+
if (roleOf(message) !== "user")
|
|
153
|
+
continue;
|
|
154
|
+
if (isRealUserTurn(messageText(message)))
|
|
155
|
+
count += 1;
|
|
156
|
+
}
|
|
157
|
+
return count;
|
|
158
|
+
}
|
|
117
159
|
/** Latest user message id from a message list. */
|
|
118
160
|
export function latestUserMessageID(messages) {
|
|
119
161
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
120
162
|
const message = messages[index];
|
|
121
163
|
if (roleOf(message) !== "user")
|
|
122
164
|
continue;
|
|
165
|
+
if (!isRealUserTurn(messageText(message)))
|
|
166
|
+
continue;
|
|
123
167
|
if (typeof message.id === "string" && message.id)
|
|
124
168
|
return message.id;
|
|
125
169
|
}
|
package/dist/ads/resolve.js
CHANGED
|
@@ -1,25 +1,16 @@
|
|
|
1
1
|
/** Resolves (or creates) the ad turn for a session request. */
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { adContextFor, latestAssistantText, latestUserMessageID, latestUserText, } from "./context.js";
|
|
3
|
+
import { adContextFor, countUserTurns, latestAssistantText, latestUserMessageID, latestUserText, } from "./context.js";
|
|
4
4
|
import { adTurnKey, getAdTurn, rememberAdTurn } from "./turns.js";
|
|
5
|
-
function userMessageCount(messages) {
|
|
6
|
-
let count = 0;
|
|
7
|
-
for (const message of messages) {
|
|
8
|
-
const role = message.role ?? message.type;
|
|
9
|
-
if (role === "user")
|
|
10
|
-
count += 1;
|
|
11
|
-
}
|
|
12
|
-
return count;
|
|
13
|
-
}
|
|
14
5
|
/**
|
|
15
6
|
* Stable, id-free turn fingerprint. Provider request messages usually carry the
|
|
16
7
|
* stored user message id, but not always; without one the ad turn would never
|
|
17
8
|
* rotate and the provider would keep answering with the same ad (or fail once
|
|
18
|
-
* it expires). The user-
|
|
9
|
+
* it expires). The real user-turn count plus the latest prompt changes exactly
|
|
19
10
|
* when the user sends a new turn.
|
|
20
11
|
*/
|
|
21
12
|
function turnFingerprint(messages) {
|
|
22
|
-
return `${
|
|
13
|
+
return `${countUserTurns(messages)}:${latestUserText(messages).slice(0, 160)}`;
|
|
23
14
|
}
|
|
24
15
|
/**
|
|
25
16
|
* Uses the request messages for primary requests and the stored session for
|
package/dist/session/hooks.js
CHANGED
|
@@ -505,9 +505,55 @@ async function registerToolHooks(ctx, deps, registrations) {
|
|
|
505
505
|
status: event.status,
|
|
506
506
|
...(event.status === "completed" ? { result: event.result } : {}),
|
|
507
507
|
});
|
|
508
|
+
nudgeFailedTool(deps, event);
|
|
508
509
|
replaceUnsupportedImages(deps, event);
|
|
509
510
|
}));
|
|
510
511
|
}
|
|
512
|
+
/**
|
|
513
|
+
* Adds the concrete next step to a tool failure the free models repeat.
|
|
514
|
+
*
|
|
515
|
+
* The scan of a week of sessions shows the same failures over and over: the
|
|
516
|
+
* portable shell scanner rejects a heredoc or a nested-quote one-liner (72
|
|
517
|
+
* times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
|
|
518
|
+
* The model reads the bare error and often repeats the call. The hint is short
|
|
519
|
+
* and only goes to free-pi sessions; other providers keep their own messages.
|
|
520
|
+
*/
|
|
521
|
+
function nudgeFailedTool(deps, event) {
|
|
522
|
+
if (event.status !== "error")
|
|
523
|
+
return;
|
|
524
|
+
if (!isFreePiSession(deps, event.sessionID))
|
|
525
|
+
return;
|
|
526
|
+
const error = event.error;
|
|
527
|
+
if (!error || typeof error !== "object")
|
|
528
|
+
return;
|
|
529
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
530
|
+
if (!message)
|
|
531
|
+
return;
|
|
532
|
+
let hint = "";
|
|
533
|
+
if (message.includes("Portable shell scanner cannot analyze command")) {
|
|
534
|
+
hint =
|
|
535
|
+
" Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
|
|
536
|
+
}
|
|
537
|
+
else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
|
|
538
|
+
hint =
|
|
539
|
+
" Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
|
|
540
|
+
}
|
|
541
|
+
else if (/Found \d+ matches? for oldString/i.test(message)) {
|
|
542
|
+
hint =
|
|
543
|
+
" Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
|
|
544
|
+
}
|
|
545
|
+
else if (/has not been read yet|read it before/i.test(message)) {
|
|
546
|
+
hint = " Read the file with the read tool in this turn before editing it.";
|
|
547
|
+
}
|
|
548
|
+
if (!hint)
|
|
549
|
+
return;
|
|
550
|
+
try {
|
|
551
|
+
error.message = `${message}${hint}`;
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
// A frozen error still reaches the model unchanged; the hint is best effort.
|
|
555
|
+
}
|
|
556
|
+
}
|
|
511
557
|
/**
|
|
512
558
|
* Models whose upstream accepts images get them natively, so a `read` that
|
|
513
559
|
* returns a picture must keep the file part. Text-only models would turn it
|
package/dist/session/replay.js
CHANGED
|
@@ -45,7 +45,7 @@ export async function rememberReplayBody(deps, event) {
|
|
|
45
45
|
deps.state.replayBodies.delete(key);
|
|
46
46
|
deps.state.replayBodies.set(key, body);
|
|
47
47
|
trimMap(deps.state.replayBodies, REPLAY_BODY_LIMIT);
|
|
48
|
-
traceRequestBody(deps, event.sessionID, body);
|
|
48
|
+
traceRequestBody(deps, event.sessionID, body, request.headers);
|
|
49
49
|
}
|
|
50
50
|
catch {
|
|
51
51
|
// A non-replayable body simply falls back to the normal retry hook.
|
package/dist/session/trace.d.ts
CHANGED
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
* the last message OpenCode sends. It never runs unless the env var is set.
|
|
8
8
|
*/
|
|
9
9
|
import type { Deps } from "../deps.js";
|
|
10
|
-
export declare function traceRequestBody(deps: Deps, sessionID: string, body: string): void;
|
|
10
|
+
export declare function traceRequestBody(deps: Deps, sessionID: string, body: string, headers?: Headers): void;
|
package/dist/session/trace.js
CHANGED
|
@@ -19,7 +19,7 @@ function textOf(content) {
|
|
|
19
19
|
: "")
|
|
20
20
|
.join("");
|
|
21
21
|
}
|
|
22
|
-
export function traceRequestBody(deps, sessionID, body) {
|
|
22
|
+
export function traceRequestBody(deps, sessionID, body, headers) {
|
|
23
23
|
if (process.env.FREE_PI_TRACE !== "1")
|
|
24
24
|
return;
|
|
25
25
|
try {
|
|
@@ -60,6 +60,10 @@ export function traceRequestBody(deps, sessionID, body) {
|
|
|
60
60
|
? parsed.tools.map((tool) => tool?.function?.name ?? "?")
|
|
61
61
|
: [];
|
|
62
62
|
const last = messages.at(-1);
|
|
63
|
+
const lastRealUser = [...messages]
|
|
64
|
+
.reverse()
|
|
65
|
+
.find((message) => message.role === "user" &&
|
|
66
|
+
!textOf(message.content).startsWith("# free-pi turn check"));
|
|
63
67
|
deps.log.info("free-pi trace request", {
|
|
64
68
|
sessionID,
|
|
65
69
|
model: parsed.model,
|
|
@@ -72,9 +76,49 @@ export function traceRequestBody(deps, sessionID, body) {
|
|
|
72
76
|
toolNames: tools,
|
|
73
77
|
lastRole: last?.role,
|
|
74
78
|
lastStart: textOf(last?.content).slice(0, 80).replace(/\n/g, " "),
|
|
79
|
+
lastRealUserKeys: lastRealUser ? Object.keys(lastRealUser) : [],
|
|
80
|
+
lastRealUserSynthetic: lastRealUser?.synthetic ??
|
|
81
|
+
lastRealUser?.metadata?.source ??
|
|
82
|
+
null,
|
|
83
|
+
...headerTrace(headers),
|
|
75
84
|
});
|
|
76
85
|
}
|
|
77
86
|
catch {
|
|
78
87
|
// A body that is not JSON is not a model request worth tracing.
|
|
79
88
|
}
|
|
80
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Summarises the plugin's headers without leaking the token. The ad context is
|
|
92
|
+
* base64url JSON, so it is decoded here: if the reminder ever replaced the real
|
|
93
|
+
* user text, this trace is what proves it.
|
|
94
|
+
*/
|
|
95
|
+
function headerTrace(headers) {
|
|
96
|
+
if (!headers)
|
|
97
|
+
return {};
|
|
98
|
+
const ad = headers.get("x-ad-context");
|
|
99
|
+
let adUserChars = 0;
|
|
100
|
+
let adAssistantChars = 0;
|
|
101
|
+
let adUserStart = "";
|
|
102
|
+
if (ad && ad !== "none") {
|
|
103
|
+
try {
|
|
104
|
+
const payload = JSON.parse(Buffer.from(ad, "base64url").toString("utf8"));
|
|
105
|
+
adUserChars = payload.user?.length ?? 0;
|
|
106
|
+
adAssistantChars = payload.assistant?.length ?? 0;
|
|
107
|
+
adUserStart = (payload.user ?? "").slice(0, 60).replace(/\s+/g, " ");
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// An opaque ad context is still worth reporting as present.
|
|
111
|
+
adUserChars = ad.length;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const session = headers.get("x-session-id") ?? "";
|
|
115
|
+
return {
|
|
116
|
+
xTurnID: headers.get("x-turn-id") ?? "",
|
|
117
|
+
xSessionSuffix: session.includes("-r") ? session.slice(session.indexOf("-r")) : "",
|
|
118
|
+
xAdContext: ad === "none" ? "none" : `${adUserChars}u/${adAssistantChars}a`,
|
|
119
|
+
xAdUserStart: adUserStart,
|
|
120
|
+
xSubagent: headers.get("x-freepi-subagent") ?? "",
|
|
121
|
+
xToolMeta: headers.get("x-freepi-tool-meta") ?? "",
|
|
122
|
+
xCompacted: headers.get("x-freepi-compacted") ?? "",
|
|
123
|
+
};
|
|
124
|
+
}
|
package/package.json
CHANGED
package/src/ads/context.ts
CHANGED
|
@@ -3,6 +3,22 @@
|
|
|
3
3
|
import { AD_CONTEXT_MAX_CHARS, TURN_REMINDER_MARKER } from "../constants.js";
|
|
4
4
|
import { cleanText } from "../utils/text.js";
|
|
5
5
|
|
|
6
|
+
/** Start of the synthetic user message OpenCode creates for a finished subagent. */
|
|
7
|
+
const SUBAGENT_RESULT_PREFIX = "<subagent ";
|
|
8
|
+
/**
|
|
9
|
+
* User-role messages OpenCode injects on its own. They are stored as
|
|
10
|
+
* `type: "synthetic"` but lowered to `user` on the wire, so the prefix is the
|
|
11
|
+
* only signal the ad context can use.
|
|
12
|
+
*/
|
|
13
|
+
const SYNTHETIC_USER_PREFIXES = [
|
|
14
|
+
SUBAGENT_RESULT_PREFIX,
|
|
15
|
+
"<shell ",
|
|
16
|
+
"Instructions from: ",
|
|
17
|
+
"The server restarted while you were working.",
|
|
18
|
+
"The previous response was interrupted.",
|
|
19
|
+
"User requested that active blocking work be moved to the background.",
|
|
20
|
+
] as const;
|
|
21
|
+
|
|
6
22
|
const AD_SECRET_PATTERNS: Array<[string, RegExp]> = [
|
|
7
23
|
[
|
|
8
24
|
"private_key",
|
|
@@ -135,16 +151,46 @@ export function latestUserText(messages: readonly AdMessage[]): string {
|
|
|
135
151
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
136
152
|
const message = messages[index];
|
|
137
153
|
if (roleOf(message) !== "user") continue;
|
|
138
|
-
const text =
|
|
139
|
-
typeof message.text === "string" ? message.text : contentText(message.content),
|
|
140
|
-
);
|
|
154
|
+
const text = messageText(message);
|
|
141
155
|
// The plugin appends this after the ad turn is resolved; ignore it if the
|
|
142
156
|
// event is reused so the next ad never describes the reminder itself.
|
|
143
|
-
if (text
|
|
157
|
+
if (isRealUserTurn(text)) return text;
|
|
144
158
|
}
|
|
145
159
|
return "";
|
|
146
160
|
}
|
|
147
161
|
|
|
162
|
+
function messageText(message: AdMessage): string {
|
|
163
|
+
return cleanText(
|
|
164
|
+
typeof message.text === "string" ? message.text : contentText(message.content),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* A user-role message that is not the user's own turn.
|
|
170
|
+
*
|
|
171
|
+
* OpenCode lowers a finished subagent into a `user` message that starts with
|
|
172
|
+
* `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
|
|
173
|
+
* also a `user` message. Treating either as a new turn rotated the ad in the
|
|
174
|
+
* middle of one user request and sent its internal ids as the ad context.
|
|
175
|
+
*/
|
|
176
|
+
function isRealUserTurn(text: string): boolean {
|
|
177
|
+
return (
|
|
178
|
+
text.length > 0 &&
|
|
179
|
+
!text.startsWith(TURN_REMINDER_MARKER) &&
|
|
180
|
+
!SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix))
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Number of real user turns; synthetic messages do not start a new one. */
|
|
185
|
+
export function countUserTurns(messages: readonly AdMessage[]): number {
|
|
186
|
+
let count = 0;
|
|
187
|
+
for (const message of messages) {
|
|
188
|
+
if (roleOf(message) !== "user") continue;
|
|
189
|
+
if (isRealUserTurn(messageText(message))) count += 1;
|
|
190
|
+
}
|
|
191
|
+
return count;
|
|
192
|
+
}
|
|
193
|
+
|
|
148
194
|
/** Latest user message id from a message list. */
|
|
149
195
|
export function latestUserMessageID(
|
|
150
196
|
messages: readonly AdMessage[],
|
|
@@ -152,6 +198,7 @@ export function latestUserMessageID(
|
|
|
152
198
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
153
199
|
const message = messages[index];
|
|
154
200
|
if (roleOf(message) !== "user") continue;
|
|
201
|
+
if (!isRealUserTurn(messageText(message))) continue;
|
|
155
202
|
if (typeof message.id === "string" && message.id) return message.id;
|
|
156
203
|
}
|
|
157
204
|
return undefined;
|
package/src/ads/resolve.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { Deps } from "../deps.js";
|
|
|
5
5
|
import type { AdTurn } from "../types.js";
|
|
6
6
|
import {
|
|
7
7
|
adContextFor,
|
|
8
|
+
countUserTurns,
|
|
8
9
|
latestAssistantText,
|
|
9
10
|
latestUserMessageID,
|
|
10
11
|
latestUserText,
|
|
@@ -12,24 +13,15 @@ import {
|
|
|
12
13
|
} from "./context.js";
|
|
13
14
|
import { adTurnKey, getAdTurn, rememberAdTurn } from "./turns.js";
|
|
14
15
|
|
|
15
|
-
function userMessageCount(messages: readonly AdMessage[]): number {
|
|
16
|
-
let count = 0;
|
|
17
|
-
for (const message of messages) {
|
|
18
|
-
const role = message.role ?? message.type;
|
|
19
|
-
if (role === "user") count += 1;
|
|
20
|
-
}
|
|
21
|
-
return count;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
16
|
/**
|
|
25
17
|
* Stable, id-free turn fingerprint. Provider request messages usually carry the
|
|
26
18
|
* stored user message id, but not always; without one the ad turn would never
|
|
27
19
|
* rotate and the provider would keep answering with the same ad (or fail once
|
|
28
|
-
* it expires). The user-
|
|
20
|
+
* it expires). The real user-turn count plus the latest prompt changes exactly
|
|
29
21
|
* when the user sends a new turn.
|
|
30
22
|
*/
|
|
31
23
|
function turnFingerprint(messages: readonly AdMessage[]): string {
|
|
32
|
-
return `${
|
|
24
|
+
return `${countUserTurns(messages)}:${latestUserText(messages).slice(0, 160)}`;
|
|
33
25
|
}
|
|
34
26
|
|
|
35
27
|
export type AdTurnRequest = {
|
package/src/session/hooks.ts
CHANGED
|
@@ -689,11 +689,49 @@ async function registerToolHooks(
|
|
|
689
689
|
status: event.status,
|
|
690
690
|
...(event.status === "completed" ? { result: event.result } : {}),
|
|
691
691
|
});
|
|
692
|
+
nudgeFailedTool(deps, event);
|
|
692
693
|
replaceUnsupportedImages(deps, event);
|
|
693
694
|
}),
|
|
694
695
|
);
|
|
695
696
|
}
|
|
696
697
|
|
|
698
|
+
/**
|
|
699
|
+
* Adds the concrete next step to a tool failure the free models repeat.
|
|
700
|
+
*
|
|
701
|
+
* The scan of a week of sessions shows the same failures over and over: the
|
|
702
|
+
* portable shell scanner rejects a heredoc or a nested-quote one-liner (72
|
|
703
|
+
* times), `edit` gets identical strings (12) or an ambiguous `oldString` (8).
|
|
704
|
+
* The model reads the bare error and often repeats the call. The hint is short
|
|
705
|
+
* and only goes to free-pi sessions; other providers keep their own messages.
|
|
706
|
+
*/
|
|
707
|
+
function nudgeFailedTool(deps: Deps, event: any): void {
|
|
708
|
+
if (event.status !== "error") return;
|
|
709
|
+
if (!isFreePiSession(deps, event.sessionID)) return;
|
|
710
|
+
const error = event.error;
|
|
711
|
+
if (!error || typeof error !== "object") return;
|
|
712
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
713
|
+
if (!message) return;
|
|
714
|
+
let hint = "";
|
|
715
|
+
if (message.includes("Portable shell scanner cannot analyze command")) {
|
|
716
|
+
hint =
|
|
717
|
+
" Write the script to a file with the write tool and run that file; on Windows use PowerShell cmdlets instead of cmd syntax.";
|
|
718
|
+
} else if (/No changes to apply: oldString and newString are identical/i.test(message)) {
|
|
719
|
+
hint =
|
|
720
|
+
" Change the replacement text: oldString and newString must differ. Re-read the line you want to change first.";
|
|
721
|
+
} else if (/Found \d+ matches? for oldString/i.test(message)) {
|
|
722
|
+
hint =
|
|
723
|
+
" Include enough surrounding lines so oldString matches exactly once, or set replaceAll when every occurrence must change.";
|
|
724
|
+
} else if (/has not been read yet|read it before/i.test(message)) {
|
|
725
|
+
hint = " Read the file with the read tool in this turn before editing it.";
|
|
726
|
+
}
|
|
727
|
+
if (!hint) return;
|
|
728
|
+
try {
|
|
729
|
+
error.message = `${message}${hint}`;
|
|
730
|
+
} catch {
|
|
731
|
+
// A frozen error still reaches the model unchanged; the hint is best effort.
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
697
735
|
/**
|
|
698
736
|
* Models whose upstream accepts images get them natively, so a `read` that
|
|
699
737
|
* returns a picture must keep the file part. Text-only models would turn it
|
package/src/session/replay.ts
CHANGED
|
@@ -57,7 +57,7 @@ export async function rememberReplayBody(
|
|
|
57
57
|
deps.state.replayBodies.delete(key);
|
|
58
58
|
deps.state.replayBodies.set(key, body);
|
|
59
59
|
trimMap(deps.state.replayBodies, REPLAY_BODY_LIMIT);
|
|
60
|
-
traceRequestBody(deps, event.sessionID, body);
|
|
60
|
+
traceRequestBody(deps, event.sessionID, body, request.headers);
|
|
61
61
|
} catch {
|
|
62
62
|
// A non-replayable body simply falls back to the normal retry hook.
|
|
63
63
|
}
|
package/src/session/trace.ts
CHANGED
|
@@ -33,6 +33,7 @@ export function traceRequestBody(
|
|
|
33
33
|
deps: Deps,
|
|
34
34
|
sessionID: string,
|
|
35
35
|
body: string,
|
|
36
|
+
headers?: Headers,
|
|
36
37
|
): void {
|
|
37
38
|
if (process.env.FREE_PI_TRACE !== "1") return;
|
|
38
39
|
try {
|
|
@@ -75,6 +76,13 @@ export function traceRequestBody(
|
|
|
75
76
|
? parsed.tools.map((tool) => tool?.function?.name ?? "?")
|
|
76
77
|
: [];
|
|
77
78
|
const last = messages.at(-1);
|
|
79
|
+
const lastRealUser = [...messages]
|
|
80
|
+
.reverse()
|
|
81
|
+
.find(
|
|
82
|
+
(message) =>
|
|
83
|
+
message.role === "user" &&
|
|
84
|
+
!textOf(message.content).startsWith("# free-pi turn check"),
|
|
85
|
+
) as Record<string, unknown> | undefined;
|
|
78
86
|
deps.log.info("free-pi trace request", {
|
|
79
87
|
sessionID,
|
|
80
88
|
model: parsed.model,
|
|
@@ -87,8 +95,50 @@ export function traceRequestBody(
|
|
|
87
95
|
toolNames: tools,
|
|
88
96
|
lastRole: last?.role,
|
|
89
97
|
lastStart: textOf(last?.content).slice(0, 80).replace(/\n/g, " "),
|
|
98
|
+
lastRealUserKeys: lastRealUser ? Object.keys(lastRealUser) : [],
|
|
99
|
+
lastRealUserSynthetic:
|
|
100
|
+
(lastRealUser as any)?.synthetic ??
|
|
101
|
+
(lastRealUser as any)?.metadata?.source ??
|
|
102
|
+
null,
|
|
103
|
+
...headerTrace(headers),
|
|
90
104
|
});
|
|
91
105
|
} catch {
|
|
92
106
|
// A body that is not JSON is not a model request worth tracing.
|
|
93
107
|
}
|
|
94
108
|
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Summarises the plugin's headers without leaking the token. The ad context is
|
|
112
|
+
* base64url JSON, so it is decoded here: if the reminder ever replaced the real
|
|
113
|
+
* user text, this trace is what proves it.
|
|
114
|
+
*/
|
|
115
|
+
function headerTrace(headers: Headers | undefined): Record<string, unknown> {
|
|
116
|
+
if (!headers) return {};
|
|
117
|
+
const ad = headers.get("x-ad-context");
|
|
118
|
+
let adUserChars = 0;
|
|
119
|
+
let adAssistantChars = 0;
|
|
120
|
+
let adUserStart = "";
|
|
121
|
+
if (ad && ad !== "none") {
|
|
122
|
+
try {
|
|
123
|
+
const payload = JSON.parse(
|
|
124
|
+
Buffer.from(ad, "base64url").toString("utf8"),
|
|
125
|
+
) as { user?: string; assistant?: string };
|
|
126
|
+
adUserChars = payload.user?.length ?? 0;
|
|
127
|
+
adAssistantChars = payload.assistant?.length ?? 0;
|
|
128
|
+
adUserStart = (payload.user ?? "").slice(0, 60).replace(/\s+/g, " ");
|
|
129
|
+
} catch {
|
|
130
|
+
// An opaque ad context is still worth reporting as present.
|
|
131
|
+
adUserChars = ad.length;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const session = headers.get("x-session-id") ?? "";
|
|
135
|
+
return {
|
|
136
|
+
xTurnID: headers.get("x-turn-id") ?? "",
|
|
137
|
+
xSessionSuffix: session.includes("-r") ? session.slice(session.indexOf("-r")) : "",
|
|
138
|
+
xAdContext: ad === "none" ? "none" : `${adUserChars}u/${adAssistantChars}a`,
|
|
139
|
+
xAdUserStart: adUserStart,
|
|
140
|
+
xSubagent: headers.get("x-freepi-subagent") ?? "",
|
|
141
|
+
xToolMeta: headers.get("x-freepi-tool-meta") ?? "",
|
|
142
|
+
xCompacted: headers.get("x-freepi-compacted") ?? "",
|
|
143
|
+
};
|
|
144
|
+
}
|