@eduardo191labs/opencode-free-pi 0.7.7 → 0.7.9
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 +6 -1
- package/dist/ads/context.d.ts +2 -0
- package/dist/ads/context.js +48 -2
- package/dist/ads/resolve.js +3 -12
- 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 +53 -4
- package/src/ads/resolve.ts +3 -11
- package/src/session/replay.ts +1 -1
- package/src/session/trace.ts +50 -0
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
|
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,23 @@
|
|
|
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
|
+
"<image ",
|
|
15
|
+
"Instructions from: ",
|
|
16
|
+
"The server restarted while you were working.",
|
|
17
|
+
"The previous response was interrupted.",
|
|
18
|
+
"User requested that active blocking work be moved to the background.",
|
|
19
|
+
"Your last response hit the output token limit",
|
|
20
|
+
];
|
|
4
21
|
const AD_SECRET_PATTERNS = [
|
|
5
22
|
[
|
|
6
23
|
"private_key",
|
|
@@ -106,20 +123,49 @@ export function latestUserText(messages) {
|
|
|
106
123
|
const message = messages[index];
|
|
107
124
|
if (roleOf(message) !== "user")
|
|
108
125
|
continue;
|
|
109
|
-
const text =
|
|
126
|
+
const text = messageText(message);
|
|
110
127
|
// The plugin appends this after the ad turn is resolved; ignore it if the
|
|
111
128
|
// event is reused so the next ad never describes the reminder itself.
|
|
112
|
-
if (text
|
|
129
|
+
if (isRealUserTurn(text))
|
|
113
130
|
return text;
|
|
114
131
|
}
|
|
115
132
|
return "";
|
|
116
133
|
}
|
|
134
|
+
function messageText(message) {
|
|
135
|
+
return cleanText(typeof message.text === "string" ? message.text : contentText(message.content));
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* A user-role message that is not the user's own turn.
|
|
139
|
+
*
|
|
140
|
+
* OpenCode lowers a finished subagent into a `user` message that starts with
|
|
141
|
+
* `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
|
|
142
|
+
* also a `user` message. Treating either as a new turn rotated the ad in the
|
|
143
|
+
* middle of one user request and sent its internal ids as the ad context.
|
|
144
|
+
*/
|
|
145
|
+
function isRealUserTurn(text) {
|
|
146
|
+
return (text.length > 0 &&
|
|
147
|
+
!text.startsWith(TURN_REMINDER_MARKER) &&
|
|
148
|
+
!SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix)));
|
|
149
|
+
}
|
|
150
|
+
/** Number of real user turns; synthetic messages do not start a new one. */
|
|
151
|
+
export function countUserTurns(messages) {
|
|
152
|
+
let count = 0;
|
|
153
|
+
for (const message of messages) {
|
|
154
|
+
if (roleOf(message) !== "user")
|
|
155
|
+
continue;
|
|
156
|
+
if (isRealUserTurn(messageText(message)))
|
|
157
|
+
count += 1;
|
|
158
|
+
}
|
|
159
|
+
return count;
|
|
160
|
+
}
|
|
117
161
|
/** Latest user message id from a message list. */
|
|
118
162
|
export function latestUserMessageID(messages) {
|
|
119
163
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
120
164
|
const message = messages[index];
|
|
121
165
|
if (roleOf(message) !== "user")
|
|
122
166
|
continue;
|
|
167
|
+
if (!isRealUserTurn(messageText(message)))
|
|
168
|
+
continue;
|
|
123
169
|
if (typeof message.id === "string" && message.id)
|
|
124
170
|
return message.id;
|
|
125
171
|
}
|
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/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,24 @@
|
|
|
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
|
+
"<image ",
|
|
17
|
+
"Instructions from: ",
|
|
18
|
+
"The server restarted while you were working.",
|
|
19
|
+
"The previous response was interrupted.",
|
|
20
|
+
"User requested that active blocking work be moved to the background.",
|
|
21
|
+
"Your last response hit the output token limit",
|
|
22
|
+
] as const;
|
|
23
|
+
|
|
6
24
|
const AD_SECRET_PATTERNS: Array<[string, RegExp]> = [
|
|
7
25
|
[
|
|
8
26
|
"private_key",
|
|
@@ -135,16 +153,46 @@ export function latestUserText(messages: readonly AdMessage[]): string {
|
|
|
135
153
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
136
154
|
const message = messages[index];
|
|
137
155
|
if (roleOf(message) !== "user") continue;
|
|
138
|
-
const text =
|
|
139
|
-
typeof message.text === "string" ? message.text : contentText(message.content),
|
|
140
|
-
);
|
|
156
|
+
const text = messageText(message);
|
|
141
157
|
// The plugin appends this after the ad turn is resolved; ignore it if the
|
|
142
158
|
// event is reused so the next ad never describes the reminder itself.
|
|
143
|
-
if (text
|
|
159
|
+
if (isRealUserTurn(text)) return text;
|
|
144
160
|
}
|
|
145
161
|
return "";
|
|
146
162
|
}
|
|
147
163
|
|
|
164
|
+
function messageText(message: AdMessage): string {
|
|
165
|
+
return cleanText(
|
|
166
|
+
typeof message.text === "string" ? message.text : contentText(message.content),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A user-role message that is not the user's own turn.
|
|
172
|
+
*
|
|
173
|
+
* OpenCode lowers a finished subagent into a `user` message that starts with
|
|
174
|
+
* `<subagent sessionID=… state=…>`, and the plugin's own per-turn reminder is
|
|
175
|
+
* also a `user` message. Treating either as a new turn rotated the ad in the
|
|
176
|
+
* middle of one user request and sent its internal ids as the ad context.
|
|
177
|
+
*/
|
|
178
|
+
function isRealUserTurn(text: string): boolean {
|
|
179
|
+
return (
|
|
180
|
+
text.length > 0 &&
|
|
181
|
+
!text.startsWith(TURN_REMINDER_MARKER) &&
|
|
182
|
+
!SYNTHETIC_USER_PREFIXES.some((prefix) => text.startsWith(prefix))
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Number of real user turns; synthetic messages do not start a new one. */
|
|
187
|
+
export function countUserTurns(messages: readonly AdMessage[]): number {
|
|
188
|
+
let count = 0;
|
|
189
|
+
for (const message of messages) {
|
|
190
|
+
if (roleOf(message) !== "user") continue;
|
|
191
|
+
if (isRealUserTurn(messageText(message))) count += 1;
|
|
192
|
+
}
|
|
193
|
+
return count;
|
|
194
|
+
}
|
|
195
|
+
|
|
148
196
|
/** Latest user message id from a message list. */
|
|
149
197
|
export function latestUserMessageID(
|
|
150
198
|
messages: readonly AdMessage[],
|
|
@@ -152,6 +200,7 @@ export function latestUserMessageID(
|
|
|
152
200
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
153
201
|
const message = messages[index];
|
|
154
202
|
if (roleOf(message) !== "user") continue;
|
|
203
|
+
if (!isRealUserTurn(messageText(message))) continue;
|
|
155
204
|
if (typeof message.id === "string" && message.id) return message.id;
|
|
156
205
|
}
|
|
157
206
|
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/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
|
+
}
|