SSyncropel Docs

TypeScript SDK

Use Syncropel from JavaScript or TypeScript: add records, query threads, and keep your app running through network errors. Works in Node, Deno, Bun, edge runtimes and browsers.

Install

npm install @syncropel/sdk
# or: pnpm add / yarn add / bun add

Requires Node 18+ or any runtime with a global fetch. Zero native dependencies.

Hello, Syncropel

Start a workspace locally (spl serve), then:

import { Client, Identity, Ref } from "@syncropel/sdk";

const client = new Client({
  endpoint: "http://localhost:9100",
  identity: Identity.static("did:example:my-app"),
});

const result = await client.emit({
  act: "PUT",
  kind: "music.catalog.track",
  body: { title: "Glow", artists: ["Zonke"] },
  refs: [Ref.musicTrack({ isrc: "USJI19810404" })],
  thread: "th_library",
});

console.log(result.success, result.recordId);

One call validates the body.kind grammar, builds the record, retries on temporary server and network errors, and returns a result instead of throwing on network failures, so a flaky network never crashes your handler.

What you get

  • Universal runtime: Node, Deno, Bun, edge runtimes, browsers. Uses platform fetch.
  • Async client: emit, query, queryThread, intend, fulfill, plus reserved-kind helpers
  • Files: client.data.* reads and writes files (see Files & blobs)
  • Derived views & live threads: client.folds.resolve() reads computed views such as thread state and trust; client.threads.watch() streams a thread live
  • Kind checking: body.kind is validated before any network call
  • Shared references: 11 built-in constructors that let records from different apps point at the same thing
  • Reads that don't crash, errors that don't hide: record reads return an empty result on network trouble, so your UI keeps running; malformed requests and file writes throw, so a lost write is never mistaken for success
  • Identity-aware: records carry the configured DID
  • MockKernel: a fake workspace at @syncropel/sdk/testing for unit tests
  • Companion types: pair with @syncropel/projections when you work with rendered document formats

Core API

Client

MethodPurpose
emit(opts)Primary emit. Validates, retries on temporary errors, and returns an EmitResult. Never throws on network failures.
intend(opts)Open a thread with an INTEND record. Generates a thread ID if none supplied.
fulfill(opts)Close a thread with a KNOW record. fulfills accepts one record id or an array.
queryThread(opts)All records in a thread. Returns [] on a network error.
query(opts)Filtered records by kind, actor or thread. Returns an empty result on a network error.
health()Checks the server's health. Returns an empty result on a network error.
close()Does nothing (kept for compatibility).

Constructor options (ClientOptions):

new Client({
  endpoint?: string,              // default: http://localhost:9100
  identity: Identity,             // required
  timeoutMs?: number,             // per-request timeout
  maxRetries?: number,            // retries on temporary server or network errors
  backoffMs?: number,             // base backoff between retries
  onEmit?: (result) => void,      // observation hook (fires after every emit)
  apiKey?: string,                // bearer token for workspaces that require sign-in
  fetch?: typeof fetch,           // custom transport (use for testing)
});

Namespaces

Beyond the flat emit/query methods, the rest of the surface is grouped into namespaces on the client:

NamespaceWhat it covers
client.records.create(opts) (emit alias), .get(id), .richQuery({ filter, sort?, limit? }), a filtered query run on the workspace.
client.threads.list(), .records(id), .state(id), .project(id, format), and .watch(id), a live AsyncIterable of thread events (see below).
client.folds.resolve<V>(name, cacheKey?) reads any derived view (fold) through one typed method; .watermark(name, key) checks whether it changed without recomputing it.
client.dataFiles: write (with conflict detection), read, list, stat, publish, search. See Files & blobs.
client.namespaces.list(), .create({ id, description?, policy? }).
client.federation.peers(), .pair(peer), .sync(thread, peer?), .discoverPeers(), .mergeResults().
client.invitesissue / list / preview / redeem / revoke / audit invitations.
client.graph.query({ start, edges?, depth?, filter? }): graph queries over your workspace.
client.expr.eval({ expression, context, record? }): evaluate a CEL expression on the workspace.
client.decisions.pending(), .decide(id, { decision, reason? }): pending decisions, and approving, rejecting or answering them.

Reading derived views

The workspace computes views from a thread's (or the whole workspace's) records: the turn timeline, thread state, trust, and more. In the SDK these are called folds. Read any of them with one method:

// per-thread view: pass the thread ID as the cache key
const turns = await client.folds.resolve("turn", threadId);
render(turns.value);

