@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,1893 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skills loader — reads .md files from ~/.chroxy/skills/ (global) and
|
|
3
|
+
* <repo>/.chroxy/skills/ (repo overlay) and formats them for injection
|
|
4
|
+
* into provider system prompts / first user messages.
|
|
5
|
+
*
|
|
6
|
+
* MVP design (issue #2957):
|
|
7
|
+
* - Location: ~/.chroxy/skills/ (one file per skill)
|
|
8
|
+
* - No frontmatter — the file body IS the skill content
|
|
9
|
+
* - Active = every *.md that does NOT end in .disabled.md
|
|
10
|
+
* - Disable a skill by renaming foo.md → foo.disabled.md
|
|
11
|
+
*
|
|
12
|
+
* Repo overlay (#3067):
|
|
13
|
+
* - Per-session: walk up from session.cwd looking for .chroxy/skills/
|
|
14
|
+
* - Repo skills override global by filename — repo file `coding-style.md`
|
|
15
|
+
* replaces global file `coding-style.md` in the merged set.
|
|
16
|
+
*
|
|
17
|
+
* Trust-model hardening (#2959):
|
|
18
|
+
* - Symlink defense (#3201): realpath() each candidate before reading.
|
|
19
|
+
* Reject if the resolved path escapes the configured skills root unless
|
|
20
|
+
* it lands under an explicit allowlist root.
|
|
21
|
+
* - Markdown-only enforcement (#3203): only configured extensions are
|
|
22
|
+
* accepted (default `['md', 'markdown']`); content sniffing scans the
|
|
23
|
+
* ENTIRE file for NUL bytes and non-whitespace control chars (#3216).
|
|
24
|
+
* Vendored / executable subtrees (`.git`, `node_modules`,
|
|
25
|
+
* `__pycache__`, `dist`, `build`) are skipped.
|
|
26
|
+
* - Path sanitization in logs (#3215): rejection warnings expose only the
|
|
27
|
+
* basename + an 8-char SHA-256 hash. The full path is logged once at
|
|
28
|
+
* debug level (which does not fan out to dashboards at default info).
|
|
29
|
+
* - Size budgets (#3202): each skill is capped at `maxSkillBytes`
|
|
30
|
+
* (default 32KB) and the merged set is capped at `maxTotalSkillBytes`
|
|
31
|
+
* (default 256KB). Lower-priority skills are dropped first when the
|
|
32
|
+
* total budget is exceeded; absent priority info, alphabetical order
|
|
33
|
+
* is the tiebreaker.
|
|
34
|
+
*
|
|
35
|
+
* v2 frontmatter consumers (#2958 / #2959):
|
|
36
|
+
* - parseFrontmatter helper + `metadata` field on each Skill — #3197.
|
|
37
|
+
* - `providers:` filter (#3198): a skill whose frontmatter declares
|
|
38
|
+
* `providers: [claude-sdk, codex]` is included only for sessions whose
|
|
39
|
+
* provider matches one of the listed values. Missing `providers:`
|
|
40
|
+
* means apply-to-all (back-compat with v1). Matching is case-insensitive
|
|
41
|
+
* exact-match against the session's provider id (the registry key from
|
|
42
|
+
* providers.js, e.g. `claude-sdk`); the alias `claude` is treated as a
|
|
43
|
+
* family match for any `claude-*` provider so users don't have to know
|
|
44
|
+
* the exact registry key.
|
|
45
|
+
* - `activation: manual` (#3199): skills with `metadata.activation ===
|
|
46
|
+
* 'manual'` are filtered out of the default-active set. They reappear
|
|
47
|
+
* only when their name is in the `activeManualSkills` Set passed to
|
|
48
|
+
* the loader. Default activation is `auto` (i.e., always active when
|
|
49
|
+
* the other gates pass). The runtime toggle WS API is #3209.
|
|
50
|
+
* - `injection:` mode (#3200): each loaded Skill carries an
|
|
51
|
+
* `injectionMode` of 'prepend' | 'append' | 'system', derived from
|
|
52
|
+
* `metadata.injection` (default = the provider's default mode passed
|
|
53
|
+
* via `defaultInjectionMode`). Callers that want to split skills by
|
|
54
|
+
* injection point use `groupSkillsByInjectionMode()` and feed each
|
|
55
|
+
* group through `formatSkillsForPrompt()` separately.
|
|
56
|
+
*/
|
|
57
|
+
import {
|
|
58
|
+
readdirSync,
|
|
59
|
+
readFileSync,
|
|
60
|
+
statSync,
|
|
61
|
+
fstatSync,
|
|
62
|
+
realpathSync,
|
|
63
|
+
openSync,
|
|
64
|
+
closeSync,
|
|
65
|
+
} from 'fs'
|
|
66
|
+
import { dirname, join, relative, resolve, sep } from 'path'
|
|
67
|
+
import { homedir } from 'os'
|
|
68
|
+
import { createLogger } from './logger.js'
|
|
69
|
+
import { getErrorMessage } from './utils/error-message.js'
|
|
70
|
+
|
|
71
|
+
const log = createLogger('skills-loader')
|
|
72
|
+
|
|
73
|
+
export const DEFAULT_SKILLS_DIR = join(homedir(), '.chroxy', 'skills')
|
|
74
|
+
|
|
75
|
+
// Cap walk-up iterations as a safety belt; real repos are nowhere near this deep.
|
|
76
|
+
const REPO_DISCOVERY_MAX_DEPTH = 100
|
|
77
|
+
|
|
78
|
+
// #3223: validator helpers extracted to skills-content-validator.js.
|
|
79
|
+
import {
|
|
80
|
+
DEFAULT_ALLOWED_EXTENSIONS,
|
|
81
|
+
SKIP_DIRECTORY_NAMES,
|
|
82
|
+
_normalizeExtension,
|
|
83
|
+
_bufferLooksLikeText,
|
|
84
|
+
_pathLabel,
|
|
85
|
+
} from './skills-content-validator.js'
|
|
86
|
+
|
|
87
|
+
// #3223: budget + allowlist enforcement extracted to skills-budget.js.
|
|
88
|
+
import {
|
|
89
|
+
DEFAULT_MAX_SKILL_BYTES,
|
|
90
|
+
DEFAULT_MAX_TOTAL_SKILL_BYTES,
|
|
91
|
+
_enforceTotalBudget,
|
|
92
|
+
_filterByProviderAllowlist,
|
|
93
|
+
_compareByPriorityThenName,
|
|
94
|
+
DEFAULT_SKILL_PRIORITY,
|
|
95
|
+
} from './skills-budget.js'
|
|
96
|
+
|
|
97
|
+
// #3223: frontmatter parser + frontmatter-driven gating helpers extracted
|
|
98
|
+
// to skills-frontmatter.js. Re-exported below for back-compat with the
|
|
99
|
+
// loader's public API surface (parseFrontmatter is consumed by tests and
|
|
100
|
+
// findSkillForRetrust here).
|
|
101
|
+
import {
|
|
102
|
+
parseFrontmatter,
|
|
103
|
+
_normalizeProviderName,
|
|
104
|
+
_coerceManualSet,
|
|
105
|
+
_skillMatchesProvider,
|
|
106
|
+
_normalizeInjectionMode,
|
|
107
|
+
_resolveInjectionMode,
|
|
108
|
+
_skillIsActive,
|
|
109
|
+
_readFrontmatterOnly,
|
|
110
|
+
} from './skills-frontmatter.js'
|
|
111
|
+
|
|
112
|
+
// Re-export for callers that historically imported from skills-loader.js.
|
|
113
|
+
export { parseFrontmatter }
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Return true if `child` is the same as or nested inside `parent`. Both
|
|
118
|
+
* must be absolute paths; comparison is case-insensitive on darwin/win32 to
|
|
119
|
+
* match real filesystem semantics there (HFS+/APFS/NTFS default).
|
|
120
|
+
*
|
|
121
|
+
* Uses path-segment comparison (not `startsWith`) so `/foo/barbaz` doesn't
|
|
122
|
+
* match `/foo/bar` as a prefix.
|
|
123
|
+
*/
|
|
124
|
+
function _pathContains(parent, child) {
|
|
125
|
+
if (typeof parent !== 'string' || typeof child !== 'string') return false
|
|
126
|
+
let p = parent
|
|
127
|
+
let c = child
|
|
128
|
+
if (_PATH_COMPARE_CASE_INSENSITIVE) {
|
|
129
|
+
p = p.toLowerCase()
|
|
130
|
+
c = c.toLowerCase()
|
|
131
|
+
}
|
|
132
|
+
if (p === c) return true
|
|
133
|
+
const withSep = p.endsWith(sep) ? p : p + sep
|
|
134
|
+
return c.startsWith(withSep)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Resolve every entry in `roots` with realpath (silently dropping ones that
|
|
139
|
+
* don't exist) and return the deduped, absolute list.
|
|
140
|
+
*/
|
|
141
|
+
function _resolveRoots(roots) {
|
|
142
|
+
const out = []
|
|
143
|
+
const seen = new Set()
|
|
144
|
+
for (const r of roots) {
|
|
145
|
+
if (typeof r !== 'string' || !r) continue
|
|
146
|
+
let real
|
|
147
|
+
try {
|
|
148
|
+
real = realpathSync(r)
|
|
149
|
+
} catch {
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
const key = _PATH_COMPARE_CASE_INSENSITIVE ? real.toLowerCase() : real
|
|
153
|
+
if (seen.has(key)) continue
|
|
154
|
+
seen.add(key)
|
|
155
|
+
out.push(real)
|
|
156
|
+
}
|
|
157
|
+
return out
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Scan `dir` for active skills and return them as an array sorted by name.
|
|
163
|
+
*
|
|
164
|
+
* A skill is any regular file whose extension is in `opts.allowedExtensions`
|
|
165
|
+
* (defaults to `['md', 'markdown']`) and whose name does NOT end in
|
|
166
|
+
* `.disabled.<ext>` — the disabled-suffix convention is generalised per
|
|
167
|
+
* allowed extension so a `*.disabled.md` is off when `md` is allowed,
|
|
168
|
+
* `*.disabled.txt` is off when `txt` is allowed, etc.
|
|
169
|
+
*
|
|
170
|
+
* Returns `[]` if the directory does not exist or contains no active skills —
|
|
171
|
+
* skills are optional, so a missing dir is not an error.
|
|
172
|
+
*
|
|
173
|
+
* Security hardening (#3201, #3203, #3215, #3216, #3202):
|
|
174
|
+
* - Each candidate's real path is resolved with `fs.realpathSync` and must
|
|
175
|
+
* either remain inside `dir` or land under one of `opts.allowedRoots`.
|
|
176
|
+
* - Files outside `opts.allowedExtensions` (default `['md', 'markdown']`)
|
|
177
|
+
* are skipped.
|
|
178
|
+
* - Each candidate's full bytes are scanned; files containing NUL or
|
|
179
|
+
* other non-whitespace control chars are rejected (#3216).
|
|
180
|
+
* - Each skill is capped at `opts.maxSkillBytes` (default 32KB).
|
|
181
|
+
* - Rejection warnings include only `basename#hash` (#3215); the full
|
|
182
|
+
* absolute path is logged once at debug level.
|
|
183
|
+
*
|
|
184
|
+
* Trust hashing (#3204): when a `trustStore` is supplied, each skill's
|
|
185
|
+
* post-frontmatter body is hashed with SHA-256 and compared against the
|
|
186
|
+
* stored value. First-seen content is recorded; mismatches log a
|
|
187
|
+
* sanitised warn and (in `block` mode) cause the skill to be filtered.
|
|
188
|
+
* `onTrustMismatch(info)` is invoked for every mismatch so callers can
|
|
189
|
+
* fan a `skill_changed` WS event downstream.
|
|
190
|
+
*
|
|
191
|
+
* @param {string} dir - Directory to scan (e.g. ~/.chroxy/skills)
|
|
192
|
+
* @param {{
|
|
193
|
+
* source?: 'global' | 'repo',
|
|
194
|
+
* allowedRoots?: string[],
|
|
195
|
+
* allowedExtensions?: string[],
|
|
196
|
+
* maxSkillBytes?: number,
|
|
197
|
+
* provider?: string|null,
|
|
198
|
+
* activeManualSkills?: Set<string>|string[]|null,
|
|
199
|
+
* defaultInjectionMode?: 'prepend'|'append'|'system'|null,
|
|
200
|
+
* trustStore?: object|null,
|
|
201
|
+
* onTrustMismatch?: (info: object) => void,
|
|
202
|
+
* communityTrustChecker?: ((realPath: string, author: string) => boolean) | null,
|
|
203
|
+
* onCommunityTrustPending?: (info: object) => void,
|
|
204
|
+
* }} [opts]
|
|
205
|
+
* - `provider`: the session's provider id (e.g. `claude-sdk`, `codex`).
|
|
206
|
+
* When set, skills whose frontmatter declares a `providers:` list are
|
|
207
|
+
* filtered to that subset (#3198).
|
|
208
|
+
* - `activeManualSkills`: names of skills the user has explicitly
|
|
209
|
+
* activated. Skills with `metadata.activation === 'manual'` only load
|
|
210
|
+
* when their name is in this set (#3199). Default = none.
|
|
211
|
+
* - `defaultInjectionMode`: provider-default injection mode applied when
|
|
212
|
+
* a skill doesn't pin a `metadata.injection` value (#3200). Defaults
|
|
213
|
+
* to `'append'` to match the Claude SDK's existing systemPrompt.append
|
|
214
|
+
* channel; subprocess providers should pass `'prepend'`.
|
|
215
|
+
* - `trustStore`: a `SkillsTrustStore` instance (or any object exposing
|
|
216
|
+
* `inspect(absPath, body)` and `mode`). When provided, the loader
|
|
217
|
+
* records / verifies a SHA-256 hash for each skill (#3204).
|
|
218
|
+
* - `onTrustMismatch`: optional callback invoked with the mismatch
|
|
219
|
+
* info `{ name, source, path, oldHash, newHash, blocked, mode }` for
|
|
220
|
+
* every skill whose stored hash differs. `mode` (#3241) is projected
|
|
221
|
+
* from `trustStore.mode` so downstream consumers can render
|
|
222
|
+
* mode-specific UX without re-deriving it from `blocked`. Loader
|
|
223
|
+
* callers (BaseSession) fan this into a `skill_changed` WS event for
|
|
224
|
+
* #3205.
|
|
225
|
+
* - `includeInactive`: when true, manual skills that aren't in
|
|
226
|
+
* `activeManualSkills` are still returned but tagged with
|
|
227
|
+
* `active: false`. Used by `list_skills` for the toggle UX (#3209).
|
|
228
|
+
* - `includeAllProviders`: when true, the per-skill provider gate
|
|
229
|
+
* (#3198) is bypassed so scoped skills appear in the result
|
|
230
|
+
* regardless of the session's provider. Used by `list_skills` for
|
|
231
|
+
* the "browse all installed skills" view (#3226). Default false —
|
|
232
|
+
* runtime prompt-build callers keep provider scoping enforced.
|
|
233
|
+
* - `parseCache`: optional `Map` of mtime-keyed parse results to skip
|
|
234
|
+
* re-reading and re-parsing unchanged files (#3248).
|
|
235
|
+
* - `maxTotalBytes`: per-tier byte budget that bounds peak memory (#3222).
|
|
236
|
+
* When set, the loader uses a two-pass approach (#3279): pass 1
|
|
237
|
+
* (`_collectCandidates`) does a bounded ~4KB frontmatter-only read for
|
|
238
|
+
* every candidate to extract priority, then pass 2 walks candidates in
|
|
239
|
+
* priority-descending order (name-ascending tiebreak) reading full bodies
|
|
240
|
+
* until the budget is exhausted. Skills that don't fit are skipped with
|
|
241
|
+
* `continue` (not `break`) so a later smaller skill can still fit.
|
|
242
|
+
* When unset, the original single-pass alphabetical loop runs unchanged
|
|
243
|
+
* (back-compat). Layered loader sets this to `maxTotalSkillBytes` so a
|
|
244
|
+
* single tier can never exhaust more than the global cap, capping peak
|
|
245
|
+
* memory at 2× the global cap across both tier loads.
|
|
246
|
+
* - `communityTrustChecker`: optional `(realPath, author) => boolean`. When
|
|
247
|
+
* provided, called for every skill discovered under `community/<author>/`.
|
|
248
|
+
* Returns `true` if the author is trusted, `false` if not yet trusted
|
|
249
|
+
* (pending). When `null`/undefined the loader fails-open (treats all
|
|
250
|
+
* community skills as trusted) — required for trust-disabled sessions and
|
|
251
|
+
* for back-compat with callers that don't pass the option. (#3206 / #3296)
|
|
252
|
+
* - `onCommunityTrustPending`: optional `(info) => void`. Fired once per
|
|
253
|
+
* pending community skill (i.e. a skill under `community/<author>/` where
|
|
254
|
+
* `communityTrustChecker` returns false). `info` shape:
|
|
255
|
+
* `{ name, author, source, description, path }`. PR B will wire this to a
|
|
256
|
+
* `skill_trust_request` WS broadcast. (#3206 / #3296)
|
|
257
|
+
*
|
|
258
|
+
* Community-namespace gate (#3206 / #3296):
|
|
259
|
+
* Skills under `<root>/community/<author>/` are subject to a first-
|
|
260
|
+
* activation prompt. `communityTrustChecker(realPath, author)` decides
|
|
261
|
+
* trusted vs pending. Pending skills are excluded from the default-active
|
|
262
|
+
* set (when `includeInactive: false`, the default) and only surface in the
|
|
263
|
+
* `includeInactive` listing path so the dashboard can render them with a
|
|
264
|
+
* trust-grant affordance. Trusted community skills run through the full
|
|
265
|
+
* pipeline unchanged and are tagged `trustState: 'trusted'`. Non-community
|
|
266
|
+
* skills are not tagged with `trustState` or `communityAuthor`.
|
|
267
|
+
*
|
|
268
|
+
* Walk depth: the loader performs a one-level recursive walk under
|
|
269
|
+
* `community/` — `<root>/community/<author>/x.md` is discovered;
|
|
270
|
+
* `<root>/community/<author>/sub/y.md` is NOT (depth capped at 1 under
|
|
271
|
+
* each author dir as a v1 simplification; can be lifted later). The walk
|
|
272
|
+
* still respects `SKIP_DIRECTORY_NAMES` under `community/`.
|
|
273
|
+
* @returns {Array<{ name: string, body: string, description: string, source?: string, metadata: object|null, injectionMode: string }>}
|
|
274
|
+
*/
|
|
275
|
+
export function loadActiveSkills(dir, opts = {}) {
|
|
276
|
+
const { source } = opts
|
|
277
|
+
const provider = _normalizeProviderName(opts.provider)
|
|
278
|
+
const activeManualSkills = _coerceManualSet(opts.activeManualSkills)
|
|
279
|
+
const defaultInjectionMode = _normalizeInjectionMode(opts.defaultInjectionMode) || 'append'
|
|
280
|
+
const trustStore = opts.trustStore || null
|
|
281
|
+
const onTrustMismatch = typeof opts.onTrustMismatch === 'function' ? opts.onTrustMismatch : null
|
|
282
|
+
// #3209: when true, manual skills that aren't in `activeManualSkills`
|
|
283
|
+
// are still returned but tagged with `active: false`. Used by the
|
|
284
|
+
// dashboard's `list_skills` so it can render toggles for inactive
|
|
285
|
+
// manual skills. Runtime prompt-build callers keep the default (false)
|
|
286
|
+
// so an inactive manual skill never lands in the system prompt.
|
|
287
|
+
const includeInactive = !!opts.includeInactive
|
|
288
|
+
// #3226: when true, the provider-scoping gate (#3198) is bypassed.
|
|
289
|
+
// Used by the dashboard `list_skills` fallback path so the "browse
|
|
290
|
+
// all installed skills" view shows provider-scoped skills even when
|
|
291
|
+
// no provider is bound (or the bound session can't report one).
|
|
292
|
+
// The runtime prompt-build path keeps the default (false) so a skill
|
|
293
|
+
// scoped to `providers: [claude-sdk]` never lands in a non-Claude
|
|
294
|
+
// session's prompt.
|
|
295
|
+
const includeAllProviders = !!opts.includeAllProviders
|
|
296
|
+
// #3248: optional caller-supplied parse cache. Keyed by realpath,
|
|
297
|
+
// value is `{ mtimeMs, size, body, frontmatter, finalBody, description }`.
|
|
298
|
+
// When the cache holds an entry whose mtimeMs+size match the
|
|
299
|
+
// current statSync result, the loader skips readFileSync and
|
|
300
|
+
// parseFrontmatter. Trust hashing still runs (cheap on the
|
|
301
|
+
// already-parsed body). Callers (BaseSession) pass a per-session
|
|
302
|
+
// Map; first call populates, subsequent calls hit. Invalidation
|
|
303
|
+
// is automatic — any on-disk edit bumps mtimeMs.
|
|
304
|
+
const parseCache = opts.parseCache instanceof Map ? opts.parseCache : null
|
|
305
|
+
// #3206 / #3296: community-namespace gate. When provided,
|
|
306
|
+
// communityTrustChecker(realPath, author) decides if a community skill is
|
|
307
|
+
// trusted or pending. Null/undefined → fail-open (treat as trusted) so
|
|
308
|
+
// trust-disabled sessions and callers that don't pass the opt are unaffected.
|
|
309
|
+
const communityTrustChecker = typeof opts.communityTrustChecker === 'function'
|
|
310
|
+
? opts.communityTrustChecker
|
|
311
|
+
: null
|
|
312
|
+
// Callback fired once per pending community skill so callers can fan a
|
|
313
|
+
// skill_trust_request WS event. Non-fatal if it throws — loader swallows.
|
|
314
|
+
const onCommunityTrustPending = typeof opts.onCommunityTrustPending === 'function'
|
|
315
|
+
? opts.onCommunityTrustPending
|
|
316
|
+
: null
|
|
317
|
+
let entries
|
|
318
|
+
try {
|
|
319
|
+
entries = readdirSync(dir)
|
|
320
|
+
} catch {
|
|
321
|
+
return []
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Resolve the skills root + caller-supplied allowlist via realpath.
|
|
325
|
+
// If the root itself doesn't exist, bail — readdirSync would have thrown
|
|
326
|
+
// anyway, but we'd like to be explicit.
|
|
327
|
+
let dirReal
|
|
328
|
+
try {
|
|
329
|
+
dirReal = realpathSync(dir)
|
|
330
|
+
} catch {
|
|
331
|
+
return []
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const allowedRoots = _resolveRoots([dirReal, ...(Array.isArray(opts.allowedRoots) ? opts.allowedRoots : [])])
|
|
335
|
+
|
|
336
|
+
// Build the set of valid extensions. Each entry is the lower-case suffix
|
|
337
|
+
// without the leading dot.
|
|
338
|
+
const rawExts = Array.isArray(opts.allowedExtensions) && opts.allowedExtensions.length > 0
|
|
339
|
+
? opts.allowedExtensions
|
|
340
|
+
: DEFAULT_ALLOWED_EXTENSIONS
|
|
341
|
+
const allowedExtensions = new Set()
|
|
342
|
+
for (const ext of rawExts) {
|
|
343
|
+
const norm = _normalizeExtension(ext)
|
|
344
|
+
if (norm) allowedExtensions.add(norm)
|
|
345
|
+
}
|
|
346
|
+
if (allowedExtensions.size === 0) {
|
|
347
|
+
for (const ext of DEFAULT_ALLOWED_EXTENSIONS) allowedExtensions.add(ext)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const maxSkillBytes = Number.isFinite(opts.maxSkillBytes) && opts.maxSkillBytes > 0
|
|
351
|
+
? Math.floor(opts.maxSkillBytes)
|
|
352
|
+
: DEFAULT_MAX_SKILL_BYTES
|
|
353
|
+
|
|
354
|
+
// #3222: per-tier byte budget. Bounds peak memory before the layered
|
|
355
|
+
// loader's post-merge prune by stopping the read loop once cumulative
|
|
356
|
+
// bytes for THIS tier would exceed the budget. Default = unbounded
|
|
357
|
+
// (back-compat — prior behaviour was post-merge-only). Layered loader
|
|
358
|
+
// sets this to `maxTotalSkillBytes` so a single tier can never exhaust
|
|
359
|
+
// more than the global cap, capping peak memory at 2× the global cap
|
|
360
|
+
// across both tier loads. Final cross-tier pruning still runs in
|
|
361
|
+
// `_enforceTotalBudget` after the merge.
|
|
362
|
+
const tierBudget = Number.isFinite(opts.maxTotalBytes) && opts.maxTotalBytes > 0
|
|
363
|
+
? Math.floor(opts.maxTotalBytes)
|
|
364
|
+
: null
|
|
365
|
+
|
|
366
|
+
// Process entries in deterministic order so the budget cuts off the same
|
|
367
|
+
// skills across runs (filesystem readdir order is platform-dependent). Sort
|
|
368
|
+
// alphabetically by basename — this is the tiebreaker within each priority
|
|
369
|
+
// bucket for the two-pass path, and the full cutoff order for the
|
|
370
|
+
// single-pass path.
|
|
371
|
+
entries = Array.isArray(entries)
|
|
372
|
+
? entries.slice().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
|
373
|
+
: []
|
|
374
|
+
|
|
375
|
+
// #3206 / #3296: one-level recursive walk under community/.
|
|
376
|
+
// Each string entry in `entries` is a basename relative to `dir`. After the
|
|
377
|
+
// top-level sort, augment the list with entries discovered under any
|
|
378
|
+
// `community/<author>/` subdirectory. Community entries are represented as
|
|
379
|
+
// objects `{ entry: basename, fullPath: string }` (vs plain strings for
|
|
380
|
+
// top-level entries) so both loops below can reconstruct the correct path and
|
|
381
|
+
// name stem without confusing the two forms.
|
|
382
|
+
//
|
|
383
|
+
// Walk depth: one level under each author dir. Files at
|
|
384
|
+
// `<root>/community/<author>/sub/y.md` are NOT discovered (v1 cap).
|
|
385
|
+
//
|
|
386
|
+
// The SKIP_DIRECTORY_NAMES guard is applied to both the `community/` dir
|
|
387
|
+
// itself and each author-level subdir to mirror the top-level entry filter.
|
|
388
|
+
for (const entry of entries) {
|
|
389
|
+
if (typeof entry !== 'string') continue
|
|
390
|
+
const entryCmp = _PATH_COMPARE_CASE_INSENSITIVE ? entry.toLowerCase() : entry
|
|
391
|
+
if (entryCmp !== 'community') continue
|
|
392
|
+
// `entry` is the (case-normalized) string 'community'. Verify it is
|
|
393
|
+
// actually a directory (not a file named 'community.md' would never reach
|
|
394
|
+
// here, but a file named 'community' might).
|
|
395
|
+
const communityPath = join(dir, entry)
|
|
396
|
+
let communityDirSt
|
|
397
|
+
try {
|
|
398
|
+
communityDirSt = statSync(communityPath)
|
|
399
|
+
} catch {
|
|
400
|
+
continue
|
|
401
|
+
}
|
|
402
|
+
if (!communityDirSt.isDirectory()) continue
|
|
403
|
+
// Read the author-level subdirectories. Sort to match the top-level
|
|
404
|
+
// alphabetical order (#3302) — readdirSync return order is filesystem-
|
|
405
|
+
// dependent, and without this sort the tier-budget cutoff during the
|
|
406
|
+
// community walk could admit a different set of skills across runs on
|
|
407
|
+
// the same machine when name-collision tiebreaks fall back to insertion
|
|
408
|
+
// order.
|
|
409
|
+
let authorEntries
|
|
410
|
+
try {
|
|
411
|
+
authorEntries = readdirSync(communityPath).sort()
|
|
412
|
+
} catch {
|
|
413
|
+
continue
|
|
414
|
+
}
|
|
415
|
+
for (const authorEntry of authorEntries) {
|
|
416
|
+
if (typeof authorEntry !== 'string' || !authorEntry) continue
|
|
417
|
+
// Hidden author dirs (e.g. `.alice`) are not valid community namespaces.
|
|
418
|
+
if (authorEntry.startsWith('.')) continue
|
|
419
|
+
if (SKIP_DIRECTORY_NAMES.has(authorEntry)) continue
|
|
420
|
+
const authorPath = join(communityPath, authorEntry)
|
|
421
|
+
let authorSt
|
|
422
|
+
try {
|
|
423
|
+
authorSt = statSync(authorPath)
|
|
424
|
+
} catch {
|
|
425
|
+
continue
|
|
426
|
+
}
|
|
427
|
+
if (!authorSt.isDirectory()) continue
|
|
428
|
+
// Walk one level inside the author dir. Sort for the same reason as
|
|
429
|
+
// authorEntries above (#3302): keep the budget cutoff deterministic
|
|
430
|
+
// even if readdirSync returns files in an unstable order.
|
|
431
|
+
let authorFiles
|
|
432
|
+
try {
|
|
433
|
+
authorFiles = readdirSync(authorPath).sort()
|
|
434
|
+
} catch {
|
|
435
|
+
continue
|
|
436
|
+
}
|
|
437
|
+
for (const fileEntry of authorFiles) {
|
|
438
|
+
if (typeof fileEntry !== 'string' || !fileEntry) continue
|
|
439
|
+
if (SKIP_DIRECTORY_NAMES.has(fileEntry)) continue
|
|
440
|
+
// Inject as an object so the per-entry loop can distinguish it from
|
|
441
|
+
// top-level string entries and compute the full path correctly.
|
|
442
|
+
entries.push({ entry: fileEntry, fullPath: join(authorPath, fileEntry) })
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
// Only one 'community' directory can exist at the top level; stop after
|
|
446
|
+
// finding it.
|
|
447
|
+
break
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// ── Two-pass priority-aware path (#3279) ──
|
|
451
|
+
// When a tier budget is set, run _collectCandidates (pass 1) to gather a
|
|
452
|
+
// lightweight descriptor for every validated candidate, then sort by
|
|
453
|
+
// priority and walk in priority order (pass 2) to read full bodies. Skills
|
|
454
|
+
// that don't fit the budget are skipped with `continue` (not `break`) so a
|
|
455
|
+
// smaller later-priority skill can still slip in — preserving the existing
|
|
456
|
+
// "smaller-later-fits" semantic from the alphabetical path.
|
|
457
|
+
if (tierBudget !== null) {
|
|
458
|
+
const candidates = _collectCandidates(
|
|
459
|
+
entries, dir, dirReal, allowedRoots, allowedExtensions, maxSkillBytes, parseCache,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
// Sort by priority desc, name asc for deterministic tiebreaking.
|
|
463
|
+
// _compareByPriorityThenName expects { name, metadata: { priority } };
|
|
464
|
+
// candidate.name is the pre-computed stem (without extension) so the
|
|
465
|
+
// alphabetical tiebreak matches _enforceTotalBudget exactly. Using the
|
|
466
|
+
// stem (rather than the full entry filename) avoids the '.' vs '-' ASCII
|
|
467
|
+
// ordering inversion: "abc-extra.md" < "abc.md" by full filename (since
|
|
468
|
+
// '-' 0x2D < '.' 0x2E), but "abc" < "abc-extra" by stem — same pair,
|
|
469
|
+
// opposite winner. Storing the stem on the descriptor in _collectCandidates
|
|
470
|
+
// keeps both sort sites in sync with a single source of truth.
|
|
471
|
+
candidates.sort((a, b) => _compareByPriorityThenName(
|
|
472
|
+
{ name: a.name, metadata: { priority: a.priority } },
|
|
473
|
+
{ name: b.name, metadata: { priority: b.priority } },
|
|
474
|
+
))
|
|
475
|
+
// Micro-optimization (deferred): when sum(fstat.size) <= tierBudget we
|
|
476
|
+
// know all candidates fit and the priority sort above is wasted work.
|
|
477
|
+
// Worth ~5ms cold-start on a 50-skill directory. Deferred until
|
|
478
|
+
// benchmarks justify it; parseCache absorbs the per-skill partial-read
|
|
479
|
+
// cost on every subsequent session anyway.
|
|
480
|
+
|
|
481
|
+
const skills = []
|
|
482
|
+
let tierTotalBytes = 0
|
|
483
|
+
|
|
484
|
+
for (const candidate of candidates) {
|
|
485
|
+
const { name, fullPath, label, realPath, fstat: fstatSnap, cachedFrontmatter } = candidate
|
|
486
|
+
|
|
487
|
+
// Pre-read tier budget check. `continue` (not `break`) so smaller
|
|
488
|
+
// lower-priority skills can still fit if they come after a large one.
|
|
489
|
+
if (typeof fstatSnap.size === 'number' && tierTotalBytes + fstatSnap.size > tierBudget) {
|
|
490
|
+
log.warn(`Skipping skill ${label}: tier budget reached (${tierTotalBytes + fstatSnap.size} > ${tierBudget})`)
|
|
491
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
492
|
+
continue
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Cache fast path: if pass 1 recorded a fresh cache hit, we can skip
|
|
496
|
+
// re-opening the file entirely and use all cached parse fields.
|
|
497
|
+
if (cachedFrontmatter) {
|
|
498
|
+
const { frontmatter, finalBody, description } = cachedFrontmatter
|
|
499
|
+
|
|
500
|
+
if (!includeAllProviders && !_skillMatchesProvider(frontmatter, provider)) continue
|
|
501
|
+
|
|
502
|
+
const isActive = _skillIsActive(frontmatter, name, activeManualSkills)
|
|
503
|
+
if (!isActive && !includeInactive) continue
|
|
504
|
+
|
|
505
|
+
// Account for the cached body in the tier total — mirroring the
|
|
506
|
+
// cache-miss path which also counts bytes only after the provider and
|
|
507
|
+
// activation gates pass. Counting before the gates would let a warm
|
|
508
|
+
// cache shrink the effective budget for subsequent skills even when
|
|
509
|
+
// a skill is ultimately skipped due to provider mismatch or inactivity.
|
|
510
|
+
tierTotalBytes += fstatSnap.size
|
|
511
|
+
|
|
512
|
+
if (!isActive) {
|
|
513
|
+
const inactive = { name, description, metadata: frontmatter, active: false, path: realPath }
|
|
514
|
+
if (source) inactive.source = source
|
|
515
|
+
skills.push(inactive)
|
|
516
|
+
continue
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// #3206 / #3296: community-namespace gate (cache fast path).
|
|
520
|
+
const { isCommunity: isCommunityC, author: communityAuthorC } = _isCommunityNamespace(realPath, dirReal)
|
|
521
|
+
let communityTrustStateC = null
|
|
522
|
+
if (isCommunityC) {
|
|
523
|
+
const trustedC = communityTrustChecker
|
|
524
|
+
? !!communityTrustChecker(realPath, communityAuthorC)
|
|
525
|
+
: true
|
|
526
|
+
if (!trustedC) {
|
|
527
|
+
communityTrustStateC = 'pending'
|
|
528
|
+
if (onCommunityTrustPending) {
|
|
529
|
+
try {
|
|
530
|
+
onCommunityTrustPending({ name, author: communityAuthorC, source: source || null, description, path: realPath })
|
|
531
|
+
} catch (err) {
|
|
532
|
+
log.warn(`onCommunityTrustPending callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (!includeInactive) continue
|
|
536
|
+
const pending = {
|
|
537
|
+
name, description, metadata: frontmatter, active: false, path: realPath,
|
|
538
|
+
trustState: 'pending', communityAuthor: communityAuthorC,
|
|
539
|
+
}
|
|
540
|
+
if (source) pending.source = source
|
|
541
|
+
skills.push(pending)
|
|
542
|
+
continue
|
|
543
|
+
}
|
|
544
|
+
communityTrustStateC = 'trusted'
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const injectionMode = _resolveInjectionMode(frontmatter, defaultInjectionMode)
|
|
548
|
+
|
|
549
|
+
if (trustStore && typeof trustStore.inspect === 'function') {
|
|
550
|
+
let inspectResult
|
|
551
|
+
try {
|
|
552
|
+
inspectResult = trustStore.inspect(realPath, finalBody)
|
|
553
|
+
} catch (err) {
|
|
554
|
+
log.warn(`Skill ${label}: trust inspect threw (${getErrorMessage(err, err)}); allowing skill`)
|
|
555
|
+
inspectResult = null
|
|
556
|
+
}
|
|
557
|
+
if (inspectResult && inspectResult.status === 'mismatch') {
|
|
558
|
+
if (onTrustMismatch) {
|
|
559
|
+
try {
|
|
560
|
+
onTrustMismatch({
|
|
561
|
+
name, source: source || null, path: realPath,
|
|
562
|
+
oldHash: inspectResult.oldHash, newHash: inspectResult.newHash,
|
|
563
|
+
blocked: !!inspectResult.blocked, mode: trustStore.mode,
|
|
564
|
+
})
|
|
565
|
+
} catch (err) {
|
|
566
|
+
log.warn(`onTrustMismatch callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (inspectResult.blocked) {
|
|
570
|
+
log.warn(`Skipping skill ${label}: trust mismatch in block mode`)
|
|
571
|
+
continue
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const skill = { name, body: finalBody, description, metadata: frontmatter, injectionMode }
|
|
577
|
+
if (source) skill.source = source
|
|
578
|
+
skill.active = isActive
|
|
579
|
+
skill.path = realPath
|
|
580
|
+
if (communityTrustStateC !== null) {
|
|
581
|
+
skill.trustState = communityTrustStateC
|
|
582
|
+
skill.communityAuthor = communityAuthorC
|
|
583
|
+
}
|
|
584
|
+
skills.push(skill)
|
|
585
|
+
continue
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// Cache miss: re-open, re-validate (TOCTOU defense), read full body.
|
|
589
|
+
// Re-opening here is intentional — holding an fd open across pass 1's
|
|
590
|
+
// full scan would risk exhausting the fd limit on large directories.
|
|
591
|
+
// The TOCTOU window between passes is detected by comparing dev+ino
|
|
592
|
+
// from the fresh fstatSync against the values recorded in pass 1.
|
|
593
|
+
let fd2
|
|
594
|
+
try {
|
|
595
|
+
fd2 = openSync(fullPath, 'r')
|
|
596
|
+
} catch (err) {
|
|
597
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
598
|
+
log.warn(`Skipping skill ${label}: open failed (${code})`)
|
|
599
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
600
|
+
continue
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
try {
|
|
604
|
+
let fstat2
|
|
605
|
+
try {
|
|
606
|
+
fstat2 = fstatSync(fd2)
|
|
607
|
+
} catch {
|
|
608
|
+
continue
|
|
609
|
+
}
|
|
610
|
+
if (!fstat2.isFile()) continue
|
|
611
|
+
|
|
612
|
+
if (typeof fstat2.size === 'number' && fstat2.size > maxSkillBytes) {
|
|
613
|
+
log.warn(`Skipping skill ${label}: size ${fstat2.size} exceeds per-skill cap ${maxSkillBytes}`)
|
|
614
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
615
|
+
continue
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Re-validate realpath in case a symlink was swapped between passes.
|
|
619
|
+
let realPath2
|
|
620
|
+
try {
|
|
621
|
+
realPath2 = realpathSync(fullPath)
|
|
622
|
+
} catch (err) {
|
|
623
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
624
|
+
log.warn(`Skipping skill ${label}: realpath failed (${code})`)
|
|
625
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
626
|
+
continue
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// Symlink swap detection: if the resolved path drifted since pass 1,
|
|
630
|
+
// skip this candidate — we validated a different path.
|
|
631
|
+
if (realPath2 !== realPath) {
|
|
632
|
+
log.warn(`Skipping skill ${label}: realPath drifted between passes (possible symlink swap)`)
|
|
633
|
+
log.debug(`skill ${label} pass-1 realPath: ${realPath}, pass-2 realPath: ${realPath2}`)
|
|
634
|
+
continue
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// #3218: dev+ino re-check with the fresh fd — catches any swap
|
|
638
|
+
// that occurred after pass 1 closed its fd.
|
|
639
|
+
let realStat2
|
|
640
|
+
try {
|
|
641
|
+
realStat2 = statSync(realPath2)
|
|
642
|
+
} catch {
|
|
643
|
+
continue
|
|
644
|
+
}
|
|
645
|
+
if (fstat2.dev !== realStat2.dev || fstat2.ino !== realStat2.ino) {
|
|
646
|
+
log.warn(`Skipping skill ${label}: fd inode does not match validated real path (TOCTOU swap detected)`)
|
|
647
|
+
log.debug(`skill ${label} full path: ${fullPath} fd ino=${fstat2.ino} realPath ino=${realStat2.ino}`)
|
|
648
|
+
continue
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// Also verify the pass-1 inode snapshot matches the pass-2 fstat.
|
|
652
|
+
// If the file was replaced between passes, this catches it even when
|
|
653
|
+
// the dev+ino re-check above passes (e.g. same device, recycled inode).
|
|
654
|
+
if (fstat2.dev !== fstatSnap.dev || fstat2.ino !== fstatSnap.ino) {
|
|
655
|
+
log.warn(`Skipping skill ${label}: inode changed between pass 1 and pass 2 (file replaced)`)
|
|
656
|
+
log.debug(`skill ${label} full path: ${fullPath} pass1 ino=${fstatSnap.ino} pass2 ino=${fstat2.ino}`)
|
|
657
|
+
continue
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
let body
|
|
661
|
+
let frontmatter
|
|
662
|
+
let finalBody
|
|
663
|
+
let description
|
|
664
|
+
|
|
665
|
+
// Check cache again with the fresh fstat — the file may have been
|
|
666
|
+
// cached between pass 1 and pass 2 by another call site (edge case).
|
|
667
|
+
const cached2 = parseCache?.get(realPath2)
|
|
668
|
+
const cacheHit2 = cached2
|
|
669
|
+
&& typeof fstat2.mtimeMs === 'number'
|
|
670
|
+
&& cached2.mtimeMs === fstat2.mtimeMs
|
|
671
|
+
&& cached2.size === fstat2.size
|
|
672
|
+
|
|
673
|
+
if (cacheHit2) {
|
|
674
|
+
body = cached2.body
|
|
675
|
+
frontmatter = cached2.frontmatter
|
|
676
|
+
finalBody = cached2.finalBody
|
|
677
|
+
description = cached2.description
|
|
678
|
+
tierTotalBytes += fstat2.size
|
|
679
|
+
} else {
|
|
680
|
+
let buf
|
|
681
|
+
try {
|
|
682
|
+
buf = readFileSync(fd2)
|
|
683
|
+
} catch {
|
|
684
|
+
continue
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
if (buf.length > maxSkillBytes) {
|
|
688
|
+
log.warn(`Skipping skill ${label}: size ${buf.length} exceeds per-skill cap ${maxSkillBytes}`)
|
|
689
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
690
|
+
continue
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
tierTotalBytes += buf.length
|
|
694
|
+
|
|
695
|
+
if (!_bufferLooksLikeText(buf)) {
|
|
696
|
+
log.warn(`Skipping skill ${label}: content does not look like text (NUL or control byte)`)
|
|
697
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
698
|
+
continue
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
body = buf.toString('utf8')
|
|
702
|
+
const parsed = parseFrontmatter(body)
|
|
703
|
+
frontmatter = parsed.frontmatter
|
|
704
|
+
finalBody = parsed.frontmatter !== null ? parsed.body : body
|
|
705
|
+
description = _firstNonEmptyLine(finalBody) || name
|
|
706
|
+
|
|
707
|
+
if (parseCache && typeof fstat2.mtimeMs === 'number') {
|
|
708
|
+
parseCache.set(realPath2, {
|
|
709
|
+
mtimeMs: fstat2.mtimeMs,
|
|
710
|
+
size: fstat2.size,
|
|
711
|
+
body,
|
|
712
|
+
frontmatter,
|
|
713
|
+
finalBody,
|
|
714
|
+
description,
|
|
715
|
+
})
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
if (!includeAllProviders && !_skillMatchesProvider(frontmatter, provider)) continue
|
|
720
|
+
|
|
721
|
+
const isActive = _skillIsActive(frontmatter, name, activeManualSkills)
|
|
722
|
+
if (!isActive && !includeInactive) continue
|
|
723
|
+
if (!isActive) {
|
|
724
|
+
const inactive = { name, description, metadata: frontmatter, active: false, path: realPath2 }
|
|
725
|
+
if (source) inactive.source = source
|
|
726
|
+
skills.push(inactive)
|
|
727
|
+
continue
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// #3206 / #3296: community-namespace gate (two-pass cache-miss path).
|
|
731
|
+
const { isCommunity: isCommunityM, author: communityAuthorM } = _isCommunityNamespace(realPath2, dirReal)
|
|
732
|
+
let communityTrustStateM = null
|
|
733
|
+
if (isCommunityM) {
|
|
734
|
+
const trustedM = communityTrustChecker
|
|
735
|
+
? !!communityTrustChecker(realPath2, communityAuthorM)
|
|
736
|
+
: true
|
|
737
|
+
if (!trustedM) {
|
|
738
|
+
communityTrustStateM = 'pending'
|
|
739
|
+
if (onCommunityTrustPending) {
|
|
740
|
+
try {
|
|
741
|
+
onCommunityTrustPending({ name, author: communityAuthorM, source: source || null, description, path: realPath2 })
|
|
742
|
+
} catch (err) {
|
|
743
|
+
log.warn(`onCommunityTrustPending callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (!includeInactive) continue
|
|
747
|
+
const pending = {
|
|
748
|
+
name, description, metadata: frontmatter, active: false, path: realPath2,
|
|
749
|
+
trustState: 'pending', communityAuthor: communityAuthorM,
|
|
750
|
+
}
|
|
751
|
+
if (source) pending.source = source
|
|
752
|
+
skills.push(pending)
|
|
753
|
+
continue
|
|
754
|
+
}
|
|
755
|
+
communityTrustStateM = 'trusted'
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const injectionMode = _resolveInjectionMode(frontmatter, defaultInjectionMode)
|
|
759
|
+
|
|
760
|
+
if (trustStore && typeof trustStore.inspect === 'function') {
|
|
761
|
+
let inspectResult
|
|
762
|
+
try {
|
|
763
|
+
inspectResult = trustStore.inspect(realPath2, finalBody)
|
|
764
|
+
} catch (err) {
|
|
765
|
+
log.warn(`Skill ${label}: trust inspect threw (${getErrorMessage(err, err)}); allowing skill`)
|
|
766
|
+
inspectResult = null
|
|
767
|
+
}
|
|
768
|
+
if (inspectResult && inspectResult.status === 'mismatch') {
|
|
769
|
+
if (onTrustMismatch) {
|
|
770
|
+
try {
|
|
771
|
+
onTrustMismatch({
|
|
772
|
+
name, source: source || null, path: realPath2,
|
|
773
|
+
oldHash: inspectResult.oldHash, newHash: inspectResult.newHash,
|
|
774
|
+
blocked: !!inspectResult.blocked, mode: trustStore.mode,
|
|
775
|
+
})
|
|
776
|
+
} catch (err) {
|
|
777
|
+
log.warn(`onTrustMismatch callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (inspectResult.blocked) {
|
|
781
|
+
log.warn(`Skipping skill ${label}: trust mismatch in block mode`)
|
|
782
|
+
continue
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const skill = { name, body: finalBody, description, metadata: frontmatter, injectionMode }
|
|
788
|
+
if (source) skill.source = source
|
|
789
|
+
skill.active = isActive
|
|
790
|
+
skill.path = realPath2
|
|
791
|
+
if (communityTrustStateM !== null) {
|
|
792
|
+
skill.trustState = communityTrustStateM
|
|
793
|
+
skill.communityAuthor = communityAuthorM
|
|
794
|
+
}
|
|
795
|
+
skills.push(skill)
|
|
796
|
+
} finally {
|
|
797
|
+
try { closeSync(fd2) } catch { /* non-fatal */ }
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
skills.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
802
|
+
return skills
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// ── Single-pass alphabetical loop (back-compat when tierBudget === null) ──
|
|
806
|
+
// This path is unchanged from the pre-#3279 implementation. Callers that
|
|
807
|
+
// do not pass `maxTotalBytes` continue to get exactly the prior behaviour
|
|
808
|
+
// (no priority awareness, no frontmatter pre-read, alphabetical order).
|
|
809
|
+
const skills = []
|
|
810
|
+
for (const rawEntry of entries) {
|
|
811
|
+
// Each element is either:
|
|
812
|
+
// string — top-level basename (fullPath = join(dir, entry))
|
|
813
|
+
// object { entry: basename, fullPath: string } — community entry
|
|
814
|
+
let entry, fullPath
|
|
815
|
+
if (typeof rawEntry === 'string') {
|
|
816
|
+
if (!rawEntry) continue
|
|
817
|
+
if (SKIP_DIRECTORY_NAMES.has(rawEntry)) continue
|
|
818
|
+
entry = rawEntry
|
|
819
|
+
fullPath = join(dir, entry)
|
|
820
|
+
} else if (rawEntry && typeof rawEntry === 'object' && typeof rawEntry.entry === 'string') {
|
|
821
|
+
entry = rawEntry.entry
|
|
822
|
+
fullPath = rawEntry.fullPath
|
|
823
|
+
} else {
|
|
824
|
+
continue
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// Extract extension and reject anything outside the allowlist before we
|
|
828
|
+
// touch the file. This also catches `.md` vs `.MD` consistently.
|
|
829
|
+
const dotIdx = entry.lastIndexOf('.')
|
|
830
|
+
if (dotIdx <= 0) continue
|
|
831
|
+
const ext = entry.slice(dotIdx + 1).toLowerCase()
|
|
832
|
+
if (!allowedExtensions.has(ext)) continue
|
|
833
|
+
|
|
834
|
+
// Disabled-suffix check: per allowed extension, treat `*.disabled.<ext>`
|
|
835
|
+
// as off. We keep the historical `.disabled.md` shape verbatim for `md`
|
|
836
|
+
// and generalize for any other allowed extension.
|
|
837
|
+
if (entry.endsWith(`.disabled.${ext}`)) continue
|
|
838
|
+
|
|
839
|
+
const label = _pathLabel(fullPath)
|
|
840
|
+
|
|
841
|
+
// statSync FOLLOWS symlinks — that's intentional here. We just need to
|
|
842
|
+
// gate out non-files (dirs, sockets, devices). The realpath check below
|
|
843
|
+
// is the actual symlink-escape defense; it operates on the resolved
|
|
844
|
+
// target, so a symlink that points at /etc/passwd is rejected there.
|
|
845
|
+
let st
|
|
846
|
+
try {
|
|
847
|
+
st = statSync(fullPath)
|
|
848
|
+
} catch {
|
|
849
|
+
continue
|
|
850
|
+
}
|
|
851
|
+
if (!st.isFile()) continue
|
|
852
|
+
|
|
853
|
+
// Per-skill size cap (#3202). Stat already followed the symlink, so the
|
|
854
|
+
// size we're checking is the size of the underlying file.
|
|
855
|
+
if (typeof st.size === 'number' && st.size > maxSkillBytes) {
|
|
856
|
+
log.warn(`Skipping skill ${label}: size ${st.size} exceeds per-skill cap ${maxSkillBytes}`)
|
|
857
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
858
|
+
continue
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// #3218: open the file ONCE and read all subsequent bytes via the fd
|
|
862
|
+
// to close the TOCTOU window between realpathSync and the body read.
|
|
863
|
+
// Without this, a local attacker could swap the file at `fullPath`
|
|
864
|
+
// (or somewhere on its symlink chain) between the realpath check and
|
|
865
|
+
// the readFileSync, and the loader would happily ingest the swapped
|
|
866
|
+
// bytes despite the validated path. Opening once at check-time
|
|
867
|
+
// pins the inode for the lifetime of this iteration.
|
|
868
|
+
let fd
|
|
869
|
+
try {
|
|
870
|
+
fd = openSync(fullPath, 'r')
|
|
871
|
+
} catch (err) {
|
|
872
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
873
|
+
log.warn(`Skipping skill ${label}: open failed (${code})`)
|
|
874
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
875
|
+
continue
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
try {
|
|
879
|
+
// Confirm the open fd refers to a regular file. statSync above used
|
|
880
|
+
// path-based stat which a swap could invalidate; fstatSync inspects
|
|
881
|
+
// the inode our fd has pinned.
|
|
882
|
+
let fstat
|
|
883
|
+
try {
|
|
884
|
+
fstat = fstatSync(fd)
|
|
885
|
+
} catch {
|
|
886
|
+
continue
|
|
887
|
+
}
|
|
888
|
+
if (!fstat.isFile()) continue
|
|
889
|
+
|
|
890
|
+
// Re-check the per-skill size cap against the pinned inode. If the
|
|
891
|
+
// file grew between the path stat and our open, fstatSync sees the
|
|
892
|
+
// current size and we still reject anything over budget.
|
|
893
|
+
if (typeof fstat.size === 'number' && fstat.size > maxSkillBytes) {
|
|
894
|
+
log.warn(`Skipping skill ${label}: size ${fstat.size} exceeds per-skill cap ${maxSkillBytes}`)
|
|
895
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
896
|
+
continue
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// Symlink defense: resolve to the real path and confirm it lives
|
|
900
|
+
// inside an allowed root. realpathSync still operates on the path
|
|
901
|
+
// (the only inputs Node gives us), so a path-side swap could in
|
|
902
|
+
// theory return a different realPath than the inode we have open.
|
|
903
|
+
// The fd-based read below means an attacker who races would get
|
|
904
|
+
// their `realPath` validated against an `allowedRoots` containment
|
|
905
|
+
// check, but the bytes we read still come from the originally-opened
|
|
906
|
+
// inode — they don't get to substitute content.
|
|
907
|
+
let realPath
|
|
908
|
+
try {
|
|
909
|
+
realPath = realpathSync(fullPath)
|
|
910
|
+
} catch (err) {
|
|
911
|
+
// Node's realpathSync errors interpolate the offending path into
|
|
912
|
+
// `err.message` (e.g. ENOENT 'no such file or directory, lstat ...').
|
|
913
|
+
// log.warn fans out via log_entry to paired WS clients — same leak
|
|
914
|
+
// channel addressed by #3215. Strip to the error code only; full
|
|
915
|
+
// path is logged separately at debug.
|
|
916
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
917
|
+
log.warn(`Skipping skill ${label}: realpath failed (${code})`)
|
|
918
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
919
|
+
continue
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const inAllowedRoot = allowedRoots.some((root) => _pathContains(root, realPath))
|
|
923
|
+
if (!inAllowedRoot) {
|
|
924
|
+
log.warn(`Skipping skill ${label}: real path escapes skills root`)
|
|
925
|
+
log.debug(`skill ${label} full path: ${fullPath} resolved to ${realPath}, root ${dirReal}`)
|
|
926
|
+
continue
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// #3218 (review): inode-bind the open fd to the validated realPath.
|
|
930
|
+
// Without this, a swap during the window
|
|
931
|
+
// openSync(fullPath) → fd pinned to attacker-chosen inode
|
|
932
|
+
// realpathSync(fullPath) → resolves to a now-allowed path
|
|
933
|
+
// would let an attacker trick the loader into reading bytes from
|
|
934
|
+
// an out-of-tree inode while the path-side check approves an
|
|
935
|
+
// in-tree realPath. Comparing dev+ino between fstat (the inode
|
|
936
|
+
// we have open) and statSync(realPath) (the inode the validated
|
|
937
|
+
// path now resolves to) catches this exact case: if they don't
|
|
938
|
+
// match, the fd is pointing at something other than what we
|
|
939
|
+
// validated, and we skip.
|
|
940
|
+
let realStat
|
|
941
|
+
try {
|
|
942
|
+
realStat = statSync(realPath)
|
|
943
|
+
} catch {
|
|
944
|
+
// realPath disappeared between realpathSync and statSync — abort.
|
|
945
|
+
continue
|
|
946
|
+
}
|
|
947
|
+
if (fstat.dev !== realStat.dev || fstat.ino !== realStat.ino) {
|
|
948
|
+
log.warn(`Skipping skill ${label}: fd inode does not match validated real path (TOCTOU swap detected)`)
|
|
949
|
+
log.debug(`skill ${label} full path: ${fullPath} fd ino=${fstat.ino} realPath ino=${realStat.ino}`)
|
|
950
|
+
continue
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// Strip the matching extension (case-preserving) when computing the
|
|
954
|
+
// display name. We checked the lower-cased suffix above, so trim the
|
|
955
|
+
// same number of chars (+1 for the dot).
|
|
956
|
+
const name = entry.slice(0, -(ext.length + 1))
|
|
957
|
+
|
|
958
|
+
// #3248: parse-cache fast path. fstatSync above gave us the
|
|
959
|
+
// post-open file's mtime+size; if the cache entry's mtimeMs+size
|
|
960
|
+
// match, skip readFileSync / text-validation / parseFrontmatter
|
|
961
|
+
// and reuse the cached parse. Mismatch (or no entry) falls
|
|
962
|
+
// through to the full read+parse path below. #3218: keying on
|
|
963
|
+
// fstat (not the path-side statSync done before openSync) means
|
|
964
|
+
// a swap-during-realpath can't yield a false cache-hit on the
|
|
965
|
+
// original mtimeMs.
|
|
966
|
+
let body
|
|
967
|
+
let frontmatter
|
|
968
|
+
let finalBody
|
|
969
|
+
let description
|
|
970
|
+
const cached = parseCache?.get(realPath)
|
|
971
|
+
const cacheHit = cached
|
|
972
|
+
&& typeof fstat.mtimeMs === 'number'
|
|
973
|
+
&& cached.mtimeMs === fstat.mtimeMs
|
|
974
|
+
&& cached.size === fstat.size
|
|
975
|
+
|
|
976
|
+
if (cacheHit) {
|
|
977
|
+
body = cached.body
|
|
978
|
+
frontmatter = cached.frontmatter
|
|
979
|
+
finalBody = cached.finalBody
|
|
980
|
+
description = cached.description
|
|
981
|
+
} else {
|
|
982
|
+
// #3218: read from the open fd, not from the path. The fd is
|
|
983
|
+
// pinned to the inode we already validated above.
|
|
984
|
+
let buf
|
|
985
|
+
try {
|
|
986
|
+
buf = readFileSync(fd)
|
|
987
|
+
} catch {
|
|
988
|
+
continue
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
if (buf.length > maxSkillBytes) {
|
|
992
|
+
log.warn(`Skipping skill ${label}: size ${buf.length} exceeds per-skill cap ${maxSkillBytes}`)
|
|
993
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
994
|
+
continue
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
if (!_bufferLooksLikeText(buf)) {
|
|
998
|
+
log.warn(`Skipping skill ${label}: content does not look like text (NUL or control byte)`)
|
|
999
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
1000
|
+
continue
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
body = buf.toString('utf8')
|
|
1004
|
+
|
|
1005
|
+
// Parse YAML frontmatter (#3197). Failures are non-fatal — the body
|
|
1006
|
+
// is returned unchanged and metadata is null. Every Skill carries a
|
|
1007
|
+
// `metadata` field for forward compatibility, even when null.
|
|
1008
|
+
const parsed = parseFrontmatter(body)
|
|
1009
|
+
frontmatter = parsed.frontmatter
|
|
1010
|
+
finalBody = parsed.frontmatter !== null ? parsed.body : body
|
|
1011
|
+
description = _firstNonEmptyLine(finalBody) || name
|
|
1012
|
+
|
|
1013
|
+
// Populate the cache for next time. Stamp from fstat (post-open)
|
|
1014
|
+
// so the cached entry reflects the inode we actually read.
|
|
1015
|
+
if (parseCache && typeof fstat.mtimeMs === 'number') {
|
|
1016
|
+
parseCache.set(realPath, {
|
|
1017
|
+
mtimeMs: fstat.mtimeMs,
|
|
1018
|
+
size: fstat.size,
|
|
1019
|
+
body,
|
|
1020
|
+
frontmatter,
|
|
1021
|
+
finalBody,
|
|
1022
|
+
description,
|
|
1023
|
+
})
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// Provider gating (#3198): if frontmatter declares a `providers:` list,
|
|
1028
|
+
// include the skill only when the session's provider is in it. Missing
|
|
1029
|
+
// / empty list means apply-to-all, preserving v1 back-compat.
|
|
1030
|
+
// #3226: `includeAllProviders` (set by the dashboard's `list_skills`
|
|
1031
|
+
// fallback) bypasses this gate so the operator's "browse all
|
|
1032
|
+
// installed skills" view doesn't silently drop scoped entries.
|
|
1033
|
+
if (!includeAllProviders && !_skillMatchesProvider(frontmatter, provider)) continue
|
|
1034
|
+
|
|
1035
|
+
// #3206 / #3296: community-namespace detection. Resolved early — before
|
|
1036
|
+
// the activation gate — so that inactive-manual community skills also
|
|
1037
|
+
// receive trustState/communityAuthor in the includeInactive path. The
|
|
1038
|
+
// trust-checker call (and onCommunityTrustPending callback) is deferred
|
|
1039
|
+
// to after the activation check: it only fires for active skills, keeping
|
|
1040
|
+
// the existing semantics that inactive skills skip trust inspection.
|
|
1041
|
+
const { isCommunity, author: communityAuthor } = _isCommunityNamespace(realPath, dirReal)
|
|
1042
|
+
|
|
1043
|
+
// Manual activation (#3199): skills with `activation: manual` are off
|
|
1044
|
+
// by default and require explicit opt-in via `activeManualSkills`.
|
|
1045
|
+
// #3209: `includeInactive` keeps inactive manual skills in the
|
|
1046
|
+
// result so the dashboard can render toggles for them; they are
|
|
1047
|
+
// tagged with `active: false` and the trust-hash branch is
|
|
1048
|
+
// skipped (the skill body never reaches the prompt, so a hash
|
|
1049
|
+
// mismatch on an inactive skill is meaningless to the operator
|
|
1050
|
+
// until they actually activate it).
|
|
1051
|
+
const isActive = _skillIsActive(frontmatter, name, activeManualSkills)
|
|
1052
|
+
if (!isActive && !includeInactive) continue
|
|
1053
|
+
if (!isActive) {
|
|
1054
|
+
// Minimal metadata-only entry. Don't include `body` because the
|
|
1055
|
+
// dashboard only needs name + description + metadata to render
|
|
1056
|
+
// the toggle, and shipping the body to the WS client when the
|
|
1057
|
+
// skill is inactive wastes bandwidth.
|
|
1058
|
+
// Include community fields so the dashboard can render trust-grant
|
|
1059
|
+
// affordances for inactive-manual community skills too.
|
|
1060
|
+
const inactive = { name, description, metadata: frontmatter, active: false, path: realPath }
|
|
1061
|
+
if (isCommunity) {
|
|
1062
|
+
inactive.communityAuthor = communityAuthor
|
|
1063
|
+
inactive.trustState = communityTrustChecker
|
|
1064
|
+
? (communityTrustChecker(realPath, communityAuthor) ? 'trusted' : 'pending')
|
|
1065
|
+
: 'trusted' // fail-open when no checker (trust-disabled session)
|
|
1066
|
+
}
|
|
1067
|
+
if (source) inactive.source = source
|
|
1068
|
+
skills.push(inactive)
|
|
1069
|
+
continue
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// #3206 / #3296: community-namespace trust gate. Runs after the activation
|
|
1073
|
+
// check but BEFORE trustStore.inspect(). For skills under
|
|
1074
|
+
// <root>/community/<author>/, the communityTrustChecker decides whether
|
|
1075
|
+
// the author is trusted or pending. Pending skills bypass inspect()
|
|
1076
|
+
// entirely — they're never injected into prompts until first-activation
|
|
1077
|
+
// consent is granted (PR B wires the trust-grant WS flow).
|
|
1078
|
+
// NOTE: isCommunity/communityAuthor already resolved above.
|
|
1079
|
+
let communityTrustState = null
|
|
1080
|
+
if (isCommunity) {
|
|
1081
|
+
const trusted = communityTrustChecker
|
|
1082
|
+
? !!communityTrustChecker(realPath, communityAuthor)
|
|
1083
|
+
: true // fail-open when no checker (trust-disabled session)
|
|
1084
|
+
if (!trusted) {
|
|
1085
|
+
communityTrustState = 'pending'
|
|
1086
|
+
if (onCommunityTrustPending) {
|
|
1087
|
+
try {
|
|
1088
|
+
onCommunityTrustPending({ name, author: communityAuthor, source: source || null, description, path: realPath })
|
|
1089
|
+
} catch (err) {
|
|
1090
|
+
log.warn(`onCommunityTrustPending callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (!includeInactive) continue
|
|
1094
|
+
// includeInactive path: surface the skill so the dashboard can
|
|
1095
|
+
// render a trust-grant affordance. No body — same as inactive
|
|
1096
|
+
// manual skills above.
|
|
1097
|
+
const pending = {
|
|
1098
|
+
name,
|
|
1099
|
+
description,
|
|
1100
|
+
metadata: frontmatter,
|
|
1101
|
+
active: false,
|
|
1102
|
+
path: realPath,
|
|
1103
|
+
trustState: 'pending',
|
|
1104
|
+
communityAuthor,
|
|
1105
|
+
}
|
|
1106
|
+
if (source) pending.source = source
|
|
1107
|
+
skills.push(pending)
|
|
1108
|
+
continue
|
|
1109
|
+
}
|
|
1110
|
+
communityTrustState = 'trusted'
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// Resolve the per-skill injection mode (#3200). Fall through to the
|
|
1114
|
+
// caller-supplied default (typically the provider's preferred channel)
|
|
1115
|
+
// when the skill doesn't pin a mode itself or pins something we don't
|
|
1116
|
+
// recognise — typo tolerance.
|
|
1117
|
+
const injectionMode = _resolveInjectionMode(frontmatter, defaultInjectionMode)
|
|
1118
|
+
|
|
1119
|
+
// Trust hashing (#3204). The hash covers the post-frontmatter body —
|
|
1120
|
+
// changes to the body are what actually mutate the skill's runtime
|
|
1121
|
+
// behaviour, so frontmatter-only edits (renaming, switching activation
|
|
1122
|
+
// mode) don't trigger a mismatch every time. The trust-store inspect
|
|
1123
|
+
// call records a first-seen hash transparently; mismatches return a
|
|
1124
|
+
// mode-aware `blocked` flag that we honour here.
|
|
1125
|
+
if (trustStore && typeof trustStore.inspect === 'function') {
|
|
1126
|
+
let inspectResult
|
|
1127
|
+
try {
|
|
1128
|
+
inspectResult = trustStore.inspect(realPath, finalBody)
|
|
1129
|
+
} catch (err) {
|
|
1130
|
+
// Trust failures must never block legitimate skill loads — log
|
|
1131
|
+
// and fall through. The `inspect` implementation owns logging
|
|
1132
|
+
// for normal cases; this branch only fires if the implementor
|
|
1133
|
+
// throws unexpectedly.
|
|
1134
|
+
log.warn(`Skill ${label}: trust inspect threw (${getErrorMessage(err, err)}); allowing skill`)
|
|
1135
|
+
inspectResult = null
|
|
1136
|
+
}
|
|
1137
|
+
if (inspectResult && inspectResult.status === 'mismatch') {
|
|
1138
|
+
if (onTrustMismatch) {
|
|
1139
|
+
try {
|
|
1140
|
+
onTrustMismatch({
|
|
1141
|
+
name,
|
|
1142
|
+
source: source || null,
|
|
1143
|
+
path: realPath,
|
|
1144
|
+
oldHash: inspectResult.oldHash,
|
|
1145
|
+
newHash: inspectResult.newHash,
|
|
1146
|
+
blocked: !!inspectResult.blocked,
|
|
1147
|
+
// #3241: project the active trust mode directly from the store
|
|
1148
|
+
// rather than letting the normaliser reverse-engineer it from
|
|
1149
|
+
// `blocked`. Today the two coincide (only `block` mode sets
|
|
1150
|
+
// `blocked: true`); future modes (e.g. `block-once`,
|
|
1151
|
+
// `soft-block`) may filter the skill while still wanting their
|
|
1152
|
+
// own UX label on the wire.
|
|
1153
|
+
mode: trustStore.mode,
|
|
1154
|
+
})
|
|
1155
|
+
} catch (err) {
|
|
1156
|
+
// Callback errors are swallowed — they shouldn't change the
|
|
1157
|
+
// load outcome. Pure observer concern.
|
|
1158
|
+
log.warn(`onTrustMismatch callback threw for ${label}: ${getErrorMessage(err, err)}`)
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
if (inspectResult.blocked) {
|
|
1162
|
+
log.warn(`Skipping skill ${label}: trust mismatch in block mode`)
|
|
1163
|
+
continue
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const skill = { name, body: finalBody, description, metadata: frontmatter, injectionMode }
|
|
1169
|
+
if (source) skill.source = source
|
|
1170
|
+
// #3209: tag the skill so the dashboard can render the right
|
|
1171
|
+
// toggle state. `auto` skills are always active; `manual` ones
|
|
1172
|
+
// reflect the live `activeManualSkills` membership at load time.
|
|
1173
|
+
skill.active = isActive
|
|
1174
|
+
// #3205: realpath is needed by `list_skills` to look up the
|
|
1175
|
+
// trust-store record (recorded hash + lastVerified) without
|
|
1176
|
+
// re-reading the file. Stripped before the WS payload — the
|
|
1177
|
+
// absolute filesystem path never crosses the wire (operator-
|
|
1178
|
+
// facing log lines use basename via `_pathLabel`).
|
|
1179
|
+
skill.path = realPath
|
|
1180
|
+
// #3206 / #3296: community-namespace tags. Only set for skills that
|
|
1181
|
+
// are actually under community/<author>/. Non-community skills do not
|
|
1182
|
+
// carry these fields so the wire payload stays tight.
|
|
1183
|
+
if (communityTrustState !== null) {
|
|
1184
|
+
skill.trustState = communityTrustState
|
|
1185
|
+
skill.communityAuthor = communityAuthor
|
|
1186
|
+
}
|
|
1187
|
+
skills.push(skill)
|
|
1188
|
+
} finally {
|
|
1189
|
+
// #3218: always release the fd, even when `continue` short-circuits
|
|
1190
|
+
// any of the validation branches above. Node runs `finally` before
|
|
1191
|
+
// the `continue` takes effect, so this is leak-safe.
|
|
1192
|
+
try {
|
|
1193
|
+
closeSync(fd)
|
|
1194
|
+
} catch {
|
|
1195
|
+
// Already-closed fd or transient EBADF — non-fatal.
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
skills.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
1201
|
+
return skills
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* Pass 1 for the two-pass priority-aware tier budget (#3279).
|
|
1206
|
+
*
|
|
1207
|
+
* Two-pass design rationale
|
|
1208
|
+
* ─────────────────────────
|
|
1209
|
+
* Without a pre-pass, the only way to do a priority-aware per-tier cutoff
|
|
1210
|
+
* would be to read every skill body upfront and then sort — burning up to
|
|
1211
|
+
* `N × maxSkillBytes` of memory before any pruning. Instead:
|
|
1212
|
+
* Pass 1 (_collectCandidates): read only frontmatter (~4KB per skill) to
|
|
1213
|
+
* extract priority. Never holds more than one fd open. Returns unsorted
|
|
1214
|
+
* descriptors; caller sorts via _compareByPriorityThenName before the
|
|
1215
|
+
* pass-2 loop.
|
|
1216
|
+
* Pass 2 (caller): re-opens each candidate in priority order and reads the
|
|
1217
|
+
* full body, stopping once the tier budget is exhausted.
|
|
1218
|
+
* Peak in-memory skill body data is bounded at ~tierBudget per tier: the
|
|
1219
|
+
* per-tier read loop never accumulates more than `tierBudget` bytes of body
|
|
1220
|
+
* content. The parseCache is caller-supplied and unbounded; its size is
|
|
1221
|
+
* governed by the caller's eviction policy, not by this function.
|
|
1222
|
+
*
|
|
1223
|
+
* Iterates every directory entry and runs the full TOCTOU-safe validation
|
|
1224
|
+
* cluster (extension check, statSync, openSync, fstatSync, realpathSync,
|
|
1225
|
+
* allowedRoots containment, dev+ino re-check). For each candidate that
|
|
1226
|
+
* passes all gates, performs a bounded ~4KB read via `_readFrontmatterOnly`
|
|
1227
|
+
* to extract the `priority` field without pulling the full skill body into
|
|
1228
|
+
* memory. Closes the fd in a `finally` block before moving to the next
|
|
1229
|
+
* entry so pass 1 never holds more than one fd open at a time.
|
|
1230
|
+
*
|
|
1231
|
+
* Returns an array of lightweight candidate descriptors:
|
|
1232
|
+
* { name, fullPath, label, realPath, fstat: { size, mtimeMs, dev, ino },
|
|
1233
|
+
* priority, cachedFrontmatter }
|
|
1234
|
+
*
|
|
1235
|
+
* `name` is the pre-computed stem (entry without extension). Storing it on the
|
|
1236
|
+
* descriptor ensures the pass-1 sort adapter and _enforceTotalBudget use the
|
|
1237
|
+
* same extension-free comparand — avoids the '.' vs '-' ASCII flip that occurs
|
|
1238
|
+
* when comparing full filenames for equal-priority prefix pairs (#3287).
|
|
1239
|
+
*
|
|
1240
|
+
* `cachedFrontmatter` is set when a parseCache hit matched on mtimeMs+size —
|
|
1241
|
+
* pass 2 can skip the partial read and use the cached frontmatter directly,
|
|
1242
|
+
* and also skip re-parsing after the full read (just reuse the cached parse).
|
|
1243
|
+
*
|
|
1244
|
+
* @param {string[]} entries alphabetically sorted basenames from readdirSync
|
|
1245
|
+
* @param {string} dir the skills directory (pre-resolved)
|
|
1246
|
+
* @param {string} dirReal realpathSync(dir)
|
|
1247
|
+
* @param {string[]} allowedRoots resolved allowed root paths
|
|
1248
|
+
* @param {Set<string>} allowedExtensions normalised extension set
|
|
1249
|
+
* @param {number} maxSkillBytes per-skill byte cap
|
|
1250
|
+
* @param {Map|null} parseCache optional mtime-keyed parse cache
|
|
1251
|
+
* @returns {Array<object>}
|
|
1252
|
+
*/
|
|
1253
|
+
function _collectCandidates(entries, dir, dirReal, allowedRoots, allowedExtensions, maxSkillBytes, parseCache) {
|
|
1254
|
+
const candidates = []
|
|
1255
|
+
|
|
1256
|
+
for (const rawEntry of entries) {
|
|
1257
|
+
// Each element is either:
|
|
1258
|
+
// string — top-level basename (fullPath = join(dir, entry))
|
|
1259
|
+
// object { entry: basename, fullPath: string } — community entry
|
|
1260
|
+
let entry, fullPath
|
|
1261
|
+
if (typeof rawEntry === 'string') {
|
|
1262
|
+
if (!rawEntry) continue
|
|
1263
|
+
if (SKIP_DIRECTORY_NAMES.has(rawEntry)) continue
|
|
1264
|
+
entry = rawEntry
|
|
1265
|
+
fullPath = join(dir, entry)
|
|
1266
|
+
} else if (rawEntry && typeof rawEntry === 'object' && typeof rawEntry.entry === 'string') {
|
|
1267
|
+
entry = rawEntry.entry
|
|
1268
|
+
fullPath = rawEntry.fullPath
|
|
1269
|
+
} else {
|
|
1270
|
+
continue
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
const dotIdx = entry.lastIndexOf('.')
|
|
1274
|
+
if (dotIdx <= 0) continue
|
|
1275
|
+
const ext = entry.slice(dotIdx + 1).toLowerCase()
|
|
1276
|
+
if (!allowedExtensions.has(ext)) continue
|
|
1277
|
+
if (entry.endsWith(`.disabled.${ext}`)) continue
|
|
1278
|
+
|
|
1279
|
+
const label = _pathLabel(fullPath)
|
|
1280
|
+
|
|
1281
|
+
let st
|
|
1282
|
+
try {
|
|
1283
|
+
st = statSync(fullPath)
|
|
1284
|
+
} catch {
|
|
1285
|
+
continue
|
|
1286
|
+
}
|
|
1287
|
+
if (!st.isFile()) continue
|
|
1288
|
+
|
|
1289
|
+
if (typeof st.size === 'number' && st.size > maxSkillBytes) {
|
|
1290
|
+
log.warn(`Skipping skill ${label}: size ${st.size} exceeds per-skill cap ${maxSkillBytes}`)
|
|
1291
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
1292
|
+
continue
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
let fd
|
|
1296
|
+
try {
|
|
1297
|
+
fd = openSync(fullPath, 'r')
|
|
1298
|
+
} catch (err) {
|
|
1299
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
1300
|
+
log.warn(`Skipping skill ${label}: open failed (${code})`)
|
|
1301
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
1302
|
+
continue
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
try {
|
|
1306
|
+
let fstat
|
|
1307
|
+
try {
|
|
1308
|
+
fstat = fstatSync(fd)
|
|
1309
|
+
} catch {
|
|
1310
|
+
continue
|
|
1311
|
+
}
|
|
1312
|
+
if (!fstat.isFile()) continue
|
|
1313
|
+
|
|
1314
|
+
if (typeof fstat.size === 'number' && fstat.size > maxSkillBytes) {
|
|
1315
|
+
log.warn(`Skipping skill ${label}: size ${fstat.size} exceeds per-skill cap ${maxSkillBytes}`)
|
|
1316
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
1317
|
+
continue
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
let realPath
|
|
1321
|
+
try {
|
|
1322
|
+
realPath = realpathSync(fullPath)
|
|
1323
|
+
} catch (err) {
|
|
1324
|
+
const code = (err && typeof err.code === 'string') ? err.code : 'UNKNOWN'
|
|
1325
|
+
log.warn(`Skipping skill ${label}: realpath failed (${code})`)
|
|
1326
|
+
log.debug(`skill ${label} full path: ${fullPath}`)
|
|
1327
|
+
continue
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
const inAllowedRoot = allowedRoots.some((root) => _pathContains(root, realPath))
|
|
1331
|
+
if (!inAllowedRoot) {
|
|
1332
|
+
log.warn(`Skipping skill ${label}: real path escapes skills root`)
|
|
1333
|
+
log.debug(`skill ${label} full path: ${fullPath} resolved to ${realPath}, root ${dirReal}`)
|
|
1334
|
+
continue
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
// #3218: dev+ino re-check — same as the single-pass path.
|
|
1338
|
+
let realStat
|
|
1339
|
+
try {
|
|
1340
|
+
realStat = statSync(realPath)
|
|
1341
|
+
} catch {
|
|
1342
|
+
continue
|
|
1343
|
+
}
|
|
1344
|
+
if (fstat.dev !== realStat.dev || fstat.ino !== realStat.ino) {
|
|
1345
|
+
log.warn(`Skipping skill ${label}: fd inode does not match validated real path (TOCTOU swap detected)`)
|
|
1346
|
+
log.debug(`skill ${label} full path: ${fullPath} fd ino=${fstat.ino} realPath ino=${realStat.ino}`)
|
|
1347
|
+
continue
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// Extract priority with minimal I/O. Check parseCache first — if the
|
|
1351
|
+
// cache entry is fresh (mtimeMs+size match), use the cached priority
|
|
1352
|
+
// directly and record the entry so pass 2 can skip re-parsing. On a
|
|
1353
|
+
// cache miss, call _readFrontmatterOnly for a bounded ~4KB read.
|
|
1354
|
+
let priority = DEFAULT_SKILL_PRIORITY
|
|
1355
|
+
let cachedFrontmatter = null
|
|
1356
|
+
|
|
1357
|
+
const cached = parseCache?.get(realPath)
|
|
1358
|
+
const cacheHit = cached
|
|
1359
|
+
&& typeof fstat.mtimeMs === 'number'
|
|
1360
|
+
&& cached.mtimeMs === fstat.mtimeMs
|
|
1361
|
+
&& cached.size === fstat.size
|
|
1362
|
+
|
|
1363
|
+
if (cacheHit) {
|
|
1364
|
+
// Cache is fresh: reuse cached frontmatter for priority extraction.
|
|
1365
|
+
// Pass 2 can use the full cached parse (body, finalBody, description)
|
|
1366
|
+
// without re-reading the file at all.
|
|
1367
|
+
cachedFrontmatter = cached
|
|
1368
|
+
if (cached.frontmatter && Number.isFinite(cached.frontmatter.priority)) {
|
|
1369
|
+
priority = cached.frontmatter.priority
|
|
1370
|
+
}
|
|
1371
|
+
} else {
|
|
1372
|
+
// Cache miss (or no cache): bounded read for frontmatter only.
|
|
1373
|
+
// _readFrontmatterOnly uses an explicit position=0 so the fd cursor
|
|
1374
|
+
// is not advanced — important for correctness even though pass 1
|
|
1375
|
+
// always closes the fd before pass 2 re-opens.
|
|
1376
|
+
try {
|
|
1377
|
+
const partial = _readFrontmatterOnly(fd, fstat.size, { maxBytes: 4096 })
|
|
1378
|
+
if (partial.frontmatter && Number.isFinite(partial.frontmatter.priority)) {
|
|
1379
|
+
priority = partial.frontmatter.priority
|
|
1380
|
+
}
|
|
1381
|
+
} catch {
|
|
1382
|
+
// _readFrontmatterOnly only throws on bad opts — won't happen
|
|
1383
|
+
// here because we pass a valid literal. If it does throw for
|
|
1384
|
+
// any reason, default priority is safe.
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
candidates.push({
|
|
1389
|
+
name: entry.slice(0, -(ext.length + 1)),
|
|
1390
|
+
fullPath,
|
|
1391
|
+
label,
|
|
1392
|
+
realPath,
|
|
1393
|
+
fstat: { size: fstat.size, mtimeMs: fstat.mtimeMs, dev: fstat.dev, ino: fstat.ino },
|
|
1394
|
+
priority,
|
|
1395
|
+
cachedFrontmatter,
|
|
1396
|
+
})
|
|
1397
|
+
} finally {
|
|
1398
|
+
// Always release the fd before moving to the next entry. Pass 2
|
|
1399
|
+
// re-opens the file — holding fds open across all candidates would
|
|
1400
|
+
// risk exhausting the process fd limit on large skill directories.
|
|
1401
|
+
try { closeSync(fd) } catch { /* non-fatal */ }
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
return candidates
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
/**
|
|
1409
|
+
* Walk up from `cwd` looking for the nearest `.chroxy/skills/` directory (#3067).
|
|
1410
|
+
*
|
|
1411
|
+
* The walk lets a user `cd` into any subfolder of a repo and still pick up the
|
|
1412
|
+
* repo-root skills overlay — same ergonomic pattern as `.git` discovery. Stops
|
|
1413
|
+
* at the user's home directory, the filesystem root, or after
|
|
1414
|
+
* `REPO_DISCOVERY_MAX_DEPTH` iterations (whichever comes first).
|
|
1415
|
+
*
|
|
1416
|
+
* The user's home directory is never a valid repo overlay — `~/.chroxy/skills/`
|
|
1417
|
+
* is the global tier (#3088). Without this guard, a session whose `cwd` is
|
|
1418
|
+
* anywhere under `$HOME` but not inside a real repo would walk up to `~` and
|
|
1419
|
+
* silently match the global directory as `repoDir`, mislabeling every global
|
|
1420
|
+
* skill with `source: 'repo'`.
|
|
1421
|
+
*
|
|
1422
|
+
* @param {string|null|undefined} cwd - Session working directory
|
|
1423
|
+
* @returns {string|null} Absolute path to the nearest `.chroxy/skills/`, or null
|
|
1424
|
+
*/
|
|
1425
|
+
export function findRepoSkillsDir(cwd) {
|
|
1426
|
+
if (!cwd || typeof cwd !== 'string') return null
|
|
1427
|
+
|
|
1428
|
+
let dir
|
|
1429
|
+
try {
|
|
1430
|
+
dir = resolve(cwd)
|
|
1431
|
+
} catch {
|
|
1432
|
+
return null
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
const home = (() => {
|
|
1436
|
+
try {
|
|
1437
|
+
return resolve(homedir())
|
|
1438
|
+
} catch {
|
|
1439
|
+
return null
|
|
1440
|
+
}
|
|
1441
|
+
})()
|
|
1442
|
+
|
|
1443
|
+
let prev = null
|
|
1444
|
+
let iterations = 0
|
|
1445
|
+
while (dir !== prev && iterations < REPO_DISCOVERY_MAX_DEPTH) {
|
|
1446
|
+
const candidate = join(dir, '.chroxy', 'skills')
|
|
1447
|
+
try {
|
|
1448
|
+
if (statSync(candidate).isDirectory()) {
|
|
1449
|
+
// Defensive: the user's global skills dir is never a repo overlay.
|
|
1450
|
+
// Even if we somehow walk up to it, refuse to claim it as repo-scoped.
|
|
1451
|
+
if (_sameAbsolutePath(candidate, DEFAULT_SKILLS_DIR)) return null
|
|
1452
|
+
return candidate
|
|
1453
|
+
}
|
|
1454
|
+
} catch {
|
|
1455
|
+
// Not present at this level — keep walking.
|
|
1456
|
+
}
|
|
1457
|
+
// Stop the walk at $HOME so we never consider `~/.chroxy/skills/` (the
|
|
1458
|
+
// global tier) as a candidate. Real repos don't live above $HOME.
|
|
1459
|
+
// Use the same path comparator as the global guard so a darwin/win32 case
|
|
1460
|
+
// mismatch (HFS+/APFS/NTFS are case-insensitive by default) doesn't slip
|
|
1461
|
+
// past the boundary check.
|
|
1462
|
+
if (home && _sameAbsolutePath(dir, home)) return null
|
|
1463
|
+
prev = dir
|
|
1464
|
+
dir = dirname(dir)
|
|
1465
|
+
iterations++
|
|
1466
|
+
}
|
|
1467
|
+
return null
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* Load skills from a global directory and a repo-scoped directory and merge
|
|
1472
|
+
* them, with repo overriding global on filename conflicts (#3067).
|
|
1473
|
+
*
|
|
1474
|
+
* Both directories are optional. Pass null/undefined to skip a tier. If both
|
|
1475
|
+
* paths resolve to the same absolute directory, the global load is skipped to
|
|
1476
|
+
* avoid double-counting the same files under conflicting source tags.
|
|
1477
|
+
*
|
|
1478
|
+
* Size budgets (#3202 / #3279): per-skill cap is enforced inside
|
|
1479
|
+
* `loadActiveSkills`; the total budget is applied twice — once per tier
|
|
1480
|
+
* (priority-aware, via the two-pass `_collectCandidates` path) and once
|
|
1481
|
+
* post-merge here via `_enforceTotalBudget`. Both passes use
|
|
1482
|
+
* `_compareByPriorityThenName` (priority desc, name asc) as the eviction
|
|
1483
|
+
* order so a high-priority skill in any tier is never crowded out by
|
|
1484
|
+
* lower-priority fillers that happen to sort earlier alphabetically.
|
|
1485
|
+
* The post-merge pass is the cross-tier safety net: repo overrides win
|
|
1486
|
+
* before we trim, and the final set is bounded by `maxTotalSkillBytes`.
|
|
1487
|
+
*
|
|
1488
|
+
* Per-provider allowlist (#3207): when `providerSkillAllowlist` is supplied,
|
|
1489
|
+
* Claude-family providers stay permissive (unchanged behaviour); non-Claude
|
|
1490
|
+
* providers (codex, gemini, …) only keep skills whose name appears in the
|
|
1491
|
+
* allowlist for that provider. A missing key OR an empty array filters out
|
|
1492
|
+
* ALL skills for that provider (fail-secure). Passing `null` / omitting
|
|
1493
|
+
* the key entirely leaves the v1 permissive behaviour intact.
|
|
1494
|
+
*
|
|
1495
|
+
* @param {{
|
|
1496
|
+
* globalDir?: string|null,
|
|
1497
|
+
* repoDir?: string|null,
|
|
1498
|
+
* allowedRoots?: string[],
|
|
1499
|
+
* allowedExtensions?: string[],
|
|
1500
|
+
* maxSkillBytes?: number,
|
|
1501
|
+
* maxTotalSkillBytes?: number,
|
|
1502
|
+
* provider?: string|null,
|
|
1503
|
+
* activeManualSkills?: Set<string>|string[]|null,
|
|
1504
|
+
* defaultInjectionMode?: 'prepend'|'append'|'system'|null,
|
|
1505
|
+
* providerSkillAllowlist?: Record<string, string[]>|null,
|
|
1506
|
+
* trustStore?: object|null,
|
|
1507
|
+
* onTrustMismatch?: (info: object) => void,
|
|
1508
|
+
* includeInactive?: boolean,
|
|
1509
|
+
* includeAllProviders?: boolean,
|
|
1510
|
+
* parseCache?: Map<string, object>,
|
|
1511
|
+
* }} [opts]
|
|
1512
|
+
* - `provider`, `activeManualSkills`, `defaultInjectionMode`: forwarded
|
|
1513
|
+
* to `loadActiveSkills` for #3198 (provider gating), #3199 (manual
|
|
1514
|
+
* activation), and #3200 (per-skill injection mode).
|
|
1515
|
+
* - `providerSkillAllowlist`: per-provider allowlist (#3207). See
|
|
1516
|
+
* `_filterByProviderAllowlist` for semantics.
|
|
1517
|
+
* - `includeInactive`: when true, inactive manual skills are returned
|
|
1518
|
+
* tagged `active: false` so the dashboard can render toggles (#3209).
|
|
1519
|
+
* - `includeAllProviders`: when true, both the per-skill provider
|
|
1520
|
+
* gate (#3198) AND the per-provider allowlist (#3207) are bypassed
|
|
1521
|
+
* so the dashboard's `list_skills` fallback shows ALL installed
|
|
1522
|
+
* skills (#3226). Runtime prompt-build callers keep the default
|
|
1523
|
+
* (false) so scoped skills never reach the wrong provider's prompt.
|
|
1524
|
+
* - `parseCache`: optional `Map` of mtime-keyed parse results, shared
|
|
1525
|
+
* across both tier loads so a global+repo merge skips redundant
|
|
1526
|
+
* re-parses on a warm cache (#3248).
|
|
1527
|
+
* @returns {Array<{ name: string, body: string, description: string, source: 'global' | 'repo', metadata: object|null, injectionMode: string }>}
|
|
1528
|
+
*/
|
|
1529
|
+
export function loadActiveSkillsLayered({
|
|
1530
|
+
globalDir,
|
|
1531
|
+
repoDir,
|
|
1532
|
+
allowedRoots,
|
|
1533
|
+
allowedExtensions,
|
|
1534
|
+
maxSkillBytes,
|
|
1535
|
+
maxTotalSkillBytes,
|
|
1536
|
+
provider,
|
|
1537
|
+
activeManualSkills,
|
|
1538
|
+
defaultInjectionMode,
|
|
1539
|
+
providerSkillAllowlist,
|
|
1540
|
+
trustStore,
|
|
1541
|
+
onTrustMismatch,
|
|
1542
|
+
includeInactive,
|
|
1543
|
+
// #3226: bypass the provider-scoping gate so the dashboard's
|
|
1544
|
+
// `list_skills` fallback shows ALL installed skills (including
|
|
1545
|
+
// those with `providers:` frontmatter) when no provider is bound.
|
|
1546
|
+
// Default false — the runtime prompt-build path still respects
|
|
1547
|
+
// provider scoping for the active session.
|
|
1548
|
+
includeAllProviders,
|
|
1549
|
+
// #3248: per-session parse cache. Forwarded as-is to both tier
|
|
1550
|
+
// loaders so they share the same Map (skill name collisions
|
|
1551
|
+
// resolve at the realpath level — global/repo overlay can both
|
|
1552
|
+
// cache distinct entries).
|
|
1553
|
+
parseCache,
|
|
1554
|
+
} = {}) {
|
|
1555
|
+
const sameDir = globalDir && repoDir && _sameAbsolutePath(globalDir, repoDir)
|
|
1556
|
+
|
|
1557
|
+
const loaderOpts = {}
|
|
1558
|
+
if (Array.isArray(allowedRoots)) loaderOpts.allowedRoots = allowedRoots
|
|
1559
|
+
if (Array.isArray(allowedExtensions)) loaderOpts.allowedExtensions = allowedExtensions
|
|
1560
|
+
if (Number.isFinite(maxSkillBytes) && maxSkillBytes > 0) loaderOpts.maxSkillBytes = maxSkillBytes
|
|
1561
|
+
// #3222: pass the global byte cap to each tier as the per-tier budget
|
|
1562
|
+
// so peak memory across both loads is bounded. The post-merge prune
|
|
1563
|
+
// still runs to apply priority-aware cuts down to one full budget,
|
|
1564
|
+
// but each tier on its own can never read more than the global cap.
|
|
1565
|
+
if (Number.isFinite(maxTotalSkillBytes) && maxTotalSkillBytes > 0) {
|
|
1566
|
+
loaderOpts.maxTotalBytes = Math.floor(maxTotalSkillBytes)
|
|
1567
|
+
} else {
|
|
1568
|
+
loaderOpts.maxTotalBytes = DEFAULT_MAX_TOTAL_SKILL_BYTES
|
|
1569
|
+
}
|
|
1570
|
+
if (provider != null) loaderOpts.provider = provider
|
|
1571
|
+
if (activeManualSkills != null) loaderOpts.activeManualSkills = activeManualSkills
|
|
1572
|
+
if (defaultInjectionMode != null) loaderOpts.defaultInjectionMode = defaultInjectionMode
|
|
1573
|
+
if (trustStore != null) loaderOpts.trustStore = trustStore
|
|
1574
|
+
if (typeof onTrustMismatch === 'function') loaderOpts.onTrustMismatch = onTrustMismatch
|
|
1575
|
+
// #3209: pass-through. The per-tier loader applies the inactive-
|
|
1576
|
+
// skill marking; the merge step below treats them like any other
|
|
1577
|
+
// entry (repo overrides global on conflict, etc.).
|
|
1578
|
+
if (includeInactive) loaderOpts.includeInactive = true
|
|
1579
|
+
// #3226: pass-through for the listing-path provider-scope bypass.
|
|
1580
|
+
if (includeAllProviders) loaderOpts.includeAllProviders = true
|
|
1581
|
+
if (parseCache instanceof Map) loaderOpts.parseCache = parseCache
|
|
1582
|
+
|
|
1583
|
+
const globals = (globalDir && !sameDir)
|
|
1584
|
+
? loadActiveSkills(globalDir, { ...loaderOpts, source: 'global' })
|
|
1585
|
+
: []
|
|
1586
|
+
const repos = repoDir
|
|
1587
|
+
? loadActiveSkills(repoDir, { ...loaderOpts, source: 'repo' })
|
|
1588
|
+
: (sameDir ? loadActiveSkills(globalDir, { ...loaderOpts, source: 'repo' }) : [])
|
|
1589
|
+
|
|
1590
|
+
// Repo overrides global on filename conflict — Map iteration order means the
|
|
1591
|
+
// second `set` for a given name wins, and that's exactly what we want.
|
|
1592
|
+
//
|
|
1593
|
+
// #3205 nuance: when `includeInactive` is enabled, an inactive repo entry
|
|
1594
|
+
// must NOT override an active global entry of the same name. The actual
|
|
1595
|
+
// prompt-build path runs with `includeInactive: false` and would skip the
|
|
1596
|
+
// inactive repo skill (filtered out at the per-tier loader), then pick up
|
|
1597
|
+
// the active global skill via the same merge — so `list_skills` would
|
|
1598
|
+
// misreport the skill as inactive when the prompt is actually using the
|
|
1599
|
+
// global active version. Prefer `active: true` over `active: false` on
|
|
1600
|
+
// collision; otherwise repo-wins-last continues to apply.
|
|
1601
|
+
const byName = new Map()
|
|
1602
|
+
for (const s of globals) byName.set(s.name, s)
|
|
1603
|
+
for (const s of repos) {
|
|
1604
|
+
const existing = byName.get(s.name)
|
|
1605
|
+
if (existing && existing.active === true && s.active === false) continue
|
|
1606
|
+
byName.set(s.name, s)
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
const merged = Array.from(byName.values()).sort(
|
|
1610
|
+
(a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
|
|
1611
|
+
)
|
|
1612
|
+
|
|
1613
|
+
// Apply the per-provider allowlist (#3207) AFTER the merge but BEFORE the
|
|
1614
|
+
// total-budget pass — a skill the operator deny-listed should not be
|
|
1615
|
+
// counted toward the cumulative budget, even if pruning would have
|
|
1616
|
+
// dropped it anyway.
|
|
1617
|
+
// #3226: the listing fallback path bypasses the allowlist for the
|
|
1618
|
+
// same reason it bypasses provider scoping — the dashboard's "browse
|
|
1619
|
+
// all installed skills" view shouldn't lose entries that an operator
|
|
1620
|
+
// restricted on a per-provider basis. The runtime prompt-build path
|
|
1621
|
+
// keeps the allowlist active.
|
|
1622
|
+
const filtered = includeAllProviders
|
|
1623
|
+
? merged
|
|
1624
|
+
: _filterByProviderAllowlist(merged, provider, providerSkillAllowlist)
|
|
1625
|
+
|
|
1626
|
+
const totalCap = Number.isFinite(maxTotalSkillBytes) && maxTotalSkillBytes > 0
|
|
1627
|
+
? Math.floor(maxTotalSkillBytes)
|
|
1628
|
+
: DEFAULT_MAX_TOTAL_SKILL_BYTES
|
|
1629
|
+
|
|
1630
|
+
return _enforceTotalBudget(filtered, totalCap)
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// Platform-default heuristic for filesystem case-sensitivity.
|
|
1634
|
+
//
|
|
1635
|
+
// macOS (HFS+/APFS) and Windows (NTFS) are case-insensitive by default. A
|
|
1636
|
+
// `cwd` like `/Users/Bob/proj` and a homedir like `/Users/bob` resolve to the
|
|
1637
|
+
// same directory but compare unequal as strings, which would defeat both the
|
|
1638
|
+
// $HOME boundary check and the global-skills-dir guard. Lowercase before
|
|
1639
|
+
// compare on those platforms to make the equality check actually correspond
|
|
1640
|
+
// to "same directory on disk".
|
|
1641
|
+
//
|
|
1642
|
+
// IMPORTANT — this is an OS heuristic, not a filesystem probe. Two known
|
|
1643
|
+
// non-conforming configurations will misbehave silently:
|
|
1644
|
+
//
|
|
1645
|
+
// • macOS case-sensitive APFS volume (created with
|
|
1646
|
+
// `diskutil apfs addVolume ... "APFS (Case-sensitive)"`): this flag is
|
|
1647
|
+
// `true`, so paths are lowercased before comparison even though the
|
|
1648
|
+
// filesystem treats `Community/` and `community/` as distinct inodes.
|
|
1649
|
+
// In practice this means a `Community/` directory is matched as if it
|
|
1650
|
+
// were `community/`, but both could legitimately coexist on disk.
|
|
1651
|
+
//
|
|
1652
|
+
// • Linux with a case-insensitive mount (ZFS `casesensitivity=insensitive`,
|
|
1653
|
+
// ciopfs, FAT/exFAT, or a WSL workspace on an NTFS volume): this flag is
|
|
1654
|
+
// `false`, so path comparison is case-sensitive even though the underlying
|
|
1655
|
+
// filesystem folds case. A `Community/` directory on such a mount will not
|
|
1656
|
+
// be recognised as a community namespace.
|
|
1657
|
+
//
|
|
1658
|
+
// A runtime filesystem probe (create a temp file, stat with altered case)
|
|
1659
|
+
// would close both gaps but adds startup I/O. Track in a follow-up if the
|
|
1660
|
+
// heuristic becomes a real user pain point.
|
|
1661
|
+
const _PATH_COMPARE_CASE_INSENSITIVE =
|
|
1662
|
+
process.platform === 'darwin' || process.platform === 'win32'
|
|
1663
|
+
|
|
1664
|
+
function _sameAbsolutePath(a, b) {
|
|
1665
|
+
try {
|
|
1666
|
+
const ra = resolve(a)
|
|
1667
|
+
const rb = resolve(b)
|
|
1668
|
+
if (_PATH_COMPARE_CASE_INSENSITIVE) {
|
|
1669
|
+
return ra.toLowerCase() === rb.toLowerCase()
|
|
1670
|
+
}
|
|
1671
|
+
return ra === rb
|
|
1672
|
+
} catch {
|
|
1673
|
+
return false
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
/**
|
|
1678
|
+
* Determine whether `realPath` lives inside a community-namespace directory
|
|
1679
|
+
* directly under `dirReal`, i.e. `<dirReal>/community/<author>/<file>`.
|
|
1680
|
+
*
|
|
1681
|
+
* Returns `{ isCommunity: boolean, author: string|null }`.
|
|
1682
|
+
*
|
|
1683
|
+
* Rules:
|
|
1684
|
+
* - First segment of the relative path must equal `'community'`. On
|
|
1685
|
+
* case-insensitive platforms (`_PATH_COMPARE_CASE_INSENSITIVE === true`,
|
|
1686
|
+
* i.e. darwin / win32 by default) the comparison is done after
|
|
1687
|
+
* lowercasing, so `Community/` and `COMMUNITY/` are also accepted. On
|
|
1688
|
+
* case-sensitive platforms (Linux by default) the match is exact.
|
|
1689
|
+
* - Second segment (the author dir) must be non-empty, must not be `'.'`
|
|
1690
|
+
* or `'..'`, and must not start with `'.'` (no hidden author dirs)
|
|
1691
|
+
* - If both conditions hold: `isCommunity = true, author = segment[1]`
|
|
1692
|
+
* - Otherwise: `isCommunity = false, author = null`
|
|
1693
|
+
*
|
|
1694
|
+
* Edge cases:
|
|
1695
|
+
* `<dirReal>/community/skill.md` (no author dir) → false
|
|
1696
|
+
* `<dirReal>/community/.alice/skill.md` (hidden author) → false
|
|
1697
|
+
* `<dirReal>/foo/community/skill.md` (community not at root) → false
|
|
1698
|
+
*
|
|
1699
|
+
* @param {string} realPath Absolute, realpath-resolved skill path
|
|
1700
|
+
* @param {string} dirReal Absolute, realpath-resolved skills root
|
|
1701
|
+
* @returns {{ isCommunity: boolean, author: string|null }}
|
|
1702
|
+
*/
|
|
1703
|
+
export function _isCommunityNamespace(realPath, dirReal) {
|
|
1704
|
+
if (typeof realPath !== 'string' || typeof dirReal !== 'string') {
|
|
1705
|
+
return { isCommunity: false, author: null }
|
|
1706
|
+
}
|
|
1707
|
+
const rel = relative(dirReal, realPath)
|
|
1708
|
+
// relative() returns paths starting with '..' when realPath escapes dirReal.
|
|
1709
|
+
// Those should never reach this helper (allowedRoots gate blocks them), but
|
|
1710
|
+
// guard here anyway.
|
|
1711
|
+
if (!rel || rel.startsWith('..')) return { isCommunity: false, author: null }
|
|
1712
|
+
const segments = rel.split(sep)
|
|
1713
|
+
if (segments.length < 3) return { isCommunity: false, author: null }
|
|
1714
|
+
const seg0 = _PATH_COMPARE_CASE_INSENSITIVE ? segments[0].toLowerCase() : segments[0]
|
|
1715
|
+
if (seg0 !== 'community') return { isCommunity: false, author: null }
|
|
1716
|
+
const author = segments[1]
|
|
1717
|
+
if (!author || author === '.' || author === '..' || author.startsWith('.')) {
|
|
1718
|
+
return { isCommunity: false, author: null }
|
|
1719
|
+
}
|
|
1720
|
+
return { isCommunity: true, author }
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
// Header text emitted at the top of the formatted skills payload. Exposed as
|
|
1724
|
+
// a constant so callers that build a multi-bucket payload (e.g. the subprocess
|
|
1725
|
+
// providers, which concat the prepend + append buckets into one user-message
|
|
1726
|
+
// prefix — #3228) can render the header exactly once at the concat boundary
|
|
1727
|
+
// instead of producing two `# User skills` sections.
|
|
1728
|
+
//
|
|
1729
|
+
// The header terminates with a literal blank line (`\n\n`) so callers can
|
|
1730
|
+
// concatenate it directly with the first `## Skill: …` section without
|
|
1731
|
+
// losing the visual separator. Without the trailing blank line the
|
|
1732
|
+
// preamble runs straight into the first heading (`Apply them...\n## Skill:`)
|
|
1733
|
+
// — caught by PR #3231 review (Copilot #3 / #4).
|
|
1734
|
+
export const SKILLS_PROMPT_HEADER = [
|
|
1735
|
+
'# User skills',
|
|
1736
|
+
'',
|
|
1737
|
+
'The following skills have been shared from the user\'s skills directory. Apply them when relevant to the task at hand.',
|
|
1738
|
+
'',
|
|
1739
|
+
'',
|
|
1740
|
+
].join('\n')
|
|
1741
|
+
|
|
1742
|
+
/**
|
|
1743
|
+
* Format a list of skills as a single string suitable for appending to a
|
|
1744
|
+
* system prompt or prepending to a user message.
|
|
1745
|
+
*
|
|
1746
|
+
* Returns an empty string for empty/missing input so callers can branch on
|
|
1747
|
+
* truthiness without null-checking.
|
|
1748
|
+
*
|
|
1749
|
+
* Pass `opts.includeHeader = false` to omit the leading `# User skills`
|
|
1750
|
+
* preamble — this lets a caller building a payload from multiple buckets
|
|
1751
|
+
* render the header exactly once at the concat boundary (#3228) instead of
|
|
1752
|
+
* stamping it on each bucket and producing two headers in the final string.
|
|
1753
|
+
*
|
|
1754
|
+
* @param {Array<{ name: string, body: string }>|null|undefined} skills
|
|
1755
|
+
* @param {{ includeHeader?: boolean }} [opts]
|
|
1756
|
+
* @returns {string}
|
|
1757
|
+
*/
|
|
1758
|
+
/**
|
|
1759
|
+
* #3235: resolve a skill name to its on-disk realpath + post-frontmatter
|
|
1760
|
+
* body, scanning the same directories `loadActiveSkillsLayered` walks.
|
|
1761
|
+
*
|
|
1762
|
+
* The trust-accept handler can't use `_getSkills()` because the loader
|
|
1763
|
+
* filters out skills whose hash mismatches in `block` mode — those are
|
|
1764
|
+
* exactly the skills the operator is trying to re-trust. This helper
|
|
1765
|
+
* does a minimal scan that ignores the trust gate so the handler can
|
|
1766
|
+
* locate the file, hash its current content, and call `acceptHash`.
|
|
1767
|
+
*
|
|
1768
|
+
* Symlink defense + extension allowlist are still applied (an operator
|
|
1769
|
+
* re-trusting a skill should not be a vector to ingest content from
|
|
1770
|
+
* outside the skills tree). Returns null if the skill name doesn't
|
|
1771
|
+
* resolve to anything in the configured directories.
|
|
1772
|
+
*
|
|
1773
|
+
* @param {object} args
|
|
1774
|
+
* @param {string} args.skillName - The skill's display name (no extension).
|
|
1775
|
+
* @param {string} [args.globalDir] - Defaults to DEFAULT_SKILLS_DIR.
|
|
1776
|
+
* @param {string|null} [args.repoDir] - Optional repo overlay dir.
|
|
1777
|
+
* @param {string[]} [args.allowedExtensions] - Defaults to DEFAULT_ALLOWED_EXTENSIONS.
|
|
1778
|
+
* @returns {{ realPath: string, body: string } | null}
|
|
1779
|
+
*/
|
|
1780
|
+
export function findSkillForRetrust({
|
|
1781
|
+
skillName,
|
|
1782
|
+
globalDir,
|
|
1783
|
+
repoDir,
|
|
1784
|
+
allowedExtensions,
|
|
1785
|
+
} = {}) {
|
|
1786
|
+
if (typeof skillName !== 'string' || skillName === '') return null
|
|
1787
|
+
const exts = (Array.isArray(allowedExtensions) && allowedExtensions.length > 0
|
|
1788
|
+
? allowedExtensions.map(_normalizeExtension).filter(Boolean)
|
|
1789
|
+
: DEFAULT_ALLOWED_EXTENSIONS)
|
|
1790
|
+
|
|
1791
|
+
// Repo overlay searched first (mirrors loader precedence: repo wins).
|
|
1792
|
+
const dirs = []
|
|
1793
|
+
if (repoDir) dirs.push({ dir: repoDir, source: 'repo' })
|
|
1794
|
+
if (globalDir) dirs.push({ dir: globalDir, source: 'global' })
|
|
1795
|
+
if (dirs.length === 0) {
|
|
1796
|
+
dirs.push({ dir: DEFAULT_SKILLS_DIR, source: 'global' })
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
for (const { dir } of dirs) {
|
|
1800
|
+
let dirReal
|
|
1801
|
+
try {
|
|
1802
|
+
dirReal = realpathSync(dir)
|
|
1803
|
+
} catch {
|
|
1804
|
+
continue
|
|
1805
|
+
}
|
|
1806
|
+
const allowedRoots = _resolveRoots([dirReal])
|
|
1807
|
+
|
|
1808
|
+
for (const ext of exts) {
|
|
1809
|
+
const candidate = join(dir, `${skillName}.${ext}`)
|
|
1810
|
+
let st
|
|
1811
|
+
try {
|
|
1812
|
+
st = statSync(candidate)
|
|
1813
|
+
} catch {
|
|
1814
|
+
continue
|
|
1815
|
+
}
|
|
1816
|
+
if (!st.isFile()) continue
|
|
1817
|
+
|
|
1818
|
+
let realPath
|
|
1819
|
+
try {
|
|
1820
|
+
realPath = realpathSync(candidate)
|
|
1821
|
+
} catch {
|
|
1822
|
+
continue
|
|
1823
|
+
}
|
|
1824
|
+
const inAllowedRoot = allowedRoots.some((root) => _pathContains(root, realPath))
|
|
1825
|
+
if (!inAllowedRoot) continue
|
|
1826
|
+
|
|
1827
|
+
let buf
|
|
1828
|
+
try {
|
|
1829
|
+
buf = readFileSync(realPath)
|
|
1830
|
+
} catch {
|
|
1831
|
+
continue
|
|
1832
|
+
}
|
|
1833
|
+
if (!_bufferLooksLikeText(buf)) continue
|
|
1834
|
+
const body = buf.toString('utf8')
|
|
1835
|
+
const parsed = parseFrontmatter(body)
|
|
1836
|
+
const finalBody = parsed.frontmatter !== null ? parsed.body : body
|
|
1837
|
+
return { realPath, body: finalBody }
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
return null
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
export function formatSkillsForPrompt(skills, opts = {}) {
|
|
1845
|
+
if (!Array.isArray(skills) || skills.length === 0) return ''
|
|
1846
|
+
|
|
1847
|
+
const includeHeader = opts && opts.includeHeader === false ? false : true
|
|
1848
|
+
|
|
1849
|
+
const sections = skills.map((s) => {
|
|
1850
|
+
const body = typeof s.body === 'string' ? s.body.trim() : ''
|
|
1851
|
+
return `## Skill: ${s.name}\n\n${body}`
|
|
1852
|
+
})
|
|
1853
|
+
|
|
1854
|
+
const sectionText = sections.join('\n\n---\n\n')
|
|
1855
|
+
return includeHeader ? `${SKILLS_PROMPT_HEADER}${sectionText}` : sectionText
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
function _firstNonEmptyLine(s) {
|
|
1859
|
+
if (typeof s !== 'string') return ''
|
|
1860
|
+
for (const line of s.split('\n')) {
|
|
1861
|
+
const trimmed = line.trim()
|
|
1862
|
+
if (trimmed) return trimmed
|
|
1863
|
+
}
|
|
1864
|
+
return ''
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
/**
|
|
1868
|
+
* Group a skill list by injection mode (#3200). Returns an object with one
|
|
1869
|
+
* array per mode — callers feed each non-empty array through
|
|
1870
|
+
* `formatSkillsForPrompt()` separately and route the resulting text to the
|
|
1871
|
+
* matching channel (system prompt vs first user message).
|
|
1872
|
+
*
|
|
1873
|
+
* The 'system' mode is folded into 'append' — both end up on the same
|
|
1874
|
+
* channel for Claude SDK (`systemPrompt.append`); on subprocess providers,
|
|
1875
|
+
* callers can decide to treat 'system' as a synonym for 'append' (no-op
|
|
1876
|
+
* since neither is supported there) or fall back to 'prepend'. Using two
|
|
1877
|
+
* distinct buckets here would force every caller to merge them anyway.
|
|
1878
|
+
*
|
|
1879
|
+
* @param {Array<{injectionMode?: string}>|null|undefined} skills
|
|
1880
|
+
* @returns {{ prepend: Array<object>, append: Array<object> }}
|
|
1881
|
+
*/
|
|
1882
|
+
export function groupSkillsByInjectionMode(skills) {
|
|
1883
|
+
const out = { prepend: [], append: [] }
|
|
1884
|
+
if (!Array.isArray(skills) || skills.length === 0) return out
|
|
1885
|
+
for (const s of skills) {
|
|
1886
|
+
const mode = _normalizeInjectionMode(s && s.injectionMode) || 'append'
|
|
1887
|
+
if (mode === 'prepend') out.prepend.push(s)
|
|
1888
|
+
else out.append.push(s) // 'append' and 'system' both land here
|
|
1889
|
+
}
|
|
1890
|
+
return out
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
|