Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

projection.ts

236 lines9.1 KB

1/**
2 * Claude Code workspace projector — the reference implementation the other
3 * harness projectors (codex, opencode) mirror.
4 *
5 * `withSandbox` surfaces a portable `WorkspaceProjection` (skills, plugins, a
6 * secret resolver, and a one-time marker path) via a capability. Each harness
7 * adapter reads it in its `chatStream` setup and projects those inputs into the
8 * CLI's native format. For Claude Code that means:
9 *
10 * - MCP servers → a project-scoped `.mcp.json` at the workspace root.
11 * - gitSkill repos → linked under `.claude/skills/<basename>`.
12 * - agentSkill → no reliable claude primitive pulls a public skill by
13 * bare name, so we warn and skip rather than invent one.
14 * - plugins → `claude plugin install <name> --scope project`
15 * (best-effort; project scope so the adapter's default
16 * `--setting-sources project` loads it).
17 *
18 * The secret-bearing `.mcp.json` is (re)written on EVERY call, re-resolving
19 * secrets each time, so claude always reads current values and a snapshot can
20 * never serve a stale or rotated secret. Only the safe, idempotent, non-secret
21 * operations (gitSkill links, plugin installs, agentSkill handling) are guarded
22 * by a one-time marker file under the workspace.
23 *
24 * External-convention caveat: the `.mcp.json` location/shape, the skills dir,
25 * and the plugin-install command are verified against the installed `claude`
26 * CLI. Where claude has no clean primitive (agentSkill by bare name) we no-op
27 * with a warning instead of fabricating a command.
28 */
29import {
30 discoverSkillDirs,
31 isSecretRef,
32 resolveGitSkillDir,
33 resolveHarnessCwd,
34} from '@tanstack/ai-sandbox'
35import type {
36 BearerRef,
37 SandboxHandle,
38 SecretRef,
39 WorkspaceProjection,
40 WorkspaceSkill,
41} from '@tanstack/ai-sandbox'
42​
43/** POSIX single-quote escape for embedding a value in a shell command. */
44function shellQuote(value: string): string {
45 return `'${value.replace(/'/g, `'\\''`)}'`
47​
48/** True when `value` is a `bearer(ref)` marker created by `@tanstack/ai-sandbox`. */
49function isBearerMarker(value: unknown): value is BearerRef {
50 return (
51 typeof value === 'object' &&
52 value !== null &&
53 isSecretRef((value as { __bearerRef?: unknown }).__bearerRef)
54 )
56​
57/**
58 * Resolve a single MCP header value: a `SecretRef` resolves to its plaintext, a
59 * `bearer(ref)` marker resolves to `Bearer <plaintext>`, and a plain string is
60 * passed through unchanged.
61 */
62function resolveHeaderValue(
63 value: string | SecretRef | BearerRef,
64 resolveSecret: (ref: SecretRef) => string,
65): string {
66 if (isSecretRef(value)) return resolveSecret(value)
67 if (isBearerMarker(value)) return `Bearer ${resolveSecret(value.__bearerRef)}`
68 return value
70​
71/** A claude-format HTTP MCP server entry. */
72interface ClaudeMcpServer {
73 type: 'http'
74 url: string
75 headers: Record<string, string>
77​
78/**
79 * Build claude's project-scoped MCP config from the `{ kind: 'mcp' }` skills,
80 * resolving every header value (SecretRef / bearer / string). Returns
81 * `undefined` when there are no MCP skills so the caller can skip the write.
82 */
83function buildMcpConfig(
84 skills: Array<WorkspaceSkill>,
85 resolveSecret: (ref: SecretRef) => string,
86): { mcpServers: Record<string, ClaudeMcpServer> } | undefined {
87 const mcpServers: Record<string, ClaudeMcpServer> = {}
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 mcpServers[skill.name] = { type: 'http', url, headers }
100 }
101 return count > 0 ? { mcpServers } : undefined
103​
104/**
105 * Write the project-scoped `.mcp.json`, re-resolving every secret. This runs on
106 * EVERY projection call (never gated by the marker) so claude always reads the
107 * current secret values and a snapshot can never serve a stale or rotated one.
108 * With `snapshot:'after-run'` the file may still be captured in the image, so
109 * secret-bearing MCP material is best used with the default `after-setup`
110 * strategy. When there are no MCP skills the write is skipped.
111 */
112async function projectMcpServers(
113 handle: SandboxHandle,
114 projection: WorkspaceProjection,
115): Promise<void> {
116 const config = buildMcpConfig(projection.skills, projection.resolveSecret)
117 if (config === undefined) return
118 const target = `${projection.root}/.mcp.json`
119 await handle.fs.write(target, JSON.stringify(config, null, 2))
121​
122/**
123 * Ensure each cloned `gitSkill` repo is available under claude's project skills
124 * dir (`<root>/.claude/skills/<basename>`) via a symlink, falling back to a
125 * recursive copy on platforms without `ln -s`.
126 */
127async function projectGitSkills(
128 handle: SandboxHandle,
129 projection: WorkspaceProjection,
130): Promise<void> {
131 const skillsDir = `${projection.root}/.claude/skills`
132 let madeDir = false
133 for (const skill of projection.skills) {
134 if (skill.kind !== 'git') continue
135 if (!madeDir) {
136 await handle.fs.mkdir(skillsDir)
137 madeDir = true
138 }
139 // Discover over virtual `/workspace` paths (handle.fs remaps). Remap only
140 // for shell `ln`/`cp`, where absolute paths must match the real workdir.
141 const source = skill.into ?? resolveGitSkillDir(projection.root, skill)
142 const discovered = await discoverSkillDirs(handle, source)
143 for (const { name, dir } of discovered) {
144 const target = resolveHarnessCwd(handle, `${skillsDir}/${name}`)
145 const realDir = resolveHarnessCwd(handle, dir)
146 const lnCmd = `ln -s ${shellQuote(realDir)} ${shellQuote(target)}`
147 const result = await handle.process.exec(lnCmd, { cwd: projection.root })
148 if (result.exitCode !== 0) {
149 const cpCmd = `cp -r ${shellQuote(realDir)} ${shellQuote(target)}`
150 const copied = await handle.process.exec(cpCmd, {
151 cwd: projection.root,
152 })
153 if (copied.exitCode !== 0) {
154 console.warn(
155 `[claude-code] failed to link gitSkill "${skill.repo}" into ${target}: ${copied.stderr.trim()}`,
156 )
157 }
158 }
159 }
160 }
162​
163/**
164 * `agentSkill` references a public skill by bare name. Claude Code has no
165 * primitive to fetch a skill from a bare name (skills resolve from local
166 * `.claude/skills/` dirs and plugin marketplaces), so we warn and skip rather
167 * than fabricate a command.
168 */
169function projectAgentSkills(projection: WorkspaceProjection): void {
170 for (const skill of projection.skills) {
171 if (skill.kind !== 'agent-skill') continue
172 console.warn(
173 `[claude-code] agentSkill "${skill.name}" cannot be projected: Claude Code has ` +
174 'no command to install a public skill by bare name. Provide it as a gitSkill ' +
175 'or a plugin instead. Skipping.',
176 )
177 }
179​
180/**
181 * Install each declared plugin via `claude plugin install <name>` at project
182 * scope (user scope is not read under the default `--setting-sources project`).
183 * Plugin installs are best-effort: a failure (no marketplace, network, …) warns
184 * but never throws, so a missing plugin can't break the run.
185 */
186async function projectPlugins(
187 handle: SandboxHandle,
188 projection: WorkspaceProjection,
189): Promise<void> {
190 for (const name of projection.plugins) {
191 const cmd = `claude plugin install ${shellQuote(name)} --scope project`
192 try {
193 const result = await handle.process.exec(cmd, { cwd: projection.root })
194 if (result.exitCode !== 0) {
195 console.warn(
196 `[claude-code] "claude plugin install ${name}" exited ${result.exitCode}: ${result.stderr.trim()}`,
197 )
198 }
199 } catch (error: unknown) {
200 const message = error instanceof Error ? error.message : String(error)
201 console.warn(
202 `[claude-code] failed to install plugin "${name}": ${message}`,
203 )
204 }
205 }
207​
208/**
209 * Project a `WorkspaceProjection` into the Claude Code sandbox. Safe to call on
210 * every `chatStream`. The secret-bearing `.mcp.json` is (re)written on every
211 * call, re-resolving secrets, so claude always reads current values and a
212 * snapshot can never serve a stale or rotated secret. The safe, idempotent,
213 * non-secret operations (gitSkill links, plugin installs, agentSkill handling)
214 * are guarded by a one-time marker so they run only on the first call after
215 * create/restore.
216 *
217 * @param handle - The sandbox handle (`fs` + `process`).
218 * @param projection - The portable workspace inputs from `withSandbox`.
219 */
220export async function projectClaudeWorkspace(
221 handle: SandboxHandle,
222 projection: WorkspaceProjection,
223): Promise<void> {
224 // Always re-resolve and rewrite the secret-bearing MCP config so rotated
225 // secrets re-apply and snapshots can't serve stale values.
226 await projectMcpServers(handle, projection)
227​
228 // Gate only the safe, idempotent, non-secret operations on the marker.
229 if (await handle.fs.exists(projection.markerPath)) return
230​
231 await projectGitSkills(handle, projection)
232 projectAgentSkills(projection)
233 await projectPlugins(handle, projection)
234​
235 await handle.fs.write(projection.markerPath, '')