@ccx-agent/opencode-ccx 0.2.2 → 0.2.4

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,7 +2,8 @@
2
2
  <h1 align="center">ccx</h1>
3
3
  <p align="center"><strong>Coding Copilot, eXtended</strong></p>
4
4
  <p align="center">
5
- An <a href="https://opencode.ai">OpenCode</a> plugin that makes your AI coding agent disciplined, verification-driven, and risk-aware.
5
+ An <a href="https://opencode.ai">OpenCode</a> plugin that brings Claude Code's behavioral discipline to any model.<br/>
6
+ Built by reverse-engineering Claude Code's prompt architecture and adapting it for the OpenCode ecosystem.
6
7
  </p>
7
8
  <p align="center">
8
9
  <a href="https://www.npmjs.com/package/@ccx-agent/opencode-ccx"><img src="https://img.shields.io/npm/v/@ccx-agent/opencode-ccx?style=flat-square&color=blue" alt="npm version"></a>
@@ -16,9 +17,13 @@
16
17
 
17
18
  LLM coding agents tend to over-engineer, skip verification, and run destructive commands without thinking. They add abstractions nobody asked for, report "done" without testing, and `rm -rf` without blinking.
18
19
 
20
+ Claude Code solved this with a sophisticated behavioral framework — but it's locked to Anthropic's CLI and pricing.
21
+
19
22
  ## The Solution
20
23
 
21
- ccx injects a complete behavioral framework into your OpenCode agent — system prompt sections that enforce coding discipline, specialized subagents that verify and plan, and safety hooks that catch dangerous operations before they execute.
24
+ ccx extracts the core behavioral principles from Claude Code's prompt architecture and makes them work in OpenCode — with any model, any provider.
25
+
26
+ It's not a wrapper or a proxy. It's a complete behavioral framework: 8 composable system prompt sections, 5 specialized subagents, 10 runtime hooks that dynamically adapt the agent's behavior every turn.
22
27
 
23
28
  **Before ccx:** Agent writes 200 lines, adds 3 helper files, says "done."
24
29
 
@@ -32,7 +37,9 @@ ccx injects a complete behavioral framework into your OpenCode agent — system
32
37
  opencode plugin @ccx-agent/opencode-ccx
33
38
  ```
34
39
 
35
- That's it. Restart OpenCode, press `@`, select **ccx**.
40
+ That's it. Restart OpenCode, press `Tab` to switch agent, select **ccx**.
41
+
42
+ > **Important:** ccx registers as a standalone agent, not a modifier on the default agent. You must switch to the `ccx` agent for the behavioral framework to take effect. If you want ccx to be your default agent, add `"default_agent": "ccx"` to your `opencode.json`.
36
43
 
37
44
  For global install (applies to all projects):
38
45
 
@@ -42,13 +49,13 @@ opencode plugin @ccx-agent/opencode-ccx -g
42
49
 
43
50
  ### Manual Installation
44
51
 
45
- If you prefer manual setup, add to your `opencode.json`:
52
+ Add to your `opencode.json`:
46
53
 
47
54
  ```jsonc
48
55
  // ~/.config/opencode/opencode.json
49
56
  {
50
57
  "plugin": [
51
- "@ccx-agent/opencode-ccx@0.1.0"
58
+ "@ccx-agent/opencode-ccx@0.2.2"
52
59
  ]
53
60
  }
