@ccx-agent/opencode-ccx 0.1.0 → 0.2.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ccx-agent
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,48 +1,73 @@
1
- # ccx — Coding Copilot, eXtended
1
+ <p align="center">
2
+ <h1 align="center">ccx</h1>
3
+ <p align="center"><strong>Coding Copilot, eXtended</strong></p>
4
+ <p align="center">
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.
7
+ </p>
8
+ <p align="center">
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>
10
+ <a href="https://github.com/Rejudge-F/ccx/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Rejudge-F/ccx?style=flat-square" alt="license"></a>
11
+ </p>
12
+ </p>
2
13
 
3
- An [OpenCode](https://opencode.ai) plugin that turns your AI coding agent into a disciplined software engineer. ccx injects a complete behavioral framework — system prompt sections, specialized subagents, and safety hooks — so the agent writes less unnecessary code, verifies its own work, and thinks before running destructive commands.
14
+ ---
4
15
 
5
- ## Why
16
+ ## The Problem
6
17
 
7
- Out of the box, LLM coding agents tend to over-engineer, skip verification, and act before thinking. ccx fixes this by injecting a set of behavioral constraints and specialized subagents into your OpenCode session:
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.
8
19
 
9
- - **Writes less, not more** — no speculative abstractions, no unrequested refactors, no gold-plating
10
- - **Verifies before reporting done** — an adversarial verification agent stress-tests implementations with real commands, not code reading
11
- - **Asks before destroying** — a risk guard flags `rm -rf`, `git push --force`, and other irreversible actions before they execute
12
- - **Delegates intelligently** — a coordinator agent decomposes complex tasks into research, implementation, and verification phases across parallel workers
20
+ Claude Code solved this with a sophisticated behavioral framework — but it's locked to Anthropic's CLI and pricing.
13
21
 
14
- ## What You Get
22
+ ## The Solution
15
23
 
16
- | Component | What it does |
17
- |-----------|-------------|
18
- | **ccx** (primary agent) | Main agent with 7 composable system prompt sections governing coding discipline, risk awareness, tool usage, and output style |
19
- | **ccx-explore** | Read-only codebase search specialist. Fast parallel file/content search across large repos |
20
- | **ccx-plan** | Read-only software architect. Investigates code and produces step-by-step implementation plans with critical file lists |
21
- | **ccx-verification** | Adversarial verifier with VERDICT protocol (PASS/FAIL/PARTIAL). Runs builds, tests, linters, then tries to break things with boundary values, concurrency probes, and idempotency checks |
22
- | **ccx-general-purpose** | Multi-strategy task worker for anything that doesn't fit the specialists |
23
- | **ccx-coordinator** | Multi-agent orchestrator. Decomposes work into Research → Synthesis → Implementation → Verification phases across parallel workers |
24
- | **Risk Guard** | `tool.execute.before` hook that warns on destructive operations |
25
- | **Verification Reminder** | `tool.execute.after` hook that nudges verification after N file edits |
24
+ ccx extracts the core behavioral principles from Claude Code's prompt architecture and makes them work in OpenCode — with any model, any provider.
26
25
 
27
- ## Install
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.
27
+
28
+ **Before ccx:** Agent writes 200 lines, adds 3 helper files, says "done."
29
+
30
+ **After ccx:** Agent writes 40 lines, runs the tests, spawns a verification agent that tries to break it, then reports the VERDICT.
31
+
32
+ ---
33
+
34
+ ## Quick Start
35
+
36
+ ```bash
37
+ opencode plugin @ccx-agent/opencode-ccx
38
+ ```
39
+
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`.
43
+
44
+ For global install (applies to all projects):
28
45
 
29
46
  ```bash
30
- bun add ccx
47
+ opencode plugin @ccx-agent/opencode-ccx -g
31
48
  ```
32
49
 
33
- Add to your OpenCode config:
50
+ ### Manual Installation
51
+
52
+ Add to your `opencode.json`:
34
53
 
35
54
  ```jsonc
36
55
  // ~/.config/opencode/opencode.json
37
56
  {
38
57
  "plugin": [
39
- "ccx"
40
- // ... your other plugins
58
+ "@ccx-agent/opencode-ccx@0.2.2"
41
59
  ]
42
60
  }
43
61
  ```
44
62
 
45
- Or use a local build:
63
+ ### Development / Local Build
64
+
65
+ ```bash
66
+ git clone https://github.com/Rejudge-F/ccx.git
67
+ cd ccx && bun install && bun run build
68
+ ```
69
+
70
+ Then in `opencode.json`:
46
71
 
47
72
  ```jsonc
48
73
  {
@@ -52,9 +77,180 @@ Or use a local build:
52
77
  }
53
78
  ```
54
79
 
55
- Restart OpenCode. Press `@` to see `ccx` in the agent list.
80
+ ---
81
+
82
+ ## What's Inside
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
+
112
+ ### Primary Agent: `ccx`
113
+
114
+ The main agent comes with 8 composable system prompt sections derived from Claude Code's prompt architecture:
115
+
116
+ | Section | What it enforces |
117
+ |---------|-----------------|
118
+ | **intro** | Agent identity, trust boundary, prompt injection defense |
119
+ | **system-rules** | Permission model, context compression, prompt injection awareness |
120
+ | **doing-tasks** | Scope control — no unrequested features, no speculative abstractions, verify before declaring done |
121
+ | **actions** | Risk classification — reversible vs irreversible, local vs shared, ask before destroying |
122
+ | **using-tools** | Dedicated tools over Bash, parallel tool calls, structured progress tracking |
123
+ | **tone-style** | Concise output, no emojis, `file:line` references, `owner/repo#N` links |
124
+ | **output-efficiency** | Lead with the answer, skip filler, report at milestones not continuously |
125
+ | **environment** | Dynamic workspace context — cwd, git status, platform, shell |
126
+
127
+ ### 5 Specialized Subagents
128
+
129
+ | Agent | Mode | Purpose |
130
+ |-------|------|---------|
131
+ | **ccx-explore** | read-only | Fast codebase search — parallel glob/grep/read across large repos |
132
+ | **ccx-plan** | read-only | Software architect — produces step-by-step plans with critical file lists |
133
+ | **ccx-verification** | read-only | Adversarial verifier — VERDICT protocol (PASS/FAIL/PARTIAL), runs real commands, catches self-rationalizations |
134
+ | **ccx-general-purpose** | read-write | Multi-strategy worker for tasks outside other specialists |
135
+ | **ccx-coordinator** | orchestrator | Decomposes complex work into Research, Synthesis, Implementation, Verification across parallel workers |
136
+
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)
159
+
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 |
196
+
197
+ ---
198
+
199
+ ## The Verification Agent
200
+
201
+ The most opinionated part of ccx. Key design decisions:
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
+
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.
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.
240
+ - **Type-specific strategies** — different verification approaches for frontend, backend, CLI, infrastructure, database migrations, refactoring, mobile, data pipelines, and more.
241
+ - **Adversarial probes required** — before issuing PASS, at least one probe must be attempted: concurrency, boundary values, idempotency, or orphan operations.
242
+
243
+ Output format:
56
244
 