// workspace-wide view: omit the cache key
const trust = await client.folds.resolve("trust");

// has the view changed since you last read it?
const wm = await client.folds.watermark("turn", threadId);

On a network error, resolve returns an empty view (watermark: -1, value: null).

Live thread streaming

client.threads.watch() returns an AsyncIterable over a thread's live events. It reconnects automatically and picks up where it left off, falls back to polling after repeated disconnects, and can be cancelled with an AbortSignal:

for await (const event of client.threads.watch(threadId)) {
  if (event.type === "record") render(event.record);
  // also: "scribe.delta", "connected", "disconnected"
}

Prefer watch(); the older callback-based client.subscribe(thread, cb) still works.

Identity

Identity.static("did:example:my-app")    // Supported
Identity.key(pathOrBytes)                 // Not supported; throws if called
Identity.federated(...)                   // Not supported; throws if called

Reserved-kind helpers

For records that correct, erase, rename or transfer earlier ones:

await client.emitCorrection({
  corrects: [recordId],
  revisedFields: { title: "Glow (Remastered)" },
  reason: "updated metadata",
  thread: "th_library",
});

await client.emitErasure({
  erases: [recordId],
  reason: "GDPR request",
  thread: "th_library",
});

await client.emitAlias({
  oldKind: "music.song",
  newKind: "music.catalog.track",
  reason: "grammar migration",
  thread: "th_library",
});

await client.emitScopeTransfer({
  scope: "music.catalog",
  fromPublisher: "did:web:old-label.example.com",
  toPublisher: "did:web:new-label.example.com",
  reason: "catalog transfer",
  thread: "th_library",
});

await client.emitScopeClaim({
  scope: "music.catalog",
  governancePolicy: { versioning: "semver" },
  thread: "th_library",
});

Canonical references (Ref)

References let records about the same real-world thing match up across apps:

Ref.musicTrack({ isrc: "USJI19810404" })            // → @music.track
Ref.codeFile({ repo: "acme/myproject",
               path: "src/main.rs" })               // → @code.file
Ref.opsIncident({ pagerduty: "ABC123" })            // → @ops.incident
Ref.calEvent({ uid: "abc@google.com" })             // → @cal.event
Ref.socialPerson({ email: "alice@example.com" })    // → @social.person
Ref.mediaPhoto({ sha256: "..." })                   // → @media.photo
Ref.mediaVideo({ youtube: "abc123" })               // → @media.video
Ref.docText({ doi: "10.1234/example" })             // → @doc.text
Ref.finTransaction({ stripe: "ch_abc123" })         // → @fin.transaction
Ref.researchPaper({ arxiv: "2401.12345" })          // → @research.paper
Ref.coreThread({ id: "th_abc123" })                 // → @core.thread

Types

type ActType = "GET" | "PUT" | "CALL" | "MAP" | "INTEND" | "DO" | "KNOW" | "LEARN";
type DataType = "SCALAR" | "FORMULA" | "DISTRIBUTION" | "REFERENCE" | "MORPHISM" | "VOID";

interface CanonicalRef { kind: string; id: string; }

interface EmitResult {
  success: boolean;
  recordId?: string;
  clock?: number;
  error?: string;
  retried: number;
  kind: string;
  act: string;
  thread: string;
}

Authenticating to a remote workspace

When the workspace requires sign-in, pass the token via apiKey:

const client = new Client({
  endpoint: "https://your-host.example.com:9100",
  identity: Identity.static("did:example:my-app"),
  apiKey: process.env.SPL_TOKEN,
});

The client sends Authorization: Bearer <token> on every outbound request. See Authentication & Service Accounts for how to mint the token.

Inference: client.infer()

client.infer() sends an inference request and, by default, waits for the answer. The full query anatomy lives in the Inference guide; this section covers the SDK.

import { Client } from "@syncropel/sdk";

const client = new Client({ endpoint: "http://localhost:9100" });

const result = await client.infer({
  input: { goal: "Summarise this paper in one paragraph" },
  responders: [
    { kind: "llm", model: "~sonnet" },
    { kind: "llm", model: "~gpt-4o" },
  ],
  fold: { function: "consensus", min_quorum: 2 },
  answer_shape: { kind: "core.summary.v1" },
  side_effects: { max_cost_usd: 0.30, max_latency_secs: 60 },
});

console.log(result.answer);
console.log(`Trust: ${result.trust_summary.mean.toFixed(2)}`);
console.log(`Cost: $${result.cost_actual_usd.toFixed(4)}`);

