Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 2,454 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { join } from "node:path";

// Pi 1.5's OpenAI adapter omits Google's tool-call extra_content when it builds
// the next request. Preserve the original opaque signatures, as Stanford's
// _compat_echo does; never synthesize a signature or weaken its validation.
export default function (pi) {
  const directory = process.env.PI_CODING_AGENT_DIR || "/tmp/harbor-pi-agent";
  const file = join(directory, "google-thought-signatures.json");
  const signatures = new Map(existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : []);
  const partial = new Map();

  pi.on("provider_stream_event", (event) => {
    if (event.api !== "openai-completions" || !String(event.model || "").startsWith("gemini-")) return;
    for (const choice of event.data?.choices || []) {
      for (const call of choice.delta?.tool_calls || []) {
        const key = `${choice.index || 0}:${call.index || 0}`;
        const accumulated = partial.get(key) || {};
        if (call.id) accumulated.id = call.id;
        if (call.extra_content) accumulated.extra = structuredClone(call.extra_content);
        partial.set(key, accumulated);
        if (accumulated.id && accumulated.extra?.google?.thought_signature) {
          signatures.set(accumulated.id, accumulated.extra);
          mkdirSync(directory, { recursive: true });
          const temporary = `${file}.${process.pid}.tmp`;
          writeFileSync(temporary, JSON.stringify([...signatures]), { mode: 0o600 });
          renameSync(temporary, file);
        }
      }
    }
  });

  pi.on("before_provider_request", (event) => {
    const payload = event.payload;
    if (!payload || !String(payload.model || "").startsWith("gemini-")) return;
    // Google's compatibility endpoint also rejects OpenAI's optional store flag.
    const { store, ...compatible } = payload;
    compatible.messages = (compatible.messages || []).map((message) => {
      if (!message.tool_calls) return message;
      return { ...message, tool_calls: message.tool_calls.map((call) => {
        const extra = signatures.get(call.id);
        if (!extra || call.extra_content?.google?.thought_signature) return call;
        return { ...call, extra_content: { ...extra, ...call.extra_content,
          google: { ...extra.google, ...call.extra_content?.google } } };
      }) };
    });
    partial.clear();
    return compatible;
  });
}