Samples

Complete, runnable code examples for common agent patterns — from bootstrap to production.

Overview

Each example is self-contained with prerequisites listed. Copy them directly into your project.


Agent bootstrap script

Create an agent with a routine in a single executable script.

Prerequisites: npm install @archastro/sdk tsx, set ARCHASTRO_SECRET_KEY

// src/agents/bootstrap.ts
import { ArchAstroClient } from "@archastro/sdk";

const client = new ArchAstroClient({
  baseURL: "https://api.archastro.ai",
  secretKey: process.env.ARCHASTRO_SECRET_KEY!,
});

async function main() {
  await client.ready;

  // Create agent identity
  const agent = await client.rest.createAgent({
    name: "Support Agent",
    lookup_key: "support",
    identity: "You are a customer support specialist for Acme Corp.",
  });
  console.log("Agent:", agent.id);

  // Attach event-driven routine
  const routine = await client.rest.createAgentRoutine({
    agent_id: agent.id,
    name: "message_handler",
    event_type: "thread.message_added",
    handler_type: "script",
    script: `
      const msg = event.payload.message;
      const intent = msg.text.toLowerCase().includes("billing")
        ? "billing" : "general";
      return { intent, agent_id: "${agent.id}" };
    `,
  });
  console.log("Routine:", routine.id);

  console.log("\nAgent ready. Activate the routine in the portal or via API.");
  await client.dispose();
}

main().catch(console.error);
npx tsx src/agents/bootstrap.ts

Next.js server auth

Server-side authentication with session management and federated login.

Prerequisites: npm install @archastro/sdk @archastro/sdk-nextjs, set ARCHASTRO_SECRET_KEY and SESSION_SECRET

// src/lib/auth.ts
import {
  createSessionManager,
  createAuthActions,
} from "@archastro/sdk-nextjs/server";

export const sessionManager = createSessionManager({
  secretKey: process.env.SESSION_SECRET!,
  cookieName: "archastro_session",
});

export const authActions = createAuthActions({
  sessionManager,
  apiKey: process.env.ARCHASTRO_SECRET_KEY!,
});
// src/lib/federated-auth.ts
import { createFederatedAuth } from "@archastro/sdk-nextjs/server";
import { sessionManager } from "./auth";

export const federatedAuth = createFederatedAuth({
  providers: ["google", "github"],
  sessionManager,
  apiKey: process.env.ARCHASTRO_SECRET_KEY!,
});
// src/app/api/auth/[...route]/route.ts
import { authActions } from "@/lib/auth";

export const POST = authActions.handler;
export const GET = authActions.handler;

Real-time chat with agents

Join a thread and interact with agents in real time.

Prerequisites: npm install @archastro/sdk, set ARCHASTRO_SECRET_KEY

// src/chat/realtime-demo.ts
import { ArchAstroClient, ChatRoomService } from "@archastro/sdk";

const client = new ArchAstroClient({
  baseURL: "https://api.archastro.ai",
  secretKey: process.env.ARCHASTRO_SECRET_KEY!,
});

async function main() {
  await client.ready;

  // Create a team and thread
  const teams = await client.rest.listTeams();
  const teamId = teams[0].id;
  const thread = await client.rest.createThread(teamId, "Agent demo");
  console.log("Thread:", thread.id);

  // Connect via WebSocket
  const chat = new ChatRoomService(client.socket);
  const room = await chat.joinThread(teamId, thread.id);

  // Listen for all message events
  room.on("message_added", (e) => {
    const sender = e.message.actor?.name || "Unknown";
    console.log(`[${sender}] ${e.message.content}`);
  });

  room.on("message_updated", (e) => {
    console.log(`[Edited] ${e.message.content}`);
  });

  // Send a message
  await room.postMessage("Hello, I need help with my account");

  // Keep alive for demo
  console.log("Listening for messages... (Ctrl+C to exit)");
}

main().catch(console.error);

Agent conversation (direct)

Start a direct agent conversation using the AgentConversationService.

Prerequisites: npm install @archastro/sdk, set ARCHASTRO_SECRET_KEY

// src/chat/agent-conversation.ts
import { ArchAstroClient } from "@archastro/sdk";

const client = new ArchAstroClient({
  baseURL: "https://api.archastro.ai",
  secretKey: process.env.ARCHASTRO_SECRET_KEY!,
});

async function main() {
  await client.ready;

  const teams = await client.rest.listTeams();

  const session = await client.socket.agentConversationService
    .joinConversation({
      scope: "team",
      teamId: teams[0].id,
    });

  console.log("Session:", session.getSessionId());

  // Listen for agent responses
  session.onEvent((event) => {
    switch (event.type) {
      case "message_added":
        console.log(`Agent: ${event.message.content}`);
        break;
      case "session_ended":
        console.log(`Session ended: ${event.reason}`);
        break;
    }
  });

  // Send a message
  await session.sendMessage({ content: "What can you help me with?" });
  console.log("Message sent, waiting for response...");
}

main().catch(console.error);

Multi-agent network

Create two agents that collaborate in a shared thread using participate routines.

Prerequisites: npm install @archastro/sdk tsx, set ARCHASTRO_SECRET_KEY

// src/agents/multi-agent-network.ts
import { ArchAstroClient, ChatRoomService } from "@archastro/sdk";

const client = new ArchAstroClient({
  baseURL: "https://api.archastro.ai",
  secretKey: process.env.ARCHASTRO_SECRET_KEY!,
});

