@agent-assistant/harness

中文文档
0.4.37发布于 2026/10/04TypeScriptES Module构建来源已验证近 30 天下载 2.8万

Bounded iterative assistant-turn runtime for Agent Assistant SDK

原始使用文档
文档目录19 节
  1. What It Owns
  2. What It Does Not Own
  3. Installation
  4. Workspace VFS Tools
  5. Public GitHub Tools
  6. Quick Example
  7. OpenRouter execution adapter
  8. What it is
  9. Current scope
  10. Current non-goals
  11. Example
  12. Honest usage guidance
  13. Local command execution adapter
  14. Agent Relay execution adapter
  15. spawnWorker vs worker-bridge
  16. Worker-bridge ( @agent-assistant/harness/worker-bridge )
  17. Public API
  18. Runtime Behavior Notes
  19. Development

@agent-assistant/harness

@agent-assistant/harness is the bounded runtime for one assistant turn with iterative model/tool/model execution, truthful stop semantics, structured continuation payloads, and trace hooks.

It exists to fill the gap between a thin one-shot assistant runtime and an unbounded autonomous agent framework.

What It Owns

  • bounded execution for a single assistant turn
  • iterative model/tool/model loop
  • truthful outcomes: completed, needs_clarification, awaiting_approval, deferred, failed
  • explicit stop reasons
  • compact continuation payloads for clarification, approval, and deferred resume
  • trace/telemetry lifecycle events
  • adapter seams for model, tools, approvals, and trace sinks

What It Does Not Own

  • assistant lifecycle or runtime registration (@agent-assistant/core)
  • sessions persistence (@agent-assistant/sessions)
  • memory storage or retrieval (@agent-assistant/memory)
  • routing policy ownership (@agent-assistant/routing)
  • approvals policy ownership (@agent-assistant/policy)
  • coordination/workflow engines (@agent-assistant/coordination)
  • workforce persona definitions

Installation

npm install @agent-assistant/harness

Workspace VFS Tools

createWorkspaceToolRegistry exposes provider-neutral workspace_search, workspace_list, workspace_read, and workspace_read_json tools for assistants that have a VfsProvider from @agent-assistant/vfs. The tools emit VFS paths, including sourcePath-style structured outputs for JSON reads, so callers can cite file paths in user-visible replies instead of answering workspace questions from memory.

Public GitHub Tools

GitHubPublicFetcher supports bounded read-only inspection of a public GitHub repo: metadata, README/package excerpts, directory listing, focused file reads, recent commits, and authenticated code search. The default fetch fallback reads globalThis.fetch at call time so Cloudflare Workers consumers can safely stub or rely on the platform fetch binding.

Use createPublicGitHubToolRegistry({ owner, repo }) when an assistant has already resolved one explicitly named public repo and needs deeper source navigation through public_repo_metadata, public_repo_list_tree, public_repo_read_file, public_repo_recent_commits, and optionally public_repo_search_code.

Quick Example

import { createHarness } from '@agent-assistant/harness';

const harness = createHarness({
  model: {
    async nextStep(input) {
      if (input.toolCallCount === 0) {
        return {
          type: 'tool_request',
          calls: [
            {
              id: 'call-1',
              name: 'lookup_weather',
              input: { city: 'Oslo' },
            },
          ],
        };
      }

      return {
        type: 'final_answer',
        text: 'It looks chilly in Oslo today.',
      };
    },
  },
  tools: {
    async listAvailable() {
      return [{ name: 'lookup_weather', description: 'Get current weather' }];
    },
    async execute(call) {
      return {
        callId: call.id,
        toolName: call.name,
        status: 'success',
        output: '{"temperatureC":8}',
      };
    },
  },
});

const result = await harness.runTurn({
  assistantId: 'sage',
  turnId: 'turn-123',
  sessionId: 'session-123',
  message: {
    id: 'msg-1',
    text: 'What is the weather in Oslo?',
    receivedAt: new Date().toISOString(),
  },
  instructions: {
    systemPrompt: 'You are Sage. Be concise and truthful.',
  },
});

OpenRouter execution adapter

The harness package now also exposes a bounded hosted execution adapter for OpenRouter-backed turns.

What it is

The OpenRouterExecutionAdapter is a direct hosted backend behind the existing ExecutionAdapter seam.

This means Agent Assistant still owns:

  • assistant identity
  • turn-context assembly
  • policy
  • continuation semantics
  • Relay-native collaboration

The adapter only owns:

  • request translation
  • backend invocation
  • output normalization
  • truthful capability/degradation reporting

Current scope

