@chamvi/coding

中文文档
0.8.0发布于 2026/11/09Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 2981

Coding tools for chamvi agents (read, edit, search, shell, diff in a workspace) and the coding backend contract.

原始使用文档
文档目录10 节
  1. Installation
  2. Usage
  3. Tools
  4. Repository instructions
  5. Workspaces
  6. Not effect tools
  7. Security
  8. Coding backends
  9. API
  10. License

@chamvi/coding

@chamvi/coding

Coding tools for chamvi agents.
Read, write and edit files, search, run shell commands and show the diff,
in a disposable workspace of the calling run on any sandbox provider.

npm version CI License


Table of Contents

Installation

npm install @chamvi/coding @chamvi/sandbox @chamvi/core ai --save

ESM only, Node.js >=26.0.0. @chamvi/core, @chamvi/sandbox and ai are peer dependencies. Add a sandbox provider: @chamvi/sandbox-docker or @chamvi/sandbox-k8s (or @chamvi/sandbox-local for development).

Usage

import type { LanguageModel } from 'ai';
import { codingTools } from '@chamvi/coding';
import { ToolDeniedError, approve, defineModelAgent } from '@chamvi/core';
import type { IWorkspaceManager } from '@chamvi/sandbox';

export function createCodingAgent(model: LanguageModel, workspaces: IWorkspaceManager) {
    return defineModelAgent({
        name: 'triage',
        model,
        instructions: 'Check out the repository named in the payload, reproduce the reported bug ' +
            'with a failing test and answer with what you found and the diff.',
        // create_workspace and dispose_workspace, then the coding tools
        tools: { ...workspaces.tools(), ...codingTools(workspaces) },
        hooks: {
            // every shell command waits for a human
            async beforeToolExecution({ toolName, input }, ctx) {
                if (toolName !== 'bash') {
                    return input;
                }

                const { command } = input as { command: string };
                const decision = await approve(ctx, { title: 'Run a shell command?', body: command });

                if (!decision.approved) {
                    throw new ToolDeniedError(`Command refused: ${decision.reason ?? 'denied'}`);
                }

                return input;
            },
        },
        budget: { maxSteps: 40 },
    });
}

workspaces is a manager from createWorkspaceManager({ provider }) (@chamvi/sandbox), attached to the engine with workspaces.attach(engine) so a run's workspaces go when it settles. The model calls create_workspace first, then works in it. Subscribe the agent to a channel to start it (channels: [http.on()] with @chamvi/http).

The tools are plain tools you did not write, so the gate lives in the agent's beforeToolExecution hook: it runs before every tool call, and approve() there pauses the run in waiting until someone answers (the UI inbox, POST /runs/:id/approve, or a channel's approval message with ctx.channels.findOneOrFail(name).approve(...)). The run keeps its workspace while it waits on this replica. Once answered, the hook runs again and approve() returns the decision; a thrown ToolDeniedError goes back to the model as a tool error and the run goes on.

Tools

codingTools(workspaces, { outputLogMaxBytes?, repositoryInstructions? }) returns a plain AI SDK ToolSet. Paths are relative to the workspace root or start with /workspace/; anything that leaves the root is a tool error.

