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
3 changes: 3 additions & 0 deletions app/src/lib/copilot/bot-offer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type CapabilityKey,
myCapabilitiesQueryOptions,
} from "@/lib/enterprise/queries";
import { sendPartsByReference } from "@/lib/copilot/run-parts";
import { agentSkillsQueryOptions } from "@/lib/plugins/queries";

/**
Expand Down Expand Up @@ -239,6 +240,8 @@ export function offerItsOwnTools(
}),
);
});
// After the narrowing, so the list sent by its hash is the one this Bot is offered.
sendPartsByReference(agent, queries);
}

/**
Expand Down
173 changes: 173 additions & 0 deletions app/src/lib/copilot/run-parts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import type { AbstractAgent } from "@copilotkit/react-core/v2";
import {
byReference,
RUN_PARTS_NEEDED,
sentByReference,
} from "@openbot/shared/run-parts";
import type { QueryClient } from "@tanstack/react-query";
import {
type DeploymentCapabilities,
deploymentKeys,
} from "@/lib/deployment/queries";

/**
* A run's tools, context and generative UI catalog, sent once and then by their hashes.
*
* WHY. Every run carried the same three parts, about 145 KB for a Bot holding every component and
* its computer, for a few hundred bytes of conversation: on every message, and again on every step
* of a turn, since each answered tool call starts a run of its own. Joining a conversation sent them
* too. Where the server takes them by reference (`runPartsByReference`), a run names each part by
* its hash and carries it only until the server holds it; the server puts every part back before
* the run goes anywhere, so every Bot, built in or connected over AG-UI, is sent exactly the run it
* was sent before. See `shared/run-parts.ts` for the form.
*
* ON THE REQUEST, NOT THE RUN. The SDK checks a run against AG-UI's schema as it sends it, and the
* form's `context` is deliberately not one AG-UI takes (so an older server refuses it rather than
* running it without its parts). So the run is left whole all the way through the SDK, which is
* also what every subscriber and middleware on the page sees, and only the request's body is
* changed, by the agent's own `fetch`. It is the body of a run or a join of a conversation
* (`agent/<id>/run`, `agent/<id>/connect`), on the address the SDK posts each to, whether the run's
* events come back on the request or over the realtime socket.
*
* WHAT THIS PAGE KNOWS. A part counts as held once a request that carried it is answered: the server
* keeps every part it is given before anything runs. Kept for the page's life, in memory: the first
* request of a page carries each part, and every one after it the hashes.
*
* WHEN THE SERVER DISAGREES. A part the server no longer holds is refused before anything runs
* (409 `RUN_PARTS_NEEDED`), and the request goes again once, carrying every part. Any other 409 (a
* conversation already answering) goes back to the SDK as it came. A server that refuses the form
* itself (400: one from before this, behind an answer from a newer one, as in a rolling upgrade) is
* sent that request whole, and every one after it for the rest of the page.
*/

/** The hashes of the parts the server holds, as far as this page knows. */
const held = new Set<string>();

/** Set once a server refused the by-reference form: from then on, every request goes whole. */
let formRefused = false;

/** The requests whose body is a run: a run, or a join of a conversation. */
const RUN_REQUEST = /\/agent\/[^/]+\/(run|connect)$/;

type Fetch = (url: string, init?: RequestInit) => Promise<Response>;

/**
* Each fetch sending parts by reference, by the fetch it sends with, so wrapping one again gives the
* same function, and a wrapper is never wrapped again.
*/
const wrappers = new WeakMap<Fetch, Fetch>();
const wrapped = new WeakSet<Fetch>();

/** Why the server refused a request before anything ran, or undefined. */
async function refusalOf(
response: Response,
): Promise<"needed" | "form" | undefined> {
if (response.status === 400) return "form";
if (response.status !== 409) return undefined;
try {
const problem = (await response.clone().json()) as { code?: unknown };
return problem?.code === RUN_PARTS_NEEDED ? "needed" : undefined;
} catch {
return undefined;
}
}

/** The run a request carries, when it is one this can send by reference. */
function runOf(
url: unknown,
init: RequestInit | undefined,
): Record<string, unknown> | undefined {
if (typeof url !== "string" || typeof init?.body !== "string") return;
if ((init.method ?? "GET").toUpperCase() !== "POST") return;
if (!RUN_REQUEST.test(new URL(url, "http://openbot.invalid").pathname))
return;
try {
const body = JSON.parse(init.body) as unknown;
if (!body || typeof body !== "object" || Array.isArray(body)) return;
return sentByReference(body as Record<string, unknown>)
? undefined
: (body as Record<string, unknown>);
} catch {
return;
}
}

