GET STARTED

Build your first SDK Harness

Write a minimal two-agent Harness in TypeScript with a host-enforced Service, read/write role permissions, and verified file export.

Before diving into every SDK primitive, let’s build the smallest useful multi-agent Harness from end to end.

The workflow:

  1. A read-only publisher Agent reads a reference from release-data.txt inside its sandbox and posts it to a host Service (handoff.publish).
  2. A writable writer Agent fetches that reference from the same Service (handoff.take) and writes delivery.txt.
  3. The host verifies the authenticated caller identities and the exact exported bytes — never trusting either Agent’s self-reported success.

Prerequisites: complete Quickstart (anyswarm setup and ANYSWARM_MODEL_* environment variables).

1. Eject and run the starter project

anyswarm eject first-harness --dir ./first-harness
cd ./first-harness
npm install
npm start -- --cwd ./input --prompt 'Prepare a release handoff.' --output-dir ./runs
anyswarm trace --root ./runs --port 8787

Now let’s walk through the three pieces of TypeScript inside ./first-harness that make this work.

2. Define a host Service (handoff.ts)

Instead of passing untrusted text between containers, you declare a typed host Service. Host Gateway validates input schemas and attaches an unforgeable caller.agentId to every call:

import { createServiceReplyAdapter, type ServiceDefinition, type ServiceInterface } from '@anyswarm/core';

export const handoffInterface: ServiceInterface = {
  description: 'Pass a verified release reference from publisher to writer.',
  operations: {
    publish: {
      description: 'Save the release reference.',
      inputSchema: {
        type: 'object',
        properties: { reference: { type: 'string', pattern: '^[a-f0-9]{12}$' } },
        required: ['reference'],
        additionalProperties: false,
      },
      idempotent: true,
    },
    take: {
      description: 'Read the published release reference.',
      sideEffect: 'read',
    },
  },
};

export function createHandoff() {
  let note: { reference: string; author: string } | undefined;
  let reader: string | undefined;

  const service: ServiceDefinition = {
    interface: handoffInterface,
    provider: 'in-process',
    create: () => ({
      adapter: createServiceReplyAdapter(({ capability, input, caller, assertAuthorized }) => {
        assertAuthorized();
        if (capability.operation === 'publish') {
          const { reference } = input as { reference: string };
          note ??= { reference, author: caller.agentId };
        } else {
          if (!note) return { ok: false, error: { code: 'NO_HANDOFF', message: 'Not published yet' } };
          reader ??= caller.agentId;
        }
        return { ok: true, result: { reference: note.reference } };
      }),
    }),
  };

  return { service, evidence: () => ({ note, reader }) };
}

3. Declare Profiles, permissions, and Runtime (harness.ts)

Register the Service, then create a Runtime where each role gets only the filesystem and Service permissions it needs:

import { createRuntime, createSandbox, runInput, ServiceRegistry } from '@anyswarm/core';
import { createHandoff } from './handoff.js';

const handoff = createHandoff();
const services = new ServiceRegistry();
services.register('handoff', handoff.service, { toolMode: 'cli' });

const runtime = await createRuntime({
  sandbox: createSandbox(config.sandbox),
  connection: config.connection,
  executor: config.executor,
  models: config.models,
  services,
  maxAgents: 2,
  outputDir: context.outputDir,
  profiles: {
    publisher: {
      model: config.model,
      image: config.image,
      writable: false,                  // read-only workspace
      services: { handoff: ['publish'] }, // can ONLY publish
      addedSystemPrompt: 'Read release-data.txt and publish its reference via swarm service invoke handoff publish.',
    },
    writer: {
      model: config.model,
      image: config.image,
      writable: true,                   // can write delivery.txt
      services: { handoff: ['take'] },  // can ONLY take
      addedSystemPrompt: 'Fetch the reference via swarm service invoke handoff take and write delivery.txt.',
    },
  },
});

4. Spawn, orchestrate, and verify on the host

Spawn each Agent into its own isolated sandbox, drive each turn with a bounded timeout, verify the host evidence and exported bytes, and close cleanly:

try {
  // 1. Publisher reads secret reference and posts to host Service
  const publisher = await runtime.spawn({
    requestId: 'spawn-publisher',
    profile: 'publisher',
    files: { ...initialFiles, 'release-data.txt': { encoding: 'utf8', data: `${reference}\n` } },
  });
  await runInput(runtime, publisher.id, 'Publish the reference from release-data.txt.', {
    requestId: 'publisher-turn',
    timeoutMs: 120_000,
  });

  // Host verifies authenticated publisher identity — never trusts agent prose
  if (handoff.evidence().note?.author !== publisher.id) {
    throw new Error('Authenticated publisher did not publish the expected reference.');
  }

  // 2. Writer fetches reference and writes delivery.txt (marked required for export)
  const writer = await runtime.spawn({
    requestId: 'spawn-writer',
    profile: 'writer',
    files: initialFiles,
    collect: { paths: ['delivery.txt'], maxBytes: 4096, required: true },
  });
  await runInput(runtime, writer.id, 'Fetch the reference and write delivery.txt.', {
    requestId: 'writer-turn',
    timeoutMs: 120_000,
  });

  // 3. Host verifies exact bytes inside the sandbox before closing
  const snap = await runtime.files.snapshot(writer.id, {
    requestId: 'verify-delivery',
    paths: ['delivery.txt'],
    maxBytes: 4096,
  });
  // Compare snap.files['delivery.txt'] against expected bytes...
} finally {
  // Stop → Export → Delete: archives traces and delivery.txt before removing containers
  const receipt = await runtime.close({ timeoutMs: 60_000 });
}

Key takeaways

Every multi-agent Harness you build on AnySwarm follows this exact three-step skeleton:

  1. Services hold shared state and enforce schemas/identity on the host.
  2. Profiles isolate each role’s workspace write access and allowed Service operations.
  3. Orchestration & Host Verification bound every turn, verify outputs independently of Agent claims, and rely on runtime.close() to archive artifacts cleanly.

Need interactive human-in-the-loop questions over SDK or JSONL RPC? The ejected project also includes session.ts demonstrating askUser — see CLI & RPC Reference.


Next: dive into each SDK building block in detail, starting with Runtime.