OpenCode-CLI-Controller
通过本地 Web 服务器 API 控制 Open Code CLI 的强大技能。允许在本地网络中远程执行命令、管理会话以及自动生成代码。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install totalclaw:totalclaw~malek262-opencode-api-control-skillcURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~malek262-opencode-api-control-skill/file -o malek262-opencode-api-control-skill.md## 概述(中文)
通过本地 Web 服务器 API 控制 Open Code CLI 的强大技能。允许在本地网络中远程执行命令、管理会话以及自动生成代码。
## 原文
# OpenCode CLI API Control
> [!IMPORTANT]
> **OPERATIONAL GUIDELINES**:
> While you may use `ls` or basic file system checks to verify that files/directories exist, you are **EXPLICITLY PROHIBITED** from reading or modifying the project's source code files directly.
> Your primary channel for task execution and progress monitoring is the **OpenCode API and the provided scripts**.
## Overview
This skill provides a set of tools to programmatically interface with the Open Code CLI through its local web server API. It enables you to act as a **Supervisor/Orchestrator** who directs OpenCode to handle all coding, file operations, and quality checks.
## Core Mandate: Orchestrator vs. Executor
- **You are NOT the Coder**: You do not write or verify code directly. OpenCode handles the implementation.
- **You are the Orchestrator**: You send high-level instructions to OpenCode, monitor its progress, and report the outcome to the user.
- **Trust the System**: OpenCode is responsible for its own file operations. Your job is to wait for it to finish and then check the *status* and *diff summary*, not the file contents.
## When to Use
- User requests creating or managing projects through OpenCode
- User asks for coding tasks, debugging, or code analysis via OpenCode
- User wants AI-powered development with specific providers/models
- User needs to manage multiple OpenCode sessions or monitor tasks
## Prerequisites
1. OpenCode server running (Preferred: `bash ./scripts/start_server.sh`)
2. Configuration file exists: `./config.json`
3. Required scripts in `./scripts/` directory
## Configuration
Read settings from `./config.json`:
```bash
BASE_URL=$(jq -r '.base_url' ./config.json)
PROJECTS_DIR=$(jq -r '.projects_base_dir' ./config.json)
```
## Important Agent Responsibilities
### Your Role as Orchestrator
You are the **supervisor and communication bridge** between the user and OpenCode.
**Operational Boundaries**:
- ❌ **NEVER** read or edit the code files generated by OpenCode directly for development tasks.
- ❌ **NEVER** try to fix or verify code logic by inspecting the project files yourself.
- ✅ **MAY** use `ls` or simple directory checks only to confirm file existence if necessary.
- ⚠️ **PREFER** using the provided scripts and API for all project-related information.
**Required Workflow**:
- ✅ **PRIMARY**: Use `monitor_session.sh` or `check_status.sh` to track progress.
- ✅ **PRIMARY**: Use `get_diff.sh` to see a summary of what was changed.
- ✅ **ALWAYS** report the results based on the API response or script output.
- ✅ **TRUST** OpenCode's implementation of the requested features.
### Server Initialization Wait
**CRITICAL**: After starting OpenCode web server, it takes **10-15 seconds** to fully initialize. You **MUST** verify server readiness before sending any requests.
**Correct initialization sequence**:
```bash
# Start server using the robust backgrounding script
bash ./scripts/start_server.sh
# 3. Now safe to proceed with operations
bash ./scripts/update_providers.sh
# ... continue workflow
```
**Never** send requests immediately after starting the server - always verify health first.
### Intelligent Task Monitoring
For long-running tasks, use **smart monitoring** strategies:
**Option 1: Event-based monitoring (Recommended)**
```bash
# Start task
bash ./scripts/send_message.sh "Complex task" &
# Monitor events (blocks until completion)
bash ./scripts/monitor_session.sh
```
**Option 2: Intelligent polling**
```bash
# For environments where event streaming is unreliable
bash ./scripts/send_message.sh "Build application"
# Smart polling with exponential backoff
SLEEP_TIME=2
MAX_SLEEP=30
while true; do
STATUS=$(bash ./scripts/check_status.sh)
if [ "$STATUS" = "idle" ]; then
echo "✓ Task completed"
break
elif [ "$STATUS" = "busy" ]; then
echo "⟳ Still working... (checking again in ${SLEEP_TIME}s)"
sleep $SLEEP_TIME
# Increase wait time (but cap at MAX_SLEEP)
SLEEP_TIME=$((SLEEP_TIME < MAX_SLEEP ? SLEEP_TIME + 2 : MAX_SLEEP))
else
echo "⚠ Unexpected status: $STATUS"
break
fi
done
```
**Option 3: Timeout-based waiting**
```bash
# For predictable task durations
bash ./scripts/send_message.sh "Quick task"
# Wait reasonable time before checking
sleep 10
# Then check once
if [ "$(bash ./scripts/check_status.sh)" = "idle" ]; then
bash ./scripts/get_diff.sh
fi
```
**Anti-patterns to AVOID**:
- ❌ Checking status every 1-2 seconds (wastes resources)
- ❌ Reading files repeatedly to see if task is done
- ❌ Using `ls` or file system checks for progress
- ❌ Making multiple API calls without waiting
**Best practices**:
- ✅ Use `monitor_session.sh` for real-time updates
- ✅ Use exponential backoff for polling (start 2s, increase to 30s)
- ✅ Estimate task duration and wait appropriately
- ✅ Only check final results after confirmation of completion
- ✅ Let OpenCode agents work independently - don't micromanage
## Task Initiation Protocol
Before starting any task (new project, code analysis, debugging, etc.), **ask the user in ONE message**:
> I'll help you with that. Two quick questions:
> 1. **Provider**: Use default from config, or specify a provider (opencode, anthropic, gemini, etc.)?
> 2. **Monitoring**:
> - **Standard** (recommended): Send task → wait for completion summary → notify you when done (saves tokens)
> - **Real-time**: Show live progress, file edits, and events as they happen (uses more tokens)
>
> How would you like to proceed?
**Default if not specified**: Use config defaults + Standard mode.
### Why This Matters
- **Standard mode**: Uses `send_message.sh` → waits → shows final summary. Efficient for most tasks.
- **Real-time mode**: Uses `monitor_session.sh` with event streaming. Good for long/complex tasks where you want visibility.
### Example Response Handling
- "Default provider, standard mode" → Proceed immediately
- "Use Claude Sonnet, real-time" → Run `select_provider.sh` then `monitor_session.sh`
- "Gemini Pro" → Find provider + ask monitoring preference if not specified
---
### Task Completion Verification
When a task completes, get summary via:
```bash
# Get file changes summary (not individual files)
bash ./scripts/get_diff.sh
# Output example:
# added: src/App.tsx (+120/-0)
# modified: package.json (+5/-2)
# added: src/components/Dashboard.tsx (+89/-0)
```
This gives you all information needed to report to the user without reading actual file contents.
**Only read specific files if**:
- User explicitly asks to see code
- User requests explanation of specific implementation
- Debugging a reported issue
Otherwise, trust the diff summary and OpenCode's implementation.
## Core Workflow
### Step 1: Verify Server
```bash
# Check health
curl -s "$BASE_URL/global/health" | jq
# Expected: {"healthy": true, "version": "..."}
```
### Step 2: Update Providers Cache
```bash
# Run provider update script
bash ./scripts/update_providers.sh
```
This caches **only connected providers** to `./providers.json`.
### Step 3: Create or Select Project
**New Project**:
```bash
PROJECT_NAME="dashboard-app"
PROJECT_PATH="$PROJECTS_DIR/$PROJECT_NAME"
mkdir -p "$PROJECT_PATH"
```
**Existing Project**:
```bash
PROJECT_NAME="existing-app"
PROJECT_PATH="$PROJECTS_DIR/$PROJECT_NAME"
# Verify exists
[ -d "$PROJECT_PATH" ] || { echo "Project not found"; exit 1; }
```
### Step 4: Create Session
Create a session in the project directory using the provided script:
```bash
SESSION_ID=$(bash ./scripts/create_session.sh "$PROJECT_PATH" "Session Title")
```
### Step 5: Save Session State
```bash
# Use state management script
bash ./scripts/save_state.sh "$SESSION_ID" "$PROJECT_PATH"
```
### Step 6: Send Message
Use the provided script to send prompts to the AI:
```bash
# Use defaults from config
bash ./scripts/send_message.sh "Your prompt here"
# Or use a specific provider and model