This repository was archived by the owner on Apr 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path10097.patch
More file actions
2398 lines (2386 loc) · 89.5 KB
/
10097.patch
File metadata and controls
2398 lines (2386 loc) · 89.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 7b33f4a5344a0fa09ac5f104513b8a91c5dadb19 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dennis=20Kr=C3=A4mer?= <dkraemerwork@gmail.com>
Date: Tue, 20 Jan 2026 01:37:13 +0100
Subject: [PATCH] Add local claude cli provider
---
bun.lock | 1 -
package.json | 2 +-
packages/console/app/vite.config.ts | 6 +-
packages/enterprise/vite.config.ts | 6 +-
packages/opencode/src/provider/provider.ts | 184 +-
.../sdk/claude-code/src/claude-code-config.ts | 71 +
.../src/claude-code-language-model.ts | 1834 +++++++++++++++++
.../src/provider/sdk/claude-code/src/index.ts | 68 +
packages/opencode/src/session/llm.ts | 9 +-
packages/opencode/src/session/processor.ts | 33 +-
10 files changed, 2191 insertions(+), 23 deletions(-)
create mode 100644 packages/opencode/src/provider/sdk/claude-code/src/claude-code-config.ts
create mode 100644 packages/opencode/src/provider/sdk/claude-code/src/claude-code-language-model.ts
create mode 100644 packages/opencode/src/provider/sdk/claude-code/src/index.ts
diff --git a/bun.lock b/bun.lock
index e7b9dc09cea..b84a932abb7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1,6 +1,5 @@
{
"lockfileVersion": 1,
- "configVersion": 1,
"workspaces": {
"": {
"name": "opencode",
diff --git a/package.json b/package.json
index 4267ef64566..9edda9e6d9f 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"description": "AI-powered development tool",
"private": true,
"type": "module",
- "packageManager": "bun@1.3.5",
+ "packageManager": "bun@1.3.6",
"scripts": {
"dev": "bun run --cwd packages/opencode --conditions=browser src/index.ts",
"typecheck": "bun turbo typecheck",
diff --git a/packages/console/app/vite.config.ts b/packages/console/app/vite.config.ts
index 3b013e99011..b1ae3b73e23 100644
--- a/packages/console/app/vite.config.ts
+++ b/packages/console/app/vite.config.ts
@@ -1,10 +1,10 @@
-import { defineConfig, PluginOption } from "vite"
+import { defineConfig } from "vite"
import { solidStart } from "@solidjs/start/config"
import { nitro } from "nitro/vite"
export default defineConfig({
plugins: [
- solidStart() as PluginOption,
+ solidStart(),
nitro({
compatibilityDate: "2024-09-19",
preset: "cloudflare_module",
@@ -12,7 +12,7 @@ export default defineConfig({
nodeCompat: true,
},
}),
- ],
+ ] as any,
server: {
allowedHosts: true,
},
diff --git a/packages/enterprise/vite.config.ts b/packages/enterprise/vite.config.ts
index 11ca1729dfe..73350970171 100644
--- a/packages/enterprise/vite.config.ts
+++ b/packages/enterprise/vite.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig, PluginOption } from "vite"
+import { defineConfig } from "vite"
import { solidStart } from "@solidjs/start/config"
import { nitro } from "nitro/vite"
import tailwindcss from "@tailwindcss/vite"
@@ -20,12 +20,12 @@ const nitroConfig: any = (() => {
export default defineConfig({
plugins: [
tailwindcss(),
- solidStart() as PluginOption,
+ solidStart(),
nitro({
...nitroConfig,
baseURL: process.env.OPENCODE_BASE_URL,
}),
- ],
+ ] as any,
server: {
host: "0.0.0.0",
allowedHosts: true,
diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts
index fdd4ccdfb61..83c40b32eaf 100644
--- a/packages/opencode/src/provider/provider.ts
+++ b/packages/opencode/src/provider/provider.ts
@@ -13,6 +13,9 @@ import { Env } from "../env"
import { Instance } from "../project/instance"
import { Flag } from "../flag/flag"
import { iife } from "@/util/iife"
+import { PermissionNext } from "@/permission/next"
+import { Question } from "@/question/index"
+import { Identifier } from "@/id/id"
// Direct imports for bundled providers
import { createAmazonBedrock, type AmazonBedrockProviderSettings } from "@ai-sdk/amazon-bedrock"
@@ -25,6 +28,7 @@ import { createOpenAI } from "@ai-sdk/openai"
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
import { createOpenRouter, type LanguageModelV2 } from "@openrouter/ai-sdk-provider"
import { createOpenaiCompatible as createGitHubCopilotOpenAICompatible } from "./sdk/openai-compatible/src"
+import { createClaudeCode } from "./sdk/claude-code/src"
import { createXai } from "@ai-sdk/xai"
import { createMistral } from "@ai-sdk/mistral"
import { createGroq } from "@ai-sdk/groq"
@@ -76,6 +80,7 @@ export namespace Provider {
"@gitlab/gitlab-ai-provider": createGitLab,
// @ts-ignore (TODO: kill this code so we dont have to maintain it)
"@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
+ "@opencode/claude-code": createClaudeCode,
}
type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
@@ -504,6 +509,136 @@ export namespace Provider {
},
}
},
+ "claude-code": async () => {
+ let cliPath = Env.get("CLAUDE_CLI_PATH")
+ let cliAvailable = false
+
+ if (!cliPath) {
+ try {
+ const whichResult = Bun.spawnSync(["which", "claude"], { timeout: 5000 })
+ if (whichResult.exitCode === 0) {
+ cliPath = whichResult.stdout.toString().trim()
+ }
+ } catch {}
+ }
+
+ if (!cliPath) {
+ cliPath = "claude"
+ }
+
+ try {
+ const result = Bun.spawnSync([cliPath, "--version"], { timeout: 5000 })
+ cliAvailable = result.exitCode === 0
+ } catch {
+ cliAvailable = false
+ }
+
+ return {
+ autoload: cliAvailable,
+ async getModel(sdk: any, modelID: string) {
+ return sdk.languageModel(modelID)
+ },
+ options: {
+ cliPath,
+ skipPermissions: false,
+ // Enable OpenCode's permission handling for permission-requiring tools
+ handleToolsInOpenCode: true,
+ permissionHandler: async (
+ request: { id: string; type: string; tool?: string; path?: string; command?: string; description?: string },
+ sessionID?: string,
+ ) => {
+ if (!sessionID) {
+ log.warn("claude-code permission request without sessionID, auto-approving", { requestId: request.id })
+ return true
+ }
+
+ const permission = mapClaudePermissionType(request.type, request.tool)
+ const patterns = getPermissionPatterns(request)
+
+ try {
+ await PermissionNext.ask({
+ id: Identifier.ascending("permission"),
+ sessionID: sessionID as `session_${string}`,
+ permission,
+ patterns,
+ metadata: {
+ tool: request.tool ?? "claude-code",
+ command: request.command,
+ path: request.path,
+ description: request.description,
+ },
+ always: patterns,
+ ruleset: [],
+ })
+ return true
+ } catch (e) {
+ if (e instanceof PermissionNext.RejectedError || e instanceof PermissionNext.DeniedError) {
+ return false
+ }
+ if (e instanceof PermissionNext.CorrectedError) {
+ return false
+ }
+ throw e
+ }
+ },
+ questionHandler: async (
+ input: { question: string; options?: any[]; custom?: boolean; multiple?: boolean },
+ sessionID?: string,
+ ) => {
+ if (!sessionID) return ""
+ try {
+ const answers = await Question.ask({
+ sessionID: sessionID as any,
+ questions: [
+ {
+ question: input.question,
+ header: "Question",
+ options: input.options ?? [],
+ custom: input.custom ?? true,
+ multiple: input.multiple,
+ },
+ ],
+ })
+ const ans = answers[0]
+ if (!ans) return ""
+ if (Array.isArray(ans)) return ans.join(",")
+ return ans
+ } catch {
+ return ""
+ }
+ },
+ },
+ }
+ },
+ }
+
+ function mapClaudePermissionType(type: string, tool?: string): string {
+ if (tool) {
+ const toolLower = tool.toLowerCase()
+ if (toolLower.includes("read") || toolLower.includes("view")) return "read"
+ if (toolLower.includes("write") || toolLower.includes("edit") || toolLower.includes("patch")) return "edit"
+ if (toolLower.includes("bash") || toolLower.includes("command") || toolLower.includes("exec")) return "bash"
+ }
+
+ switch (type) {
+ case "file_read":
+ return "read"
+ case "file_write":
+ case "file_edit":
+ return "edit"
+ case "bash":
+ case "command":
+ case "execute":
+ return "bash"
+ default:
+ return "bash"
+ }
+ }
+
+ function getPermissionPatterns(request: { path?: string; command?: string }): string[] {
+ if (request.path) return [request.path]
+ if (request.command) return [request.command]
+ return ["*"]
}
export const Model = z
@@ -713,6 +848,16 @@ export namespace Provider {
}
}
+ // Add Claude Code provider for local CLI usage
+ database["claude-code"] = {
+ id: "claude-code",
+ name: "Claude Code CLI",
+ source: "custom",
+ env: [],
+ options: {},
+ models: {},
+ }
+
function mergeProvider(providerID: string, provider: Partial<Info>) {
const existing = providers[providerID]
if (existing) {
@@ -963,6 +1108,13 @@ export namespace Provider {
})
const s = await state()
const provider = s.providers[model.providerID]
+ if (!provider) {
+ log.error("Provider not found in providers map", {
+ providerID: model.providerID,
+ availableProviders: Object.keys(s.providers),
+ })
+ throw new Error(`Provider not found: ${model.providerID}`)
+ }
const options = { ...provider.options }
if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
@@ -1027,14 +1179,34 @@ export namespace Provider {
const bundledKey =
model.providerID === "google-vertex-anthropic" ? "@ai-sdk/google-vertex/anthropic" : model.api.npm
const bundledFn = BUNDLED_PROVIDERS[bundledKey]
+ log.info("getSDK bundled lookup", {
+ providerID: model.providerID,
+ bundledKey,
+ hasBundledFn: !!bundledFn,
+ availableBundled: Object.keys(BUNDLED_PROVIDERS),
+ })
if (bundledFn) {
- log.info("using bundled provider", { providerID: model.providerID, pkg: bundledKey })
- const loaded = bundledFn({
- name: model.providerID,
- ...options,
+ log.info("using bundled provider", {
+ providerID: model.providerID,
+ pkg: bundledKey,
+ options: JSON.stringify(options),
})
- s.sdk.set(key, loaded)
- return loaded as SDK
+ try {
+ const loaded = bundledFn({
+ name: model.providerID,
+ ...options,
+ })
+ log.info("bundled provider loaded successfully", { providerID: model.providerID })
+ s.sdk.set(key, loaded)
+ return loaded as SDK
+ } catch (bundledError) {
+ log.error("bundled provider failed to load", {
+ providerID: model.providerID,
+ error: bundledError instanceof Error ? bundledError.message : String(bundledError),
+ stack: bundledError instanceof Error ? bundledError.stack : undefined,
+ })
+ throw bundledError
+ }
}
let installedPath: string
diff --git a/packages/opencode/src/provider/sdk/claude-code/src/claude-code-config.ts b/packages/opencode/src/provider/sdk/claude-code/src/claude-code-config.ts
new file mode 100644
index 00000000000..baf7165ce77
--- /dev/null
+++ b/packages/opencode/src/provider/sdk/claude-code/src/claude-code-config.ts
@@ -0,0 +1,71 @@
+export interface ClaudeCodeConfig {
+ provider: string
+ cliPath: string
+ cwd?: string
+ sessionId?: string
+ skipPermissions?: boolean
+
+ /**
+ * When true, permission-requiring tools (Edit, Write, Bash, etc.) will be handled
+ * by OpenCode instead of Claude CLI. This enables OpenCode's permission UI to be
+ * used for these tools. Claude CLI will still handle read-only tools.
+ * When enabled, --dangerously-skip-permissions is automatically used to prevent
+ * Claude CLI from blocking on its own permission prompts.
+ */
+ handleToolsInOpenCode?: boolean
+
+ /**
+ * Permission mode to use with Claude CLI.
+ * - "default": Standard permission behavior, triggers permissionHandler
+ * - "acceptEdits": Auto-accept file edits and filesystem operations
+ * - "bypassPermissions": Skip all permission checks (same as skipPermissions: true)
+ * - "plan": Planning mode, no tool execution
+ */
+ permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan"
+
+ /**
+ * Called when Claude CLI requests permission.
+ * @param request - The permission request details
+ * @param sessionID - The OpenCode session ID (from providerOptions)
+ * @returns true to approve, false to deny
+ */
+ permissionHandler?: (request: ClaudePermissionRequest, sessionID?: string) => Promise<boolean>
+
+ /**
+ * Called when Claude CLI asks a question (AskUserQuestion tool).
+ * @param input - The question input (question, options, etc.)
+ * @param sessionID - The OpenCode session ID
+ * @returns The user's answer
+ */
+ questionHandler?: (
+ input: { question: string; options?: any[]; custom?: boolean; multiple?: boolean },
+ sessionID?: string,
+ ) => Promise<string>
+}
+
+/**
+ * Future: MCP Permission Server approach
+ *
+ * Claude CLI supports delegating permission decisions to an MCP server via the
+ * `--permission-prompt-tool` flag. This is the cleanest way to integrate with
+ * OpenCode's permission UI:
+ *
+ * 1. Spawn an MCP server that exposes a `permission_prompt` tool
+ * 2. Pass `--permission-prompt-tool mcp__server__permission_prompt` to Claude CLI
+ * 3. When Claude needs permission, it calls the MCP tool with:
+ * { tool_use_id, tool_name, input }
+ * 4. MCP server calls OpenCode's permissionHandler
+ * 5. Returns { behavior: "allow" } or { behavior: "deny", message: "..." }
+ *
+ * This approach allows Claude CLI to properly wait for permission approval
+ * before executing tools.
+ */
+
+export interface ClaudePermissionRequest {
+ id: string
+ type: string
+ tool?: string
+ path?: string
+ command?: string
+ description?: string
+}
diff --git a/packages/opencode/src/provider/sdk/claude-code/src/claude-code-language-model.ts b/packages/opencode/src/provider/sdk/claude-code/src/claude-code-language-model.ts
new file mode 100644
index 00000000000..4d890531b59
--- /dev/null
+++ b/packages/opencode/src/provider/sdk/claude-code/src/claude-code-language-model.ts
@@ -0,0 +1,1834 @@
+import { spawn } from "node:child_process"
+import { createInterface } from "node:readline"
+import { EventEmitter } from "node:events"
+import type {
+ LanguageModelV2,
+ LanguageModelV2CallWarning,
+ LanguageModelV2Content,
+ LanguageModelV2FinishReason,
+ LanguageModelV2StreamPart,
+ LanguageModelV2Usage,
+} from "@ai-sdk/provider"
+import { generateId } from "@ai-sdk/provider-utils"
+import type { ClaudeCodeConfig, ClaudePermissionRequest } from "./claude-code-config"
+import { Log } from "@/util/log"
+import { Storage } from "@/storage/storage"
+
+const log = Log.create({ service: "claude-code" })
+
+/**
+ * Persist Claude CLI session ID for an OpenCode session
+ */
+async function saveClaudeSessionId(openCodeSessionID: string, claudeSessionId: string) {
+ log.info("attempting to persist claude session mapping", { openCodeSessionID, claudeSessionId })
+ try {
+ await Storage.write(["claude-code-session", openCodeSessionID], { claudeSessionId, timestamp: Date.now() })
+ log.info("successfully persisted claude session mapping", { openCodeSessionID, claudeSessionId })
+ } catch (e) {
+ log.error("failed to persist claude session mapping", {
+ openCodeSessionID,
+ claudeSessionId,
+ error: e instanceof Error ? e.message : String(e),
+ stack: e instanceof Error ? e.stack : undefined,
+ })
+ }
+}
+
+/**
+ * Load persisted Claude CLI session ID for an OpenCode session
+ */
+async function loadClaudeSessionId(openCodeSessionID: string): Promise<string | undefined> {
+ log.info("attempting to load persisted claude session mapping", { openCodeSessionID })
+ try {
+ const data = await Storage.read<{ claudeSessionId: string; timestamp?: number }>(["claude-code-session", openCodeSessionID])
+ if (data?.claudeSessionId) {
+ log.info("successfully loaded persisted claude session mapping", {
+ openCodeSessionID,
+ claudeSessionId: data.claudeSessionId,
+ savedAt: data.timestamp ? new Date(data.timestamp).toISOString() : "unknown",
+ })
+ return data.claudeSessionId
+ }
+ log.warn("persisted mapping found but claudeSessionId is missing", { openCodeSessionID, data })
+ } catch (e) {
+ // Check if it's a NotFoundError (expected for new sessions)
+ if (e && typeof e === "object" && "name" in e && e.name === "NotFoundError") {
+ log.info("no persisted session mapping found (new session)", { openCodeSessionID })
+ } else {
+ log.warn("unexpected error loading persisted session mapping", {
+ openCodeSessionID,
+ error: e instanceof Error ? e.message : String(e),
+ })
+ }
+ }
+ return undefined
+}
+
+/**
+ * Claude CLI stream-json message types.
+ * The CLI outputs various message types during a conversation.
+ */
+interface ClaudeStreamMessage {
+ type: string
+ subtype?: string
+
+ // For assistant messages
+ message?: {
+ role?: string
+ model?: string
+ content?: Array<{
+ type: string
+ text?: string
+ name?: string
+ input?: unknown
+ id?: string
+ tool_use_id?: string
+ content?: string | Array<{ type: string; text?: string }>
+ thinking?: string
+ }>
+ }
+
+ // For tool_use events
+ tool?: {
+ name?: string
+ id?: string
+ input?: unknown
+ }
+
+ // For tool_result events
+ tool_result?: {
+ tool_use_id?: string
+ content?: string | Array<{ type: string; text?: string }>
+ is_error?: boolean
+ }
+
+ // Session and metadata
+ session_id?: string
+ total_cost_usd?: number
+ duration_ms?: number
+ duration_api_ms?: number
+ request_id?: string
+ id?: string
+ result?: string
+ is_error?: boolean
+ num_turns?: number
+
+ // Permission denials (in result message)
+ permission_denials?: Array<{
+ tool_name: string
+ tool_use_id: string
+ tool_input: unknown
+ }>
+
+ // Permission requests
+ permission?: {
+ id?: string
+ type?: string
+ tool?: string
+ path?: string
+ command?: string
+ }
+
+ // Usage stats
+ usage?: {
+ input_tokens?: number
+ output_tokens?: number
+ cache_read_input_tokens?: number
+ cache_creation_input_tokens?: number
+ }
+
+ // For content streaming
+ content_block?: {
+ type: string
+ text?: string
+ id?: string
+ name?: string
+ input?: string
+ thinking?: string
+ }
+ delta?: {
+ type: string
+ text?: string
+ partial_json?: string
+ thinking?: string
+ }
+ index?: number
+}
+
+// Tools that should be handled by OpenCode, not Claude CLI
+// This ensures proper permission handling and state tracking (e.g., read-before-write checks)
+const OPENCODE_HANDLED_TOOLS = new Set([
+ "Edit",
+ "Write",
+ "Bash",
+ "NotebookEdit",
+ "TodoWrite", // Route to OpenCode so todos appear in the UI
+ "Read", // Route to OpenCode so read-before-write checks work
+ "Glob",
+ "Grep",
+])
+
+/**
+ * Convert Claude CLI tool input (snake_case) to OpenCode tool input (camelCase)
+ */
+function mapToolInput(name: string, input: any): any {
+ if (!input) return input
+
+ switch (name) {
+ case "Write":
+ return {
+ filePath: input.file_path ?? input.filePath,
+ content: input.content,
+ }
+ case "Edit":
+ return {
+ filePath: input.file_path ?? input.filePath,
+ oldString: input.old_string ?? input.oldString,
+ newString: input.new_string ?? input.newString,
+ replaceAll: input.replace_all ?? input.replaceAll,
+ }
+ case "Read":
+ return {
+ filePath: input.file_path ?? input.filePath,
+ offset: input.offset,
+ limit: input.limit,
+ }
+ case "Bash":
+ return {
+ command: input.command,
+ // Provide a default description if not given (OpenCode requires this field)
+ description: input.description || `Execute: ${String(input.command || "").slice(0, 50)}${String(input.command || "").length > 50 ? "..." : ""}`,
+ timeout: input.timeout,
+ }
+ case "NotebookEdit":
+ return {
+ notebookPath: input.notebook_path ?? input.notebookPath,
+ cellNumber: input.cell_number ?? input.cellNumber,
+ newSource: input.new_source ?? input.newSource,
+ cellType: input.cell_type ?? input.cellType,
+ editMode: input.edit_mode ?? input.editMode,
+ }
+ case "Glob":
+ return {
+ pattern: input.pattern,
+ path: input.path,
+ }
+ case "Grep":
+ return {
+ pattern: input.pattern,
+ path: input.path,
+ include: input.include,
+ }
+ case "TodoWrite":
+ // Claude CLI sends todos with: content, status, activeForm
+ // OpenCode expects: content, status, priority, id
+ if (Array.isArray(input.todos)) {
+ const mappedTodos = input.todos.map((todo: any, index: number) => ({
+ content: todo.content,
+ status: todo.status || "pending",
+ priority: todo.priority || "medium",
+ // Generate an id if not provided
+ id: todo.id || `todo_${Date.now()}_${index}`,
+ }))
+
+ // Log the full todo list for visibility
+ log.info("TodoWrite - Full todo list from Claude CLI:", {
+ count: mappedTodos.length,
+ todos: mappedTodos.map((t: any) => `[${t.status}] ${t.content}`),
+ })
+
+ // Also log each todo with its status for better visibility
+ const pending = mappedTodos.filter((t: any) => t.status === "pending").length
+ const inProgress = mappedTodos.filter((t: any) => t.status === "in_progress").length
+ const completed = mappedTodos.filter((t: any) => t.status === "completed").length
+ log.info(`TodoWrite summary: ${pending} pending, ${inProgress} in progress, ${completed} completed`)
+
+ return { todos: mappedTodos }
+ }
+ return input
+ default:
+ return input
+ }
+}
+
+// Map Claude CLI tool names to OpenCode equivalents
+const TOOL_NAME_MAPPING: Record<string, string> = {
+ // Claude CLI uses WebSearch, OpenCode might have websearch_web_search_exa or webfetch
+ WebSearch: "websearch_web_search_exa",
+ web_search: "websearch_web_search_exa",
+ // Plan mode
+ EnterPlanMode: "plan_enter",
+ ExitPlanMode: "plan_exit",
+ // Other potential mappings
+ AskUserQuestion: "question",
+ ask_user_question: "question",
+}
+
+function mapTool(
+ name: string,
+ input?: any,
+ forceOpenCodeExecution?: boolean,
+): { name: string; input?: any; executed: boolean } {
+ // Check for direct tool name mappings first
+ if (name === "EnterPlanMode") return { name: "plan_enter", input: {}, executed: false }
+ if (name === "ExitPlanMode") return { name: "plan_exit", input: {}, executed: false }
+
+ // Map WebSearch to the available web search tool
+ if (name === "WebSearch" || name === "web_search") {
+ const mappedInput = input?.query ? { query: input.query } : input
+ log.info("mapping WebSearch to websearch_web_search_exa", { originalInput: input, mappedInput })
+ return { name: "websearch_web_search_exa", input: mappedInput, executed: false }
+ }
+
+ if (name === "TaskOutput") {
+ if (!input) return { name: "bash", executed: false }
+
+ // TaskOutput might have 'content' or 'output' or be the object itself
+ const output = input?.content || input?.output || JSON.stringify(input)
+ return {
+ name: "bash",
+ input: {
+ command: `echo "TASK OUTPUT: ${String(output).replace(/"/g, '\\"')}"`,
+ description: "Displaying task output",
+ },
+ executed: false,
+ }
+ }
+
+ // Map MCP tools from Claude CLI format to OpenCode format
+ // Claude CLI: mcp__<server-name>__<tool-name>
+ // OpenCode: <server-name>_<tool-name>
+ if (name.startsWith("mcp__")) {
+ const parts = name.slice(5).split("__") // Remove "mcp__" prefix and split by "__"
+ if (parts.length >= 2) {
+ const serverName = parts[0]
+ const toolName = parts.slice(1).join("_") // Join remaining parts with "_"
+ const openCodeName = `${serverName}_${toolName}`
+ log.info("mapping MCP tool", { original: name, mapped: openCodeName })
+ return { name: openCodeName, input, executed: false }
+ }
+ }
+
+ // If forceOpenCodeExecution is true, have OpenCode handle permission-requiring tools
+ if (forceOpenCodeExecution && OPENCODE_HANDLED_TOOLS.has(name)) {
+ const mappedInput = mapToolInput(name, input)
+ // Map tool names to OpenCode's expected names (lowercase)
+ // Claude CLI uses PascalCase (Edit, Write, Bash), OpenCode uses lowercase (edit, write, bash)
+ const openCodeName = name.toLowerCase()
+ log.info("routing tool to OpenCode for permission handling", { name, openCodeName, hasInput: !!input, hasMappedInput: !!mappedInput })
+ return { name: openCodeName, input: mappedInput, executed: false }
+ }
+
+ // Check if there's a mapping for this tool name
+ const mappedName = TOOL_NAME_MAPPING[name]
+ if (mappedName) {
+ log.info("mapped tool name", { original: name, mapped: mappedName })
+ return { name: mappedName, input, executed: false }
+ }
+
+ return { name, input, executed: true }
+}
+
+const handledToolCalls = new Set<string>()
+
+// Permission denial patterns to detect in Claude CLI output
+const PERMISSION_DENIAL_PATTERNS = [
+ /Claude requested permissions? to (?:write|edit|modify|create|delete) (?:to )?(?:the file )?[`"']?([^`"'\n]+)[`"']?/i,
+ /but you haven'?t granted (?:it|permission) yet/i,
+ /Could you grant me permission to (?:edit|write|modify|create|delete)/i,
+ /I (?:don'?t|do not) have permission to/i,
+ /Permission denied/i,
+ /I need permission to (?:edit|write|modify|create|delete)/i,
+ /I'?ll need (?:your )?permission to/i,
+ /waiting for (?:your )?permission/i,
+]
+
+interface DetectedPermissionRequest {
+ type: "write" | "read" | "execute" | "unknown"
+ path?: string
+ description: string
+}
+
+function detectPermissionDenial(text: string): DetectedPermissionRequest | null {
+ if (!text) return null
+
+ // Check if any denial pattern matches
+ let hasPermissionIssue = false
+ for (const pattern of PERMISSION_DENIAL_PATTERNS) {
+ if (pattern.test(text)) {
+ hasPermissionIssue = true
+ break
+ }
+ }
+
+ if (!hasPermissionIssue) return null
+
+ // Try to extract the file path
+ const filePatterns = [
+ /(?:write|edit|modify|create|delete) (?:to )?(?:the file )?[`"']?([^\s`"']+\.[a-z]+)[`"']?/i,
+ /file [`"']?([^\s`"']+\.[a-z]+)[`"']?/i,
+ /path [`"']?([^\s`"']+)[`"']?/i,
+ ]
+
+ let path: string | undefined
+ for (const pattern of filePatterns) {
+ const match = text.match(pattern)
+ if (match && match[1]) {
+ path = match[1]
+ break
+ }
+ }
+
+ // Determine type from text
+ let type: "write" | "read" | "execute" | "unknown" = "unknown"
+ if (/write|edit|modify|create|delete/i.test(text)) {
+ type = "write"
+ } else if (/read|view|access/i.test(text)) {
+ type = "read"
+ } else if (/execute|run|command/i.test(text)) {
+ type = "execute"
+ }
+
+ log.info("detected permission denial in text", { type, path, textSnippet: text.slice(0, 200) })
+
+ return {
+ type,
+ path,
+ description: text.slice(0, 500),
+ }
+}
+
+async function handleDetectedPermissionDenial(
+ detected: DetectedPermissionRequest,
+ stdin: NodeJS.WritableStream | null,
+ config: ClaudeCodeConfig,
+ sessionID?: string,
+): Promise<boolean> {
+ log.info("handling detected permission denial", {
+ type: detected.type,
+ path: detected.path,
+ hasHandler: !!config.permissionHandler,
+ sessionID,
+ })
+
+ let approved = true
+
+ if (config.permissionHandler) {
+ try {
+ // Create a permission request from the detected info
+ const permissionRequest: ClaudePermissionRequest = {
+ id: `detected-${Date.now()}`,
+ type: detected.type,
+ tool: detected.type === "write" ? "Edit" : detected.type === "execute" ? "Bash" : "Read",
+ path: detected.path,
+ description: detected.description,
+ }
+
+ approved = await config.permissionHandler(permissionRequest, sessionID)
+ log.info("permission decision for detected denial", {
+ type: detected.type,
+ path: detected.path,
+ approved,
+ sessionID,
+ })
+ } catch (e) {
+ log.error("permission handler error for detected denial", { error: e })
+ approved = false
+ }
+ }
+
+ if (approved && stdin) {
+ // Send approval message to Claude CLI
+ const approvalMessage = JSON.stringify({
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "text", text: "Yes, I grant permission. Please proceed." }],
+ },
+ })
+ stdin.write(approvalMessage + "\n")
+ log.info("sent permission approval to Claude CLI", { sessionID })
+ }
+
+ return approved
+}
+
+async function handleQuestion(
+ rawInput: any,
+ config: ClaudeCodeConfig,
+ sessionID: string | undefined,
+ proc: import("child_process").ChildProcess,
+ toolCallId: string,
+) {
+ handledToolCalls.add(toolCallId)
+
+ // Log the raw input to see exactly what Claude CLI sends
+ log.info("handleQuestion: raw input received", {
+ toolCallId,
+ rawInputType: typeof rawInput,
+ rawInputKeys: rawInput ? Object.keys(rawInput) : [],
+ rawInputStringified: JSON.stringify(rawInput)?.slice(0, 500),
+ })
+
+ // Normalize input - Claude CLI might send different formats
+ // Format 1: { question: string, options?: array }
+ // Format 2: { questions: [{ question: string, header?: string, options?: array, multiSelect?: boolean }] }
+ let input: { question: string; options?: any[]; custom?: boolean; multiple?: boolean }
+
+ if (rawInput?.questions && Array.isArray(rawInput.questions) && rawInput.questions.length > 0) {
+ // Format 2: questions array (Claude CLI's AskUserQuestion tool uses this format)
+ const q = rawInput.questions[0]
+ input = {
+ question: q.question || q.text || "Question?",
+ options: q.options || q.answers,
+ custom: q.custom ?? true,
+ multiple: q.multiple ?? q.multiSelect,
+ }
+ log.info("handleQuestion: using questions array format", {
+ question: input.question,
+ optionsCount: input.options?.length,
+ hasCustom: input.custom,
+ hasMultiple: input.multiple,
+ })
+ } else {
+ // Format 1: direct question field
+ input = {
+ question: rawInput?.question || rawInput?.text || "Question?",
+ options: rawInput?.options || rawInput?.answers,
+ custom: rawInput?.custom ?? true,
+ multiple: rawInput?.multiple ?? rawInput?.multiSelect,
+ }
+ log.info("handleQuestion: using direct question format", {
+ question: input.question,
+ rawKeys: Object.keys(rawInput || {}),
+ optionsCount: input.options?.length,
+ })
+ }
+
+ let answer = ""
+ if (config.questionHandler) {
+ try {
+ answer = await config.questionHandler(input, sessionID)
+ } catch {
+ // Ignore error
+ }
+ }
+
+ const response = JSON.stringify({
+ type: "user",
+ message: {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: toolCallId,
+ content: answer,
+ },
+ ],
+ },
+ })
+ proc.stdin?.write(response + "\n")
+ return answer
+}
+
+/**
+ * Compact conversation history into a context summary for when we need to
+ * start a fresh Claude CLI session but want to preserve OpenCode's conversation context.
+ */
+function compactConversationHistory(prompt: Parameters<LanguageModelV2["doGenerate"]>[0]["prompt"]): string | null {
+ // Skip system messages, only include user/assistant exchanges
+ const conversationMessages = prompt.filter((m) => m.role === "user" || m.role === "assistant")
+
+ if (conversationMessages.length <= 1) {
+ // No prior conversation to compact
+ return null
+ }
+
+ // Build a summary of the conversation (excluding the current message)
+ const historyParts: string[] = []
+
+ for (let i = 0; i < conversationMessages.length - 1; i++) {
+ const msg = conversationMessages[i]
+ const role = msg.role === "user" ? "User" : "Assistant"
+
+ let text = ""
+ if (typeof msg.content === "string") {
+ text = msg.content
+ } else if (Array.isArray(msg.content)) {
+ const textParts = (msg.content as any[])
+ .filter((p) => p.type === "text" && p.text)
+ .map((p) => p.text)
+ text = textParts.join("\n")
+
+ // Also note tool calls/results briefly
+ const toolCalls = (msg.content as any[]).filter((p) => p.type === "tool-call")
+ const toolResults = (msg.content as any[]).filter((p) => p.type === "tool-result")
+
+ if (toolCalls.length > 0) {
+ text += `\n[Called ${toolCalls.length} tool(s): ${toolCalls.map((t: any) => t.toolName).join(", ")}]`
+ }
+ if (toolResults.length > 0) {
+ text += `\n[Received ${toolResults.length} tool result(s)]`
+ }
+ }
+
+ if (text.trim()) {
+ // Truncate very long messages
+ const truncated = text.length > 2000 ? text.slice(0, 2000) + "..." : text
+ historyParts.push(`${role}: ${truncated}`)
+ }
+ }
+
+ if (historyParts.length === 0) {