/** `send`, with the runs it posts sent by reference wherever the server says it takes them. */
export function partsByReference(send: Fetch, queries: QueryClient): Fetch {
if (wrapped.has(send)) return send;
const existing = wrappers.get(send);
if (existing) return existing;
const sending: Fetch = async (url, init) => {
const run = runOf(url, init);
const offered =
queries.getQueryData<DeploymentCapabilities>(
deploymentKeys.capabilities(),
)?.runPartsByReference === true;
if (!run || !offered || formRefused) return send(url, init);
const post = async (whole: boolean) => {
const { body, carried } = await byReference(
run,
(hash) => held.has(hash),
{ whole },
);
const response = await send(url, { ...init, body: JSON.stringify(body) });
if (response.ok) for (const hash of carried) held.add(hash);
return response;
};
const response = await post(false);
if (response.ok) return response;
const refusal = await refusalOf(response);
if (refusal === "needed") {
held.clear();
return post(true);
}
if (refusal === "form") {
formRefused = true;
return send(url, init);
}
return response;
};
wrapped.add(sending);
wrappers.set(send, sending);
return sending;
}

/** The agents already given this. */
const given = new WeakSet<AbstractAgent>();

/**
* Send this agent's runs with their parts by reference, wherever the server says it takes them.
* Given once per agent, beside its offer (`offerItsOwnTools`).
*
* AS THE AGENT'S `fetch`, HOWEVER OFTEN IT IS SET. The SDK sets an agent's `fetch` to its own
* runtime fetch whenever it registers the agent again, so wrapping the value once was undone at the
* next registration. Whatever `fetch` the agent is given is wrapped as it is set. A copy of the
* agent is made with the agent's `fetch`, so it starts wrapped too, and is given this itself as its
* turn starts (`BotOffers`).
*/
export function sendPartsByReference(
agent: AbstractAgent,
queries: QueryClient,
): void {
if (given.has(agent)) return;
given.add(agent);
const wrap = (send: unknown) =>
typeof send === "function"
? partsByReference(send as Fetch, queries)
: send;
let current = wrap((agent as unknown as { fetch?: unknown }).fetch);
Object.defineProperty(agent, "fetch", {
configurable: true,
enumerable: true,
get: () => current,
set: (send: unknown) => {
current = wrap(send);
},
});
}

/** For tests: forget what this page knows, as a fresh page would. */
export function forgetHeldRunParts(): void {
held.clear();
formRefused = false;
}
7 changes: 7 additions & 0 deletions app/src/lib/deployment/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ export type DeploymentCapabilities = {
* conversation.
*/
computerStepsByReference?: boolean;
/**
* Whether a run may carry its tools, its context and its generative UI catalog by reference,
* each named by its hash once the server holds it (`lib/copilot/run-parts.ts`). False from a
* server that doesn't say, which takes only whole runs.
*/
runPartsByReference?: boolean;
};

/**
Expand Down Expand Up @@ -326,6 +332,7 @@ export function deploymentCapabilitiesQueryOptions() {
botComputers: body.botComputers !== false,
hostedSignIn: body.hostedSignIn === true,
computerStepsByReference: body.computerStepsByReference === true,
runPartsByReference: body.runPartsByReference === true,
};
},
});
Expand Down
31 changes: 25 additions & 6 deletions app/tests/run-parts-app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@ class QuietSocket {
}

export const runs: SentRun[] = [];
/** Every join of the conversation the app sends (`agent/<id>/connect`), as it left. */
export const joins: SentRun[] = [];

/** A join answered with an empty conversation. */
export function emptyJoin(join: SentRun): Response {
const threadId = join.body.threadId;
return sse([
{ type: "RUN_STARTED", threadId, runId: "join" },
{ type: "MESSAGES_SNAPSHOT", messages: [] },
{ type: "RUN_FINISHED", threadId, runId: "join" },
]);
}

/** The server's answer to each join. */
let answerJoin: (join: SentRun) => Response | Promise<Response> = emptyJoin;
export function answerJoinsWith(
answer: (join: SentRun) => Response | Promise<Response>,
) {
answerJoin = answer;
}
/** The server's answer to each run. */
export let answerRun: (run: SentRun) => Response | Promise<Response> = (run) =>
reply(run.body);
Expand Down Expand Up @@ -171,12 +191,10 @@ export function setUpApp() {
telemetryDisabled: true,
});
if (url.pathname.endsWith("/connect")) {
const { threadId } = (await request.json()) as { threadId: string };
return sse([
{ type: "RUN_STARTED", threadId, runId: "join" },
{ type: "MESSAGES_SNAPSHOT", messages: [] },
{ type: "RUN_FINISHED", threadId, runId: "join" },
]);
const raw = await request.text();
const join = { raw, body: JSON.parse(raw) as Record<string, unknown> };
joins.push(join);
return answerJoin(join);
}
if (url.pathname.endsWith("/run")) {
const raw = await request.text();
Expand Down Expand Up @@ -223,6 +241,7 @@ export async function openConversation(options: {
cleanup();
queryClient.clear();
runs.length = 0;
joins.length = 0;
queryClient.setQueryData(deploymentKeys.capabilities(), {
generativeUi: true,
selfHostBanner: false,
Expand Down
Loading
Loading