@eduardo191labs/opencode-free-pi 0.7.7 → 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 CHANGED
@@ -186,7 +186,12 @@ Después de iniciar sesión, ejecuta `/reload` en OpenCode o reinícialo.
186
186
  free-pi. El CLI nunca los hace y cada ping gastaría créditos y anuncios.
187
187
  - **Timeouts del CLI**: 5 minutos para las cabeceras y para cada trozo de la
188
188
  respuesta, los mismos valores que `httpIdleTimeoutMs` de pi.
189
- - 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.
190
195
  - Cada agente y subagente usa su propio `x-session-id`, `x-turn-id` y contexto
191
196
  de anuncios; nunca reutiliza los del agente principal.
192
197
  - **Cierre de sesión**: free-pi limita la cuenta a 4 sesiones simultáneas. El
@@ -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;
@@ -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 = cleanText(typeof message.text === "string" ? message.text : contentText(message.content));
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 && !text.startsWith(TURN_REMINDER_MARKER))
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
  }
@@ -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-message count plus the latest prompt changes exactly
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 `${userMessageCount(messages)}:${latestUserText(messages).slice(0, 160)}`;
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
@@ -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.
@@ -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;
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduardo191labs/opencode-free-pi",
3
- "version": "0.7.7",
3
+ "version": "0.7.8",
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",
@@ -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 = cleanText(
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 && !text.startsWith(TURN_REMINDER_MARKER)) return 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;
@@ -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-message count plus the latest prompt changes exactly
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 `${userMessageCount(messages)}:${latestUserText(messages).slice(0, 160)}`;
24
+ return `${countUserTurns(messages)}:${latestUserText(messages).slice(0, 160)}`;
33
25
  }
34
26
 
35
27
  export type AdTurnRequest = {
@@ -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
  }
@@ -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
+ }