Back to docs

Thread and Workflows

title: Thread and Workflows

--- title: Thread and Workflows description: Thread engine and durable workflow integration. ---

Thread and Workflows

This section documents the thread engine in @ekairos/thread and how it integrates with workflows.

Thread definition

A thread defines context + model + tools + options. It is registered into the thread engine.

import { createThread } from "@ekairos/thread";
import { tool } from "ai";
import { z } from "zod";

const myThread = createThread("platform:example")
  .context(async (stored) => stored?.content ?? {})
  .system(() => "You are an assistant...")
  .tools(async () => ({
    updateEntity: tool({
      description: "Updates a domain entity",
      inputSchema: z.object({
        id: z.string(),
        title: z.string().optional(),
      }),
      execute: async ({ id, title }) => ({ ok: true, id, title }),
    }),
  }))
  .model("openai/gpt-5.1-thinking")
  .build();

Thread runner and workflows

Threads are executed by the workflow runner using the "use workflow" directive.

import { getWritable } from "workflow";
import { myThread } from "@/threads/example";

export async function exampleWorkflow(params: {
  triggerEvent: any;
  env: { orgId: string };
  contextId?: string;
}) {
  "use workflow";
  const writable = getWritable();
  return await myThread.react(params.triggerEvent, {
    env: params.env,
    context: params.contextId ? { id: params.contextId } : null,
    options: { writable },
  });
}

Runtime configuration

The runtime binds threads to database access and org context. This is configured in a bootstrap module.

import { configureRuntime } from "@ekairos/domain/runtime";
import { getOrgAdminDb } from "@/lib/admin-org-db";
import { buildMyThread } from "@/lib/domain/my-thread";
import { appDomain } from "@/lib/domain";

export const runtimeConfig = configureRuntime({
  domain: { domain: appDomain },
  runtime: async (env) => {
    const orgId = String(env.orgId ?? "");
    return await getOrgAdminDb(orgId);
  },
  threads: [buildMyThread()],
});

Execution model

  • A workflow run is durable.
  • Tool actions are executed step by step.
  • Thread state and events are stored in InstantDB.

Key packages and files

  • packages/thread/src/thread.ts
  • packages/thread/src/thread.engine.ts
  • packages/thread/src/thread.builder.ts
  • packages/thread/src/schema.ts
  • packages/thread/src/runtime.ts