303 lines
9.7 KiB
TypeScript
303 lines
9.7 KiB
TypeScript
import { BaseTensorZeroClient } from "./base-client";
|
|
import { buildGatewayUrl } from "../gateway-url";
|
|
import type {
|
|
ApproveAllToolCallsGatewayRequest,
|
|
ApproveAllToolCallsResponse,
|
|
CreateEventGatewayRequest,
|
|
CreateEventResponse,
|
|
EditPayload,
|
|
GatewayEvent,
|
|
GatewayListConfigWritesResponse,
|
|
GatewayListEventsResponse,
|
|
GatewayStreamUpdate,
|
|
ListConfigWritesParams,
|
|
ListEventsParams,
|
|
ListSessionsParams,
|
|
ListSessionsResponse,
|
|
StreamEventsParams,
|
|
WriteConfigToolParams,
|
|
} from "~/types/tensorzero";
|
|
|
|
/**
|
|
* A client for calling TensorZero Autopilot API endpoints.
|
|
*/
|
|
export class AutopilotClient extends BaseTensorZeroClient {
|
|
private betaTools: string | null;
|
|
private extraHeaders: Record<string, string>;
|
|
|
|
constructor(
|
|
baseUrl: string,
|
|
apiKey?: string,
|
|
betaTools?: string,
|
|
extraHeaders?: Record<string, string>,
|
|
) {
|
|
super(baseUrl, apiKey);
|
|
this.betaTools = betaTools ?? null;
|
|
this.extraHeaders = extraHeaders ?? {};
|
|
}
|
|
|
|
/**
|
|
* Lists autopilot sessions with optional pagination.
|
|
*/
|
|
async listAutopilotSessions(
|
|
params?: ListSessionsParams,
|
|
): Promise<ListSessionsResponse> {
|
|
const searchParams = new URLSearchParams();
|
|
if (params?.limit) searchParams.set("limit", params.limit.toString());
|
|
if (params?.offset) searchParams.set("offset", params.offset.toString());
|
|
const queryString = searchParams.toString();
|
|
const endpoint = `/internal/autopilot/v1/sessions${queryString ? `?${queryString}` : ""}`;
|
|
|
|
const response = await this.fetch(endpoint, { method: "GET" });
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
return (await response.json()) as ListSessionsResponse;
|
|
}
|
|
|
|
/**
|
|
* Interrupts an autopilot session.
|
|
*/
|
|
async interruptAutopilotSession(sessionId: string): Promise<void> {
|
|
const endpoint = `/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/actions/interrupt`;
|
|
const response = await this.fetch(endpoint, { method: "POST" });
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Lists events for an autopilot session with optional pagination.
|
|
*/
|
|
async listAutopilotEvents(
|
|
sessionId: string,
|
|
params?: ListEventsParams,
|
|
): Promise<GatewayListEventsResponse> {
|
|
const searchParams = new URLSearchParams();
|
|
if (params?.limit) searchParams.set("limit", params.limit.toString());
|
|
if (params?.before) searchParams.set("before", params.before);
|
|
const queryString = searchParams.toString();
|
|
const endpoint = `/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/events${queryString ? `?${queryString}` : ""}`;
|
|
|
|
const response = await this.fetch(endpoint, { method: "GET" });
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
return (await response.json()) as GatewayListEventsResponse;
|
|
}
|
|
|
|
/**
|
|
* Creates an event in an autopilot session.
|
|
* Use session_id = "00000000-0000-0000-0000-000000000000" (nil UUID) to create a new session.
|
|
*/
|
|
async createAutopilotEvent(
|
|
sessionId: string,
|
|
request: CreateEventGatewayRequest,
|
|
): Promise<CreateEventResponse> {
|
|
const endpoint = `/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/events`;
|
|
const headers: Record<string, string> = {};
|
|
if (this.betaTools) {
|
|
headers["tensorzero-beta-tools"] = this.betaTools;
|
|
}
|
|
// Extra headers override betaTools on conflict
|
|
Object.assign(headers, this.extraHeaders);
|
|
const response = await this.fetch(endpoint, {
|
|
method: "POST",
|
|
body: JSON.stringify(request),
|
|
headers,
|
|
});
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
return (await response.json()) as CreateEventResponse;
|
|
}
|
|
|
|
/**
|
|
* Approves all pending tool calls for a session up to a specified event ID.
|
|
* This atomically approves all pending tool calls with event IDs <= last_tool_call_event_id.
|
|
*/
|
|
async approveAllToolCalls(
|
|
sessionId: string,
|
|
request: ApproveAllToolCallsGatewayRequest,
|
|
): Promise<ApproveAllToolCallsResponse> {
|
|
const endpoint = `/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/actions/approve_all`;
|
|
const response = await this.fetch(endpoint, {
|
|
method: "POST",
|
|
body: JSON.stringify(request),
|
|
});
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
return (await response.json()) as ApproveAllToolCallsResponse;
|
|
}
|
|
|
|
/**
|
|
* Streams events for an autopilot session using Server-Sent Events.
|
|
* Returns an async generator that yields GatewayStreamUpdate objects.
|
|
*/
|
|
async *streamAutopilotEvents(
|
|
sessionId: string,
|
|
params?: StreamEventsParams,
|
|
): AsyncGenerator<GatewayStreamUpdate, void, unknown> {
|
|
const url = buildGatewayUrl(
|
|
this.baseUrl,
|
|
`/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/events/stream`,
|
|
);
|
|
if (params?.last_event_id) {
|
|
url.searchParams.set("last_event_id", params.last_event_id);
|
|
}
|
|
|
|
const headers: Record<string, string> = {
|
|
Accept: "text/event-stream",
|
|
};
|
|
if (this.apiKey) {
|
|
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
|
}
|
|
|
|
const response = await fetch(url, { headers });
|
|
if (!response.ok) {
|
|
const message = await response.text();
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
|
|
const reader = response.body?.getReader();
|
|
if (!reader) {
|
|
throw new Error("Response body is not readable");
|
|
}
|
|
|
|
const decoder = new TextDecoder();
|
|
let buffer = "";
|
|
|
|
try {
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
|
|
buffer += decoder.decode(value, { stream: true });
|
|
const lines = buffer.split("\n");
|
|
buffer = lines.pop() || "";
|
|
|
|
for (const line of lines) {
|
|
if (line.startsWith("data: ")) {
|
|
const data = line.slice(6);
|
|
if (data) {
|
|
const event = JSON.parse(data) as GatewayStreamUpdate;
|
|
yield event;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Lists config writes (write_config tool calls) for a session.
|
|
*/
|
|
async listConfigWrites(
|
|
sessionId: string,
|
|
params?: ListConfigWritesParams,
|
|
): Promise<GatewayListConfigWritesResponse> {
|
|
const searchParams = new URLSearchParams();
|
|
if (params?.limit !== undefined) {
|
|
searchParams.set("limit", params.limit.toString());
|
|
}
|
|
if (params?.offset !== undefined) {
|
|
searchParams.set("offset", params.offset.toString());
|
|
}
|
|
const queryString = searchParams.toString();
|
|
const endpoint = `/internal/autopilot/v1/sessions/${encodeURIComponent(sessionId)}/config-writes${queryString ? `?${queryString}` : ""}`;
|
|
|
|
const response = await this.fetch(endpoint, { method: "GET" });
|
|
if (!response.ok) {
|
|
const message = await this.getErrorText(response);
|
|
this.handleHttpError({ message, response });
|
|
}
|
|
return (await response.json()) as GatewayListConfigWritesResponse;
|
|
}
|
|
}
|
|
|
|
const CONFIG_WRITES_PAGE_SIZE = 100;
|
|
|
|
/**
|
|
* Fetches all config writes for a session by paginating through results.
|
|
* Uses the N+1 pattern: requests `pageSize + 1` items to detect if more pages exist.
|
|
*/
|
|
export async function listAllConfigWrites(
|
|
client: Pick<AutopilotClient, "listConfigWrites">,
|
|
sessionId: string,
|
|
pageSize: number = CONFIG_WRITES_PAGE_SIZE,
|
|
): Promise<GatewayEvent[]> {
|
|
const allConfigWrites: GatewayEvent[] = [];
|
|
let offset = 0;
|
|
for (;;) {
|
|
const page = await client.listConfigWrites(sessionId, {
|
|
limit: pageSize + 1,
|
|
offset,
|
|
});
|
|
const hasMore = page.config_writes.length > pageSize;
|
|
const items = hasMore
|
|
? page.config_writes.slice(0, pageSize)
|
|
: page.config_writes;
|
|
allConfigWrites.push(...items);
|
|
if (!hasMore) break;
|
|
offset += pageSize;
|
|
}
|
|
return allConfigWrites;
|
|
}
|
|
|
|
/**
|
|
* Extracts the EditPayload from a config write event.
|
|
*
|
|
* Accepts `tool_call`, `tool_result`, and `tool_call_authorization` events
|
|
* because the superseding logic in EventStream may hide the original
|
|
* `tool_call` and render the button on the surviving event instead.
|
|
*
|
|
* @param event - A GatewayEvent that should be a write_config tool event
|
|
* @returns The EditPayload array from the event's arguments
|
|
* @throws Error if the event is not a write_config event or has no edit payload
|
|
*/
|
|
export function extractEditPayloadsFromConfigWrite(
|
|
event: GatewayEvent,
|
|
): EditPayload[] {
|
|
let args: WriteConfigToolParams;
|
|
|
|
if (event.payload.type === "tool_call") {
|
|
if (event.payload.name !== "write_config") {
|
|
throw new Error(
|
|
`Expected write_config tool call but got ${event.payload.name} for event ${event.id}`,
|
|
);
|
|
}
|
|
args = event.payload.arguments as unknown as WriteConfigToolParams;
|
|
} else if (
|
|
event.payload.type === "tool_result" ||
|
|
event.payload.type === "tool_call_authorization"
|
|
) {
|
|
if (event.payload.tool_call_name !== "write_config") {
|
|
throw new Error(
|
|
`Expected write_config tool event but got ${event.payload.tool_call_name} for event ${event.id}`,
|
|
);
|
|
}
|
|
args = event.payload
|
|
.tool_call_arguments as unknown as WriteConfigToolParams;
|
|
} else {
|
|
throw new Error(
|
|
`Expected tool_call, tool_result, or tool_call_authorization event but got ${event.payload.type} for event ${event.id}`,
|
|
);
|
|
}
|
|
|
|
if (!args.edit) {
|
|
throw new Error(
|
|
`Config write event ${event.id} does not have an edit payload. Args: ${JSON.stringify(args)}`,
|
|
);
|
|
}
|
|
|
|
return args.edit;
|
|
}
|