Open History to see the last commit
1/**
2 * Generic workspace projector for ACP harnesses.
3 *
4 * `withSandbox` surfaces a portable {@link WorkspaceProjection} (skills, plugins,
5 * a secret resolver, a one-time marker path) via a capability. Most of it maps
6 * onto ACP natively:
7 *
8 * - **MCP skills** → passed straight through ACP's `newSession` `mcpServers`
9 * (see {@link workspaceMcpServers}); no config file is written, because an
10 * ACP agent receives MCP servers over the protocol. This is the key
11 * difference from file-based harnesses (Claude Code, Codex) that read MCP
12 * from disk.
13 * - **gitSkill repos** → linked into the harness's skills directory (when the
14 * harness declares one via `skillsDir`, e.g. `.pi/skills`).
15 * - **agentSkill / plugins** → no generic ACP primitive, so we warn-and-skip.
16 *
17 * `fileSkill` and `instructions` are already written by the provider-agnostic
18 * bootstrap (into the workspace root + `AGENTS.md`), so they need no projection.
19 */
20import {
21 discoverSkillDirs,
22 isSecretRef,
23 resolveGitSkillDir,
24 resolveHarnessCwd,
25} from '@tanstack/ai-sandbox'
26import type {
27 BearerRef,
28 SandboxHandle,
29 SecretRef,
30 WorkspaceProjection,
31} from '@tanstack/ai-sandbox'
32
33/** ACP `newSession` MCP server descriptor (HTTP transport). */
34export interface AcpMcpServer {
35 name: string
36 url: string
37 headers: Array<{ name: string; value: string }>
38}
39
40function shellQuote(value: string): string {
41 return `'${value.replace(/'/g, `'\\''`)}'`
42}
43
44/**
45 * Make a sandbox path relative to the workspace root, so shell commands work on
46 * every provider. Only `fs.*` remaps the virtual `/workspace`; a raw `/workspace`
47 * in a shell command is the real path in a container but a non-existent absolute
48 * path on local-process. Running relative to the root (the exec cwd) is correct
49 * everywhere.
50 */
51function relativeToRoot(root: string, p: string): string {
52 return p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p
53}
54
55function isBearerMarker(value: unknown): value is BearerRef {
56 return (
57 typeof value === 'object' &&
58 value !== null &&
59 isSecretRef((value as { __bearerRef?: unknown }).__bearerRef)
60 )
61}
62
63function resolveHeaderValue(
64 value: string | SecretRef | BearerRef,
65 resolveSecret: (ref: SecretRef) => string,
66): string {
67 if (isSecretRef(value)) return resolveSecret(value)
68 if (isBearerMarker(value)) return `Bearer ${resolveSecret(value.__bearerRef)}`
69 return value
70}
71
72/**
73 * Build ACP `mcpServers` entries from the workspace's `mcp` skills, resolving
74 * every header value (SecretRef / bearer / plain string). Returns `[]` when
75 * there are no MCP skills. Pass the result to `startAcpSession({ mcpServers })`.
76 */
77export function workspaceMcpServers(
78 projection: WorkspaceProjection,
79): Array<AcpMcpServer> {
80 const servers: Array<AcpMcpServer> = []
81 for (const skill of projection.skills) {
82 if (skill.kind !== 'mcp') continue
83 const rawUrl = skill.config['url']
84 const url = typeof rawUrl === 'string' ? rawUrl : ''
85 const headers = Object.entries(skill.config.headers ?? {}).map(
86 ([name, value]) => ({
87 name,
88 value: resolveHeaderValue(value, projection.resolveSecret),
89 }),
90 )
91 servers.push({ name: skill.name, url, headers })
92 }
93 return servers
94}
95
96/**
97 * Project the non-MCP parts of a workspace into an ACP harness. Links each
98 * cloned `gitSkill` repo into the harness's skills directory when one is
99 * declared; warns and skips `agentSkill`s, `plugin`s, and (when no `skillsDir`
100 * is configured) `gitSkill`s. Idempotent — gated by the projection marker.
101 *
102 * MCP skills are NOT handled here; pass {@link workspaceMcpServers} to the ACP
103 * session instead.
104 */
105export async function projectAcpWorkspace(
106 handle: SandboxHandle,
107 projection: WorkspaceProjection,
108 options: { skillsDir?: string; harnessName: string },
109): Promise<void> {
110 // Idempotent, non-secret operations only — gate on the one-time marker.
111 if (await handle.fs.exists(projection.markerPath)) return
112
113 const { skillsDir, harnessName } = options
114 const gitSkills = projection.skills.filter((skill) => skill.kind === 'git')
115
116 if (gitSkills.length > 0) {
117 if (skillsDir === undefined) {
118 for (const skill of gitSkills) {
119 console.warn(
120 `[${harnessName}] gitSkill "${skill.repo}" cannot be projected: this ` +
121 'harness declares no `skillsDir`. The clone is still available under ' +
122 'the workspace, but the harness will not auto-discover it. Skipping link.',
123 )
124 }
125 } else {
126 // Create the skills dir via fs (which remaps the virtual root), then copy
127 // each clone in with paths relative to the exec cwd (the workspace root)
128 // so the shell command resolves on every provider.
129 await handle.fs.mkdir(`${projection.root}/${skillsDir}`)
130 for (const skill of gitSkills) {
131 // Keep virtual `/workspace` paths for fs discovery. handle.fs remaps
132 // them. Remap only when building shell-relative paths so Daytona and
133 // local-process both resolve the same clone.
134 const source = skill.into ?? resolveGitSkillDir(projection.root, skill)
135 const discovered = await discoverSkillDirs(handle, source)
136 for (const { name, dir } of discovered) {
137 const realRoot = resolveHarnessCwd(handle, projection.root)
138 const realDir = resolveHarnessCwd(handle, dir)
139 const relSource = relativeToRoot(realRoot, realDir)
140 const relTarget = `${skillsDir}/${name}`
141 const cp = await handle.process.exec(
142 `cp -r ${shellQuote(relSource)} ${shellQuote(relTarget)}`,
143 { cwd: projection.root },
144 )
145 if (cp.exitCode !== 0) {
146 console.warn(
147 `[${harnessName}] failed to copy gitSkill "${skill.repo}" into ${relTarget}: ${cp.stderr.trim()}`,
148 )
149 }
150 }
151 }
152 }
153 }
154
155 for (const skill of projection.skills) {
156 if (skill.kind === 'agent-skill') {
157 console.warn(
158 `[${harnessName}] agentSkill "${skill.name}" cannot be projected: there is ` +
159 'no generic ACP primitive to install a skill by bare name. Provide it as ' +
160 'a gitSkill instead. Skipping.',
161 )
162 }
163 }
164 for (const name of projection.plugins) {
165 console.warn(
166 `[${harnessName}] plugin "${name}" cannot be projected: ACP has no generic ` +
167 'plugin concept. Provide its functionality as a gitSkill or MCP server. Skipping.',
168 )
169 }
170
171 await handle.fs.write(projection.markerPath, '')
172}