@chamvi/coding
Coding tools for chamvi agents and the coding backend contract. The public API of packages/coding/src/index.ts.
npm install @chamvi/coding @chamvi/sandbox @chamvi/core ai --save@chamvi/core, @chamvi/sandbox and ai are peer dependencies. See Workspaces & Coding for the behaviour.
codingTools
function codingTools(workspaces: CodingWorkspaces, options?: CodingToolsOptions): ToolSet;
type CodingWorkspaces = Pick<IWorkspaceManager, 'get'>;Throws InvalidAgentDefinitionError when workspaces has no get, options is no object or options.outputLogMaxBytes is no positive integer. Returns read_file, write_file, edit_file, multi_edit, grep, glob, list_files, bash, bash_output, bash_kill and git_diff, each a defineTool() tool that resolves its workspace through workspaces.get(context.run.runId, input.workspace).
| Tool | Input | Result |
|---|---|---|
read_file | path, offset? (1-based, default 1), limit? (default and maximum 2000), encoding? (utf8 default, base64) | ReadFileResult; ReadFileBinaryResult for base64 (at most 1 MiB); ReadFileImageResult for a png, jpeg, gif or webp (at most 5 MiB), stored as a run artifact (artifactId), an image part for the model through toModelOutput and artifactFilePart(), so steps and checkpoints keep the id only |
write_file | path, content, encoding? (utf8 default, base64) | WriteFileResult |
edit_file | path, oldString, newString, replaceAll? | EditFileResult |
multi_edit | path, edits (1 to 100 of { oldString, newString, replaceAll? }, applied in order, all or none) | MultiEditResult |
grep | pattern (ripgrep syntax, else POSIX ERE: see engine), path?, ignoreCase?, includeIgnored?, limit? (default 100, at most 500) | GrepResult |
glob | pattern (*, ?, **/), path?, includeIgnored?, limit? (default 1000, at most 5000) | GlobResult |
list_files | path?, includeIgnored?, limit? (default 1000, at most 5000) | ListFilesResult |
bash | command, cwd? (this call only), timeoutMs? (default 300 000, at most 1 800 000), background? | BashResult; BashJobResult with background: true |
bash_output | job, offset? (bytes, default 0) | BashOutputResult (at most 32 KiB of output) |
bash_kill | job | BashKillResult |
git_diff | staged?, path? | GitDiffResult |
bash keeps its working directory and exported variables through an EXIT trap; a command that sets its own EXIT trap replaces it, so that call's state is not kept. edit_file and multi_edit read the file through IWorkspace.readFileRaw when the workspace redacts credentials: 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.
Every tool also takes workspace?, the id from create_workspace. A path is relative to the workspace root or starts with /workspace/; read_file and grep also take the log paths bash and bash_output name (~/.chamvi/out/<id>.stdout.log, ~/.chamvi/jobs/<id>/output), and nothing else outside the workspace. See The shell for the kept state, the output logs and the jobs. Input the model can correct (a bad path, an oldString that is missing or ambiguous) is a ValidationError tool error; a missing or oversized file and any other sandbox failure a SandboxError tool error.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IWorkspaceManager, RepositoryInstructions } from '@chamvi/sandbox';
/** What the coding tools need of a workspace manager: the run's workspaces by id. */
export type CodingWorkspaces = Pick<IWorkspaceManager, 'get'>;
export type CodingToolsOptions = {
/** Attach current path-scoped repository guidance to text reads. Default true. */
repositoryInstructions?: boolean;
/**
* Bytes one output log of `bash` may grow to (per stream). A call whose
* log passes it is killed (`outputCapped: true`) and the log cut back to
* it. Default `OUTPUT_LOG_MAX_BYTES` (64 MiB).
*/
outputLogMaxBytes?: number;
};
export type ReadFileResult = {
/** Relative to `/workspace`. */
path: string;
content: string;
/** 1-based, inclusive. */
startLine: number;
endLine: number;
totalLines: number;
/**
* Current repository guidance for this path; absent for logs, in a
* workspace without a repository or when disabled; null when collection
* failed (see `instructionsError`).
*/
instructions?: RepositoryInstructions | null;
/** Why the guidance could not be collected; set only with `instructions: null`. */
instructionsError?: string;
/** True when `content` was cut at `READ_MAX_CHARS`. */
truncated: boolean;
};
/** `read_file` with `encoding: 'base64'`. */
export type ReadFileBinaryResult = {
path: string;
encoding: 'base64';
/** The file's bytes, base64. */
content: string;
bytes: number;
};
/** `read_file` of a png, jpeg, gif or webp image: the model gets it as an image part. */
export type ReadFileImageResult = {
path: string;
type: 'image';
mediaType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp';
bytes: number;
/**
* The run artifact holding the image (`context.artifacts`): the model
* gets the bytes through its marker, so the tool step and the
* checkpoints keep this id, never the image.
*/
artifactId: string;
};
export type WriteFileResult = {
path: string;
bytes: number;
};
export type EditFileResult = {
path: string;
replacements: number;
};
export type MultiEditResult = {
path: string;
/** How many edits were applied (all of them). */
edits: number;
/** Replacements of all edits together. */
replacements: number;
};
export type GrepMatch = {
path: string;
line: number;
text: string;
};
/** The program `grep` searched with: its regular expression syntax differs. */
export type GrepEngine = 'ripgrep' | 'git-grep' | 'grep';
export type GrepResult = {
matches: GrepMatch[];
/** True when more matches exist than were returned. */
truncated: boolean;
engine: GrepEngine;
};
export type ListFilesResult = {
files: string[];
truncated: boolean;
};
export type BashResult = {
/** The command's exit status (124 or 137 after a timeout). */
exitCode: number;
/**
* Stdout, whole when it has at most `EXCERPT_HEAD_BYTES` +
* `EXCERPT_TAIL_BYTES` bytes, else its start and end around a
* `[... <n> bytes cut, full output in <stdoutLog>]` line.
*/
stdout: string;
stderr: string;
/** True when the middle of stdout was cut (the whole of it is in `stdoutLog`). */
stdoutTruncated: boolean;
stderrTruncated: boolean;
/** Bytes the command wrote to stdout. */
stdoutBytes: number;
stderrBytes: number;
/** `~/.chamvi/out/<id>.stdout.log`: the whole stdout, readable with read_file, grep or bash. */
stdoutLog: string;
stderrLog: string;
/** The working directory the next call starts in (`/workspace/...` inside the workspace). */
cwd: string;
/**
* True when a log passed `outputLogMaxBytes`: the call was killed with
* its jobs, like a timeout, and the log keeps the first bytes up to the cap.
*/
outputCapped: boolean;
timedOut: boolean;
durationMs: number;
};
/** What `bash` returns for `background: true`. */
export type BashJobResult = {
/** The job id for bash_output and bash_kill. */
job: string;
status: 'running';
/** `~/.chamvi/jobs/<id>/output`: stdout and stderr of the job. */
outputLog: string;
};
/**
* `running`; `exited` (with `exitCode`); `killed` by bash_kill; `lost` when
* it ended without an exit status (its container restarted).
*/
export type BashJobStatus = 'running' | 'exited' | 'killed' | 'lost';
export type BashOutputResult = {
job: string;
status: BashJobStatus;
exitCode?: number;
/** Output from `offset` on, at most `JOB_OUTPUT_MAX_BYTES` bytes. */
output: string;
offset: number;
/** Pass it as `offset` to read on. */
nextOffset: number;
/** Bytes of output so far. */
size: number;
/** True when more output follows `nextOffset`. */
truncated: boolean;
/**
* True when the output passed `outputLogMaxBytes`: the job was killed
* with every process it started (status `killed`) and its output cut
* back to the cap.
*/
outputCapped: boolean;
};
export type BashKillResult = {
job: string;
status: BashJobStatus;
exitCode?: number;
};
export type GlobResult = {
/** Relative to the workspace root, sorted. */
files: string[];
truncated: boolean;
};
export type GitDiffResult = {
/** `git status --short`. */
status: string;
diff: string;
truncated: boolean;
};const READ_MAX_LINES: 2_000;
const READ_MAX_CHARS: 65_536;
const SEARCH_MAX_RESULTS: 500;
const LIST_MAX_RESULTS: 5_000;
const LINE_MAX_CHARS: 500;
const OUTPUT_LOG_MAX_BYTES: 67_108_864; // 64 MiB, the default outputLogMaxBytesRepository instructions
CodingToolsOptions.repositoryInstructions defaults to true. Ordinary UTF-8 read_file results of a repository-backed workspace add the optional ReadFileResult.instructions?: RepositoryInstructions | null field (a repo-less workspace runs no collector and omits it). Each read collects guidance for the file's root and ancestors, including include expansion, scopes, hashes, parents, diagnostics and complete; the sandbox collector defines ordering, bounds and failure behavior. An incomplete collection is still visible with complete: false; an inspection/transport error (a missing utility, a stray stderr line, an exec timeout) answers the file with instructions: null and instructionsError naming the reason, never an empty context presented as complete; a cancelled run still rejects. Resolve missing guidance that could change the task before proceeding.
codingTools(workspaces, { repositoryInstructions: false }) omits the field. Binary/base64 reads, image reads and HOME log reads always omit it. The coding option is independent of createWorkspaceManager({ repositoryInstructions: false }): the manager's flag controls root collection on create and the presence of read_repository_instructions, while coding's flag controls text-read attachments. Both default on; set both off to disable both forms of context delivery. Neither restricts filesystem access.
read_file, grep, glob, list_files, git_diff, bash and bash_output declare trust: { taint: true }: their results taint the run in every workspace, repo-less ones included, since a repo-less workspace can fetch arbitrary content (curl, git clone). write_file, edit_file, multi_edit and bash_kill stay unclassified, and shell execution is never gated.
There is no cross-call cache: new reads reflect current worktree instructions, while previous tool results remain in steps and checkpoints through pauses and restarts. Before direct edits or shell work in a new subtree, request its context through read_file or the manager's read_repository_instructions tool. Repository guidance or a system prompt grants no operator authorization, permissions, credentials, skill installation or publication rights. write_file, edit_file, multi_edit and arbitrary bash do not enforce instruction scope, and bash bypasses file-tool-only enforcement. Discovery's observed symlink, special-file, .git and escape refusal is best-effort; race-free confinement remains #92.
ICodingBackend
The contract for something that solves a coding task in a workspace with its own tool loop. Only the contract ships; backends (the own tools in a nested loop, Claude Code) are planned.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IWorkspace } from '@chamvi/sandbox';
export type CodingBudget = {
maxSteps?: number;
maxTokens?: number;
timeoutMs?: number;
};
export type CodingTask = {
/** The workspace to work in; the backend never disposes it. */
workspace: IWorkspace;
/** What to do, in plain language. */
task: string;
budget?: CodingBudget;
signal?: AbortSignal;
};
export type CodingResult = {
/** `done` when the task is solved, `stuck` when the backend gave up. */
status: 'done' | 'stuck';
summary: string;
/** The workspace's changes as a unified diff. */
diff: string;
};
/**
* Something that solves a coding task in a workspace with its own tool loop
* (the own coding tools, Claude Code, ...).
*/
export interface ICodingBackend {
code(task: CodingTask): Promise<CodingResult>;
}