skill-system-tmux

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Skill System Tmux

技能系统:Tmux

Route shell commands through tmux when they risk timeout, require persistence, or need interactive terminal access. This skill provides decision heuristics and session management conventions — not tmux tutorials.
当Shell命令存在超时风险、需要持久化运行或需要交互式终端访问时,通过Tmux来执行。本技能提供决策规则和会话管理规范——而非Tmux教程。

Decision Matrix

决策矩阵

Use this matrix to decide: direct bash vs tmux.
ConditionRouteExamples
Estimated time > 60stmux
git clone <large>
,
npm install
,
docker build
, training scripts
Command does not self-terminatetmux
npm run dev
,
python app.py
,
jupyter notebook
Requires TUI or interactive inputtmux
vim
,
htop
,
pudb
,
claude
Parallel isolated execution neededtmuxMultiple agents, concurrent test suites
Remote execution over SSHtmuxCommands that must survive connection drops
Atomic, non-interactive, fast (<30s)direct bash
ls
,
grep
,
git status
,
cat
,
mkdir
Single-shot with expected outputdirect bash
python script.py
(fast),
git diff
,
npm test
(short)
Default: direct bash. Only route to tmux when a condition above is met.
使用此矩阵来决定:直接执行bash vs 通过Tmux执行
条件执行方式示例
预计执行时间 > 60秒Tmux
git clone <大型仓库>
,
npm install
,
docker build
, 训练脚本
命令不会自行终止Tmux
npm run dev
,
python app.py
,
jupyter notebook
需要TUI或交互式输入Tmux
vim
,
htop
,
pudb
,
claude
需要并行隔离执行Tmux多Agent、并发测试套件
通过SSH远程执行Tmux断开连接后仍需继续的命令
原子性、非交互式、快速(<30秒)直接bash
ls
,
grep
,
git status
,
cat
,
mkdir
单次执行且有预期输出直接bash
python script.py
(快速执行),
git diff
,
npm test
(短时间)
默认:直接执行bash。 仅当满足上述任一条件时,才通过Tmux执行。

Time Estimation Heuristics

时间估算规则

Commands likely to exceed timeout:
  • Git operations:
    clone
    (large repos),
    push
    (large payloads),
    checkout
    (>1GB working tree)
  • Package install:
    npm install
    ,
    pip install
    (many deps),
    cargo build
  • Build tools:
    docker build
    ,
    make
    (large projects),
    webpack
    (production builds)
  • Data processing: Training scripts, preprocessing pipelines, large file transfers
  • CI/test suites: Full test runs on large projects
可能超时的命令类型:
  • Git操作
    clone
    (大型仓库)、
    push
    (大负载)、
    checkout
    (工作区>1GB)
  • 包安装
    npm install
    pip install
    (依赖众多)、
    cargo build
  • 构建工具
    docker build
    make
    (大型项目)、
    webpack
    (生产构建)
  • 数据处理:训练脚本、预处理流水线、大文件传输
  • CI/测试套件:大型项目的完整测试运行

Session Naming Convention

会话命名规范

Use project-context naming for human readability:
Format: {project}-{purpose}

Agent-created sessions (MANDATORY prefix):
  oc-{purpose}        # e.g., oc-audit, oc-verify, oc-render
  oc-{project}-{task}  # e.g., oc-skills-build, oc-subproject-test

User/infra sessions (no prefix required):
  postgres-dev
  frontend-watch
  ml-training
Rules:
  • Agent-created sessions MUST use
    oc-
    prefix
    — enables bulk identification and cleanup
  • Lowercase, hyphens for separators (not underscores)
  • Include project context for multi-project environments
  • Reuse well-known
    oc-
    session names when they exist (e.g.,
    oc-exp-runner
    )
  • If you inherit a legacy agent session without the prefix, rename it to
    oc-*
    before reuse
  • Never create sessions with numeric-only names (e.g.,
    531
    )
使用项目上下文命名以提升可读性:
格式:{项目名}-{用途}