54
61
  ```
@@ -74,21 +81,50 @@ Then in `opencode.json`:
74
81
 
75
82
  ## What's Inside
76
83
 
84
+ ### Architecture & Hook Integration
85
+
86
+ ccx intercepts the standard OpenCode execution loop at multiple points to inject discipline and safety:
87
+
88
+ ```mermaid
89
+ graph TD
90
+ User([User Request]) --> OP[OpenCode Agent Loop]
91
+
92
+ subgraph ccx Plugin
93
+ H1[chat.message] -.->|Inject Verification Reminders| OP
94
+ H2[chat.system.transform] -.->|Load CLAUDE.md & Context| OP
95
+ H3[chat.params] -.->|Agent-specific Temp/TopP| OP
96
+
97
+ OP --> ToolCall{Tool Call}
98
+
99
+ ToolCall -->|Before| H4[tool.execute.before]
100
+ H4 -.->|Risk Guard Warning| ToolCall
101
+
102
+ ToolCall -->|Execute| Exec[Run Tool]
103
+
104
+ Exec -->|After| H5[tool.execute.after]
105
+ H5 -.->|Track Edits & Remind| OP
106
+
107
+ OP -->|Context Full| H6[session.compacting]
108
+ H6 -.->|Preserve Plan & Verdict| OP
109
+ end
110
+ ```
111
+
77
112
  ### Primary Agent: `ccx`
78
113
 
79
- The main agent comes with 7 composable system prompt sections:
114
+ The main agent comes with 8 composable system prompt sections derived from Claude Code's prompt architecture:
80
115
 
81
116
  | Section | What it enforces |
82
117
  |---------|-----------------|
83
- | **intro** | Agent identity and trust boundary for untrusted content |
118
+ | **intro** | Agent identity, trust boundary, prompt injection defense |
84
119
  | **system-rules** | Permission model, context compression, prompt injection awareness |
85
- | **doing-tasks** | Scope control — no unrequested features, no speculative abstractions, duplicate code > premature abstraction |
120
+ | **doing-tasks** | Scope control — no unrequested features, no speculative abstractions, verify before declaring done |
86
121
  | **actions** | Risk classification — reversible vs irreversible, local vs shared, ask before destroying |
87
122
  | **using-tools** | Dedicated tools over Bash, parallel tool calls, structured progress tracking |
88
123
  | **tone-style** | Concise output, no emojis, `file:line` references, `owner/repo#N` links |
89
124
  | **output-efficiency** | Lead with the answer, skip filler, report at milestones not continuously |
125
+ | **environment** | Dynamic workspace context — cwd, git status, platform, shell |
90
126
 
91
- ### Subagents
127
+ ### 5 Specialized Subagents
92
128
 
93
129
  | Agent | Mode | Purpose |
94
130
  |-------|------|---------|
@@ -98,12 +134,65 @@ The main agent comes with 7 composable system prompt sections:
98
134
  | **ccx-general-purpose** | read-write | Multi-strategy worker for tasks outside other specialists |
99
135
  | **ccx-coordinator** | orchestrator | Decomposes complex work into Research, Synthesis, Implementation, Verification across parallel workers |
100
136
 
101
- ### Safety Hooks
137
+ ### 10 Runtime Hooks
138
+
139
+ ccx uses every major hook point in the OpenCode plugin API to dynamically shape agent behavior:
140
+
141
+ #### Static Hooks (startup)
142
+
143
+ | Hook | What it does |
144
+ |------|-------------|
145
+ | **config** | Registers the ccx agent + 5 subagents with their system prompts and tool restrictions |
146
+ | **tool** | Creates agent dispatch tools for the subagent registry |
147
+
148
+ #### Per-Turn Hooks (every LLM call)
149
+
150
+ | Hook | What it does |
151
+ |------|-------------|
152
+ | **chat.message** | Injects `<system-reminder>` with verification contract, edit tracking |
153
+ | **chat.params** | Tunes temperature/topP per agent — low for plan/verification (precision), higher for explore (creativity) |
154
+ | **experimental.chat.system.transform** | Dynamically injects project instructions (CLAUDE.md), session context (edited files list), and verification reminders into the system prompt |
155
+ | **tool.definition** | Appends safety rules to bash/edit/write tool descriptions, usage hints to glob/grep/read |
156
+ | **experimental.chat.messages.transform** | Trims long tool outputs (>8KB), collapses consecutive reasoning parts to save context |
157
+
158
+ #### Event Hooks (reactive)
102
159
 
