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

agents-file.ts

139 lines5.1 KB

1/**
2 * Universal AGENTS.md writer with per-CLI symlink projection, plus the
3 * canonical helper for locating cloned gitSkill repositories inside a sandbox.
4 *
5 * The known-names set below lists the canonical instruction-file names for
6 * each AI coding assistant CLI. Keep the list in one place so it is easy to
7 * extend. The copy fallback ensures correctness on platforms without symlink
8 * support (e.g. Windows).
9 *
10 * External per-CLI convention: each assistant looks for its own instruction
11 * file by name (CLAUDE.md for Claude Code, GEMINI.md for Gemini CLI, …).
12 * We write a single authoritative AGENTS.md and point each name at it.
13 */
14import { walkSkillDirs } from '@tanstack/ai-skills'
15import type { SandboxHandle } from './contracts'
16import type { WorkspaceSkill } from './workspace'
17​
18/** CLI instruction-file names that should resolve to AGENTS.md. */
19const SYMLINK_NAMES: ReadonlyArray<string> = ['CLAUDE.md', 'GEMINI.md']
20​
21/**
22 * Resolve the directory a `gitSkill` repo is cloned into when no explicit
23 * `into` override is provided. The convention is:
24 *
25 * `<root>/.tanstack-skills/<basename>`
26 *
27 * where `basename` is derived from the `repo` field by taking the last
28 * path segment and stripping a trailing `.git` suffix.
29 *
30 * Per-harness projectors (e.g. the Claude Code adapter) import this helper
31 * so they can locate cloned skill repos consistently.
32 *
33 * @param root - Workspace root inside the sandbox (e.g. `/workspace`).
34 * @param skill - A `WorkspaceSkill` of `kind === 'git'`.
35 */
36export function resolveGitSkillDir(
37 root: string,
38 skill: Extract<WorkspaceSkill, { kind: 'git' }>,
39): string {
40 const rawBasename = skill.repo.split('/').pop() ?? skill.repo
41 const basename = rawBasename.endsWith('.git')
42 ? rawBasename.slice(0, -4)
43 : rawBasename
44 return `${root}/.tanstack-skills/${basename}`
46​
47/** A folder that contains `SKILL.md`, ready to project under a harness skills dir. */
48export interface DiscoveredSkillDir {
49 name: string
50 dir: string
52​
53function basenameOf(path: string): string {
54 const segments = path.split('/').filter((segment) => segment !== '')
55 return segments[segments.length - 1] ?? path
57​
58/**
59 * Find every skill folder under a cloned `gitSkill` repo.
60 *
61 * A skill folder is a directory that contains `SKILL.md`. Nested packs
62 * (`skills/foo/SKILL.md`) are returned as `{ name: 'foo', dir: '…/skills/foo' }`.
63 * A flat clone with `SKILL.md` at the root is returned as one entry named
64 * after the clone. If no `SKILL.md` is found, the clone itself is returned
65 * so existing basename projection still works.
66 *
67 * The tree walk itself is the shared `walkSkillDirs` from `@tanstack/ai-skills`
68 * (parameterized over an injected lister — here `handle.fs.list`). The
69 * empty→clone-dir fallback is kept here because it is correct for harness
70 * projection but wrong for a skills catalog, so it must not live in the shared
71 * helper.
72 */
73export async function discoverSkillDirs(
74 handle: SandboxHandle,
75 cloneDir: string,
76): Promise<Array<DiscoveredSkillDir>> {
77 const found = await walkSkillDirs((dir) => handle.fs.list(dir), cloneDir)
78 if (found.length === 0) {
79 return [{ name: basenameOf(cloneDir), dir: cloneDir }]
80 }
81 return found
83​
84/** Format workspace scripts as a `## Workspace scripts` markdown section. */
85export function formatWorkspaceScriptsSection(
86 scripts: Record<string, string>,
87): string {
88 const names = Object.keys(scripts).sort()
89 if (names.length === 0) return ''
90 const lines = names.map((name) => `- ${name} → ${scripts[name]}`)
91 return `## Workspace scripts\n\n${lines.join('\n')}`
93​
94/**
95 * Merge base AGENTS.md content with an optional workspace scripts section.
96 * Returns `undefined` when there is nothing to write.
97 */
98export function mergeAgentsContent(
99 base: string | undefined,
100 scripts: Record<string, string> | undefined,
101): string | undefined {
102 const scriptsSection =
103 scripts !== undefined ? formatWorkspaceScriptsSection(scripts) : ''
104 if (base === undefined && scriptsSection.length === 0) return undefined
105 if (base === undefined) return scriptsSection
106 if (scriptsSection.length === 0) return base
107 return `${base.trimEnd()}\n\n${scriptsSection}`
109​
110/** Escape a string for safe use as a single-quoted shell argument. */
111function sqEscape(value: string): string {
112 return value.replace(/'/g, `'\\''`)
114​
115/**
116 * Write `AGENTS.md` under `root` and create per-CLI symlinks (or copies as a
117 * fallback when `ln -s` is unavailable).
118 *
119 * @param handle - The sandbox handle providing `fs` and `process`.
120 * @param root - Absolute path inside the sandbox under which to write.
121 * @param content - Markdown content for the instruction file.
122 */
123export async function writeAgentsFile(
124 handle: SandboxHandle,
125 root: string,
126 content: string,
127): Promise<void> {
128 const agentsPath = `${root}/AGENTS.md`
129 await handle.fs.write(agentsPath, content)
130​
131 for (const name of SYMLINK_NAMES) {
132 const lnCmd = `ln -s '${sqEscape('AGENTS.md')}' '${sqEscape(name)}'`
133 const result = await handle.process.exec(lnCmd, { cwd: root })
134 if (result.exitCode !== 0) {
135 // Symlinks are not supported on this platform — fall back to a copy.
136 await handle.fs.write(`${root}/${name}`, content)
137 }
138 }