mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
* fix(ruflo-console): Plugin Catalog reads a Windows marketplace clone (0.47.1)
Claude Code records the ruflo marketplace clone's installLocation as a drive
path (C:\Users\...\marketplaces\ruflo). readCatalog refused any location not
starting with "/", so the catalog showed "the clone's marketplace.json is not
readable" with the file in place.
- readCatalog uses isAbsolutePath / hasParentSegment from paths.ts.
- The catalog's plugin folders, manifests, skill/agent/command reads and the
snapshot's marketplace.json read (freshness row) build paths with joinPath
instead of a hardcoded "/".
- tests/windows-drive-path-sites.spec.ts: a Windows clone lists its plugins,
reads a skill file, and still refuses a relative or climbing location. The
new tests fail without the fix.
- Version 0.47.0 -> 0.47.1 in plugin.json, hooks/version.ts, scripts/smoke.sh
and CHANGELOG.md.
The other ruflo-console specs fail the same 12 tests with and without this
change on this machine (mission-cost, menu-entry, tui-ai-page, write-argv).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): forget-history actions and TUI colour work on Windows
- Events "forget history" and Workflows "forget saved views" ran `rm -f`, which
Windows does not have (write-flavor.ts: no delete on host-fs). On host-fs they
now empty the file(s) through the host file API (new emptyFiles in
write-via.ts; forgetSpec carries a `write` op like event-export does). The
saved-views file is rewritten as a valid empty document, and the forget is
verified by what the file holds. Linux/macOS keep the rm argv.
- depthOf returned "none" whenever TERM was unset. Windows Terminal, PowerShell
and cmd leave TERM unset (COLORTERM=truecolor, OS=Windows_NT), so the
standalone TUI drew without colour. On Windows only an explicit TERM=dumb or
NO_COLOR turns colour off.
Tests: both forget actions in host-fs flavor (files emptied, no rm run, refusal
reported, missing file left alone), forgetSpec verification, depthOf on Windows.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): ADR status edits on CRLF records, and codex detection, on Windows
- withStatus / withSupersedes compared whole lines ("---") and checked
startsWith("---\n"), so a MADR record checked out with CRLF (git autocrlf is on
by default on Windows) failed with "the front matter is not closed", and other
formats got mixed line endings. Records with CRLF are now edited as LF text and
written back with CRLF.
- The Conversation board looked for codex with `which`, which Windows lacks, so
codex was never offered there. A Windows home (drive path or share) uses
`where`.
Tests: CRLF records for all three ADR formats (same edit as LF, CRLF kept, MADR
front matter found, supersede link), and the finder per platform. The ADR tests
fail without the fix.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): keep the Windows fixes under the size rule, skip POSIX-only specs on Windows (0.47.2)
- Move the forget-history spec out of events-ui.ts into events-forget.ts: the
Windows branch had taken events-ui.ts to 521 lines (smoke step 11 caps files at
500). Move the codex-finder test out of wf-control-views.spec.ts (514 lines)
into wf-convo-finder.spec.ts.
- wf-replay-views: the Forget button asks one tick later now that it awaits the
write flavor; the spec waits for it.
- write-argv.spec.ts: the real-disk POSIX script specs check Unix mode bits and
FIFOs, which NTFS has not; Windows writes through the host file API. Skipped
there. tui-ai-page.spec.ts: the --plain spec needs a runnable fake codex (a
shebang script), which Windows cannot run; it asserts the codex line exists.
- Version 0.47.1 -> 0.47.2 in plugin.json, hooks/version.ts, scripts/smoke.sh and
CHANGELOG.md (the entry lists every Windows fix of this branch).
Verified: the specs of the changed areas pass; the remaining failures in a full
run are menu-entry (a circular import, not Windows-specific, fails on the
baseline), the *.test.ts kit files (need claude-code/testing), and two
timing-sensitive specs that pass alone.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-cost-tracker): the ledger scripts run on Windows (0.28.3)
ledger.mjs, advise.mjs and local-cost.mjs ran only when
import.meta.url === `file://${process.argv[1]}`. On Windows that is
file:///C:/... against C:\..., never equal, so every call exited 0 with no
output and the plugin's own test-ledger.mjs failed 7 tests. They compare against
pathToFileURL(process.argv[1]).href now.
Two more breaks sat behind it for the ruflo console's mission spend:
- ledger.mjs --project required a leading "/", so a Windows project exited 2.
- inProject matched with "/" and exact case; transcripts record C:\Users\x\proj.
A drive-lettered path now compares with either separator and any letter case;
POSIX matching is unchanged (exact, directory boundary).
Tests: test-ledger.mjs gains Windows rows and cases (drive path in both
separator styles and letter cases, relative or climbing drive paths still exit 2,
POSIX rule stays exact). Version 0.28.2 -> 0.28.3 in plugin.json, smoke.sh and
CHANGELOG.md. smoke.sh still fails 5 steps on a Windows Git Bash for a reason
that predates this (it hands /c/... paths to a Windows node), unchanged here.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the autopilot's text checks know Windows paths, commands and shells
Groundwork for the Windows-aware path checks that ap-windows-gate.spec.ts names as
the follow-up (an autopilot start is still refused on Windows). Each rule only
parks or refuses more; none allows anything that was refused before.
- classifyTask read only POSIX paths from a task's text, so a task naming
C:\Windows\..., \\srv\share\..., ..\..\x, ~\x, %USERPROFILE%\x or
$env:USERPROFILE\x was not checked against the envelope folders. It is now.
- delete-outside-worktree knew the POSIX recursive-delete forms but not the
Windows ones: rmdir /s, del on a drive, the drive-format command,
Remove-Item -Recurse, or a recursive rm on a drive or a variable.
- verifyProblem took the program name by splitting on "/" only, so
C:\Windows\System32\cmd.exe, bash.exe or powershell passed the banned-program
check. It uses either separator, drops .exe/.cmd/.bat/.ps1, and a second set
bans the Windows shells, script hosts and destructive or system tools.
Tests (ap-windows-guard.spec.ts): path extraction and the envelope check, the deny
forms and ordinary text that must not match, verify programs allowed and refused.
Four of them fail without the change; the POSIX behaviour is asserted unchanged.
CHANGELOG: added to the unreleased 0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the Overview heading shortens a Windows project path
"ruflo state in <last two folders>" split the cwd on "/" only, so a Windows cwd
(C:\Users\x\proj) printed whole. tailOf in paths.ts splits on either separator;
the overview uses it. Test in paths.spec.ts. CHANGELOG: added to the unreleased
0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): transcript search, model keys and peer sends on Windows; smoke under Git Bash
The last Windows gaps of the sweep, each tested.
- Stopping or messaging a workflow run reads the run's task id from the session
transcript; over 2 MB that was `grep -o`, which Windows lacks. Windows now runs
PowerShell's Select-String (windowsSearchArgv in data/wf-control.ts). The path
and the pattern ride inside the script as base64, so a path with a space, a
quote, $, & or ; is only data and the script holds no double quote. Tested
against a real PowerShell on a 5 MB-class file through such a path.
- taskIdOf returned the FIRST launch when a search printed two launches of one
run (a resume), because the pattern's `[^}]` ran across both matches (nothing
prints a closing brace between them). It takes the last task id in the match.
This also affected `grep -o` on Linux and macOS.
- A model key for an HTTP endpoint was read with `printenv`, which Windows lacks.
Host gains an optional `env` (register.ts: $.env.get, already used for other
names) and SendDeps an optional `readEnv`, set only for a Windows home; elsewhere
`printenv` is unchanged.
- A send to a federation peer runs `bash <helper>`. On a Windows PATH `bash` is
the WSL launcher (System32\bash.exe), which cannot open a C:\ script path, so
the send failed obscurely. On a Windows home it now refuses, running nothing,
and says why.
- ruflo-cost-tracker scripts/smoke.sh builds ROOT with `pwd -W` under Git Bash:
a Windows node could not open /c/... paths, which failed 5 steps (now 66/0).
Checked and left alone: the npx launcher. The installed Claude Code (a native
binary with the host code inside it) runs $.process.run through a bundled execa
on cross-spawn, which finds `npx` as npx.cmd through PATHEXT and runs it via
cmd.exe /d /s /c with its own argument escaping, so ['npx', ...] works on
Windows. The same lookup is why `bash` there is the first bash.exe on the PATH
(the WSL launcher on this machine), which the peer refusal above relies on.
CHANGELOG: both plugins' unreleased entries (0.47.2, 0.28.3) list these.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): what running every view on a real Windows machine turned up
The previous commits came from pattern scans. This one comes from running the
console's own readers against a real Windows machine (every view through the
standalone terminal; the plugin catalog, ADR loader and workflow reader called
directly), plus a complete triage of the path-handling patterns in hooks/.
Found by the real run:
- The standalone terminal left state.configDir null when CLAUDE_CONFIG_DIR was
unset (the usual case), so the installed plugins, the marketplaces and the
workflow runs were all "unreadable". It now falls back to <home>/.claude, as
register.ts does in the engine. Not Windows-specific.
- research.ts kept its own POSIX-only safeInstallPath, so ruflo-goals was never
found on Windows. It uses the Windows-aware one in cost-ledger.ts (same
character set on POSIX); on this machine goalsOf now answers ready with the
real C:\ root.
Found by triaging every `split('/')`, `lastIndexOf('/')` and `startsWith('/')`:
- isRunPath, isRunFile and isUnder checked for ".." only between slashes, so a
segment written with a backslash passed on Windows; a config folder ending in
a backslash did not match. They use hasParentSegment / trimTrailing, as does
under().
- The menu and the boot screen named the project by splitting cwd on "/", which
printed a whole C:\ path. baseOf in paths.ts.
Test-suite and cycle fixes so the smoke's own command passes here:
- views/pane built BODIES = { menu: menuView, ... } at load time, but
views/menu reaches pane through mission-control > mission-claude > model-tools,
so loading menu first left menuView undefined under the test runner (native
ESM hoists the function; the app loads pane first). It is read at call time.
- tui-actions waited a fixed 1.2 s for a 1 s retry plus a redraw, and failed
under CPU contention in a full run (also on the baseline). It waits for the
outcome it asserts, up to 10 s.
Verified: the smoke's exact command (every spec, 30 s timeout) is 239 files
passed, 0 failed, 3486 tests; the console smoke is 20 passed, 0 failed; all 34
views render with exit 0 and no stderr; an ADR project with a space in its path
and CRLF records loads and plans a status change keeping its CRLF.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the install record of a plugin that applies to this project, compared the Windows way
installed_plugins.json holds one record per install of a plugin, and a project-scope
record names the project it was made for. The snapshot took entries[0], so a plugin
installed for several projects showed another project's version and install folder.
On a real Windows machine ruflo-console@ruflo has five records (four project, one
user) and the first is a different project's 0.44.7; everything derived from it,
the version shown and the installPath used to find a plugin's scripts, could point
at the wrong copy.
- parseInstalled(text, cwd) picks the project or local record whose projectPath is
the session folder or holds it, else the user record, else the first.
- insideOrSame in paths.ts is that comparison, Windows-aware (case, either
separator, a folder inside the project); hooks/updates.ts decides which installs
to update with it too. It compared with === and startsWith(path + "/"), so on
Windows a session in a subfolder of the project, or with a different drive-letter
case, did not count the project's own install and left it stale.
tui-actions: "a read runs at once" waited a fixed 500 ms for a stand-in CLI process
to start; it waits for the run it asserts, and its neighbour, which failed only
because that run landed late in the shared log, no longer does.
Tests (windows-path-guards.spec.ts): the record chosen for the project under both
separators, other letter case, a subfolder, a sibling sharing the prefix, no match,
no user record, no cwd; the updater's rule; insideOrSame. Verified: the smoke's
exact command (every spec, 30 s timeout) is 239 files passed, 0 failed, 3491 tests.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the focus-lost spec waits for the output to go quiet before it asserts silence
"stops drawing while the terminal reports focus lost" marked the output length 60 ms
after the focus-lost report and then expected no growth. A frame already in flight
when focus was lost lands after that mark on a busy machine, which reads as the page
still drawing; the smoke's first vitest pass failed on it and only the retry passed.
It now waits until the output stops changing before it marks, still asserts 500 ms of
silence after that, and waits for the redraw on focus regained instead of a fixed
300 ms. Passes 4 of 4 isolated runs.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the hostile-regex spec bounds the scan's CPU time, not the wall clock
"a slow pattern over ten thousand 200-character events stops at its budget" asserted
that the scan finished in under 2500 ms of wall-clock time. The scan is CPU-bound, and
the wall clock also counts every other worker of a parallel run, so the spec passed
alone (all 12 specs of the file in 316 ms) and failed in full runs, including both
tries of the smoke's step 14 on the previous HEAD. It now bounds the scan's CPU time
(process.cpuUsage) at the same 2500 ms and keeps a 30 s wall-clock bound as a guard
against a hang. The product code is untouched.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the host-boundary spec does not scan the mutation specs' temporary files
tui-boundary.spec.ts reads every .ts under hooks/ when it loads. adr-mutation and
mission-advisor-mutation make temporary .mut-N-*.ts copies of hooks modules inside
hooks/ and delete them, in other workers of the same run. Two ways that disturbs this
spec: a copy that is still there is checked as if it were a hooks module (shown with a
throwaway .mut- file that imports a Node module: the spec failed before this change,
passes after), and a copy listed and then deleted can throw at load, which fails the
whole file (the smoke's step 14 showed one such file-level failure that did not repeat;
six runs of the three specs together did not reproduce it, so that part is the likely
cause, not a demonstrated one).
The walk skips .mut- names and tolerates a file that vanishes. A real violation in
hooks/ is still caught (checked with a throwaway file).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the mod loads again: $.env.get takes a literal name
An earlier commit on this branch (f54772424) gave the host an `env` read that was
`async name => $.env.get(name)`. The engine lists the variables a module reads, so
`claude plugin validate` refuses a computed name:
$.env.get takes a literal name as its first argument ...
and when it refuses register.ts the mod does not load at all: no /ruflo command, no
pane. Vitest never runs the engine's validator, so no test caught it; it showed up
when the branch was installed into a real Claude Code.
- register.ts reads only the one key it can name literally,
$.env.get('OPENROUTER_API_KEY'); any other name answers undefined.
- wf-send says, for a custom endpoint key on Windows, that it cannot be read here and
that only $OPENROUTER_API_KEY can, instead of claiming the variable is unset. The
OpenRouter key keeps the "is not set" wording.
- tui-boundary.spec.ts: no $.env.get/set in hooks/ may take a non-literal name (fails on
the old line, passes on the fix).
- smoke.sh step 21 runs `claude plugin validate` on the plugin when the CLI is present
(passes now; reports "Validation failed" against the old line).
- CHANGELOG corrected: it described the broken behaviour.
Verified with the real validator: before, "Found 1 error"; after, "Validation passed",
and the hook list shows command.run{command=ruflo}. The 9 "gating hook without .catch"
notes it prints are identical on upstream/main.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): specs remove their temp folder with a retry, so a still-exiting child does not fail the file on Windows
After the merge, tui-actions.spec.ts was reported as a failed FILE with all 8 of its
tests passing:
EBUSY: resource busy or locked, rmdir '...\tui-actions-XXXX\project'
On Windows a folder cannot be deleted while a process started in it is still running,
and these specs start the stand-in CLI and terminal sessions with the project folder as
their working directory. force: true does not cover EBUSY, and neither does maxRetries
on rmSync: measured on Node 22 with a child holding the folder for 1.2 s, rmSync fails
in 3 ms with or without maxRetries, while fs.promises.rm with maxRetries (and a manual
loop) removes it after about a second.
- tests/fixtures/rm-tree.ts: removeTree(), the async rm with up to ~5 s of retries.
- The ten specs that start processes or sessions in their temp folder (tui-actions,
tui-ai-host, tui-ai-page, tui-host, tui-nav, tui-pagebar, tui-parity, tui-pictures,
tui-session, wf-control-windows) use it in afterAll.
- tests/rm-tree.spec.ts: removes a tree and an already-gone one; on Windows, a real child
holding the folder makes rmSync fail with EBUSY and removeTree wait it out.
All eleven files pass.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
---------
Co-authored-by: RuFlo <ruv@ruv.net>
177 lines
8.4 KiB
TypeScript
177 lines
8.4 KiB
TypeScript
/**
|
|
* The ruflo marketplace as a catalog: every plugin its clone lists, with the skills, agents, commands, MCP config and
|
|
* mod (function hooks) each ships, read from the clone on disk. An external plugin (listed by a git source, maintained in
|
|
* another repository) has no copy in the clone: it is read from its install path in `installed_plugins.json` when it is
|
|
* installed. Read-only, bounded, nothing run: a file over the cap, a name that is not a plain word and a path with `..`
|
|
* are skipped, and every read may be refused.
|
|
*/
|
|
import type { ReaderFs } from './files'
|
|
import { plain } from './parse'
|
|
import { hasParentSegment, isAbsolutePath, joinPath } from './paths'
|
|
|
|
export type CatalogPlugin = {
|
|
name: string
|
|
description: string
|
|
version: string | null
|
|
/** Folder of the plugin inside the clone, or of the installed copy of an external one (absolute); '' when there is neither. */
|
|
dir: string
|
|
skills: string[]
|
|
agents: string[]
|
|
commands: string[]
|
|
hasMcp: boolean
|
|
/** The plugin.json userConfig keys: the options Settings can edit. */
|
|
options: string[]
|
|
/** A `hooks/register.ts` makes it a mod: function hooks run in the engine. */
|
|
isMod: boolean
|
|
/** Set for an external plugin: the repository, folder and ref the marketplace pins it to. */
|
|
external?: string
|
|
}
|
|
|
|
const NAME = /^[A-Za-z0-9._-]{1,80}$/
|
|
const PLUGINS_MAX = 200
|
|
const LIST_MAX = 200
|
|
const DOC_BYTES = 120_000
|
|
/** Lines of a SKILL.md or command file the Result panel shows. */
|
|
export const DOC_LINES = 40
|
|
|
|
const recordOf = (value: unknown): Record<string, unknown> | null => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null)
|
|
|
|
const safeSource = (source: unknown): string | null =>
|
|
typeof source === 'string' && source.startsWith('./') && !source.split('/').includes('..') && source.length < 200 ? source.slice(2).replace(/\/+$/, '') : null
|
|
|
|
async function namesIn(fs: ReaderFs, dir: string, kind: 'dir' | 'md'): Promise<string[]> {
|
|
const entries = await fs.list(dir).catch(() => [])
|
|
|
|
return entries
|
|
.flatMap(entry => {
|
|
const isDir = entry.kind === undefined ? !entry.name.includes('.') : entry.kind === 'directory' || entry.kind === 'dir'
|
|
const name = kind === 'md' ? entry.name.replace(/\.md$/, '') : entry.name
|
|
|
|
return (kind === 'md' ? entry.name.endsWith('.md') && !isDir : isDir) && NAME.test(name) ? [name] : []
|
|
})
|
|
.sort()
|
|
.slice(0, LIST_MAX)
|
|
}
|
|
|
|
/** An external source (`git-subdir`, `github`, `git`, `url`) as one plain line, or null for anything else. */
|
|
function externalOf(source: unknown): string | null {
|
|
const record = recordOf(source)
|
|
const at = (value: unknown) => (typeof value === 'string' ? value : '')
|
|
|
|
if (record === null || !['git-subdir', 'github', 'git', 'url'].includes(at(record.source))) return null
|
|
|
|
const where = [at(record.url) || at(record.repo), at(record.path)].filter(Boolean).join(' ')
|
|
const ref = at(record.ref) || at(record.sha).slice(0, 12)
|
|
|
|
return where === '' ? null : plain(`${where}${ref === '' ? '' : ` @ ${ref}`}`, 200)
|
|
}
|
|
|
|
const exists = async (fs: ReaderFs, path: string): Promise<boolean> => (await fs.stat(path).catch(() => undefined)) !== undefined
|
|
|
|
async function pluginOf(fs: ReaderFs, location: string, entry: Record<string, unknown>, installed: ReadonlyMap<string, string>): Promise<CatalogPlugin | null> {
|
|
const name = entry.name
|
|
const source = safeSource(entry.source)
|
|
const external = source === null ? externalOf(entry.source) : null
|
|
|
|
if (typeof name !== 'string' || !NAME.test(name) || (source === null && external === null)) return null
|
|
|
|
const dir = source !== null ? joinPath(location, source) : (installed.get(name) ?? '')
|
|
|
|
if (dir === '') {
|
|
return { name, options: [], description: plain(typeof entry.description === 'string' ? entry.description : '', 400), version: null, dir, skills: [], agents: [], commands: [], hasMcp: false, isMod: false, ...(external !== null && { external }) }
|
|
}
|
|
|
|
const manifest = await fs.read(joinPath(dir, '.claude-plugin', 'plugin.json')).then(
|
|
text => recordOf(JSON.parse(text)),
|
|
() => null,
|
|
)
|
|
const [skills, agents, commands, hasMcp, isMod] = await Promise.all([
|
|
namesIn(fs, joinPath(dir, 'skills'), 'dir'),
|
|
namesIn(fs, joinPath(dir, 'agents'), 'md'),
|
|
namesIn(fs, joinPath(dir, 'commands'), 'md'),
|
|
exists(fs, joinPath(dir, '.mcp.json')),
|
|
exists(fs, joinPath(dir, 'hooks', 'register.ts')),
|
|
])
|
|
const version = typeof manifest?.version === 'string' ? plain(manifest.version, 30) : typeof entry.version === 'string' ? plain(entry.version, 30) : null
|
|
|
|
const options = Object.keys(recordOf(manifest?.userConfig) ?? {}).filter(key => NAME.test(key)).slice(0, 60)
|
|
|
|
return { name, options, description: plain(typeof entry.description === 'string' ? entry.description : typeof manifest?.description === 'string' ? manifest.description : '', 400), version, dir, skills, agents, commands, hasMcp, isMod, ...(external !== null && { external }) }
|
|
}
|
|
|
|
/**
|
|
* Every plugin the marketplace clone at `location` lists, or null when its manifest cannot be read. `installed` maps a plugin name to
|
|
* its install path (absolute, already checked by the caller): an external plugin is read from there.
|
|
*/
|
|
export async function readCatalog(fs: ReaderFs, location: string, installed: ReadonlyMap<string, string> = new Map()): Promise<CatalogPlugin[] | null> {
|
|
if (!isAbsolutePath(location) || hasParentSegment(location)) return null
|
|
|
|
const raw = await fs.read(joinPath(location, '.claude-plugin', 'marketplace.json')).catch(() => null)
|
|
let list: unknown[] = []
|
|
|
|
try {
|
|
const plugins = raw === null ? null : recordOf(JSON.parse(raw))?.plugins
|
|
|
|
if (!Array.isArray(plugins)) return null
|
|
|
|
list = plugins.slice(0, PLUGINS_MAX)
|
|
} catch {
|
|
return null
|
|
}
|
|
|
|
const found: CatalogPlugin[] = []
|
|
|
|
// Eight at a time: forty-odd plugins are a few hundred small reads, none of which should crowd the engine's own.
|
|
for (let at = 0; at < list.length; at += 8) {
|
|
const batch = await Promise.all(
|
|
list.slice(at, at + 8).map(async entry => {
|
|
const record = recordOf(entry)
|
|
|
|
return record === null ? null : pluginOf(fs, location, record, installed).catch(() => null)
|
|
}),
|
|
)
|
|
|
|
for (const plugin of batch) if (plugin !== null) found.push(plugin)
|
|
}
|
|
|
|
return found.sort((a, b) => a.name.localeCompare(b.name))
|
|
}
|
|
|
|
/** A skill, agent or command file's first lines (and its frontmatter description), or null when it cannot be read. */
|
|
export async function readDoc(fs: ReaderFs, plugin: CatalogPlugin, kind: 'skill' | 'agent' | 'command', name: string): Promise<{ description: string; lines: string[] } | null> {
|
|
if (!NAME.test(name) || plugin.dir === '') return null
|
|
|
|
const path = kind === 'skill' ? joinPath(plugin.dir, 'skills', name, 'SKILL.md') : joinPath(plugin.dir, kind === 'agent' ? 'agents' : 'commands', `${name}.md`)
|
|
const stat = await fs.stat(path).catch(() => undefined)
|
|
|
|
if (stat === undefined || (stat.size ?? 0) > DOC_BYTES) return null
|
|
// A link, or anything but a plain file, is never read: its target may be outside the plugin and its text would be drawn and handed to the model (#3817).
|
|
if (stat.isLink === true || (stat.kind !== undefined && stat.kind !== 'file')) return null
|
|
|
|
const text = await fs.read(path).catch(() => null)
|
|
|
|
if (text === null) return null
|
|
|
|
const lines = text.split('\n').map(line => plain(line, 200))
|
|
const description = lines.find(line => /^description:/i.test(line))?.replace(/^description:\s*/i, '').replace(/^["']|["']$/g, '') ?? ''
|
|
|
|
return { description: plain(description, 200), lines: lines.slice(0, DOC_LINES) }
|
|
}
|
|
|
|
export type CatalogMode = 'all' | 'installed' | 'missing' | 'mods' | 'skills' | 'agents'
|
|
|
|
/** The plugins a mode and a filter word keep: the word matches a name, a description, or any skill/agent/command name. */
|
|
export function visible(all: readonly CatalogPlugin[], installed: ReadonlySet<string>, mode: CatalogMode, word: string): CatalogPlugin[] {
|
|
const needle = word.trim().toLowerCase()
|
|
|
|
return all.filter(plugin => {
|
|
if (mode === 'installed' && !installed.has(plugin.name)) return false
|
|
if (mode === 'missing' && installed.has(plugin.name)) return false
|
|
if (mode === 'mods' && !plugin.isMod) return false
|
|
if (mode === 'skills' && plugin.skills.length === 0) return false
|
|
if (mode === 'agents' && plugin.agents.length === 0) return false
|
|
|
|
return needle === '' || [plugin.name, plugin.description, ...plugin.skills, ...plugin.agents, ...plugin.commands].some(text => text.toLowerCase().includes(needle))
|
|
})
|
|
}
|