103
- | Hook | Trigger | Behavior |
104
- |------|---------|----------|
105
- | **Risk Guard** | `tool.execute.before` | Warns on `rm -rf`, `git push --force`, `DROP TABLE`, and other irreversible commands |
106
- | **Verification Reminder** | `tool.execute.after` | Nudges the agent to run `ccx-verification` after N file edits |
160
+ | Hook | What it does |
161
+ |------|-------------|
162
+ | **tool.execute.before** | Risk Guard — flags `rm -rf`, `git push --force`, `DROP TABLE`, and other destructive patterns |
163
+ | **tool.execute.after** | Tracks file edits, feeds the dynamic verification reminder system |
164
+ | **experimental.session.compacting** | Customizes context compaction to preserve: original task, implementation plan, edited files, verification status, architectural decisions |
165
+
166
+ ---
167
+
168
+ ## Claude Code Alignment
169
+
170
+ ccx was built by studying Claude Code's prompt architecture and adapting its core behavioral principles for OpenCode. Here's what maps and what doesn't:
171
+
172
+ ### What ccx replicates
173
+
174
+ | Claude Code Feature | ccx Implementation |
175
+ |--------------------|--------------------|
176
+ | 8-section system prompt | 8 composable prompt sections, near-identical content |
177
+ | 5 subagent types (explore, plan, verify, general, coordinator) | Same 5 agents with equivalent prompts |
178
+ | Verification contract (3+ file edits → mandatory review) | Dynamic system prompt injection + chat.message reminders |
179
+ | VERDICT protocol (PASS/FAIL/PARTIAL) | Identical format and adversarial strategies |
180
+ | Per-turn `<system-reminder>` attachments | `chat.message` hook injects context each turn |
181
+ | Project instructions (CLAUDE.md) | Auto-loaded from CLAUDE.md / .claude/instructions.md / AGENTS.md |
182
+ | Tool safety hints | `tool.definition` hook appends rules to bash/edit/write descriptions |
183
+ | Context compaction preservation | Custom compaction prompt via `experimental.session.compacting` |
184
+ | Trust boundary / prompt injection defense | Explicit section in system prompt |
185
+
186
+ ### What only Claude Code has (engine-level)
187
+
188
+ | Feature | Why ccx can't replicate it |
189
+ |---------|---------------------------|
190
+ | Streaming tool execution (run tools while generating) | Engine-level, no plugin hook |
191
+ | Model fallback on 529 errors | Engine-level retry logic |
192
+ | Fork mode (shared prompt cache across subagents) | Engine-level session management |
193
+ | AI-powered safety classifier (YOLO mode) | Would require LLM call in hook, adds latency |
194
+ | Plan mode with user approval gate | Requires TUI integration (experimental) |
195
+ | AST-level bash command analysis | Possible but high complexity cost |
107
196
 
108
197
  ---
109
198
 
@@ -111,6 +200,41 @@ The main agent comes with 7 composable system prompt sections:
111
200
 
112
201
  The most opinionated part of ccx. Key design decisions:
113
202
 
203
+ ```mermaid
204
+ sequenceDiagram
205
+ participant User
206
+ participant CCX as ccx Agent
207
+ participant Plan as ccx-plan
208
+ participant Verify as ccx-verification
209
+ participant OS as Filesystem/Bash
210
+
211
+ User->>CCX: "Implement X feature"
212
+ CCX->>Plan: delegate(prompt)
213
+ Plan->>OS: Glob/Grep/Read (Read-only)
214
+ Plan-->>CCX: Blueprint & Critical Files
215
+
216
+ CCX->>OS: Edit/Write (Implementation)
217
+ CCX->>OS: Bash (Tests/Build)
218
+ Note over CCX: > 3 files edited<br>Hook injects: "Must verify"
219
+
220
+ CCX->>Verify: delegate(files, approach)
221
+
222
+ loop Verification Cycle
223
+ Verify->>OS: Bash (Run tests, lint, probes)
224
+ OS-->>Verify: Output
225
+
226
+ alt Fails or Needs Change
227
+ Verify-->>CCX: VERDICT: FAIL + Reproduction
228
+ CCX->>OS: Edit (Fix issues)
229
+ CCX->>Verify: delegate(corrections)
230
+ else Succeeds
231
+ Verify-->>CCX: VERDICT: PASS + Proof
232
+ end
233
+ end
234
+
235
+ CCX-->>User: "Done. Verification passed."
236
+ ```
237
+
114
238
  - **Execution over reading** — every check must include a `Command run` block with real terminal output. "I reviewed the code and it looks correct" is rejected.
