dsh-brain/vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-skills/src/service.ts

1590 lines
91 KiB
TypeScript

import { creationChoices, validateCreationConfig } from './creation-roots.ts'
import type { SkillCreationConfig } from './contracts.ts'
import { inQuotaDay, quota, retainedBudget, type BudgetEntry } from './auto-adoption-budget.ts'
import { triageSuggestion } from './triage.ts'
import type { AutoAdoptionReservation } from './contracts.ts'
import { randomUUID } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
import { withMemoryStorageLock } from 'dsh-brain-mnemon/extension-sdk'
import {
SKILL_ROOT_KINDS, skillCaseSignature, skillDraftSignature, compareAutomaticSkillRuns, type AutoAdoptionEvent, type AutomaticAdoption, type DraftExpectation,
type BacktestRun, type CaseResult, type CatalogView, type DraftPreferencesView, type DraftView, type EvalCase, type EvidencePack, type ModelRoute, type SuggestionView,
type MarketEntry, type MarketInstall, type MarketInstallState, type MarketItem, type MarketPreview, type MarketRegistry, type MarketRegistryFile, type MarketSearchResult,
type MarketSourceKind, type MarketView, type ReviewRecordInput, type ReviewRecordResult, type RunTarget, type SkillCatalog, type SkillDocument,
type SkillDraft, type SkillDraftFileChange, type SkillOrigin, type SkillResolution, type SkillResourceFile, type SkillRootKind, type SkillSuggestion, type SkillSummary, type SkillVersion, type SkillVersionReason, type SkillsOverview, type Trajectory, type TrajectorySummary, type TrashEntry, type TrashRestoreInput, type TrashRestorePreview,
} from './contracts.ts'
import { activeSkill, catalogFingerprint, findSkill, readCatalog, readSkillDocument, requireWritableRoot, requireWritableSkill, rootPath, sha256, type SkillRootOptions } from './catalog.ts'
import { snapshotResourcePreview, snapshotBundleFiles, changedBundleSnapshot, restoreBundleFiles, applyBundleFileChanges, extractConcreteBundleReferences, prepareDraftFileChanges, readBundleResourceState } from './bundle-files.ts'
import { legacySuggestionWorkspace, skillOrigin, validOrigin } from './identity.ts'
import { isSkillName, setFrontmatterKey, skillTemplate, validateSkillContent, withInvocation } from './frontmatter.ts'
import { admitReview, expireSuggestions, OPEN_STATUSES, policyFrom, similarCase, trajectorySummary } from './policy.ts'
import { entryExists, MAX_CASES_PER_SKILL, MAX_VERSIONS_PER_SKILL, SkillsStore, writeFileAtomic, type SkillBundleSnapshot, type EvalsFile, type LedgerFile, type RegistryRecord } from './store.ts'
import {
bundledOfficialRegistry, defaultFetcher, fetchSkillDocument, fetchSkillFiles, indexedParts, isDiscoveryIndex, isPluginMarketplace, listSkillFiles, loadDiscovery,
loadJson, loadRegistry, loadRepository, marketplaceRepository, OFFICIAL_REGISTRY_ID, OFFICIAL_REGISTRY_URL, parseDiscovery, parseRegistry, REGISTRY_REFRESH_MS,
registryId, resolveIndexed, searchSkillsSh, skillMeta, SKILLS_SH_ID, SKILLS_SH_URL, skillsShAudits, skillsShSnapshot, type Fetcher, type SkillFile,
} from './market.ts'
import { detectSource, parseGithub } from './source-kind.ts'
const RUN_STALE_MS = 45 * 60 * 1000
export interface CaseInput {
id?: string
skillName: string
title: string
prompt: string
context?: string
requiresVision?: boolean
checks: Array<{ id?: string; text: string; must: boolean }>
enabled?: boolean
}
function clip(value: string, maximum: number): string {
const text = value.trim()
return text.length <= maximum ? text : text.slice(0, maximum - 1) + '…'
}
function bundleTextMap(files: readonly SkillResourceFile[]): Record<string, string> {
const out: Record<string, string> = {}
for (const file of files) if (file.content !== undefined) out[file.path] = file.content
return out
}
function toResourceList(map: Record<string, string>): Array<{ path: string; content: string }> {
return Object.keys(map).sort((a, b) => a.localeCompare(b)).map(path => ({ path, content: map[path]! }))
}
function staleRun(run: BacktestRun, now: number): BacktestRun {
return run.status === 'running' && now - Date.parse(run.startedAt) > RUN_STALE_MS ? { ...run, status: 'interrupted' } : run
}
function runScore(results: readonly CaseResult[]): { passRate?: number; score?: number; errors: number } {
const graded = results.filter(result => result.verdict !== 'error')
const errors = results.length - graded.length
if (graded.length === 0) return { errors }
return {
passRate: graded.filter(result => result.verdict === 'pass').length / graded.length,
score: graded.reduce((sum, result) => sum + result.score, 0) / graded.length,
errors,
}
}
export class SkillsService {
readonly store: SkillsStore
private scopedCatalogCache: Map<string, SkillCatalog> | undefined
private readonly creation: SkillCreationConfig | undefined
constructor(dataDir: string, private readonly roots: Omit<SkillRootOptions, 'workspace'> & { skillRoots?: SkillCreationConfig } = {}, private readonly clock: () => Date = () => new Date(), private readonly fetcher: Fetcher = defaultFetcher) {
this.creation = validateCreationConfig(roots.skillRoots)
this.store = new SkillsStore(join(dataDir, 'skills'))
}
private defaultRoot(workspace: string | undefined): SkillRootKind {
return this.creation === undefined ? 'user-dsh' : creationChoices(this.creation, this.catalog(workspace)).default
}
private options(workspace: string | undefined): SkillRootOptions {
return { ...this.roots, ...(workspace === undefined ? {} : { workspace }) }
}
private withCatalog<T>(operation: () => T): T {
if (this.scopedCatalogCache !== undefined) return operation()
this.scopedCatalogCache = new Map()
try {
return operation()
} finally {
this.scopedCatalogCache = undefined
}
}
private invalidateCatalog(): void {
this.scopedCatalogCache?.clear()
}
private writeSkillFile(path: string, content: string): void {
writeFileAtomic(path, content)
this.invalidateCatalog()
}
private write<T>(operation: () => T): Promise<T> {
return withMemoryStorageLock(this.store.directory, () => this.withCatalog(operation))
}
revision(workspace: string | undefined): string {
return 'skills:' + sha256(`${this.store.fingerprint()}#${catalogFingerprint(this.options(workspace))}`).slice(0, 32)
}
catalog(workspace: string | undefined): SkillCatalog {
const options = this.options(workspace)
const cache = this.scopedCatalogCache
if (cache === undefined) return readCatalog(options)
const key = `${workspace?.trim() ?? ''}\0${options.dshHome ?? process.env.DSH_HOME ?? ''}\0${options.agentsHome ?? process.env.DSH_AGENTS_HOME ?? ''}\0${options.allowLinkedUpdates === true}`
const cached = cache.get(key)
if (cached !== undefined) return cached
const loaded = readCatalog(options)
cache.set(key, loaded)
return loaded
}
private original(key: string | undefined, origin: SkillOrigin | undefined, legacyWorkspace?: string): { resolution: SkillResolution; skill?: SkillSummary; origin?: SkillOrigin } {
if (key === undefined || (origin !== undefined && !validOrigin(key, origin))
|| (key.startsWith('project-') && origin === undefined && legacyWorkspace === undefined)) return { resolution: 'origin-unavailable' }
const catalog = this.catalog(origin?.workspace ?? legacyWorkspace)
const skill = catalog.skills.find(candidate => candidate.key === key && (origin === undefined || resolve(candidate.path) === resolve(origin.path)))
return skill === undefined ? { resolution: 'missing' } : { resolution: 'available', skill, origin: skillOrigin(catalog, skill) }
}
private suggestionOriginal(ledger: LedgerFile, suggestion: SkillSuggestion) {
return this.original(suggestion.skillKey, suggestion.origin, suggestion.origin === undefined ? legacySuggestionWorkspace(ledger, suggestion) : undefined)
}
private draftOriginal(ledger: LedgerFile, draft: SkillDraft) {
if (draft.origin !== undefined) return this.original(draft.baseKey, draft.origin)
const suggestion = ledger.suggestions.find(candidate => candidate.id === draft.suggestionId && candidate.skillKey === draft.baseKey)
return suggestion === undefined ? this.original(draft.baseKey, undefined) : this.suggestionOriginal(ledger, suggestion)
}
private requireOriginal(original: { resolution: SkillResolution; skill?: SkillSummary; origin?: SkillOrigin }): SkillSummary {
if (original.skill !== undefined) return original.skill
throw new Error(original.resolution === 'origin-unavailable'
? 'The original workspace was not recorded reliably. Open the skill in its original workspace and generate a new draft; the existing draft and evidence are kept.'
: 'The original skill file was deleted, moved, or cannot be read. Restore it or open the skill at its new location and generate a new draft.')
}
catalogView(workspace: string | undefined): CatalogView {
const catalog = this.catalog(workspace)
const ledger = this.store.ledger()
const evals = this.store.evals()
expireSuggestions(ledger, this.clock())
const stats: CatalogView['stats'] = {}
for (const skill of catalog.skills) {
if (stats[skill.name] !== undefined) continue
const loaded = activeSkill(catalog, skill.name)
const last = evals.runs.find(run => run.skillName === skill.name && run.status === 'completed' && run.target.kind === 'current' && run.target.hash === loaded?.hash)
stats[skill.name] = {
open: ledger.suggestions.filter(suggestion => suggestion.skillName === skill.name && OPEN_STATUSES.has(suggestion.status)).length,
cases: evals.cases.filter(entry => entry.skillName === skill.name && entry.enabled).length,
...(last?.passRate === undefined ? {} : { lastPassRate: last.passRate }),
...(last?.score === undefined ? {} : { lastScore: last.score }),
...(last?.finishedAt === undefined ? {} : { lastRunAt: last.finishedAt }),
}
}
return { ...catalog, stats, ...(this.creation === undefined ? {} : { creation: creationChoices(this.creation, catalog) }) }
}
overview(workspace: string | undefined): SkillsOverview {
const now = this.clock()
const ledger = this.store.ledger()
const evals = this.store.evals()
expireSuggestions(ledger, now)
const catalog = this.catalog(workspace)
const attention: SkillsOverview['attention'] = [
...ledger.suggestions.filter(suggestion => suggestion.status === 'pending').map(suggestion => ({ kind: 'suggestion' as const, id: suggestion.id, skillName: suggestion.skillName, title: suggestion.summary, at: suggestion.updatedAt })),
...ledger.drafts.filter(draft => draft.status === 'ready').map(draft => ({ kind: 'draft' as const, id: draft.id, skillName: draft.skillName, title: draft.notes || draft.skillName, at: draft.updatedAt })),
]
const finished = evals.runs.filter(run => run.status === 'completed' && run.target.kind === 'current' && run.score !== undefined)
for (const name of new Set(finished.map(run => run.skillName))) {
const [latest, previous] = finished.filter(run => run.skillName === name)
if (latest !== undefined && previous !== undefined && latest.score! < previous.score! - 0.05) {
attention.push({ kind: 'regression', id: latest.id, skillName: name, title: `${Math.round(previous.score! * 100)} → ${Math.round(latest.score! * 100)}`, at: latest.finishedAt ?? latest.startedAt })
}
}
attention.sort((a, b) => Date.parse(b.at) - Date.parse(a.at))
return {
counts: {
skills: new Set(catalog.skills.map(skill => skill.name)).size,
pending: ledger.suggestions.filter(suggestion => suggestion.status === 'pending').length,
drafting: ledger.suggestions.filter(suggestion => suggestion.status === 'drafting').length,
drafts: ledger.drafts.filter(draft => draft.status === 'ready').length,
trajectories: ledger.trajectories.length,
cases: evals.cases.filter(entry => entry.enabled).length,
runsRunning: evals.runs.filter(run => staleRun(run, now.getTime()).status === 'running').length,
trash: this.store.trashEntries().length,
},
...(ledger.reviews[0] === undefined ? {} : { lastReviewAt: ledger.reviews[0].at }),
attention: attention.slice(0, 20),
reviews: ledger.reviews.slice(0, 20),
}
}
skill(workspace: string | undefined, key: string): SkillDocument & { versions: SkillVersion[] } {
const summary = findSkill(this.catalog(workspace), key)
return { ...readSkillDocument(summary), versions: this.versions(key) }
}
versions(key: string): SkillVersion[] {
return this.store.ledger().versions.filter(version => version.skillKey === key)
}
version(key: string, id: string): { version: SkillVersion; content: string } {
const version = this.versions(key).find(candidate => candidate.id === id)
if (version === undefined) throw new Error('version not found: ' + id)
return { version, content: this.store.versionContent(version) }
}
suggestions(statuses?: readonly string[]): SkillSuggestion[] {
const ledger = this.store.ledger()
expireSuggestions(ledger, this.clock())
return ledger.suggestions.filter(suggestion => statuses === undefined || statuses.length === 0 || statuses.includes(suggestion.status))
.map(suggestion => ({ ...suggestion, triage: triageSuggestion(suggestion, ledger.trajectories) }))
}
suggestion(workspace: string | undefined, id: string): SuggestionView {
return this.withCatalog(() => {
const ledger = this.store.ledger()
expireSuggestions(ledger, this.clock())
const suggestion = ledger.suggestions.find(candidate => candidate.id === id)
if (suggestion === undefined) throw new Error('suggestion not found: ' + id)
const original = suggestion.action === 'update' ? this.suggestionOriginal(ledger, suggestion) : undefined
const catalog = this.catalog(workspace)
const skill = original === undefined ? activeSkill(catalog, suggestion.skillName) : original.skill
const draft = suggestion.draftId === undefined ? undefined : ledger.drafts.find(candidate => candidate.id === suggestion.draftId)
const cited = new Set(suggestion.evidence.map(reference => reference.trajectoryId))
return {
suggestion: { ...suggestion, triage: triageSuggestion(suggestion, ledger.trajectories) },
hashCurrent: suggestion.action === 'create' ? skill === undefined : skill !== undefined && skill.hash === suggestion.skillFileHash,
...(original === undefined ? {} : { resolution: original.resolution }),
...(skill === undefined ? {} : { skill: readSkillDocument(skill), skillInCatalog: catalog.skills.some(candidate => candidate.key === skill.key && candidate.path === skill.path) }),
...(draft === undefined ? {} : { draft }),
trajectories: ledger.trajectories.filter(entry => cited.has(entry.id)),
}
})
}
trajectories(filter: { skill?: string; signal?: string; sessionId?: string } = {}): TrajectorySummary[] {
const ledger = this.store.ledger()
const skillSuggestionIds = filter.skill === undefined
? undefined
: new Set(ledger.suggestions.filter(suggestion => suggestion.skillName === filter.skill).map(suggestion => suggestion.id))
return ledger.trajectories.filter(entry => (filter.skill === undefined || entry.stats.skills.includes(filter.skill) || entry.suggestionIds.some(id => skillSuggestionIds!.has(id)))
&& (filter.signal === undefined || entry.signals.includes(filter.signal as never))
&& (filter.sessionId === undefined || entry.sessionId === filter.sessionId))
}
trajectory(id: string): Trajectory {
return this.store.trajectory(id)
}
cases(skillName?: string): EvalCase[] {
const cases = this.store.evals().cases
return skillName === undefined ? cases : cases.filter(entry => entry.skillName === skillName)
}
runs(skillName?: string): BacktestRun[] {
const now = this.clock().getTime()
return this.store.evals().runs.filter(run => skillName === undefined || run.skillName === skillName).map(run => staleRun(run, now))
}
run(id: string): BacktestRun {
const run = this.store.evals().runs.find(candidate => candidate.id === id)
if (run === undefined) throw new Error('run not found: ' + id)
return staleRun(run, this.clock().getTime())
}
drafts(filter: { suggestionId?: string; skill?: string; path?: string } = {}): SkillDraft[] {
return this.withCatalog(() => {
const ledger = this.store.ledger()
return ledger.drafts.filter(draft => (filter.suggestionId === undefined || draft.suggestionId === filter.suggestionId)
&& (filter.skill === undefined || draft.skillName === filter.skill)
&& (filter.path === undefined || this.draftOriginal(ledger, draft).skill?.path === filter.path))
})
}
draft(workspace: string | undefined, id: string): DraftView {
return this.withCatalog(() => {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === id)
if (draft === undefined) throw new Error('draft not found: ' + id)
const original = draft.action === 'update' ? this.draftOriginal(ledger, draft) : undefined
const base = original?.skill
const baseDoc = base === undefined ? undefined : readSkillDocument(base)
let fileConflict = false
const baseFileContents: Record<string, string> = {}
if (draft.action === 'update' && base !== undefined) {
for (const [relPath, expectedHash] of Object.entries(draft.baseFileHashes ?? {})) {
if (base.layout !== 'bundle') { fileConflict = true; break }
try {
const state = readBundleResourceState(dirname(base.path), relPath)
if (state.hash !== expectedHash) { fileConflict = true }
if (state.content !== undefined) baseFileContents[relPath] = state.content
} catch { fileConflict = true }
}
for (const file of draft.files ?? []) {
if (base.layout === 'bundle' && baseFileContents[file.path] === undefined) {
try {
const state = readBundleResourceState(dirname(base.path), file.path)
if (state.content !== undefined) baseFileContents[file.path] = state.content
} catch { }
}
}
}
const conflict = draft.action === 'update'
? base !== undefined && (base.hash !== draft.baseHash || fileConflict) ? 'base-changed' as const : undefined
: activeSkill(this.catalog(workspace), draft.skillName) !== undefined ? 'target-exists' as const : undefined
const now = this.clock().getTime()
const evals = draft.runIds.length === 0 ? undefined : this.store.evals()
const runs = evals === undefined ? [] : draft.runIds.flatMap(runId => {
const run = evals.runs.find(candidate => candidate.id === runId)
return run === undefined ? [] : [staleRun(run, now)]
})
return {
draft,
...(conflict === undefined ? {} : { conflict }),
...(original === undefined ? {} : { resolution: original.resolution }),
...(baseDoc === undefined ? {} : { base: baseDoc }),
...(Object.keys(baseFileContents).length === 0 ? {} : { baseFileContents }),
runs,
}
})
}
reviews(filter: { sessionId?: string; limit?: number } = {}): LedgerFile['reviews'] {
const reviews = this.store.ledger().reviews
return (filter.sessionId === undefined ? reviews : reviews.filter(review => review.sessionId === filter.sessionId)).slice(0, Math.max(1, Math.min(200, filter.limit ?? 50)))
}
evidencePack(workspace: string | undefined, input: { suggestionId?: string; draftId?: string; skill?: string; action?: 'create' | 'update' }): EvidencePack {
return this.withCatalog(() => {
const ledger = this.store.ledger()
const evals = this.store.evals()
const catalog = this.catalog(workspace)
const prior = input.draftId === undefined ? undefined : ledger.drafts.find(candidate => candidate.id === input.draftId)
if (input.draftId !== undefined && prior === undefined) throw new Error('draft not found: ' + input.draftId)
if (prior !== undefined && input.suggestionId !== undefined && prior.suggestionId !== input.suggestionId) throw new Error('draft is for another suggestion')
const suggestion = input.suggestionId === undefined ? undefined : ledger.suggestions.find(candidate => candidate.id === input.suggestionId)
if (input.suggestionId !== undefined && suggestion === undefined) throw new Error('suggestion not found: ' + input.suggestionId)
const skillName = prior?.skillName ?? suggestion?.skillName ?? input.skill
if (skillName === undefined || !isSkillName(skillName)) throw new Error('a skill name or a suggestion is required')
const loaded = prior?.action === 'update' ? this.requireOriginal(this.draftOriginal(ledger, prior))
: suggestion?.action === 'update' ? this.requireOriginal(this.suggestionOriginal(ledger, suggestion)) : activeSkill(catalog, skillName)
const action = loaded === undefined ? 'create' : 'update'
let references = suggestion?.evidence
if (references === undefined) {
const skillSuggestionIds = new Set(ledger.suggestions.filter(candidate => candidate.skillName === skillName).map(candidate => candidate.id))
references = ledger.trajectories
.filter(entry => entry.stats.skills.includes(skillName) || entry.suggestionIds.some(id => skillSuggestionIds.has(id)))
.slice(0, 3)
.map(entry => ({ trajectoryId: entry.id, steps: [] as number[] }))
}
const excerpts: EvidencePack['excerpts'] = []
for (const reference of references.slice(-4)) {
let trajectory: Trajectory
try { trajectory = this.store.trajectory(reference.trajectoryId, ledger) } catch { continue }
const wanted = new Set(reference.steps)
const keep = wanted.size === 0 ? trajectory.steps : trajectory.steps.filter(step => [...wanted].some(index => Math.abs(index - step.index) <= 1))
excerpts.push({
trajectoryId: trajectory.id,
...(trajectory.sessionTitle === undefined ? {} : { sessionTitle: trajectory.sessionTitle }),
steps: keep.slice(0, 60),
annotations: trajectory.annotations.filter(annotation => keep.some(step => step.index === annotation.step)),
})
}
const cases = evals.cases.filter(entry => entry.skillName === skillName && entry.enabled)
const lastRun = loaded === undefined ? undefined : evals.runs.find(run => run.skillName === skillName && run.status === 'completed' && run.target.kind === 'current' && run.target.hash === loaded.hash)
return {
skillName,
action,
...(suggestion === undefined ? {} : { suggestion }),
...(loaded === undefined ? {} : { skill: readSkillDocument(loaded) }),
excerpts,
cases,
...(lastRun === undefined ? {} : { lastRun }),
catalog: catalog.skills.filter(skill => skill.shadowedBy === undefined).slice(0, 80).map(skill => ({ name: skill.name, description: clip(skill.description, 200), root: skill.root })),
drafts: ledger.drafts.filter(draft => draft.skillName === skillName
&& (loaded === undefined ? draft.action === 'create' : this.draftOriginal(ledger, draft).skill?.path === loaded.path)).slice(0, 3),
}
})
}
private recordVersion(
ledger: LedgerFile,
skillKey: string,
content: string,
reason: SkillVersionReason,
previous: string | undefined,
links: { suggestionId?: string; draftId?: string; note?: string } = {},
bundles?: { previous?: SkillBundleSnapshot; current?: SkillBundleSnapshot },
): SkillVersion {
const now = this.clock()
const existing = ledger.versions.filter(version => version.skillKey === skillKey)
const make = (body: string, why: SkillVersionReason, extra: typeof links, offset: number, bundleFiles?: SkillBundleSnapshot): SkillVersion => {
const hash = sha256(body)
const version: SkillVersion = {
id: `${(now.getTime() + offset).toString(36)}-${hash.slice(0, 8)}`, skillKey, hash, bytes: Buffer.byteLength(body, 'utf8'), reason: why,
createdAt: new Date(now.getTime() + offset).toISOString(), ...extra,
}
this.store.saveVersionContent(version, body)
if (bundleFiles !== undefined) this.store.saveVersionResources(version, bundleFiles)
ledger.versions.unshift(version)
return version
}
if (previous !== undefined && (bundles?.previous !== undefined || (existing.length === 0 && sha256(previous) !== sha256(content)))) {
make(previous, existing.length === 0 ? 'original' : 'edit', {}, 0, bundles?.previous)
}
const version = make(content, reason, links, 1, bundles?.current)
const forSkill = ledger.versions.filter(candidate => candidate.skillKey === skillKey)
if (forSkill.length > MAX_VERSIONS_PER_SKILL) {
const removable = forSkill.filter(candidate => candidate.reason !== 'original').slice(MAX_VERSIONS_PER_SKILL - 1)
for (const old of removable) this.store.deleteVersionContent(old)
ledger.versions = ledger.versions.filter(candidate => !removable.includes(candidate))
}
return version
}
private requireHash(skill: SkillSummary, expectedHash: string | undefined): string {
const current = readFileSync(skill.path, 'utf8')
if (expectedHash === undefined || sha256(current) !== expectedHash) throw new Error(`${skill.name} changed since it was read; reload it and try again`)
return current
}
createSkill(workspace: string | undefined, input: { name: string; description: string; root?: SkillRootKind; content?: string }): Promise<SkillSummary> {
return this.write(() => {
if (!isSkillName(input.name)) throw new Error('a skill name uses lowercase letters, digits and single hyphens (max 64)')
const catalog = this.catalog(workspace)
const root = input.root ?? this.defaultRoot(workspace)
if (!SKILL_ROOT_KINDS.includes(root)) throw new Error('unknown skill root: ' + root)
requireWritableRoot(rootPath(catalog, root))
const directory = join(rootPath(catalog, root), input.name)
if (catalog.skills.some(skill => skill.root === root && skill.name === input.name) || existsSync(directory) || existsSync(directory + '.md')) throw new Error(`${input.name} already exists in this root`)
const content = input.content?.trim() ? input.content : skillTemplate(input.name, input.description)
validateSkillContent(content, input.name)
this.writeSkillFile(join(directory, 'SKILL.md'), content)
const ledger = this.store.ledger()
this.recordVersion(ledger, `${root}:${input.name}`, content, 'create', undefined)
this.store.saveLedger(ledger)
return findSkill(this.catalog(workspace), `${root}:${input.name}`)
})
}
saveSkill(workspace: string | undefined, input: { key: string; content: string; expectedHash: string }): Promise<SkillSummary> {
return this.write(() => {
const skill = findSkill(this.catalog(workspace), input.key)
const path = requireWritableSkill(skill, this.roots.allowLinkedUpdates)
const previous = this.requireHash({ ...skill, path }, input.expectedHash)
validateSkillContent(input.content, skill.name)
this.writeSkillFile(path, input.content)
const ledger = this.store.ledger()
this.recordVersion(ledger, skill.key, input.content, 'edit', previous)
this.store.saveLedger(ledger)
return findSkill(this.catalog(workspace), skill.key)
})
}
setInvocation(workspace: string | undefined, input: { key: string; modelInvocable: boolean; userInvocable: boolean; expectedHash: string }): Promise<SkillSummary> {
return this.write(() => {
const skill = findSkill(this.catalog(workspace), input.key)
const path = requireWritableSkill(skill, this.roots.allowLinkedUpdates)
const previous = this.requireHash({ ...skill, path }, input.expectedHash)
const content = withInvocation(previous, { modelInvocable: input.modelInvocable, userInvocable: input.userInvocable })
validateSkillContent(content, skill.name)
this.writeSkillFile(path, content)
const ledger = this.store.ledger()
this.recordVersion(ledger, skill.key, content, 'invocation', previous)
this.store.saveLedger(ledger)
return findSkill(this.catalog(workspace), skill.key)
})
}
deleteSkill(workspace: string | undefined, input: { key: string; expectedHash: string }): Promise<{ trashedTo: string }> {
return this.write(() => {
const catalog = this.catalog(workspace)
const skill = findSkill(catalog, input.key)
const previous = this.requireHash(skill, input.expectedHash)
const ledger = this.store.ledger()
if (ledger.versions.every(version => version.skillKey !== skill.key)) this.recordVersion(ledger, skill.key, previous, 'original', undefined)
const path = skill.layout === 'bundle' ? dirname(skill.path) : skill.path
const trashedTo = this.store.trash(path, skill.name, this.trashOrigin(skill, catalog))
this.invalidateCatalog()
const now = this.clock().toISOString()
for (const suggestion of ledger.suggestions) {
if (suggestion.skillKey === skill.key && suggestion.action === 'update' && OPEN_STATUSES.has(suggestion.status)) { suggestion.status = 'invalidated'; suggestion.updatedAt = now }
}
this.store.saveLedger(ledger)
return { trashedTo }
})
}
trashItems(): TrashEntry[] {
return this.store.trashEntries()
}
private trashOrigin(skill: SkillSummary, catalog: SkillCatalog) {
return {
root: skill.root, key: skill.key, originalPath: skill.layout === 'bundle' ? dirname(skill.path) : skill.path,
...(skill.root.startsWith('project-') && catalog.projectRoot !== undefined ? { workspace: catalog.projectRoot } : {}),
}
}
private trashTarget(workspace: string | undefined, input: TrashRestoreInput) {
const entry = this.store.trashEntry(input.id)
const name = input.name ?? entry.name
if (!isSkillName(name)) throw new Error('a skill name uses lowercase letters, digits and single hyphens (max 64)')
const selected = this.catalog(workspace)
const root = input.root ?? entry.root
if (root !== undefined && !SKILL_ROOT_KINDS.includes(root)) throw new Error('unknown skill root: ' + root)
if (root === undefined || (input.root === undefined && root.startsWith('project-') && entry.workspace === undefined)) {
return { entry, name, roots: selected.roots.map(item => item.kind), destination: undefined }
}
const catalog = input.root === undefined && entry.workspace !== undefined ? this.catalog(entry.workspace) : selected
const directory = rootPath(catalog, root)
let path = join(directory, entry.kind === 'file' ? `${name}.md` : name)
if (input.root === undefined && name === entry.name && entry.originalPath !== undefined) {
if (!isAbsolute(entry.originalPath) || resolve(dirname(entry.originalPath)) !== resolve(directory)) throw new Error('the original skill root has changed; choose a restore location')
path = entry.originalPath
}
const conflict = catalog.skills.find(skill => skill.root === root && skill.name === name)
const occupied = [path, join(directory, name), join(directory, `${name}.md`)].filter(entryExists)
const conflictPath = conflict === undefined ? undefined : conflict.layout === 'bundle' ? dirname(conflict.path) : conflict.path
if (occupied.some(candidate => candidate !== conflictPath)) throw new Error('the restore location already holds another file; choose a different name')
return { entry, name, roots: selected.roots.map(item => item.kind), destination: { root, path, catalog, conflict, conflictPath } }
}
previewTrashRestore(workspace: string | undefined, input: TrashRestoreInput): TrashRestorePreview {
return this.withCatalog(() => {
const target = this.trashTarget(workspace, input)
return {
name: target.name, roots: target.roots, needsRoot: target.destination === undefined,
...(target.destination === undefined ? {} : { path: target.destination.path }),
...(target.destination?.conflict === undefined ? {} : { conflict: { hash: target.destination.conflict.hash } }),
}
})
}
restoreTrash(workspace: string | undefined, input: TrashRestoreInput): Promise<{ key: string; path: string }> {
return this.write(() => {
const { entry, name, destination } = this.trashTarget(workspace, input)
if (destination === undefined) throw new Error('choose a root for this Trash entry; its original location is unknown')
const { root, path, catalog, conflict, conflictPath } = destination
if (conflict !== undefined && (input.replace !== true || input.expectedHash !== conflict.hash)) throw new Error(`${name} already exists in ${root}; rename it or confirm replacement of the current version`)
let content: string | undefined
if (name !== entry.name) {
content = setFrontmatterKey(this.store.trashContent(entry), 'name', name)
validateSkillContent(content, name)
}
let displaced: string | undefined
try {
if (conflict !== undefined) displaced = this.store.trash(conflictPath!, conflict.name, this.trashOrigin(conflict, catalog))
this.store.restoreTrash(entry, path, content)
} catch (error) {
if (displaced !== undefined && !existsSync(conflictPath!)) try { renameSync(displaced, conflictPath!) } catch { }
this.invalidateCatalog()
throw error
}
this.invalidateCatalog()
const key = `${root}:${name}`
const ledger = this.store.ledger()
try { content ??= readFileSync(entry.kind === 'file' ? path : join(path, 'SKILL.md'), 'utf8') } catch { }
if (content !== undefined) this.recordVersion(ledger, key, content, 'restore', undefined)
this.store.saveLedger(ledger)
return { key, path }
})
}
purgeTrash(input: { id: string }): Promise<{ purged: string }> {
return this.write(() => {
const entry = this.store.trashEntry(input.id)
this.store.purgeTrash(entry)
this.store.saveLedger(this.store.ledger())
return { purged: entry.id }
})
}
emptyTrash(): Promise<{ purged: number }> {
return this.write(() => {
const entries = this.store.trashEntries()
for (const entry of entries) this.store.purgeTrash(entry)
if (entries.length > 0) this.store.saveLedger(this.store.ledger())
return { purged: entries.length }
})
}
draftPreferences(): DraftPreferencesView {
const stored = this.store.preferences()
return {
...(stored.draftModel === undefined ? {} : { model: stored.draftModel }),
...(stored.runModel === undefined ? {} : { runModel: stored.runModel }),
suggestionModels: stored.suggestionModels,
skillRunModels: stored.skillRunModels,
}
}
setDraftPreference(input: { slot?: string; suggestionId?: string; skillName?: string; model: ModelRoute | null }): Promise<DraftPreferencesView> {
return this.write(() => {
const preferences = this.store.preferences()
if (input.slot === 'run') {
if (input.skillName !== undefined) {
if (input.model === null) delete preferences.skillRunModels[input.skillName]
else preferences.skillRunModels[input.skillName] = input.model
} else if (input.model === null) delete preferences.runModel
else preferences.runModel = input.model
} else if (input.suggestionId !== undefined) {
if (input.model === null) delete preferences.suggestionModels[input.suggestionId]
else preferences.suggestionModels[input.suggestionId] = input.model
} else if (input.model === null) delete preferences.draftModel
else preferences.draftModel = input.model
this.store.savePreferences(preferences)
return this.draftPreferences()
})
}
restoreVersion(workspace: string | undefined, input: { key: string; versionId: string; expectedHash: string }): Promise<SkillSummary> {
return this.write(() => {
const skill = findSkill(this.catalog(workspace), input.key)
const path = requireWritableSkill(skill, this.roots.allowLinkedUpdates)
const previous = this.requireHash({ ...skill, path }, input.expectedHash)
const ledger = this.store.ledger()
const version = ledger.versions.find(candidate => candidate.skillKey === skill.key && candidate.id === input.versionId)
if (version === undefined) throw new Error('version not found: ' + input.versionId)
const content = this.store.versionContent(version)
validateSkillContent(content, skill.name)
const targetResources = skill.layout === 'bundle' ? this.store.versionResources(version) : undefined
const previousResources = skill.layout === 'bundle' && targetResources !== undefined
? snapshotBundleFiles(dirname(path))
: undefined
let bundleApplied: ReturnType<typeof restoreBundleFiles> | undefined
if (targetResources !== undefined && skill.layout === 'bundle') {
bundleApplied = restoreBundleFiles(dirname(path), targetResources, previousResources!)
}
try {
this.writeSkillFile(path, content)
} catch (error) {
bundleApplied?.rollback()
this.invalidateCatalog()
throw error
}
this.recordVersion(ledger, skill.key, content, 'restore', previous, { note: version.id },
targetResources === undefined ? undefined : { ...(previousResources === undefined ? {} : { previous: previousResources }), current: bundleApplied!.snapshot })
this.store.saveLedger(ledger)
return findSkill(this.catalog(workspace), skill.key)
})
}
private withSuggestion<T>(id: string, change: (suggestion: SkillSuggestion, ledger: LedgerFile) => T): Promise<T> {
return this.write(() => {
const ledger = this.store.ledger()
expireSuggestions(ledger, this.clock())
const suggestion = ledger.suggestions.find(candidate => candidate.id === id)
if (suggestion === undefined) throw new Error('suggestion not found: ' + id)
const value = change(suggestion, ledger)
suggestion.updatedAt = this.clock().toISOString()
this.store.saveLedger(ledger)
return value
})
}
dismissSuggestion(id: string): Promise<SkillSuggestion> {
return this.withSuggestion(id, (suggestion, ledger) => {
if (!OPEN_STATUSES.has(suggestion.status)) throw new Error('this suggestion is already ' + suggestion.status)
if (suggestion.status === 'drafting') throw new Error('a draft is being written for this suggestion; wait for it to finish')
suggestion.status = 'dismissed'
for (const draft of ledger.drafts) if (draft.suggestionId === id && draft.status === 'ready') { draft.status = 'discarded'; draft.updatedAt = suggestion.updatedAt }
return suggestion
})
}
deleteSuggestion(id: string): Promise<{ deleted: string }> {
return this.write(() => {
const ledger = this.store.ledger()
expireSuggestions(ledger, this.clock())
const index = ledger.suggestions.findIndex(candidate => candidate.id === id)
if (index < 0) throw new Error('suggestion not found: ' + id)
const suggestion = ledger.suggestions[index]!
if (suggestion.status === 'drafting') throw new Error('a draft is being written for this suggestion; wait for it to finish')
ledger.suggestions.splice(index, 1)
ledger.drafts = ledger.drafts.filter(draft => draft.suggestionId !== id)
const preferences = this.store.preferences()
if (preferences.suggestionModels[id] !== undefined) {
delete preferences.suggestionModels[id]
this.store.savePreferences(preferences)
}
this.store.saveLedger(ledger)
return { deleted: id }
})
}
suggestionStatus(input: { id: string; status: 'drafting' | 'pending'; error?: string; expectedDraft?: DraftExpectation; signal?: AbortSignal }): Promise<SkillSuggestion> {
return this.withSuggestion(input.id, (suggestion, ledger) => {
input.signal?.throwIfAborted()
this.requireExpectedDraft(ledger, suggestion, input.expectedDraft)
if (input.status === 'drafting') {
if (suggestion.status !== 'pending' && suggestion.status !== 'review') throw new Error('this suggestion is ' + suggestion.status + '; only an open suggestion can be drafted')
suggestion.status = 'drafting'
delete suggestion.lastError
} else {
if (suggestion.status !== 'drafting') return suggestion
suggestion.status = suggestion.draftId === undefined ? 'pending' : 'review'
if (input.error !== undefined) suggestion.lastError = clip(input.error, 500)
}
return suggestion
})
}
private requireExpectedDraft(ledger: LedgerFile, suggestion: SkillSuggestion | undefined, expected: DraftExpectation | undefined): void {
if (expected === undefined) return
const current = ledger.drafts.find(draft => draft.id === suggestion?.draftId)
const matches = expected === null ? suggestion !== undefined && suggestion.draftId === undefined
: current?.id === expected.id && current.status === 'ready' && sha256(skillDraftSignature(current)) === expected.hash
if (!matches) throw new Error('The suggestion or draft changed while this draft was being generated; leave it for manual review')
}
recordAutoAdoption(id: string, input: Omit<AutoAdoptionEvent, 'at'>): Promise<SkillSuggestion> {
return this.withSuggestion(id, (suggestion, ledger) => {
const event: AutoAdoptionEvent = { ...input, ...(input.detail === undefined ? {} : { detail: clip(input.detail, 500) }), at: this.clock().toISOString() }
suggestion.autoAdoption = [...(suggestion.autoAdoption ?? []), event].slice(-16)
const review = ledger.reviews.find(entry => entry.id === suggestion.reviewId)
if (review !== undefined) review.autoAdoptions = [...(review.autoAdoptions ?? []), { ...event, suggestionId: id, skillName: suggestion.skillName }].slice(-160)
return suggestion
})
}
private automaticIdentity(workspace: string | undefined, suggestion: SkillSuggestion): string {
const target = suggestion.action === 'update'
? this.requireOriginal(this.suggestionOriginal(this.store.ledger(), suggestion)).path
: join(rootPath(this.catalog(workspace), suggestion.targetRoot ?? this.defaultRoot(workspace)), suggestion.skillName, 'SKILL.md')
return sha256(resolve(target))
}
private budgetEntries(ledger: LedgerFile): BudgetEntry[] {
const stored = this.store.autoAdoptionBudget()
if (stored !== undefined) return retainedBudget(stored, this.clock())
const entries = new Map<string, BudgetEntry>()
for (const suggestion of ledger.suggestions) {
const at = suggestion.autoAdoption?.find(event => event.stage === 'queued' || event.stage === 'drafting' || event.stage === 'adopted')?.at
if (at !== undefined) {
let identity = 'legacy:' + sha256(suggestion.skillName)
try { identity = this.automaticIdentity(legacySuggestionWorkspace(ledger, suggestion), suggestion) } catch { }
entries.set(suggestion.id, { id: randomUUID(), suggestionId: suggestion.id, identity, at })
}
}
for (const review of ledger.reviews) for (const event of review.autoAdoptions ?? []) {
if (!entries.has(event.suggestionId) && ['queued', 'drafting', 'adopted'].includes(event.stage)) entries.set(event.suggestionId, { id: randomUUID(), suggestionId: event.suggestionId, identity: 'legacy:' + sha256(event.skillName), at: event.at })
}
return retainedBudget([...entries.values()], this.clock())
}
private reserveBudget(ledger: LedgerFile, suggestion: SkillSuggestion, identity: string, limit: number, timeZone: string): AutoAdoptionReservation {
const entries = this.budgetEntries(ledger)
const value = quota(entries, this.clock(), limit, timeZone)
if (entries.some(entry => inQuotaDay(entry, value) && (entry.suggestionId === suggestion.id || entry.identity === identity || entry.identity === 'legacy:' + sha256(suggestion.skillName)))) {
this.store.saveAutoAdoptionBudget(entries)
return { ...value, allowed: false, reason: 'duplicate-skill' }
}
if (value.used >= value.limit) {
this.store.saveAutoAdoptionBudget(entries)
return { ...value, allowed: false, reason: 'daily-limit' }
}
const entry: BudgetEntry = { id: randomUUID(), suggestionId: suggestion.id, identity, at: this.clock().toISOString() }
this.store.saveAutoAdoptionBudget([...entries, entry])
return { ...value, used: value.used + 1, allowed: true, reservationId: entry.id }
}
reserveAutomatic(workspace: string | undefined, id: string, limit: number, timeZone: string): Promise<AutoAdoptionReservation> {
return this.write(() => {
const ledger = this.store.ledger()
expireSuggestions(ledger, this.clock())
const suggestion = ledger.suggestions.find(candidate => candidate.id === id)
if (suggestion?.status !== 'pending' || suggestion.draftId !== undefined) throw new Error('Suggestion changed; automatic adoption requires manual review')
return this.reserveBudget(ledger, suggestion, this.automaticIdentity(workspace, suggestion), limit, timeZone)
})
}
pinTrajectory(id: string, pinned: boolean): Promise<TrajectorySummary> {
return this.write(() => {
const ledger = this.store.ledger()
const entry = ledger.trajectories.find(candidate => candidate.id === id)
if (entry === undefined) throw new Error('trajectory not found: ' + id)
entry.pinned = pinned
const trajectory = this.store.trajectory(id, ledger)
this.store.saveTrajectory({ ...trajectory, pinned })
this.store.saveLedger(ledger)
return entry
})
}
deleteTrajectory(id: string): Promise<{ deleted: string }> {
return this.write(() => {
const ledger = this.store.ledger()
const citing = ledger.suggestions.filter(suggestion => OPEN_STATUSES.has(suggestion.status) && suggestion.evidence.some(reference => reference.trajectoryId === id))
if (citing.length > 0) throw new Error('an open suggestion cites this trajectory; dismiss or finish it first')
ledger.trajectories = ledger.trajectories.filter(candidate => candidate.id !== id)
this.store.deleteTrajectory(id)
this.store.saveLedger(ledger)
return { deleted: id }
})
}
private normalizeCase(input: CaseInput, existing: EvalCase | undefined, origin: EvalCase['origin']): EvalCase {
if (input.requiresVision !== undefined && typeof input.requiresVision !== 'boolean') throw new Error('requiresVision must be a boolean')
if (!isSkillName(input.skillName)) throw new Error('a case belongs to a skill with a valid name')
const title = clip(input.title, 120)
const prompt = clip(input.prompt, 4_000)
if (title === '' || prompt === '') throw new Error('a case needs a title and a task')
const checks = input.checks.map(check => ({ id: check.id?.trim() || randomUUID(), text: clip(check.text, 300), must: check.must === true })).filter(check => check.text !== '').slice(0, 8)
if (checks.length === 0) throw new Error('a case needs at least one check')
if (!checks.some(check => check.must)) checks[0]!.must = true
const now = this.clock().toISOString()
return {
id: existing?.id ?? randomUUID(), skillName: input.skillName, title, prompt,
...(input.context === undefined || input.context.trim() === '' ? {} : { context: clip(input.context, 4_000) }),
...((input.requiresVision ?? existing?.requiresVision) === true ? { requiresVision: true } : {}),
checks, origin: existing?.origin ?? origin, enabled: input.enabled ?? existing?.enabled ?? true,
createdAt: existing?.createdAt ?? now, updatedAt: now,
}
}
saveCase(input: CaseInput): Promise<EvalCase> {
return this.write(() => {
const evals = this.store.evals()
const existing = input.id === undefined ? undefined : evals.cases.find(candidate => candidate.id === input.id)
if (input.id !== undefined && existing === undefined) throw new Error('case not found: ' + input.id)
if (existing === undefined && evals.cases.filter(entry => entry.skillName === input.skillName).length >= MAX_CASES_PER_SKILL) throw new Error(`a skill keeps at most ${MAX_CASES_PER_SKILL} cases`)
const entry = this.normalizeCase(input, existing, { kind: 'manual' })
evals.cases = existing === undefined ? [entry, ...evals.cases] : evals.cases.map(candidate => candidate.id === entry.id ? entry : candidate)
this.store.saveEvals(evals)
return entry
})
}
deleteCase(id: string): Promise<{ deleted: string }> {
return this.write(() => {
const evals = this.store.evals()
if (!evals.cases.some(entry => entry.id === id)) throw new Error('case not found: ' + id)
evals.cases = evals.cases.filter(entry => entry.id !== id)
this.store.saveEvals(evals)
return { deleted: id }
})
}
addCases(input: { skillName: string; trajectoryId?: string; steps?: number[]; cases: CaseInput[] }): Promise<{ added: EvalCase[]; skipped: number }> {
return this.write(() => {
const evals = this.store.evals()
const added: EvalCase[] = []
let skipped = 0
for (const raw of input.cases) {
const entry = this.normalizeCase({ ...raw, skillName: input.skillName }, undefined, {
kind: 'trajectory', ...(input.trajectoryId === undefined ? {} : { trajectoryId: input.trajectoryId }), ...(input.steps === undefined ? {} : { steps: input.steps }),
})
if (similarCase(evals.cases, entry.skillName, entry.title, entry.prompt) !== undefined || evals.cases.filter(candidate => candidate.skillName === entry.skillName).length >= MAX_CASES_PER_SKILL) { skipped++; continue }
evals.cases.unshift(entry)
added.push(entry)
}
this.store.saveEvals(evals)
if (input.trajectoryId !== undefined && added.length > 0) {
const ledger = this.store.ledger()
const summary = ledger.trajectories.find(candidate => candidate.id === input.trajectoryId)
if (summary !== undefined) {
summary.caseIds = [...summary.caseIds, ...added.map(entry => entry.id)]
try {
const trajectory = this.store.trajectory(input.trajectoryId, ledger)
this.store.saveTrajectory({ ...trajectory, caseIds: summary.caseIds })
} catch { }
}
this.store.saveLedger(ledger)
}
return { added, skipped }
})
}
recordDraft(workspace: string | undefined, input: { suggestionId?: string; draftId?: string; skillName: string; content: string; notes: string; changes: string[]; guidance: string[]; files?: SkillDraftFileChange[]; targetRoot?: SkillRootKind; expectedBaseHash?: string | null; expectedDraft?: DraftExpectation; signal?: AbortSignal }): Promise<SkillDraft> {
return this.write(() => {
input.signal?.throwIfAborted()
validateSkillContent(input.content, input.skillName)
const ledger = this.store.ledger()
const catalog = this.catalog(workspace)
const now = this.clock().toISOString()
const prior = input.draftId === undefined ? undefined : ledger.drafts.find(candidate => candidate.id === input.draftId)
if (input.draftId !== undefined && prior === undefined) throw new Error('draft not found: ' + input.draftId)
if (prior !== undefined && (prior.skillName !== input.skillName || prior.suggestionId !== input.suggestionId)) throw new Error('draft is for another skill or suggestion')
const suggestion = input.suggestionId === undefined ? undefined : ledger.suggestions.find(candidate => candidate.id === input.suggestionId)
if (input.suggestionId !== undefined && suggestion === undefined) throw new Error('suggestion not found: ' + input.suggestionId)
if (suggestion !== undefined && suggestion.skillName !== input.skillName) throw new Error('suggestion is for another skill')
this.requireExpectedDraft(ledger, suggestion, input.expectedDraft)
const original = prior?.action === 'update' ? this.draftOriginal(ledger, prior) : suggestion?.action === 'update' ? this.suggestionOriginal(ledger, suggestion) : undefined
const loaded = original === undefined ? activeSkill(catalog, input.skillName) : this.requireOriginal(original)
if (loaded !== undefined) requireWritableSkill(loaded, this.roots.allowLinkedUpdates)
if (input.expectedBaseHash !== undefined && (loaded?.hash ?? null) !== input.expectedBaseHash) throw new Error('The skill changed while this draft was being generated; regenerate it from the current file')
const origin = loaded === undefined ? undefined : original?.origin ?? skillOrigin(catalog, loaded)
const baseDoc = loaded === undefined ? undefined : readSkillDocument(loaded)
const preparedFiles = prepareDraftFileChanges({
action: loaded === undefined ? 'create' : 'update',
isFlatSkill: loaded?.layout === 'flat',
skillContent: input.content,
...(baseDoc === undefined ? {} : { baseContent: baseDoc.content }),
existingResources: baseDoc?.resourceFiles ?? [],
...(input.files === undefined ? {} : { files: input.files }),
})
for (const draft of ledger.drafts) {
if (draft.status === 'ready' && draft.skillName === input.skillName && draft.suggestionId === input.suggestionId
&& (loaded === undefined ? draft.action === 'create' : this.draftOriginal(ledger, draft).skill?.path === loaded.path)) { draft.status = 'discarded'; draft.updatedAt = now }
}
const draft: SkillDraft = {
id: randomUUID(),
...(input.suggestionId === undefined ? {} : { suggestionId: input.suggestionId }),
skillName: input.skillName,
action: loaded === undefined ? 'create' : 'update',
...(loaded === undefined ? { targetRoot: input.targetRoot ?? prior?.targetRoot ?? suggestion?.targetRoot ?? this.defaultRoot(workspace) } : { baseKey: loaded.key, baseHash: loaded.hash, origin: origin! }),
content: input.content,
...(preparedFiles.files === undefined ? {} : { files: preparedFiles.files }),
...(preparedFiles.baseFileHashes === undefined ? {} : { baseFileHashes: preparedFiles.baseFileHashes }),
notes: clip(input.notes, 2_000),
changes: input.changes.map(change => clip(change, 300)).filter(Boolean).slice(0, 12),
guidance: input.guidance.map(text => clip(text, 2_000)).filter(Boolean).slice(-8),
status: 'ready',
runIds: [],
createdAt: now,
updatedAt: now,
}
ledger.drafts.unshift(draft)
if (suggestion !== undefined) { suggestion.status = 'review'; suggestion.draftId = draft.id; suggestion.updatedAt = now; delete suggestion.lastError }
this.store.saveLedger(ledger)
return draft
})
}
updateDraft(input: { id: string; content: string }): Promise<SkillDraft> {
return this.write(() => {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === input.id)
if (draft === undefined || draft.status !== 'ready') throw new Error('only a draft waiting for review can be edited')
validateSkillContent(input.content, draft.skillName)
if (draft.files !== undefined || extractConcreteBundleReferences(input.content).length > 0) {
const original = draft.action === 'update' ? this.draftOriginal(ledger, draft).skill : undefined
const baseDoc = original === undefined ? undefined : readSkillDocument(original)
prepareDraftFileChanges({
action: draft.action,
isFlatSkill: original?.layout === 'flat',
skillContent: input.content,
...(baseDoc === undefined ? {} : { baseContent: baseDoc.content }),
existingResources: baseDoc?.resourceFiles ?? [],
...(draft.files === undefined ? {} : { files: draft.files }),
})
}
draft.content = input.content
draft.updatedAt = this.clock().toISOString()
this.store.saveLedger(ledger)
return draft
})
}
adoptDraft(workspace: string | undefined, id: string, input: { root?: SkillRootKind; automatic?: AutomaticAdoption; signal?: AbortSignal } = {}): Promise<{ skill: SkillSummary; version: SkillVersion }> {
return this.write(() => {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === id)
if (draft === undefined || draft.status !== 'ready') throw new Error('only a draft waiting for review can be adopted')
let automaticResult: ReturnType<typeof compareAutomaticSkillRuns> | undefined
if (input.automatic !== undefined) {
const proof = input.automatic
const suggestion = ledger.suggestions.find(entry => entry.id === draft.suggestionId)
const evals = this.store.evals()
const cases = evals.cases.filter(entry => entry.skillName === draft.skillName && entry.enabled)
const casesHash = sha256(skillCaseSignature(cases))
const before = evals.runs.find(run => run.id === proof.baselineRunId)
const after = evals.runs.find(run => run.id === proof.draftRunId)
automaticResult = compareAutomaticSkillRuns(cases, before, after, casesHash)
if (suggestion?.status !== 'review' || suggestion.draftId !== draft.id || Date.parse(suggestion.expiresAt) <= this.clock().getTime()
|| proof.draftHash !== sha256(skillDraftSignature(draft)) || casesHash !== proof.casesHash
|| before?.skillName !== draft.skillName || after?.skillName !== draft.skillName
|| !(Date.parse(before.startedAt) >= Date.parse(draft.createdAt)) || !(Date.parse(after.startedAt) >= Date.parse(draft.createdAt))
|| after.target.kind !== 'draft' || after.target.draftId !== draft.id || after.target.hash !== proof.draftHash
|| (draft.action === 'update' ? before.target.kind !== 'current' || before.target.hash !== draft.baseHash : before.target.kind !== 'none')
|| automaticResult.outcome !== 'not-worse') {
throw new Error('The draft, cases, or complete matching backtest results changed; automatic adoption requires manual review')
}
}
if (input.automatic !== undefined) {
const suggestion = ledger.suggestions.find(entry => entry.id === draft.suggestionId)!
const identity = this.automaticIdentity(workspace, { ...suggestion, targetRoot: input.root ?? draft.targetRoot ?? this.defaultRoot(workspace) })
if (input.automatic.reservationId !== undefined) {
const entry = this.budgetEntries(ledger).find(candidate => candidate.id === input.automatic!.reservationId)
if (entry?.suggestionId !== suggestion.id || entry.identity !== identity) throw new Error('Automatic adoption reservation changed; manual review required')
} else {
const entries = this.budgetEntries(ledger)
const value = quota(entries, this.clock(), 2, 'local')
const migrated = entries.find(entry => entry.suggestionId === suggestion.id && inQuotaDay(entry, value))
const reserved = migrated !== undefined && value.used <= value.limit
? { allowed: true }
: this.reserveBudget(ledger, suggestion, identity, 2, 'local')
if (migrated !== undefined && reserved.allowed) this.store.saveAutoAdoptionBudget(entries)
if (!reserved.allowed) throw new Error('Automatic adoption daily budget requires manual review')
}
}
input.signal?.throwIfAborted()
validateSkillContent(draft.content, draft.skillName)
const catalog = this.catalog(workspace)
let key: string
let previous: string | undefined
let updated: SkillSummary | undefined
let versionBundles: { previous?: SkillBundleSnapshot; current?: SkillBundleSnapshot } | undefined
const hasFileChanges = (draft.files?.length ?? 0) > 0
if (draft.action === 'update') {
const original = this.draftOriginal(ledger, draft)
const base = this.requireOriginal(original)
const path = requireWritableSkill(base, this.roots.allowLinkedUpdates)
previous = this.requireHash({ ...base, path }, draft.baseHash)
if (draft.baseFileHashes !== undefined) {
if (base.layout !== 'bundle') throw new Error(`${base.name} supporting files changed since this draft was created; generate a new draft`)
for (const [relPath, expectedHash] of Object.entries(draft.baseFileHashes)) {
const state = readBundleResourceState(dirname(path), relPath)
if (state.hash !== expectedHash) throw new Error(`${base.name} (${relPath}) changed since it was read; generate a new draft`)
}
}
if (hasFileChanges && base.layout !== 'bundle') {
throw new Error(`${base.name} is a single .md file and cannot adopt supporting files`)
}
const previousResources = hasFileChanges ? snapshotBundleFiles(dirname(path)) : undefined
const currentResources = previousResources === undefined ? undefined : changedBundleSnapshot(previousResources, draft.files!)
let bundleApplied: { rollback(): void } | undefined
if (hasFileChanges) bundleApplied = applyBundleFileChanges(dirname(path), draft.files!)
try {
this.writeSkillFile(path, draft.content)
} catch (error) {
bundleApplied?.rollback()
this.invalidateCatalog()
throw error
}
if (hasFileChanges) {
this.invalidateCatalog()
versionBundles = {
...(previousResources === undefined ? {} : { previous: previousResources }),
current: currentResources!,
}
}
key = base.key
updated = findSkill(this.catalog(original.origin?.workspace), key)
} else {
const root = input.root ?? draft.targetRoot ?? this.defaultRoot(workspace)
if (activeSkill(catalog, draft.skillName) !== undefined) throw new Error(`${draft.skillName} exists now; draft it again as an update`)
const target = rootPath(catalog, root)
requireWritableRoot(target)
if (root.startsWith('project-')) {
try {
if (catalog.projectRoot === undefined || !statSync(catalog.projectRoot).isDirectory()) throw new Error('not a directory')
} catch { throw new Error('The selected workspace project is unavailable; select an existing workspace or explicitly choose a user skill root.') }
}
const directory = join(target, draft.skillName)
if (existsSync(directory) || existsSync(directory + '.md')) throw new Error(`${draft.skillName} already exists in this root`)
const skillPath = join(directory, 'SKILL.md')
this.writeSkillFile(skillPath, draft.content)
if (hasFileChanges) {
try {
applyBundleFileChanges(directory, draft.files!)
} catch (error) {
rmSync(directory, { recursive: true, force: true })
this.invalidateCatalog()
throw error
}
this.invalidateCatalog()
versionBundles = { current: changedBundleSnapshot({ version: 1, complete: true, files: {} }, draft.files!) }
}
key = `${root}:${draft.skillName}`
}
const now = this.clock().toISOString()
const version = this.recordVersion(ledger, key, draft.content, 'evolution', previous, { draftId: draft.id, ...(draft.suggestionId === undefined ? {} : { suggestionId: draft.suggestionId }) }, versionBundles)
draft.status = 'adopted'
draft.updatedAt = now
const suggestion = draft.suggestionId === undefined ? undefined : ledger.suggestions.find(candidate => candidate.id === draft.suggestionId)
if (suggestion !== undefined) {
suggestion.status = 'adopted'; suggestion.updatedAt = now
if (input.automatic !== undefined && automaticResult !== undefined) {
const event: AutoAdoptionEvent = { at: now, stage: 'adopted', attempt: input.automatic.attempt,
...(automaticResult.baselineScore === undefined ? {} : { baselineScore: automaticResult.baselineScore }),
...(automaticResult.draftScore === undefined ? {} : { draftScore: automaticResult.draftScore }),
}
suggestion.autoAdoption = [...(suggestion.autoAdoption ?? []), event].slice(-16)
const review = ledger.reviews.find(entry => entry.id === suggestion.reviewId)
if (review !== undefined) review.autoAdoptions = [...(review.autoAdoptions ?? []), { ...event, suggestionId: suggestion.id, skillName: suggestion.skillName }].slice(-160)
}
}
this.store.saveLedger(ledger)
return { skill: updated ?? findSkill(this.catalog(workspace), key), version }
})
}
discardDraft(id: string): Promise<SkillDraft> {
return this.write(() => {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === id)
if (draft === undefined || draft.status !== 'ready') throw new Error('only a draft waiting for review can be discarded')
const now = this.clock().toISOString()
draft.status = 'discarded'
draft.updatedAt = now
const suggestion = draft.suggestionId === undefined ? undefined : ledger.suggestions.find(candidate => candidate.id === draft.suggestionId)
if (suggestion !== undefined && suggestion.status === 'review') { suggestion.status = 'pending'; delete suggestion.draftId; suggestion.updatedAt = now }
this.store.saveLedger(ledger)
return draft
})
}
deleteDraft(id: string): Promise<{ deleted: string }> {
return this.write(() => {
const ledger = this.store.ledger()
const index = ledger.drafts.findIndex(candidate => candidate.id === id)
if (index < 0) throw new Error('draft not found: ' + id)
const draft = ledger.drafts[index]!
ledger.drafts.splice(index, 1)
if (draft.suggestionId !== undefined) {
const suggestion = ledger.suggestions.find(candidate => candidate.id === draft.suggestionId)
if (suggestion?.draftId === draft.id) {
delete suggestion.draftId
if (suggestion.status === 'review') suggestion.status = 'pending'
suggestion.updatedAt = this.clock().toISOString()
}
}
this.store.saveLedger(ledger)
return { deleted: id }
})
}
reclaimOrphanDrafts(): Promise<{ reclaimed: number }> {
return this.write(() => {
const ledger = this.store.ledger()
const before = ledger.suggestions.filter(suggestion => suggestion.status === 'drafting').length
if (!expireSuggestions(ledger, this.clock())) return { reclaimed: 0 }
this.store.saveLedger(ledger)
const after = ledger.suggestions.filter(suggestion => suggestion.status === 'drafting').length
return { reclaimed: Math.max(0, before - after) }
})
}
reclaimStaleRuns(): Promise<{ reclaimed: number }> {
return this.write(() => {
const evals = this.store.evals()
const now = this.clock()
let reclaimed = 0
for (const run of evals.runs) {
if (run.status !== 'running' || Number.isFinite(Date.parse(run.startedAt)) && now.getTime() - Date.parse(run.startedAt) <= RUN_STALE_MS) continue
run.status = 'interrupted'
run.finishedAt = now.toISOString()
run.error = 'Backtest exceeded its 45 minute deadline; run it again.'
reclaimed++
}
if (reclaimed > 0) this.store.saveEvals(evals)
return { reclaimed }
})
}
targetContent(workspace: string | undefined, skillName: string, target: RunTarget): { content?: string; resources?: Array<{ path: string; content: string }>; target: RunTarget } {
return this.withCatalog(() => {
if (target.kind === 'none') return { target: { kind: 'none' } }
if (target.kind === 'draft') {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === target.draftId)
if (draft === undefined || draft.skillName !== skillName) throw new Error('draft not found for this skill')
const resourcesMap: Record<string, string> = {}
if (draft.action === 'update') {
const base = this.draftOriginal(ledger, draft).skill
if (base !== undefined) Object.assign(resourcesMap, bundleTextMap(readSkillDocument(base).resourceFiles ?? []))
}
for (const change of draft.files ?? []) {
if (change.action === 'delete') delete resourcesMap[change.path]
else if (change.content !== undefined) resourcesMap[change.path] = change.content
}
const resources = toResourceList(resourcesMap)
return {
content: draft.content,
...(resources.length === 0 ? {} : { resources }),
target: { kind: 'draft', draftId: draft.id, hash: sha256(skillDraftSignature(draft)) },
}
}
if (target.kind === 'version') {
const version = this.store.ledger().versions.find(candidate => candidate.id === target.versionId)
if (version === undefined) throw new Error('version not found: ' + target.versionId)
const versionResources = this.store.versionResources(version)
const resources = versionResources === undefined ? [] : snapshotResourcePreview(versionResources)
return {
content: this.store.versionContent(version),
...(resources.length === 0 ? {} : { resources }),
target: { kind: 'version', versionId: version.id, skillKey: version.skillKey, hash: version.hash },
}
}
const ledger = target.draftId === undefined ? undefined : this.store.ledger()
const draft = target.draftId === undefined ? undefined : ledger!.drafts.find(candidate => candidate.id === target.draftId && candidate.skillName === skillName)
if (target.draftId !== undefined && draft === undefined) throw new Error('draft not found for this skill')
const loaded = draft === undefined ? activeSkill(this.catalog(workspace), skillName) : this.requireOriginal(this.draftOriginal(ledger!, draft))
if (loaded === undefined) throw new Error(`${skillName} has no file to test; test a draft or no skill`)
const document = readSkillDocument(loaded)
const resources = toResourceList(bundleTextMap(document.resourceFiles ?? []))
return {
content: document.content,
...(resources.length === 0 ? {} : { resources }),
target: { kind: 'current', skillKey: loaded.key, hash: document.hash, ...(draft === undefined ? {} : { draftId: draft.id }) },
}
})
}
startRun(input: { skillName: string; target: RunTarget; caseIds: string[]; expectedCasesHash?: string; model?: BacktestRun['model']; signal?: AbortSignal }): Promise<BacktestRun> {
return this.write(() => {
input.signal?.throwIfAborted()
const evals = this.store.evals()
const cases = input.caseIds.map(id => evals.cases.find(entry => entry.id === id && entry.skillName === input.skillName))
if (cases.length === 0 || cases.some(entry => entry === undefined)) throw new Error('a run needs at least one case of this skill')
const casesHash = sha256(skillCaseSignature(cases as EvalCase[]))
if (input.expectedCasesHash !== undefined && input.expectedCasesHash !== casesHash) throw new Error('Eval cases changed before this backtest started')
const run: BacktestRun = {
id: randomUUID(), skillName: input.skillName, target: input.target, status: 'running',
progress: { done: 0, total: cases.length }, caseIds: input.caseIds, casesHash, ...(input.model === undefined ? {} : { model: input.model }), results: [], startedAt: this.clock().toISOString(),
}
evals.runs.unshift(run)
this.store.saveEvals(evals)
if (input.target.draftId !== undefined) {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === input.target.draftId)
if (draft !== undefined) draft.runIds = [...draft.runIds, run.id].slice(-12)
this.store.saveLedger(ledger)
}
return run
})
}
linkRun(draftId: string, runId: string): Promise<void> {
return this.write(() => {
const ledger = this.store.ledger()
const draft = ledger.drafts.find(candidate => candidate.id === draftId)
if (draft === undefined) throw new Error('draft not found: ' + draftId)
if (!draft.runIds.includes(runId)) draft.runIds = [...draft.runIds, runId].slice(-12)
this.store.saveLedger(ledger)
})
}
progressRun(input: { id: string; result: CaseResult; signal?: AbortSignal }): Promise<BacktestRun> {
return this.write(() => {
input.signal?.throwIfAborted()
const evals = this.store.evals()
const run = evals.runs.find(candidate => candidate.id === input.id)
if (run === undefined || run.status !== 'running') throw new Error('run is not running: ' + input.id)
const result: CaseResult = {
...input.result,
steps: input.result.steps.map(step => clip(step, 400)).slice(0, 20),
answer: clip(input.result.answer, 2_000),
checks: input.result.checks.map(check => ({ ...check, note: clip(check.note, 300) })),
...(input.result.summary === undefined ? {} : { summary: clip(input.result.summary, 500) }),
...(input.result.error === undefined ? {} : { error: clip(input.result.error, 500) }),
}
run.results = [...run.results.filter(existing => existing.caseId !== result.caseId), result]
run.progress = { done: run.results.length, total: run.progress.total }
this.store.saveEvals(evals)
return run
})
}
finishRun(input: { id: string; status: 'completed' | 'failed' | 'interrupted'; error?: string; signal?: AbortSignal }): Promise<BacktestRun> {
return this.write(() => {
input.signal?.throwIfAborted()
const evals = this.store.evals()
const run = evals.runs.find(candidate => candidate.id === input.id)
if (run === undefined) throw new Error('run not found: ' + input.id)
if (run.status !== 'running') return run
run.status = input.status
run.finishedAt = this.clock().toISOString()
if (input.error !== undefined) run.error = clip(input.error, 500)
if (run.results.length > 0) {
const { passRate, score, errors } = runScore(run.results)
delete run.passRate
delete run.score
Object.assign(run, passRate === undefined ? {} : { passRate }, score === undefined ? {} : { score }, errors > 0 ? { errors } : {})
}
this.store.saveEvals(evals)
return run
})
}
recordReview(workspace: string | undefined, input: ReviewRecordInput): Promise<ReviewRecordResult> {
return this.write(() => {
const ledger = this.store.ledger()
const evals: EvalsFile = this.store.evals()
const { result, trajectory, removedTrajectories } = admitReview({
ledger, evals, policy: policyFrom(input.policy), catalog: this.catalog(workspace), now: this.clock(), id: randomUUID,
}, input)
this.store.saveTrajectory(trajectory)
for (const id of removedTrajectories) this.store.deleteTrajectory(id)
this.store.saveEvals(evals)
this.store.saveLedger(ledger)
return result
})
}
trajectorySummary(trajectory: Trajectory): TrajectorySummary {
return trajectorySummary(trajectory)
}
private registryRecords(): Array<RegistryRecord & { kind: MarketSourceKind }> {
const stored = this.store.registries()
const enabled = (id: string) => stored.find(record => record.id === id)?.enabled ?? true
return [
{ id: OFFICIAL_REGISTRY_ID, kind: 'catalog', location: OFFICIAL_REGISTRY_URL, builtin: true, enabled: enabled(OFFICIAL_REGISTRY_ID) },
{ id: SKILLS_SH_ID, kind: 'search', location: SKILLS_SH_URL, builtin: true, enabled: enabled(SKILLS_SH_ID) },
...stored.filter(record => record.id !== OFFICIAL_REGISTRY_ID && record.id !== SKILLS_SH_ID).map(record => ({ ...record, kind: record.kind ?? 'catalog', builtin: false })),
]
}
private registryFile(record: RegistryRecord): { registry?: MarketRegistryFile; fetchedAt?: string; error?: string } {
const cache = this.store.registryCache(record.id)
if (cache?.registry !== undefined) return cache
if (record.id === OFFICIAL_REGISTRY_ID) return { registry: bundledOfficialRegistry(), ...(cache?.error === undefined ? {} : { error: cache.error }) }
return cache ?? {}
}
private loadSource(kind: MarketSourceKind, location: string, signal?: AbortSignal): Promise<MarketRegistryFile> {
switch (kind) {
case 'catalog': return loadRegistry(location, this.fetcher, signal)
case 'well-known': return loadDiscovery(location, this.fetcher, signal)
case 'github': return loadRepository(location, this.fetcher, signal)
case 'search': return Promise.reject(new Error('a search source is searched, not listed'))
}
}
private installState(catalog: SkillCatalog, installs: readonly MarketInstall[], registry: string, name: string, version: string | undefined, sameOrigin?: (install: MarketInstall) => boolean): { state: MarketInstallState; skillKey?: string; installedVersion?: string } {
const skill = activeSkill(catalog, name)
if (skill === undefined) return { state: 'available' }
const install = installs.find(candidate => candidate.skillKey === skill.key)
const fromHere = install !== undefined && install.name === name && (install.registryId === registry || sameOrigin?.(install) === true)
const state: MarketInstallState = !fromHere ? 'conflict'
: skill.hash !== install!.hash ? 'modified'
: version !== undefined && install!.version !== undefined && version !== install!.version ? 'update'
: 'installed'
return { state, skillKey: skill.key, ...(fromHere && install!.version !== undefined ? { installedVersion: install!.version } : {}) }
}
marketView(workspace: string | undefined): MarketView {
const now = this.clock().getTime()
const catalog = this.catalog(workspace)
const installs = this.store.ledger().installs
const registries: MarketRegistry[] = []
const items: MarketItem[] = []
const categories = new Map<string, MarketView['categories'][number]>()
const stale: string[] = []
for (const record of this.registryRecords()) {
const file = record.kind === 'search' ? {} : this.registryFile(record)
registries.push({
id: record.id, kind: record.kind, location: record.location, builtin: record.builtin, enabled: record.enabled, entries: file.registry?.skills.length ?? 0,
...(file.registry?.name === undefined ? {} : { name: file.registry.name }),
...(file.registry?.description === undefined ? {} : { description: file.registry.description }),
...(file.registry?.homepage === undefined ? {} : { homepage: file.registry.homepage }),
...(file.fetchedAt === undefined ? {} : { fetchedAt: file.fetchedAt }),
...(file.error === undefined || record.builtin && file.fetchedAt === undefined ? {} : { error: file.error }),
})
if (!record.enabled || record.kind === 'search') continue
if (file.fetchedAt === undefined || now - Date.parse(file.fetchedAt) > REGISTRY_REFRESH_MS) stale.push(record.id)
for (const category of file.registry?.categories ?? []) if (!categories.has(category.id)) categories.set(category.id, category)
for (const entry of file.registry?.skills ?? []) items.push({ ...entry, registryId: record.id, ...this.installState(catalog, installs, record.id, entry.name, entry.version) })
}
return { registries, categories: [...categories.values()], items, stale }
}
async searchMarket(workspace: string | undefined, query: string, signal?: AbortSignal): Promise<MarketSearchResult> {
const text = query.trim().slice(0, 200)
const index = this.registryRecords().find(record => record.id === SKILLS_SH_ID)!
if (text.length < 2 || !index.enabled) return { query: text, items: [] }
let found: Awaited<ReturnType<typeof searchSkillsSh>>
try { found = await searchSkillsSh(text, this.fetcher, signal) } catch (error) {
if (signal?.aborted === true) throw error
return { query: text, items: [], error: error instanceof Error ? error.message : String(error) }
}
const catalog = this.catalog(workspace)
const installs = this.store.ledger().installs
return {
query: text,
items: found.map(skill => ({
name: skill.name, description: '', source: { type: 'indexed', id: skill.id }, origin: skill.origin, installs: skill.installs, author: skill.origin.split('/')[0]!,
registryId: SKILLS_SH_ID,
...this.installState(catalog, installs, SKILLS_SH_ID, skill.name, undefined, install => install.source.type === 'github' && install.source.repo === skill.origin),
})),
}
}
private entry(registry: string, name: string): { record: RegistryRecord; entry: MarketRegistryFile['skills'][number] } {
const record = this.registryRecords().find(candidate => candidate.id === registry)
if (record === undefined) throw new Error('unknown skill registry: ' + registry)
const entry = this.registryFile(record).registry?.skills.find(candidate => candidate.name === name)
if (entry === undefined) throw new Error(`${name} is not in registry ${registry}; refresh the market and try again`)
return { record, entry }
}
private indexedEntry(id: string, signal?: AbortSignal): Promise<MarketEntry> {
const parts = indexedParts(id)
if (parts === undefined) throw new Error('not a skill id of skills.sh: ' + id)
return resolveIndexed({ origin: parts.origin, skill: parts.skill, name: parts.skill }, this.fetcher, signal)
}
async marketPreview(registry: string, name: string, signal?: AbortSignal): Promise<MarketPreview> {
if (registry === SKILLS_SH_ID) {
const audits = skillsShAudits(name, this.fetcher, signal)
try {
const entry = await this.indexedEntry(name, signal)
const [content, files] = await Promise.all([fetchSkillDocument(entry, '', this.fetcher, signal), listSkillFiles(entry, '', this.fetcher, signal)])
return { registryId: registry, name, content, files: files.slice(0, 200), totalBytes: files.reduce((sum, file) => sum + file.bytes, 0), audits: await audits, ...(entry.homepage === undefined ? {} : { homepage: entry.homepage }) }
} catch (error) {
if (signal?.aborted === true) throw error
const snapshot = await skillsShSnapshot(name, this.fetcher, signal).catch(() => { throw error })
return {
registryId: registry, name, content: snapshot.find(file => file.path === 'SKILL.md')!.data.toString('utf8'),
files: snapshot.map(file => ({ path: file.path, bytes: file.data.byteLength })).slice(0, 200), totalBytes: snapshot.reduce((sum, file) => sum + file.data.byteLength, 0),
audits: await audits, partial: true, homepage: `${SKILLS_SH_URL}/${name}`,
}
}
}
const { record, entry } = this.entry(registry, name)
const [content, files] = await Promise.all([fetchSkillDocument(entry, record.location, this.fetcher, signal), listSkillFiles(entry, record.location, this.fetcher, signal)])
return { registryId: registry, name, content, files: files.slice(0, 200), totalBytes: files.reduce((sum, file) => sum + file.bytes, 0), ...(entry.homepage === undefined ? {} : { homepage: entry.homepage }) }
}
async refreshMarket(ids?: readonly string[], signal?: AbortSignal): Promise<MarketView['registries']> {
const records = this.registryRecords().filter(record => record.enabled && record.kind !== 'search' && (ids === undefined || ids.includes(record.id)))
const results = await Promise.all(records.map(async record => {
try { return { record, registry: await this.loadSource(record.kind, record.location, signal) } } catch (error) { return { record, error: error instanceof Error ? error.message : String(error) } }
}))
await this.write(() => {
const at = this.clock().toISOString()
for (const result of results) {
const previous = this.store.registryCache(result.record.id)
this.store.saveRegistryCache(result.record.id, result.registry !== undefined
? { fetchedAt: at, registry: result.registry }
: { ...(previous?.registry === undefined ? {} : { registry: previous.registry }), ...(previous?.fetchedAt === undefined ? {} : { fetchedAt: previous.fetchedAt }), error: result.error! })
}
})
return this.marketView(undefined).registries
}
async addRegistry(input: string, signal?: AbortSignal): Promise<MarketRegistry> {
const detected = detectSource(input)
if (detected === undefined) throw new Error('add a GitHub repository (owner/repo), a website, or a JSON file by URL or absolute path')
const taken = () => this.registryRecords().some(record => record.location === detected.location)
if (taken()) throw new Error('this source is already added')
let kind: MarketSourceKind
let location = detected.location
let registry: MarketRegistryFile
if (detected.kind === 'json' || detected.kind === 'catalog') {
const value = await loadJson(location, this.fetcher, signal)
if (isPluginMarketplace(value)) {
const repository = /^https?:\/\//u.test(location) ? marketplaceRepository(location) : undefined
if (repository === undefined) throw new Error('a plugin marketplace is read from its GitHub repository; add the repository instead')
kind = 'github'
location = repository
if (this.registryRecords().some(record => record.location === location)) throw new Error('this source is already added')
registry = await loadRepository(location, this.fetcher, signal)
} else if (isDiscoveryIndex(value)) {
if (!/^https?:\/\//u.test(location)) throw new Error('an Agent Skills index is read from the site that publishes it')
kind = 'well-known'
registry = parseDiscovery(value, location)
} else {
kind = 'catalog'
registry = parseRegistry(value).registry
}
} else {
kind = detected.kind
registry = await this.loadSource(kind, location, signal)
}
if (kind !== 'catalog' && registry.skills.length === 0) throw new Error('this source publishes no skill DSH can load')
const id = await this.write(() => {
const stored = this.store.registries()
const added = stored.filter(record => record.id !== OFFICIAL_REGISTRY_ID && record.id !== SKILLS_SH_ID)
if (added.some(record => record.location === location)) throw new Error('this source is already added')
const slug = (text: string) => text.toLowerCase().replace(/[^a-z0-9]+/gu, '-').replace(/^-+|-+$/gu, '').slice(0, 56)
const declared = kind === 'catalog' ? registry.id : kind === 'github' ? slug(parseGithub(location)!.repo) : slug(new URL(location).host)
const id = registryId(location, declared === '' ? undefined : declared, new Set(added.map(record => record.id)))
this.store.saveRegistries([...stored.filter(record => record.id === OFFICIAL_REGISTRY_ID || record.id === SKILLS_SH_ID), ...added, { id, kind, location, enabled: true, builtin: false }])
this.store.saveRegistryCache(id, { fetchedAt: this.clock().toISOString(), registry })
return id
})
return this.marketView(undefined).registries.find(record => record.id === id)!
}
removeRegistry(id: string): Promise<{ removed: string }> {
return this.write(() => {
if (id === OFFICIAL_REGISTRY_ID || id === SKILLS_SH_ID) throw new Error('a built-in source can be switched off, not removed')
const records = this.store.registries()
if (!records.some(record => record.id === id)) throw new Error('unknown skill registry: ' + id)
this.store.saveRegistries(records.filter(record => record.id !== id))
this.store.deleteRegistryCache(id)
return { removed: id }
})
}
toggleRegistry(id: string, enabled: boolean): Promise<MarketRegistry> {
return this.write(() => {
const records = this.registryRecords()
const record = records.find(candidate => candidate.id === id)
if (record === undefined) throw new Error('unknown skill registry: ' + id)
this.store.saveRegistries(records.map(candidate => candidate.id === id ? { ...candidate, enabled } : candidate))
return this.marketView(undefined).registries.find(candidate => candidate.id === id)!
})
}
async installMarket(workspace: string | undefined, input: { registryId: string; name: string; root?: SkillRootKind; overwrite?: boolean }, signal?: AbortSignal): Promise<{ skill: SkillSummary; updated: boolean }> {
const indexed = input.registryId === SKILLS_SH_ID
const { record, entry } = indexed
? { record: this.registryRecords().find(candidate => candidate.id === SKILLS_SH_ID)!, entry: await this.indexedEntry(input.name, signal) }
: this.entry(input.registryId, input.name)
const files = await fetchSkillFiles(entry, record.location, this.fetcher, signal)
const document = files.find(file => file.path === 'SKILL.md')!.data.toString('utf8')
const name = indexed ? skillMeta(document)?.name ?? entry.name : entry.name
validateSkillContent(document, name)
return this.write(() => {
const catalog = this.catalog(workspace)
const ledger = this.store.ledger()
const existing = activeSkill(catalog, name)
const install = existing === undefined ? undefined : ledger.installs.find(candidate => candidate.skillKey === existing.key)
if (existing !== undefined && (install === undefined || install.registryId !== record.id || install.name !== name)) {
throw new Error(`a skill named ${name} already exists in ${existing.root}; it did not come from this market entry`)
}
if (existing !== undefined && existing.hash !== install!.hash && input.overwrite !== true) {
throw new Error(`${name} was edited after it was installed; confirm to replace your changes`)
}
const root = existing?.root ?? input.root ?? this.defaultRoot(workspace)
const target = existing === undefined ? join(rootPath(catalog, root), name) : existing.layout === 'bundle' ? dirname(existing.path) : existing.path
if (existing === undefined && (existsSync(target) || existsSync(target + '.md'))) throw new Error(`${name} already exists in this root`)
const staged = stageFiles(this.store.stagingDirectory(), files)
const previous = existing === undefined ? undefined : readFileSync(existing.path, 'utf8')
let trashed: string | undefined
try {
if (existing !== undefined) trashed = this.store.trash(target, name, this.trashOrigin(existing, catalog))
const finalTarget = existing?.layout === 'flat' ? join(dirname(target), name) : target
moveInto(staged, finalTarget)
} catch (error) {
rmSync(staged, { recursive: true, force: true })
if (trashed !== undefined && !existsSync(target)) try { renameSync(trashed, target) } catch { }
this.invalidateCatalog()
throw error
}
this.invalidateCatalog()
const key = `${root}:${name}`
const now = this.clock().toISOString()
const hash = sha256(document)
ledger.installs = [
{ skillKey: key, registryId: record.id, name, ...(entry.version === undefined ? {} : { version: entry.version }), source: entry.source, hash, files: files.length, installedAt: now } satisfies MarketInstall,
...ledger.installs.filter(candidate => candidate.skillKey !== key),
]
this.recordVersion(ledger, key, document, 'install', previous, { note: `${record.id}/${indexed ? input.name : name}` })
this.store.saveLedger(ledger)
return { skill: findSkill(this.catalog(workspace), key), updated: existing !== undefined }
})
}
installs(): MarketInstall[] {
return this.store.ledger().installs
}
}
function stageFiles(stagingRoot: string, files: readonly SkillFile[]): string {
const directory = join(stagingRoot, randomUUID())
for (const file of files) {
const path = join(directory, ...file.path.split('/'))
if (!path.startsWith(directory + sep)) throw new Error('a file of the skill escapes its folder: ' + file.path)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, file.data)
}
return directory
}
function moveInto(staged: string, target: string): void {
mkdirSync(dirname(target), { recursive: true })
try {
renameSync(staged, target)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error
cpSync(staged, target, { recursive: true, errorOnExist: true })
rmSync(staged, { recursive: true, force: true })
}
}