57
- ## Configure
245
+ ```
246
+ VERDICT: PASS
247
+ ```
248
+
249
+ or `FAIL` with reproduction steps, or `PARTIAL` with what couldn't be verified and why.
250
+
251
+ ---
252
+
253
+ ## Configuration
58
254
 
59
255
  Create `~/.config/opencode/ccx.json` (global) or `.opencode/ccx.json` (project-level):
60
256
 
@@ -73,59 +269,63 @@ Create `~/.config/opencode/ccx.json` (global) or `.opencode/ccx.json` (project-l
73
269
 
74
270
  | Field | Type | Default | Description |
75
271
  |-------|------|---------|-------------|
76
- | `enabled` | boolean | `true` | Master toggle |
77
- | `disabled_sections` | string[] | `[]` | System prompt sections to skip (e.g., `["tone-style", "output-efficiency"]`) |
78
- | `disabled_hooks` | string[] | `[]` | Hooks to disable (e.g., `["risk-guard"]`) |
79
- | `output_style` | string \| null | `null` | Custom output style name |
80
- | `verification.auto_remind` | boolean | `true` | Nudge verification after file edits |
81
- | `verification.min_file_edits` | number | `3` | Edit threshold before nudge |
82
-
83
- ## How It Works
272
+ | `enabled` | `boolean` | `true` | Master toggle for the entire plugin |
273
+ | `disabled_sections` | `string[]` | `[]` | Prompt sections to skip (e.g., `["tone-style"]`) |
274
+ | `disabled_hooks` | `string[]` | `[]` | Hooks to disable (e.g., `["risk-guard"]`) |
275
+ | `output_style` | `string \| null` | `null` | Custom output style name |
276
+ | `verification.auto_remind` | `boolean` | `true` | Auto-nudge verification after edits |
277
+ | `verification.min_file_edits` | `number` | `3` | File edit threshold before nudge |
84
278
 
85
- ccx hooks into OpenCode's plugin lifecycle at two points:
86
-
87
- **1. `config` hook** — Injects the `ccx` primary agent (with full system prompt) and 5 subagents into `config.agent`. The primary agent's prompt is composed from 7 independent sections + subagent orchestration guidance.
88
-
89
- **2. `tool.execute.before/after` hooks** — Risk Guard scans commands for destructive patterns pre-execution; Verification Reminder tracks file edit count post-execution.
90
-
91
- ### System Prompt Sections
92
-
93
- The primary agent's system prompt is assembled from these composable sections:
94
-
95
- | Section | Purpose |
96
- |---------|---------|
97
- | `intro` | Agent identity and trust boundary |
98
- | `system-rules` | Permission model, context compression, prompt injection awareness |
99
- | `doing-tasks` | Coding discipline — scope control, minimal abstraction, honest reporting |
100
- | `actions` | Risk classification for reversible vs irreversible operations |
101
- | `using-tools` | Prefer dedicated tools over Bash, parallel tool call strategy |
102
- | `tone-style` | No emojis, concise output, code reference formatting |
103
- | `output-efficiency` | Lead with answers, skip filler, milestone-based updates |
104
-
105
- ### Verification Agent
106
-
107
- The verification agent is the most opinionated component. Key behaviors:
108
-
109
- - **Runs commands, not reads code** — every check must include a `Command run` block with actual terminal output
110
- - **Catches its own rationalizations** — the prompt explicitly lists excuses the agent will reach for ("the code looks correct", "the tests already pass") and instructs it to do the opposite
111
- - **Adapts by change type** — different verification strategies for frontend, backend, CLI, infrastructure, database migrations, refactoring, etc.
112
- - **Requires adversarial probes** — at least one concurrency, boundary value, or idempotency test before issuing PASS
279
+ ---
113
280
 
114
281
  ## Project Structure
115
282
 
116
283
  ```
117
284
  ccx/
118
285
  ├── src/
119
- │ ├── index.ts # Plugin entry point
120
- │ ├── prompts/ # 7 system prompt sections + compose + environment
121
- │ ├── agents/ # 5 subagent definitions (explore, plan, verification, coordinator, general-purpose)
122
- │ ├── hooks/ # config-handler, risk-guard, verification-reminder, environment-context, system-prompt-injector
123
- │ ├── config/ # Zod schema + JSONC config loader
124
- │ └── plugin/ # OpenCode plugin interface + tool registry
286
+ │ ├── index.ts # Plugin entry — composes everything
287
+ │ ├── prompts/ # 8 system prompt sections + composer
288
+ │ ├── agents/ # 5 subagent definitions with tailored prompts
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
300
+ │ ├── config/ # Zod schema + JSONC config loader
301
+ │ └── plugin/ # OpenCode plugin interface + agent tool registry
302
+ ├── .github/workflows/
303
+ │ └── publish.yml # Auto-publish to npm on tag push
125
304
  ├── package.json
126
305
  └── tsconfig.json
127
306
  ```
128
307
 
308
+ ---
309
+
310
+ ## Contributing
311
+
312
+ ```bash
313
+ git clone https://github.com/Rejudge-F/ccx.git
314
+ cd ccx
315
+ bun install
316
+ bun run typecheck # type check
317
+ bun run build # build to dist/
318
+ ```
319
+
320
+ To publish a new version:
321
+
322
+ ```bash
323
+ # bump version in package.json, then:
324
+ git add -A && git commit -m "chore: bump to x.y.z"
325
+ git tag vx.y.z && git push origin main --tags
326
+ # GitHub Actions auto-publishes to npm
327
+ ```
328
+
129
329
  ## License
130
330
 
131
331
  MIT
@@ -0,0 +1,21 @@
1
+ import type { OhMyCCAgentConfig } from "../config/schema";
2
+ type ChatMessageInput = {
3
+ sessionID: string;
4
+ agent?: string;
5
+ model?: {
6
+ providerID: string;
7
+ modelID: string;
8
+ };
9
+ messageID?: string;
10
+ };
11
+ type ChatMessageOutput = {
12
+ message: Record<string, unknown>;
13
+ parts: Array<{
14
+ type: string;
15
+ text?: string;
16
+ [key: string]: unknown;
17
+ }>;
18
+ };
19
+ export declare function recordToolCall(sessionID: string, tool: string, file?: string): void;
20
+ export declare function createChatMessageHook(config: OhMyCCAgentConfig): (input: ChatMessageInput, output: ChatMessageOutput) => Promise<void>;
21
+ export {};
@@ -0,0 +1,18 @@
1
+ type ChatParamsInput = {
2
+ sessionID: string;
3
+ agent: string;
4
+ model: {
5
+ modelID?: string;
6
+ [key: string]: unknown;
7
+ };
8
+ provider: unknown;
9
+ message: unknown;
10
+ };
11
+ type ChatParamsOutput = {
12
+ temperature: number;
13
+ topP: number;
14
+ topK: number;
15
+ options: Record<string, unknown>;
16
+ };
17
+ export declare function createChatParamsHook(): (input: ChatParamsInput, output: ChatParamsOutput) => Promise<void>;
18
+ export {};
@@ -0,0 +1,6 @@
1
+ export declare function createCompactionHook(): (input: {
2
+ sessionID: string;
3
+ }, output: {
4
+ context: string[];
5
+ prompt?: string;
6
+ }) => Promise<void>;
@@ -0,0 +1,9 @@
1
+ import type { OhMyCCAgentConfig } from "../config/schema";
2
+ export declare function trackFileEdit(sessionID: string, filePath: string): void;
3
+ export declare function markVerificationTriggered(sessionID: string): void;
4
+ export declare function createDynamicSystemPrompt(config: OhMyCCAgentConfig, directory: string): (input: {
5
+ sessionID?: string;
6
+ model: unknown;
7
+ }, output: {
8
+ system: string[];
9
+ }) => Promise<void>;
@@ -0,0 +1,16 @@
1
+ type MessageInfo = {
2
+ info: {
3
+ role: string;
4
+ [key: string]: unknown;
5
+ };
6
+ parts: Array<{
7
+ type: string;
8
+ text?: string;
9
+ output?: string;
10
+ [key: string]: unknown;
11
+ }>;
12
+ };
13
+ export declare function createMessageTransformHook(): (_input: Record<string, unknown>, output: {
14
+ messages: MessageInfo[];
15
+ }) => Promise<void>;
16
+ export {};
@@ -0,0 +1,6 @@
1
+ export declare function createToolDefinitionHook(): (input: {
2
+ toolID: string;
3
+ }, output: {
4
+ description: string;
5
+ parameters: unknown;
6
+ }) => Promise<void>;
package/dist/index.js CHANGED
@@ -1,12 +1,16 @@
1
1
  // @bun
2
2
  var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
3
7
  var __export = (target, all) => {
4
8
  for (var name in all)
5
9
  __defProp(target, name, {
6
10
  get: all[name],
7
11
  enumerable: true,
8
12
  configurable: true,
9
- set: (newValue) => all[name] = () => newValue
13
+ set: __exportSetter.bind(all, name)
10
14
  });
11
15
  };
12
16
 
@@ -13634,6 +13638,143 @@ function loadConfig(directory) {
13634
13638
  return readConfigFile(projectConfigPath) ?? readConfigFile(userConfigPath) ?? defaults;
13635
13639
  }
13636
13640
 
13641
+ // src/hooks/dynamic-system-prompt.ts
13642
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
13643
+ import { join as join2 } from "path";
13644
+ var sessionStates = new Map;
13645
+ function getState(sessionID) {
13646
+ const existing = sessionStates.get(sessionID);
13647
+ if (existing)
13648
+ return existing;
13649
+ const state = {
13650
+ editedFiles: new Set,
13651
+ verificationTriggered: false,
13652
+ turnCount: 0
13653
+ };
13654
+ sessionStates.set(sessionID, state);
13655
+ return state;
13656
+ }
13657
+ function trackFileEdit(sessionID, filePath) {
13658
+ getState(sessionID).editedFiles.add(filePath);
13659
+ }
13660
+ function loadProjectInstructions(directory) {
13661
+ const candidates = ["CLAUDE.md", ".claude/instructions.md", "AGENTS.md"];
13662
+ for (const name of candidates) {
13663
+ const fullPath = join2(directory, name);
13664
+ if (existsSync2(fullPath)) {
13665
+ try {
13666
+ const content = readFileSync2(fullPath, "utf-8").trim();
13667
+ if (content)
13668
+ return content;
13669
+ } catch {
13670
+ continue;
13671
+ }
13672
+ }
13673
+ }
13674
+ return null;
13675
+ }
13676
+ function createDynamicSystemPrompt(config2, directory) {
13677
+ const projectInstructions = loadProjectInstructions(directory);
13678
+ return async (input, output) => {
13679
+ if (!config2.enabled)
13680
+ return;
13681
+ const sessionID = input.sessionID;
13682
+ if (projectInstructions) {
13683
+ output.system.push(`# Project Instructions
13684
+
13685
+ The following instructions were found in the project root and MUST be followed:
13686
+
13687
+ ${projectInstructions}`);
13688
+ }
13689
+ if (sessionID) {
13690
+ const state = getState(sessionID);
13691
+ state.turnCount++;
13692
+ if (state.editedFiles.size > 0) {
13693
+ const fileList = [...state.editedFiles].slice(-20).join(", ");
13694
+ output.system.push(`# Session Context
13695
+
13696
+ Files edited in this session (${state.editedFiles.size} total): ${fileList}`);
13697
+ }
13698
+ if (config2.verification.auto_remind && state.editedFiles.size >= config2.verification.min_file_edits && !state.verificationTriggered) {
13699
+ output.system.push(`# Verification Reminder
13700
+
13701
+ You have edited ${state.editedFiles.size} files in this session. You MUST run verification (via ccx-verification subagent) before declaring the task complete. This is not optional.`);
13702
+ }
13703
+ }
13704
+ };
13705
+ }
13706
+
13707
+ // src/hooks/chat-message.ts
13708
+ var EDIT_TOOLS = new Set(["edit", "write"]);
13709
+ var recentToolCalls = new Map;
13710
+ function recordToolCall(sessionID, tool, file2) {
13711
+ const calls = recentToolCalls.get(sessionID) ?? [];
13712
+ calls.push({ tool, file: file2 });
13713
+ if (calls.length > 50)
13714
+ calls.shift();
13715
+ recentToolCalls.set(sessionID, calls);
13716
+ }
13717
+ function createChatMessageHook(config2) {
13718
+ return async (input, output) => {
13719
+ if (!config2.enabled)
13720
+ return;
13721
+ const { sessionID, agent } = input;
13722
+ if (!sessionID)
13723
+ return;
13724
+ const calls = recentToolCalls.get(sessionID);
13725
+ if (calls && calls.length > 0) {
13726
+ const editedInRecent = calls.filter((c) => EDIT_TOOLS.has(c.tool) && c.file).map((c) => c.file);
13727
+ for (const file2 of editedInRecent) {
13728
+ trackFileEdit(sessionID, file2);
13729
+ }
13730
+ }
13731
+ if (agent && !agent.startsWith("ccx"))
13732
+ return;
13733
+ const reminders = [];
13734
+ if (config2.verification.auto_remind && calls && calls.filter((c) => EDIT_TOOLS.has(c.tool)).length >= config2.verification.min_file_edits) {
13735
+ reminders.push(`<system-reminder>You have made file edits. Remember the verification contract: run ccx-verification before declaring completion if you have 3+ file edits, backend/API changes, or infrastructure changes.</system-reminder>`);
13736
+ }
13737
+ if (reminders.length > 0) {
13738
+ output.parts.push({
13739
+ type: "text",
13740
+ text: reminders.join(`
13741
+ `),
13742
+ sessionID,
13743
+ messageID: input.messageID
13744
+ });
13745
+ }
13746
+ };
13747
+ }
13748
+
13749
+ // src/hooks/chat-params.ts
13750
+ var AGENT_PARAMS = {
13751
+ "ccx-plan": { temperature: 0.3, topP: 0.9 },
13752
+ "ccx-verification": { temperature: 0.2, topP: 0.85 },
13753
+ "ccx-explore": { temperature: 0.5, topP: 0.95 },
13754
+ "ccx-coordinator": { temperature: 0.4, topP: 0.9 },
13755
+ "ccx-general-purpose": { temperature: 0.5, topP: 0.95 }
13756
+ };
13757
+ function createChatParamsHook() {
13758
+ return async (input, output) => {
13759
+ const agentParams = AGENT_PARAMS[input.agent];
13760
+ if (!agentParams)
13761
+ return;
13762
+ if (agentParams.temperature !== undefined)
13763
+ output.temperature = agentParams.temperature;
13764
+ if (agentParams.topP !== undefined)
13765
+ output.topP = agentParams.topP;
13766
+ if (agentParams.topK !== undefined)
13767
+ output.topK = agentParams.topK;
13768
+ };
13769
+ }
13770
+
13771
+ // src/hooks/compaction.ts
13772
+ function createCompactionHook() {
13773
+ return async (input, output) => {
13774
+ output.context.push("IMPORTANT: When summarizing this conversation, you MUST preserve the following:", "1. The original user task/request and any refinements", "2. The implementation plan if one was created", "3. All file paths that were edited, created, or deleted", "4. The current verification status (PASS/FAIL/PARTIAL) if verification was run", "5. Any unresolved issues, blockers, or pending decisions", "6. Key architectural decisions and their rationale", "7. The names of any subagents that were dispatched and their outcomes", "Do NOT summarize tool outputs verbatim \u2014 capture only the conclusions and any error messages.");
13775
+ };
13776
+ }
13777
+
13637
13778
  // src/prompts/actions.ts
13638
13779
  function getActionsSection() {
13639
13780
  return `# Executing actions with care
@@ -13688,8 +13829,8 @@ function getDoingTasksSection() {
13688
13829
  }
13689
13830
 
13690
13831
  // src/prompts/environment.ts
13691
- import { existsSync as existsSync2 } from "fs";
13692
- import { join as join2 } from "path";
13832
+ import { existsSync as existsSync3 } from "fs";
13833
+ import { join as join3 } from "path";
13693
13834
  import { type as osType, release as osRelease } from "os";
13694
13835
  function normalizeShell(shell) {
13695
13836
  if (shell.includes("zsh"))
@@ -13715,7 +13856,7 @@ function getOsVersion() {
13715
13856
  }
13716
13857
  function detectGit(cwd) {
13717
13858
  try {
13718
- return existsSync2(join2(cwd, ".git"));
13859
+ return existsSync3(join3(cwd, ".git"));
13719
13860
  } catch {
13720
13861
  return false;
13721
13862
  }
@@ -14348,8 +14489,8 @@ function createConfigHook(config2, directory) {
14348
14489
  }
14349
14490
 
14350
14491
  // src/hooks/environment-context.ts
14351
- import { existsSync as existsSync3 } from "fs";
14352
- import { join as join3 } from "path";
14492
+ import { existsSync as existsSync4 } from "fs";
14493
+ import { join as join4 } from "path";
14353
14494
  var environmentBySession = new Map;
14354
14495
  function isRecord(value) {
14355
14496
  return typeof value === "object" && value !== null;
@@ -14367,7 +14508,7 @@ function createEnvironmentContext(directory) {
14367
14508
  const sessionID = typeof event.sessionID === "string" ? event.sessionID : typeof event.sessionId === "string" ? event.sessionId : undefined;
14368
14509
  const environment = {
14369
14510
  cwd: directory,
14370
- isGit: existsSync3(join3(directory, ".git")),
14511
+ isGit: existsSync4(join4(directory, ".git")),
14371
14512
  platform: process.platform,
14372
14513
  shell: process.env.SHELL ?? "unknown"
14373
14514
  };
@@ -14380,6 +14521,51 @@ function createEnvironmentContext(directory) {
14380
14521
  };
14381
14522
  }
14382
14523
 
14524
+ // src/hooks/message-transform.ts
14525
+ var MAX_TOOL_OUTPUT_LENGTH = 8000;
14526
+ var TOOL_OUTPUT_TRIM_TO = 4000;
14527
+ function trimLongToolOutputs(messages) {
14528
+ for (const msg of messages) {
14529
+ if (msg.info.role !== "assistant")
14530
+ continue;
14531
+ for (const part of msg.parts) {
14532
+ if (part.type !== "tool")
14533
+ continue;
14534
+ const output = typeof part.output === "string" ? part.output : undefined;
14535
+ if (output && output.length > MAX_TOOL_OUTPUT_LENGTH) {
14536
+ const head = output.slice(0, TOOL_OUTPUT_TRIM_TO / 2);
14537
+ const tail = output.slice(-TOOL_OUTPUT_TRIM_TO / 2);
14538
+ const trimmed = output.length - TOOL_OUTPUT_TRIM_TO;
14539
+ part.output = `${head}
14540
+
14541
+ ... [${trimmed} characters trimmed] ...
14542
+
14543
+ ${tail}`;
14544
+ }
14545
+ }
14546
+ }
14547
+ }
14548
+ function collapseConsecutiveReasoningParts(messages) {
14549
+ for (const msg of messages) {
14550
+ if (msg.info.role !== "assistant")
14551
+ continue;
14552
+ const collapsed = [];
14553
+ for (const part of msg.parts) {
14554
+ if (part.type === "reasoning" && collapsed.length > 0 && collapsed[collapsed.length - 1].type === "reasoning") {
14555
+ continue;
14556
+ }
14557
+ collapsed.push(part);
14558
+ }
14559
+ msg.parts = collapsed;
14560
+ }
14561
+ }
14562
+ function createMessageTransformHook() {
14563
+ return async (_input, output) => {
14564
+ trimLongToolOutputs(output.messages);
14565
+ collapseConsecutiveReasoningParts(output.messages);
14566
+ };
14567
+ }
14568
+
14383
14569
  // src/hooks/risk-guard.ts
14384
14570
  var RISK_PATTERNS = [
14385
14571
  /rm\s+-rf\b/i,
@@ -14427,6 +14613,35 @@ function createRiskGuard() {
14427
14613
  };
14428
14614
  }
14429
14615
 
14616
+ // src/hooks/tool-definition.ts
14617
+ var TOOL_SAFETY_HINTS = {
14618
+ bash: "SAFETY: Before executing, verify the command is non-destructive. Never run rm -rf, git push --force, git reset --hard, DROP TABLE, or TRUNCATE TABLE without explicit user approval. Prefer --dry-run flags when available. Quote all file paths containing spaces.",
14619
+ edit: "SAFETY: Always read the file first before editing. Preserve existing indentation. Do not modify files you have not examined. Never edit .env files or credentials.",
14620
+ write: "SAFETY: Prefer editing existing files over creating new ones. Never write to .env or credential files. Avoid creating files in the workspace root unless they are permanent source code."
14621
+ };
14622
+ var TOOL_CONTEXT_HINTS = {
14623
+ glob: "Use this for finding files by name pattern. Prefer this over bash find commands.",
14624
+ grep: "Use this for searching file contents by regex. Prefer this over bash grep/rg commands.",
14625
+ read: "Use this for reading file contents. Prefer this over bash cat/head/tail commands."
14626
+ };
14627
+ function createToolDefinitionHook() {
14628
+ return async (input, output) => {
14629
+ const toolName = input.toolID.toLowerCase();
14630
+ const safetyHint = TOOL_SAFETY_HINTS[toolName];
14631
+ if (safetyHint) {
14632
+ output.description = `${output.description}
14633
+
14634
+ ${safetyHint}`;
14635
+ }
14636
+ const contextHint = TOOL_CONTEXT_HINTS[toolName];
14637
+ if (contextHint) {
14638
+ output.description = `${output.description}
14639
+
14640
+ ${contextHint}`;
14641
+ }
14642
+ };
14643
+ }
14644
+
14430
14645
  // src/hooks/verification-reminder.ts
14431
14646
  var sessionStateById = new Map;
14432
14647
  var EDIT_TOOL_NAMES = new Set(["edit", "write"]);
@@ -26848,14 +27063,35 @@ function createPluginInterface(args) {
26848
27063
  const riskGuard = createRiskGuard();
26849
27064
  const verificationReminder = createVerificationReminder(config3);
26850
27065
  const environmentContext = createEnvironmentContext(ctx.directory);
27066
+ const dynamicSystemPrompt = createDynamicSystemPrompt(config3, ctx.directory);
27067
+ const chatMessageHook = createChatMessageHook(config3);
27068
+ const chatParamsHook = createChatParamsHook();
27069
+ const compactionHook = createCompactionHook();
27070
+ const toolDefinitionHook = createToolDefinitionHook();
27071
+ const messageTransformHook = createMessageTransformHook();
26851
27072
  return {
26852
27073
  config: configHook,
26853
27074
  tool: createAgentTools(),
26854
27075
  "tool.execute.before": riskGuard,
26855
- "tool.execute.after": verificationReminder,
27076
+ "tool.execute.after": async (input, output) => {
27077
+ await verificationReminder(input, output);
27078
+ const sessionID = typeof input.sessionID === "string" ? input.sessionID : undefined;
27079
+ const tool3 = typeof input.tool === "string" ? input.tool.toLowerCase() : undefined;
27080
+ if (sessionID && tool3) {
27081
+ const args2 = input.args;
27082
+ const file3 = typeof args2?.filePath === "string" ? args2.filePath : typeof args2?.path === "string" ? args2.path : undefined;
27083
+ recordToolCall(sessionID, tool3, file3);
27084
+ }
27085
+ },
26856
27086
  event: async (input) => {
26857
27087
  await environmentContext(input, {});
26858
- }
27088
+ },
27089
+ "chat.message": chatMessageHook,
27090
+ "chat.params": chatParamsHook,
27091
+ "tool.definition": toolDefinitionHook,
27092
+ "experimental.chat.system.transform": dynamicSystemPrompt,
27093
+ "experimental.chat.messages.transform": messageTransformHook,
27094
+ "experimental.session.compacting": compactionHook
26859
27095
  };
26860
27096
  }
26861
27097
 
@@ -2,7 +2,7 @@ import type { Plugin } from "@opencode-ai/plugin";
2
2
  import type { OhMyCCAgentConfig } from "../config/schema";
3
3
  type PluginContext = Parameters<Plugin>[0];
4
4
  type PluginInstance = Awaited<ReturnType<Plugin>>;
5
- export type PluginInterface = Pick<PluginInstance, "config" | "tool" | "tool.execute.before" | "tool.execute.after" | "event">;
5
+ export type PluginInterface = Pick<PluginInstance, "config" | "tool" | "tool.execute.before" | "tool.execute.after" | "event" | "chat.message" | "chat.params" | "tool.definition" | "experimental.chat.system.transform" | "experimental.chat.messages.transform" | "experimental.session.compacting">;
6
6
  export declare function createPluginInterface(args: {
7
7
  ctx: PluginContext;
8
8
  config: OhMyCCAgentConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ccx-agent/opencode-ccx",
3
- "version": "0.1.0",
3
+ "version": "0.2.3",
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",
@@ -20,6 +20,10 @@
20
20
  "typecheck": "tsc --noEmit",
21
21
  "prepublishOnly": "bun run clean && bun run build"
22
22
  },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/Rejudge-F/ccx.git"
26
+ },
23
27
  "keywords": [
24
28
  "opencode",
25
29
  "plugin",