GitHub 0
Skip to content

JavaScript API

Reference for skillrc's three entries: skillrc/io, skillrc/definitions and skillrc/sync, with their main functions and types.

skillrc has three entries and no root export. Every function that reads or writes your program's files takes a Places first: { program, state, config }, from fleethosts/places. skillrc names files, locks, variables and messages after places.program.

import { standardPlaces } from "fleethosts/places";

const places = standardPlaces("mytool");
ts

Config files, fetching, locks, links and hashes. Places is re-exported here.

function editConfigFile(
  places: Places,
  file: string,
  plan: (root: Record<string, unknown> | undefined) => readonly KeyEdit[],
  options?: {
    format?: "json" | "jsonc";
    create?: boolean;
    mode?: number;
    dryRun?: boolean;
    lock?: boolean;
    staleMs?: number;
  },
): ConfigEditResult
ts

Edits a JSON or JSONC file one key at a time and keeps every other byte. plan gets the object read under the lock, or undefined for a missing file, and returns the edits. Follows a link to its target. The options and their defaults are in Config files.

interface KeyEdit {
  path: readonly string[];
  value?: unknown;
  item?: number;
  insert?: boolean;
}
ts

Sets value at path, or removes the key when value is undefined. With item, works on that index of the list at path. With insert, puts value before the item instead of replacing it.

interface ConfigEditResult {
  changed: boolean;
  skipped?: string;
  error?: string;
}
ts

skipped is worth retrying: the lock was busy or the file changed meanwhile. error is not: the file doesn't parse or the edit can't be placed. Neither throws.

function readConfigFile(file: string, format?: "json" | "jsonc"): { root?: Record<string, unknown>; error?: string }
ts

The file's object, { error } when it doesn't parse, or {} when it is missing. Objects have no prototype.

function valueAt(root: unknown, path: readonly string[]): unknown
ts

The value at a key path, or undefined at the first missing key.

function lockFile(file: string, staleMs?: number): (() => void) | undefined
ts

Takes <file>.lock the way proper-lockfile does, so Claude Code and skillrc never write one file at once. Returns the release, or undefined while another holder has it.

function readText(file: string): string | undefined
function replaceIfUnchanged(places: Places, target: string, snapshot: string | undefined, text: string, mode: number | undefined): boolean
ts

replaceIfUnchanged renames text over target only if target still holds snapshot, and returns false when it changed.

function setTomlTable(places: Places, text: string, table: string, name: string, value: unknown): { text: string } | { refused: string }
function readTomlTable(text: string, table: string, name: string): unknown
ts

setTomlTable sets [<table>.<name>] and its subtables, or removes them when value is undefined, and refuses anything that would touch another table. See TOML.

function editJsonText(text: string, before: unknown, after: unknown, notes?: string[]): string | undefined
ts

Edits JSON text that parses to before so it parses to after, changing only what differs. Returns undefined for text it can't follow, such as comments.

function fetchClone(
  places: Places,
  url: string,
  ref: string | undefined,
  root: string,
  options?: {
    offline?: boolean;
    readOnly?: boolean;
    cacheUrl?: string;
    signal?: AbortSignal;
    check?: (url: string, cwd: string) => Promise<string | undefined>;
  },
): Promise<CachedClone>
ts

The files of url at ref from a cache under root, fetched shallow when needed. offline fetches nothing. readOnly runs no git. check returns why a URL may not be fetched. cacheUrl names the cache entry when it differs from url. See The git cache.

{ dir, commit, collisions, refused, submodules, repo?, previous? }: the files of commit with no .git folder, the paths left out and why, the bare repository, and the commit before this fetch when it brought another.

FunctionWhat it returns
gitUrl(spec)The URL for owner/repo, gitlab:owner/repo or any URL, as git fetches it
repoKey(url)Host and path, lowercased, so https, ssh and shorthand forms compare equal
cloneKey(url, ref)The cache entry's name: 16 hex digits of a sha256
hasCachedClone(url, ref, root)Whether the cache has a checkout for them
isCommitRef(ref)Whether ref is 7 to 40 hex digits
withGitTree(repo, commit, read)Calls read with another commit's files in a temporary folder, then removes it
function fetchNpm(
  places: Places,
  spec: string,
  registry: string | undefined,
  cacheRoot: string,
  options?: { sendToken?: boolean; fetch?: typeof fetch; signal?: AbortSignal },
): Promise<{ dir: string; version: string; packageKey: string }>
ts

Downloads name, name@version or name@tag and unpacks it into the cache. Checks the tarball's integrity and the download limits. Sends NPM_TOKEN unless sendToken is false. Ranges are not resolved.

