SynaptraDocs

    Reference

    TypeScript SDK

    npm install synaptra-sdk: the same client for TypeScript and JavaScript. No runtime dependencies (global fetch and Web Crypto), so it runs on Node 18+, Bun, Deno, Cloudflare Workers and in browsers.

    #

    Install and connect

    Terminal
    npm install synaptra-sdk
    export SYNAPTRA_TOKEN=syn_...   # from Connect → API tokens
    connect.ts
    import { Harness } from "synaptra-sdk";
    
    const h = await Harness.create({ name: "Support bot", metric: "accuracy", bar: 0.8 });
    // or: const h = await Harness.connect("support-bot");
    console.log(h.id, await h.nextStep);

    url falls back to SYNAPTRA_URL (default https://synaptra.my; a trailing /api is fine) and token to SYNAPTRA_TOKEN. In a Worker or a browser there are no environment variables: pass { url, token }. Plain http is refused except to localhost (set SYNAPTRA_ALLOW_HTTP=1 for a private network), and redirects are never followed. The package is an ES module: import, not require. Types ship with it.

    #

    Where it runs

    RuntimeSupportedWhen Synaptra can't be reached
    Node 18+yesLive-run records and spend wait in files under ~/.synaptra/buffer (or SYNAPTRA_BUFFER_DIR), private to the user.
    BunyesFiles, as on Node.
    DenoyesMemory, shared by the runs and meters of the process. Call flush() before it ends.
    Cloudflare WorkersyesMemory, per isolate. Call flush() inside ctx.waitUntil before the request ends.
    BrowsersyesMemory, per page. Call flush() before the page closes.

    What's still in memory when the process, isolate or page ends is lost. Filesystem features (logPath, bufferDir, flush({ path }), fingerprinting a local dataset file) need Node or Bun. Pass bufferDir: false to use memory on Node too.

    worker.ts
    import { flush, track } from "synaptra-sdk";
    
    export default {
      async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
        const opts = { url: "https://synaptra.my", token: env.SYNAPTRA_TOKEN };
        const run = await track.init({ ...opts, harnessId: "support-bot", name: "edge eval" });
        run.log({ latency_ms: 42 }, { step: 0 });
        await run.finish();
        ctx.waitUntil(flush(opts));          // sends anything that couldn't go during the request
        return new Response("ok");
      },
    };
    #

    Harness

    CallDoes
    Harness.create({ name, description?, objective?, metric?, direction?, bar?, template?, id?, maxCostUsd?, url?, token? })A new harness from the Synaptra base harness. direction: "max" (default) or "min"; template: harness, llm_agent or pipeline.
    Harness.connect(id, { url?, token? })An existing harness.
    h.id, h.dataIts id, and the data Synaptra last answered.
    await h.refresh()Reads the harness again; returns its data.
    await h.readinessThe readiness checklist, read fresh.
    await h.nextStepWhat to do next, in a sentence, read fresh.
    await h.tools({ includeRemoved? })The registered tools and hooks.
    await h.versions()Every version, each with its spec (every page).
    await h.export()The harness as portable JSON (synaptra.harness/1).
    await h.setStatus("parked" | "active")Parks the harness or makes it active again.
    #

    Registering

    CallDoes
    h.tool({ name?, description?, schema?, toJSONSchema?, config? }, fn?)Registers an action tool. name defaults to the function's name; schema is a JSON Schema or a Zod schema.
    h.scorer({ name?, description?, schema?, config? }, fn?)Registers the scorer: what turns one output into the metric. It runs on your side.
    h.dataset(name = "test_set", { path?, items?, content?, size?, hash?, description?, config? })Registers the test set: its location, size and SHA-256 fingerprint, never its contents. A local path on Node or Bun is fingerprinted too (bytes, and lines for .jsonl). The fingerprint of items matches the Python client's for the same items.
    h.runner(cmd, { name?, description?, config? })Registers the run command, with {variant}, {tier}, {task} placeholders. Recorded, never run.
    h.register({ name, kind, description?, schema?, config? })Registers anything: kind action, scorer, dataset or runner.
    h.removeTool(toolId)Soft-removes a tool: it stays on record.

    TypeScript types don't exist at runtime, so a tool's arguments are described by a schema you pass: JSON Schema, or Zod. Zod 4 schemas convert themselves and .describe() becomes the description; for Zod 3 add toJSONSchema: zodToJsonSchema. Zod isn't a dependency of the client.

    register.ts
    await h.tool(
      {
        name: "kb_search",
        description: "Search the help centre and return the top k articles.",
        schema: {
          type: "object",
          properties: { query: { type: "string" }, k: { type: "integer", default: 5 } },
          required: ["query"],
        },
      },
      kbSearch,
    );
    
    // The same with Zod 4
    import { z } from "zod";
    await h.tool(
      { name: "kb_search", schema: z.object({ query: z.string(), k: z.number().int().default(5) })
                                    .describe("Search the help centre and return the top k articles.") },
      kbSearch,
    );
    
    await h.scorer({ name: "exact" }, ({ output, expected }) => Number(output.trim() === expected.trim()));
    await h.dataset("golden", { items: goldenRows });      // sends size + fingerprint only
    await h.runner("node eval.js --variant {variant} --tier {tier}");
    #

    The loop

    CallDoes
    h.propose({ title, variant, hypothesis, predictions, treatmentAxes?, maxCostUsd?, idempotencyKey? })Opens an experiment with the numbers you expect per tier, before anything runs. hypothesis is required. Returns the experiment (e.id).
    h.gate({ variant, tier, nRuns?, experimentId? })May variant run on tier now? allowed, reasons, warnings, estimated_cost_usd, passes_own_gate, budget. A refusal is an answer, not an error.
    h.report(rows, { experimentId?, variant?, tier?, idempotencyKey?, batchSize? })Sends rows in batches of 250, each with its own Idempotency-Key. See Reporting runs.
    h.close({ experimentId, decision, note, variant?, overrideReason?, idempotencyKey? })adopt, iterate, reject or kill, with a note saying why (required). Returns { experiment, harnessVersion } (the new version on adopt, else null). Throws GateRefused when the adopted variant fails its gate.
    loop.ts
    const e = await h.propose({
      title: "Search before answering",
      variant: "search-first",
      hypothesis: "Replies miss policy details the help centre has",
      predictions: { T0: { pass_rate: 1.0 }, T1: { mean_resolved: 0.78 } },
      maxCostUsd: 5,
    });
    const gate = await h.gate({ variant: "search-first", tier: "T1", nRuns: 60, experimentId: e.id });
    if (gate.allowed)
      await h.report(await runT1("search-first"), { experimentId: e.id, variant: "search-first", tier: "T1" });
    const { harnessVersion } = await h.close({
      experimentId: e.id,
      decision: "adopt",
      note: "Beat the incumbent on the dev set and the held-out test set",
    });
    console.log(harnessVersion);
    #

    Reporting runs

    A row is { task, metrics, variant?, tier?, cost_usd?, seconds?, status?, meta? }: the API's own field names, so cost_usd and seconds keep their underscores and units. metrics must include the harness's metric; status is ok, invalid (the harness broke: not a fail) or provisional; meta.axes tags draws. The client adds the host, the runtime and its version to meta.

    report.ts
    const rows = results.map((t) => ({
      task: t.id, metrics: { accuracy: score(t) }, cost_usd: t.cost, seconds: t.ms / 1000,
      meta: { axes: { seed } },
    }));
    await h.report(rows, { experimentId: 42, variant: "prompt-v2", tier: "T1",
                           idempotencyKey: `exp42-prompt-v2-T1-seed${seed}` });
    • Batching. Rows go 250 per request (REPORT_BATCH; the API takes at most 5,000). With one batch you get the API's answer as is; with several, { batches: [...] }.
    • Idempotency. Every write (POST, PATCH, DELETE) carries an Idempotency-Key that stays the same across the client's retries. Pass idempotencyKey to make a report safe to retry from another process too: batch n of several uses <key>-<n>. The same key with different rows is 409 CONFLICT.
    • Units. Options that are durations are in milliseconds (timeoutMs, pushEveryMs, syncEveryMs, maxWaitMs); the one exception, stallAfterS, says seconds in its name. Rows keep the API's seconds.
    #

    Live runs and metering

    train.ts
    import { track, Meter } from "synaptra-sdk";
    
    await using run = await track.init({ harnessId: "support-bot", name: "prompt-v2 T1", experimentId: 42,
                                         alerts: [{ metric: "loss", rises_for: 5, stop: true }] });
    await using m = await Meter.open({ experimentId: 42 });   // cap = the experiment's max_cost_usd
    for (const [step, batch] of batches.entries()) {
      m.allow(0.02);                        // refuse a call that would cross the cap
      const loss = await trainStep(batch);
      m.charge(0.018, { item: "step" });
      run.log({ loss }, { step });
      if (run.shouldStop()) break;
    }
    CallDoes
    track.init({ harnessId?, name?, experimentId?, variant?, tier?, config?, alerts?, goal?, capUsd?, logPath?, bufferDir?, offline?, pushEveryMs?, pushTimeoutMs?, stallAfterS?, url?, token? })Starts a live run. Records go every pushEveryMs (5,000). capUsd: a logged cumulative cost_usd above it stops the run. logPath (Node and Bun) also writes every record to a JSONL file.
    run.log(values, { step? })Logs metrics; never waits for the network. Returns the alert messages that fired.
    run.shouldStop(), run.stopReasonTrue once a stop rule fired (NaN, the cost cap, a rule with stop: true) or someone asked the run to stop.
    await run.sync()Sends what's waiting now and returns shouldStop().
    await run.finish(status = "finished", summary?)Ends the run (await using does it for you). Mark a failure with run.finish("failed", { error: String(e) }).
    track.stop(runId, reason)Asks a live run to stop. reason is required.
    Meter.open({ experimentId, capUsd?, prices?, spentBefore?, note?, logPath?, sync?, syncEveryMs?, bufferDir? })A meter whose cap is known: the experiment's max_cost_usd unless you pass capUsd (needed with sync: false).
    m.allow(estUsd)Throws BudgetExceeded if a call costing about that would cross the cap: the hard stop.
    m.charge(usd, { item?, model? }), m.chargeTokens(model, tokensIn, tokensOut, { item?, prices? })Records money spent; throws BudgetExceeded once the total crosses the cap. m.spent, m.remaining.
    await m.close(stopped?)Sends the final total (await using does it for you).
    flush({ url?, token?, path?, bufferDir? })Sends what was buffered while Synaptra couldn't be reached → { sent, kept, errors }.

    Alert rules: { metric, above }, { metric, below }, { metric, rises_for: n }, { metric, falls_for: n }, { metric, flat_for: n, tol }, with optional after_step and stop: true. camelCase spellings (risesFor, afterStep) work too. Report metered runs afterwards with cost_usd 0: the meter already counted the money.

    #

    Client options

    Every call that makes a client (Harness.create, Harness.connect, track.init, Meter.open, flush) takes these too:

    OptionDefaultMeaning
    urlSYNAPTRA_URL, then https://synaptra.myThe site.
    tokenSYNAPTRA_TOKENAn API token.
    timeoutMs30000Per attempt.
    retries4Retries on 429, 5xx and network errors.
    backoffMs500The first backoff; it doubles each retry, plus jitter.
    maxWaitMs60000The longest wait before a retry; a longer Retry-After isn't slept.
    fetchglobal fetchYour own fetch, e.g. for a proxy.
    loggernone{ debug?, info? }: the token never reaches it.
    #

    Required fields

    Three things are refused before anything is sent (TypeError), because the record is worthless without them: a hypothesis on propose, a note on close, and a reason on track.stop.

    #

    Errors

    Calls throw SynaptraError or a subclass, with status, code, the API's plain-language detail, and the error body (a quota's limit and used). Branch on the class and show detail to people.

    ClassStatus and codeWhen
    BadRequestError400 BAD_REQUESTThe body or a parameter is wrong. Fix the request.
    AuthError401 UNAUTHORIZED, 403 FORBIDDENNo token, or a revoked or wrong one.
    NotFoundError404 NOT_FOUNDNo such harness, experiment or run in this workspace.
    GateRefused (a ConflictError)409 GATEThe adopted variant fails its gate; detail gives the reasons.
    ConflictError409 CONFLICTIt exists already, or an Idempotency-Key was reused with a different body.
    QuotaError429 QUOTAA quota is full. retryAfter (seconds) is set only when waiting helps, e.g. the daily run quota.
    RateLimitError (a QuotaError)429 RATE_LIMITEDToo many requests this minute, still refused after the retries.
    ServerError5xx INTERNALSomething broke on our side, still failing after the retries.
    ConnectionError (also exported as SynaptraConnectionError)none (status is null)Synaptra couldn't be reached: DNS, refused, timeout, TLS, or a redirect.
    errors.ts
    import { GateRefused, QuotaError } from "synaptra-sdk";
    
    try {
      await h.close({ experimentId: e.id, decision: "adopt", note: "Beat the bar on T1" });
    } catch (err) {
      if (err instanceof GateRefused) console.log("Not adopted:", err.detail);
      else if (err instanceof QuotaError) console.log("Quota full:", err.detail, err.retryAfter);
      else throw err;
    }

    Rate limits (429 RATE_LIMITED), server errors and network errors are retried first, with backoff, honouring Retry-After and keeping the same Idempotency-Key, so a retried write never counts twice. The error is raised only when the retries run out. A 429 QUOTA is raised at once unless its Retry-After is within the client's longest wait (60 seconds): a per-day quota frees up at midnight UTC, which is your call, not a sleep inside a request. The token is never logged or put in an error message. See Errors and rate limits.

    Something unclear or missing? Email support@synaptra.my.