@kodizm/acp 0.4.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.
Files changed (4) hide show
  1. package/LICENSE +200 -0
  2. package/README.md +659 -0
  3. package/dist/index.js +135 -0
  4. package/package.json +50 -0
package/LICENSE ADDED
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may accept support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or support.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file's class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright 2026 Kodizm
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
199
+ implied. See the License for the specific language governing
200
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,659 @@
1
+ # kodizm-acp
2
+
3
+ Kodizm runtime's ACP bridge. One protocol controls Claude Code, codex, and opencode CLIs under a single canonical surface, so the orchestrator wires every backend the same way: token rollup, model selection, system prompt replace + append, additional directories, MCP server injection, skill injection, image content blocks, thinking + output + tool streaming, subagent observability, resume + fork, permission + AskUserQuestion, MCP elicitation, dynamic tool dispatch, chatgpt token refresh, deferred-permission lifecycle (Pattern B incl. cross-process resume), debug capture, heartbeat liveness, structured failure events.
4
+
5
+ Status: Phase 1, 1.5, 1.6, 1.7, 2, 3 complete. Three backends ship: `claude`, `codex`, `opencode`.
6
+
7
+ ## Backend parity matrix
8
+
9
+ Every Phase 1 / 1.5 / 1.6 / 1.7 / 2 / 3 surface is wired identically across the three shipping backends. The orchestrator does not branch on backend; the same canonical wire shape carries every feature.
10
+
11
+ | Feature | Claude | Codex | Opencode |
12
+ |---------|--------|-------|----------|
13
+ | `session/new` + `session/load` + `session/fork` + `session/cancel` | yes | yes | yes |
14
+ | `session/prompt` text content blocks | yes | yes | yes |
15
+ | `session/prompt` image content blocks (`{ type: 'image', uri: 'file://...' \| 'http(s)://...' }`) | yes | yes (`localImage` / `image` UserInput) | yes (opencode `FilePart`) |
16
+ | Token + cost rollup (`usage` event) | yes | yes | yes (from `Assistant.tokens` + `cost` on `message.updated`) |
17
+ | Model selection (`model` field + `model_advertisement` event) | yes | yes (api-key auth honors override; chatgpt-mode keeps default) | yes (canonical `<providerID>/<modelID>` slash format) |
18
+ | `additionalDirectories` -> sandbox | yes (SDK) | yes (`SandboxPolicy.WorkspaceWrite.writableRoots`) | n/a (opencode has no sandbox primitive; falls back to container symlink layout) |
19
+ | `mcpServers` inline injection | yes (SDK options) | yes (CODEX_HOME `config.toml` + `[mcp_servers.*]`) | yes (per-session `sdk.mcp.add` + reverse-name map) |
20
+ | `systemPrompt` replace / append | yes | yes (codex `baseInstructions` / `developerInstructions`) | yes (forwarded as-is to v1 prompt) |
21
+ | `skills` pre-load + `skill_activation` events | yes (`skillEvents: true`) | n/a (codex has no skill loader) | n/a (opencode has no skill loader) |
22
+ | `toolPolicy.defaultMode` (5 enum) | yes | yes | yes (translates to opencode `Ruleset` per-session) |
23
+ | `toolPolicy.allow` / `deny` / `ask` | yes (SDK rules) | yes (sandbox + permission profile) | yes (lowercase native tool keys + mcp `<server>_<tool>` translation) |
24
+ | `autoCompact` on/off | yes (`DISABLE_AUTO_COMPACT=1`) | yes (codex respects `model_auto_compact_token_limit`) | yes (opencode summarizer respects orchestrator decision) |
25
+ | `permission_request` event + `session/request_permission` RPC | yes | yes (3 codex RPCs collapse to one canonical) | yes (`permission.asked` bus event collapses to one canonical) |
26
+ | Legacy `applyPatchApproval` + `execCommandApproval` | n/a | yes (auto-aliased to v2 `item/*/requestApproval` shape) | n/a |
27
+ | `question_request` + `session/ask_user_question` RPC | yes (AskUserQuestion tool) | yes (`item/tool/requestUserInput` + `mcpServer/elicitation/request` both feed in) | yes (opencode `Question.Service` + `tool/question.ts` native; `multiple` -> `multiSelect`, `custom` -> `_meta.customByQuestion`) |
28
+ | `session/dynamic_tool_call` (orchestrator-hosted tools) | n/a | yes (codex `item/tool/call`) | n/a |
29
+ | `session/codex_chatgpt_token_refresh` | n/a | yes (codex `account/chatgptAuthTokens/refresh`) | n/a |
30
+ | `permission_deferred` + `permission_resumed` events (Pattern B) | yes | yes | yes (synthetic tool_result via `sdk.session.message.append` carrying `__KODIZM_PERMISSION_DEFERRED__`) |
31
+ | Cross-process Pattern B (`hydrateSession()` API) | yes | yes | yes (`loadSession({sessionId, _meta.opencodeSessionId})`) |
32
+ | `session/permission_deferred_persist` + `session/permission_deferred_state` RPCs | yes | yes | yes |
33
+ | Pattern B JSONL injection | `~/.claude/projects/.../<sessionId>.jsonl` | `~/.codex/sessions/rollout-*-<threadId>.jsonl` (resume-by-threadId) | opencode SQLite via `sdk.session.message.append` |
34
+ | `compaction_started` + `compaction_completed` events | yes | yes (`ContextCompaction` item lifecycle) | yes (`session.updated` `time.compacting` set + `session.compacted`) |
35
+ | `subagent_spawn` + `subagent_complete` events | yes (Task tool) | yes (`CollabAgentToolCall`; chatgpt-mode tier-gated) | yes (opencode `task` tool spawns child sessions; `state.metadata.sessionID` = childId) |
36
+ | `tool_call_begin` / `progress` / `end` events | yes | yes (CommandExecution / FileChange / McpToolCall) | yes (per-callID latched: exactly one begin + one end pair, despite multiple opencode `running` updates) |
37
+ | `output_chunk` event | yes | yes | yes (`message.part.delta` `field=text` on `TextPart`) |
38
+ | `thinking_chunk` event | yes | yes (`item/reasoning/summaryTextDelta` + `item/reasoning/textDelta`) | yes (`message.part.delta` `field=text` on `ReasoningPart`) |
39
+ | `debug_log` (9 stages) + per-session toggle | yes | yes | yes |
40
+ | `heartbeat` event | yes | yes | yes |
41
+ | `session_failed` event + 7-value reason enum | yes | yes | yes (`ProviderAuthError` -> `auth_error`, `APIError 429/503` -> `rate_limit`, `APIError 5xx` -> `transport_error`, `MessageAbortedError` -> cancel sentinel) |
42
+ | Per-reason `shouldExitOnReason` exit policy | yes | yes | yes |
43
+ | Graceful SIGTERM shutdown hook | yes | yes (subprocess `kill()` + grace) | yes (`bridge.stop()` per session) |
44
+ | `BackendStallError` (-32006) | yes | yes | yes |
45
+
46
+ `DriverCapabilities` carries 8 flags. Phase 3 added `askQuestion: boolean` to advertise first-class user-question support; Claude (SDK plugin), codex (`requestUserInput` + elicitation), and opencode (native `Question.Service`) all set it `true`.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ bun install
52
+ bun build src/index.ts --target=bun --outdir=dist
53
+ ```
54
+
55
+ ## Environment
56
+
57
+ | Variable | Description |
58
+ |----------|-------------|
59
+ | `KODIZM_BACKEND` | `claude` (Phase 1) / `codex` (Phase 2) / `opencode` (Phase 3) |
60
+ | `CODEX_API_KEY` or `OPENAI_API_KEY` | codex backend api-key auth (alternative to chatgpt OAuth) |
61
+ | `CLAUDE_CODE_OAUTH_TOKEN` + `CLAUDE_CODE_REMOTE=1` | Subscription auth |
62
+ | `ANTHROPIC_API_KEY` | API key auth (fallback) |
63
+ | `OPENCODE_AUTH_CONTENT` | opencode per-provider auth blob (JSON keyed by providerID; layered onto subprocess env at `bridge.start`) |
64
+ | `KODIZM_LOG_LEVEL` | `debug` / `info` / `warn` / `error`. Default `info` |
65
+ | `KODIZM_DEBUG` | `1` enables process-wide debug capture |
66
+ | `KODIZM_DEBUG_DIR` | Forensic JSONL dir, default `/tmp/kodizm-debug` |
67
+ | `KODIZM_DEBUG_RAW_SECRETS` | `1` disables allow-list redaction (incident-only) |
68
+ | `KODIZM_ACP_FORWARD_STDERR` | `1` tees codex subprocess stderr to parent stderr (diagnosis) |
69
+
70
+ Stdout is reserved for ACP frames. Never log to stdout.
71
+
72
+ ## Quick start
73
+
74
+ ```bash
75
+ # Claude:
76
+ echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}' \
77
+ | KODIZM_BACKEND=claude CLAUDE_CODE_OAUTH_TOKEN="sk-ant-oat01-..." CLAUDE_CODE_REMOTE=1 \
78
+ bun run dist/index.js
79
+
80
+ # Codex (same protocol, just switch the backend env):
81
+ echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}' \
82
+ | KODIZM_BACKEND=codex OPENAI_API_KEY="sk-..." \
83
+ bun run dist/index.js
84
+
85
+ # Opencode (auth blob via env so the per-session subprocess inherits it):
86
+ echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}' \
87
+ | KODIZM_BACKEND=opencode \
88
+ OPENCODE_AUTH_CONTENT='{"opencode-go":{"type":"api","key":"..."}}' \
89
+ bun run dist/index.js
90
+ ```
91
+
92
+ Programmatic embedding:
93
+
94
+ ```ts
95
+ import { ClaudeDriver } from '@/backends/claude/driver.ts'
96
+ import { query } from '@anthropic-ai/claude-agent-sdk'
97
+
98
+ const driver = new ClaudeDriver({
99
+ credentials: { type: 'subscription', token: process.env.CLAUDE_CODE_OAUTH_TOKEN! },
100
+ agentInfo: { version: '0.0.1' },
101
+ sdk: { query: ({ prompt, options }) => query({ prompt, options }) },
102
+ })
103
+
104
+ const { sessionId } = await driver.newSession({
105
+ cwd: process.cwd(),
106
+ mcpServers: [],
107
+ model: 'claude-haiku-4-5-20251001',
108
+ })
109
+
110
+ const events: SessionUpdateEvent[] = []
111
+ const result = await driver.prompt(
112
+ sessionId,
113
+ { sessionId, prompt: [{ type: 'text', text: 'Say hi.' }] },
114
+ { send: (event) => events.push(event) },
115
+ )
116
+ ```
117
+
118
+ ## API reference
119
+
120
+ ### `createAcpServer({ transport, backend?, debugSink? })`
121
+
122
+ JSON-RPC 2.0 dispatcher over an NDJSON transport. When `backend` is set, the server auto-registers six lifecycle methods (`initialize`, `session/new`, `session/prompt`, `session/cancel`, `session/load`, `session/fork`) with schema validation + capability gating. When `debugSink` is set, every inbound + outbound frame tees through `record('rpc.in' | 'rpc.out', frame)`.
123
+
124
+ ```ts
125
+ import { createAcpServer } from '@/server/acp-server.ts'
126
+ import { createNdjsonTransport } from '@/server/transport.ts'
127
+ import { DebugRecorder } from '@/util/debug-recorder.ts'
128
+
129
+ const recorder = new DebugRecorder({
130
+ sessionId: 's1',
131
+ emit: { send: (e) => server.notify('sessionUpdate', e) },
132
+ debug: true,
133
+ debugFilePath: '/tmp/kodizm-debug/s1.jsonl',
134
+ })
135
+
136
+ const server = createAcpServer({
137
+ transport: createNdjsonTransport({ readable: Bun.stdin.stream(), writable }),
138
+ backend: driver,
139
+ debugSink: recorder,
140
+ })
141
+
142
+ await server.serve()
143
+ ```
144
+
145
+ ### `RPC_METHOD_ALIASES`
146
+
147
+ The permission RPC name drifted between SDK drafts (`requestPermission` ↔ `session/request_permission`). Handlers registered under either form route to the same handler.
148
+
149
+ ```ts
150
+ server.on('session/request_permission', handler) // also: requestPermission
151
+ server.on('session/ask_user_question', askHandler) // also: askUserQuestion
152
+ ```
153
+
154
+ ### `BackendDriver`
155
+
156
+ Every backend implements this contract.
157
+
158
+ ```ts
159
+ interface BackendDriver {
160
+ initialize(params: InitializeRequest): Promise<InitializeResult>
161
+ newSession(params: NewSessionRequest): Promise<NewSessionResult>
162
+ prompt(sessionId: string, params: PromptRequest, emit: EventEmitter): Promise<PromptResult>
163
+ cancel(request: CancelRequest): Promise<void>
164
+ loadSession(params: LoadSessionRequest): Promise<NewSessionResult>
165
+ forkSession(params: ForkSessionRequest): Promise<NewSessionResult>
166
+ capabilities(): DriverCapabilities
167
+ }
168
+
169
+ interface DriverCapabilities {
170
+ resume: boolean
171
+ fork: boolean
172
+ fileUpload: boolean
173
+ thinking: boolean
174
+ subagent: boolean
175
+ skillEvents: boolean
176
+ debug: boolean
177
+ askQuestion: boolean
178
+ }
179
+
180
+ interface PromptResult {
181
+ stopReason: 'end_turn' | 'cancelled' | 'process_died' | 'max_tokens' | 'tool_use' | 'session_failed'
182
+ failureReason?: SessionFailedReason
183
+ failureDetail?: string
184
+ }
185
+ ```
186
+
187
+ ### `ClaudeDriver`
188
+
189
+ ```ts
190
+ const { sessionId } = await driver.newSession({
191
+ cwd: '/workspace',
192
+ mcpServers: [
193
+ { type: 'http', name: 'kodizm', url: 'https://kodizm.com/mcp/internal',
194
+ headers: [{ name: 'Authorization', value: 'Bearer kdz-int-jwt.x.y' }] },
195
+ ],
196
+ additionalDirectories: ['/data/shared'],
197
+ systemPrompt: { append: 'Always respond in Turkish.' },
198
+ model: 'claude-haiku-4-5-20251001',
199
+ skills: ['my-coding'],
200
+ toolPolicy: { defaultMode: 'default', allow: ['Read'], deny: ['Bash:git push*'] },
201
+ autoCompact: false,
202
+ permissionTimeoutMs: 30_000,
203
+ permissionDeferTimeoutMs: 1_800_000,
204
+ debug: true,
205
+ heartbeatIntervalMs: 10_000,
206
+ inactivityThresholdMs: 60_000,
207
+ })
208
+ ```
209
+
210
+ Per-turn override:
211
+
212
+ ```ts
213
+ await driver.prompt(
214
+ sessionId,
215
+ { sessionId, prompt: [...], model: 'claude-sonnet-4-6' },
216
+ emit,
217
+ )
218
+ ```
219
+
220
+ Cancel:
221
+
222
+ ```ts
223
+ await driver.cancel({ sessionId })
224
+ // emits cancelled event; prompt() returns stopReason='cancelled'
225
+ ```
226
+
227
+ ### `CodexDriver`
228
+
229
+ Identical contract; just import the codex driver instead. The orchestrator does not branch on backend; every wire shape from `NewSessionRequest` down through `SessionUpdateEvent` is the same.
230
+
231
+ ```ts
232
+ import { CodexDriver } from '@/backends/codex/driver.ts'
233
+ import { CodexAppServerProcess } from '@/backends/codex/app-server-spawn.ts'
234
+
235
+ const driver = new CodexDriver({
236
+ agentInfo: { version: '0.0.1' },
237
+ spawnFactory: async (options) => {
238
+ const proc = new CodexAppServerProcess({
239
+ binaryPath: 'codex',
240
+ configPath: options.configPath,
241
+ })
242
+ await proc.spawn()
243
+ return proc
244
+ },
245
+ server, // for outbound canonical permission / ask / dynamic-tool / token-refresh RPCs
246
+ deferredStore, // optional Pattern B store
247
+ })
248
+
249
+ const { sessionId } = await driver.newSession({
250
+ cwd: '/workspace',
251
+ mcpServers: [
252
+ { type: 'http', name: 'kodizm', url: 'https://kodizm.com/mcp/internal' },
253
+ ],
254
+ toolPolicy: { defaultMode: 'default' },
255
+ systemPrompt: { append: 'Always respond in Turkish.' },
256
+ permissionDeferTimeoutMs: 1_800_000,
257
+ debug: true,
258
+ heartbeatIntervalMs: 10_000,
259
+ inactivityThresholdMs: 60_000,
260
+ })
261
+ ```
262
+
263
+ The driver:
264
+ - spawns one `codex app-server --listen stdio://` subprocess per session (no `--config <path>` flag in app-server mode; per-key overrides via `-c key=value` and `[mcp_servers.*]` via CODEX_HOME's `config.toml`).
265
+ - maps canonical `permissionMode` 5-enum to codex's `AskForApproval` (`untrusted` / `on-failure` / `on-request` / `never`) + pairs `plan` mode with `ReadOnly` sandbox.
266
+ - maps canonical `systemPrompt` to codex's `baseInstructions` (string form) or `developerInstructions` (`{ append }` form) per `v2/ThreadStartParams.ts`.
267
+ - forwards canonical image content blocks to codex `UserInput`: `file://` paths and bare absolute paths become `localImage`; `http(s)://` URLs become `image`.
268
+ - collapses 7 codex serverRequest channels onto canonical wire:
269
+ - 3 approval RPCs (`item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, `item/permissions/requestApproval`) plus 2 legacy aliases (`applyPatchApproval`, `execCommandApproval`) -> canonical `permission_request` event with `name` discriminator (`codex_exec` / `codex_apply_patch` / `codex_permission_grant`).
270
+ - `item/tool/requestUserInput` + `mcpServer/elicitation/request` -> canonical `question_request` event + `session/ask_user_question` RPC.
271
+ - `item/tool/call` -> outbound `session/dynamic_tool_call` RPC.
272
+ - `account/chatgptAuthTokens/refresh` -> outbound `session/codex_chatgpt_token_refresh` RPC.
273
+ - maps codex `ContextCompaction` items to canonical `compaction_started` / `compaction_completed`.
274
+ - maps codex `CollabAgentToolCall` items to canonical `subagent_spawn` / `subagent_complete` (parent `sessionId` + fresh Kodizm `childId`; codex thread ids never leak).
275
+ - routes codex `item/reasoning/summaryTextDelta` + `item/reasoning/textDelta` to canonical `thinking_chunk` (separate from `output_chunk`).
276
+ - writes Pattern B sentinel as `RolloutItem` line + resumes via `thread/resume { threadId }`.
277
+
278
+ ### `CodexDriver.hydrateSession({ sessionId, codexThreadId, codexJsonlPath?, ... })`
279
+
280
+ Cross-process Pattern B entry. A fresh driver instance can resume a Kodizm sessionId by replaying codex's `thread/resume` against the persisted threadId. Use this when the original driver instance died (container restart, deploy, machine shutdown) and a new driver needs to consume a deferred-permission cached answer or keep streaming on the same Kodizm `sessionId`.
281
+
282
+ ```ts
283
+ await driverB.hydrateSession({
284
+ sessionId, // same Kodizm sessionId from Process A
285
+ codexThreadId, // captured from Process A's session state
286
+ codexJsonlPath, // optional; codex glob-resolves from threadId if absent
287
+ cwd: process.cwd(),
288
+ mcpServers: [],
289
+ toolPolicy: { defaultMode: 'default' },
290
+ })
291
+
292
+ // Process B's first prompt automatically picks up the orchestrator's
293
+ // cached answer from the deferredStore + fires permission_resumed.
294
+ ```
295
+
296
+ ### `OpencodeDriver`
297
+
298
+ Same contract; switches the backend env to `opencode`. The driver spawns `opencode serve --port 0 --hostname 127.0.0.1` per Kodizm session via `createOpencodeServer` from `@opencode-ai/sdk`, then drives turns through v1 `sdk.session.prompt`.
299
+
300
+ ```ts
301
+ import { OpencodeDriver } from '@/backends/opencode/driver.ts'
302
+
303
+ const driver = new OpencodeDriver({
304
+ agentInfo: { version: '0.0.1' },
305
+ server, // for outbound canonical permission + ask_user_question RPCs
306
+ })
307
+
308
+ const { sessionId } = await driver.newSession({
309
+ cwd: '/workspace',
310
+ mcpServers: [
311
+ { type: 'http', name: 'kodizm', url: 'https://kodizm.com/mcp/internal' },
312
+ ],
313
+ model: 'opencode-go/deepseek-v4-flash', // canonical <providerID>/<modelID>
314
+ toolPolicy: { defaultMode: 'default', ask: ['Bash'] },
315
+ _meta: {
316
+ opencodeAuth: '{"opencode-go":{"type":"api","key":"sk-..."}}',
317
+ },
318
+ })
319
+
320
+ const events: SessionUpdateEvent[] = []
321
+ const result = await driver.prompt(
322
+ sessionId,
323
+ { sessionId, prompt: [{ type: 'text', text: 'Run echo HELLO using bash.' }] },
324
+ { send: (e) => events.push(e) },
325
+ )
326
+ // stopReason: 'end_turn'; events include permission_request, tool_call_begin/end, usage.
327
+ ```
328
+
329
+ The driver:
330
+ - boots one opencode HTTP server per Kodizm session via `createOpencodeServer` (the SDK's official subprocess helper). Per-session lifecycle terminator is `bridge.stop()`.
331
+ - creates the underlying opencode session via `sdk.session.create({permission})` where `permission` comes from `buildOpencodeRuleset(toolPolicy)`. Empty ruleset = opencode's own per-tool ask flow.
332
+ - splits canonical model `<providerID>/<modelID>` into the SDK's `{providerID, modelID}` tuple. No-slash falls back to opencode's default provider.
333
+ - uses v1 `sdk.session.prompt` (NOT v2, which only queues a message). The v1 path drives the LLM loop and returns when the assistant message completes.
334
+ - subscribes to opencode's `/event` SSE stream and dispatches:
335
+ - `message.part.delta` `field=text` on `TextPart` -> `output_chunk`
336
+ - `message.part.delta` `field=text` on `ReasoningPart` -> `thinking_chunk`
337
+ - `message.part.updated` tool/running -> `tool_call_begin` (one-shot per `callID`)
338
+ - `message.part.updated` tool/completed|error -> `tool_call_end` (one-shot per `callID`)
339
+ - `message.part.updated` task/running|completed|error -> `subagent_spawn` / `subagent_complete`
340
+ - `session.updated` `info.time.compacting` newly set -> `compaction_started`
341
+ - `session.compacted` -> `compaction_completed`
342
+ - `message.updated` `role=assistant` `time.completed` set -> `usage` event
343
+ - `permission.asked` -> canonical `permission_request` event + outbound `session/request_permission` RPC, replied via `sdk.permission.reply({requestID, reply})`
344
+ - `question.asked` -> canonical `question_request` event + outbound `session/ask_user_question` RPC, replied via `sdk.question.reply({requestID, answers})`
345
+ - maintains per-session `mcpReverseMap: Map<sanitizedServerName, originalServerName>` so opencode tool keys (`<sanitizedServer>_<tool>`, single underscore) reverse-translate to canonical `mcp__<server>__<tool>` (double underscore) for the orchestrator wire.
346
+ - maps `ProviderAuthError`, `APIError 401/403` to `auth_error`; `APIError 429/503` to `rate_limit`; `APIError 5xx` + `ContextOverflowError` to `transport_error`; `MessageAbortedError` to the cancel sentinel; everything else to `sdk_throw`.
347
+ - writes Pattern B deferred sentinel via `sdk.session.message.append` carrying `__KODIZM_PERMISSION_DEFERRED__ requestId=<id> tool=<name>`.
348
+
349
+ ### `OpencodeDriver.loadSession({ sessionId, _meta.opencodeSessionId, ... })`
350
+
351
+ Cross-process Pattern B entry for opencode. Same role as `CodexDriver.hydrateSession` but for opencode SQLite-persisted sessions:
352
+
353
+ ```ts
354
+ await driverB.loadSession({
355
+ sessionId, // same Kodizm sessionId from Process A
356
+ cwd: process.cwd(),
357
+ mcpServers: [],
358
+ _meta: {
359
+ opencodeSessionId: 'ses_1fd1...', // captured from Process A's session state
360
+ },
361
+ })
362
+ // Boots a fresh listener, validates the opencode session via sdk.session.get,
363
+ // seats driver state. The next prompt resumes the same opencode session.
364
+ ```
365
+
366
+ ### `NewSessionRequest` schema
367
+
368
+ | Field | Type | Phase | Description |
369
+ |-------|------|-------|-------------|
370
+ | `cwd` | absolute path | 1 | Workspace root |
371
+ | `mcpServers` | array | 1 | MCP server inline injection |
372
+ | `additionalDirectories` | array | 1 | Extra read roots |
373
+ | `systemPrompt` | string \| `{append}` | 1 | Replace or append SDK preset |
374
+ | `model` | string | 1 | Canonical `<providerID>/<modelID>` for opencode; raw model id for Claude / codex |
375
+ | `skills` | string[] | 1 | Pre-loaded skill names |
376
+ | `toolPolicy` | object | 1.5 | `<ToolName>:<pattern>` rules + `defaultMode` |
377
+ | `autoCompact` | boolean | 1.5 | `false` injects `DISABLE_AUTO_COMPACT=1` |
378
+ | `permissionTimeoutMs` | int ms | 1.5 | Hard-deny on permission RPC timeout |
379
+ | `permissionDeferTimeoutMs` | int ms | 1.6 | Soft-defer on permission RPC timeout (Pattern B); mutually exclusive with `permissionTimeoutMs` |
380
+ | `debug` | boolean | 1.7 | Per-session debug capture toggle |
381
+ | `debugCaptureRawSdk` | boolean | 1.7 | Skip `sdk.message` + `sdk.error` |
382
+ | `debugCaptureRpc` | boolean | 1.7 | Skip `rpc.in` + `rpc.out` |
383
+ | `heartbeatIntervalMs` | int ms | 1.7 | Liveness ping cadence (default 10_000) |
384
+ | `inactivityThresholdMs` | int ms | 1.7 | SDK message gap threshold (default 60_000) |
385
+ | `_meta.opencodeAuth` | string \| object | 3 | opencode per-provider auth blob; layered onto `OPENCODE_AUTH_CONTENT` for `bridge.start` |
386
+ | `_meta.opencodeSessionId` | string | 3 | opencode session id for cross-process resume via `loadSession` |
387
+
388
+ ### Event union (`@/wire/events`)
389
+
390
+ Discriminated on `type`. Every variant carries `sessionId`.
391
+
392
+ | Event | Phase | Carries |
393
+ |-------|-------|---------|
394
+ | `output_chunk` | 1 | `text` |
395
+ | `thinking_chunk` | 1 | `text` |
396
+ | `tool_call_begin` | 1 | `toolUseId`, `name`, `input` |
397
+ | `tool_call_progress` | 1 | `toolUseId`, `delta` |
398
+ | `tool_call_end` | 1 | `toolUseId`, `result`, `isError` |
399
+ | `usage` | 1 | 4 token counts + `costUsd` |
400
+ | `subagent_spawn` / `subagent_complete` | 1 | child token slice |
401
+ | `skill_activation` | 1 | `skillName`, `source` |
402
+ | `model_advertisement` | 1 | `model` |
403
+ | `process_died` / `cancelled` | 1 | terminal |
404
+ | `permission_request` | 1.5 | `toolUseId`, `name`, `options[]`, `agentId?` |
405
+ | `question_request` | 1.5 | `toolUseId`, `questions[]` |
406
+ | `compaction_started` / `compaction_completed` | 1.5 | trigger + token counts |
407
+ | `permission_deferred` / `permission_resumed` | 1.6 | Pattern B |
408
+ | `debug_log` | 1.7 | `level`, `stage`, `capturedAt`, `payload`, `redacted?` |
409
+ | `heartbeat` | 1.7 | `uptimeMs`, `lastSdkMs` |
410
+ | `session_failed` | 1.7 | `reason`, `detail`, `capturedAt`, `cause?` |
411
+
412
+ ### Permission flow (`@/backends/claude/permission-bridge`)
413
+
414
+ ```ts
415
+ import { buildCanUseTool } from '@/backends/claude/permission-bridge.ts'
416
+
417
+ const canUseTool = buildCanUseTool({
418
+ server,
419
+ sessionId: 's1',
420
+ emit,
421
+ signal: abortController.signal,
422
+ permissionTimeoutMs: 30_000,
423
+ deferTimeoutMs: 1_800_000,
424
+ onDefer: ({ toolName, input, options }) => driverDeferHandler(...),
425
+ })
426
+ ```
427
+
428
+ Outcomes:
429
+ - `selected.allow` → `{ behavior: 'allow', updatedInput }`
430
+ - `selected.allow_always` → `{ behavior: 'allow', ..., updatedPermissions }`
431
+ - `selected.reject` (or other) → `{ behavior: 'deny', message }`
432
+ - `cancelled` → throws `Tool use aborted`
433
+ - `AcpTimeoutError` → `{ behavior: 'deny', message: 'Permission RPC timed out' }`
434
+ - `DEFERRED_SENTINEL` → calls `onDefer` (Pattern B JSONL injection + state persist)
435
+
436
+ The opencode + codex bridges share the same `awaitPermissionResponse` race semantics; only the per-backend reply shape differs.
437
+
438
+ ### Deferred permission, Pattern B (`@/backends/{claude,codex,opencode}/deferred-permission`)
439
+
440
+ Process A defers when `permissionDeferTimeoutMs` elapses without an answer:
441
+
442
+ ```ts
443
+ // 1. writeDeferredSentinel(...) // synthetic transcript row
444
+ // 2. deferredStore.set(sessionId, { toolUseId, ...input }) // state persistence
445
+ // 3. emit { type: 'permission_deferred', sessionId, toolUseId, name }
446
+ // 4. canUseTool returns { behavior: 'deny', interrupt: true } (SDK unwinds)
447
+ ```
448
+
449
+ Process B resumes when the orchestrator caches an answer:
450
+
451
+ ```ts
452
+ // 1. one-shot deferredStore.get(sessionId) lookup at first prompt
453
+ // 2. retry prefix injected into user prompt
454
+ // 3. canUseTool wrap fires cached answer for matching tool name
455
+ // 4. emit { type: 'permission_resumed', sessionId, toolUseId, decision }
456
+ // 5. deferredStore.delete(sessionId) (one-shot consumption)
457
+ ```
458
+
459
+ Marker `__KODIZM_PERMISSION_DEFERRED__` flags rows the orchestrator's audit pipeline filters.
460
+
461
+ ```ts
462
+ import { type DeferredPermissionStore, InMemoryDeferredStore } from '@/session/deferred-store.ts'
463
+
464
+ const driver = new ClaudeDriver({
465
+ credentials, agentInfo, sdk, server,
466
+ deferredStore: new InMemoryDeferredStore(),
467
+ })
468
+ ```
469
+
470
+ Without `deferredStore`, the driver issues `session/permission_deferred_persist` (write) + `session/permission_deferred_state` (read) outbound RPCs.
471
+
472
+ ### Debug capture (`@/util/debug-recorder`)
473
+
474
+ ```ts
475
+ import { DebugRecorder } from '@/util/debug-recorder.ts'
476
+
477
+ const recorder = new DebugRecorder({
478
+ sessionId: 's1',
479
+ emit: { send: (e) => orchestratorWire.notify(e) },
480
+ debug: true,
481
+ debugFilePath: '/tmp/kodizm-debug/s1.jsonl',
482
+ debugCaptureRawSdk: true,
483
+ debugCaptureRpc: true,
484
+ rawSecretsMode: false,
485
+ })
486
+
487
+ recorder.record('sdk.message', sdkMsg)
488
+ recorder.record('rpc.in', frame)
489
+ await recorder.flushPending()
490
+ recorder.close()
491
+ ```
492
+
493
+ Stages: `rpc.in`, `rpc.out`, `sdk.message`, `sdk.error`, `tool.permission_request`, `tool.permission_response`, `session.config`, `driver.state_change`, `transport.spawn`, `transport.exit`.
494
+
495
+ Allow-list redaction masks `sk-ant-(api|oat|ort)*`, `Bearer`, `apiKey=value`, `kdz-*` patterns. Override via `KODIZM_DEBUG_RAW_SECRETS=1`.
496
+
497
+ ### Heartbeat + inactivity (`@/server/heartbeat`)
498
+
499
+ ```ts
500
+ import { HeartbeatTimer } from '@/server/heartbeat.ts'
501
+
502
+ const timer = new HeartbeatTimer({
503
+ sessionId: 's1',
504
+ intervalMs: 10_000,
505
+ emit,
506
+ getLastSdkMs: () => state.lastSdkMessageAt,
507
+ })
508
+ timer.start(Date.now())
509
+ // ... prompt runs ...
510
+ timer.stop()
511
+ ```
512
+
513
+ `ClaudeDriver.prompt()` and `CodexDriver.prompt()` instantiate one timer per turn when `heartbeatIntervalMs` is set. The inactivity probe runs alongside; when the SDK message gap exceeds `inactivityThresholdMs`, the driver emits `session_failed { reason: 'sdk_stall' }` + aborts the per-turn controller.
514
+
515
+ ### Structured failures (`@/backends/{claude,codex,opencode}/error-classifier`)
516
+
517
+ ```ts
518
+ import { classifyClaudeError } from '@/backends/claude/error-classifier.ts'
519
+ import { classifyCodexError } from '@/backends/codex/error-classifier.ts'
520
+ import { classifyOpencodeError } from '@/backends/opencode/error-classifier.ts'
521
+ import { shouldExitOnReason } from '@/util/exit-policy.ts'
522
+
523
+ const classified = classifyOpencodeError(err)
524
+ // { reason: 'auth_error' | 'rate_limit' | 'transport_error' | 'sdk_throw' | ..., detail }
525
+
526
+ if (shouldExitOnReason(classified.reason)) {
527
+ // sdk_stall, transport_error, internal_panic, protocol_violation -> exit
528
+ } else {
529
+ // sdk_throw, auth_error, rate_limit -> stay alive, orchestrator may retry
530
+ }
531
+ ```
532
+
533
+ ### Graceful shutdown (`@/server/shutdown`)
534
+
535
+ ```ts
536
+ import { runShutdown } from '@/server/shutdown.ts'
537
+
538
+ const result = await runShutdown({
539
+ graceMs: 3_000,
540
+ flushRecorders: async () => Promise.all(activeRecorders.map((r) => r.flushPending())),
541
+ flushTransport: () => transport.flush(),
542
+ emitFinal: (e) => server.notify('sessionUpdate', e),
543
+ finalReason: 'transport_error',
544
+ finalDetail: 'SIGTERM received',
545
+ finalSessionIds: [...activeSessionIds],
546
+ })
547
+ // result.timedOut, result.errors
548
+ ```
549
+
550
+ Bin entrypoint installs SIGTERM + SIGINT handlers automatically:
551
+
552
+ ```ts
553
+ import { installShutdownHook, registerActiveRecorder, registerShutdownFlusher } from 'kodizm-acp'
554
+
555
+ installShutdownHook()
556
+ const dispose = registerActiveRecorder(recorder)
557
+ registerShutdownFlusher(() => transport.flush())
558
+ ```
559
+
560
+ ### Tool policy grammar (`@/wire/policy`)
561
+
562
+ | Canonical | Claude SDK | Codex profile | Opencode ruleset |
563
+ |-----------|------------|---------------|------------------|
564
+ | `Read` | `Read` | profile entry | `{permission: 'read', pattern: '*', action: ...}` |
565
+ | `Read:/workspace/**` | `Read(/workspace/**)` | sandbox path | `{permission: 'read', pattern: '/workspace/**', action: ...}` |
566
+ | `Bash:git commit*` | `Bash(git commit:*)` | exec rule | `{permission: 'bash', pattern: 'git commit*', action: ...}` |
567
+ | `mcp:kodizm` | `mcp__kodizm` | mcp gate | `{permission: 'kodizm_*', pattern: '*', action: ...}` |
568
+ | `mcp:kodizm/*` | `mcp__kodizm__*` | wildcard | `{permission: 'kodizm_*', pattern: '*', action: ...}` |
569
+ | `mcp:kodizm/create_task` | `mcp__kodizm__create_task` | exact | `{permission: 'kodizm_create_task', pattern: '*', action: ...}` |
570
+
571
+ ```ts
572
+ import { parseCanonicalPattern } from '@/wire/policy.ts'
573
+
574
+ const parsed = parseCanonicalPattern('Bash:git commit*')
575
+ // { toolName: 'Bash', argPattern: 'git commit*' }
576
+ ```
577
+
578
+ ### Error codes (`@/server/errors`)
579
+
580
+ | Error | Code |
581
+ |-------|------|
582
+ | `MethodNotFoundError` / `MethodNotSupportedError` | -32601 |
583
+ | `InvalidParamsError` / `SessionNotFoundError` | -32602 |
584
+ | `InternalError` | -32603 |
585
+ | `ProcessDiedError` | -32001 |
586
+ | `CancelledError` | -32002 |
587
+ | `BackendDriverError` | -32003 |
588
+ | `AcpTimeoutError` | -32004 |
589
+ | `AcpProtocolError` | -32005 |
590
+ | `BackendStallError` | -32006 |
591
+
592
+ ## Codex CLI specifics
593
+
594
+ Codex's app-server protocol drifts from claude's SDK in subtle ways the driver normalizes:
595
+
596
+ - **Field shape is camelCase v2**: `threadId`, `turnId`, `itemId`, `approvalId`, `cachedInputTokens`, `tokenUsage.total.*`. Pre-v2 snake_case (`thread_id`, `item_id`) and the legacy `conversationId` / `callId` shape from `applyPatchApproval` / `execCommandApproval` are auto-aliased in the approval pipeline.
597
+ - **Item type discriminator is camelCase**: `commandExecution`, `fileChange`, `mcpToolCall`, `contextCompaction`, `collabAgentToolCall`. Driver accepts both `PascalCase` and `camelCase` for forward + back compat.
598
+ - **Reasoning chunks travel on dedicated methods**, NOT via `subtype='reasoning'` on `agentMessage/delta`. The driver routes `item/reasoning/summaryTextDelta` + `item/reasoning/textDelta` to canonical `thinking_chunk`.
599
+ - **`codex app-server` has NO `--config <path>` flag.** To inject `[mcp_servers.*]` etc., set `CODEX_HOME` to a temp dir + write `config.toml` there. Per-key overrides via `-c key=value`.
600
+ - **ChatGPT-mode auth ignores `model` overrides** and silently keeps `gpt-5.5`. API-key auth honors them.
601
+ - **Some features only expose with explicit feature flags**:
602
+ - `features.default_mode_request_user_input=true` for `requestUserInput` tool
603
+ - `features.request_permissions_tool=true` for permission grants
604
+ - `features.multi_agent_v2=true` for `spawn_agent` (still account-tier gated; chatgpt-mode never invokes it organically regardless of Plus / Free)
605
+
606
+ ## Opencode CLI specifics
607
+
608
+ Opencode's HTTP server diverges from the Claude SDK + codex stdio model in several places worth knowing:
609
+
610
+ - **Boot mode is the SDK helper, not the raw runtime.** `createOpencodeServer` from `@opencode-ai/sdk` spawns `opencode serve --port 0 --hostname 127.0.0.1` and returns `{url, close}` once the listening marker hits stdout. The driver wraps that into `OpencodeHttpBridge` so `bridge.start({env})` + `bridge.stop()` mirrors the codex per-session subprocess invariant.
611
+ - **v2 `session.prompt` does NOT drive the LLM loop.** It queues a message but returns immediately. Always use v1 `sdk.session.prompt({sessionID, model: {providerID, modelID}, parts, ...})` for actual turns.
612
+ - **SDK reply shapes are flat.** `sdk.permission.reply({requestID, reply, message?})`, `sdk.question.reply({requestID, answers})`, `sdk.question.reject({requestID})`. NOT `{id, body: {...}}` (that was an older draft shape).
613
+ - **MCP tool naming differs from codex / Claude.** opencode uses `<sanitizedServer>_<tool>` (single underscore); canonical wire uses `mcp__<server>__<tool>` (double underscore). The driver maintains a per-session reverse map populated at `sdk.mcp.add` time and resolves opencode tool keys back to canonical names via longest-prefix-match.
614
+ - **Tool lifecycle fires multiple `running` updates per call.** opencode emits `message.part.updated` with `state.status='running'` repeatedly as the tool's input record fills in. The event-mapper has `toolBegan` + `toolEnded` `Set<callID>` latches so canonical `tool_call_begin` + `tool_call_end` each fire exactly once per call.
615
+ - **Permission ruleset must be passed at session creation.** `sdk.session.create({permission: buildOpencodeRuleset(toolPolicy)})`. opencode has no per-driver default mode; everything is per-session.
616
+ - **Auth via `OPENCODE_AUTH_CONTENT` env, not file mutation.** The driver layers `_meta.opencodeAuth` onto `process.env` for the duration of `bridge.start()` then restores. The opencode subprocess inherits the env and reads it at boot.
617
+ - **Canonical `<providerID>/<modelID>` model wire.** Examples: `opencode-go/deepseek-v4-flash`, `github-copilot/gpt-5-mini`, `anthropic/claude-haiku-4-5`. Driver splits on first `/`. No-slash falls back to opencode's default provider.
618
+ - **`ContextOverflowError` maps to `transport_error`.** The canonical `SessionFailedReason` union has no `compaction_failure`; opencode's overflow signal lands on `transport_error` so the orchestrator's retry path handles it.
619
+ - **No native sandbox primitive.** opencode does not have an `additional_directories` equivalent; the kodizm-ai-docker image's symlink layout fills the gap (Phase 5 hardening).
620
+
621
+ ## Run tests
622
+
623
+ Always run from the package directory (Bun 1.3.10 has a subprocess lifecycle quirk under `bun test` when invoked from a parent dir).
624
+
625
+ ```bash
626
+ cd packages/kodizm-acp
627
+
628
+ # Unit + e2e (mocked SDK + fake codex subprocess + real opencode bridge)
629
+ bun test test/unit test/e2e
630
+
631
+ # Real-CLI smoke (requires CLAUDE_CODE_OAUTH_TOKEN, codex login, OR opencode-go auth)
632
+ bun test test/integration
633
+
634
+ # Specific real-codex suites
635
+ bun test test/integration/codex-features.smoke.test.ts
636
+ bun test test/integration/codex-thinking.smoke.test.ts
637
+ bun test test/integration/codex-mcp-elicit.smoke.test.ts
638
+
639
+ # Real-LLM opencode F1-F6 (uses opencode-go/deepseek-v4-flash, ~$0.05/run)
640
+ bun test test/integration/opencode-features.smoke.test.ts
641
+ ```
642
+
643
+ Coverage at last run (ChatGPT Plus + Claude OAuth + opencode-go on host):
644
+
645
+ | Layer | Tests | Source |
646
+ |-------|------:|--------|
647
+ | Unit + e2e | 600+ | `test/unit/`, `test/e2e/` |
648
+ | Codex baseline real-CLI | 3 | `codex-real.smoke` |
649
+ | Codex features F1-F19 real-CLI | 21 | `codex-features.smoke`, `codex-features-extended.smoke`, `codex-features-complete.smoke` |
650
+ | Codex deep F20-F28 real-CLI | 9 | `codex-features-deep.smoke` |
651
+ | Codex final A1-A4 + B1-B4 + C1-C4 (deterministic fake fixture) | 17 | `codex-features-final.smoke` |
652
+ | Codex dedicated real-CLI (auth_error, cross-process, thinking, auth_refresh, mcp_elicit) | 5 | per-file smokes |
653
+ | Opencode F1-F6 real-LLM strict-asserted | 5 + 1 skip-branch | `opencode-features.smoke` against `opencode-go/deepseek-v4-flash` |
654
+
655
+ Opencode smoke verifies F1 token rollup (non-zero in/out + cost), F2 model_advertisement, F3 multi-turn memory recall, F4 askUserQuestion (`question_request` event + outbound RPC + RED/BLUE option labels), F5 permission allow (one-shot `permission_request` + bash `tool_call_begin` + `tool_call_end` carrying the `echo` stdout), F6 fork (parent + fork get distinct opencode session ids). 27 strict expects; reliability validated 3-of-3 sequential isolated runs on F4 + F5.
656
+
657
+ ## License
658
+
659
+ Apache-2.0.
package/dist/index.js ADDED
@@ -0,0 +1,135 @@
1
+ // @bun
2
+ // src/server/errors.ts
3
+ class BackendNotConfiguredError extends Error {
4
+ name = "BackendNotConfiguredError";
5
+ constructor(detail) {
6
+ super(`KODIZM_BACKEND is not set or empty (${detail})`);
7
+ }
8
+ }
9
+
10
+ class UnknownBackendError extends Error {
11
+ name = "UnknownBackendError";
12
+ constructor(value, knownBackends) {
13
+ super(`unknown backend: ${value} (known: ${knownBackends.join(", ")})`);
14
+ }
15
+ }
16
+
17
+ // src/server/shutdown.ts
18
+ async function runShutdown(options) {
19
+ const errors = [];
20
+ if (options.emitFinal !== undefined && options.finalReason !== undefined && options.finalSessionIds !== undefined) {
21
+ const detail = options.finalDetail ?? "shutdown";
22
+ const capturedAt = Date.now();
23
+ for (const sessionId of options.finalSessionIds) {
24
+ try {
25
+ options.emitFinal({
26
+ sessionId,
27
+ type: "session_failed",
28
+ reason: options.finalReason,
29
+ detail,
30
+ capturedAt
31
+ });
32
+ } catch (err) {
33
+ errors.push(toError(err));
34
+ }
35
+ }
36
+ }
37
+ const flushers = (async () => {
38
+ try {
39
+ await options.flushRecorders();
40
+ } catch (err) {
41
+ errors.push(toError(err));
42
+ }
43
+ try {
44
+ await options.flushTransport();
45
+ } catch (err) {
46
+ errors.push(toError(err));
47
+ }
48
+ })();
49
+ let timedOut = false;
50
+ await Promise.race([
51
+ flushers,
52
+ new Promise((resolve) => {
53
+ setTimeout(() => {
54
+ timedOut = true;
55
+ resolve();
56
+ }, options.graceMs);
57
+ })
58
+ ]);
59
+ return { timedOut, errors };
60
+ }
61
+ function toError(err) {
62
+ return err instanceof Error ? err : new Error(String(err));
63
+ }
64
+
65
+ // src/index.ts
66
+ var KNOWN_BACKENDS = ["claude", "codex", "opencode"];
67
+ var SHUTDOWN_GRACE_MS = 3000;
68
+ var activeRecorders = new Set;
69
+ var transportFlusher;
70
+ function registerActiveRecorder(recorder) {
71
+ activeRecorders.add(recorder);
72
+ return () => activeRecorders.delete(recorder);
73
+ }
74
+ function registerShutdownFlusher(flusher) {
75
+ transportFlusher = flusher;
76
+ }
77
+ async function performShutdown(graceMs = SHUTDOWN_GRACE_MS) {
78
+ await runShutdown({
79
+ graceMs,
80
+ flushRecorders: async () => {
81
+ const recorders = [...activeRecorders];
82
+ await Promise.all(recorders.map((r) => r.flushPending()));
83
+ for (const recorder of recorders) {
84
+ recorder.close();
85
+ }
86
+ },
87
+ flushTransport: async () => {
88
+ if (transportFlusher !== undefined) {
89
+ await transportFlusher();
90
+ }
91
+ }
92
+ });
93
+ }
94
+ function installShutdownHook() {
95
+ const handler = async (signal) => {
96
+ process.stderr.write(`${JSON.stringify({ level: "info", message: "kodizm-acp shutdown", signal })}
97
+ `);
98
+ await performShutdown();
99
+ process.exit(0);
100
+ };
101
+ process.removeAllListeners("SIGTERM");
102
+ process.removeAllListeners("SIGINT");
103
+ process.on("SIGTERM", () => void handler("SIGTERM"));
104
+ process.on("SIGINT", () => void handler("SIGINT"));
105
+ }
106
+ function resolveBackendFromEnv(env) {
107
+ const raw = env.KODIZM_BACKEND;
108
+ if (raw === undefined || raw === "") {
109
+ throw new BackendNotConfiguredError(`expected one of: ${KNOWN_BACKENDS.join(", ")}`);
110
+ }
111
+ if (!KNOWN_BACKENDS.includes(raw)) {
112
+ throw new UnknownBackendError(raw, KNOWN_BACKENDS);
113
+ }
114
+ return raw;
115
+ }
116
+ async function main() {
117
+ installShutdownHook();
118
+ const backend = resolveBackendFromEnv(process.env);
119
+ process.stderr.write(`${JSON.stringify({ level: "info", message: "kodizm-acp resolved backend", backend })}
120
+ `);
121
+ }
122
+ if (import.meta.main) {
123
+ await main();
124
+ }
125
+ export {
126
+ resolveBackendFromEnv,
127
+ registerShutdownFlusher,
128
+ registerActiveRecorder,
129
+ performShutdown,
130
+ main,
131
+ installShutdownHook,
132
+ UnknownBackendError,
133
+ SHUTDOWN_GRACE_MS,
134
+ BackendNotConfiguredError
135
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@kodizm/acp",
3
+ "version": "0.4.0",
4
+ "description": "Custom ACP server bridging Claude Code, codex, and opencode CLIs through a single Kodizm-flavored protocol surface.",
5
+ "type": "module",
6
+ "bin": {
7
+ "kodizm-acp": "./dist/index.js"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "files": ["dist/", "README.md", "LICENSE"],
11
+ "scripts": {
12
+ "dev": "bun run src/index.ts",
13
+ "build": "bun build src/index.ts --target=bun --outdir=dist",
14
+ "test": "bun test test/unit test/e2e",
15
+ "test:unit": "bun test test/unit",
16
+ "test:e2e": "bun test test/e2e",
17
+ "test:integration": "bun test test/integration",
18
+ "test:watch": "bun test --watch",
19
+ "lint": "biome check src test",
20
+ "lint:fix": "biome check --write src test",
21
+ "format": "biome format --write src test",
22
+ "typecheck": "tsc --noEmit",
23
+ "typecheck:src": "tsc --noEmit -p tsconfig.publish.json",
24
+ "prepublishOnly": "bun run build && bun run typecheck:src"
25
+ },
26
+ "engines": {
27
+ "bun": ">=1.1.0"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@agentclientprotocol/sdk": "^0.21.0",
34
+ "@anthropic-ai/claude-agent-sdk": "^0.2.0",
35
+ "@opencode-ai/sdk": "^1.14.40",
36
+ "zod": "^3.25.0"
37
+ },
38
+ "devDependencies": {
39
+ "@biomejs/biome": "^1.9.0",
40
+ "@types/bun": "latest",
41
+ "typescript": "^5.6.0"
42
+ },
43
+ "license": "Apache-2.0",
44
+ "homepage": "https://github.com/kodizm/acp",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/kodizm/acp.git"
48
+ },
49
+ "keywords": ["acp", "agent-client-protocol", "claude", "codex", "opencode", "ai", "bridge", "jsonrpc"]
50
+ }