import { createHash } from "node:crypto"
import { once } from "node:events"
import type { IncomingMessage, ServerResponse } from "node:http"
import Checkfu from "@checkfu/sdk"
import type { JsonSessionEvent } from "@checkfu/sdk"
import * as Effect from "effect/Effect"
export async function relaySession(
client: Pick<Checkfu, "sessions">,
request: IncomingMessage,
response: ServerResponse,
sessionId: string,
) {
const last = request.headers["last-event-id"]
const cursor = typeof last === "string" && /^\d+$/.test(last) ? Number(last) : NaN
const after = Number.isSafeInteger(cursor) ? cursor : undefined
const controller = new AbortController()
const cancel = () => controller.abort()
response.once("close", cancel)
try {
if (response.destroyed) return
const opened: { status?: 200 | 204 } = {}
const events = await client.sessions.events.stream(
sessionId,
{ after },
{
signal: controller.signal,
onOpen: (status) =>
Effect.sync(() => {
opened.status = status
}),
},
)
if (response.destroyed || controller.signal.aborted) return
if (opened.status === 204) {
response.writeHead(204).end()
return
}
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" })
response.flushHeaders()
for await (const event of events) {
const frame = `id: ${event.seq}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`
if (!response.write(frame)) await once(response, "drain", { signal: controller.signal })
}
response.end()
} catch (error) {
if (controller.signal.aborted) return
if (!response.headersSent) throw error
console.error("Session relay ended", sessionId, error)
response.end()
} finally {
response.off("close", cancel)
controller.abort()
}
}
type CustomCall = Extract<JsonSessionEvent, { type: "agent.custom_tool_use" }>
type Pause = Extract<JsonSessionEvent, { type: "session.status_idle" }>
const MAX_TOOL_RESULT_LENGTH = 16_384
export const isRejectedToolRequest = (error: unknown) =>
error instanceof Checkfu.BadRequestError || error instanceof Checkfu.PayloadTooLargeError
export type ToolResult = {
id: string
type: "user.custom_tool_result"
custom_tool_use_id: string
content: [{ type: "text"; text: string }]
is_error: boolean
}
type Results = {
read: (key: string) => Promise<ToolResult | undefined>
write: (key: string, result: ToolResult) => Promise<void>
}
export function createToolProcessor(
client: Pick<Checkfu, "baseUrl" | "sessions">,
tools: Record<string, (input: Record<string, unknown>) => Promise<unknown>>,
results: Results,
) {
const stillWaiting = async (sessionId: string, pause: Pause, callId: string) => {
const session = await client.sessions.retrieve(sessionId)
if (session.status !== "idle" || session.archived_at !== null) return false
for await (const event of client.sessions.events.list(sessionId, {
order: "desc",
types: ["session.status_idle", "user.custom_tool_result"],
})) {
if (event.type === "user.custom_tool_result" && event.custom_tool_use_id === callId)
return false
if (event.type === "session.status_idle") return event.seq === pause.seq
}
return false
}
const findCall = async (sessionId: string, id: string) => {
for await (const event of client.sessions.events.list(sessionId, {
order: "desc",
types: ["agent.custom_tool_use", "agent.mcp_tool_use"],
})) {
if (event.id === id) {
return event.type === "agent.custom_tool_use" ? event : undefined
}
}
}
const answer = async (sessionId: string, pause: Pause, call: CustomCall) => {
if (!(await stillWaiting(sessionId, pause, call.id))) return
const key = createHash("sha256")
.update(JSON.stringify([client.baseUrl, sessionId, call.id]))
.digest("hex")
let result = await results.read(key)
if (result === undefined) {
const evaluate = async (): Promise<readonly [string, boolean]> => {
const run = Object.hasOwn(tools, call.name) ? tools[call.name] : undefined
if (run === undefined) throw new Error("Unknown application tool")
const text = JSON.stringify(await run(call.input)) ?? "null"
if (text.length > MAX_TOOL_RESULT_LENGTH) {
return ["Application tool result exceeds the text limit.", true]
}
return [text, false]
}
const [text, isError] = await evaluate().catch(
() => ["Application tool failed.", true] as const,
)
result = {
id: "result-" + key,
type: "user.custom_tool_result",
custom_tool_use_id: call.id,
content: [{ type: "text", text }],
is_error: isError,
}
await results.write(key, result)
}
try {
await client.sessions.events.send(sessionId, { events: [result] })
} catch (error) {
if (isRejectedToolRequest(error) || (await stillWaiting(sessionId, pause, call.id)))
throw error
}
}
return async (sessionId: string, event: JsonSessionEvent) => {
if (event.type !== "session.status_idle" || event.stop_reason.type !== "requires_action") return
for (const id of event.stop_reason.event_ids) {
const call = await findCall(sessionId, id)
if (call !== undefined) await answer(sessionId, event, call)
}
}
}