FunctionWhat it does
parseNpmSpec(spec)Splits a spec into { name, want }, with want defaulting to latest
createCappedFetch(places, refused, budget?)A fetch with the download limits. Failures go into refused.
guardedFetch(problem)A fetch that asks problem about every URL, redirects included, and requests none it objects to
tarFileSizes(places, tar)Each file of a tar and its size
zipEntries(places, zip)Each entry of a zip, its size, and whether it is a folder
function takeLock(places: Places, file: string, mine: string, options?: LockOptions): string | undefined
ts

Creates the lock file with the text mine, whole or not at all. Throws LockHeldError while a live holder has it. Returns a note when it broke a stale lock. See The sync lock.

ExportWhat it is
lockText(command?)The text a lock holds for this process
readLock(file){ text, holder }, or undefined when there is no lock
syncRunning(places)Whether a live sync holds <state>/sync.lock
LOCK_MAX_AGE_MSTwo hours: the age past which any lock is stale
LockHeldErrorA UserError naming the holder
FunctionWhat it does
hashDir(places, dir)The sha256 of every file under dir, by /-separated path
changedFiles(before, after)Paths whose hash differs
readJson(path)The parsed file, undefined when missing. Throws JsonFileError when it doesn't parse.
writeJson(path, value)Writes through a temporary file and a rename
hashValue(value), sameValue(a, b)Hash and compare values with object keys sorted
decideEntry(state)What a sync does with one config entry it merges: write, keep, update, prune, hold
FunctionWhat it does
expandPath(path, base?)Expands ~ and resolves against base
tildify(path)Writes the home folder as ~, for messages
xdgDir(name)XDG_CONFIG_HOME or XDG_STATE_HOME, when set to an absolute path
globFilter(glob)A test for /-separated paths. * stays in one segment, ** crosses them.
globBase(glob)The folder before the first wildcard
nameKey(name)A name folded for case and Unicode form, as macOS and Windows compare it
sourceIdProblem(id)Why id can't name a source, or undefined
class UserError extends Error {}
ts

A mistake the user can fix, such as a wrong name: print its message as one line, with no stack. LockHeldError is one.

MCP servers and hooks. See Definitions.

function parseMcpFile(places: Places, text: string, file?: string): {
  servers: Record<string, McpServer>;
  problems: McpProblem[];
}
ts

Reads an mcpServers file. A server with a mistake goes into problems as { server, message }, and the rest pass. Throws McpFileError for text that isn't JSON or has no mcpServers object.

function mcpEntries(agent: McpAgent, servers: Record<string, McpServer>): {
  entries: Record<string, McpEntry>;
  skipped: McpProblem[];
}
ts

Each server whose agents include agent, in that agent's shape. A server the agent can't take is skipped for it with the reason. McpAgent is one of MCP_AGENTS: claude-code, codex, cursor, gemini-cli, github-copilot, grok, opencode.

type Template = ReadonlyArray<string | { env: string }>;
type McpServer = StdioServer | RemoteServer;

interface StdioServer {
  transport: "stdio";
  command: Template;
  args: Template[];
  env: Record<string, Template>;
  cwd?: Template;
  agents?: McpAgent[];
}

interface RemoteServer {
  transport: "http" | "sse";
  url: Template;
  headers: Record<string, Template>;
  agents?: McpAgent[];
}
ts

Every string is a Template: text and ${VAR} references in order. parseTemplate(text, where?) builds one, templateText(template) writes it back, and wholeReference(template) returns the variable of a template that is one reference.

function parseHookFile(agent: HookDefAgent, text: string, file?: string): HookEvents
ts

Checks a hook file in agent's own format and returns its events. Throws HookFileError naming the first mistake. HookDefAgent is one of HOOK_DEF_AGENTS: claude-code, codex, grok, gemini-cli, cursor.

FunctionWhat it returns
claudePluginFiles(places, definitions)The files of the Claude Code plugin ~/.claude/skills/<program>/, by path. Empty when there are no definitions.
codexHooksWith(places, current, desired){ file, changed, slots, review }: Codex's hooks.json with your groups set, no other group moved
grokHookFiles(places, definitions)One file per definition, by name in ~/.grok/hooks/
hookMark(places)The key that marks a group or script as yours: x-hook-owner:<program>

definitions maps each definition's name to its HookEvents.

The sync engine. See Sync.

function sync(places: Places, host: SyncHost, options?: SyncOptions): Promise<Report>
ts

