openclaw-code-agent 3.0.0 → 3.2.0

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
@@ -4,422 +4,115 @@
4
4
  [![npm downloads](https://img.shields.io/npm/dm/openclaw-code-agent.svg)](https://www.npmjs.com/package/openclaw-code-agent)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
6
 
7
- An [OpenClaw](https://openclaw.com) plugin that lets AI agents orchestrate coding agent sessions as managed background processes. Launch, monitor, and interact with multiple concurrent coding sessions directly from Telegram, Discord, or any OpenClaw-supported messaging platform without leaving your chat interface.
7
+ `openclaw-code-agent` is the OpenClaw plugin for running Claude Code and Codex as managed background coding sessions from chat. Launch work from Telegram, Discord, or any OpenClaw-supported channel, review the plan before execution, keep the job isolated in its own git worktree, and merge or open a PR without leaving the thread.
8
8
 
9
- ## Why?
9
+ - **Plan -> Review -> Execute**. `plan` is the default launch mode, with `ask`, `delegate`, and `approve` deciding how much plan approval autonomy the orchestrator gets.
10
+ - **Optional worktree isolation**. New sessions default to `off`; opt into `ask`, `delegate`, `auto-merge`, or `auto-pr` when you want worktree-backed branch isolation and post-run branch handling.
11
+ - **State-driven decision UX**. `ask` sends explicit action buttons for **Merge locally**, **Create PR**, **Decide later**, and **Dismiss**. The same action-token model now backs both Telegram and Discord interactive callbacks.
12
+ - **Lifecycle-first cleanup**. Worktrees are treated as temporary task sandboxes. The plugin distinguishes `merged` from `released` so different-SHA branches whose content already landed on the base branch can still be cleaned safely.
13
+ - **Full session lifecycle**. Suspend, resume, fork, interrupt, and recover sessions across restarts with persisted metadata and output.
14
+ - **Explicit goal-task loops**. Opt into verifier-driven repair loops or Ralph-style completion loops when you need iterative autonomous execution toward a specific goal.
15
+ - **Real operator visibility**. `agent_sessions`, `agent_output`, and `agent_stats` show status, buffered output, duration, and USD cost.
16
+ - **Two harnesses, one control plane**. Claude Code and Codex share the same tools, routing, notification pipeline, and worktree strategy model while each backend uses its own native execution substrate.
17
+ - **One continuation primitive**. `agent_respond` is the only way to continue, approve, revise, or redirect an existing session. Forks still go through `agent_launch(..., resume_session_id=..., fork_session=true)`.
10
18
 
11
- This plugin started as a response to a real gap in OpenClaw's built-in ACP support. At the time, ACP was effectively a raw relay into ACP backends: useful for handing off a prompt, but without the orchestration layer needed for coding-agent work in chat. There was no plan review flow, no plugin-managed pause/resume model, no fork flow, no cost or session stats, and no async notification path back to the originating chat when a session needed input or finished.
19
+ Need the version-pinned ACP breakdown? See [docs/ACP-COMPARISON.md](docs/ACP-COMPARISON.md).
12
20
 
13
- ACP has improved since then. OpenClaw core ACP now supports multi-turn sessions, resuming prior work, and a broader set of ACP runtimes and harnesses. That closes part of the original gap.
21
+ ## New In 3.2.0
14
22
 
15
- What still remains is the orchestration layer this plugin was built to provide: propose/revise/approve plan review before execution, forkable coding sessions, dedicated session catalog + operator-facing stats, cost accounting, and an explicit async notification pipeline that wakes the origin chat only when the job needs attention or completes.
23
+ `3.2.0` is the release that makes the newer worktree and plan-review model feel reliable enough for daily use.
16
24
 
17
- For the current version-pinned breakdown, see [docs/ACP-COMPARISON.md](docs/ACP-COMPARISON.md).
25
+ - **Deterministic completion and approval state**. Terminal notifications and wakes no longer depend on transcript-style summary heuristics, and plan-gated sessions now surface explicit approval/execution state for operators and orchestration logic.
26
+ - **Real auto-merge conflict recovery**. `auto-merge` now gets one autonomous conflict-resolution attempt, then retries the merge automatically before escalating back to a preserved branch or PR path.
27
+ - **Lifecycle-first worktree cleanup**. Worktree status and cleanup now treat `released` as a first-class resolved state, so rebased, squashed, and cherry-picked work can still be identified and cleaned safely.
28
+ - **Safer repository follow-through**. Worktree disk-space validation now checks the correct filesystem on first run and for custom worktree directories, and cross-repo PR auto-targeting now works for upstream-only repos.
29
+ - **Stronger release hygiene**. The repo now standardizes on `pnpm` validation, and release automation validates `package.json`, `openclaw.plugin.json`, and the release version together before publish.
18
30
 
19
- ## Demo
20
- <img src="assets/ask-readme.gif" alt="Ask mode demo showing plan review and approval before execution">
31
+ ## From Prompt To Merged Branch
21
32
 
22
- *Plan review and approval in ask mode: the agent pauses for your decision before executing.*
33
+ 1. Launch a coding session from chat with `/agent ...` or `agent_launch(...)`.
34
+ 2. Review the plan in the same thread before anything touches the repo.
35
+ 3. Let the agent finish in an isolated worktree, then merge or publish the result from chat.
23
36
 
24
- ### Autonomous mode (delegate)
37
+ ### Explicit Goal Tasks
25
38
 
26
- <img src="assets/delegate-readme.gif" alt="Delegate mode demo showing autonomous execution with selective escalation">
39
+ Goal tasks are an explicit opt-in path for iterative autonomous work. They do not replace the default `agent_launch` flow.
27
40
 
28
- *In delegate mode, the orchestrator auto-approves low-risk plans and only escalates when needed.*
41
+ Use the dedicated goal entrypoints:
29
42
 
30
- ## Supported Agents
43
+ - `/goal ...`
44
+ - `goal_launch(...)`
31
45
 
32
- | Agent | Status | Notes |
33
- |-------|--------|-------|
34
- | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | ✅ Supported | Full support via `@anthropic-ai/claude-agent-sdk` |
35
- | [Codex](https://github.com/openai/codex) | ✅ Supported | Full support via `@openai/codex-sdk` thread API |
36
- | Other agents | 🚧 Planned | Plugin architecture supports adding new harnesses |
46
+ The plugin does not automatically switch into goal mode just because a freeform prompt contains the words `goal task`.
37
47
 
38
- > **vs. built-in ACP?** See [docs/ACP-COMPARISON.md](docs/ACP-COMPARISON.md) for the current version-pinned breakdown.
48
+ Use them when you want the plugin to keep looping toward one concrete outcome:
39
49
 
40
- ---
50
+ - **Verifier mode** reruns one or more shell checks after each coding turn and keeps iterating until they pass or the iteration budget is exhausted.
51
+ - **Ralph mode** keeps resuming the same task until the agent emits an exact completion promise, with optional verifiers run after completion is claimed.
41
52
 
42
- ## Features
43
-
44
- - **Multi-session management** — Run multiple concurrent coding agent sessions, each with a unique ID and human-readable name
45
- - **Plan → Execute workflow** — Claude Code sessions expose plan mode; Codex uses a soft first-turn planning prompt while staying externally in implement mode
46
- - **Plan approval modes** — Three configurable modes (`ask` / `delegate` / `approve`) control how the orchestrator handles plan-approval events before execution
47
- - **Real Codex approval policy support** — Codex sessions default to the real Codex SDK/CLI `approvalPolicy: "on-request"` and can be pinned back to `"never"` via `harnesses.codex.approvalPolicy`
48
- - **Git worktree isolation** — Opt-in worktree support keeps main checkout clean; configurable strategies: `manual`, `ask`, `delegate`, `auto-merge`, `auto-pr`
49
- - **Telegram inline buttons** — `ask` strategy sends inline keyboard buttons (Merge locally / Create PR) directly in chat; button taps route back to the plugin
50
- - **PR lifecycle management** — `agent_pr` detects existing open/merged/closed PRs and updates instead of duplicating; full lifecycle handling via `gh` CLI
51
- - **Conflict resolution** — Auto-merge conflicts spawn Claude Code conflict-resolver sessions automatically
52
- - **Thread-based routing** — Notifications go to the Telegram thread/topic where the session was launched
53
- - **Pause + auto-resume** — Non-question turn completion pauses sessions (`done`) and next `agent_respond` auto-resumes with context intact
54
- - **Turn-end wake signaling** — Every turn end emits a deterministic wake signal with output preview and waiting hint
55
- - **Smart waiting detection** — Heuristic waiting detector reduces false-positive wake escalations
56
- - **Multi-turn conversations** — Send follow-up messages, interrupt, or iterate with a running agent
57
- - **Session resume & fork** — Resume any completed session or fork it into a new conversation branch
58
- - **Deliverable mode** — `output_mode: "deliverable"` switches from `✅ Completed` to `📄 Deliverable ready` for document/report generation tasks
59
- - **Merged session listing** — `agent_sessions` shows active + persisted sessions in one view (deduped by internal session ID)
60
- - **Pending MessageStream safety** — queued follow-ups are preserved across turn completion so messages are not dropped
61
- - **Codex SDK streaming harness** — uses `@openai/codex-sdk` thread streaming with soft first-turn planning, waiting detection, and activity heartbeats
62
- - **Multi-agent support** — Route notifications to the correct agent/chat via workspace-based channel mapping
63
- - **Auto-respond rules** — Orchestrator auto-handles permission requests and confirmations; forwards real decisions to you
64
- - **Anti-cascade protection** — Orchestrator never launches new sessions from wake events
65
- - **Startup recovery** — Orphaned worktrees and crashed running-state sessions are automatically cleaned up on gateway restart
66
- - **Automatic cleanup** — Completed sessions are garbage-collected after a configurable TTL (`sessionGcAgeMinutes`, default 24h); IDs persist for resume
67
- - **Harness-agnostic architecture** — Pluggable `AgentHarness` interface allows adding new coding agent backends
68
-
69
- ---
70
-
71
- ## Compatibility
72
-
73
- | Plugin version | OpenClaw version |
74
- |---|---|
75
- | 2.3.x | >=2026.3.13 |
76
- | 2.4.x | >=2026.3.22 |
77
- | 3.0.x | >=2026.3.22 |
78
-
79
- Tested against OpenClaw v2026.3.23. The plugin uses CLI-based integration and is unaffected by OpenClaw plugin SDK surface changes.
80
-
81
- **Codex model options (v2026.3.22+):** In addition to the default `gpt-5.4`, you can configure `gpt-5.4-mini` or `gpt-5.4-nano` in `harnesses.codex.allowedModels` for lower-cost Codex sessions.
82
-
83
- ---
84
-
85
- ## Quick Start
86
-
87
- ### 1. Install the plugin
88
-
89
- ```bash
90
- openclaw plugins install openclaw-code-agent
91
- openclaw plugins enable openclaw-code-agent
92
- openclaw gateway restart
93
- ```
94
-
95
- ### 2. Configure notifications
96
-
97
- Add to `~/.openclaw/openclaw.json` under `plugins.entries["openclaw-code-agent"]`:
98
-
99
- ```json
100
- {
101
- "plugins": {
102
- "entries": {
103
- "openclaw-code-agent": {
104
- "enabled": true,
105
- "config": {
106
- "fallbackChannel": "telegram|my-bot|123456789",
107
- "maxSessions": 20,
108
- "harnesses": {
109
- "codex": {
110
- "defaultModel": "gpt-5.4",
111
- "allowedModels": ["gpt-5.4"],
112
- "reasoningEffort": "medium",
113
- "approvalPolicy": "on-request"
114
- },
115
- "claude-code": {
116
- "defaultModel": "sonnet",
117
- "allowedModels": ["sonnet", "opus"]
118
- }
119
- }
120
- }
121
- }
122
- }
123
- }
124
- }
125
- ```
126
-
127
- Replace `my-bot` with your Telegram bot account name and `123456789` with your Telegram chat ID.
128
-
129
- ### 2a. Codex auth safety
130
-
131
- If you run Codex sessions, strongly recommend forcing ChatGPT login in your Codex config:
132
-
133
- ```toml
134
- forced_login_method = "chatgpt"
135
- ```
136
-
137
- Put that in `~/.codex/config.toml`. This keeps Codex on the ChatGPT auth path and avoids account/login mismatches that can surface as unsupported-model or auth failures.
138
-
139
- ### 3. Typical workflow
140
-
141
- 1. Ask your agent: *"Fix the bug in auth.ts"*
142
- 2. A coding agent session launches and explores the task. Claude Code exposes **plan mode**; Codex can do a plan-first turn without surfacing plan mode in session status
143
- 3. The agent's questions and plan appear in the **same Telegram thread** where you launched
144
- 4. When a session is awaiting plan approval, approve it with `agent_respond(..., approve=true)` and the session switches to implement mode
145
- 5. The agent implements with full permissions, then you get a brief completion summary
146
-
147
- ---
148
-
149
- ## Tools
150
-
151
- | Tool | Description | Key Parameters |
152
- |------|-------------|----------------|
153
- | `agent_launch` | Start a new coding agent session in background | `prompt`, `name`, `workdir`, `model`, `resume_session_id`, `fork_session`, `permission_mode`, `harness`, `worktree_strategy`, `output_mode` |
154
- | `agent_respond` | Send a follow-up message to a running session | `session`, `message`, `interrupt`, `approve`, `userInitiated` |
155
- | `agent_kill` | Terminate or complete a running session | `session`, `reason` |
156
- | `agent_output` | Read buffered output from a session | `session`, `lines`, `full` |
157
- | `agent_sessions` | List recent sessions (5 by default, `full` for 24h view) | `status`, `full` |
158
- | `agent_stats` | Show usage metrics (counts, durations, costs) | *(none)* |
159
- | `agent_merge` | Merge a worktree branch back to base branch | `session`, `base_branch`, `strategy`, `push`, `delete_branch` |
160
- | `agent_pr` | Create or update a GitHub PR for a worktree branch (full lifecycle) | `session`, `title`, `body`, `base_branch`, `force_new` |
161
- | `agent_worktree_status` | Show worktree status for sessions | `session` (optional) |
162
- | `agent_worktree_cleanup` | Clean up merged agent/* branches | `workdir`, `base_branch`, `skip_session_check`, `dry_run`, `session` |
163
-
164
- Core orchestration workflows use `agent_launch`, `agent_respond`, `agent_output`, `agent_sessions`, and `agent_kill`.
165
-
166
- All tools are also available as **chat commands** (`/agent`, `/agent_respond`, `/agent_kill`, `/agent_sessions`, `/agent_resume`, `/agent_stats`, `/agent_output`).
167
-
168
- ---
169
-
170
- ## Usage Examples
53
+ Examples:
171
54
 
172
55
  ```bash
173
- # Launch a session (starts in plan mode by default)
174
- /agent Fix the authentication bug in src/auth.ts
175
- /agent --name fix-auth Fix the authentication bug
176
-
177
- # Monitor
178
- /agent_sessions
179
- /agent_sessions --full
180
-
181
- # Interact with a running session
182
- /agent_respond fix-auth Also add unit tests
183
- /agent_respond --interrupt fix-auth Stop that and do this instead
184
-
185
- # Approve a pending plan (tool call)
186
- agent_respond(session='fix-auth', message='Approved. Go ahead.', approve=true)
187
-
188
- # Lifecycle management
189
- /agent_kill fix-auth
190
- /agent_resume fix-auth Add error handling
191
- /agent_resume --fork fix-auth Try a different approach
192
- /agent_stats
56
+ /goal --workdir /repo --verify "npm test" --verify "npm run lint" Fix the failing auth flow
57
+ /goal --workdir /repo --mode ralph --completion-promise DONE Ship the draft blog post workflow end to end
58
+ goal_launch(goal="Fix the failing auth flow", verifier_commands=["npm test", "npm run lint"], workdir="/repo")
59
+ goal_launch(goal="Ship the draft blog post workflow end to end", goal_mode="ralph", completion_promise="DONE", workdir="/repo")
193
60
  ```
194
61
 
195
- ---
196
-
197
- ## Notifications
198
-
199
- The plugin sends targeted notifications to the originating Telegram thread:
200
-
201
- | Emoji | Event | Description |
202
- |-------|-------|-------------|
203
- | 🚀 | Launched | Session started with prompt summary |
204
- | ❓ | Waiting for input | Session is waiting for user input |
205
- | 📋 | Plan ready | Plan approval requested — reply "go" to approve |
206
- | ⏸️ | Paused after turn | Turn completed, session paused (auto-resumable) |
207
- | ↪️ | Responded / Redirected | `agent_respond` sent a message; also fires when `interrupt: true` redirects active work |
208
- | 👍 | Plan approved | Plan was approved via `agent_respond(..., approve: true)` |
209
- | ▶️ | Auto-resumed | Session resumed on the next `agent_respond` |
210
- | ✅ | Completed | Completion summary with cost and duration |
211
- | 📄 | Deliverable ready | Session finished with `output_mode: "deliverable"` |
212
- | ❌ | Failed | Error notification with `harnessSessionId` and resume guidance |
213
- | 💤 | Idle timeout | Session timed out while waiting; auto-resumes on next respond |
214
- | ⛔ | Stopped | Session was stopped by user, shutdown, or another forced stop |
215
- | 🔀 | Worktree decision (`ask`) | Telegram inline buttons sent: Merge locally / Create PR |
216
- | 🤖 | Worktree decision (`delegate`) | Wake sent to orchestrator with diff context for autonomous decision |
217
-
218
- ---
219
-
220
- ## Plan → Execute Mode Switch
221
-
222
- - **Claude Code** starts in `plan` mode by default. Approve a pending plan with `agent_respond(..., approve=true)` and the session switches to `bypassPermissions`.
223
- - **Codex** does not surface `plan` or `awaiting-plan-approval` in session state. When launched with `permissionMode: "plan"`, its first turn is prompted to return a plan and ask whether to proceed, while the exposed session phase remains implementation-oriented.
224
- - For **Codex**, plugin `permissionMode` is a plugin-orchestrated planning/approval workflow. It is not the same thing as the Codex SDK/CLI `approvalPolicy`.
225
- - The real Codex SDK/CLI approval behavior is controlled by `harnesses.codex.approvalPolicy`. Supported values are `"on-request"` (default) and `"never"`.
226
-
227
- On approval, the plugin prepends a system instruction telling the agent to exit plan mode and implement with full permissions.
228
-
229
- ---
230
-
231
- ## Auto-Respond Rules
232
-
233
- The orchestrator agent follows strict auto-respond rules to minimize noise:
234
-
235
- **Auto-respond (immediate):**
236
- - Permission requests (file read/write/bash) → "Yes, proceed."
237
- - Explicit "should I continue?" confirmations → "Yes, continue."
62
+ Once launched, use `goal_status` / `/goal_status` to inspect progress and `goal_stop` / `/goal_stop` to terminate the loop. Goal-task state is persisted so recoverable loops can resume after a gateway restart.
238
63
 
239
- **Forward to user (everything else):**
240
- - Architecture/design decisions
241
- - Destructive operations
242
- - Scope changes
243
- - Credential/production questions
244
- - Any ambiguous or non-trivial question
64
+ ### Plan First
245
65
 
246
- When forwarding, the orchestrator quotes the agent's exact question without adding its own commentary.
66
+ The differentiator is the plan-review loop. Claude Code and Codex both feed the same review UX now: the plugin receives a structured plan artifact, keeps execution blocked until approval, and resumes the same session with `agent_respond(..., approve=true)`. If the user asks for revisions, the revised submission becomes the new actionable review version for that same session, and `approve=true` resolves against that latest version instead of any stale earlier change-request state.
247
67
 
248
- ---
68
+ <img src="assets/ask-readme.gif" alt="Plan review in ask mode with inline approval controls">
249
69
 
250
- ## Configuration
70
+ *`ask` mode keeps the human in the loop: the plan lands back in the originating thread, and execution only starts after approval.*
251
71
 
252
- Set values in `~/.openclaw/openclaw.json` under `plugins.entries["openclaw-code-agent"].config`:
72
+ ### Finish Cleanly
253
73
 
254
- | Option | Type | Default | Description |
255
- |--------|------|---------|-------------|
256
- | `agentChannels` | `object` | — | Map workdir paths → notification channels (see [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md)) |
257
- | `fallbackChannel` | `string` | — | Default notification channel when no workspace match found |
258
- | `maxSessions` | `number` | `20` | Maximum concurrent sessions |
259
- | `maxAutoResponds` | `number` | `10` | Max consecutive auto-responds before requiring user input |
260
- | `permissionMode` | `string` | `"plan"` | Plugin orchestration mode: `"default"` (standard prompts) / `"plan"` (present plan first) / `"bypassPermissions"` (fully autonomous) |
261
- | `idleTimeoutMinutes` | `number` | `15` | Idle timeout before auto-kill |
262
- | `sessionGcAgeMinutes` | `number` | `1440` | TTL for completed/failed/killed runtime sessions before GC eviction |
263
- | `maxPersistedSessions` | `number` | `10000` | Max completed sessions kept for resume; the 24h GC TTL (`sessionGcAgeMinutes`) is the primary retention control |
264
- | `planApproval` | `string` | `"ask"` | `"ask"` (always forward to user) / `"delegate"` (orchestrator decides) / `"approve"` (orchestrator can auto-approve) |
265
- | `defaultHarness` | `string` | `"claude-code"` | Default harness for new sessions (`"claude-code"` / `"codex"`) |
266
- | `harnesses` | `object` | built-in defaults | Per-harness defaults and restrictions. Built-in defaults: `claude-code.defaultModel = "sonnet"`, `claude-code.allowedModels = ["sonnet","opus"]`, `codex.defaultModel = "gpt-5.4"`, `codex.allowedModels = ["gpt-5.4"]`, `codex.reasoningEffort = "medium"`, `codex.approvalPolicy = "on-request"` |
267
- | `defaultWorkdir` | `string` | — | Default working directory for new sessions |
268
- | `defaultWorktreeStrategy` | `string` | `"ask"` | Default worktree strategy for new sessions when `worktree_strategy` is omitted from `agent_launch`. Accepts any `WorktreeStrategy` value including `"delegate"` |
269
- | `worktreeDir` | `string` | `<repoRoot>/.worktrees` | Override base directory for agent worktrees |
74
+ When the task is done, the plugin can leave the branch for review, merge it automatically, or help create a PR. In `ask`, the user gets the same explicit decision buttons in the originating thread. In `delegate`, the orchestrator receives the diff context, may merge if safe, and always escalates PR decisions to the user. Planning artifacts belong in `/tmp/` — the agent will not commit analysis notes to the branch.
270
75
 
271
- Out of the box (with no custom config), the plugin delivers the full interactive experience: `planApproval: "ask"` ensures every plan is forwarded to the user for review before execution, and `defaultWorktreeStrategy: "ask"` means every session runs in an isolated git worktree and presents inline Telegram buttons (Merge locally / Create PR) on completion. Set either to `"delegate"` to hand those decisions to the orchestrator autonomously.
76
+ <img src="assets/delegate-readme.gif" alt="Delegated worktree flow with autonomous follow-through">
272
77
 
273
- ### Permission Mode Mapping By Harness
78
+ *The main checkout stays clean. The branch lifecycle happens in the worktree, and the chat thread stays current on what was shipped.*
274
79
 
275
- Permission modes are shared at the plugin API, but each harness maps them differently:
80
+ ### Worktree Lifecycle
276
81
 
277
- - **Claude Code harness**
278
- - `default`, `plan`, `bypassPermissions` are passed through the SDK
279
- - **Codex harness**
280
- - Always runs with SDK thread option `sandboxMode: "danger-full-access"`
281
- - Uses Codex SDK/CLI `approvalPolicy: "on-request"` by default, or `"never"` when `harnesses.codex.approvalPolicy` is set
282
- - Supports `harnesses.codex.defaultModel`, `harnesses.codex.allowedModels`, `harnesses.codex.reasoningEffort`, and `harnesses.codex.approvalPolicy`
283
- - In `bypassPermissions`, the harness adds filesystem root (`/` on POSIX) to Codex `additionalDirectories`, plus optional extras from `OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS` (comma-separated)
284
- - `setPermissionMode()` is applied by recreating the thread on the next turn via `resumeThread` (same thread ID)
285
- - `plan` remains a plugin behavioral orchestration constraint (planning/approval flow), not a Codex sandbox or SDK approval setting
82
+ Worktree-backed sessions move through product-facing lifecycle states:
286
83
 
287
- ### Runtime Environment Overrides
84
+ - `active`: sandbox still in use
85
+ - `pending decision`: waiting for merge / PR / dismiss follow-through
86
+ - `pr_open`: PR exists and the sandbox is being preserved
87
+ - `merged`: branch landed by normal git ancestry
88
+ - `released`: content is already on the base branch even though branch SHAs differ after rebase, squash, or cherry-pick
89
+ - `dismissed`: user intentionally discarded the sandbox
90
+ - `no_change`: session finished without a committed delta
288
91
 
289
- - `OPENCLAW_CODE_AGENT_SESSIONS_PATH` explicit persisted session index path
290
- - `OPENCLAW_HOME` — base dir for persisted session index when explicit path is unset (`$OPENCLAW_HOME/code-agent-sessions.json`)
291
- - `OPENCLAW_WORKTREE_DIR` — base directory for worktrees (default: system tmpdir)
292
- - `OPENCLAW_WORKTREE_BASE_BRANCH` — global base branch override (default: auto-detected from repo)
293
- - `OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS` — age threshold for orphan worktree cleanup (default: 1 hour)
294
- - `OPENCLAW_CODEX_BYPASS_ADDITIONAL_DIRS` — comma-separated extra directories for Codex bypass mode
295
- - `OPENCLAW_CODEX_HEARTBEAT_MS` — Codex activity heartbeat interval in milliseconds (default `10000`)
92
+ For cleanup, use `agent_worktree_cleanup(mode="preview_safe")` to preview what **Clean all safe** would remove, `mode="clean_safe"` to perform that cleanup, and `mode="preview_all"` to review both safe sandboxes and the reasons other worktrees were retained.
296
93
 
297
- ### Session Lifecycle + GC
94
+ ## Supported Harnesses
298
95
 
299
- - Active sessions live in runtime memory (`SessionManager.sessions`)
300
- - Terminal sessions are persisted with metadata/output stubs for resume and listing
301
- - Runtime records are evicted after `sessionGcAgeMinutes` (default 1440 / 24h)
302
- - Eviction means **removed from runtime cache**, not deleted permanently; persisted session records remain resumable
303
-
304
- ### Discord Notifications
96
+ | Harness | Status | Notes |
97
+ | --- | --- | --- |
98
+ | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | Supported | Native harness via `@anthropic-ai/claude-agent-sdk` |
99
+ | [Codex](https://github.com/openai/codex) | Supported | Native harness via Codex App Server over stdio |
305
100
 
306
- To route notifications to a Discord channel or user, set `originChannel` (or `fallbackChannel`) using the Discord format:
101
+ Launches and notifications work from Telegram, Discord, or any OpenClaw-supported channel. Telegram and Discord now share the same action-token callback flow for plan approvals, question options, resume/restart, and worktree decisions.
307
102
 
308
- ```
309
- discord|channel:CHANNEL_ID
310
- discord|accountId|channel:CHANNEL_ID
311
- ```
312
-
313
- - Use `channel:CHANNEL_ID` for a server channel, or `user:USER_ID` for a DM.
314
- - The `accountId` segment is optional and selects a specific Discord bot account when you have multiple Discord integrations.
315
- - Discord session keys (`agent:*:discord:channel:ID`) are auto-parsed — no explicit `originChannel` is required when a session is launched from a Discord thread.
316
- - If using bot notifications, set `allowBots: "mentions"` in your OpenClaw Discord integration config so the bot is permitted to receive and forward mention events.
317
-
318
- Example `fallbackChannel` for Discord:
319
-
320
- ```json
321
- "fallbackChannel": "discord|channel:1234567890123456789"
322
- ```
323
-
324
- With an explicit account:
325
-
326
- ```json
327
- "fallbackChannel": "discord|my-discord-bot|channel:1234567890123456789"
328
- ```
329
-
330
- ### Git Worktree Support
331
-
332
- When `worktree_strategy` is set to anything other than `"off"` (via `agent_launch` or plugin config `defaultWorktreeStrategy`), the agent will automatically create a git worktree for the session if the `workdir` is a git repository. This keeps the main checkout clean while the agent works in an isolated branch.
333
-
334
- **Behavior:**
335
- - Worktree path: `<OPENCLAW_WORKTREE_DIR>/openclaw-worktree-<session-name>` (default: system tmpdir)
336
- - Branch name: `agent/<session-name>` (sanitized, with random suffix if needed)
337
- - Worktrees are automatically cleaned up when the session terminates
338
- - **Branches are kept** — `agent/<name>` branches persist after session cleanup to allow pushing commits
339
- - Base branch auto-detection: `OPENCLAW_WORKTREE_BASE_BRANCH` env var → origin/HEAD → main → master
340
-
341
- **Worktree Strategies:**
342
-
343
- Control what happens to worktree branches when a session completes via `worktree_strategy`. Set it per-launch in `agent_launch`, or set a default for all sessions via `defaultWorktreeStrategy` in plugin config.
344
-
345
- - **`off`** — No worktree. Session runs in the main checkout.
346
- - **`ask`** (plugin config default) — Push branch and send a Telegram notification with inline buttons (Merge locally / Create PR). Also wakes the orchestrator with full decision context (diff summary, original prompt, decision guidance) to present the choice to the user.
347
- - **`delegate`** — Push branch and wake the orchestrator to decide autonomously (merge, create PR, or leave for later). Always sends a brief one-line notification to the user. **Available via `defaultWorktreeStrategy` plugin config; not exposed as a `worktree_strategy` tool parameter.**
348
- - **`auto-merge`** — Automatically merge back to the base branch on session completion. On conflicts, spawns a Claude Code conflict-resolver session.
349
- - **`auto-pr`** — Automatically open a GitHub PR on session completion (requires `gh` CLI). If `gh` is unavailable, falls back to `ask` strategy.
350
- - **`manual`** — Push the branch but take no further action; user handles merge/PR manually via `agent_merge` or `agent_pr`.
351
-
352
- Example with auto-pr:
353
- ```javascript
354
- agent_launch({
355
- prompt: "Fix the auth bug",
356
- worktree_strategy: "auto-pr"
357
- })
358
- ```
359
-
360
- **`output_mode: "deliverable"`:**
361
-
362
- Use this when the session is producing a document, report, or artifact rather than a code change. Instead of the default `✅ Completed` notification, the session emits `📄 Deliverable ready`:
363
-
364
- ```javascript
365
- agent_launch({
366
- prompt: "Write a technical spec for the new auth system",
367
- output_mode: "deliverable"
368
- })
369
- ```
370
-
371
- **Merge-Back Tools:**
372
-
373
- Four tools are available for manual worktree management:
374
-
375
- - `agent_merge` — Merge a worktree branch to base branch. On conflicts, spawns conflict-resolver session.
376
- - `agent_pr` — Create or update a GitHub PR for a worktree branch (requires `gh` CLI). Handles full PR lifecycle: creates new PRs, updates existing open PRs with comments, detects merged/closed PRs.
377
- - `agent_worktree_status` — Show worktree status for sessions (branch name, commits ahead, merge/PR status).
378
- - `agent_worktree_cleanup` — List and delete merged `agent/*` branches. Use `dry_run: true` to preview, `force: true` to delete all agent branches regardless of merge status.
379
-
380
- **PR Lifecycle Management:**
381
-
382
- When using `auto-pr` strategy or calling `agent_pr` manually:
383
-
384
- - **No PR exists**: Creates a new PR with auto-generated title and commit summary
385
- - **Open PR exists**: Pushes new commits and adds a detailed comment with diff stats
386
- - **Merged PR**: Notifies that the PR was already merged
387
- - **Closed PR**: Prompts user to choose: reopen manually, delete branch, or recreate PR
388
-
389
- **Conflict Resolution:**
390
-
391
- When auto-merge encounters conflicts, a Claude Code session is automatically spawned with `bypassPermissions` to resolve conflicts and commit the resolution. You'll receive a notification when this happens.
392
-
393
- **Cleanup:**
394
- Users can manually prune accumulated agent branches with `agent_worktree_cleanup`. Three categories are always protected from deletion: branches with active sessions, branches with unmerged commits, and branches with open PRs.
395
-
396
- ```javascript
397
- // Preview what would be deleted
398
- agent_worktree_cleanup({ workdir: "/path/to/repo", dry_run: true })
399
-
400
- // Delete fully merged branches (unmerged and open-PR branches are always kept)
401
- agent_worktree_cleanup({ workdir: "/path/to/repo" })
103
+ ## Quick Start
402
104
 
403
- // Skip the active-session check (e.g. session crashed and left a stale branch)
404
- // NOTE: unmerged-commit and open-PR protections still apply
405
- agent_worktree_cleanup({ workdir: "/path/to/repo", skip_session_check: true })
105
+ Install and enable the plugin:
406
106
 
407
- // Dismiss a pending worktree decision for a session without merging
408
- agent_worktree_cleanup({ session: "fix-auth-bug" })
107
+ ```bash
108
+ openclaw plugins install openclaw-code-agent
109
+ openclaw plugins enable openclaw-code-agent
110
+ openclaw gateway restart
409
111
  ```
410
112
 
411
- **Environment Variables:**
412
- - `OPENCLAW_WORKTREE_DIR` — Base directory for worktrees (default: system tmpdir)
413
- - `OPENCLAW_WORKTREE_BASE_BRANCH` — Global base branch override (default: auto-detected)
414
- - `OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS` — Age threshold for orphan worktree cleanup (default: 1 hour)
415
-
416
- **Limitations:**
417
- - Worktree creation requires the workdir to be a git repository
418
- - Only works with committed changes — uncommitted changes in the main checkout are not transferred to the worktree
419
- - Worktree creation is enabled by default via `defaultWorktreeStrategy: "ask"`. Pass `worktree_strategy: "off"` to `agent_launch` (or set `defaultWorktreeStrategy: "off"` in plugin config) to disable
420
- - Push and PR operations (`ask`, `auto-pr`, `delegate`) require a configured remote
113
+ This release targets the OpenClaw `v2026.4.9` external plugin contract. `package.json` now carries the plugin API compatibility and build metadata used by modern OpenClaw / ClawHub installs, so keep those fields in sync when bumping the plugin release baseline.
421
114
 
422
- ### Example
115
+ Add a minimal config block under `plugins.entries["openclaw-code-agent"]` in `~/.openclaw/openclaw.json`:
423
116
 
424
117
  ```json
425
118
  {
@@ -428,26 +121,19 @@ agent_worktree_cleanup({ session: "fix-auth-bug" })
428
121
  "openclaw-code-agent": {
429
122
  "enabled": true,
430
123
  "config": {
431
- "maxSessions": 3,
124
+ "fallbackChannel": "telegram|my-bot|123456789",
125
+ "planApproval": "ask",
126
+ "defaultWorktreeStrategy": "off",
432
127
  "harnesses": {
433
- "codex": {
434
- "defaultModel": "gpt-5.4",
435
- "allowedModels": ["gpt-5.4"],
436
- "reasoningEffort": "high",
437
- "approvalPolicy": "on-request"
438
- },
439
128
  "claude-code": {
440
129
  "defaultModel": "sonnet",
441
130
  "allowedModels": ["sonnet", "opus"]
131
+ },
132
+ "codex": {
133
+ "defaultModel": "gpt-5.4",
134
+ "allowedModels": ["gpt-5.4"],
135
+ "reasoningEffort": "medium"
442
136
  }
443
- },
444
- "permissionMode": "plan",
445
- "planApproval": "ask", // "ask" = always forward plans to user (default); "delegate" = orchestrator decides autonomously
446
- "defaultWorktreeStrategy": "ask", // "ask" = isolated worktree + inline Merge/PR buttons (default); "off" = no worktree
447
- "fallbackChannel": "telegram|my-bot|123456789",
448
- "agentChannels": {
449
- "/home/user/project-alpha": "telegram|my-bot|123456789",
450
- "/home/user/project-beta": "telegram|ops-bot|987654321"
451
137
  }
452
138
  }
453
139
  }
@@ -456,139 +142,77 @@ agent_worktree_cleanup({ session: "fix-auth-bug" })
456
142
  }
457
143
  ```
458
144
 
459
- ---
460
-
461
- ## Orchestration Skill
462
-
463
- <details>
464
- <summary>Example orchestration skill (click to expand)</summary>
465
-
466
- The plugin is a **transparent transport layer** — business logic lives in **OpenClaw skills**:
467
-
468
- ```markdown
469
- ---
470
- name: Coding Agent Orchestrator
471
- description: Orchestrates coding agent sessions with auto-response rules.
472
- metadata: {"openclaw": {"requires": {"plugins": ["openclaw-code-agent"]}}}
473
- ---
474
-
475
- # Coding Agent Orchestrator
476
-
477
- ## Anti-cascade rule
478
- When woken by a waiting-for-input or completion event, ONLY use agent_respond
479
- or agent_output for the referenced session. NEVER launch new sessions from wake events.
480
-
481
- ## Auto-response rules
145
+ If you run Codex sessions, keep Codex on the ChatGPT auth path:
482
146
 
483
- When a coding agent session asks a question, analyze and decide:
484
-
485
- ### Auto-respond (use `agent_respond` immediately):
486
- - Permission requests for file reads, writes, or bash commands -> "Yes, proceed."
487
- - Confirmations like "Should I continue?" -> "Yes, continue."
488
-
489
- ### Forward to user (everything else):
490
- - Architecture decisions, destructive operations, ambiguous requirements,
491
- scope changes, credential/production questions
492
- - Quote the agent's exact question. No commentary.
493
-
494
- ## Workflow
495
- 1. User sends a coding task -> `agent_launch(prompt, ...)`
496
- 2. Session runs in background. Monitor via wake events.
497
- 3. On wake event -> `agent_output` to read the question, then auto-respond or forward.
498
- 4. On completion -> summarize briefly: files changed, cost, duration, issues.
147
+ ```toml
148
+ forced_login_method = "chatgpt"
499
149
  ```
500
150
 
501
- A comprehensive orchestration skill is available at [`skills/code-agent-orchestration/SKILL.md`](skills/code-agent-orchestration/SKILL.md).
502
-
503
- </details>
504
-
505
- ---
506
-
507
- ## Architecture
508
-
509
- For a detailed look at how the plugin works internally, see the [docs/](docs/) directory:
151
+ Put that in `~/.codex/config.toml`.
510
152
 
511
- | Document | Description |
512
- |----------|-------------|
513
- | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | System design, component breakdown, and data flow |
514
- | [docs/NOTIFICATIONS.md](docs/NOTIFICATIONS.md) | Notification architecture, delivery model, and wake mechanism |
515
- | [docs/AGENT_CHANNELS.md](docs/AGENT_CHANNELS.md) | Multi-agent setup, notification routing, and workspace mapping |
516
- | [docs/TOOLS.md](docs/TOOLS.md) | Detailed tool reference with parameters and examples |
517
- | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Development guide, project structure, and build instructions |
153
+ Codex approval behavior is fixed to the supported execution path, and OpenClaw handles review gates through `permissionMode` plus `planApproval`.
518
154
 
519
- ---
520
-
521
- ## Development
522
-
523
- Build output is an **ESM bundle** at `dist/index.js` (`package.json` has `"type": "module"`).
155
+ Launch a first session:
524
156
 
525
157
  ```bash
526
- # Install dependencies
527
- pnpm install
158
+ /agent --name fix-auth Fix the auth middleware bug
159
+ /agent_sessions
160
+ /agent_respond fix-auth Add unit tests too
161
+ agent_launch(prompt="<new task>", resume_session_id="fix-auth", fork_session=true)
162
+ ```
528
163
 
529
- # Build (esbuild dist/index.js)
530
- pnpm run build
164
+ For multi-workspace or multi-bot setups, configure `agentChannels`. The full routing rules, config matrix, and notification behavior live in [docs/REFERENCE.md](docs/REFERENCE.md).
531
165
 
532
- # Type-check
533
- pnpm run typecheck
166
+ Prefer fully routable channel strings such as `telegram|123456789` or `telegram|my-bot|123456789`. A bare provider like `telegram` is only a weak fallback; the plugin now repairs topic routing from `originSessionKey` when possible, but explicit channels are still the safer default.
534
167
 
535
- # Run tests
536
- pnpm test
537
- ```
168
+ ### Upgrade Note For 3.2.0
538
169
 
539
- ### Project Structure
170
+ If you are upgrading from `3.1.0`, the important behavioral changes are:
540
171
 
541
- ```
542
- openclaw-code-agent/
543
- ├── index.ts # Plugin entry point
544
- ├── openclaw.plugin.json # Plugin manifest & config schema
545
- ├── src/
546
- │ ├── harness/ # Agent harness abstraction layer
547
- │ │ ├── types.ts # AgentHarness interface & message types
548
- │ │ ├── claude-code.ts # Claude Code harness (SDK wrapper)
549
- │ │ ├── codex.ts # Codex harness (@openai/codex-sdk thread stream wrapper)
550
- │ │ └── index.ts # Harness registry
551
- │ ├── types.ts # TypeScript interfaces
552
- │ ├── config.ts # Config singleton + channel resolution
553
- │ ├── format.ts # Formatting utilities
554
- │ ├── singletons.ts # Module-level singleton refs
555
- │ ├── session.ts # Session class (state machine, timers, harness)
556
- │ ├── session-manager.ts # Session pool management + lifecycle
557
- │ ├── session-store.ts # Persisted session/index storage abstraction
558
- │ ├── session-metrics.ts # Metrics recorder abstraction
559
- │ ├── wake-dispatcher.ts # Wake delivery + retry abstraction
560
- │ ├── notifications.ts # Notification service
561
- │ ├── actions/respond.ts # Shared respond logic (tool + command)
562
- │ ├── application/ # Shared app-layer logic used by tools + commands
563
- │ ├── tools/ # Tool implementations (9 tools)
564
- │ └── commands/ # Chat command implementations (7 commands)
565
- ├── tests/ # Unit tests (node:test + tsx)
566
- ├── skills/ # Orchestration skill definitions
567
- └── docs/ # Architecture & reference docs
568
- ```
172
+ - `defaultWorktreeStrategy` is back to `off`, so worktree isolation remains opt-in unless you configure it explicitly.
173
+ - `auto-merge` now attempts one autonomous conflict resolution before escalating.
174
+ - Completion wakes and no-change outcomes are deterministic and carry explicit approval/execution state instead of relying on transcript inference.
175
+ - Worktree cleanup is lifecycle-first and can now classify already-landed branches as `released`, which makes `preview_safe` and `clean_safe` more trustworthy after rebase, squash, or cherry-pick flows.
176
+ - Release validation now checks package/plugin version parity in addition to the normal `pnpm verify` gate.
569
177
 
570
- ---
178
+ ### Backend Capabilities
571
179
 
572
- ## Troubleshooting
180
+ - Claude Code stays on plugin-managed worktrees.
181
+ - Codex now runs through App Server structured events and may execute inside a native backend-managed worktree.
182
+ - Merge, PR, reminder, and decision policy remain plugin-owned above both backends.
183
+ - Operators should continue sessions by plugin session ID or name. Backend conversation IDs are accepted only for recovery and diagnostics.
573
184
 
574
- - Plugin installed but the gateway does not see it yet: run `openclaw gateway restart`.
575
- - Notifications are not arriving: verify `fallbackChannel` uses the exact format `"telegram|bot-name|chat-id"` in `~/.openclaw/openclaw.json`.
185
+ ## Tool Surface
576
186
 
577
- ---
187
+ | Tool | Purpose |
188
+ | --- | --- |
189
+ | `agent_launch` | Start a background coding session |
190
+ | `agent_respond` | Reply, redirect, approve a plan, or escalate permissions |
191
+ | `agent_output` | Read buffered session output |
192
+ | `agent_sessions` | List active and recent sessions |
193
+ | `agent_kill` | Stop or mark a session completed |
194
+ | `agent_stats` | Show aggregate usage and cost |
195
+ | `agent_merge` | Merge a worktree branch back to base |
196
+ | `agent_pr` | Create or update a GitHub PR |
197
+ | `agent_worktree_status` | Show authoritative lifecycle state, derived repo evidence, cleanup safety, and retained reasons |
198
+ | `agent_worktree_cleanup` | Clean all lifecycle-safe worktrees or dismiss one pending decision without touching live/unsafe worktrees |
199
+ | `goal_launch` | Start an explicit verifier or Ralph-style goal loop |
200
+ | `goal_status` | Show one goal task or list all goal tasks |
201
+ | `goal_stop` | Stop a running goal task |
578
202
 
579
- ## Contributing
203
+ The chat command surface mirrors the common workflows: `/agent`, `/agent_sessions`, `/agent_output`, `/agent_respond`, `/agent_kill`, `/agent_stats`, `/goal`, `/goal_status`, and `/goal_stop`.
580
204
 
581
- Contributions are welcome! Please:
205
+ ## Docs
582
206
 
583
- 1. Fork the repository
584
- 2. Create a feature branch
585
- 3. Make your changes with tests
586
- 4. Submit a pull request
587
-
588
- ---
207
+ | Doc | What It Covers |
208
+ | --- | --- |
209
+ | [docs/REFERENCE.md](docs/REFERENCE.md) | Install, config, tools, commands, notifications, routing, worktrees, troubleshooting |
210
+ | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Session manager, harness model, notification pipeline, persistence, worktree internals |
211
+ | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Local setup, repo layout, build/test flow, extension points |
212
+ | [docs/ACP-COMPARISON.md](docs/ACP-COMPARISON.md) | Current comparison with OpenClaw core ACP |
213
+ | [skills/code-agent-orchestration/SKILL.md](skills/code-agent-orchestration/SKILL.md) | Operational skill for orchestrating sessions from an agent |
214
+ | [CHANGELOG.md](CHANGELOG.md) | Release history |
589
215
 
590
216
  ## License
591
217
 
592
- MIT see [LICENSE](LICENSE) for details.
593
-
594
- Originally based on [alizarion/openclaw-claude-code-plugin](https://github.com/alizarion/openclaw-claude-code-plugin). Renamed to `openclaw-code-agent` to be harness-agnostic.
218
+ MIT. See [LICENSE](LICENSE).