Orchestrate deterministic MCP tool calls from one workflow script with `tool()`. Use when the task is a fixed pipeline of tool calls whose control flow can be written as JavaScript and must be reproducible on resume. Use ultracode instead when stages need independent LLM agents or judgment between steps.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Codemode?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/konghayao-codemode)
---
name: codemode
description: >
Orchestrate deterministic MCP tool calls from one workflow script with `tool()`.
Use when the task is a fixed pipeline of tool calls whose control flow can be
written as JavaScript and must be reproducible on resume. Use ultracode instead
when stages need independent LLM agents or judgment between steps.
userInvocable: true
argumentHint: "[tool pipeline description or /codemode]"
---
# Codemode: Deterministic Tool Pipelines
Use the **Workflow** tool through `ToolSearch` and `ToolInvoke`. The run executes a
JavaScript script; `tool(name, args)` calls a real MCP tool through the host, and
`agent(prompt)` delegates judgment to an LLM agent. Prefer `tool()` for work a
deterministic program can express: reads, greps, shell commands, web fetches, and
custom MCP tools. Prefer `agent()` when a step needs interpretation or decisions.
Do not use codemode for a single tool call that you can run directly, and do not
replace a required multi-agent workflow (`ultracode`) with a tool-only script.
## Script shape
```js
export const meta = { name: 'audit', description: 'Collect and compare files' }
// `Glob` returns text: one path per line, `No files found.`, or a listing
// followed by an unnumbered `[Output truncated: ...]` note.
const listing = await tool('Glob', { pattern: 'src/**/*.rs' })
if (listing.trim() === 'No files found.') return { count: 0, verdict: 'no files matched' }
if (listing.split('\n').some(line => line.startsWith('[Output truncated:'))) {
throw new Error('Glob hit the result limit; rerun with a narrower pattern')
}
const targets = listing.split('\n').filter(Boolean)
// `Read` returns `cat -n` text today (no raw `structuredContent`). Strip the
// `^\s*\d+\t` prefix and drop a trailing empty numbered line before counting.
const stripRead = (text) => text
.split('\n')
.filter(line => !line.startsWith('[Output truncated:') && !line.startsWith('[Full output saved'))
.map(line => line.replace(/^\s*\d+\t/, ''))
.filter((line, index, lines) => !(index === lines.length - 1 && line === ''))
const results = await parallel(targets.map(file => async () => {
try {
const text = await tool('Read', { file_path: file })
// Status lines are unnumbered; match them on the raw text first.
if (text === '[EMPTY FILE]' || text.startsWith('[EMPTY FILE]\n')) {
return { file, lines: 0 }
}
if (text.split('\n').some(line => line.startsWith('[Output truncated:'))) {
return { file, truncated: true }
}
return { file, lines: stripRead(text).length }
} catch (error) {
// Keep the typed failure code instead of letting parallel() drop it.
// `parallel` turns an uncaught throw into `null` for that arm.
if (!error.code) throw error
return { file, error: error.code }
}
}))
const counts = results.filter(result => result && !result.error)
const unread = results
.map((result, index) =>
result && !result.error ? null : { file: targets[index], error: result?.error ?? 'unexpected_error' },
)
.filter(Boolean)
const verdict = await agent(
`Rank the largest files and flag anomalies. ` +
`Line counts: ${JSON.stringify(counts)}. Unread files: ${JSON.stringify(unread)}`,
{ label: 'rank' },
)
return { verdict, counts, unread }
```
Available hooks: `agent`, `parallel`, `pipeline`, `phase`, `log`, `workflow`, plus
`tool`. A run is always a background workflow run: report the `run_id`, wait for the
completion reminder, and read `state.json` or `outputs/` for full results.
## Calling tools
```js
const result = await tool('Read', { file_path: '/abs/path' })
```
- Pass an **effective tool name**: the same name the current model sees (for builtin
tools, the original name such as `Read`; for external servers, the exposed name).
Deferred tools must first be discovered with `ToolSearch`; the host resolves names
against the same session-visible catalog.
- Host-only meta tools (`Agent`, `AskUserQuestion`, `TodoWrite`, `SkillTool`,
`ToolSearch`, `ToolInvoke`) and the workflow's own tools are not callable from a
script. Expect `tool_not_found` or `tool_unavailable`.
- `arguments` must be a plain object or omitted. Schema validation belongs to the MCP
server; do not restate or pre-validate a schema in the script.
- The return value is `structuredContent` when present, otherwise the text content.
Results are **not truncated**. Text-only tools keep their formatted text: `Glob`
returns paths joined by newlines and `Grep` returns matching lines, so parse the
string (for example `listing.split('\n').filter(Boolean)`) before iterating it.
`Read` is text-only with `cat -n` line prefixes today — there is no raw
`structuredContent` for file bytes; strip `^\s*\d+\t` before content parsing.
- Failures throw a typed `WorkflowToolError` with `code`, `tool`, `message`, and
optional `details`. Catch it when a failure is expected:
```js
try {
await tool('Bash', { command: 'test -f marker', description: 'probe marker' })
} catch (error) {
if (error.code !== 'tool_error') throw error
log('marker missing; continuing')
}
```
Codes: `tool_not_found`, `invalid_arguments`, `tool_unavailable`, `policy_denied`,
`approval_unavailable`, `not_executed`, `tool_error`, `protocol_error`,
`task_accepted`, `outcome_unknown`, `cancelled`.
## Approvals, limits, and safety
- Every call passes the host's existing permission and approval surface. A background
run that cannot obtain an approval waits until the approval times out and then fails
closed with `approval_unavailable` or `policy_denied`; the tool is not executed.
- `tool()` calls do not consume `maxConcurrency` slots, `maxAgents`, `maxToolCalls`, or
token budgets. They run with no script-level concurrency cap. Host `budget` /
`budgetTotal` / `maxToolCalls` apply to agent stages, not to script `tool()` calls.
- Determinism: `Date.now`, `new Date`, and `Math.random` throw `NonDeterministicError`.
Pass clocks or seeds through `args` when the script needs them.
- `args` defaults to `undefined` when omitted (not `{}`). Resume-only restores prior
`args` from `state.json`; `script` + `resumeFromRunId` does not restore args unless
you pass them again.
- The script is **not a security boundary**: it can use Node built-ins such as
`process` and `require`. `tool()` routes MCP calls through host approval; it does not
sandbox the script or grant new permissions. Do not put secrets in the workflow
`script`, `args`, or tool arguments — they are persisted in `state.json` /
`tools.jsonl` under the run directory.
- `task_accepted` means the target accepted asynchronous work and v1 does not poll it.
Treat the side effect as unconfirmed instead of assuming it did not happen.
## Resume and observability
- Tool results are recorded per run (`tools.jsonl`) and replayed on resume. Replay
stops at the first mismatch (sequence, tool name, or arguments); later calls run live.
- `log(...)` appears only under `workflow://runs/<id>/events`, not in `state.json`,
`outputs/`, or the completion reminder.
- `unknownSideEffects: true` in the run state means at least one tool call had no
settled result (interrupted, accepted, or outcome unknown). Verify external effects
before trusting the run; a resumed run may retry an unsettled call.
- Long strings in the `return` value (including a top-level string or array items) are
externalized to `outputs/`; a `${label}` token in `state.json` is a reference, not the
literal result. The completion reminder may still inline the return value — do not
treat externalize as a notification truncate.
- `writeIntent` (`read_only` / write footprint) and `resumeFromRunId` shapes live on the
Workflow tool schema; resume-only restores script/args from `state.json`, while a new
`script` plus resume replays the tool journal against the new script.
## Session scope
- Prefer the **main interactive session**. Subagent catalogs and `peri --print` often
omit `Workflow`. Independent `peri mcp-start` may list the tools before the session
runtime is bound and then fail with `workflow runtime is not bound`. Direct
`workflow/start` without a host does not inject `tool()`.
## Troubleshooting (source builds)
- First `Workflow` call fails with "validated workflow artifact … unavailable": the
host started without a sidecar. From the repo root run `mise run sidecar:build`, then
relaunch via `mise run dev` (exports `PERI_WORKFLOW_ARTIFACT_DIR` only when the
content-id matches `WORKFLOW_ENTRY_SHA256`’s first 12 hex chars; stale sibling
dirs are ignored) or set `PERI_WORKFLOW_ARTIFACT_DIR` to
`dist/workflow-sidecar/peri-resources/workflow/<content-id>` **before** starting peri.
Setting the env after the process is running has no effect.
- Release installs ship `peri-resources/workflow/<content-id>` next to the binary; source
`target/debug/peri` does not, unless you export the env or install that layout yourself.
## Checklist
- The pipeline is expressible as deterministic control flow, not agent judgment.
- Every tool name is an effective name visible to this session; deferred ones were
discovered first.
- Expected failures are caught and classified, not swallowed.
- The final `return` contains the evidence needed for the handoff; large values are
allowed and will be externalized.
- The report states the `run_id` and whether the run reported `unknownSideEffects`.