Runs one sync under the lock and returns the report. A real sync also writes it to <state>/last-run.json. Throws LockHeldError while another live sync runs.

{ dryRun?, offline?, only?, apply?, copy? }, described in Options. previewSkills and initBackups serve a program's own init command.

interface SyncHost {
  load(ctx: {
    offline: boolean;
    dryRun: boolean;
    signal: AbortSignal;
    cacheRoot?: string;
    only?: string;
    warnings: string[];
  }): Promise<{ plan: Plan; name: string }>;
  targets(agents: "all" | string[], signal: AbortSignal): Promise<AgentTarget[]>;
  formerTargets(targets: readonly AgentTarget[]): string[];
  replacementTargets?(targets: readonly AgentTarget[]): Map<string, Set<string>>;
  kinds: Readonly<Record<string, AgentKinds>>;
  notes?(plan: Plan, state: State): string[];
  hookEnv?(hook: Hook, changed: string): Record<string, string>;
  beforeReport?(plan: Plan, signal: AbortSignal): Promise<void>;
  command: string;
  version: string;
}
ts

What the engine asks of your program. See The host.

interface AgentKinds {
  home: () => string;
  instructions?: () => string;
  subagents?: () => string;
  commands?: () => string;
  mcp?: { file: () => string; format: "json" | "jsonc" | "toml"; key: readonly string[] };
  agentHooks?: AgentHooksCell;
}
ts

Where one agent reads each kind of file. AgentHooksCell has a style: plugin for Claude Code, file for Codex, entries for Gemini CLI and Cursor, files for Grok.

interface Plan {
  root: PlanRoot;
  sources: Source[];
  warnings: string[];
  failed?: string[];
}

interface PlanRoot {
  file: string;
  agents: "all" | string[];
  sources: Source[];
  forks: Record<string, Fork>;
  hooks: Hook[];
  hub?: string;
  report?: { run: string };
}

type Source = GitSource | NpmSource | IndexSource | CloneSource | LocalSource;
ts

Every source has id, update ("auto" or "review"), origin, and optional skills, include, exclude and files. By kind:

TypeFields
GitSourcegit, ref?
NpmSourcenpm, registry?, sendToken
IndexSourceindex
CloneSourcegit, ref?, path, adopt, followLinks
LocalSourcelocal, adopt

isVendored(source) is true for git, npm and index sources, which are copied into the store. Hook is { name, run, on }, with on a list of <source>:<glob> patterns.

{ version, host, program, manifest, startedAt, finishedAt, dryRun, offline, ok, sources, skills, files, entries, hooks, warnings, errors, previewLimitations? }. hooks is a list of HookRun: { name, matched, code, output }. See The report.

function withSyncLock<T>(places: Places, command: string, work: () => Promise<T>): Promise<T>
ts

Runs work holding the sync lock. Waits up to 10 seconds for a running sync, then throws a UserError. A sync called inside shares the lock.

function loadState(places: Places, options?: { warnings?: string[]; backupInvalid?: boolean }): State
function saveState(places: Places, state: State): void
ts

loadState reads <state>/state.json. A missing file, one that doesn't parse, or one another version wrote reads as empty. With backupInvalid, a bad file is copied to <state>/backup first, with a warning. saveState writes the whole state. sweepJsonTemps(dir) removes temporary files that a killed write left.

FunctionWhat it does
forkSkill(places, plan, name, { dryRun?, editForks })Moves a vendored git skill into the personal source and records where it came from
mergeSkill(places, plan, name, { dryRun?, editForks })Merges upstream changes into an edited copy or a fork, leaving git's conflict markers where they clash
adoptSkill(places, plan, path, { dryRun? })Moves a hand-made skill folder into the personal source
diffSkill(places, plan, name)Local edits against upstream, or a held update against what is installed, as a diff
diffPending(places, plan)Every update the sources hold
diffEntry(places, kinds, plan, id)An MCP entry in the agent's config against what the plan gives it

editForks returns a PlanEdit, { file, push, check, save }, that records the fork in your config. skillrc calls check before it moves a file, and save after.

FunctionWhat it does
teamGitProblem(spec, cwd?)Why a shared config may not name this repository: it is local, or git's config rewrites it to a local one
teamUrlProblem(url)Why a shared config may not fetch this URL: not http or https, or this machine
isRemoteGit(spec, rules?)Whether spec names a repository on another machine

getSupportedAgents(), detectAgents(options?) and listSkills(options?) are re-exported from the skills package, with the AgentInfo type: { id, name, projectSkillsDir, globalSkillsDir, universal }.