index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /**
  2. * Local filesystem skill provider.
  3. *
  4. * This package is one implementation of the `ctx.skills` provider registry. It
  5. * discovers directory-bundle and flat Markdown skills from project, custom, and
  6. * user roots, parses YAML frontmatter, and loads bodies through `ctx.fs` when a
  7. * filesystem service is present.
  8. *
  9. * @module @deepseek-ai/dsh-skill-local
  10. */
  11. import { access, readdir, readFile, stat } from 'node:fs/promises'
  12. import { dirname, join, resolve } from 'node:path'
  13. import { homedir } from 'node:os'
  14. import type { Context } from 'cordis'
  15. import z from 'schemastery'
  16. import type Schema from 'schemastery'
  17. import { parse as parseYaml } from 'yaml'
  18. import type { FileSystem, FsDirEntry, FsTarget } from '@deepseek-ai/dsh-fs'
  19. import {
  20. isSkillName,
  21. type SkillCandidate,
  22. type SkillDefinition,
  23. type SkillLookupOptions,
  24. type SkillProvider,
  25. type SkillSource,
  26. } from '@deepseek-ai/dsh-skill'
  27. const PROJECT_DSH_RANK = 100
  28. const PROJECT_AGENTS_RANK = 200
  29. const CUSTOM_RANK = 300
  30. const USER_DSH_RANK = 400
  31. const USER_AGENTS_RANK = 500
  32. export const name = 'skill-local'
  33. export const inject = ['skills']
  34. /** Local filesystem skill provider configuration. */
  35. export interface Config {
  36. /** DeepSeek Harness config root. Defaults to `$DSH_HOME` or `~/.dsh`. */
  37. dshHome?: string
  38. /** Shared agent config root. Defaults to `$DSH_AGENTS_HOME` or `~/.agents`. */
  39. agentsHome?: string
  40. /** Additional skill roots scanned after project roots and before user roots. */
  41. customSkillDirs?: string[]
  42. }
  43. export const Config: Schema<Config> = z.object({
  44. dshHome: z.string(),
  45. agentsHome: z.string(),
  46. customSkillDirs: z.array(z.string()).default([]),
  47. })
  48. interface SkillRoot {
  49. path: string
  50. source: SkillSource
  51. rank: number
  52. skipSystem?: boolean
  53. }
  54. interface SkillRootEntry {
  55. name: string
  56. type: 'directory' | 'file' | 'other'
  57. path: string
  58. }
  59. interface ParsedSkill {
  60. name: string
  61. description: string
  62. whenToUse?: string
  63. disableModelInvocation?: boolean
  64. metadata?: Record<string, unknown>
  65. content: string
  66. }
  67. interface LocalLocator {
  68. path: string
  69. directory: string
  70. }
  71. /** Register the local filesystem skill provider on `ctx.skills`. */
  72. export function apply(ctx: Context, config: Config = {}): void {
  73. const provider = new LocalSkillProvider(ctx, config)
  74. ctx.skills.registerProvider(provider)
  75. }
  76. /** Provider that maps local project/user skill roots into `ctx.skills`. */
  77. export class LocalSkillProvider implements SkillProvider {
  78. readonly name = 'local'
  79. private readonly dshHome: string
  80. private readonly agentsHome: string
  81. private readonly customSkillDirs: string[]
  82. constructor(private readonly ctx: Context, config: Config = {}) {
  83. this.dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'))
  84. this.agentsHome = resolve(config.agentsHome ?? process.env.DSH_AGENTS_HOME ?? join(homedir(), '.agents'))
  85. this.customSkillDirs = (config.customSkillDirs ?? []).map(root => resolve(root))
  86. }
  87. /**
  88. * Discover local skill summaries for a cwd-sensitive workspace.
  89. * @param options - lookup options; `cwd` selects the project roots to scan.
  90. * @returns local provider candidates with stable root ranks.
  91. */
  92. async list(options: SkillLookupOptions): Promise<SkillCandidate[]> {
  93. const roots = await this.roots(options.cwd)
  94. const candidates: SkillCandidate[] = []
  95. for (const root of roots) {
  96. for (const skill of await discoverRoot(root, this.ctx)) {
  97. candidates.push(skill)
  98. }
  99. }
  100. return candidates
  101. }
  102. /**
  103. * Load a complete local skill body from the candidate's file locator.
  104. * @param candidate - the winning candidate returned by this provider.
  105. * @param options - lookup options whose signal cancels filesystem reads.
  106. * @returns the full local skill, or `undefined` if the file disappeared.
  107. */
  108. async get(candidate: SkillCandidate, options: SkillLookupOptions): Promise<SkillDefinition | undefined> {
  109. const locator = candidate.locator as LocalLocator
  110. const parsed = await parseSkillFile(locator.path, this.ctx, options.signal)
  111. if (parsed === undefined) return undefined
  112. return {
  113. name: parsed.name,
  114. description: parsed.description,
  115. ...parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {},
  116. ...parsed.disableModelInvocation !== undefined ? { disableModelInvocation: parsed.disableModelInvocation } : {},
  117. source: candidate.source,
  118. provider: this.name,
  119. resourceBase: { kind: 'directory', path: locator.directory },
  120. path: locator.path,
  121. ...parsed.metadata !== undefined ? { metadata: parsed.metadata } : {},
  122. content: parsed.content,
  123. }
  124. }
  125. private async roots(cwd: string | undefined): Promise<SkillRoot[]> {
  126. const roots: SkillRoot[] = []
  127. if (cwd !== undefined) {
  128. const projectRoot = await findProjectRoot(resolve(cwd), optionalFileSystem(this.ctx))
  129. roots.push(
  130. { path: join(projectRoot, '.dsh/skills'), source: 'project-dsh', rank: PROJECT_DSH_RANK },
  131. { path: join(projectRoot, '.agents/skills'), source: 'project-agents', rank: PROJECT_AGENTS_RANK },
  132. )
  133. }
  134. roots.push(
  135. ...this.customSkillDirs.map(path => ({ path, source: 'custom' as const, rank: CUSTOM_RANK })),
  136. { path: join(this.dshHome, 'skills'), source: 'user-dsh', rank: USER_DSH_RANK, skipSystem: true },
  137. { path: join(this.agentsHome, 'skills'), source: 'user-agents', rank: USER_AGENTS_RANK },
  138. )
  139. return roots
  140. }
  141. }
  142. async function discoverRoot(root: SkillRoot, ctx: Context): Promise<SkillCandidate[]> {
  143. const skills: SkillCandidate[] = []
  144. const entries = await listSkillRootEntries(root, ctx)
  145. for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
  146. if (root.skipSystem && entry.name === '.system') continue
  147. const locator = entry.type === 'directory'
  148. ? { path: join(entry.path, 'SKILL.md'), directory: entry.path }
  149. : entry.type === 'file' && entry.name.endsWith('.md')
  150. ? { path: entry.path, directory: root.path }
  151. : undefined
  152. if (locator === undefined) continue
  153. const parsed = await parseSkillFile(locator.path, ctx)
  154. if (parsed === undefined) continue
  155. skills.push({
  156. name: parsed.name,
  157. description: parsed.description,
  158. ...parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {},
  159. ...parsed.disableModelInvocation !== undefined ? { disableModelInvocation: parsed.disableModelInvocation } : {},
  160. provider: 'local',
  161. source: root.source,
  162. rank: root.rank,
  163. locator,
  164. resourceBase: { kind: 'directory', path: locator.directory },
  165. path: locator.path,
  166. ...parsed.metadata !== undefined ? { metadata: parsed.metadata } : {},
  167. })
  168. }
  169. return skills
  170. }
  171. async function listSkillRootEntries(root: SkillRoot, ctx: Context): Promise<SkillRootEntry[]> {
  172. const fs = optionalFileSystem(ctx)
  173. if (fs !== undefined) return await listSkillRootEntriesFromFileSystem(root, fs)
  174. return await listSkillRootEntriesFromNode(root, ctx)
  175. }
  176. async function listSkillRootEntriesFromFileSystem(root: SkillRoot, fs: FileSystem): Promise<SkillRootEntry[]> {
  177. // Skill roots are optional; an absent or unlistable root contributes no skills.
  178. const entries = await fsListDir(fs, root.path).catch(() => undefined)
  179. return entries === undefined ? [] : entries.map(entryFromFs)
  180. }
  181. async function fsListDir(fs: FileSystem, path: string): Promise<FsDirEntry[]> {
  182. const target = await fs.resolve(path)
  183. return await fs.listDir(target)
  184. }
  185. function entryFromFs(entry: FsDirEntry): SkillRootEntry {
  186. return { name: entry.name, type: entry.type, path: entry.target.displayPath }
  187. }
  188. async function listSkillRootEntriesFromNode(root: SkillRoot, ctx: Context): Promise<SkillRootEntry[]> {
  189. let entries
  190. try {
  191. entries = await readdir(root.path, { withFileTypes: true, encoding: 'utf8' })
  192. } catch {
  193. // Missing or unreadable local skill roots are expected in most deployments.
  194. return []
  195. }
  196. const result: SkillRootEntry[] = []
  197. for (const entry of entries) {
  198. const path = join(root.path, entry.name)
  199. const type = await nodeEntryKind(path, entry, ctx)
  200. result.push({ name: entry.name, type: type ?? 'other', path })
  201. }
  202. return result
  203. }
  204. async function parseSkillFile(path: string, ctx: Context, signal?: AbortSignal): Promise<ParsedSkill | undefined> {
  205. const raw = await readSkillText(ctx, path, signal)
  206. signal?.throwIfAborted()
  207. if (raw === undefined) {
  208. return undefined
  209. }
  210. let parsed
  211. try {
  212. parsed = parseFrontmatter(raw)
  213. } catch (error) {
  214. ctx.logger.warn(`skill file ${path} ignored: invalid YAML frontmatter: ${errorMessage(error)}`)
  215. return undefined
  216. }
  217. if (!parsed) {
  218. ctx.logger.warn(`skill file ${path} ignored: missing YAML frontmatter`)
  219. return undefined
  220. }
  221. const name = stringField(parsed.data, 'name')
  222. const description = stringField(parsed.data, 'description')
  223. if (name === undefined || description === undefined) {
  224. ctx.logger.warn(`skill file ${path} ignored: frontmatter requires name and description`)
  225. return undefined
  226. }
  227. if (!isSkillName(name)) {
  228. ctx.logger.warn(`skill file ${path} ignored: invalid skill name "${name}"`)
  229. return undefined
  230. }
  231. return {
  232. name,
  233. description,
  234. ...optionalString(parsed.data, 'whenToUse'),
  235. ...optionalBoolean(parsed.data, 'disableModelInvocation'),
  236. ...optionalMetadata(parsed.data),
  237. content: parsed.body.trim(),
  238. }
  239. }
  240. function optionalFileSystem(ctx: Context): FileSystem | undefined {
  241. return ctx.get('fs')
  242. }
  243. async function readSkillText(ctx: Context, path: string, signal?: AbortSignal): Promise<string | undefined> {
  244. signal?.throwIfAborted()
  245. const fs = optionalFileSystem(ctx)
  246. if (fs !== undefined) {
  247. return await readSkillTextFromFileSystem(ctx, fs, path, signal)
  248. }
  249. try {
  250. return await readFile(path, { encoding: 'utf8', signal })
  251. } catch {
  252. signal?.throwIfAborted()
  253. return undefined
  254. }
  255. }
  256. async function readSkillTextFromFileSystem(ctx: Context, fs: FileSystem, path: string, signal?: AbortSignal): Promise<string | undefined> {
  257. // A missing or temporarily inaccessible skill file is not fatal to discovery.
  258. signal?.throwIfAborted()
  259. const target = await fs.resolve(path).catch(() => undefined)
  260. signal?.throwIfAborted()
  261. if (target === undefined) return undefined
  262. let info
  263. try {
  264. info = await fs.stat(target, signal)
  265. } catch (error) {
  266. signal?.throwIfAborted()
  267. ctx.logger.warn(`skill file ${path} ignored: failed to stat through filesystem service: ${errorMessage(error)}`)
  268. return undefined
  269. }
  270. if (info === undefined || info.type !== 'file') return undefined
  271. try {
  272. return await fs.readText(target, signal)
  273. } catch (error) {
  274. signal?.throwIfAborted()
  275. ctx.logger.warn(`skill file ${path} ignored: ${fsReadErrorMessage(target, error)}`)
  276. return undefined
  277. }
  278. }
  279. function fsReadErrorMessage(target: FsTarget, error: unknown): string {
  280. return `failed to read text file at ${target.displayPath}: ${errorMessage(error)}`
  281. }
  282. async function nodeEntryKind(fullPath: string, entry: { isDirectory(): boolean; isFile(): boolean; isSymbolicLink(): boolean }, ctx: Context): Promise<'directory' | 'file' | undefined> {
  283. if (entry.isDirectory()) return 'directory'
  284. if (entry.isFile()) return 'file'
  285. /* v8 ignore next -- Non-file directory entries such as FIFOs are platform-specific and intentionally skipped. */
  286. if (!entry.isSymbolicLink()) return undefined
  287. try {
  288. const info = await stat(fullPath)
  289. if (info.isDirectory()) return 'directory'
  290. if (info.isFile()) return 'file'
  291. return undefined
  292. } catch (error) {
  293. ctx.logger.warn(`skill entry ${fullPath} ignored: failed to follow symbolic link: ${errorMessage(error)}`)
  294. return undefined
  295. }
  296. }
  297. function parseFrontmatter(raw: string): { data: Record<string, unknown>; body: string } | undefined {
  298. const firstLineEnd = raw.indexOf('\n')
  299. if (firstLineEnd < 0) return undefined
  300. const firstLine = raw.slice(0, firstLineEnd).replace(/\r$/, '')
  301. if (firstLine !== '---') return undefined
  302. const start = firstLineEnd + 1
  303. const closing = findClosingFrontmatter(raw, start)
  304. if (closing === undefined) return undefined
  305. const yaml = raw.slice(start, closing.start)
  306. const parsed = parseYaml(yaml) as unknown
  307. if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined
  308. return { data: parsed as Record<string, unknown>, body: raw.slice(closing.bodyStart) }
  309. }
  310. function findClosingFrontmatter(raw: string, start: number): { start: number; bodyStart: number } | undefined {
  311. let lineStart = start
  312. while (lineStart <= raw.length) {
  313. const nextNewline = raw.indexOf('\n', lineStart)
  314. const lineEnd = nextNewline < 0 ? raw.length : nextNewline
  315. const line = raw.slice(lineStart, lineEnd).replace(/\r$/, '')
  316. if (line === '---') {
  317. return { start: lineStart, bodyStart: nextNewline < 0 ? raw.length : nextNewline + 1 }
  318. }
  319. if (nextNewline < 0) return undefined
  320. lineStart = nextNewline + 1
  321. }
  322. }
  323. async function findProjectRoot(cwd: string, fs: FileSystem | undefined): Promise<string> {
  324. let current = cwd
  325. while (true) {
  326. if (await pathExists(join(current, '.git'), fs)) {
  327. return current
  328. }
  329. const parent = dirname(current)
  330. if (parent === current) return cwd
  331. current = parent
  332. }
  333. }
  334. async function pathExists(path: string, fs: FileSystem | undefined): Promise<boolean> {
  335. if (fs !== undefined) {
  336. return await pathExistsInFileSystem(path, fs)
  337. }
  338. return await pathExistsInNode(path)
  339. }
  340. async function pathExistsInFileSystem(path: string, fs: FileSystem): Promise<boolean> {
  341. let target
  342. try {
  343. target = await fs.resolve(path)
  344. } catch {
  345. // A backend may reject or hide this candidate; continue walking upward.
  346. return false
  347. }
  348. try {
  349. return await fs.stat(target) !== undefined
  350. } catch {
  351. // Transient stat failures make only this git-root candidate unusable.
  352. return false
  353. }
  354. }
  355. async function pathExistsInNode(path: string): Promise<boolean> {
  356. try {
  357. await access(path)
  358. return true
  359. } catch {
  360. // Missing host paths are expected while walking toward the filesystem root.
  361. return false
  362. }
  363. }
  364. function stringField(data: Record<string, unknown>, key: string): string | undefined {
  365. const value = data[key]
  366. return typeof value === 'string' && value.length > 0 ? value : undefined
  367. }
  368. function optionalString(data: Record<string, unknown>, key: string): { [K in typeof key]?: string } {
  369. const value = data[key]
  370. return typeof value === 'string' && value.length > 0 ? { [key]: value } : {}
  371. }
  372. function optionalBoolean(data: Record<string, unknown>, key: string): { [K in typeof key]?: boolean } {
  373. const value = data[key]
  374. return typeof value === 'boolean' ? { [key]: value } : {}
  375. }
  376. function optionalMetadata(data: Record<string, unknown>): { metadata?: Record<string, unknown> } {
  377. const value = data.metadata
  378. if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
  379. return { metadata: value as Record<string, unknown> }
  380. }
  381. return {}
  382. }
  383. function errorMessage(error: unknown): string {
  384. return String(error)
  385. }