### View events for the quickstart thread Source: https://tardigrade.sh/docs/quickstart Shows the events for the 'quickstart' thread created in this guide. ```bash tdg events quickstart ``` -------------------------------- ### Setup provider and default model Source: https://tardigrade.sh/docs/cli Configure the first connection and default model within an existing actor directory. ```bash tdg setup provider openai '{"env":["OPENAI_API_KEY"]}' tdg setup default --provider openai --model gpt-5.2 ``` -------------------------------- ### Setup custom provider Source: https://tardigrade.sh/docs/cli Configure a custom provider by specifying its endpoint and protocol. ```bash tdg setup provider private-gateway '{"baseUrl":"https://models.example.com/v1","protocol":"openai-responses","env":["PRIVATE_MODEL_KEY"]}' ``` -------------------------------- ### Install tardie with bun Source: https://tardigrade.sh/docs/sdk Installs the Tardigrade SDK package using the Bun package manager. ```bash bun add tardie ``` -------------------------------- ### Deploy to Cloudflare Source: https://tardigrade.sh/docs/quickstart Deploys the agent to Cloudflare. Requires following the Cloudflare setup guide first to create the catalog database, apply migration, and set secrets. ```bash bun run deploy:cloudflare ``` -------------------------------- ### Install Tardie CLI with Bun Source: https://tardigrade.sh/docs/quickstart Installs the Tardie CLI globally using Bun. Requires Bun 1.4 or above. ```bash bun add -g tardie@latest ``` -------------------------------- ### Create a thread and send a message Source: https://tardigrade.sh/docs/quickstart Creates a root thread named 'quickstart' and sends a message asking about the weather in Singapore. The thread ID is printed by the creation command. ```bash tdg thread create --name quickstart tdg call message '{"text":"What is the weather in Singapore?"}' --thread quickstart ``` -------------------------------- ### Install Wrangler Source: https://tardigrade.sh/docs/platforms/cloudflare Installs the latest Wrangler CLI as a dev dependency. Use a release that supports the compatibility_date in wrangler.jsonc. ```bash bun add --dev wrangler@latest ``` -------------------------------- ### Initialize Tardie Agent Project with tdg init Source: https://tardigrade.sh/docs/quickstart Creates a new tardie-agent directory with the quickstart template and configures a language model provider. Generates files including actor.ts, server.ts, worker.ts, wrangler.jsonc, celld.jsonc, models.lock.json, migrations/0001_catalog.sql, and package.json. ```bash tdg init tardie-agent --template quickstart ``` -------------------------------- ### Apply local migration and start Worker Source: https://tardigrade.sh/docs/platforms/cloudflare Applies the local catalog migration and starts the Worker locally. Requires TARDIGRADE_TOKEN and provider credentials in .dev.vars. ```bash bunx wrangler d1 migrations apply CATALOG_DB --local bun run dev:cloudflare ``` -------------------------------- ### Install esbuild for Bun Source: https://tardigrade.sh/docs/platforms/celld Installs esbuild as a dev dependency for a Bun project, required for bundling before deploying to Celld. ```bash bun add --dev esbuild ``` -------------------------------- ### Example file layout for Rick's instance and threads Source: https://tardigrade.sh/docs/actors Text diagram showing the resulting file layout under /data for Rick's instance. The instance database is named with the base64url encoding of ["meeseeks","rick"], and the thread databases are stored in a .threads directory with base64url-encoded thread names (bWFpbg for main, bGFi for lab). ```text /data/ ├── WyJtZWVzZWVrcyIsInJpY2siXQ.sqlite # Rick's instance database └── WyJtZWVzZWVrcyIsInJpY2siXQ.sqlite.threads/ ├── bWFpbg.sqlite # main └── bGFi.sqlite # lab ``` -------------------------------- ### Setup Amazon Bedrock provider Source: https://tardigrade.sh/docs/cli Configure the Amazon Bedrock provider by providing the gateway endpoint, AWS region, and environment variables. ```bash tdg setup provider amazon-bedrock '{"baseUrl":"https://gateway.example.com/bedrock","region":"ap-southeast-1","env":["CLOUDFLARE_API_TOKEN"]}' ``` -------------------------------- ### Serve host over HTTP with tardie/bun serve Source: https://tardigrade.sh/docs/actors Expose the host to other processes by starting an HTTP server. The host continues to own execution and storage; the server provides network access. Stop it with await server.close() before closing the host. ```ts import { serve } from "tardie/bun" const server = await serve(host, { port: 4242 }) ``` -------------------------------- ### Complete actor host example with defineActor and createBunHost Source: https://tardigrade.sh/docs/actors Defines an actor named 'meeseeks' with a message method and layers, creates a Bun host with storage './data', allocates four root threads (rick/main, rick/lab, morty/main, morty/lab), invokes the message method on two threads, logs responses, and closes the host in a finally block. Requires the imported components, methods, and packages from the application. ```TypeScript import { defineActor } from "tardie/core" import { createBunHost } from "tardie/bun" import { layersFor } from "./layers" import { infer, codeMode } from "./components" import { message } from "./methods" import { mcpPackage } from "./packages" const meeseeks = defineActor( "meeseeks", { message }, [infer, codeMode(mcpPackage)], ) const host = await createBunHost({ actor: meeseeks, storage: "./data", layersFor, }) try { const rickMain = await host.allocateRootThread({ instance: "rick", name: "main" }) const rickLab = await host.allocateRootThread({ instance: "rick", name: "lab" }) const mortyMain = await host.allocateRootThread({ instance: "morty", name: "main" }) const mortyLab = await host.allocateRootThread({ instance: "morty", name: "lab" }) const rickResponse = await rickLab.methods.message({ text: "Design an experiment to test the portal gun's power source.", }, { key: "portal-experiment" }) const mortyResponse = await mortyMain.methods.message({ text: "Help me plan my day around school and homework.", }, { key: "school-plan" }) console.log({ rickResponse, mortyResponse }) } finally { await host.close() } ``` -------------------------------- ### Run Bun development server Source: https://tardigrade.sh/docs/platforms/bun Starts the generated Bun server that mounts actor.ts and serves its API. Loads .dev.vars, watches TypeScript sources, restarts on edits, listens on port 4242 by default, and exposes /healthz. ```bash bun run dev ``` -------------------------------- ### Creating a counter component Source: https://tardigrade.sh/docs/concepts Example of using the component helper from tardie/core to define a counter that increments on Counted events. ```typescript import { component } from "tardie/core" const counter = component({ name: "counter", initial: () => 0, step: (count, event) => event.type === "Counted" ? count + 1 : count, output: (count) => ({ view: count, transitions: [] }) }) ``` -------------------------------- ### Component with transition context Source: https://tardigrade.sh/docs/concepts Example component that acknowledges a request. It uses the transition context to declare work via context.intent, and returns the pending work in its output. The component retains the owning context until completion. ```TypeScript import { component } from "tardie/core" import type { TransitionContext } from "tardie/core/component" import type { Transition } from "tardie/core/transition" type Pending = { context: TransitionContext work: Transition } const acknowledge = component({ name: "acknowledge", initial: () => undefined, step: (pending, event, context) => { if (event.type === "Requested") { return { context, work: context.intent("ack", { type: "Acknowledged" }) } } return pending?.context.matches("ack", event) ? undefined : pending }, output: (pending) => ({ view: undefined, transitions: pending === undefined ? [] : [pending.work] }) }) ``` -------------------------------- ### Compose an RLM agent with Tardigrade Source: https://tardigrade.sh/docs/examples/rlm Composes a recursive language model agent with Tardigrade. The budget component records its starting allowance as BudgetGranted before inference; set { limit: 20, authority: caller() } to start with 20 tool calls (default is DEFAULT_BUDGET_POLICY.limit, which is 40). Each tool call uses only the grants recorded before it, so a later grant cannot admit an earlier refused call, and restarting with a different default leaves a recorded allowance unchanged. ```ts import { actor } from "tardie/core" import { agentMethods, agentsPackage, budget, budgetAuthority, caller, codeMode, compaction, infer, outputValidateOnce, system } from "tardie/agent" import { fetchPackage, workspacePackage } from "tardie/code" const instructions = system( "Investigate with code and delegate independent work." ) const rlm = actor({ name: "researcher", methods: agentMethods, components: [ infer([ instructions, budget([ codeMode([ fetchPackage(), agentsPackage(), workspacePackage() ]) ], { authority: caller() }), compaction(), outputValidateOnce ]), budgetAuthority() ] }) ``` -------------------------------- ### Define an actor with defineActor Source: https://tardigrade.sh/docs/actors Example of defining an actor named 'meeseeks' that exposes a message method and uses components for inference and code execution with an MCP package. The './components', './methods', './packages', and './layers' modules belong to your application. ```ts import { defineActor } from "tardie/core" import { infer, codeMode } from "./components" import { message } from "./methods" import { mcpPackage } from "./packages" const meeseeks = defineActor( "meeseeks", { message }, [infer, codeMode(mcpPackage)], ) ``` -------------------------------- ### curl POST to invoke actor method over HTTP Source: https://tardigrade.sh/docs/actors Call Rick's main thread from another process using curl. The Idempotency-Key header makes retries reuse the same call. The server returns 202 Accepted with a receipt and a Location header; poll that location with GET until state is completed, failed, or cancelled. ```sh curl -X POST 'http://localhost:4242/v1/actors/rick/threads/main/methods/message' \ -H 'Content-Type: application/json' \ -H 'Idempotency-Key: portal-code' \ -d '{"text":"What is the portal code?"}' ``` -------------------------------- ### Initialize project interactively Source: https://tardigrade.sh/docs/cli Run interactive initialization to create a directory, choose the first provider and model, and write the generated actor. ```bash tdg init tardie-agent --template quickstart cd tardie-agent bun run dev ``` -------------------------------- ### Initialize project with custom model Source: https://tardigrade.sh/docs/cli Creates a project with a custom model by including 'models' in the provider configuration. The command sets the provider protocol, base URL, environment variable, and model metadata. After initialization, it changes into the project directory. ```sh tdg init tardie-agent \ --provider localhost \ --provider-config '{"protocol":"openai-chat-completions","baseUrl":"http://localhost:8080/v1","env":["API_KEY"],"models":{"qwen-local":{"metadata":{"contextWindowTokens":32768,"toolCall":true}}}}' \ --default-model qwen-local cd tardie-agent ``` -------------------------------- ### Initialize project non-interactively Source: https://tardigrade.sh/docs/cli Supply connection details as JSON to initialize without interactive prompts. The JSON references secret environment variables without containing the actual secret values. ```bash tdg init tardie-agent \ --template quickstart \ --provider openrouter \ --provider-config '{"env":["OPENROUTER_API_KEY"]}' \ --default-model anthropic/claude-sonnet-4.6 cd tardie-agent ``` -------------------------------- ### Create a Bun host with defineActor and createBunHost Source: https://tardigrade.sh/docs/actors Defines an actor named 'meeseeks' with methods and components, then creates a Bun host with storage and layersFor. Use the host to allocate threads and call methods, and close it with await host.close(). ```ts import { defineActor } from "tardie/core" import { createBunHost } from "tardie/bun" import { layersFor } from "./layers" import { infer, codeMode } from "./components" import { message } from "./methods" import { mcpPackage } from "./packages" const meeseeks = defineActor( "meeseeks", { message }, [infer, codeMode(mcpPackage)], ) const host = await createBunHost({ actor: meeseeks, storage: "./data", layersFor, }) ``` -------------------------------- ### Search providers and models Source: https://tardigrade.sh/docs/cli Inspects provider requirements and searches models through a running server. Each response includes pagination fields; pass the optional next_cursor with the same filters to read the next page. ```bash tdg providers --search gateway --limit 20 --json tdg models --provider openrouter --search claude --limit 20 --json ``` -------------------------------- ### Bun host encodes instance and thread names as base64url filenames Source: https://tardigrade.sh/docs/actors Shows how the Bun host encodes the JSON pair [actor, instance] as a base64url filename for the instance database, and encodes the thread name as a base64url filename for the thread database. The thread database is stored in a .threads directory next to the instance database. ```TypeScript import { Buffer } from "node:buffer" import { join } from "node:path" const instanceFile = Buffer.from(JSON.stringify(["meeseeks", "rick"])).toString("base64url") const actorDatabase = join("/data", `${instanceFile}.sqlite`) const thread = "main" const filename = Buffer.from(thread, "utf8").toString("base64url") const target = join(`${actorDatabase}.threads`, `${filename}.sqlite`) ``` -------------------------------- ### Deploy to Celld Source: https://tardigrade.sh/docs/quickstart Deploys the agent to your own cloud using Celld. ```bash bun run deploy:celld ``` -------------------------------- ### Create a thread and send a message to the cloud agent Source: https://tardigrade.sh/docs/quickstart Creates a root thread on the remote host and invokes the message method. Set ACTOR_URL to your deployment URL. ```bash tdg thread create --name quickstart --url "$ACTOR_URL" tdg call message '{"text":"What is the weather in Singapore?"}' --thread quickstart --url "$ACTOR_URL" ``` -------------------------------- ### Change to Project Directory Source: https://tardigrade.sh/docs/quickstart Changes the current directory to the newly created tardie-agent project directory. ```bash cd tardie-agent ``` -------------------------------- ### Create thread and call methods Source: https://tardigrade.sh/docs/cli Creates a thread, invokes a method with --no-wait, reads its state, and cancels it. The thread ID is used with --thread; --id enables idempotent retries. State and cancel require the same actor, thread, method, and invocation ID. ```bash tdg methods --json tdg thread create --name root tdg call message '{"text":"What is the weather in Singapore?"}' --no-wait --thread root --id m1 tdg call state message m1 --thread root tdg call cancel message m1 --thread root --reason "operator stopped it" ``` -------------------------------- ### Deploy Worker with celld (dry-run and actual) Source: https://tardigrade.sh/docs/cli Deploy the Worker using the Celld CLI. The dry-run command validates the configuration without deploying, while the actual command performs the deployment. Requires the celld.jsonc configuration file. ```bash celld deploy --config celld.jsonc --dry-run ``` ```bash celld deploy --config celld.jsonc ``` -------------------------------- ### Deploy to Celld with dry-run validation Source: https://tardigrade.sh/docs/platforms/celld Deploys to Celld: the first command validates the deployment with --dry-run, the second publishes it. The bucket is set with --bucket. ```bash bun run deploy:celld --bucket s3://actors --dry-run bun run deploy:celld --bucket s3://actors ``` -------------------------------- ### Typical agent harness loop in TypeScript Source: https://tardigrade.sh/docs/why Shows a conventional agent loop with a policy for context window, compaction, and turn limits. It compacts messages when token count exceeds the threshold, calls the model, and processes tool calls until no tool calls remain or the turn limit is reached. ```ts type AgentPolicy = { readonly contextWindow: number readonly compactAt: number readonly maxTurns: number } const runAgent = async (messages, policy: AgentPolicy) => { for (let turn = 0; turn < policy.maxTurns; turn++) { if (tokenCount(messages) >= policy.contextWindow * policy.compactAt) { messages = await compact(messages) } const response = await model.generate({ messages, system, tools }) messages.push(response) if (response.toolCalls.length === 0) return response.text // Check permissions, run tools, and append their results. } throw new Error("Turn limit reached") } ``` -------------------------------- ### Projection and Machine interfaces Source: https://tardigrade.sh/docs/concepts Defines a Moore-style machine with initial, step, and output functions; Projection is a Machine over events. ```typescript interface Machine { initial(): State step(state: State, input: Input): State output(state: State): Output } type Projection = Machine ``` -------------------------------- ### View events for a thread Source: https://tardigrade.sh/docs/quickstart Displays the events for a specified thread. The thread name is used as the argument. ```bash tdg events ``` -------------------------------- ### Validate and run locally with tdg lint, tdg build, and bun run dev Source: https://tardigrade.sh/docs/cli Run these commands to validate the actor's component and method seams before building or deploying. tdg lint fails when a declared method has no handler, a component handles an absent method, several components handle the same method, or a fixed actor reference calls an undeclared method. Pass --json to inspect each method and outgoing call seam. ```bash tdg lint actor.ts tdg build actor.ts bun run dev ``` -------------------------------- ### Create D1 database Source: https://tardigrade.sh/docs/platforms/cloudflare Creates the D1 database for a project named tardie-agent. Copy the returned database_id into the CATALOG_DB entry in wrangler.jsonc. ```bash bunx wrangler d1 create tardie-agent-catalog ``` -------------------------------- ### Durable Object namespace layout for actor instances and threads Source: https://tardigrade.sh/docs/actors Text diagram showing the Durable Object namespaces ACTORS and THREADS. ACTORS contains one entry per instance (e.g., ["meeseeks","rick"]), and THREADS contains entries for each thread (e.g., ["meeseeks","rick","main"] and ["meeseeks","rick","lab"]). ```text Durable Object namespaces ├── ACTORS │ └── ["meeseeks","rick"] # Rick's instance └── THREADS ├── ["meeseeks","rick","main"] # main └── ["meeseeks","rick","lab"] # lab ``` -------------------------------- ### Complete search tool component Source: https://tardigrade.sh/docs/components Full component definition combining initial, step, and output. Includes imports and type definitions. The component is named 'search_logs' and uses Effect for external actions. ```TypeScript import { Clock, Effect } from "effect" import { component, type TransitionContext } from "tardie/core" type Call = { callId: string name: string arguments: unknown turn?: string } type Pending = { call: Call context: TransitionContext } const searchTool = ( searchLogs: (call: Call, signal: AbortSignal) => Effect.Effect ) => component({ name: "search_logs", initial: (): ReadonlyArray => [], step: (pending, event, context) => { if ( event.type === "ToolCalled" && typeof event.callId === "string" && event.name === "search_logs" ) { return [...pending, { context, call: { callId: event.callId, name: event.name, arguments: event.arguments, ...(typeof event.turn === "string" ? { turn: event.turn } : {}) } }] } const remaining = pending.filter( (item) => !item.context.matches("search", event) ) return remaining.length === pending.length ? pending : remaining }, output: (pending) => ({ view: { pendingCalls: pending.length }, transitions: pending.map(({ call, context }) => context.effect("search", { input: call, act: (input, { signal }) => Effect.gen(function* () { const result = yield* searchLogs(input, signal) const at = yield* Clock.currentTimeMillis return { type: "ToolReturned", ...input, result, at } }) }) ) }) }) ``` -------------------------------- ### Apply remote migration Source: https://tardigrade.sh/docs/platforms/cloudflare Applies the schema to the remote D1 database. ```bash bunx wrangler d1 migrations apply CATALOG_DB --remote ``` -------------------------------- ### Configure Celld node with Worker variables Source: https://tardigrade.sh/docs/platforms/celld Configures a Celld node with Worker variables for the Tardigrade token and OpenAI API key, plus the Worker Loader binding for Code Mode. The internal listener should be on a trusted private network. ```bash CELLD_WORKER_LOADER=LOADER \ CELLD_VAR_TARDIGRADE_TOKEN="$TARDIGRADE_TOKEN" \ CELLD_VAR_OPENAI_API_KEY="$OPENAI_API_KEY" \ celld \ --bucket s3://actors \ --listen 0.0.0.0:8080 \ --internal-listen 10.0.0.12:8081 \ --advertise 10.0.0.12:8081 ``` -------------------------------- ### Allocate root threads with instance and name Source: https://tardigrade.sh/docs/actors Allocates root threads for actor instances 'rick' and 'morty' with names 'main' and 'lab'. Repeating an allocation with the same scope and name returns a reference to the same logical thread. ```TypeScript const rickMain = await host.allocateRootThread({ instance: "rick", name: "main" }) const rickLab = await host.allocateRootThread({ instance: "rick", name: "lab" }) const mortyMain = await host.allocateRootThread({ instance: "morty", name: "main" }) const mortyLab = await host.allocateRootThread({ instance: "morty", name: "lab" }) ``` -------------------------------- ### Import core primitives directly Source: https://tardigrade.sh/docs/sdk Imports lower-level primitive types directly from their subpath entry points for integrations that need them. ```ts import type { Machine } from "tardie/core/machine" import type { Projection } from "tardie/core/projection" import type { ComponentOutput } from "tardie/core/component" ``` -------------------------------- ### Send a follow-up message Source: https://tardigrade.sh/docs/quickstart Sends another message to the same thread to continue the conversation. ```bash tdg call message '{"text":"How about San Francisco?"}' --thread quickstart ``` -------------------------------- ### Import actor and agent components Source: https://tardigrade.sh/docs/sdk Imports the main actor definition and agent components from the public entry points. Most applications can use these imports directly. ```ts import { actor } from "tardie/core" import { agentMethods, budget, codeMode, compaction, infer, nativeOutput, system, tool } from "tardie/agent" ``` -------------------------------- ### List threads and inspect events remotely Source: https://tardigrade.sh/docs/cli Lists threads and inspects a thread's event log. Remote calls add the server connection and actor instance to the commands. ```bash tdg ls --url https://tardigrade.example.com --token "$TOKEN" --actor researcher tdg events root --types TurnFailed --actor researcher ``` -------------------------------- ### Agent message method with input/output schemas Source: https://tardigrade.sh/docs/quickstart Defines the agentMessageMethod with input and output schemas. The input includes text, optional input, and optional model. The method records events, projects state, and handles cancellation. ```ts const AgentMessageInput = Schema.Struct({ text: Schema.String, input: Schema.optionalKey(Schema.Unknown), model: Schema.optionalKey(ModelRef) }) const agentMessageMethod = actorMethod({ input: AgentMessageInput, output: Schema.String, event, projection, cancellation: { event: cancellationEvent } }) ``` -------------------------------- ### Merge application Effect service layer in server.ts Source: https://tardigrade.sh/docs/platforms/bun Shows how to merge an application Effect service layer with model services in server.ts. The factory receives thread and instance IDs separately, and AppConfig is an application-owned service with thread and instance fields. Pass api to serve(host, { port, api }) to expose model discovery and live inference output. ```ts import { Layer } from "effect" import { createBunHost } from "tardie/bun" import { bunModelServices } from "tardie/server/model-services" import { AppConfig } from "./application" import definition from "./actor" const { config, layers, api } = await bunModelServices({ env: process.env }) const host = await createBunHost({ actor: definition, storage: config.actorData, driver: { maxConcurrentThreads: config.maxConcurrentThreads }, layersFor: (thread, instance) => Layer.mergeAll( layers, Layer.succeed(AppConfig, { thread, instance }) ) }) ``` -------------------------------- ### Deploy Worker Source: https://tardigrade.sh/docs/platforms/cloudflare Deploys the Worker to Cloudflare. The deployed Worker exposes the same actor, thread, method, and event routes used locally. ```bash bunx wrangler deploy ``` -------------------------------- ### Invoke actor thread method with rickMain.methods.message Source: https://tardigrade.sh/docs/actors Use the thread reference to list available methods and invoke one with await. The key option identifies the invocation so retries reuse the same call and result. ```ts Object.keys(rickMain.methods) // ["message"] const response = await rickMain.methods.message({ text: "Help me build a portal gun.", }, { key: "portal-plan" }) ``` -------------------------------- ### Child thread coordinate JSON Source: https://tardigrade.sh/docs/actors Shows the structure of a thread coordinate returned by the host, containing actor, instance, and thread names. ```JSON { "actor": "meeseeks", "instance": "rick", "thread": "researcher" } ``` -------------------------------- ### Define layersFor with OpenAI model layer Source: https://tardigrade.sh/docs/actors Defines a modelLayer that provides an OpenAI language model (gpt-5) using Effect layers, and exports layersFor that returns this layer. Requires OPENAI_API_KEY environment variable; throws if missing. ```ts import { Layer, Redacted } from "effect" import { FetchHttpClient } from "effect/unstable/http" import { OpenAiClient, OpenAiLanguageModel } from "@tardie/ai-openai" export const modelLayer = (apiKey: string) => OpenAiLanguageModel.layer({ model: "gpt-5" }).pipe( Layer.provide(OpenAiClient.layer({ apiKey: Redacted.make(apiKey) })), Layer.provide(FetchHttpClient.layer), ) const apiKey = process.env.OPENAI_API_KEY if (!apiKey) throw new Error("OPENAI_API_KEY is required") export const layersFor = (_thread: string) => modelLayer(apiKey) ``` -------------------------------- ### Cloudflare host Durable Object lookup for actor instance and thread Source: https://tardigrade.sh/docs/actors Shows how the Cloudflare host resolves a thread by using JSON arrays to name the actor instance and thread Durable Objects. The actor, instance, and thread are stringified into JSON arrays and passed to getByName on the ACTORS and THREADS namespaces. ```TypeScript const actor = "meeseeks" const instance = "rick" const thread = "main" const supervisor = env.ACTORS.getByName(JSON.stringify([actor, instance])) const target = env.THREADS.getByName(JSON.stringify([actor, instance, thread])) ``` -------------------------------- ### Component interfaces Source: https://tardigrade.sh/docs/concepts ComponentOutput and Component interfaces for a named projection with a view and transitions. ```typescript interface ComponentOutput { view: View transitions: ReadonlyArray> } interface Component { name: string machine: Projection> } ``` -------------------------------- ### Define initial state with empty array Source: https://tardigrade.sh/docs/components Sets the component's initial state to an empty list, indicating no pending search requests. ```TypeScript initial: () => [], ``` -------------------------------- ### Run Cloudflare Worker locally with Durable Object runtime Source: https://tardigrade.sh/docs/platforms/bun Runs the Cloudflare Worker locally when the Durable Object runtime is needed. ```bash bun run dev:cloudflare ``` -------------------------------- ### Local verification commands Source: https://tardigrade.sh/docs/platforms/cloudflare Verifies the local Worker with a health check, creates a thread, and calls a message. Requires TARDIGRADE_TOKEN set in the shell. ```bash curl http://localhost:8787/healthz tdg thread create --name quickstart --url http://localhost:8787 --token "$TARDIGRADE_TOKEN" tdg call message '{"text":"What is the weather in Singapore?"}' --thread quickstart --url http://localhost:8787 --token "$TARDIGRADE_TOKEN" ``` -------------------------------- ### Allocate threads with generated names Source: https://tardigrade.sh/docs/actors Omitting the name parameter lets the host assign a friendly slug like 'quiet-fox-k7m2'. The host checks for collisions and retries if a name is taken. ```TypeScript const root = await host.allocateRootThread({ instance: "rick" }) const child = await host.allocateChildThread({ parent: root.coordinate }) ``` -------------------------------- ### Update state on ToolCalled and search completion Source: https://tardigrade.sh/docs/components Handles ToolCalled events to add pending requests and removes them when the search effect completes. Uses context.matches to recognize completion. ```TypeScript step: (pending, event, context) => { if ( event.type === "ToolCalled" && event.name === "search_logs" && typeof event.callId === "string" ) { return [...pending, { context, call: { callId: event.callId, name: event.name, arguments: event.arguments, ...(typeof event.turn === "string" ? { turn: event.turn } : {}) } }] } const remaining = pending.filter( (request) => !request.context.matches("search", event) ) return remaining.length === pending.length ? pending : remaining }, ``` -------------------------------- ### Define an actor interface Source: https://tardigrade.sh/docs/actors Shows the structure of an actor definition, including its name, methods, and components. This is the base type that describes an actor's methods and behavior. ```ts interface Actor { name: string methods: ActorMethods components: ReadonlyArray } ``` -------------------------------- ### Actor definition with agent method Source: https://tardigrade.sh/docs/concepts Defines an actor named 'assistant' with a single method 'message' using agentMessageMethod, and includes an infer component with outputValidateOnce. The actor provides a callable interface for the composed machines. ```TypeScript import { actor } from "tardie/core" import { agentMessageMethod, infer, outputValidateOnce } from "tardie/agent" const assistant = actor({ name: "assistant", methods: { message: agentMessageMethod }, components: [infer([outputValidateOnce])] }) ``` -------------------------------- ### Weather tool definition Source: https://tardigrade.sh/docs/quickstart Defines the weather tool component that contributes 'get_weather' to the agent's view. The tool's specification and Effect handler are kept together. ```ts const weather = tool({ spec: { name: "get_weather", description: "Get the current weather for a city", inputSchema: { type: "object", properties: {}, additionalProperties: false } }, run: () => Effect.succeed({ temperature: 21 }) }) ``` -------------------------------- ### ComponentDefinition diagram Source: https://tardigrade.sh/docs/why Text diagram showing the structure of ComponentDefinition: event history as private state, value observed by parent, and Effect services for transitions. ```text ┌── event history remembered as private state │ ┌── value observed by the parent │ │ ┌── Effect services its transitions may require │ │ │ ▼ ▼ ▼ ComponentDefinition ``` -------------------------------- ### ViewAlgebra interface Source: https://tardigrade.sh/docs/concepts Defines the core algebra for views: an empty view and a combine operation to merge two views. Used as the foundation for view composition in Tardigrade. ```TypeScript interface ViewAlgebra { empty: View combine(left: View, right: View): View } ``` -------------------------------- ### ComponentDefinition interface Source: https://tardigrade.sh/docs/why Defines the interface for a component in Tardigrade. It includes required fields for name, initial, step, and output, plus optional cancelState and keys. The output returns a view and transitions. ```TypeScript interface ComponentDefinition { readonly name: string readonly initial: () => State readonly step: (state: State, event: Event) => State readonly output: (state: State) => { readonly view: View readonly transitions: ReadonlyArray> } readonly cancelState?: ( state: State, cancellation: InvocationCancellation ) => ReadonlyArray> readonly keys?: KeyFragment } ``` -------------------------------- ### Declare search effects in output Source: https://tardigrade.sh/docs/components Reads the current state to expose pending call count and declares a search effect for each pending request. The effect runs external work and returns a ToolReturned event. ```TypeScript output: (pending) => ({ view: { pendingCalls: pending.length }, transitions: pending.map(({ call, context }) => context.effect("search", { input: call, act: (input, { signal }) => Effect.gen(function* () { const result = yield* searchLogs(input, signal) const at = yield* Clock.currentTimeMillis return { type: "ToolReturned", ...input, result, at } }) }) ) }), ``` -------------------------------- ### Set Wrangler secrets Source: https://tardigrade.sh/docs/platforms/cloudflare Stores the Tardigrade token and provider credentials as Wrangler secrets. Use the credential name configured for your provider in place of OPENAI_API_KEY. ```bash bunx wrangler secret put TARDIGRADE_TOKEN bunx wrangler secret put OPENAI_API_KEY ``` -------------------------------- ### Actor with compaction component Source: https://tardigrade.sh/docs/why Defines a researcher actor that uses the compaction component with a trigger ratio of 0.8 and retain ratio of 0.5. The highlighted lines (6-10) show the compaction configuration. ```TypeScript export const researcher = actor({ name: "researcher", methods: agentMethods, components: [infer([ system("Research the given topic and cite your sources."), compaction({ triggerRatio: 0.8, retainRatio: 0.5 }), nativeOutput ])] }) ``` -------------------------------- ### Define actor with weather tool in actor.ts Source: https://tardigrade.sh/docs/quickstart Defines a Tardigrade actor named 'tardie-agent' with a weather tool that returns dummy data. Uses Effect for the tool's run function and includes system instructions and output validation. ```ts import { Effect } from "effect" import { actor } from "tardie/core" import { agentMessageMethod, infer, outputValidateOnce, system, tool } from "tardie/agent" const actorName = "tardie-agent" const actorInstructions = ` Answer questions about the weather. Use the weather tool for current conditions. `.trim() const weather = tool({ spec: { name: "get_weather", description: "Get the current weather for a city", inputSchema: { type: "object", properties: {}, additionalProperties: false } }, run: () => Effect.succeed({ temperature: 21 }) }) export default actor({ name: actorName, methods: { message: agentMessageMethod }, components: [infer([ system(actorInstructions), weather, outputValidateOnce ])] }) ``` -------------------------------- ### Actor method definition with message method Source: https://tardigrade.sh/docs/quickstart Defines an actor with a 'message' method that uses the agentMessageMethod. The method is a typed, durable call boundary with input/output schemas, event recording, projection, and cancellation handling. ```ts export default actor({ name: actorName, methods: { message: agentMessageMethod }, components: [infer([ system(actorInstructions), weather, outputValidateOnce ])] }) ``` -------------------------------- ### Allocate child threads with parent coordinate Source: https://tardigrade.sh/docs/actors Creates child threads within the same actor instance. The parent-child relationship determines the naming scope; the parent coordinate is passed to allocateChildThread. ```TypeScript const researcher = await host.allocateChildThread({ parent: rickMain.coordinate, name: "researcher", }) const factChecker = await host.allocateChildThread({ parent: researcher.coordinate, name: "fact-checker", }) ``` -------------------------------- ### Actor method definition Source: https://tardigrade.sh/docs/concepts Defines an actor method using actorMethod, taking input/output schemas, an event builder, and a projection. The projection exposes lifecycle queries; an optional cancellation declaration provides the cancellation event builder. ```TypeScript import { actorMethod } from "tardie/core" import { input, output, event, projection } from "./message-contract" const message = actorMethod({ input, output, event, projection }) ``` -------------------------------- ### Event interface Source: https://tardigrade.sh/docs/concepts Interface for an event, an immutable fact with a type field and arbitrary other fields. ```typescript interface Event { type: string [field: string]: unknown } ``` -------------------------------- ### worker.ts: Define Celld Worker host Source: https://tardigrade.sh/docs/platforms/celld Defines the Worker host for Celld, wiring model services and exposing the Durable Object classes ActorDO and ThreadDO. The HTTP handler is exported as the default fetch handler. ```ts import definition from "./actor" import { defineWorkerHost, workerHttp, workerModelServices, modelScopeFrom } from "tardie/worker" import { providerLayer } from "tardie/model/providers/openai-compat" import modelLock from "./models.lock.json" const services = workerModelServices({ model: { providerLayer }, scope: modelScopeFrom(modelLock) }) const host = defineWorkerHost(definition, { services }) const http = workerHttp(host) // host exposes the Durable Object classes (platform/cloudflare/test/actor.workers.ts). // HTTP request -> Worker handler // +-- ActorDO: allocates and tracks threads // +-- ThreadDO: stores events and executes a thread export const { ActorDO, ThreadDO } = host export default { fetch: http.fetch } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.