This adapter is intentionally narrow in the current slice:

  • backend id: openrouter-api
  • direct hosted API execution
  • no-tool turns only
  • minimal trace facts
  • truthful unsupported / degraded negotiation

Current non-goals

This adapter does not currently support:

  • tool-bearing execution
  • structured tool calls
  • attachments
  • structured continuation support
  • approval interrupts

Example

import {
  OpenRouterExecutionAdapter,
  type ExecutionRequest,
} from '@agent-assistant/harness';

const adapter = new OpenRouterExecutionAdapter({
  apiKey: process.env.OPENROUTER_API_KEY,
  model: 'openai/gpt-5-mini',
});

const request: ExecutionRequest = {
  assistantId: 'sage',
  turnId: 'turn-456',
  message: {
    id: 'msg-2',
    text: 'Summarize the current PR status.',
    receivedAt: new Date().toISOString(),
  },
  instructions: {
    systemPrompt: 'You are Sage. Be concise and truthful.',
    developerPrompt: 'Do not invent missing GitHub state.',
  },
  context: {
    blocks: [
      {
        id: 'ctx-1',
        label: 'Scope',
        text: 'Only summarize what is present in the supplied context.',
      },
    ],
  },
};

const negotiation = adapter.negotiate(request);
if (!negotiation.supported) {
  throw new Error(negotiation.reasons.map((reason) => reason.message).join(' '));
}

const result = await adapter.execute(request);

Honest usage guidance

Use this adapter when you want:

  • a hosted API backend
  • one bounded no-tool turn
  • normalized ExecutionResult output through the same execution seam as other backends

Do not treat it as a replacement for:

  • the local CLI harness BYOH path
  • Relay-native collaboration
  • future tool-capable hosted execution work

Local command execution adapter

The harness package also exposes a reusable LocalCommandExecutionAdapter for BYOH/local CLI execution. It is product-neutral: products keep assistant identity, policy, memory, and turn-context assembly, while the adapter owns only local process invocation and result normalization.

Use it when a local harness can be represented as:

  • a command to spawn
  • an argv builder from ExecutionRequest
  • an output parser into normalized assistant output
  • declared ExecutionCapabilities
import {
  LocalCommandExecutionAdapter,
  type ExecutionRequest,
} from '@agent-assistant/harness';

const adapter = new LocalCommandExecutionAdapter({
  backendId: 'my-local-harness',
  command: 'my-harness',
  capabilities: {
    toolUse: 'adapter-mediated',
    structuredToolCalls: true,
    continuationSupport: 'none',
    approvalInterrupts: 'none',
    traceDepth: 'minimal',
    attachments: false,
  },
  buildArgs(request: ExecutionRequest) {
    return ['--json', '--prompt', request.message.text];
  },
  parseOutput(stdout) {
    const parsed = JSON.parse(stdout) as { text?: string };
    return parsed.text ? { text: parsed.text } : null;
  },
});

ClaudeCodeExecutionAdapter is now a preset over this same local-command primitive. That keeps Claude Code support intact while allowing other local harnesses to use the same ExecutionAdapter contract.

Agent Relay execution adapter

For long-lived local harnesses, AgentRelayExecutionAdapter uses Agent Relay as the local control plane. It publishes a typed execution request to a Relay worker and waits for a typed execution result on the same thread.

import {
  AgentRelayExecutionAdapter,
} from '@agent-assistant/harness';

const adapter = new AgentRelayExecutionAdapter({
  cwd: process.cwd(),
  channelId: 'nightcto-local-byoh',
  workerName: 'nightcto-local-harness',
  orchestratorName: 'nightcto-local-chat',
});

The request message body is JSON with type agent-assistant.execution-request.v1. Workers reply with JSON type agent-assistant.execution-result.v1 and an executionResult that follows the normal ExecutionResult contract. Successful turns should use executionResult.status: "completed" and put the assistant answer in executionResult.output.text. The adapter also tolerates common local-worker shorthands such as status: "ok" plus answer and normalizes them into the same ExecutionResult shape. This keeps Claude Code, Codex, OpenCode, or a custom local worker behind Relay instead of baking provider-specific CLI argv into the product.

spawnWorker vs worker-bridge

AgentRelayExecutionAdapter's spawnWorker.enabled spawns a bare CLI as a Relay agent and expects it to respond protocol-compliant messages on its own. That only works if the spawned CLI has MCP tools wired to send typed Relay messages — not the default for most CLIs. Leaving spawnWorker.enabled false and running a worker-bridge process separately (see next section) is the recommended shape; the bridge does the protocol translation so the CLI is just a prompt-in, text-out subprocess.

Worker-bridge (@agent-assistant/harness/worker-bridge)

