Open History to see the last commit
1/**
2 * OpenCode workspace projector — mirrors the Claude Code reference
3 * implementation at `packages/ai-claude-code/src/adapters/projection.ts`.
4 *
5 * `withSandbox` surfaces a portable `WorkspaceProjection` (skills, plugins, a
6 * secret resolver, and a one-time marker path) via a capability. This adapter
7 * reads it in `chatStream` setup and projects workspace inputs into OpenCode's
8 * native format:
9 *
10 * - MCP servers → `opencode.json` at the workspace root (mcp section).
11 * Written on EVERY call (never marker-gated) so rotated
12 * secrets always re-apply.
13 * - gitSkill repos → OpenCode has no recognised skills directory; we
14 * warn-and-skip rather than invent a path.
15 * - agentSkill → no bare-name primitive in opencode; warn-and-skip.
16 * - plugins → opencode has no `opencode plugin install` command;
17 * warn-and-skip.
18 *
19 * The `opencode.json` mcp-section shape mirrors the `OPENCODE_CONFIG_CONTENT`
20 * shape already used by the adapter's host-tool-bridge, ensuring both
21 * mechanisms use the same server-entry schema:
22 *
23 * ```json
24 * { "mcp": { "<name>": { "type": "remote", "url": "...", "enabled": true,
25 * "headers": { ... } } } }
26 * ```
27 *
28 * OpenCode merges project-scoped `opencode.json` with its environment config,
29 * so the workspace file coexists safely with the runtime `OPENCODE_CONFIG_CONTENT`
30 * env written for the host-tool-bridge.
31 *
32 * External-convention caveat: the `opencode.json` location and the `remote`
33 * MCP-entry shape are derived from the adapter's existing `OPENCODE_CONFIG_CONTENT`
34 * usage. Where OpenCode has no clean primitive (gitSkill dir, agentSkill,
35 * plugins) we no-op with a warning instead of fabricating a command.
36 */
37import { isSecretRef, resolveGitSkillDir } from '@tanstack/ai-sandbox'
38import type {
39 BearerRef,
40 SandboxHandle,
41 SecretRef,
42 WorkspaceProjection,
43 WorkspaceSkill,
44} from '@tanstack/ai-sandbox'
45
46/** True when `value` is a `bearer(ref)` marker created by `@tanstack/ai-sandbox`. */
47function isBearerMarker(value: unknown): value is BearerRef {
48 return (
49 typeof value === 'object' &&
50 value !== null &&
51 isSecretRef((value as { __bearerRef?: unknown }).__bearerRef)
52 )
53}
54
55/**
56 * Resolve a single MCP header value: a `SecretRef` resolves to its plaintext,
57 * a `bearer(ref)` marker resolves to `Bearer <plaintext>`, and a plain string
58 * is passed through unchanged.
59 */
60function resolveHeaderValue(
61 value: string | SecretRef | BearerRef,
62 resolveSecret: (ref: SecretRef) => string,
63): string {
64 if (isSecretRef(value)) return resolveSecret(value)
65 if (isBearerMarker(value)) return `Bearer ${resolveSecret(value.__bearerRef)}`
66 return value
67}
68
69/** An OpenCode `remote`-type MCP server entry (mirrors OPENCODE_CONFIG_CONTENT shape). */
70interface OpencodeMcpServer {
71 type: 'remote'
72 url: string
73 enabled: boolean
74 headers: Record<string, string>
75}
76
77/**
78 * Build the `mcp` section of OpenCode's `opencode.json` from the
79 * `{ kind: 'mcp' }` skills, resolving every header value (SecretRef / bearer
80 * / string). Returns `undefined` when there are no MCP skills so the caller
81 * can skip the write.
82 */
83function buildMcpSection(
84 skills: Array<WorkspaceSkill>,
85 resolveSecret: (ref: SecretRef) => string,
86): Record<string, OpencodeMcpServer> | undefined {
87 const mcp: Record<string, OpencodeMcpServer> = {}
88 let count = 0
89 for (const skill of skills) {
90 if (skill.kind !== 'mcp') continue
91 count += 1
92 const headers: Record<string, string> = {}
93 const rawHeaders = skill.config.headers ?? {}
94 for (const [name, value] of Object.entries(rawHeaders)) {
95 headers[name] = resolveHeaderValue(value, resolveSecret)
96 }
97 const rawUrl = skill.config['url']
98 const url = typeof rawUrl === 'string' ? rawUrl : ''
99 mcp[skill.name] = { type: 'remote', url, enabled: true, headers }
100 }
101 return count > 0 ? mcp : undefined
102}
103
104/**
105 * Write (or merge-update) `opencode.json` at the workspace root with the
106 * project-scoped MCP servers, re-resolving every secret. Runs on EVERY
107 * projection call (never marker-gated) so rotated secrets always re-apply.
108 *
109 * If `opencode.json` already exists (e.g. committed to the repo) we read it,
110 * merge only the `mcp` key, and rewrite, preserving other settings. When there
111 * are no MCP skills the write is skipped entirely.
112 */
113async function projectMcpServers(
114 handle: SandboxHandle,
115 projection: WorkspaceProjection,
116): Promise<void> {
117 const mcpSection = buildMcpSection(
118 projection.skills,
119 projection.resolveSecret,
120 )
121 if (mcpSection === undefined) return
122
123 const target = `${projection.root}/opencode.json`
124
125 // Read the existing file if present so we can preserve non-mcp settings.
126 let existing: Record<string, unknown> = {}
127 if (await handle.fs.exists(target)) {
128 try {
129 const raw = await handle.fs.read(target)
130 const parsed: unknown = JSON.parse(raw)
131 if (
132 typeof parsed === 'object' &&
133 parsed !== null &&
134 !Array.isArray(parsed)
135 ) {
136 existing = parsed as Record<string, unknown>
137 }
138 } catch {
139 // Unreadable or invalid JSON — start fresh so the MCP config lands cleanly.
140 }
141 }
142
143 const merged = { ...existing, mcp: mcpSection }
144 await handle.fs.write(target, JSON.stringify(merged, null, 2))
145}
146
147/**
148 * OpenCode has no recognised skills directory where we can drop gitSkill repos.
149 * AGENTS.md is already handled by the bootstrap layer (OpenCode reads it
150 * natively). We warn-and-skip instead of inventing a path.
151 */
152function projectGitSkills(projection: WorkspaceProjection): void {
153 for (const skill of projection.skills) {
154 if (skill.kind !== 'git') continue
155 const dir = skill.into ?? resolveGitSkillDir(projection.root, skill)
156 console.warn(
157 `[opencode] gitSkill "${skill.repo}" cloned to ${dir} but OpenCode has no ` +
158 'recognised skills directory to link it into. The skill is available at that ' +
159 'path — add an AGENTS.md reference to it manually if needed. Skipping.',
160 )
161 }
162}
163
164/**
165 * `agentSkill` references a public skill by bare name. OpenCode has no command
166 * to fetch a skill from a bare name, so we warn and skip.
167 */
168function projectAgentSkills(projection: WorkspaceProjection): void {
169 for (const skill of projection.skills) {
170 if (skill.kind !== 'agent-skill') continue
171 console.warn(
172 `[opencode] agentSkill "${skill.name}" cannot be projected: OpenCode has no ` +
173 'command to install a public skill by bare name. Provide it as a gitSkill ' +
174 'instead. Skipping.',
175 )
176 }
177}
178
179/**
180 * OpenCode has no plugin install command. We warn-and-skip each declared plugin
181 * rather than fabricating a command.
182 */
183function projectPlugins(projection: WorkspaceProjection): void {
184 for (const name of projection.plugins) {
185 console.warn(
186 `[opencode] plugin "${name}" cannot be installed: OpenCode has no plugin ` +
187 'install command. Skipping.',
188 )
189 }
190}
191
192/**
193 * Project a `WorkspaceProjection` into the OpenCode sandbox. Safe to call on
194 * every `chatStream`. The secret-bearing `opencode.json` mcp section is
195 * (re)written on every call, re-resolving secrets, so OpenCode always reads
196 * current values and a snapshot can never serve a stale or rotated secret.
197 * The safe, idempotent, non-secret operations (gitSkill, agentSkill, plugins
198 * — all warn-and-skip for OpenCode) are guarded by a one-time marker so they
199 * produce at most one warning per sandbox lifetime.
200 *
201 * @param handle - The sandbox handle (`fs` + `process`).
202 * @param projection - The portable workspace inputs from `withSandbox`.
203 */
204export async function projectOpencodeWorkspace(
205 handle: SandboxHandle,
206 projection: WorkspaceProjection,
207): Promise<void> {
208 // Always re-resolve and rewrite the secret-bearing MCP config so rotated
209 // secrets re-apply and snapshots can't serve stale values.
210 await projectMcpServers(handle, projection)
211
212 // Gate only the safe, idempotent, non-secret operations on the marker.
213 if (await handle.fs.exists(projection.markerPath)) return
214
215 projectGitSkills(projection)
216 projectAgentSkills(projection)
217 projectPlugins(projection)
218
219 await handle.fs.write(projection.markerPath, '')
220}