115
239
  - **Self-rationalization awareness** — the prompt lists excuses the agent will reach for ("the code looks correct", "the tests already pass", "this would take too long") and instructs it to do the opposite.
116
240
  - **Type-specific strategies** — different verification approaches for frontend, backend, CLI, infrastructure, database migrations, refactoring, mobile, data pipelines, and more.
@@ -160,9 +284,19 @@ Create `~/.config/opencode/ccx.json` (global) or `.opencode/ccx.json` (project-l
160
284
  ccx/
161
285
  ├── src/
162
286
  │ ├── index.ts # Plugin entry — composes everything
163
- │ ├── prompts/ # 7 system prompt sections + composer + environment detector
287
+ │ ├── prompts/ # 8 system prompt sections + composer
164
288
  │ ├── agents/ # 5 subagent definitions with tailored prompts
165
- │ ├── hooks/ # config-handler, risk-guard, verification-reminder
289
+ │ ├── hooks/ # 10 runtime hooks
290
+ │ │ ├── config-handler.ts # Agent registration
291
+ │ │ ├── risk-guard.ts # Destructive command detection
292
+ │ │ ├── verification-reminder.ts # Edit tracking + nudge
293
+ │ │ ├── environment-context.ts # Session environment capture
294
+ │ │ ├── dynamic-system-prompt.ts # Per-turn system prompt injection
295
+ │ │ ├── chat-message.ts # Per-turn message augmentation
296
+ │ │ ├── chat-params.ts # Per-agent LLM parameter tuning
297
+ │ │ ├── compaction.ts # Context compaction customization
298
+ │ │ ├── tool-definition.ts # Tool description enhancement
299
+ │ │ └── message-transform.ts # Message history optimization
166
300
  │ ├── config/ # Zod schema + JSONC config loader
167
301
  │ └── plugin/ # OpenCode plugin interface + agent tool registry
168
302
  ├── .github/workflows/
@@ -0,0 +1,14 @@
1
+ import type { OhMyCCAgentConfig } from "../config/schema";
2
+ export declare function recordSessionIdle(sessionID: string): void;
3
+ export declare function recordSessionTurn(sessionID: string): void;
4
+ export declare function shouldCompactOnReturn(sessionID: string): boolean;
5
+ export declare function markCompacted(sessionID: string): void;
6
+ export declare function createIdleCompactionHook(config: OhMyCCAgentConfig, client: unknown): {
7
+ onEvent: (event: {
8
+ type: string;
9
+ properties?: {
10
+ sessionID?: string;
11
+ };
12
+ }) => Promise<void>;
13
+ onChatMessage: (sessionID: string) => Promise<void>;
14
+ };
@@ -7,9 +7,11 @@ type MessageInfo = {
7
7
  type: string;
8
8
  text?: string;
9
9
  output?: string;
10
+ tool?: string;
10
11
  [key: string]: unknown;
11
12
  }>;
12
13
  };
14
+ export declare function enableMicrocompact(): void;
13
15
  export declare function createMessageTransformHook(): (_input: Record<string, unknown>, output: {
14
16
  messages: MessageInfo[];
15
17
  }) => Promise<void>;
