> For the complete documentation index, see [llms.txt](https://seekspeed.gitbook.io/seekspeed-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://seekspeed.gitbook.io/seekspeed-docs/architecture/server-functions.md).

# Server Functions

All backend work is expressed as `createServerFn` modules. Each module exports typed RPCs the client invokes via `useServerFn`. Secrets (`process.env.*`, connector API keys read from the DB) are touched only inside `.handler()` bodies.

## Anatomy

```ts
// src/lib/benchmark.functions.ts (canonical shape)
import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";

const Input = z.object({
  connectorId: z.string().uuid(),
  prompt: z.string(),
  maxTokens: z.number().int().min(1).max(8192).default(512),
  stream: z.boolean().default(true),
});

export const runBenchmarkOnce = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator((d) => Input.parse(d))
  .handler(async ({ data, context }) => {
    const { data: connector } = await context.supabase
      .from("connectors")
      .select("base_url, api_key, model, headers")
      .eq("id", data.connectorId)
      .single();

    return runWithSseTtft({
      baseUrl: connector.base_url,
      apiKey:  connector.api_key,
      model:   connector.model,
      headers: connector.headers,
      prompt:  data.prompt,
      maxTokens: data.maxTokens,
      stream:  data.stream,
    });
  });
```

## SSE → TTFT

For streamed endpoints, we measure the time from request send to the first non-empty `data: {...}` chunk that carries a token. That's the actual "user hears a syllable" latency, not the round-trip total.

```ts
const t0 = performance.now();
const res = await fetch(url, { method: "POST", headers, body });
const reader = res.body!.getReader();
const dec = new TextDecoder();
let ttft = 0, buf = "";

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buf += dec.decode(value, { stream: true });

  for (const line of buf.split("\n")) {
    if (!line.startsWith("data:")) continue;
    const payload = line.slice(5).trim();
    if (payload === "[DONE]") continue;
    try {
      const json = JSON.parse(payload);
      const delta = json.choices?.[0]?.delta?.content;
      if (delta && !ttft) { ttft = performance.now() - t0; }
    } catch { /* partial chunk */ }
  }
}
```

## Catalog

| Module                        | What it does                                                                      |
| ----------------------------- | --------------------------------------------------------------------------------- |
| `benchmark.functions.ts`      | Run one prompt, capture TTFT/total/tokens; orchestrates iterations + concurrency. |
| `connector-test.functions.ts` | One-shot 1-token request to verify an endpoint before save.                       |
| `spec-lab.functions.ts`       | Probes vLLM `/metrics`, TGI `/info`, llama.cpp `/props`; runs A/B vs baseline.    |
| `solana-auth.functions.ts`    | Verifies `tweetnacl` signature, mints a Supabase session via deterministic email. |
| `report-share.functions.ts`   | Issues a `share_token` and validates the `x-share-token` header on public reads.  |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://seekspeed.gitbook.io/seekspeed-docs/architecture/server-functions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