async function main() {
  await client.ready;

  // Create two agents with complementary roles
  const researcher = await client.rest.createAgent({
    name: "Research Agent",
    lookup_key: "researcher",
    identity:
      "You are a research specialist. Find relevant information " +
      "and provide thorough analysis with cited sources.",
  });

  const writer = await client.rest.createAgent({
    name: "Writer Agent",
    lookup_key: "writer",
    identity:
      "You are a writing specialist. Take research findings " +
      "and synthesize them into clear, actionable summaries.",
  });

  // Create a team and add both agents
  const team = await client.rest.createTeam({ name: "Research & Writing" });

  await client.rest.addTeamMember(team.id, {
    agent_id: researcher.id,
    role: "member",
  });
  await client.rest.addTeamMember(team.id, {
    agent_id: writer.id,
    role: "member",
  });

  // Create a shared thread
  const thread = await client.rest.createThread(team.id, "Analysis");

  // Attach participate routines
  for (const agent of [researcher, writer]) {
    await client.rest.createAgentRoutine({
      agent_id: agent.id,
      name: `${agent.name}_participate`,
      event_type: "thread.message_added",
      handler_type: "preset",
      preset_name: "participate",
    });
  }

  // Observe in real time
  const chat = new ChatRoomService(client.socket);
  const room = await chat.joinThread(team.id, thread.id);

  room.on("message_added", (e) => {
    console.log(`[${e.message.actor?.name}] ${e.message.content}`);
  });

  await room.postMessage("Research AI agent frameworks and summarize the top 3.");
  console.log("Conversation started. Thread:", thread.id);
}

main().catch(console.error);
npx tsx src/agents/multi-agent-network.ts

For more patterns and cross-org examples, see Agent Network and Networks.


Generic webhook receiver

Set up a webhook to receive events from an external billing system.

Prerequisites: Set ARCHASTRO_SECRET_KEY and ARCHASTRO_APP_ID

# Create the webhook with a lookup key
curl -X POST "https://api.archastro.ai/protected/api/v2/developer/apps/${ARCHASTRO_APP_ID}/webhooks" \
  -H "Authorization: Bearer ${ARCHASTRO_SECRET_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "lookup_key": "billing-events",
    "signing_secret": "whsec_your_secret_here"
  }'

External systems send events to:

POST https://api.archastro.ai/webhooks/<app_id>/billing-events

List recent events:

# Via CLI
archastro describe appwebhook <webhook_id>

# Or via API
curl "https://api.archastro.ai/protected/api/v2/developer/apps/${ARCHASTRO_APP_ID}/webhooks/<webhook_id>/events" \
  -H "Authorization: Bearer ${ARCHASTRO_SECRET_KEY}"

OAuth connector flow

Let users connect their Google account to your app.

Prerequisites: Configure Google OAuth provider in the portal first

// src/connectors/google.ts
import { ArchAstroClient, buildConnectorAuthorizeUrl } from "@archastro/sdk";

const client = new ArchAstroClient({
  baseURL: "https://api.archastro.ai",
  secretKey: process.env.ARCHASTRO_SECRET_KEY!,
});

async function connectGoogle(teamId: string) {
  // Generate OAuth URL
  const url = await buildConnectorAuthorizeUrl("google", {
    restApi: client.rest,
    teamId,
    accessLevel: "full_access",
    webRedirect: "https://yourapp.com/connectors/callback",
  });

  console.log("Redirect user to:", url);
  // After authorization, check state:

  const state = await client.rest.getConnectorState("google", teamId);
  console.log("Connected:", state.connected);
  console.log("Scopes:", state.scopes);
}

Config validation

Validate a YAML config before deploying it to production.

# Via API
curl -X POST "https://api.archastro.ai/api/v2/config/validate" \
  -H "Authorization: Bearer ${ARCHASTRO_SECRET_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "kind": "AIWorker",
    "content": "kind: AIWorker\nid: my_assistant\nmodel: claude-sonnet-4-5-20250929"
  }'
# Via CLI
archastro configs validate -k AIWorker --content "kind: AIWorker\nid: my_assistant"

Secrets management

Store and retrieve encrypted secrets at different scopes.

// Personal secret
await client.rest.createPersonalSecret({
  name: "openai_key",
  value: "sk-...",
  description: "OpenAI API key for agent completions",
});

const secret = await client.rest.getPersonalSecretValue("openai_key");
console.log("Value:", secret.value);

// Team secret
await client.rest.createTeamSecret(teamId, {
  name: "stripe_key",
  value: "sk_live_...",
  description: "Stripe API key",
});

// Update
await client.rest.updatePersonalSecret("openai_key", {
  value: "sk-new-key...",
});

// Delete
await client.rest.deletePersonalSecret("openai_key");

CLI: full workflow

End-to-end workflow using only the CLI.

# 1. Initialize project
archastro init

# 2. Create an agent
archastro create agent -n "Support Bot" -k support \
  -i "You are a helpful support agent"

# 3. Create a team and user
archastro create team -n "Support Team"
archastro create user -e customer@example.com -n "Test Customer"
archastro create user --system-user  # bot service account

# 4. Create an automation
archastro create automation -n "Welcome" -t trigger --trigger "user.created"

# 5. Set up a webhook
archastro create appwebhook -p github -s my_secret

# 6. Sync and deploy configs
archastro configs sync
archastro configs deploy -m "Initial setup"

# 7. Check status
archastro list agents --json
archastro list automations
archastro auth status