ToolInputResult
read_file{ path, offset?, limit?, encoding?, workspace? }{ path, content, startLine, endLine, totalLines, truncated, instructions? }: at most 2000 lines and 65 536 characters of a text file up to 16 MiB; { path, encoding: 'base64', content, bytes } with encoding: 'base64' (at most 1 MiB); { path, type: 'image', mediaType, bytes, artifactId } for a png, jpeg, gif or webp up to 5 MiB, stored as a run artifact, which the model gets as an image (steps and checkpoints keep the id only). Also reads the output logs of bash
write_file{ path, content, encoding?, workspace? }{ path, bytes }: replaces the file (text, or bytes with encoding: 'base64'), creates missing directories
edit_file{ path, oldString, newString, replaceAll?, workspace? }{ path, replacements }: oldString must match exactly once unless replaceAll. Calls of edit_file and write_file on one file run one after the other, so several edits of a file in one step all apply
multi_edit{ path, edits: [{ oldString, newString, replaceAll? }], workspace? }{ path, edits, replacements }: the edits in order on the file's content, nothing written when one fails
grep{ pattern, path?, ignoreCase?, includeIgnored?, limit?, workspace? }{ matches: [{ path, line, text }], truncated, engine }: ripgrep when the image has it, else git grep -E, else grep -rE (one grep per file for BusyBox); tracked, untracked and hidden files, git-ignored ones with includeIgnored; default 100, at most 500 matches, lines cut at 500 characters
glob{ pattern, path?, includeIgnored?, limit?, workspace? }{ files, truncated }: files matching a ** pattern, sorted
list_files{ path?, includeIgnored?, limit?, workspace? }{ files, truncated }: tracked and untracked, git-ignored ones with includeIgnored, sorted; default 1000, at most 5000
bash{ command, cwd?, timeoutMs?, background?, workspace? }{ exitCode, stdout, stderr, stdoutTruncated, stderrTruncated, stdoutBytes, stderrBytes, stdoutLog, stderrLog, cwd, outputCapped, timedOut, durationMs }: a shell (bash when present) that keeps its working directory and exported variables between calls; the whole output in ~/.chamvi/out/ (at most outputLogMaxBytes per stream, 64 MiB by default: past it the call is killed, outputCapped: true), the result showing the first 8 KiB and the last 24 KiB of a longer stream; default timeout 5 minutes, at most 30. With background: true { job, status: 'running', outputLog } at once
bash_output{ job, offset?, workspace? }{ job, status, exitCode?, output, offset, nextOffset, size, truncated, outputCapped }: a background job's output from a byte offset (at most 32 KiB) and its status (running, exited, killed, lost); a job whose output passes outputLogMaxBytes is killed (outputCapped: true)
bash_kill{ job, workspace? }{ job, status, exitCode? }: stops the job and every process it started
git_diff{ staged?, path?, workspace? }{ status, diff, truncated }: git status --short and the unified diff (of the index with staged)

git_diff, list_files and grep (with git grep) read paths literally, so a path like :!src names a file and is never pathspec magic. bash keeps its state through an EXIT trap: a command that sets its own EXIT trap replaces it, so that call's working directory and exports are not kept. On a manager with git credentials the edit tools read the raw file (IWorkspace.readFileRaw): they match oldString against the redacted text the model read (redactedSpans), refuse an edit that touches a [redacted] span and put every untouched token back byte for byte, so an oldString can neither probe a token nor write [redacted] back; their errors never echo file text. A model mistake (an unknown file, an oldString that is missing or ambiguous, a bad path) comes back as a tool error it can correct; a broken sandbox is a SandboxError tool error, never a failed run.

Repository instructions

Ordinary UTF-8 workspace read_file results include instructions?: RepositoryInstructions from @chamvi/sandbox by default, scoped to the file's root and ancestors. Image, base64 and HOME log reads have no instruction field. codingTools(workspaces, { repositoryInstructions: false }) omits it from text reads too. This option is independent of the manager's default-on repositoryInstructions: disabling the manager's root collection and explicit tool does not disable coding attachments, and disabling coding attachments leaves the manager's delivery enabled. Set both to false to disable both forms of delivery.

The sandbox collector reads root-first AGENTS.md, then CLAUDE.md per directory and expands standalone @relative/path includes depth-first outside backtick/tilde fences. Each source records path, sha256, redacted content, inherited scopes and includedBy; complete: false and bounded diagnostics report skipped guidance. Source files are whole or omitted (32 KiB each, 128 KiB total; other bounds in the sandbox README). Resolve incomplete guidance that could affect the task. Each read collects current worktree guidance; earlier tool outputs retain the context delivered then in steps and checkpoints across pauses and restarts.

