Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 9 additions & 13 deletions src/affinity-neutral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] {
const role = m.role === "model" ? "assistant" : typeof m.role === "string" ? m.role : "user";
const texts: string[] = [];
const calls: string[] = [];
let toolBody: string | undefined;
const toolBodies: string[] = [];
for (const part of m.parts) {
if (!part || typeof part !== "object") continue;
const p = part as { text?: unknown; functionCall?: unknown; functionResponse?: unknown };
Expand All @@ -253,11 +253,11 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] {
// gemini clients wrap the tool body under an arbitrary key
// ({output:…}/{result:…}/{content:…}); a single-string-valued
// object IS the body — unwrap so it equals the openai render.
if (typeof resp === "string") toolBody = resp;
if (typeof resp === "string") toolBodies.push(resp);
else if (resp && typeof resp === "object" && !Array.isArray(resp)) {
const entries = Object.entries(resp as Record<string, unknown>);
toolBody = entries.length === 1 && typeof entries[0]![1] === "string" ? entries[0]![1]! : canon(resp);
} else toolBody = canon(resp ?? p.functionResponse);
toolBodies.push(entries.length === 1 && typeof entries[0]![1] === "string" ? entries[0]![1]! : canon(resp));
} else toolBodies.push(canon(resp ?? p.functionResponse));
}
}
// model turns MERGE into the pending assistant run — gemini splits
Expand All @@ -273,8 +273,8 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] {
continue;
}
flushAssistant();
if (toolBody !== undefined) turns.push({ kind: "tool", text: toolBody, frags: [fragmentHash("tool", toolBody, [])] });
if (calls.length > 0 && toolBody === undefined) turns.push({ kind: "assistant", calls, frags: [fragmentHash("assistant", "", calls)] });
for (const toolBody of toolBodies) turns.push({ kind: "tool", text: toolBody, frags: [fragmentHash("tool", toolBody, [])] });
if (calls.length > 0 && toolBodies.length === 0) turns.push({ kind: "assistant", calls, frags: [fragmentHash("assistant", "", calls)] });
else if (texts.length > 0) pushTextTurn(role, texts.join(""), [fragmentHash(role, texts.join(""), [])]);
continue;
}
Expand All @@ -285,13 +285,9 @@ export function neutralTurns(messages: unknown[]): NeutralTurn[] {
const call = `${m.name}\u0000${canonicalCallArgs(m.arguments)}`;
// codex splits assistant commentary and the tool call across items —
// merge into the pending run so it reduces like the openai render.
if (asst !== null) {
asst.calls = [...(asst.calls ?? []), call];
asstFrags.push(fragmentHash("assistant", "", [call]));
continue;
}
flushAssistant();
turns.push({ kind: "assistant", calls: [call], frags: [fragmentHash("assistant", "", [call])] });
asst = asst ?? { kind: "assistant", text: "", calls: [] };
asst.calls = [...(asst.calls ?? []), call];
asstFrags.push(fragmentHash("assistant", "", [call]));
continue;
}
if (typeof m.type === "string" && (m.type === "function_call_output" || m.type === "local_shell_call_output")) {
Expand Down
30 changes: 27 additions & 3 deletions tests/affinity-crosswire-fold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,33 @@ test("cross-wire switch onto the responses and google lanes keeps the session AN

type Msg = { role: string; content: string };
const hist: Msg[] = [];
const parallelTools = [
{ id: "parallel_a", name: "read_file", args: { path: "/a.ts" }, output: "parallel result alpha" },
{ id: "parallel_b", name: "read_file", args: { path: "/b.ts" }, output: "parallel result beta" },
];
const question = "Read both source files before the next audit turn.";
const withParallel = (messages: unknown[], round: unknown[]): unknown[] => messages.length > 20
? [...messages.slice(0, 20), ...round, ...messages.slice(20)] : messages;
const openaiRound = [
{ role: "user", content: question },
{ role: "assistant", content: null, tool_calls: parallelTools.map((t) => ({ id: t.id, type: "function", function: { name: t.name, arguments: JSON.stringify(t.args) } })) },
...parallelTools.map((t) => ({ role: "tool", tool_call_id: t.id, content: t.output })),
];
const responsesRound = [
{ type: "message", role: "user", content: [{ type: "input_text", text: question }] },
...parallelTools.map((t) => ({ type: "function_call", call_id: t.id, name: t.name, arguments: JSON.stringify(t.args) })),
...parallelTools.map((t) => ({ type: "function_call_output", call_id: t.id, output: t.output })),
];
const googleRound = [
{ role: "user", parts: [{ text: question }] },
{ role: "model", parts: parallelTools.map((t) => ({ functionCall: { name: t.name, args: t.args } })) },
{ role: "user", parts: parallelTools.map((t) => ({ functionResponse: { name: t.name, response: { output: t.output } } })) },
];
try {
// Phase A — openai lane establishes the anonymous session and folds.
const openaiTurn = async (t: number): Promise<void> => {
hist.push({ role: "user", content: `Turn ${t}: audit province ${t}. ` + FILLER(t, 6) });
const resp = await fetch(openaiBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", stream: true, messages: [...hist] }) });
const resp = await fetch(openaiBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", stream: true, messages: withParallel(hist, openaiRound) }) });
assert.equal(resp.status, 200, `openai turn ${t}`);
await resp.text();
hist.push({ role: "assistant", content: `Reply about province ${t}: acknowledged. ` + FILLER(t, 0.2) });
Expand All @@ -305,7 +327,7 @@ test("cross-wire switch onto the responses and google lanes keeps the session AN
role: m.role,
content: [{ type: m.role === "assistant" ? "output_text" : "input_text", text: m.content }],
}));
const respB = await fetch(responsesBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", stream: true, instructions: "crosswire probe", input: respItems }) });
const respB = await fetch(responsesBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", stream: true, instructions: "crosswire probe", input: withParallel(respItems, responsesRound) }) });
const respRaw = await respB.text();
if (respB.status !== 200) assert.fail(`responses switch turn: ${respB.status}: ${respRaw.slice(0, 200)}`);
hist.push({ role: "assistant", content: "Responses reply about turn 13: acknowledged." });
Expand All @@ -314,6 +336,7 @@ test("cross-wire switch onto the responses and google lanes keeps the session AN
let pfasB = prefixAffinity.trackedSessionIds().filter((id) => id.startsWith("pfa-"));
assert.equal(pfasB.length, 1, `the responses switch must not fork: got ${pfasB.join(", ")}`);
assert.equal(pfasB[0], sessionId);
for (const tool of parallelTools) assert.ok(responsesBody.includes(tool.output), "both tool results survive the switch");
assert.ok(responsesBody.includes(SUMMARY_TEXT), "the fold carrier is attached on the responses wire");
assert.equal((responsesBody.match(new RegExp(EARLY_FILLER_TAG, "g")) ?? []).length, 0, "covered early content must not replay unfolded on the responses switch");
assert.equal(foldDemands, foldsBeforeSwitch, "no re-fold demanded on the responses switch");
Expand All @@ -323,14 +346,15 @@ test("cross-wire switch onto the responses and google lanes keeps the session AN
// history re-rendered as contents[].parts[].
hist.push({ role: "user", content: "Turn 14: continue with province seven." });
const contents = hist.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: [{ text: m.content }] }));
const respG = await fetch(googleBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", contents }) });
const respG = await fetch(googleBase, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "probe-model", contents: withParallel(contents, googleRound) }) });
const googleRaw = await respG.text();
if (respG.status !== 200) assert.fail(`google switch turn: ${respG.status}: ${googleRaw.slice(0, 200)}`);

const googleBody = bodies.google[bodies.google.length - 1]!;
pfasB = prefixAffinity.trackedSessionIds().filter((id) => id.startsWith("pfa-"));
assert.equal(pfasB.length, 1, `the google switch must not fork: got ${pfasB.join(", ")}`);
assert.equal(pfasB[0], sessionId);
for (const tool of parallelTools) assert.ok(googleBody.includes(tool.output), "both tool results survive the switch");
assert.ok(googleBody.includes(SUMMARY_TEXT), "the fold carrier is attached on the google wire");
assert.equal((googleBody.match(new RegExp(EARLY_FILLER_TAG, "g")) ?? []).length, 0, "covered early content must not replay unfolded on the google switch");
assert.equal(foldDemands, foldsBeforeSwitch, "no re-fold demanded on the google switch");
Expand Down
79 changes: 79 additions & 0 deletions tests/affinity-neutral.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,82 @@ test("#2791: pre-upgrade (raw-hash) entries still match through the v1 fallback
assert.equal(crossed.via, "prefix", "re-noted entry must now match across wires");
assert.equal(crossed.sessionId, "pfa-legacy000000001");
});

const parallelTools = [
{ id: "parallel_a", name: "read_file", args: { path: "/src/a.ts" }, output: "first file contents" },
{ id: "parallel_b", name: "read_file", args: { path: "/src/b.ts" }, output: "second file contents" },
];

function parallelToolRenders(): Record<string, Array<Record<string, unknown>>> {
const question = "Read both source files before comparing their exports.";
return {
openai: [
{ role: "user", content: question },
{ role: "assistant", content: null, tool_calls: parallelTools.map((t) => ({ id: t.id, type: "function", function: { name: t.name, arguments: JSON.stringify(t.args) } })) },
...parallelTools.map((t) => ({ role: "tool", tool_call_id: t.id, content: t.output })),
],
anthropic: [
{ role: "user", content: [{ type: "text", text: question }] },
{ role: "assistant", content: parallelTools.map((t) => ({ type: "tool_use", id: t.id, name: t.name, input: t.args })) },
{ role: "user", content: parallelTools.map((t) => ({ type: "tool_result", tool_use_id: t.id, content: t.output })) },
],
responses: [
{ type: "message", role: "user", content: [{ type: "input_text", text: question }] },
...parallelTools.map((t) => ({ type: "function_call", call_id: t.id, name: t.name, arguments: JSON.stringify(t.args) })),
...parallelTools.map((t) => ({ type: "function_call_output", call_id: t.id, output: t.output })),
],
google: [
{ role: "user", parts: [{ text: question }] },
{ role: "model", parts: parallelTools.map((t) => ({ functionCall: { name: t.name, args: t.args } })) },
{ role: "user", parts: parallelTools.map((t) => ({ functionResponse: { name: t.name, response: { output: t.output } } })) },
],
};
}

for (const wire of ["anthropic", "responses", "google"]) {
test(`parallel tools: ${wire} preserves the complete neutral call and result sequence`, () => {
const renders = parallelToolRenders();
const expected = neutralTurns(renders.openai!);
const actual = neutralTurns(renders[wire]!);
assert.deepEqual(actual.map(neutralTurnCanonical), expected.map(neutralTurnCanonical));
assert.deepEqual(actual.filter((t) => t.kind === "tool").map((t) => t.text), parallelTools.map((t) => t.output));
});

test(`parallel tools: switching from openai to ${wire} retains the anonymous session`, () => {
const renders = parallelToolRenders();
const resolver = new PrefixAffinityResolver();
const first = resolver.resolve(renders.openai!)!;
resolver.note(first.sessionId, first.incomingDepth, first.tailHash, first.itemHashes, false, first.sketches, first.userFlags);
const switched = resolver.resolve([...renders[wire]!, { role: "user", content: "Now compare the exports." }])!;
assert.equal(switched.via, "prefix");
assert.equal(switched.sessionId, first.sessionId);
assert.equal(switched.incomingDepth, first.incomingDepth + 1);
});
}

test("parallel tools: Gemini retains every result body and trailing user text", () => {
const bodies = ["plain", { output: "wrapped" }, { count: 2, ok: true }, ["a", "b"], null];
const actual = neutralTurns([{ role: "user", parts: [
...bodies.map((response) => ({ functionResponse: { name: "lookup", response } })),
{ text: "Continue after all results." },
] }]);
assert.deepEqual(actual.map((t) => [t.kind, t.text]), [
["tool", "plain"], ["tool", "wrapped"], ["tool", '{"count":2,"ok":true}'],
["tool", '["a","b"]'], ["tool", '{"name":"lookup","response":null}'],
["user", "Continue after all results."],
]);
});

test("parallel tools: Responses results separate consecutive call rounds", () => {
const turns = neutralTurns([
{ type: "function_call", name: "first", arguments: "{}" },
{ type: "function_call", name: "second", arguments: "{}" },
{ type: "function_call_output", output: "first result" },
{ type: "function_call_output", output: "second result" },
{ type: "function_call", name: "third", arguments: "{}" },
]);
assert.deepEqual(turns.map((t) => [t.kind, t.calls ?? t.text]), [
["assistant", ["first\u0000{}", "second\u0000{}"]],
["tool", "first result"], ["tool", "second result"], ["assistant", ["third\u0000{}"]],
]);
});
Loading