Dual of the adapter. Listens for agent-assistant.execution-request.v1 messages on a Relay channel, invokes a non-interactive CLI session (claude -p, codex exec, opencode run, gemini -p, or a bash stub for testing), captures stdout, and replies with a correctly-shaped agent-assistant.execution-result.v1 message.

// RelayAdapter wraps @agent-relay/harness-driver's broker client. It was
// exported by @agent-relay/sdk up to 6.x; the SDK no longer ships it.
import { RelayAdapter } from '@agent-assistant/harness/agent-relay';
import {
  createClaudeCliRunner,
  createRelayWorkerBridge,
} from '@agent-assistant/harness/worker-bridge';

const relay = new RelayAdapter({ cwd: process.cwd(), channels: ['specialists'] });
await relay.start();

const bridge = await createRelayWorkerBridge({
  relay,
  channelId: 'specialists',
  workerName: 'specialist-worker',
  runner: createClaudeCliRunner(),
  timeoutMs: 120_000,
});

// ... later
bridge.dispose();
await relay.shutdown();

Runners provided: createClaudeCliRunner, createCodexCliRunner, createOpenCodeCliRunner, createGeminiCliRunner, and createBashCliRunner (for token-free testing). Each takes an optional { command, spawnFn } config for overriding the executable or injecting a mock child_process.spawn.

CliRunner is a minimal interface ({ id, run(input) }) so you can plug in your own CLI or embedded function.

The adapter + bridge are intentionally separate processes in production: the adapter lives wherever your orchestrator runs, the bridge lives on the machine/container that should actually invoke the CLI. Cross-process broker discovery happens via {cwd}/.agent-relay/connection.json.

packages/webhook-runtime/examples/byoh-worker.ts is a thin wrapper over this API that exposes --cli, --channel, --worker-name, --model, and --timeout-ms flags for the two-terminal local-experimentation flow.

Public API

import {
  AgentRelayExecutionAdapter,
  HarnessConfigError,
  LocalCommandExecutionAdapter,
  OpenRouterExecutionAdapter,
  createAgentRelayExecutionAdapter,
  createHarness,
  createLocalCommandAdapter,
  createOpenRouterAdapter,
  type ExecutionAdapter,
  type ExecutionRequest,
  type ExecutionResult,
  type HarnessConfig,
  type HarnessContinuation,
  type HarnessModelAdapter,
  type HarnessResult,
  type HarnessRuntime,
  type HarnessToolRegistry,
  type HarnessTraceSink,
  type HarnessTurnInput,
} from '@agent-assistant/harness';

Runtime Behavior Notes

  • v1 tool execution is sequential by default
  • approvals are an adapter seam; the package does not own policy
  • bounded stops return deferred results with continuation payloads
  • invalid model outputs are tolerated only within configured limits
  • runtime/model/tool failures are surfaced as structured results rather than hidden behind fake completion

Development

From the package directory:

npm test
npm run build

Current package validation includes a non-trivial test suite covering:

  • final answer execution
  • sequential tool loops
  • clarification and approval continuations
  • invalid output recovery and failure bounds
  • retryable vs unrecoverable tool errors
  • deferred outcomes for iteration and budget ceilings
  • runtime error surfacing
  • focused OpenRouter adapter coverage for bounded no-tool hosted execution

HARNESS_PACKAGE_IMPLEMENTED

版本与发布记录

@agent-assistant/harness 共发布 67 个版本,首次发布于 2026/04/14;过去 12 个月发布了 67 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.37latest2026/10/041 个月前
0.4.362026/10/041 个月前
0.4.352026/05/235 个月前
0.4.332026/05/155 个月前
0.4.322026/05/125 个月前
0.4.312026/05/086 个月前

关于 @agent-assistant/harness 的常见问题

@agent-assistant/harness 是什么?

Bounded iterative assistant-turn runtime for Agent Assistant SDK

如何安装 @agent-assistant/harness?

在项目目录运行 npm install @agent-assistant/harness,或使用 pnpm add / yarn add / bun add。

@agent-assistant/harness 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agent-assistant/harness 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@agent-assistant/harness 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@agent-assistant/harness 可以商用吗?

@agent-assistant/harness 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@agent-assistant/harness 的下载量有多少?

根据 npm 官方下载统计,@agent-assistant/harness 在 2026/10/05 – 2026/11/03 这 30 天内被下载 28,311 次,日均约 944 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agent-assistant/harness 还在维护吗?

最新版本 0.4.37 发布于 2026/10/04(1 个月前);至今共发布 67 个版本,其中过去 12 个月发布了 67 个;首次发布于 2026/04/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。