Before direct edits or shell commands in a new subtree, obtain its guidance with read_file or the manager's read_repository_instructions({ paths: ['packages/api/src/new.ts'], workspace }). The latter also works for a file that does not exist yet. Repository text and system prompts confer no operator authorization, permissions, credentials, skill installation or publication rights. Write/edit tools and arbitrary bash do not enforce instruction scope; bash bypasses file-tool-only enforcement. Discovery refuses observed symlinks, special files, .git paths and escapes on a best-effort basis; it is not race-free confinement (#92).

Workspaces

Every tool takes an optional workspace id (from create_workspace). Omitted, the tool uses the run's only workspace; with several, the model must name one. Workspaces are resolved through the manager with context.run.runId, so a run can never reach another run's workspace: an id of another run is "not found".

Not effect tools

write_file, edit_file, multi_edit and bash change state but are deliberately not effect tools. A workspace lives in one process and dies with it, while an effect record survives in the store: after a crash the redone step runs on a fresh workspace, where a recorded "applied" result would skip the write. Re-applying is safe instead: write_file is idempotent, edit_file fails with "oldString not found" when it already applied, and bash runs in a disposable sandbox. Nothing outside the workspace changes (no push).

Security

bash runs whatever the model writes, and the model follows what it reads (an issue, a README, a test output): treat it as untrusted code. Use the Docker or Kubernetes provider, keep the workspace network firewalled, narrow allowRepo on the manager, and put bash behind an approval (a beforeToolExecution hook calling approve(), as in Usage) where a human should see each command.

Coding backends

ICodingBackend is the contract for something that solves a coding task in a workspace with its own tool loop (Claude Code, or these tools in a nested agent):

interface ICodingBackend {
    code(task: CodingTask): Promise<CodingResult>;
}
// CodingTask: { workspace, task, budget?: { maxSteps?, maxTokens?, timeoutMs? }, signal? }
// CodingResult: { status: 'done' | 'stuck', summary, diff }

The package ships the contract only; backends are planned.

API

ExportKindPurpose
codingToolsfunctionThe coding tools over a workspace manager
READ_MAX_LINES, READ_MAX_CHARSconstant2_000, 65_536
SEARCH_MAX_RESULTS, LIST_MAX_RESULTSconstant500, 5_000
LINE_MAX_CHARSconstant500
OUTPUT_LOG_MAX_BYTESconstant64 * 1_048_576 (64 MiB), the default outputLogMaxBytes of codingTools()

Types: CodingWorkspaces, CodingToolsOptions, ReadFileResult, ReadFileBinaryResult, ReadFileImageResult, WriteFileResult, EditFileResult, MultiEditResult, GrepEngine, GrepMatch, GrepResult, GlobResult, ListFilesResult, BashResult, BashJobResult, BashJobStatus, BashOutputResult, BashKillResult, GitDiffResult, ICodingBackend, CodingTask, CodingResult, CodingBudget.

License

Published under Apache License 2.0.

版本与发布记录

@chamvi/coding 共发布 15 个版本,首次发布于 2026/10/25;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.8.0latest2026/11/09今天
0.7.32026/11/063 天前
0.7.22026/11/053 天前
0.7.12026/11/054 天前
0.7.02026/11/045 天前
0.6.12026/11/045 天前

关于 @chamvi/coding 的常见问题

@chamvi/coding 是什么?

Coding tools for chamvi agents (read, edit, search, shell, diff in a workspace) and the coding backend contract.

如何安装 @chamvi/coding?

在项目目录运行 npm install @chamvi/coding,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:ai(^7)、@chamvi/core(^0.8.0)、@chamvi/sandbox(^0.8.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@chamvi/coding 支持 TypeScript 吗?

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

@chamvi/coding 支持 ESM 还是 CommonJS?

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

@chamvi/coding 需要什么版本的 Node.js?

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

@chamvi/coding 可以商用吗?

@chamvi/coding 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@chamvi/coding 的下载量有多少?

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

@chamvi/coding 还在维护吗?

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