# JavaScript API

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`.

```ts
import { standardPlaces } from "fleethosts/places";

const places = standardPlaces("mytool");
```

## skillrc/io

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

### editConfigFile

```ts
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
```

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](https://skillrc.loadsheet.dev/guide/config-files#options).

### KeyEdit

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

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.

### ConfigEditResult

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

`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.

### readConfigFile

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

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

### valueAt

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

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

### lockFile

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

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.

### readText and replaceIfUnchanged

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

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

### setTomlTable and readTomlTable

```ts
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
```

`setTomlTable` sets `[<table>.<name>]` and its subtables, or removes them when `value` is `undefined`, and refuses anything that would touch another table. See [TOML](https://skillrc.loadsheet.dev/guide/config-files#toml).

### editJsonText

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

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.

### fetchClone

```ts
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>
```

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](https://skillrc.loadsheet.dev/guide/fetching#the-git-cache).

### CachedClone

`{ 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.

### Git helpers

| Function | What 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 |

### fetchNpm

```ts
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 }>
```

Downloads `name`, `name@version` or `name@tag` and unpacks it into the cache. Checks the tarball's integrity and the [download limits](https://skillrc.loadsheet.dev/guide/fetching#limits). Sends `NPM_TOKEN` unless `sendToken` is `false`. Ranges are not resolved.

### npm helpers

| Function | What 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 |

### takeLock

```ts
function takeLock(places: Places, file: string, mine: string, options?: LockOptions): string | undefined
```

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](https://skillrc.loadsheet.dev/guide/fetching#the-sync-lock).

| Export | What 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_MS` | Two hours: the age past which any lock is stale |
| `LockHeldError` | A `UserError` naming the holder |

### Files and hashes

| Function | What 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 |

### Paths and names

| Function | What 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` |

### UserError

```ts
class UserError extends Error {}
```

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

## skillrc/definitions

MCP servers and hooks. See [Definitions](https://skillrc.loadsheet.dev/guide/definitions).

### parseMcpFile

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

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.

### mcpEntries

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

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`.

### McpServer

```ts
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[];
}
```

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.

### parseHookFile

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

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`.

### Hook writers

| Function | What 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`.

## skillrc/sync

The sync engine. See [Sync](https://skillrc.loadsheet.dev/guide/sync).

### sync

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

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.

### SyncOptions

`{ dryRun?, offline?, only?, apply?, copy? }`, described in [Options](https://skillrc.loadsheet.dev/guide/sync#options). `previewSkills` and `initBackups` serve a program's own `init` command.

### SyncHost

```ts
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;
}
```

What the engine asks of your program. See [The host](https://skillrc.loadsheet.dev/guide/sync#the-host).

### AgentKinds

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

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.

### Plan and Source

```ts
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;
```

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

| Type | Fields |
| --- | --- |
| `GitSource` | `git`, `ref?` |
| `NpmSource` | `npm`, `registry?`, `sendToken` |
| `IndexSource` | `index` |
| `CloneSource` | `git`, `ref?`, `path`, `adopt`, `followLinks` |
| `LocalSource` | `local`, `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.

### Report

`{ 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](https://skillrc.loadsheet.dev/guide/sync#the-report).

### withSyncLock

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

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.

### State

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

`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.

### Forks and merges

| Function | What 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.

### Team sources

| Function | What 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 |

### Agents and skills

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

<!-- vitehub-docs:section-links -->
All pages: [llms.txt](https://skillrc.loadsheet.dev/llms.txt)

Something on this page does not work as written? Tell the user, and draft an issue for them to post: [issue tracker](https://github.com/words-with-agents/skillrc/issues). Report a security vulnerability privately, never in a public issue.
