GET STARTED

搭建第一个 SDK Harness

用几十行 TypeScript 写出最小的双 Agent Harness,完整走通宿主机 Service、读写权限隔离与导出字节校验。

在深入每个 SDK 构件之前,我们先端到端写出一个最小但完整的双 Agent Harness。

工作流目标:

  1. 只读的 publisher Agent 从沙箱内的 release-data.txt 读取一段引用码,并发布到宿主机 Service(handoff.publish)。
  2. 可写的 writer Agent 从同一个 Service 读取该引用码(handoff.take),并写出 delivery.txt。
  3. 宿主机独立校验真实调用方身份与导出文件的精确字节——绝不轻信任何 Agent 的口头汇报。

前置条件:已完成 快速上手 中的 anyswarm setup 与 ANYSWARM_MODEL_* 模型配置。

1. 导出并运行起始项目

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

下面拆解 ./first-harness 里真正起作用的三段 TypeScript 代码。

2. 定义宿主机 Service(handoff.ts)

与其让容器之间互相传不可信的自然语言,不如在宿主机定义一个带 Schema 校验的 Service。Host Gateway 会自动校验入参,并注入不可伪造的 caller.agentId:

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. 声明角色 Profile、权限与 Runtime(harness.ts)

注册 Service 后创建 Runtime,按最小权限原则为每个角色分配工作区写权限与可调用的 Service 操作:

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,                    // 只读工作区
      services: { handoff: ['publish'] }, // 只能调用 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,                     // 可写 delivery.txt
      services: { handoff: ['take'] },    // 只能调用 take
      addedSystemPrompt: 'Fetch the reference via swarm service invoke handoff take and write delivery.txt.',
    },
  },
});

4. 启动、编排并在宿主机验收

依次拉起隔离沙箱,为每轮输入设置明确超时,在宿主机核验身份与文件字节,最后安全关闭并归档:

try {
  // 1. publisher 读取引用码并发布到宿主机 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,
  });

  // 宿主机校验真实发布者身份,不依赖 Agent 文本声称
  if (handoff.evidence().note?.author !== publisher.id) {
    throw new Error('Authenticated publisher did not publish the expected reference.');
  }

  // 2. writer 拉取引用码并写出 delivery.txt(标记为必须导出的产物)
  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. 关闭前在宿主机校验沙箱内精确字节
  const snap = await runtime.files.snapshot(writer.id, {
    requestId: 'verify-delivery',
    paths: ['delivery.txt'],
    maxBytes: 4096,
  });
  // 将 snap.files['delivery.txt'] 与预期字节比对...
} finally {
  // Stop → Export → Delete:先归档轨迹与 delivery.txt,再清理容器
  const receipt = await runtime.close({ timeoutMs: 60_000 });
}

核心要点

你在 AnySwarm 上构建的每一个多智能体 Harness,本质上都遵循这三步骨架:

  1. Services 在宿主机保存共享状态,并强约束 Schema 与调用身份。
  2. Profiles 隔离每个角色的写权限与可用 Service 操作。
  3. 编排与宿主机验收 为每轮调用设定超时、独立核验产出,并依靠 runtime.close() 安全归档。

如果需要基于 SDK 或 JSONL RPC 的人机问答协议,导出目录中还附带了 session.ts 示例,详见 CLI 参考。


下一步: 按顺序深入了解六大核心构件,从 Runtime 运行控制面 开始。