package/dist/index.js CHANGED
@@ -13738,7 +13738,9 @@ function createChatMessageHook(config2) {
13738
13738
  output.parts.push({
13739
13739
  type: "text",
13740
13740
  text: reminders.join(`
13741
- `)
13741
+ `),
13742
+ sessionID,
13743
+ messageID: input.messageID
13742
13744
  });
13743
13745
  }
13744
13746
  };
@@ -14522,6 +14524,33 @@ function createEnvironmentContext(directory) {
14522
14524
  // src/hooks/message-transform.ts
14523
14525
  var MAX_TOOL_OUTPUT_LENGTH = 8000;
14524
14526
  var TOOL_OUTPUT_TRIM_TO = 4000;
14527
+ var KEEP_RECENT_TOOL_OUTPUTS = 5;
14528
+ var CLEARABLE_TOOLS = new Set(["read", "grep", "glob", "bash", "webfetch"]);
14529
+ var CLEARED_MARKER = "[Old tool result content cleared]";
14530
+ function microcompactOldToolOutputs(messages) {
14531
+ const toolParts = [];
14532
+ for (let i = 0;i < messages.length; i++) {
14533
+ const msg = messages[i];
14534
+ if (msg.info.role !== "assistant")
14535
+ continue;
14536
+ for (const part of msg.parts) {
14537
+ if (part.type !== "tool")
14538
+ continue;
14539
+ const toolName = typeof part.tool === "string" ? part.tool.toLowerCase() : "";
14540
+ if (!CLEARABLE_TOOLS.has(toolName))
14541
+ continue;
14542
+ if (typeof part.output !== "string" || part.output === CLEARED_MARKER)
14543
+ continue;
14544
+ toolParts.push({ part, index: i });
14545
+ }
14546
+ }
14547
+ const clearCount = toolParts.length - KEEP_RECENT_TOOL_OUTPUTS;
14548
+ if (clearCount <= 0)
14549
+ return;
14550
+ for (let i = 0;i < clearCount; i++) {
14551
+ toolParts[i].part.output = CLEARED_MARKER;
14552
+ }
14553
+ }
14525
14554
  function trimLongToolOutputs(messages) {
14526
14555
  for (const msg of messages) {
14527
14556
  if (msg.info.role !== "assistant")
@@ -14557,13 +14586,87 @@ function collapseConsecutiveReasoningParts(messages) {
14557
14586
  msg.parts = collapsed;
14558
14587
  }
14559
14588
  }
14589
+ var microcompactEnabled = false;
14590
+ function enableMicrocompact() {
14591
+ microcompactEnabled = true;
14592
+ }
14560
14593
  function createMessageTransformHook() {
14561
14594
  return async (_input, output) => {
14595
+ if (microcompactEnabled) {
14596
+ microcompactOldToolOutputs(output.messages);
14597
+ microcompactEnabled = false;
14598
+ }
14562
14599
  trimLongToolOutputs(output.messages);
14563
14600
  collapseConsecutiveReasoningParts(output.messages);
14564
14601
  };
14565
14602
  }
14566
14603
 
14604
+ // src/hooks/idle-compaction.ts
14605
+ var sessionStates2 = new Map;
14606
+ var IDLE_THRESHOLD_MS = 30 * 60 * 1000;
14607
+ var MIN_TURNS_BEFORE_COMPACT = 10;
14608
+ function getIdleState(sessionID) {
14609
+ const existing = sessionStates2.get(sessionID);
14610
+ if (existing)
14611
+ return existing;
14612
+ const state = {
14613
+ lastIdleTimestamp: 0,
14614
+ turnCount: 0,
14615
+ compactedAt: 0
14616
+ };
14617
+ sessionStates2.set(sessionID, state);
14618
+ return state;
14619
+ }
14620
+ function recordSessionIdle(sessionID) {
14621
+ const state = getIdleState(sessionID);
14622
+ state.lastIdleTimestamp = Date.now();
14623
+ }
14624
+ function recordSessionTurn(sessionID) {
14625
+ getIdleState(sessionID).turnCount++;
14626
+ }
14627
+ function shouldCompactOnReturn(sessionID) {
14628
+ const state = getIdleState(sessionID);
14629
+ if (state.lastIdleTimestamp === 0)
14630
+ return false;
14631
+ if (state.turnCount < MIN_TURNS_BEFORE_COMPACT)
14632
+ return false;
14633
+ const idleDuration = Date.now() - state.lastIdleTimestamp;
14634
+ if (idleDuration < IDLE_THRESHOLD_MS)
14635
+ return false;
14636
+ const turnsSinceCompact = state.turnCount - state.compactedAt;
14637
+ return turnsSinceCompact >= MIN_TURNS_BEFORE_COMPACT;
14638
+ }
14639
+ function markCompacted(sessionID) {
14640
+ const state = getIdleState(sessionID);
14641
+ state.compactedAt = state.turnCount;
14642
+ }
14643
+ function createIdleCompactionHook(config2, client) {
14644
+ const typedClient = client;
14645
+ return {
14646
+ onEvent: async (event) => {
14647
+ if (!config2.enabled)
14648
+ return;
14649
+ if (event.type !== "session.idle")
14650
+ return;
14651
+ const sessionID = event.properties?.sessionID;
14652
+ if (!sessionID)
14653
+ return;
14654
+ recordSessionIdle(sessionID);
14655
+ },
14656
+ onChatMessage: async (sessionID) => {
14657
+ if (!config2.enabled)
14658
+ return;
14659
+ if (!shouldCompactOnReturn(sessionID))
14660
+ return;
14661
+ enableMicrocompact();
14662
+ try {
14663
+ await typedClient.session.summarize({ path: { id: sessionID } });
14664
+ markCompacted(sessionID);
14665
+ } catch {}
14666
+ }
14667
+ };
14668
+ }
14669
+
14567
14670
  // src/hooks/risk-guard.ts
14568
14671
  var RISK_PATTERNS = [
14569
14672
  /rm\s+-rf\b/i,
@@ -27067,6 +27170,7 @@ function createPluginInterface(args) {
27067
27170
  const compactionHook = createCompactionHook();
27068
27171
  const toolDefinitionHook = createToolDefinitionHook();
27069
27172
  const messageTransformHook = createMessageTransformHook();
27173
+ const idleCompaction = createIdleCompactionHook(config3, ctx.client);
27070
27174
  return {
27071
27175
  config: configHook,
27072
27176
  tool: createAgentTools(),
@@ -27083,8 +27187,18 @@ function createPluginInterface(args) {
27083
27187
  },
27084
27188
  event: async (input) => {
27085
27189
  await environmentContext(input, {});
27190
+ const rawEvent = input.event;
27191
+ if (rawEvent) {
27192
+ await idleCompaction.onEvent(rawEvent);
27193
+ }
27194
+ },
27195
+ "chat.message": async (input, output) => {
27196
+ await chatMessageHook(input, output);
27197
+ if (input.sessionID) {
27198
+ recordSessionTurn(input.sessionID);
27199
+ await idleCompaction.onChatMessage(input.sessionID);
27200
+ }
27086
27201
  },
27087
- "chat.message": chatMessageHook,
27088
27202
  "chat.params": chatParamsHook,
27089
27203
  "tool.definition": toolDefinitionHook,
27090
27204
  "experimental.chat.system.transform": dynamicSystemPrompt,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ccx-agent/opencode-ccx",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Production-grade prompt engineering for OpenCode — disciplined coding, risk-aware actions, adversarial verification",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -34,6 +34,7 @@
34
34
  ],
35
35
  "license": "MIT",
36
36
  "dependencies": {
37
+ "@ccx-agent/opencode-ccx": "^0.2.3",
37
38
  "@opencode-ai/plugin": "^1.2.24",
38
39
  "zod": "^4.1.8"
39
40
  },