Open History to see the last commit
1/**
2 * Codex workspace projector — mirrors the claude-code reference
3 * (`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. Each harness
7 * adapter reads it in its `chatStream` setup and projects those inputs into the
8 * CLI's native format. For Codex that means:
9 *
10 * - MCP servers → `[mcp_servers.<name>]` tables in `<root>/.codex/config.toml`
11 * (TOML), reusing the same `mcp_servers.*` key shape the
12 * adapter already uses to wire the host tool-bridge.
13 * - gitSkill repos → linked under codex's skills dir when one exists; Codex
14 * has no documented project skills dir, so we warn-and-skip.
15 * - agentSkill → no codex primitive pulls a public skill by bare name, so
16 * we warn-and-skip rather than invent one.
17 * - plugins → Codex has no plugin concept, so we warn-and-skip.
18 *
19 * The secret-bearing MCP config is (re)written on EVERY call, re-resolving
20 * secrets each time, so codex always reads current values and a snapshot can
21 * never serve a stale or rotated secret. Only the safe, idempotent, non-secret
22 * operations (gitSkill links, agentSkill / plugin handling) are guarded by a
23 * one-time marker file under the workspace.
24 *
25 * Codex specifics (verified against the codex config schema):
26 * - Codex reads `[mcp_servers.<name>]` from `<root>/.codex/config.toml`, with a
27 * streamable-HTTP server taking `url` plus optional `http_headers`
28 * (a literal header table). We write resolved header values directly into
29 * `http_headers` so a rotated secret re-applies on every projection.
30 * - AGENTS.md is written universally by bootstrap (codex reads it natively),
31 * so it is NOT rewritten here.
32 */
33import {
34 discoverSkillDirs,
35 isSecretRef,
36 resolveGitSkillDir,
37 resolveHarnessCwd,
38} from '@tanstack/ai-sandbox'
39import type {
40 BearerRef,
41 SandboxHandle,
42 SecretRef,
43 WorkspaceProjection,
44 WorkspaceSkill,
45} from '@tanstack/ai-sandbox'
46
47/** POSIX single-quote escape for embedding a value in a shell command. */
48function shellQuote(value: string): string {
49 return `'${value.replace(/'/g, `'\\''`)}'`
50}
51
52/** True when `value` is a `bearer(ref)` marker created by `@tanstack/ai-sandbox`. */
53function isBearerMarker(value: unknown): value is BearerRef {
54 return (
55 typeof value === 'object' &&
56 value !== null &&
57 isSecretRef((value as { __bearerRef?: unknown }).__bearerRef)
58 )
59}
60
61/**
62 * Resolve a single MCP header value: a `SecretRef` resolves to its plaintext, a
63 * `bearer(ref)` marker resolves to `Bearer <plaintext>`, and a plain string is
64 * passed through unchanged.
65 */
66function resolveHeaderValue(
67 value: string | SecretRef | BearerRef,
68 resolveSecret: (ref: SecretRef) => string,
69): string {
70 if (isSecretRef(value)) return resolveSecret(value)
71 if (isBearerMarker(value)) return `Bearer ${resolveSecret(value.__bearerRef)}`
72 return value
73}
74
75/** Escape a string for use as a double-quoted TOML basic string. */
76function tomlString(value: string): string {
77 const escaped = value
78 .replace(/\\/g, '\\\\')
79 .replace(/"/g, '\\"')
80 .replace(/\n/g, '\\n')
81 .replace(/\r/g, '\\r')
82 .replace(/\t/g, '\\t')
83 return `"${escaped}"`
84}
85
86/** A codex-format streamable-HTTP MCP server entry with resolved headers. */
87interface CodexMcpServer {
88 url: string
89 headers: Record<string, string>
90}
91
92/**
93 * Build codex's `mcp_servers` map from the `{ kind: 'mcp' }` skills, resolving
94 * every header value (SecretRef / bearer / string). Returns `undefined` when
95 * there are no MCP skills so the caller can skip the write.
96 */
97function buildMcpServers(
98 skills: Array<WorkspaceSkill>,
99 resolveSecret: (ref: SecretRef) => string,
100): Record<string, CodexMcpServer> | undefined {
101 const servers: Record<string, CodexMcpServer> = {}
102 let count = 0
103 for (const skill of skills) {
104 if (skill.kind !== 'mcp') continue
105 count += 1
106 const headers: Record<string, string> = {}
107 const rawHeaders = skill.config.headers ?? {}
108 for (const [name, value] of Object.entries(rawHeaders)) {
109 headers[name] = resolveHeaderValue(value, resolveSecret)
110 }
111 const rawUrl = skill.config['url']
112 const url = typeof rawUrl === 'string' ? rawUrl : ''
113 servers[skill.name] = { url, headers }
114 }
115 return count > 0 ? servers : undefined
116}
117
118/**
119 * Render codex's `[mcp_servers.<name>]` config in TOML. Each server emits a
120 * `url` and, when it has headers, an inline `http_headers` table of resolved
121 * literal values (matching the `mcp_servers.*` key shape the adapter already
122 * uses for the host tool-bridge).
123 */
124function renderMcpToml(servers: Record<string, CodexMcpServer>): string {
125 const blocks: Array<string> = []
126 for (const [name, server] of Object.entries(servers)) {
127 const lines: Array<string> = [
128 `[mcp_servers.${name}]`,
129 `url = ${tomlString(server.url)}`,
130 ]
131 const headerEntries = Object.entries(server.headers)
132 if (headerEntries.length > 0) {
133 const inline = headerEntries
134 .map(([key, value]) => `${tomlString(key)} = ${tomlString(value)}`)
135 .join(', ')
136 lines.push(`http_headers = { ${inline} }`)
137 }
138 blocks.push(lines.join('\n'))
139 }
140 return `${blocks.join('\n\n')}\n`
141}
142
143/**
144 * Write codex's `<root>/.codex/config.toml`, re-resolving every secret. This runs on
145 * EVERY projection call (never gated by the marker) so codex always reads the
146 * current secret values and a snapshot can never serve a stale or rotated one.
147 * When there are no MCP skills the write is skipped.
148 */
149async function projectMcpServers(
150 handle: SandboxHandle,
151 projection: WorkspaceProjection,
152): Promise<void> {
153 const servers = buildMcpServers(projection.skills, projection.resolveSecret)
154 if (servers === undefined) return
155 const target = `${projection.root}/.codex/config.toml`
156 await handle.fs.mkdir(`${projection.root}/.codex`)
157 await handle.fs.write(target, renderMcpToml(servers))
158}
159
160/**
161 * Ensure each cloned `gitSkill` repo is available under codex's project skills
162 * dir (`<root>/.codex/skills/<basename>`) via a symlink, falling back to a
163 * recursive copy on platforms without `ln -s`. Codex has no documented skills
164 * dir; if linking fails we warn rather than throw.
165 */
166async function projectGitSkills(
167 handle: SandboxHandle,
168 projection: WorkspaceProjection,
169): Promise<void> {
170 const skillsDir = `${projection.root}/.codex/skills`
171 let madeDir = false
172 for (const skill of projection.skills) {
173 if (skill.kind !== 'git') continue
174 if (!madeDir) {
175 await handle.fs.mkdir(skillsDir)
176 madeDir = true
177 }
178 // Discover over virtual `/workspace` paths (handle.fs remaps). Remap only
179 // for shell `ln`/`cp`, where absolute paths must match the real workdir.
180 const source = skill.into ?? resolveGitSkillDir(projection.root, skill)
181 const discovered = await discoverSkillDirs(handle, source)
182 for (const { name, dir } of discovered) {
183 const target = resolveHarnessCwd(handle, `${skillsDir}/${name}`)
184 const realDir = resolveHarnessCwd(handle, dir)
185 const lnCmd = `ln -s ${shellQuote(realDir)} ${shellQuote(target)}`
186 const result = await handle.process.exec(lnCmd, { cwd: projection.root })
187 if (result.exitCode !== 0) {
188 const cpCmd = `cp -r ${shellQuote(realDir)} ${shellQuote(target)}`
189 const copied = await handle.process.exec(cpCmd, {
190 cwd: projection.root,
191 })
192 if (copied.exitCode !== 0) {
193 console.warn(
194 `[codex] failed to link gitSkill "${skill.repo}" into ${target}: ${copied.stderr.trim()}`,
195 )
196 }
197 }
198 }
199 }
200}
201
202/**
203 * `agentSkill` references a public skill by bare name. Codex has no primitive to
204 * fetch a skill from a bare name, so we warn and skip rather than fabricate a
205 * command.
206 */
207function projectAgentSkills(projection: WorkspaceProjection): void {
208 for (const skill of projection.skills) {
209 if (skill.kind !== 'agent-skill') continue
210 console.warn(
211 `[codex] agentSkill "${skill.name}" cannot be projected: Codex has no ` +
212 'command to install a public skill by bare name. Provide it as a gitSkill ' +
213 'instead. Skipping.',
214 )
215 }
216}
217
218/**
219 * Codex has no plugin concept, so declared plugins cannot be projected. We warn
220 * once per plugin and skip rather than throw.
221 */
222function projectPlugins(projection: WorkspaceProjection): void {
223 for (const name of projection.plugins) {
224 console.warn(
225 `[codex] plugin "${name}" cannot be projected: Codex has no plugin ` +
226 'concept. Provide its functionality as a gitSkill or an MCP server ' +
227 'instead. Skipping.',
228 )
229 }
230}
231
232/**
233 * Project a `WorkspaceProjection` into the Codex sandbox. Safe to call on every
234 * `chatStream`. The secret-bearing MCP config is (re)written on every call,
235 * re-resolving secrets, so codex always reads current values and a snapshot can
236 * never serve a stale or rotated secret. The safe, idempotent, non-secret
237 * operations (gitSkill links, agentSkill / plugin handling) are guarded by a
238 * one-time marker so they run only on the first call after create/restore.
239 *
240 * @param handle - The sandbox handle (`fs` + `process`).
241 * @param projection - The portable workspace inputs from `withSandbox`.
242 */
243export async function projectCodexWorkspace(
244 handle: SandboxHandle,
245 projection: WorkspaceProjection,
246): Promise<void> {
247 // Always re-resolve and rewrite the secret-bearing MCP config so rotated
248 // secrets re-apply and snapshots can't serve stale values.
249 await projectMcpServers(handle, projection)
250
251 // Gate only the safe, idempotent, non-secret operations on the marker.
252 if (await handle.fs.exists(projection.markerPath)) return
253
254 await projectGitSkills(handle, projection)
255 projectAgentSkills(projection)
256 projectPlugins(projection)
257
258 await handle.fs.write(projection.markerPath, '')
259}