The InferRequest has the same fields as the query; fold sets how the answers from several responders are combined into one. TypeScript types for each part come from @syncropel/config:

import type {
  InferQueryV1,
  ResponderPredicate,
  Fold,
  Orchestration,
  SideEffects,
} from "@syncropel/config";

Fire-and-forget

Pass { wait: false } to send the request and return immediately:

const pending = await client.infer(request, { wait: false });
console.log(pending.correlation_id, pending.thread_id);

You get back InferPending = { pending: true; correlation_id: string; thread_id: string }. Check the thread yourself with client.threadRecords(pending.thread_id), or subscribe, to get the answer.

Options

await client.infer(request, {
  wait: true,                 // default
  poll_interval_ms: 500,      // default
  poll_timeout_ms: 300_000,   // default: 5 minutes
  thread: "th_abc123...",     // optional explicit thread
});

Result shape

interface InferResult {
  answer: unknown;
  provenance: Array<{
    responder_did: string;
    response_record_id: string;
    weight: number;
    match_level: "L0" | "L1" | "L2" | "L3" | null;
    trust_at_dispatch: number;
  }>;
  trust_summary: { mean: number; min: number; max: number; n_contributors: number };
  cost_actual_usd: number;
  fold_function: string;
  chosen_response_id?: string;
  know_record_id: string;
  thread_id: string;
}

Error handling

Unlike client.emit(), which never throws on network errors, client.infer() throws on failure:

  • Invalid request shape throws before any HTTP call.
  • A network or workspace error when sending the request throws.
  • Poll timeout throws TimeoutError.

Catch timeouts explicitly if you want to keep the thread ID and check it yourself.

Error model

The SDK handles failures in two ways:

  • Empty result: record reads (query, queryThread, richQuery, health, folds.resolve) return an empty result on a temporary failure (a briefly unavailable workspace, a 5xx, a sign-in blip), so a UI never crashes on backend trouble.
  • Thrown error: a mistake in your code or a write that must not be lost throws, so it can't be mistaken for an empty result:
ErrorThrown when
SyncropelKindErrorbody.kind breaks the naming rules; raised before any network call.
SyncropelQueryErrorA read is rejected as malformed (HTTP 4xx), e.g. a bad filter or sort. Carries .detail.
SyncropelDataErrorA client.data.* operation fails: a quota, a permission denial, or a write conflict (.isConflict).
import { SyncropelQueryError } from "@syncropel/sdk";

try {
  const { records } = await client.richQuery({ filter: { thread }, sort: { clock: -1 } });
} catch (e) {
  if (e instanceof SyncropelQueryError) {
    // the request was malformed (4xx): fix the filter or sort, don't treat it as "empty"
  }
}

Malformed queries throw. richQuery / query / queryThread throw SyncropelQueryError on a malformed 4xx rather than returning an empty result. Valid queries are unaffected; wrap any call that might send a malformed filter/sort in a try/catch. The usual fix is the object form of sort, { clock: -1 } (not a string).

Testing without a workspace

Use MockKernel to write unit tests without running spl serve:

import { Client, Identity, Ref } from "@syncropel/sdk";
import { MockKernel } from "@syncropel/sdk/testing";

test("my adapter emits a track", async () => {
  const kernel = new MockKernel();
  const client = new Client({
    endpoint: "http://mock",
    identity: Identity.static("did:example:test"),
    fetch: kernel.fetch,
  });

  await myAdapter(client);

  const tracks = kernel.recordsByKind("music.catalog.track");
  expect(tracks).toHaveLength(1);
  expect(tracks[0].body.title).toBe("Glow");
});

Useful MockKernel helpers: recordsIn(thread), recordsByKind(kind), recordsByActor(did), count(), clear(), failNextPostCall(n), failNextGetCall(n) (for testing network failures).

Running on edge runtimes

Because the SDK uses global fetch, it runs unmodified on edge runtimes. If you use the runtime's environment bindings, pass them explicitly:

export default {
  async fetch(request: Request, env: Env) {
    const client = new Client({
      endpoint: env.SYNCROPEL_ENDPOINT,
      identity: Identity.static(env.APP_DID),
      apiKey: env.SPL_TOKEN,
    });

    await client.emit({
      act: "KNOW",
      kind: "ops.request.observed",
      body: { path: new URL(request.url).pathname },
      thread: "th_ops",
    });

    return new Response("ok");
  },
};

What's next

On this page