@betrue/openclaw-claude-code-plugin 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,11 +2,7 @@
2
2
 
3
3
  **An OpenClaw plugin that orchestrates Claude Code sessions as managed background processes.**
4
4
 
5
- Claude Code Plugin lets you launch, monitor, and interact with multiple Claude Code SDK sessions directly from any OpenClaw channel (Telegram, Discord, etc.). It turns OpenClaw into a control plane for autonomous coding agents — launch tasks, stream output in real time, send follow-up messages, resume previous conversations, and catch up on missed output — all without leaving your chat interface.
6
-
7
- ---
8
-
9
- ## Demo
5
+ Launch, monitor, and interact with multiple Claude Code SDK sessions directly from any OpenClaw channel (Telegram, Discord, etc.). Turn OpenClaw into a control plane for autonomous coding agents — launch tasks, stream output in real time, send follow-up messages, resume previous conversations, and catch up on missed output — all without leaving your chat interface.
10
6
 
11
7
  [![Demo Video](https://img.youtube.com/vi/vbX1Y0Nx4Tc/maxresdefault.jpg)](https://youtube.com/shorts/vbX1Y0Nx4Tc)
12
8
 
@@ -14,98 +10,20 @@ Claude Code Plugin lets you launch, monitor, and interact with multiple Claude C
14
10
 
15
11
  ---
16
12
 
17
- ## Table of Contents
18
-
19
- - [Features](#features)
20
- - [Architecture](#architecture)
21
- - [Installation](#installation)
22
- - [Configuration](#configuration)
23
- - [Usage](#usage)
24
- - [Chat Commands](#chat-commands)
25
- - [Agent Tools](#agent-tools)
26
- - [Gateway RPC Methods](#gateway-rpc-methods)
27
- - [API Reference](#api-reference)
28
- - [Tools](#tools)
29
- - [Commands](#commands)
30
- - [RPC Methods](#rpc-methods)
31
- - [Notification System](#notification-system)
32
- - [Skill Example: Coding Agent Workflow](#skill-example-coding-agent-workflow)
33
- - [Development](#development)
34
-
35
- ---
36
-
37
13
  ## Features
38
14
 
39
- - **Multi-session management** — Run up to N concurrent Claude Code sessions (configurable), each tracked with a unique ID and human-readable name.
40
- - **Foreground / background model** — Sessions run in the background by default. Bring any session to the foreground to stream output in real time, then detach without interrupting work.
41
- - **Foreground catchup** — When you bring a session to the foreground with `claude_fg`, any output produced while it was in the background is displayed under a "📋 Catchup (N missed outputs):" header before live streaming begins, so you never miss anything.
42
- - **Multi-turn conversations** — Launch sessions in multi-turn mode to send follow-up messages, refine instructions, or have iterative dialogues with a running agent.
43
- - **Session resume & fork** — Resume any completed session from where it left off, or fork it into a new branch of conversation.
44
- - **Real-time notifications** — Completion alerts, session-limit warnings, long-running session reminders, and live tool-use indicators delivered to your chat.
45
- - **Channel propagation** — `claude_launch`, `claude_fg`, and `claude_bg` accept an optional `channel` parameter (e.g. `"telegram:123456789"`) so notifications are routed to the correct user channel instead of falling back to `"unknown"`.
46
- - **Waiting-for-input wake events** — When any session (single or multi-turn) becomes idle and waiting for input, an `openclaw system event` is fired to wake the orchestrator. Uses end-of-turn detection for multi-turn results plus a 15-second safety-net timer. A `waitingForInputFired` guard prevents duplicate events.
47
- - **Background visibility** — Even when sessions run in the background, users see `🔔 Claude asks:` when the agent needs input and `↩️ Responded:` when a follow-up is sent — the full conversation stays visible in-channel.
48
- - **Session metrics** — Per-session tracking, session counts by status, average duration, and notable-session reporting (internally tracked).
49
- - **Triple interface** — Every operation is available as a chat command (for humans), an agent tool (for the OpenClaw AI), and a gateway RPC method (for external systems).
50
- - **Automatic cleanup** — Completed sessions are garbage-collected after 1 hour; persisted session IDs survive for resume support (up to a configurable cap).
51
- - **Agent event triggers** — When a session completes or becomes idle waiting for input, an OpenClaw system event is fired so the AI agent can immediately process the result or provide follow-up instructions.
52
-
53
- ---
54
-
55
- ## Architecture
56
-
57
- ```
58
- ┌─────────────────────────────────────────────────────┐
59
- │ index.ts │
60
- │ (Plugin entry point) │
61
- │ Registers tools, commands, RPC methods, service │
62
- └──────────────┬──────────────────────────────────────┘
63
-
64
- ┌────────┼─────────────────┐
65
- │ │ │
66
- ▼ ▼ ▼
67
- Tools Commands Gateway RPC
68
- (8) (8) (5 methods)
69
- │ │ │
70
- └────────┼─────────────────┘
71
-
72
-
73
- ┌─────────────┐ ┌────────────────────┐
74
- │ shared.ts │────▶│ SessionManager │
75
- │ (globals, │ │ (spawn, resolve, │
76
- │ helpers) │ │ kill, cleanup, │
77
- │ │ │ metrics, persist)│
78
- └─────────────┘ └────────┬───────────┘
79
-
80
- ┌────────┴───────────┐
81
- │ Session │
82
- │ (Claude SDK │
83
- │ query() wrapper, │
84
- │ message stream, │
85
- │ abort, output) │
86
- └────────────────────┘
87
-
88
- ┌────────┴───────────┐
89
- │ NotificationRouter │
90
- │ (foreground │
91
- │ streaming, │
92
- │ catchup display, │
93
- │ completion, │
94
- │ session-limit, │
95
- │ long-run remind) │
96
- └────────────────────┘
97
- ```
98
-
99
- ### Key Components
100
-
101
- | Component | File | Responsibility |
102
- |---|---|---|
103
- | **Session** | `src/session.ts` | Wraps the Claude Agent SDK `query()` call. Manages the async message stream, output buffering (last 200 blocks), abort control, multi-turn `MessageStream`, idle timeouts, waiting-for-input detection (end-of-turn + 15s safety-net timer with `waitingForInputFired` guard), and event callbacks (`onOutput`, `onToolUse`, `onComplete`, `onSessionLimitReached`). |
104
- | **SessionManager** | `src/session-manager.ts` | Manages the pool of active sessions. Enforces `maxSessions`, generates unique names, wires notification callbacks, persists Claude session IDs for resume, records metrics, triggers agent events on completion and waiting-for-input, and runs periodic garbage collection. |
105
- | **NotificationRouter** | `src/notifications.ts` | Routes events to the right chat channels. Debounces foreground text streaming (500ms), shows compact tool-use indicators, sends completion/failure/session-limit notifications, foreground catchup display, and periodically checks for sessions running longer than 10 minutes. |
106
- | **Gateway** | `src/gateway.ts` | Exposes 5 JSON-RPC methods for external/programmatic access. |
107
- | **Shared** | `src/shared.ts` | Global singletons (`sessionManager`, `notificationRouter`, `pluginConfig`), helper functions (name generation, duration formatting, session listing, stats formatting), and channel resolution logic. |
108
- | **Types** | `src/types.ts` | TypeScript interfaces: `SessionConfig`, `ClaudeSession`, `PluginConfig`, `SessionStatus`, `PermissionMode`. |
15
+ - **Multi-session management** — Run up to N concurrent sessions (configurable), each with a unique ID and human-readable name
16
+ - **Foreground / background model** — Sessions run in the background by default; bring any session to the foreground to stream output in real time
17
+ - **Foreground catchup** — When foregrounding, missed background output is displayed before live streaming begins
18
+ - **Multi-turn conversations** — Sessions are multi-turn by default; send follow-up messages, refine instructions, or have iterative dialogues with a running agent. Set `multi_turn_disabled: true` for fire-and-forget sessions
19
+ - **Session resume & fork** — Resume any completed session or fork it into a new branch of conversation
20
+ - **Pre-launch safety checks** — Four mandatory guards (autonomy skill, heartbeat config, HEARTBEAT.md, agentChannels mapping) ensure every agent is properly configured before spawning sessions
21
+ - **Real-time notifications** — Completion alerts, budget exhaustion warnings, long-running reminders, and live tool-use indicators
22
+ - **Background visibility** — See `🔔 Claude asks:` and `↩️ Responded:` in-channel even when sessions run in the background
23
+ - **Waiting-for-input wake events** — `openclaw system event` fired when sessions become idle, waking the orchestrator agent
24
+ - **Multi-agent support** — Route notifications to the correct agent/chat via `agentChannels` workspace mapping with longest-prefix matching
25
+ - **Triple interface** — Every operation available as a chat command, agent tool, and gateway RPC method
26
+ - **Automatic cleanup** — Completed sessions garbage-collected after 1 hour; persisted IDs survive for resume
109
27
 
110
28
  ---
111
29
 
@@ -117,7 +35,7 @@ Claude Code Plugin lets you launch, monitor, and interact with multiple Claude C
117
35
  openclaw plugins install @betrue/openclaw-claude-code-plugin
118
36
  ```
119
37
 
120
- ### From source (git clone)
38
+ ### From source
121
39
 
122
40
  ```bash
123
41
  git clone git@github.com:alizarion/openclaw-claude-code-plugin.git
@@ -143,22 +61,55 @@ Ensure `openclaw` CLI is available in your PATH — the plugin shells out to `op
143
61
 
144
62
  ---
145
63
 
64
+ ## Pre-Launch Safety Checks
65
+
66
+ When an agent calls the `claude_launch` tool, four mandatory guards run before any session is spawned. If any check fails, the launch is blocked and an actionable error message is returned telling the agent exactly how to fix the issue. These checks are enforced only on the `claude_launch` tool — the gateway RPC `claude-code.launch` method and `/claude` chat command skip them.
67
+
68
+ ### 1. Autonomy Skill
69
+
70
+ **Checks for:** `{agentWorkspace}/skills/claude-code-autonomy/SKILL.md`
71
+
72
+ The autonomy skill defines how the agent handles Claude Code interactions (auto-respond to routine questions, forward architecture decisions to the user, etc.). Without it, the agent is told to ask the user what level of autonomy they want, then create the skill directory with `SKILL.md` and `autonomy.md`.
73
+
74
+ ### 2. Heartbeat Configuration
75
+
76
+ **Checks for:** `heartbeat` field in `~/.openclaw/openclaw.json` under `agents.list[]` for the current agent (resolved from `ctx.agentId` or `resolveAgentId(workdir)` via the `agentChannels` mapping).
77
+
78
+ Heartbeat enables automatic "waiting for input" notifications so the agent gets nudged when a Claude Code session needs attention. The expected config:
79
+
80
+ ```json
81
+ { "heartbeat": { "every": "5s", "target": "last" } }
82
+ ```
83
+
84
+ ### 3. HEARTBEAT.md Content
85
+
86
+ **Checks for:** `{agentWorkspace}/HEARTBEAT.md` with real content (not just comments, blank lines, or whitespace — validated via regex `/^(\s|#.*)*$/`).
87
+
88
+ The heartbeat file tells the agent what to do during heartbeat cycles — e.g. check for waiting Claude Code sessions, read their output, and respond or notify the user.
89
+
90
+ ### 4. agentChannels Mapping
91
+
92
+ **Checks for:** A matching entry in `pluginConfig.agentChannels` for the session's working directory, resolved via `resolveAgentChannel(workdir)`.
93
+
94
+ The workspace must be mapped to a notification channel so session events (completion, waiting-for-input, etc.) reach the correct agent/chat. Uses longest-prefix matching with trailing slash normalisation.
95
+
96
+ ---
97
+
146
98
  ## Configuration
147
99
 
148
- Configuration is defined in `openclaw.plugin.json` under `configSchema` and passed to the plugin at service start via `api.getConfig()`.
100
+ Configuration is defined in `openclaw.plugin.json` and passed to the plugin via `api.getConfig()`. Set values in `~/.openclaw/openclaw.json` under `plugins.config["openclaw-claude-code-plugin"]`.
149
101
 
150
102
  | Option | Type | Default | Description |
151
103
  |---|---|---|---|
152
- | `maxSessions` | `number` | `5` | Maximum number of concurrently active (starting/running) sessions. |
153
- | `defaultBudgetUsd` | `number` | `5` | Default max budget in USD for new sessions when not explicitly specified. |
154
- | `defaultModel` | `string` | — | Default model for new sessions (e.g. `"sonnet"`, `"opus"`). |
155
- | `defaultWorkdir` | `string` | — | Default working directory for new sessions. Falls back to `process.cwd()`. |
156
- | `idleTimeoutMinutes` | `number` | `30` | Idle timeout for multi-turn sessions. If no follow-up message is sent within this window, the session is auto-killed. |
157
- | `maxPersistedSessions` | `number` | `50` | Maximum number of completed sessions to keep in memory for resume support. Oldest sessions are evicted when the cap is exceeded. |
158
- | `fallbackChannel` | `string` | — | Fallback notification channel (e.g. `"telegram:123456789"`). Used when the origin channel cannot be determined. |
159
- | `permissionMode` | `string` | `"bypassPermissions"` | Default permission mode for Claude Code sessions. One of: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`. |
160
-
161
- ### Example configuration
104
+ | `maxSessions` | `number` | `5` | Max concurrently active sessions. |
105
+ | `defaultBudgetUsd` | `number` | `5` | Default max budget per session in USD. |
106
+ | `defaultModel` | `string` | — | Default model (e.g. `"sonnet"`, `"opus"`). |
107
+ | `defaultWorkdir` | `string` | — | Default working directory. Falls back to `process.cwd()`. |
108
+ | `idleTimeoutMinutes` | `number` | `30` | Idle timeout for multi-turn sessions before auto-kill. |
109
+ | `maxPersistedSessions` | `number` | `50` | Max completed sessions kept for resume. |
110
+ | `fallbackChannel` | `string` | — | Fallback notification channel (e.g. `"telegram\|123456789"`). |
111
+ | `permissionMode` | `string` | `"bypassPermissions"` | Default permission mode: `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`. |
112
+ | `agentChannels` | `Record<string, string>` | — | Map workdir paths to notification channels. See [Agent Channels](docs/AGENT_CHANNELS.md). |
162
113
 
163
114
  ```json
164
115
  {
@@ -166,439 +117,162 @@ Configuration is defined in `openclaw.plugin.json` under `configSchema` and pass
166
117
  "defaultBudgetUsd": 10,
167
118
  "defaultModel": "sonnet",
168
119
  "defaultWorkdir": "/home/user/projects",
169
- "idleTimeoutMinutes": 60,
170
- "maxPersistedSessions": 100,
171
- "fallbackChannel": "telegram:123456789",
172
- "permissionMode": "bypassPermissions"
120
+ "permissionMode": "bypassPermissions",
121
+ "fallbackChannel": "telegram|main-bot|123456789",
122
+ "agentChannels": {
123
+ "/home/user/agent-seo": "telegram|seo-bot|123456789",
124
+ "/home/user/agent-main": "telegram|main-bot|123456789"
125
+ }
173
126
  }
174
127
  ```
175
128
 
176
129
  ---
177
130
 
178
- ## Usage
131
+ ## Quick Usage
179
132
 
180
133
  ### Chat Commands
181
134
 
182
- Commands are invoked by humans in chat (Telegram, Discord, etc.) with a `/` prefix.
183
-
184
135
  ```
185
136
  /claude Fix the authentication bug in src/auth.ts
186
- /claude --name fix-auth Fix the authentication bug in src/auth.ts
137
+ /claude --name fix-auth Fix the authentication bug
187
138
  /claude_sessions
188
139
  /claude_fg fix-auth
189
- /claude_bg
140
+ /claude_respond fix-auth Also add unit tests
141
+ /claude_respond --interrupt fix-auth Stop that and do this instead
190
142
  /claude_bg fix-auth
191
143
  /claude_kill fix-auth
192
- /claude_respond fix-auth Also add unit tests for the fix
193
- /claude_respond --interrupt fix-auth Stop, use a different approach
144
+ /claude_resume fix-auth Add error handling
145
+ /claude_resume --fork fix-auth Try a different approach
194
146
  /claude_resume --list
195
- /claude_resume fix-auth Add error handling to the login flow
196
- /claude_resume --fork fix-auth Try a completely different approach
197
147
  /claude_stats
198
148
  ```
199
149
 
200
150
  ### Agent Tools
201
151
 
202
- Tools are invoked by the OpenClaw AI agent programmatically. They follow the MCP tool calling convention.
152
+ Tools receive the calling agent's context automatically. Channel resolution is handled internally — **no `channel` parameter** is exposed on any tool. The parameter `multi_turn_disabled` (not `multi_turn`) controls single-turn mode.
203
153
 
204
154
  ```
205
155
  claude_launch(prompt: "Fix auth bug", workdir: "/app", name: "fix-auth")
206
- claude_launch(prompt: "Refactor DB layer", multi_turn: true, channel: "telegram:123456789")
207
- claude_launch(prompt: "Continue", resume_session_id: "abc123", fork_session: true)
156
+ claude_launch(prompt: "Quick check", multi_turn_disabled: true)
208
157
  claude_sessions(status: "running")
158
+ claude_output(session: "fix-auth", lines: 20)
209
159
  claude_output(session: "fix-auth", full: true)
210
- claude_fg(session: "fix-auth", channel: "telegram:123456789")
211
- claude_bg(session: "fix-auth", channel: "telegram:123456789")
160
+ claude_fg(session: "fix-auth")
161
+ claude_bg(session: "fix-auth")
162
+ claude_respond(session: "fix-auth", message: "Also add tests")
163
+ claude_respond(session: "fix-auth", message: "Do this instead", interrupt: true)
212
164
  claude_kill(session: "fix-auth")
213
- claude_respond(session: "fix-auth", message: "Also add tests", interrupt: false)
214
165
  claude_stats()
215
166
  ```
216
167
 
217
- ### Gateway RPC Methods
218
-
219
- RPC methods are called by external clients (dashboards, APIs, other plugins) via the OpenClaw gateway.
168
+ ### Gateway RPC
220
169
 
221
170
  ```json
222
- // Launch a session
223
171
  { "method": "claude-code.launch", "params": { "prompt": "Fix auth", "workdir": "/app" } }
224
-
225
- // List sessions
226
172
  { "method": "claude-code.sessions", "params": { "status": "running" } }
227
-
228
- // Get output
229
173
  { "method": "claude-code.output", "params": { "session": "fix-auth", "full": true } }
230
-
231
- // Kill a session
232
174
  { "method": "claude-code.kill", "params": { "session": "fix-auth" } }
233
-
234
- // Get stats
235
175
  { "method": "claude-code.stats" }
236
176
  ```
237
177
 
238
- ---
239
-
240
- ## API Reference
241
-
242
- ### Tools
243
-
244
- #### `claude_launch`
245
-
246
- Launch a new Claude Code session.
247
-
248
- | Parameter | Type | Required | Description |
249
- |---|---|---|---|
250
- | `prompt` | `string` | Yes | The task prompt to execute. |
251
- | `name` | `string` | No | Human-readable name (kebab-case). Auto-generated from prompt if omitted. |
252
- | `workdir` | `string` | No | Working directory. Defaults to config `defaultWorkdir` or `cwd`. |
253
- | `model` | `string` | No | Model name (e.g. `"sonnet"`, `"opus"`). |
254
- | `max_budget_usd` | `number` | No | Maximum budget in USD. Default: `5`. |
255
- | `system_prompt` | `string` | No | Additional system prompt appended to the session. |
256
- | `allowed_tools` | `string[]` | No | Explicit list of allowed tools. |
257
- | `resume_session_id` | `string` | No | Claude session ID (or name/internal ID) to resume from. |
258
- | `fork_session` | `boolean` | No | Fork instead of continuing when resuming. |
259
- | `multi_turn` | `boolean` | No | Enable multi-turn mode for follow-up messages via `claude_respond`. |
260
- | `permission_mode` | `string` | No | One of `"default"`, `"plan"`, `"acceptEdits"`, `"bypassPermissions"`. |
261
- | `channel` | `string` | No | Origin channel for notifications (e.g. `"telegram:123456789"`). Prevents `"unknown"` routing. |
262
-
263
- #### `claude_sessions`
264
-
265
- List all sessions with status and progress.
266
-
267
- | Parameter | Type | Required | Description |
268
- |---|---|---|---|
269
- | `status` | `string` | No | Filter: `"all"` (default), `"running"`, `"completed"`, `"failed"`. |
270
-
271
- #### `claude_output`
272
-
273
- Show output from a session.
274
-
275
- | Parameter | Type | Required | Description |
276
- |---|---|---|---|
277
- | `session` | `string` | Yes | Session name or ID. |
278
- | `lines` | `number` | No | Number of recent lines to show (default 50). |
279
- | `full` | `boolean` | No | Show all available output (up to 200 buffered blocks). |
280
-
281
- #### `claude_fg`
282
-
283
- Bring a session to foreground — displays any missed background output under a "📋 Catchup (N missed outputs):" header, then starts streaming new output to the current channel in real time.
284
-
285
- | Parameter | Type | Required | Description |
286
- |---|---|---|---|
287
- | `session` | `string` | Yes | Session name or ID. |
288
- | `lines` | `number` | No | Number of recent buffered lines to show (default 30). |
289
- | `channel` | `string` | No | Target channel for streaming (e.g. `"telegram:123456789"`). Prevents `"unknown"` routing. |
290
-
291
- #### `claude_bg`
292
-
293
- Send a session back to background (stop streaming).
294
-
295
- | Parameter | Type | Required | Description |
296
- |---|---|---|---|
297
- | `session` | `string` | No | Session name or ID. If omitted, detaches all foreground sessions for the current channel. |
298
- | `channel` | `string` | No | Channel to detach from (e.g. `"telegram:123456789"`). Prevents `"unknown"` routing. |
299
-
300
- #### `claude_kill`
301
-
302
- Terminate a running session.
303
-
304
- | Parameter | Type | Required | Description |
305
- |---|---|---|---|
306
- | `session` | `string` | Yes | Session name or ID. |
307
-
308
- #### `claude_respond`
309
-
310
- Send a follow-up message to a running session.
311
-
312
- | Parameter | Type | Required | Description |
313
- |---|---|---|---|
314
- | `session` | `string` | Yes | Session name or ID. |
315
- | `message` | `string` | Yes | The message to send. |
316
- | `interrupt` | `boolean` | No | Interrupt the current turn before sending. Useful to redirect mid-response. |
317
-
318
- #### `claude_stats`
319
-
320
- Show usage metrics. Takes no parameters.
321
-
322
- Returns: session counts by status, average duration, and notable session (sorted by cost internally — cost values are not shown in user-facing output).
178
+ For the full API reference (all parameter tables, response schemas), see [docs/API.md](docs/API.md).
323
179
 
324
180
  ---
325
181
 
326
- ### Commands
327
-
328
- All commands require authentication (`requireAuth: true`).
329
-
330
- | Command | Arguments | Description |
331
- |---|---|---|
332
- | `/claude [--name <name>] <prompt>` | Required: prompt | Launch a new session. |
333
- | `/claude_sessions` | None | List all sessions. |
334
- | `/claude_kill <name-or-id>` | Required: session ref | Terminate a session. |
335
- | `/claude_fg <name-or-id>` | Required: session ref | Bring a session to foreground. |
336
- | `/claude_bg [name-or-id]` | Optional: session ref | Detach foreground session(s). |
337
- | `/claude_resume <ref> [prompt]` | Required: session ref | Resume a completed session. |
338
- | `/claude_resume --list` | Flag | List all resumable sessions. |
339
- | `/claude_resume --fork <ref> [prompt]` | Required: session ref | Fork a completed session. |
340
- | `/claude_respond <ref> <message>` | Required: session ref + message | Send a follow-up message. |
341
- | `/claude_respond --interrupt <ref> <msg>` | Flag + session ref + message | Interrupt then send. |
342
- | `/claude_stats` | None | Show usage metrics. |
182
+ ## Multi-Agent Setup
183
+
184
+ See [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) for the complete guide. Quick summary:
185
+
186
+ Each agent needs three things configured:
187
+
188
+ 1. **agentChannels mapping** Map the agent's workspace directory to its notification channel in `openclaw.json`:
189
+ ```json
190
+ {
191
+ "plugins": {
192
+ "config": {
193
+ "openclaw-claude-code-plugin": {
194
+ "agentChannels": {
195
+ "/home/user/agent-seo": "telegram|seo-bot|123456789",
196
+ "/home/user/agent-devops": "telegram|devops-bot|123456789"
197
+ }
198
+ }
199
+ }
200
+ }
201
+ }
202
+ ```
203
+
204
+ 2. **Heartbeat** — Enable heartbeat for each agent in `openclaw.json`:
205
+ ```json
206
+ {
207
+ "agents": {
208
+ "list": [
209
+ { "id": "seo-bot", "heartbeat": { "every": "5s", "target": "last" } },
210
+ { "id": "devops-bot", "heartbeat": { "every": "5s", "target": "last" } }
211
+ ]
212
+ }
213
+ }
214
+ ```
215
+
216
+ 3. **Agent files** — Each agent's workspace needs:
217
+ - `HEARTBEAT.md` — Instructions for checking Claude Code sessions during heartbeat cycles
218
+ - `skills/claude-code-autonomy/SKILL.md` — Autonomy rules for handling session interactions
343
219
 
344
220
  ---
345
221
 
346
- ### RPC Methods
347
-
348
- All methods return `respond(true, data)` on success or `respond(false, { error })` on failure.
349
-
350
- #### `claude-code.sessions`
351
-
352
- | Parameter | Type | Description |
353
- |---|---|---|
354
- | `status` | `string` | Filter: `"all"`, `"running"`, `"completed"`, `"failed"`. |
355
-
356
- **Response:** `{ sessions: [...], count: number }`
357
-
358
- Each session object includes: `id`, `name`, `status`, `prompt`, `workdir`, `model`, `startedAt`, `completedAt`, `durationMs`, `claudeSessionId`, `foreground`, `multiTurn`, `display`.
359
-
360
- #### `claude-code.launch`
361
-
362
- | Parameter | Type | Description |
363
- |---|---|---|
364
- | `prompt` | `string` | **(required)** Task prompt. |
365
- | `name` | `string` | Session name. |
366
- | `workdir` | `string` | Working directory. |
367
- | `model` | `string` | Model name. |
368
- | `maxBudgetUsd` / `max_budget_usd` | `number` | Budget cap. |
369
- | `systemPrompt` / `system_prompt` | `string` | System prompt. |
370
- | `allowedTools` / `allowed_tools` | `string[]` | Allowed tools. |
371
- | `resumeSessionId` / `resume_session_id` | `string` | Session ID to resume. |
372
- | `forkSession` / `fork_session` | `boolean` | Fork on resume. |
373
- | `multiTurn` / `multi_turn` | `boolean` | Multi-turn mode. |
374
- | `originChannel` | `string` | Origin channel for notifications. |
375
-
376
- **Response:** `{ id, name, status, workdir, model }`
377
-
378
- #### `claude-code.kill`
379
-
380
- | Parameter | Type | Description |
381
- |---|---|---|
382
- | `session` / `id` | `string` | **(required)** Session name or ID. |
383
-
384
- **Response:** `{ id, name, status, message }`
385
-
386
- #### `claude-code.output`
387
-
388
- | Parameter | Type | Description |
389
- |---|---|---|
390
- | `session` / `id` | `string` | **(required)** Session name or ID. |
391
- | `lines` | `number` | Number of lines (default 50). |
392
- | `full` | `boolean` | Return all buffered output. |
393
-
394
- **Response:** `{ id, name, status, durationMs, duration, lines, lineCount, result }`
222
+ ## Skill Example
395
223
 
396
- #### `claude-code.stats`
224
+ Claude Code Plugin is a **transparent transport layer** — it spawns sessions and delivers notifications, but business logic lives in **OpenClaw skills**. Here's a minimal skill that orchestrates coding agent sessions:
397
225
 
398
- No parameters.
399
-
400
- **Response:**
401
- ```json
402
- {
403
- "sessionsByStatus": { "completed": 10, "failed": 2, "killed": 1, "running": 1 },
404
- "totalLaunched": 14,
405
- "averageDurationMs": 45000,
406
- "notableSession": { "id": "abc123", "name": "refactor-db", "prompt": "..." },
407
- "display": "📊 Claude Code Plugin Stats\n..."
408
- }
409
- ```
226
+ ### `coding-agent/SKILL.md`
410
227
 
228
+ ```markdown
411
229
  ---
412
-
413
- ## Notification System
414
-
415
- The `NotificationRouter` implements a notification matrix based on session state and channel mode:
416
-
417
- | Event | Background session | Foreground session |
418
- |---|---|---|
419
- | Session started | Silent | Silent (streaming begins) |
420
- | Assistant text output | Silent | Streamed to chat (500ms debounce) |
421
- | Tool call | Silent | Compact indicator (e.g. `🔧 Bash — git status`) |
422
- | Tool result | Silent | Silent |
423
- | Session completed (success) | Notify origin channel | Notify all channels |
424
- | Session completed (error) | Notify origin channel | Notify all channels |
425
- | Session limit reached | Notify origin channel | Notify all channels |
426
- | Session > 10 minutes | One-time reminder | Silent (user sees output) |
427
- | Waiting for input | `🔔 [name] Claude asks:` + preview to origin channel + fire `openclaw system event` | `💬 Session waiting for input` + fire `openclaw system event` |
428
- | Agent responds (`claude_respond`) | `↩️ [name] Responded:` echoed to origin channel | `↩️ [name] Responded:` echoed to origin channel |
429
-
430
- ### Notification delivery
431
-
432
- Notifications are sent via the `openclaw message send` CLI command. The channel ID format is `"channel:target"` (e.g. `"telegram:123456789"`, `"discord:987654321"`). Bare numeric IDs are assumed to be Telegram chat IDs.
433
-
434
- ### Background visibility
435
-
436
- When a session is running in the background, users can follow the conversation without foregrounding:
437
-
438
- - **🔔 Claude asks** — When a session becomes idle and waiting for input (e.g. Claude asked a question or needs a decision), the origin channel receives a `🔔 [name] Claude asks:` message with a preview of the last output, so the user sees what Claude needs.
439
- - **↩️ Responded** — When the agent (or user via `claude_respond`) sends a follow-up message, a `↩️ [name] Responded:` message is echoed to the origin channel with the response content, so the full conversation is visible in-channel.
440
-
441
- This makes the plugin a transparent transport layer — the user sees both sides of the conversation in their chat, even when sessions run in the background.
442
-
443
- ### Agent event triggers
444
-
445
- When a session completes, an `openclaw system event` is fired with a summary of the session result, prompting the OpenClaw AI agent to process the output and relay it to the user.
446
-
447
- When any session (single or multi-turn) becomes idle and waiting for input, an `openclaw system event` is also fired to wake the orchestrator. Idle detection uses end-of-turn detection (for multi-turn results) combined with a 15-second safety-net timer. A `waitingForInputFired` flag prevents duplicate wake events from being fired for the same idle period.
448
-
449
- ---
450
-
451
- ## Skill Example: Coding Agent Workflow
452
-
453
- Claude Code Plugin is a **transparent transport layer** — it spawns sessions, streams output, and delivers notifications, but it has no opinion about *how* to orchestrate coding agents. Business logic lives in **OpenClaw skills**.
454
-
455
- Here's an example skill that defines a coding agent workflow: it auto-responds to certain Claude questions and forwards others to the user.
456
-
457
- ### `coding-agent.skill.yaml`
458
-
459
- ```yaml
460
- id: coding-agent
461
230
  name: Coding Agent Orchestrator
462
- description: >
463
- Orchestrates Claude Code sessions with smart auto-response rules.
464
- Automatically handles routine questions and forwards important decisions
465
- to the user.
466
-
467
- instructions: |
468
- You are a coding agent orchestrator. You manage Claude Code sessions
469
- via the claude-code plugin tools.
470
-
471
- ## Auto-response rules
472
-
473
- When a Claude Code session asks a question (🔔 wake event), analyze the
474
- question and decide whether to auto-respond or forward to the user:
475
-
476
- ### Auto-respond (use claude_respond immediately):
477
- - Permission requests for file reads, writes, or bash commands
478
- → Respond: "Yes, proceed."
479
- - Confirmation prompts like "Should I continue?" or "Do you want me to apply these changes?"
480
- → Respond: "Yes, continue."
481
- - Questions about which approach to take when only one is reasonable
482
- → Respond with the obvious choice
483
- - Requests for clarification about the codebase (file locations, conventions)
484
- → Respond with the info if you know it, or "Use your best judgment."
485
-
486
- ### Forward to user (relay the question to the chat):
487
- - Architecture decisions (e.g. "Should I use Redis or PostgreSQL for caching?")
488
- - Destructive operations (e.g. "Should I delete the old migration files?")
489
- - Ambiguous requirements (e.g. "The spec doesn't mention error handling — what should I do?")
490
- - Budget or scope changes (e.g. "This will require refactoring 15 files — should I proceed?")
491
- - Anything involving credentials, secrets, or production environments
231
+ description: Orchestrates Claude Code sessions with smart auto-response rules for routine questions and user forwarding for critical decisions.
232
+ metadata: {"openclaw": {"requires": {"plugins": ["openclaw-claude-code-plugin"]}}}
233
+ ---
492
234
 
493
- ## Workflow
235
+ # Coding Agent Orchestrator
494
236
 
495
- 1. User sends a coding task launch a multi-turn session:
496
- claude_launch(prompt: "<task>", multi_turn: true, channel: "<origin>")
237
+ You are a coding agent orchestrator. You manage Claude Code sessions via the claude-code plugin tools.
497
238
 
498
- 2. Session runs in background. Monitor via wake events.
239
+ ## Auto-response rules
499
240
 
500
- 3. On 🔔 wake event read the question with claude_output, then:
501
- - If auto-respond rule matches → claude_respond(session, answer)
502
- - If forward rule matches → relay the question to the user
241
+ When a Claude Code session asks a question (wake event), analyze it and decide:
503
242
 
504
- 4. On user reply to a forwarded question → claude_respond with their answer
243
+ ### Auto-respond (use `claude_respond` immediately):
244
+ - Permission requests for file reads, writes, or bash commands -> "Yes, proceed."
245
+ - Confirmation prompts like "Should I continue?" -> "Yes, continue."
246
+ - Questions about approach when only one is reasonable -> respond with the obvious choice
505
247
 
506
- 5. On completion → summarize the result and notify the user
248
+ ### Forward to user:
249
+ - Architecture decisions (Redis vs PostgreSQL, REST vs GraphQL...)
250
+ - Destructive operations (deleting files, dropping tables...)
251
+ - Anything involving credentials, secrets, or production environments
252
+ - When in doubt -> always forward to the user
507
253
 
508
- ## Important
254
+ ## Workflow
509
255
 
510
- - Always use multi_turn: true for tasks that may need follow-up
511
- - Always pass the channel parameter to maintain notification routing
512
- - Never auto-respond to questions about production deployments
513
- - When in doubt, forward to the user it's better to ask than to guess
256
+ 1. User sends a coding task -> `claude_launch(prompt, ...)`
257
+ 2. Session runs in background. Monitor via wake events.
258
+ 3. On wake event -> `claude_output` to read the question, then auto-respond or forward.
259
+ 4. On user reply to a forwarded question -> `claude_respond` with their answer.
260
+ 5. On completion -> summarize the result and notify the user.
514
261
  ```
515
262
 
516
- ### How it works
517
-
518
- This skill demonstrates the key architectural principle: **Claude Code Plugin provides the transport, skills provide the brain.**
519
-
520
- | Layer | Responsibility |
521
- |---|---|
522
- | **Claude Code Plugin** (this plugin) | Spawn sessions, stream output, deliver `🔔`/`↩️` notifications, fire wake events |
523
- | **Skill** (e.g. `coding-agent`) | Decide what to auto-respond, what to forward, how to summarize results |
524
- | **User** | Receives forwarded questions, provides high-level instructions |
525
-
526
- The same Claude Code Plugin plugin can power completely different workflows — a code review skill, a CI/CD skill, a documentation skill — simply by swapping the skill definition. The plugin itself remains a generic, reusable transport layer.
263
+ A comprehensive orchestration skill is available at [`skills/claude-code-orchestration/SKILL.md`](skills/claude-code-orchestration/SKILL.md).
527
264
 
528
265
  ---
529
266
 
530
- ## Development
267
+ ## Documentation
531
268
 
532
- ### Project Structure
533
-
534
- ```
535
- claude-code/
536
- ├── index.ts # Plugin entry point (register function)
537
- ├── openclaw.plugin.json # Plugin manifest and config schema
538
- ├── package.json # Dependencies
539
- ├── src/
540
- │ ├── types.ts # TypeScript interfaces
541
- │ ├── shared.ts # Global state, helpers, formatting
542
- │ ├── session.ts # Session class (SDK wrapper)
543
- │ ├── session-manager.ts # Session pool management
544
- │ ├── notifications.ts # NotificationRouter
545
- │ ├── gateway.ts # RPC method registration
546
- │ ├── tools/
547
- │ │ ├── claude-launch.ts # claude_launch tool
548
- │ │ ├── claude-sessions.ts # claude_sessions tool
549
- │ │ ├── claude-output.ts # claude_output tool
550
- │ │ ├── claude-fg.ts # claude_fg tool
551
- │ │ ├── claude-bg.ts # claude_bg tool
552
- │ │ ├── claude-kill.ts # claude_kill tool
553
- │ │ ├── claude-respond.ts # claude_respond tool
554
- │ │ └── claude-stats.ts # claude_stats tool
555
- │ └── commands/
556
- │ ├── claude.ts # /claude command
557
- │ ├── claude-sessions.ts # /claude_sessions command
558
- │ ├── claude-fg.ts # /claude_fg command
559
- │ ├── claude-bg.ts # /claude_bg command
560
- │ ├── claude-kill.ts # /claude_kill command
561
- │ ├── claude-resume.ts # /claude_resume command
562
- │ ├── claude-respond.ts # /claude_respond command
563
- │ └── claude-stats.ts # /claude_stats command
564
- └── docs/
565
- └── plans/ # Design documents
566
- ```
567
-
568
- ### Dependencies
569
-
570
- | Package | Purpose |
269
+ | Document | Description |
571
270
  |---|---|
572
- | `@anthropic-ai/claude-agent-sdk` | Claude Code SDKthe `query()` function that powers each session. |
573
- | `@sinclair/typebox` | JSON Schema type builder for tool parameter definitions. |
574
- | `nanoid` | Generates short unique session IDs (8 characters). |
575
-
576
- ### Key design decisions
577
-
578
- 1. **Foreground is per-channel, not per-session.** Multiple channels can watch the same session simultaneously, and one channel can have multiple sessions in foreground.
579
-
580
- 2. **Multi-turn uses `AsyncIterable` prompts.** The `MessageStream` class implements `Symbol.asyncIterator` to feed user messages into the SDK's `query()` function as an async generator, keeping the session alive across turns.
581
-
582
- 3. **Persisted sessions survive GC.** When a session is garbage-collected (1 hour after completion), its Claude session ID is retained in a separate `persistedSessions` map so it can be resumed later. Entries are stored under three keys (internal ID, name, Claude UUID) for flexible lookup.
583
-
584
- 4. **Notifications use CLI shelling.** Since the plugin API doesn't expose a runtime `sendMessage` method, outbound notifications go through `openclaw message send` via `child_process.execFile`.
585
-
586
- 5. **Metrics are in-memory only.** Session metrics are aggregated in the `SessionManager` and reset on service restart. They are not persisted to disk. Cost data is tracked internally but not exposed in any user-facing output.
587
-
588
- 6. **Waiting-for-input uses dual detection.** End-of-turn detection (when a multi-turn result resolves) is the primary signal, backed by a 15-second safety-net timer for edge cases. A `waitingForInputFired` flag prevents duplicate wake events.
589
-
590
- 7. **Channel `"unknown"` falls through.** If `channelId` is `"unknown"`, the notification system explicitly falls through to `fallbackChannel` rather than attempting delivery to an invalid destination.
591
-
592
- ### Adding a new tool or command
593
-
594
- 1. Create a new file under `src/tools/` or `src/commands/`.
595
- 2. Export a `registerXxxTool(api)` or `registerXxxCommand(api)` function.
596
- 3. Import and call it in `index.ts` inside the `register()` function.
597
-
598
- ### Service lifecycle
599
-
600
- - **`start()`** — Creates `SessionManager` and `NotificationRouter`, wires them together, starts the long-running reminder check interval (60s), and starts a GC interval (5 min).
601
- - **`stop()`** — Stops the notification router, kills all active sessions, clears intervals, and nulls singletons.
271
+ | [docs/API.md](docs/API.md) | Full API referencetools, commands, and RPC methods with parameter tables |
272
+ | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Architecture diagram and component breakdown |
273
+ | [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md) | Notification matrix, delivery details, and agent wake events |
274
+ | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Project structure, dependencies, design decisions, and contribution guide |
275
+ | [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) | Multi-agent setup, notification routing, and workspace mapping |
602
276
 
603
277
  ---
604
278