Agent创建的会话(必须加前缀):
  oc-{用途}        # 示例:oc-audit, oc-verify, oc-render
  oc-{项目名}-{任务}  # 示例:oc-skills-build, oc-subproject-test

用户/基础设施会话(无需前缀):
  postgres-dev
  frontend-watch
  ml-training
规则:
  • Agent创建的会话必须使用
    oc-
    前缀
    ——便于批量识别和清理
  • 全部小写,使用连字符分隔(而非下划线)
  • 多项目环境中需包含项目上下文
  • 若已有知名的
    oc-
    会话名称,可复用(如
    oc-exp-runner
  • 若继承了无前缀的旧Agent会话,复用前需重命名为
    oc-*
    格式
  • 禁止创建纯数字名称的会话(如
    531

Core Patterns

核心模式

Pattern 1: Fire and Forget (Background Task)

模式1:触发即遗忘(后台任务)

For long-running commands where you don't need real-time output:
bash
undefined
适用于无需实时输出的长时间运行命令:
bash
undefined

Kill any existing session with same name, then start fresh

终止同名的现有会话,然后启动新会话

tmux kill-session -t {session} 2>/dev/null || true tmux new-session -d -s {session} bash -c '{command}'

Using `interactive_bash` tool:
tmux_command: new-session -d -s {session} tmux_command: send-keys -t {session} "{command}" Enter
undefined
tmux kill-session -t {session} 2>/dev/null || true tmux new-session -d -s {session} bash -c '{command}'

使用`interactive_bash`工具:
tmux_command: new-session -d -s {session} tmux_command: send-keys -t {session} "{command}" Enter
undefined

Pattern 2: Persistent Server

模式2:持久化服务器

For dev servers or processes that must keep running:
tmux_command: new-session -d -s {session}
tmux_command: send-keys -t {session} "{command}" Enter
Check if running later:
tmux_command: has-session -t {session}
适用于需持续运行的开发服务器或进程:
tmux_command: new-session -d -s {session}
tmux_command: send-keys -t {session} "{command}" Enter
后续检查运行状态:
tmux_command: has-session -t {session}

Pattern 3: Output Capture

模式3:输出捕获

Read what a tmux session has produced:
tmux_command: capture-pane -p -t {session}
For longer history (last 1000 lines):
tmux_command: capture-pane -p -t {session} -S -1000
读取Tmux会话的输出内容:
tmux_command: capture-pane -p -t {session}
捕获更长历史(最近1000行):
tmux_command: capture-pane -p -t {session} -S -1000

Pattern 4: Readiness Detection

模式4:就绪检测

After sending a command, poll to detect completion:
  1. Capture the pane output
  2. Look for shell prompt at end of output (regex:
    /(\\$|>|#)\s*$/m
    )
  3. If prompt appears, command has finished
  4. If no prompt after expected duration, assume still running or hung
发送命令后,轮询检测是否执行完成:
  1. 捕获面板输出
  2. 检查输出末尾是否有Shell提示符(正则:
    /(\\$|>|#)\s*$/m
  3. 若出现提示符,说明命令已完成
  4. 若超过预期时间仍未出现提示符,判定为仍在运行或已挂起

Pattern 5: Clean Shutdown

模式5:优雅关闭

Always clean up sessions when done:
tmux_command: kill-session -t {session}
Kill-before-new pattern prevents zombie sessions:
tmux_command: kill-session -t {session}
任务完成后务必清理会话:
tmux_command: kill-session -t {session}
先终止再创建模式可避免僵尸会话:
tmux_command: kill-session -t {session}

(ignore error if doesn't exist)

(若会话不存在则忽略错误)

tmux_command: new-session -d -s {session}
undefined
tmux_command: new-session -d -s {session}
undefined

Pattern 6: Bulk Resource Reclaim

模式6:批量资源回收

Reclaim all agent-created sessions and detect stale resources. Run this when:
  • Machine feels sluggish or memory is high
  • Before/after long agent work sessions
  • User requests cleanup
Step 1: Identify agent sessions
bash
tmux list-sessions -F '#{session_name} #{session_activity}' | grep '^oc-'
Step 2: Kill all agent sessions
bash
tmux list-sessions -F '#{session_name}' | grep '^oc-' | xargs -I{} tmux kill-session -t {}
Step 3: Detect stale non-agent sessions
A session is likely stale if:
  • Last activity > 6 hours ago AND no running foreground process
  • Session has only an idle shell prompt (capture-pane shows just
    $
    or
    ╰─
    )
bash
undefined
回收所有Agent创建的会话并检测失效资源。在以下场景执行:
  • 机器运行缓慢或内存占用过高时
  • 长时间Agent工作会话前后
  • 用户请求清理时
步骤1:识别Agent会话
bash
tmux list-sessions -F '#{session_name} #{session_activity}' | grep '^oc-'
步骤2:终止所有Agent会话
bash
tmux list-sessions -F '#{session_name}' | grep '^oc-' | xargs -I{} tmux kill-session -t {}
步骤3:检测失效的非Agent会话
满足以下条件的会话大概率已失效:
  • 最后活动时间 > 6小时,且无前台运行进程
  • 会话仅包含空闲Shell提示符(捕获面板输出仅显示
    $
    ╰─
bash
undefined

List sessions with last activity timestamp

列出带最后活动时间戳的会话

tmux list-sessions -F '#{session_name} #{session_activity}'
tmux list-sessions -F '#{session_name} #{session_activity}'

Compare #{session_activity} (epoch) against current time

比较#{session_activity}(时间戳)与当前时间

Capture pane of suspects to verify idle state

捕获可疑会话的面板输出以验证空闲状态


**Step 4: Reclaim orphaned processes**
```bash

**步骤4:回收孤立进程**
```bash

Find opencode processes whose parent tmux pane was killed

查找父Tmux面板已终止的opencode进程

ps aux | grep opencode | grep -v grep
ps aux | grep opencode | grep -v grep

Check if port is held by a zombie

检查端口是否被僵尸进程占用

lsof -i :{port} 2>/dev/null
lsof -i :{port} 2>/dev/null

Force kill if needed (SIGTERM first, SIGKILL if unresponsive after 5s)

必要时强制终止(先发送SIGTERM,5秒后若未响应则发送SIGKILL)

kill {pid} && sleep 5 && kill -0 {pid} 2>/dev/null && kill -9 {pid}

**Important**: Never kill known non-agent infra sessions without explicit user confirmation. Legacy names from sibling projects should be normalized to `oc-*` before they are treated as agent-managed sessions.
kill {pid} && sleep 5 && kill -0 {pid} 2>/dev/null && kill -9 {pid}

**注意**:未经用户明确确认,禁止终止已知的非Agent基础设施会话。兄弟项目的旧命名会话应先标准化为`oc-*`格式,再视为Agent管理的会话。

Integration with Agent Tools

与Agent工具的集成

interactive_bash
Tool

interactive_bash
工具

The primary interface. Pass tmux subcommands directly (without
tmux
prefix):
undefined
主要交互接口。直接传递Tmux子命令(无需
tmux
前缀):
undefined

Create session

创建会话

tmux_command: new-session -d -s oc-my-session
tmux_command: new-session -d -s oc-my-session

Send command

发送命令

tmux_command: send-keys -t oc-my-session "npm run dev" Enter
tmux_command: send-keys -t oc-my-session "npm run dev" Enter

Read output

读取输出

tmux_command: capture-pane -p -t oc-my-session
tmux_command: capture-pane -p -t oc-my-session

Kill session

终止会话

tmux_command: kill-session -t oc-my-session
undefined
tmux_command: kill-session -t oc-my-session
undefined

bash
Tool with Timeout

带超时的
bash
工具

For commands near the timeout boundary, prefer increasing
timeout
parameter over tmux:
bash(command="npm install", timeout=300000)  # 5 min timeout
Use tmux only when:
  • Timeout cannot be reliably estimated
  • Process must persist beyond the current tool call
  • Interactive/TUI access is needed
对于接近超时阈值的命令,优先选择增加
timeout
参数而非使用Tmux:
bash(command="npm install", timeout=300000)  # 5分钟超时
仅在以下场景使用Tmux:
  • 无法可靠估算超时时间
  • 进程需在当前工具调用结束后仍保持运行
  • 需要交互式/TUI访问

Known Errors & Workarounds

已知错误与解决方法

capture-pane
blocked in
interactive_bash

capture-pane
interactive_bash
中被阻塞

Error:
'capture-pane' is blocked in interactive_bash
This is the most common tmux error. The
interactive_bash
tool blocks certain tmux subcommands (including
capture-pane
,
pipe-pane
,
save-buffer
). Always use the
Bash
tool instead
for these operations.
bash
undefined
错误信息
'capture-pane' is blocked in interactive_bash
这是最常见的Tmux错误。
interactive_bash
工具会阻塞部分Tmux子命令(包括
capture-pane
pipe-pane
save-buffer
)。此类操作务必使用
Bash
工具替代
bash
undefined

WRONG — will be blocked:

错误示例——会被阻塞:

interactive_bash: tmux_command: capture-pane -p -t oc-dev-server

interactive_bash: tmux_command: capture-pane -p -t oc-dev-server

CORRECT — use Bash tool:

正确示例——使用Bash工具:

tmux capture-pane -p -t oc-dev-server
tmux capture-pane -p -t oc-dev-server

Capture with history (last 1000 lines):

捕获历史输出(最近1000行):

tmux capture-pane -p -t oc-dev-server -S -1000
tmux capture-pane -p -t oc-dev-server -S -1000

Capture and grep for specific output:

捕获并过滤特定输出:

tmux capture-pane -p -t oc-dev-server | grep -i "error|ready|listening"

**Rule**: For any tmux read-only operation (`capture-pane`, `list-sessions`, `display-message`, `show-options`), prefer the `Bash` tool. Reserve `interactive_bash` for mutations (`send-keys`, `new-session`, `kill-session`).
tmux capture-pane -p -t oc-dev-server | grep -i "error|ready|listening"

**规则**:对于任何Tmux只读操作(`capture-pane`、`list-sessions`、`display-message`、`show-options`),优先使用`Bash`工具。仅在执行修改操作(`send-keys`、`new-session`、`kill-session`)时使用`interactive_bash`。

session not found
after kill/recreate

终止/重建会话后提示
session not found

Error:
can't find session: oc-xxx
Common when kill-before-new pattern races. Add a small guard:
bash
tmux kill-session -t oc-build 2>/dev/null || true
tmux new-session -d -s oc-build bash -c 'make all'
错误信息
can't find session: oc-xxx
通常是由于先终止再创建的模式存在竞争条件。添加简单的容错处理:
bash
tmux kill-session -t oc-build 2>/dev/null || true
tmux new-session -d -s oc-build bash -c 'make all'

duplicate session
on new-session

创建新会话时提示
duplicate session

Error:
duplicate session: oc-xxx
The session already exists. Either reuse it or kill-before-new:
bash
undefined
错误信息
duplicate session: oc-xxx
会话已存在。可选择复用或先终止再创建:
bash
undefined

Reuse (send new command to existing session):

复用(向现有会话发送新命令):

tmux send-keys -t oc-build "make clean && make all" Enter
tmux send-keys -t oc-build "make clean && make all" Enter

Or kill and recreate:

或终止后重建:

tmux kill-session -t oc-build 2>/dev/null || true tmux new-session -d -s oc-build bash -c 'make all'
undefined
tmux kill-session -t oc-build 2>/dev/null || true tmux new-session -d -s oc-build bash -c 'make all'
undefined

no server running
/ tmux not started

no server running
/ Tmux未启动

Error:
no server running on /tmp/tmux-*/default
No tmux server is running. Any
new-session
command will start one automatically:
bash
tmux new-session -d -s oc-init echo "tmux ready"
错误信息
no server running on /tmp/tmux-*/default
Tmux服务器未运行。任何
new-session
命令都会自动启动服务器:
bash
tmux new-session -d -s oc-init echo "tmux ready"

Tool Selection Quick Reference

工具选择速查

tmux subcommandUse
interactive_bash
?
Use
Bash
tool?
new-session
YesYes
send-keys
Yes (preferred)Yes
kill-session
YesYes
capture-pane
NO — blockedYes (required)
list-sessions
AvoidYes (preferred)
has-session
YesYes
pipe-pane
NO — blockedYes (required)
display-message
AvoidYes (preferred)
Tmux子命令是否使用
interactive_bash
是否使用
Bash
工具?
new-session
send-keys
是(优先)
kill-session
capture-pane
否——会被阻塞是(必须)
list-sessions
避免使用是 (优先)
has-session
pipe-pane
否——会被阻塞是 (必须)
display-message
避免使用是 (优先)

Anti-Patterns

反模式

Don'tDo Instead
Route every command through tmuxUse direct bash for fast, atomic commands
Forget to kill sessions after useAlways clean up with
kill-session
Use generic session names like
s1
Use descriptive names:
oc-project-purpose
Create agent sessions without
oc-
prefix
Always prefix:
oc-audit
,
oc-verify
,
oc-build
Poll capture-pane in tight loopsUse 1-2s intervals between polls
Start a new session without killing old oneAlways kill-before-new for same session name
Send commands without clearing the line firstSend
C-u
before commands if line might have residual input
Leave sessions running after task completesRun bulk reclaim (Pattern 6) at session end
Use
interactive_bash
for
capture-pane
Always use
Bash
tool for capture-pane
Retry blocked commands in
interactive_bash
Switch to
Bash
tool immediately
禁止操作正确做法
所有命令都通过Tmux执行快速、原子性命令直接使用bash执行
任务完成后忘记终止会话务必使用
kill-session
清理
使用
s1
这类通用会话名称
使用描述性名称:
oc-project-purpose
Agent创建的会话不带
oc-
前缀
始终添加前缀:
oc-audit
,
oc-verify
,
oc-build
频繁轮询capture-pane轮询间隔设置为1-2秒
不终止旧会话就启动新会话同名会话务必先终止再创建
发送命令前不先清空行内容若行中可能有残留输入,先发送
C-u
再发送命令
任务完成后仍保留会话运行会话结束时执行批量回收(模式6)
使用
interactive_bash
执行
capture-pane
务必使用
Bash
工具执行capture-pane
interactive_bash
中重试被阻塞的命令
立即切换为
Bash
工具

Existing Project Conventions

现有项目规范

This skill system's sibling projects may contain older tmux naming patterns, but agent-owned sessions in this repo must be normalized to
oc-*
.
  • Session name
    oc-exp-runner
    : Preferred agent-owned name for experiment execution
  • Watcher sessions: Background monitors that wake agents via
    tmux send-keys
  • machines.json
    config
    :
    tmux_session
    field defines per-machine session names
  • Kill-before-new: Standard cleanup pattern used across all experiment scripts
When working in a project with existing tmux conventions, preserve true user/infra sessions, but rename inherited agent sessions to the
oc-*
form before continuing.
skill
{
  "schema_version": "2.0",
  "id": "skill-system-tmux",
  "version": "1.0.0",
  "capabilities": ["tmux-route", "tmux-session-manage", "tmux-capture", "tmux-reclaim", "tmux-error-workaround"],
  "effects": ["proc.exec"],
  "operations": {
    "route-command": {
      "description": "Decide whether a command should use direct bash or tmux, and execute accordingly.",
      "input": {
        "command": { "type": "string", "required": true, "description": "The shell command to execute" },
        "estimated_duration": { "type": "string", "required": false, "description": "Estimated duration: short (<30s), medium (30-120s), long (>120s)" }
      },
      "output": {
        "description": "Execution result or session name for tmux-routed commands",
        "fields": { "route": "string", "session": "string", "result": "string" }
      },
      "entrypoints": {
        "agent": "Apply decision matrix from SKILL.md, then execute via bash or interactive_bash"
      }
    },
    "manage-session": {
      "description": "Create, list, kill, or check tmux sessions.",
      "input": {
        "action": { "type": "string", "required": true, "description": "Action: create, kill, list, check, capture" },
        "session_name": { "type": "string", "required": false, "description": "Target session name" }
      },
      "output": {
        "description": "Session status or captured output",
        "fields": { "status": "string", "output": "string" }
      },
      "entrypoints": {
        "agent": "Use interactive_bash with appropriate tmux subcommand"
      }
    },
    "reclaim-resources": {
      "description": "Bulk cleanup of stale agent tmux sessions and orphaned processes. Kills all oc-* sessions, detects idle non-agent sessions, and reclaims zombie processes holding ports.",
      "input": {
        "scope": { "type": "string", "required": false, "description": "Scope: agent-only (default, kills oc-* only), all-stale (includes idle non-agent sessions with user confirmation)" }
      },
      "output": {
        "description": "Summary of killed sessions and processes",
        "fields": { "sessions_killed": "array", "processes_killed": "array", "ports_freed": "array" }
      },
      "entrypoints": {
        "agent": "Follow Pattern 6 (Bulk Resource Reclaim) in SKILL.md"
      }
    }
  },
  "stdout_contract": {
    "last_line_json": false,
    "note": "Agent-executed; uses interactive_bash tool for tmux operations."
  }
}
本技能系统的兄弟项目可能使用旧的Tmux命名模式,但本仓库中Agent所属的会话必须标准化为
oc-*
格式。
  • 会话名称
    oc-exp-runner
    :Agent执行实验的首选名称
  • Watcher会话:通过
    tmux send-keys
    唤醒Agent的后台监视器
  • machines.json
    配置
    tmux_session
    字段定义每台机器的会话名称
  • 先终止再创建:所有实验脚本使用的标准清理模式
在遵循现有Tmux规范的项目中工作时,保留真实的用户/基础设施会话,但继承的Agent会话需先重命名为
oc-*
格式再继续使用。
skill
{
  "schema_version": "2.0",
  "id": "skill-system-tmux",
  "version": "1.0.0",
  "capabilities": ["tmux-route", "tmux-session-manage", "tmux-capture", "tmux-reclaim", "tmux-error-workaround"],
  "effects": ["proc.exec"],
  "operations": {
    "route-command": {
      "description": "Decide whether a command should use direct bash or tmux, and execute accordingly.",
      "input": {
        "command": { "type": "string", "required": true, "description": "The shell command to execute" },
        "estimated_duration": { "type": "string", "required": false, "description": "Estimated duration: short (<30s), medium (30-120s), long (>120s)" }
      },
      "output": {
        "description": "Execution result or session name for tmux-routed commands",
        "fields": { "route": "string", "session": "string", "result": "string" }
      },
      "entrypoints": {
        "agent": "Apply decision matrix from SKILL.md, then execute via bash or interactive_bash"
      }
    },
    "manage-session": {
      "description": "Create, list, kill, or check tmux sessions.",
      "input": {
        "action": { "type": "string", "required": true, "description": "Action: create, kill, list, check, capture" },
        "session_name": { "type": "string", "required": false, "description": "Target session name" }
      },
      "output": {
        "description": "Session status or captured output",
        "fields": { "status": "string", "output": "string" }
      },
      "entrypoints": {
        "agent": "Use interactive_bash with appropriate tmux subcommand"
      }
    },
    "reclaim-resources": {
      "description": "Bulk cleanup of stale agent tmux sessions and orphaned processes. Kills all oc-* sessions, detects idle non-agent sessions, and reclaims zombie processes holding ports.",
      "input": {
        "scope": { "type": "string", "required": false, "description": "Scope: agent-only (default, kills oc-* only), all-stale (includes idle non-agent sessions with user confirmation)" }
      },
      "output": {
        "description": "Summary of killed sessions and processes",
        "fields": { "sessions_killed": "array", "processes_killed": "array", "ports_freed": "array" }
      },
      "entrypoints": {
        "agent": "Follow Pattern 6 (Bulk Resource Reclaim) in SKILL.md"
      }
    }
  },
  "stdout_contract": {
    "last_line_json": false,
    "note": "Agent-executed; uses interactive_bash tool for tmux operations."
  }
}