@jbkjr/relay 0.0.0-stage → 1.2.1
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/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +386 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1525 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +320 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +637 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +329 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +629 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1502 -0
- package/docs/pinned-codex.md +321 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
// What relay reads from Claude Code's settings to tell whether a person's answer can be established
|
|
2
|
+
// in a Claude Code session: `permissions.defaultMode`, and the matchers of the
|
|
3
|
+
// hook groups of the events whose hooks can answer for the person (PreToolUse and PermissionRequest
|
|
4
|
+
// for relay's confirm tool, Elicitation and ElicitationResult for its approval dialog). Nothing else
|
|
5
|
+
// is read or kept: not the hooks' commands, and not the rest of the file. The values are taken out
|
|
6
|
+
// of each settings file by key path with macOS's plutil, so relay's process never holds the rest
|
|
7
|
+
// (a settings file's `env`, in particular, can carry credentials). Subagent definitions are checked
|
|
8
|
+
// separately by a conservative scan of their leading frontmatter block, without reading the body.
|
|
9
|
+
// Plugin JSON and skill frontmatter are checked as additional hook sources below.
|
|
10
|
+
// Doctor also extracts just crossSessionInbound to report observed inbox controls and their sources.
|
|
11
|
+
import { spawnSync } from "node:child_process";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import os from "node:os";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { git } from "./git.js";
|
|
16
|
+
/** Where an organisation's managed Claude Code settings live. Relay cannot see settings delivered from the claude.ai console. */
|
|
17
|
+
export function managedSettingsPaths() {
|
|
18
|
+
const user = os.userInfo().username;
|
|
19
|
+
return [
|
|
20
|
+
"/Library/Application Support/ClaudeCode/managed-settings.json",
|
|
21
|
+
"/Library/Application Support/ClaudeCode/managed-settings.d",
|
|
22
|
+
"/Library/Managed Preferences/com.anthropic.claudecode.plist",
|
|
23
|
+
`/Library/Managed Preferences/${user}/com.anthropic.claudecode.plist`,
|
|
24
|
+
"/etc/claude-code/managed-settings.json",
|
|
25
|
+
"/etc/claude-code/managed-settings.d",
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
/** The first managed settings location present on disk, or null. */
|
|
29
|
+
export function managedSettings() {
|
|
30
|
+
return managedSettingsPaths().find((p) => fs.existsSync(p)) ?? null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Doctor's reason relay refuses every Claude launch on a machine with organisation-managed
|
|
34
|
+
* settings. `floored`: the never floor binds Claude's jobs (core/never-coverage.ts; always, since
|
|
35
|
+
* 1.1.4), and then claude_managed_settings changes nothing (backends/claude.ts prepare refuses).
|
|
36
|
+
* Otherwise only its "refuse" refuses, and "accept" launches only what the floor does not bind.
|
|
37
|
+
*/
|
|
38
|
+
export function managedSettingsProblem(managed, floored) {
|
|
39
|
+
return floored
|
|
40
|
+
? `this machine has organisation-managed Claude Code settings (${managed}), which can override the never floor Claude jobs get, whatever claude_managed_settings says ("accept" does not permit them)`
|
|
41
|
+
: `this machine has organisation-managed Claude Code settings (${managed}), and claude_managed_settings is "refuse"; "accept" would launch only Claude work the never floor does not bind`;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The backend's refusal under claude_managed_settings "refuse", reached only by a launch without
|
|
45
|
+
* relay's never floor (one with no never policy: registry launches always carry it, and are refused
|
|
46
|
+
* before this whatever the setting says), so its advice to accept is conditional.
|
|
47
|
+
*/
|
|
48
|
+
export function managedSettingsRefusal(managed) {
|
|
49
|
+
return `this machine has organisation-managed Claude Code settings (${managed}). They outrank the settings relay passes, so relay cannot tell whether its confinement holds, and it does not launch Claude. ` +
|
|
50
|
+
'"claude_managed_settings": "accept" launches only on a route without relay\'s never floor; relay\'s own Claude jobs carry the floor and are refused on this machine whatever that setting says.';
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Why Claude must not be launched because settings relay does not vet would load, or null. A
|
|
54
|
+
* settings file's `env` sets variables for the session after relay has checked the environment it
|
|
55
|
+
* passes, so such a file can point Claude at another endpoint (ANTHROPIC_BASE_URL) where relay's
|
|
56
|
+
* endpoint check never sees it, and relay does not read those files (they may hold credentials).
|
|
57
|
+
* With only relay's own settings (child_settings "isolated", no managed settings on disk) nothing
|
|
58
|
+
* can; otherwise relay refuses unless claude_settings_env is "accept", which leaves the reported
|
|
59
|
+
* model as the only evidence of which family answers.
|
|
60
|
+
*/
|
|
61
|
+
export function settingsEnvProblem(cfg, managed) {
|
|
62
|
+
if (cfg.claude_settings_env === "accept")
|
|
63
|
+
return null;
|
|
64
|
+
const sources = [
|
|
65
|
+
...(cfg.child_settings === "inherit" ? ['your user, project and local Claude Code settings (child_settings "inherit")'] : []),
|
|
66
|
+
...(managed ? [`organisation-managed settings (${managed})`] : []),
|
|
67
|
+
];
|
|
68
|
+
if (!sources.length)
|
|
69
|
+
return null;
|
|
70
|
+
return `a launched Claude agent would load ${sources.join(" and ")}, whose env can point Claude Code at another endpoint than Anthropic's after relay has checked its environment, so relay could not tell which family of model answers. ` +
|
|
71
|
+
'Relay reaches other families only, so it does not launch Claude this way. Use child_settings "isolated", or set "claude_settings_env": "accept" in relay\'s config to launch anyway, relying on the model Claude reports.';
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The name relay's installer registers its server under in Claude Code (`claude mcp add relay`), and
|
|
75
|
+
* so the names hooks see: Elicitation hooks match on the server's name, tool hooks on the tool's.
|
|
76
|
+
*/
|
|
77
|
+
export const RELAY_SERVER = "relay";
|
|
78
|
+
export const CONFIRM_TOOL = `mcp__${RELAY_SERVER}__confirm`;
|
|
79
|
+
export const ADOPT_TOOL = `mcp__${RELAY_SERVER}__adopt`;
|
|
80
|
+
/**
|
|
81
|
+
* Hook events whose hooks can answer for the person, and the name each event's matcher is tested
|
|
82
|
+
* against for relay (Claude Code's hooks documentation): a PreToolUse hook can allow a tool call
|
|
83
|
+
* without the permission prompt and a PermissionRequest hook can answer that prompt, so either,
|
|
84
|
+
* where it matches relay's confirm tool, can let confirm through without the person. An
|
|
85
|
+
* Elicitation hook can answer an MCP elicitation before any dialog is shown, and an
|
|
86
|
+
* ElicitationResult hook can change the answer the person gave; both match on the server's name.
|
|
87
|
+
*/
|
|
88
|
+
export const ANSWERING_HOOKS = {
|
|
89
|
+
confirm: [["PreToolUse", CONFIRM_TOOL], ["PermissionRequest", CONFIRM_TOOL], ["PreToolUse", ADOPT_TOOL], ["PermissionRequest", ADOPT_TOOL]],
|
|
90
|
+
dialog: [["Elicitation", RELAY_SERVER], ["ElicitationResult", RELAY_SERVER]],
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Whether a hook matcher can match `name`, as Claude Code evaluates matchers: absent, empty or "*"
|
|
94
|
+
* matches everything; one made only of letters, digits, "_", "-", spaces, "," and "|" is a list of
|
|
95
|
+
* exact names separated by "|" or ","; anything else is an unanchored JavaScript regular
|
|
96
|
+
* expression. A matcher that is not text, or a regular expression that does not compile, counts as
|
|
97
|
+
* matching: relay fails closed.
|
|
98
|
+
*/
|
|
99
|
+
export function matcherMatches(matcher, name) {
|
|
100
|
+
if (matcher === null || matcher === undefined || matcher === "" || matcher === "*")
|
|
101
|
+
return true;
|
|
102
|
+
if (/^[A-Za-z0-9_\- ,|]*$/.test(matcher))
|
|
103
|
+
return matcher.split(/[|,]/).map((m) => m.trim()).includes(name);
|
|
104
|
+
try {
|
|
105
|
+
return new RegExp(matcher).test(name);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Permission modes under which Claude Code still puts a tool marked for user interaction to the
|
|
113
|
+
* person, or refuses it. bypassPermissions skips the prompt; any other value relay does not know
|
|
114
|
+
* is treated the same way.
|
|
115
|
+
*/
|
|
116
|
+
const PROMPTING_MODES = new Set(["default", "acceptEdits", "plan", "auto", "dontAsk"]);
|
|
117
|
+
const PLUTIL = "/usr/bin/plutil";
|
|
118
|
+
const labelOf = (s) => ("file" in s ? s.file : s.label);
|
|
119
|
+
/**
|
|
120
|
+
* One key path's value from a source, as plutil prints it raw (an array prints its length). With
|
|
121
|
+
* `expect`, a value of another type is "unreadable".
|
|
122
|
+
*/
|
|
123
|
+
function extract(src, keyPath, expect) {
|
|
124
|
+
const r = spawnSync(PLUTIL, ["-extract", keyPath, "raw", ...(expect ? ["-expect", expect] : []), "-o", "-", "file" in src ? src.file : "-"], {
|
|
125
|
+
input: "inline" in src ? src.inline : undefined,
|
|
126
|
+
encoding: "utf8",
|
|
127
|
+
timeout: 5000,
|
|
128
|
+
env: { PATH: "/usr/bin:/bin", LC_ALL: "C", LANG: "C" },
|
|
129
|
+
});
|
|
130
|
+
if (r.status === 0)
|
|
131
|
+
return { value: r.stdout.replace(/\n$/, "") };
|
|
132
|
+
if (r.status === 1 && /No value at that key path/.test(r.stderr ?? ""))
|
|
133
|
+
return "absent";
|
|
134
|
+
return "unreadable";
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Why answers in a session with these settings may not be the person's, for the dialog and for
|
|
138
|
+
* confirm (see Consent): the default mode skips permission prompts (or is not one relay knows),
|
|
139
|
+
* which stands in the way of both; or a hook that can answer for the person matches relay (see
|
|
140
|
+
* ANSWERING_HOOKS). A hook that matches only other tools or servers (a PreToolUse hook on an email
|
|
141
|
+
* tool, say) is no obstacle. Whatever relay cannot read is taken to stand in the way: it fails closed.
|
|
142
|
+
*/
|
|
143
|
+
export function answeredWithoutPerson(src) {
|
|
144
|
+
const label = labelOf(src);
|
|
145
|
+
const unreadable = `relay could not read the Claude Code settings in ${label}`;
|
|
146
|
+
const mode = extract(src, "permissions.defaultMode");
|
|
147
|
+
if (mode === "unreadable")
|
|
148
|
+
return { dialog: unreadable, confirm: unreadable };
|
|
149
|
+
if (mode !== "absent" && !PROMPTING_MODES.has(mode.value)) {
|
|
150
|
+
const why = `the Claude Code settings in ${label} set permissions.defaultMode ${JSON.stringify(mode.value.slice(0, 40))}, which skips permission prompts or is not a mode relay knows`;
|
|
151
|
+
return { dialog: why, confirm: why };
|
|
152
|
+
}
|
|
153
|
+
const hooked = (events) => {
|
|
154
|
+
for (const [event, name] of events) {
|
|
155
|
+
const groups = extract(src, `hooks.${event}`, "array");
|
|
156
|
+
if (groups === "unreadable")
|
|
157
|
+
return unreadable;
|
|
158
|
+
if (groups === "absent")
|
|
159
|
+
continue;
|
|
160
|
+
for (let i = 0; i < Number(groups.value); i++) {
|
|
161
|
+
const m = extract(src, `hooks.${event}.${i}.matcher`, "string");
|
|
162
|
+
if (m === "unreadable")
|
|
163
|
+
return `the Claude Code settings in ${label} have ${event} hooks whose matcher relay could not read, which may answer for you`;
|
|
164
|
+
const matcher = m === "absent" ? null : m.value;
|
|
165
|
+
if (matcherMatches(matcher, name)) {
|
|
166
|
+
return `the Claude Code settings in ${label} have ${event} hooks ${matcher === null || matcher === "" || matcher === "*" ? "for everything" : `matching ${JSON.stringify(matcher.slice(0, 60))}`}, which can answer for you ${name === RELAY_SERVER ? `in relay's approval dialog` : `in the permission prompt for relay's ${name === ADOPT_TOOL ? "adopt" : "confirm"}`}`;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
};
|
|
172
|
+
return { dialog: hooked(ANSWERING_HOOKS.dialog), confirm: hooked(ANSWERING_HOOKS.confirm) };
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* The directories whose `.claude/settings.local.json` Claude Code may read for a session started in
|
|
176
|
+
* `cwd`: since 2.1.211 it keeps that file at the git repository's root, and in a linked worktree at
|
|
177
|
+
* the main checkout's root, and it still reads a copy an earlier version left in the starting
|
|
178
|
+
* directory (https://code.claude.com/docs/en/settings#where-claude-code-keeps-the-local-file-in-a-git-repository).
|
|
179
|
+
* Relay reads all of them, whichever Claude Code would pick (it keeps the file in the starting
|
|
180
|
+
* directory under some ownership and home-directory conditions). Where git cannot say, the
|
|
181
|
+
* starting directory only, as before.
|
|
182
|
+
*/
|
|
183
|
+
export function localSettingsDirs(cwd) {
|
|
184
|
+
const dirs = [cwd];
|
|
185
|
+
// Both answers from one git where it gives both, one line each; otherwise (outside a work tree,
|
|
186
|
+
// a name with a line break in it) each asked on its own, as git answers it alone.
|
|
187
|
+
const both = git(cwd, ["rev-parse", "--show-toplevel", "--path-format=absolute", "--git-common-dir"]);
|
|
188
|
+
const lines = both.ok ? both.raw.split("\n") : [];
|
|
189
|
+
const [top, common] = lines.length === 3 && !lines[2] && lines[0].trim() && lines[1].trim()
|
|
190
|
+
? [lines[0].trim(), lines[1].trim()]
|
|
191
|
+
: [git(cwd, ["rev-parse", "--show-toplevel"]), git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"])].map((r) => (r.ok ? r.out : ""));
|
|
192
|
+
if (top)
|
|
193
|
+
dirs.push(top);
|
|
194
|
+
if (common)
|
|
195
|
+
dirs.push(path.dirname(common));
|
|
196
|
+
return [...new Set(dirs)];
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The settings files Claude Code reads for a session started in `cwd`: the user's (in
|
|
200
|
+
* CLAUDE_CONFIG_DIR when set, and in ~/.claude), the project's and the local ones (see
|
|
201
|
+
* localSettingsDirs), and the managed ones given (a managed-settings.d directory contributes its
|
|
202
|
+
* JSON files). Only those present.
|
|
203
|
+
*/
|
|
204
|
+
export function settingsFiles(env, cwd, managed, localDirs = localSettingsDirs(cwd)) {
|
|
205
|
+
const home = env.HOME || os.homedir();
|
|
206
|
+
const candidates = [
|
|
207
|
+
...(env.CLAUDE_CONFIG_DIR ? [path.join(env.CLAUDE_CONFIG_DIR, "settings.json")] : []),
|
|
208
|
+
path.join(home, ".claude", "settings.json"),
|
|
209
|
+
path.join(cwd, ".claude", "settings.json"),
|
|
210
|
+
...localDirs.map((d) => path.join(d, ".claude", "settings.local.json")),
|
|
211
|
+
];
|
|
212
|
+
candidates.push(...managedFiles(managed));
|
|
213
|
+
return [...new Set(candidates)].filter((p) => fs.existsSync(p));
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The managed settings files among `managed` that are on disk: a managed-settings.d directory
|
|
217
|
+
* contributes its JSON files, and one relay cannot list counts as a file, so that reading it fails.
|
|
218
|
+
*/
|
|
219
|
+
export function managedFiles(managed) {
|
|
220
|
+
const out = [];
|
|
221
|
+
for (const m of managed) {
|
|
222
|
+
let dir = false;
|
|
223
|
+
try {
|
|
224
|
+
dir = fs.statSync(m).isDirectory();
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (dir) {
|
|
230
|
+
try {
|
|
231
|
+
out.push(...fs.readdirSync(m).filter((f) => f.endsWith(".json")).sort().map((f) => path.join(m, f)));
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
// An unreadable directory: a source relay cannot read, so it counts as answering.
|
|
235
|
+
out.push(m);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
out.push(m);
|
|
240
|
+
}
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Managed settings that would take a Claude job with the network around relay's proxy. Managed
|
|
245
|
+
* settings outrank the settings relay passes: a proxy port of their own replaces relay's, local
|
|
246
|
+
* binding or Unix sockets open this machine to the sandbox directly, and a proxy variable in their
|
|
247
|
+
* env can point the Claude process (its WebFetch) elsewhere. Each key path, and what of it counts.
|
|
248
|
+
*/
|
|
249
|
+
const MANAGED_NETWORK_KEYS = [
|
|
250
|
+
["sandbox.network.httpProxyPort", "any"], ["sandbox.network.socksProxyPort", "any"],
|
|
251
|
+
["sandbox.network.allowLocalBinding", "true"], ["sandbox.network.allowAllUnixSockets", "true"], ["sandbox.network.allowUnixSockets", "list"],
|
|
252
|
+
...["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"].map((n) => [`env.${n}`, "any"]),
|
|
253
|
+
];
|
|
254
|
+
/**
|
|
255
|
+
* Why relay does not give a Claude job the network on this machine, from its managed settings on
|
|
256
|
+
* disk (MANAGED_NETWORK_KEYS), or null. What relay cannot read refuses too. Settings delivered from
|
|
257
|
+
* the claude.ai console are not on disk; relay's checks of the sandbox's report and of Claude's own traffic
|
|
258
|
+
* (backends/claude.ts) catch their effect instead.
|
|
259
|
+
*/
|
|
260
|
+
export function managedNetworkProblem(managed = managedSettingsPaths()) {
|
|
261
|
+
for (const file of managedFiles(managed)) {
|
|
262
|
+
for (const [key, counts] of MANAGED_NETWORK_KEYS) {
|
|
263
|
+
const read = extract({ file }, key, counts === "list" ? "array" : undefined);
|
|
264
|
+
if (read === "absent")
|
|
265
|
+
continue;
|
|
266
|
+
const set = read === "unreadable" || counts === "any" || (counts === "true" ? read.value === "true" : read.value !== "0");
|
|
267
|
+
if (!set)
|
|
268
|
+
continue;
|
|
269
|
+
return `${read === "unreadable" ? `relay could not read ${key} in the organisation-managed Claude Code settings ${file}` : `the organisation-managed Claude Code settings ${file} set ${key}`}, ` +
|
|
270
|
+
"and managed settings outrank relay's own, so a Claude job with the network could reach this machine or its local network around relay's proxy. Relay does not give Claude jobs the network on this machine";
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
/** The JSON object that starts at `text[start]` ("{"), by brace depth outside strings; null if it never closes. */
|
|
276
|
+
function jsonAt(text, start) {
|
|
277
|
+
let depth = 0;
|
|
278
|
+
let inString = false;
|
|
279
|
+
for (let i = start; i < text.length; i++) {
|
|
280
|
+
const c = text[i];
|
|
281
|
+
if (inString) {
|
|
282
|
+
if (c === "\\")
|
|
283
|
+
i++;
|
|
284
|
+
else if (c === '"')
|
|
285
|
+
inString = false;
|
|
286
|
+
}
|
|
287
|
+
else if (c === '"')
|
|
288
|
+
inString = true;
|
|
289
|
+
else if (c === "{")
|
|
290
|
+
depth++;
|
|
291
|
+
else if (c === "}" && --depth === 0)
|
|
292
|
+
return text.slice(start, i + 1);
|
|
293
|
+
}
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The `--settings` arguments on these command lines (as ps prints them: arguments joined by
|
|
298
|
+
* spaces), as sources: inline JSON, or a file (relative to `cwd`). An argument relay cannot make
|
|
299
|
+
* out is returned as an unreadable source, so that it counts as answering for the person.
|
|
300
|
+
*/
|
|
301
|
+
export function settingsArguments(commandLines, cwd) {
|
|
302
|
+
const out = [];
|
|
303
|
+
for (const line of commandLines) {
|
|
304
|
+
const flag = /(?:^|\s)--settings(?:=|\s+)/g;
|
|
305
|
+
for (let m = flag.exec(line); m; m = flag.exec(line)) {
|
|
306
|
+
const at = m.index + m[0].length;
|
|
307
|
+
if (line[at] === "{") {
|
|
308
|
+
const json = jsonAt(line, at);
|
|
309
|
+
out.push(json ? { inline: json, label: "a --settings argument" } : { file: "(an unterminated --settings argument)" });
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
const token = /^\S+/.exec(line.slice(at))?.[0] ?? "";
|
|
313
|
+
out.push({ file: path.resolve(cwd, token) });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Observed inbound controls, with provenance, not a claim about another process's effective
|
|
321
|
+
* settings: console-managed settings, --setting-sources, runtime changes and unseen --settings
|
|
322
|
+
* may change those. Extract only this key; never load a settings file's credentials into relay.
|
|
323
|
+
*/
|
|
324
|
+
export function inboundSettings(env, cwd, commandLines = [], managed = managedSettingsPaths()) {
|
|
325
|
+
const sources = [...settingsFiles(env, cwd, managed).map((file) => ({ file })), ...settingsArguments(commandLines, cwd)];
|
|
326
|
+
return sources.flatMap((src) => {
|
|
327
|
+
const read = extract(src, "crossSessionInbound", "string");
|
|
328
|
+
if (read === "absent")
|
|
329
|
+
return [];
|
|
330
|
+
const value = read === "unreadable" ? "unreadable" : ["accept", "hold", "refuse"].includes(read.value) ? read.value : "invalid";
|
|
331
|
+
return [{ source: labelOf(src), value }];
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Why relay cannot establish that an answer in this Claude Code session is the person's, from its
|
|
336
|
+
* settings, for the dialog and for confirm (see Consent): the user's, project, local and managed
|
|
337
|
+
* settings files, and any `--settings` argument on the command lines of the processes that started
|
|
338
|
+
* relay's server. For each, the first source that stands in the way.
|
|
339
|
+
*/
|
|
340
|
+
export function settingsAnswerForPerson(env, cwd, commandLines, managed = managedSettingsPaths()) {
|
|
341
|
+
// Where the session's repository is, asked of git once for the settings files and the subagent
|
|
342
|
+
// definitions alike: between the two only files are read.
|
|
343
|
+
const localDirs = localSettingsDirs(cwd);
|
|
344
|
+
const sources = [...settingsFiles(env, cwd, managed, localDirs).map((file) => ({ file })), ...settingsArguments(commandLines, cwd)];
|
|
345
|
+
const out = { dialog: null, confirm: null };
|
|
346
|
+
for (const src of sources) {
|
|
347
|
+
const missing = "file" in src && !fs.existsSync(src.file) ? `relay could not read the Claude Code settings in ${src.file}` : null;
|
|
348
|
+
const why = missing ? { dialog: missing, confirm: missing } : answeredWithoutPerson(src);
|
|
349
|
+
out.dialog ??= why.dialog;
|
|
350
|
+
out.confirm ??= why.confirm;
|
|
351
|
+
if (out.dialog && out.confirm)
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
// Subagent definitions have their own hooks, independent of settings.json. For 1.0 use a
|
|
355
|
+
// conservative frontmatter check rather than adding a YAML runtime: any hooks key withholds
|
|
356
|
+
// the permission-prompt paths, even an empty or unrelated hook. Ambiguous YAML fails closed.
|
|
357
|
+
out.confirm ??= subagentHooksProblem(env, cwd, localDirs);
|
|
358
|
+
const extensions = extensionHooksProblem(env, cwd, commandLines);
|
|
359
|
+
out.confirm ??= extensions.confirm;
|
|
360
|
+
out.dialog ??= extensions.dialog;
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Plugin hooks merge hooks/hooks.json with manifest hooks (inline maps or file paths).
|
|
365
|
+
* Skills can register hooks for the rest of the session. See Claude Code's hooks and plugin
|
|
366
|
+
* manifest/loading references, linked in docs/extensions.md. Scan even disabled/cached copies:
|
|
367
|
+
* the running session can have an older plugin or an already-invoked skill still registered.
|
|
368
|
+
*/
|
|
369
|
+
export function extensionHooksProblem(env, cwd, commandLines = []) {
|
|
370
|
+
const home = env.HOME || os.homedir();
|
|
371
|
+
const configs = [...new Set([path.join(home, ".claude"), ...(env.CLAUDE_CONFIG_DIR ? [env.CLAUDE_CONFIG_DIR] : [])])];
|
|
372
|
+
const out = { confirm: null, dialog: null };
|
|
373
|
+
const blocked = (why) => { out.confirm ??= why; out.dialog ??= why; };
|
|
374
|
+
const object = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
375
|
+
const read = (file) => {
|
|
376
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
|
|
377
|
+
try {
|
|
378
|
+
const st = fs.fstatSync(fd);
|
|
379
|
+
if (!st.isFile() || st.size > 1024 * 1024)
|
|
380
|
+
throw new Error("not a bounded regular JSON file");
|
|
381
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(fd)));
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
fs.closeSync(fd);
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
const present = (file) => {
|
|
388
|
+
try {
|
|
389
|
+
fs.lstatSync(file);
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
catch (e) {
|
|
393
|
+
if (e.code === "ENOENT")
|
|
394
|
+
return false;
|
|
395
|
+
throw e;
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
const hookMap = (value, label) => {
|
|
399
|
+
if (!object(value)) {
|
|
400
|
+
blocked(`relay could not read the Claude Code plugin hooks in ${label}`);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
// JavaScript hook modules can register arbitrary handlers; matchers are not inspectable.
|
|
404
|
+
if ("modules" in value)
|
|
405
|
+
blocked(`the Claude Code plugin hooks in ${label} contain a module whose matchers relay cannot inspect`);
|
|
406
|
+
for (const route of ["confirm", "dialog"])
|
|
407
|
+
for (const [event, name] of ANSWERING_HOOKS[route]) {
|
|
408
|
+
if (!(event in value))
|
|
409
|
+
continue;
|
|
410
|
+
const groups = value[event];
|
|
411
|
+
if (!Array.isArray(groups)) {
|
|
412
|
+
blocked(`relay could not read the Claude Code plugin hooks in ${label}`);
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
for (const group of groups) {
|
|
416
|
+
if (!object(group) || (group.matcher !== undefined && typeof group.matcher !== "string") || matcherMatches(group.matcher, name)) {
|
|
417
|
+
out[route] ??= `the Claude Code plugin hooks in ${label} have ${event} hooks which may answer for you (${name})`;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
const hooksFile = (file) => {
|
|
423
|
+
try {
|
|
424
|
+
const raw = read(file);
|
|
425
|
+
// Claude Code takes `hooks` (the matchers), `modules` (hooks modules), or both.
|
|
426
|
+
if (!object(raw) || !("hooks" in raw || "modules" in raw))
|
|
427
|
+
throw new Error("missing hooks map and hook modules");
|
|
428
|
+
// A hooks module is code that can register any handler; its matchers are not inspectable.
|
|
429
|
+
if ("modules" in raw)
|
|
430
|
+
blocked(`the Claude Code plugin hooks in ${file} load a hooks module whose handlers relay cannot inspect`);
|
|
431
|
+
if ("hooks" in raw)
|
|
432
|
+
hookMap(raw.hooks, file);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
blocked(`relay could not read the Claude Code plugin hooks in ${file}`);
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
const seen = new Set();
|
|
439
|
+
const definition = (file, kind) => {
|
|
440
|
+
// Claude can load a directory in its skills root as a plugin too.
|
|
441
|
+
if (path.basename(file) === "plugin.json" && path.basename(path.dirname(file)) === ".claude-plugin")
|
|
442
|
+
plugin(path.dirname(path.dirname(file)));
|
|
443
|
+
if (!(kind === "skill" ? path.basename(file).toLowerCase() === "skill.md" : file.endsWith(".md")))
|
|
444
|
+
return;
|
|
445
|
+
// Reuse DM8's bounded frontmatter reader and conservative YAML rules. A hook key is
|
|
446
|
+
// enough: interpreting arbitrary YAML to prove a matcher harmless would fail open.
|
|
447
|
+
try {
|
|
448
|
+
const front = subagentFrontmatter(file);
|
|
449
|
+
if (hookedFrontmatter(front))
|
|
450
|
+
blocked(`the Claude Code ${kind} definition ${file} has hooks or frontmatter relay cannot rule out as hooked`);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
blocked(`relay could not read the Claude Code ${kind} frontmatter in ${file}`);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
const definitions = (dir, kind) => walk(dir, (file) => definition(file, kind));
|
|
457
|
+
const walk = (dir, file, visited = new Set(), depth = 0, skip = new Set()) => {
|
|
458
|
+
try {
|
|
459
|
+
if (!present(dir))
|
|
460
|
+
return;
|
|
461
|
+
const real = fs.realpathSync(dir);
|
|
462
|
+
if (visited.has(real))
|
|
463
|
+
return;
|
|
464
|
+
visited.add(real);
|
|
465
|
+
if (depth > 32)
|
|
466
|
+
throw new Error("directory nesting exceeds scan bound");
|
|
467
|
+
if (!fs.statSync(dir).isDirectory()) {
|
|
468
|
+
file(dir);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
for (const entry of fs.readdirSync(dir).sort()) {
|
|
472
|
+
if (skip.has(entry))
|
|
473
|
+
continue;
|
|
474
|
+
const at = path.join(dir, entry);
|
|
475
|
+
if (fs.statSync(at).isDirectory())
|
|
476
|
+
walk(at, file, visited, depth + 1, skip);
|
|
477
|
+
else
|
|
478
|
+
file(at);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
blocked(`relay could not read the Claude Code extension definitions in ${dir}`);
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
const plugin = (root) => {
|
|
486
|
+
let real;
|
|
487
|
+
try {
|
|
488
|
+
real = fs.realpathSync(root);
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
blocked(`relay could not read the Claude Code plugin in ${root}`);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (seen.has(real))
|
|
495
|
+
return;
|
|
496
|
+
seen.add(real);
|
|
497
|
+
const manifest = path.join(root, ".claude-plugin/plugin.json");
|
|
498
|
+
try {
|
|
499
|
+
const raw = present(manifest) ? read(manifest) : {};
|
|
500
|
+
if (!object(raw))
|
|
501
|
+
throw new Error("invalid manifest");
|
|
502
|
+
const declared = raw.hooks === undefined ? [] : Array.isArray(raw.hooks) ? raw.hooks : [raw.hooks];
|
|
503
|
+
for (const hook of declared) {
|
|
504
|
+
if (typeof hook === "string")
|
|
505
|
+
hooksFile(path.resolve(root, hook));
|
|
506
|
+
else
|
|
507
|
+
hookMap(hook, manifest);
|
|
508
|
+
}
|
|
509
|
+
const standard = path.join(root, "hooks/hooks.json");
|
|
510
|
+
if (present(standard))
|
|
511
|
+
hooksFile(standard);
|
|
512
|
+
definitions(path.join(root, "skills"), "skill");
|
|
513
|
+
definitions(path.join(root, "agents"), "subagent");
|
|
514
|
+
definitions(path.join(root, "commands"), "command");
|
|
515
|
+
if (present(path.join(root, "SKILL.md")))
|
|
516
|
+
definitions(path.join(root, "SKILL.md"), "skill");
|
|
517
|
+
for (const [key, kind] of [["skills", "skill"], ["agents", "subagent"], ["commands", "command"]]) {
|
|
518
|
+
if (raw[key] === undefined)
|
|
519
|
+
continue;
|
|
520
|
+
const paths = Array.isArray(raw[key]) ? raw[key] : [raw[key]];
|
|
521
|
+
for (const component of paths) {
|
|
522
|
+
if (typeof component !== "string")
|
|
523
|
+
throw new Error("uninspectable component declaration");
|
|
524
|
+
definitions(path.resolve(root, component), kind);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
blocked(`relay could not read the Claude Code plugin manifest in ${manifest}`);
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
// Skills declared by marketplace entries, checked once every plugin cache and install path is known.
|
|
533
|
+
const declaredSkills = [];
|
|
534
|
+
const marketplaces = new Set();
|
|
535
|
+
const marketplace = (file) => {
|
|
536
|
+
// Marketplace entries may supplement or replace a manifest, including custom hooks paths.
|
|
537
|
+
// Without the running loader's effective entry, do not assume its on-disk manifest is all.
|
|
538
|
+
// Declared hooks, agents and commands still withhold. Declared skills are read instead
|
|
539
|
+
// (marketplaceSkills): a skill can carry hooks only in its SKILL.md frontmatter.
|
|
540
|
+
try {
|
|
541
|
+
const real = fs.realpathSync(file);
|
|
542
|
+
if (marketplaces.has(real))
|
|
543
|
+
return;
|
|
544
|
+
marketplaces.add(real);
|
|
545
|
+
const raw = read(file);
|
|
546
|
+
if (!object(raw) || !Array.isArray(raw.plugins) || raw.plugins.some((p) => !object(p)))
|
|
547
|
+
throw new Error("invalid marketplace manifest");
|
|
548
|
+
for (const entry of raw.plugins) {
|
|
549
|
+
if (["hooks", "agents", "commands"].some((k) => k in entry))
|
|
550
|
+
blocked(`the Claude Code marketplace manifest in ${file} declares extension components whose effective hook sources relay cannot establish`);
|
|
551
|
+
else if ("skills" in entry)
|
|
552
|
+
declaredSkills.push({ manifest: file, home: path.dirname(path.dirname(file)), metadata: raw.metadata, entry });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
blocked(`relay could not read the Claude Code marketplace manifest in ${file}`);
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
// Every recorded install path, by plugin name (the part of `name@marketplace` before the "@").
|
|
560
|
+
const installs = new Map();
|
|
561
|
+
const inside = (root, at) => at === root || at.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
|
|
562
|
+
/**
|
|
563
|
+
* An entry's declared skill paths resolve against its plugin root, which is wherever a copy of
|
|
564
|
+
* the plugin is on disk: under the marketplace for a relative `source` ("./x", or "x" under
|
|
565
|
+
* `metadata.pluginRoot`), and every cached version (`plugins/cache/<marketplace>/<plugin>/<v>`,
|
|
566
|
+
* under any marketplace, since a renamed one would still load) or recorded install path. A
|
|
567
|
+
* remote plugin that was never installed has no copy, and nothing of it can load. Each SKILL.md
|
|
568
|
+
* under a declared path gets the same frontmatter check as any other skill; one that cannot be
|
|
569
|
+
* read, or that resolves outside its plugin root (a link out, or `..`), withholds.
|
|
570
|
+
*/
|
|
571
|
+
const marketplaceSkills = ({ manifest, home, metadata, entry }) => {
|
|
572
|
+
const fail = (why) => blocked(`the Claude Code marketplace manifest in ${manifest} declares skills ${why}`);
|
|
573
|
+
const name = entry.name;
|
|
574
|
+
const paths = Array.isArray(entry.skills) ? entry.skills : [entry.skills];
|
|
575
|
+
if (typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name))
|
|
576
|
+
return fail("for a plugin whose name relay cannot place in the plugin cache");
|
|
577
|
+
if (!paths.length || paths.some((p) => typeof p !== "string"))
|
|
578
|
+
return fail(`for ${name} that relay cannot inspect`);
|
|
579
|
+
const roots = [];
|
|
580
|
+
if (typeof entry.source === "string") {
|
|
581
|
+
const base = object(metadata) ? metadata.pluginRoot : undefined;
|
|
582
|
+
if (base !== undefined && typeof base !== "string")
|
|
583
|
+
return fail(`for ${name} under a plugin root relay cannot read`);
|
|
584
|
+
for (const at of [path.resolve(home, entry.source), ...(base === undefined ? [] : [path.resolve(home, base, entry.source)])]) {
|
|
585
|
+
if (!inside(home, at))
|
|
586
|
+
return fail(`for ${name} from a source outside the marketplace`);
|
|
587
|
+
roots.push(at);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
else if (!object(entry.source))
|
|
591
|
+
return fail(`for ${name} from a source relay cannot read`);
|
|
592
|
+
for (const config of configs) {
|
|
593
|
+
const cache = path.join(config, "plugins", "cache");
|
|
594
|
+
try {
|
|
595
|
+
for (const market of present(cache) ? fs.readdirSync(cache).sort() : []) {
|
|
596
|
+
const dir = path.join(cache, market, name);
|
|
597
|
+
if (!present(dir))
|
|
598
|
+
continue;
|
|
599
|
+
for (const version of fs.readdirSync(dir).sort()) {
|
|
600
|
+
const at = path.join(dir, version);
|
|
601
|
+
if (fs.statSync(at).isDirectory())
|
|
602
|
+
roots.push(at);
|
|
603
|
+
// A zipped cache entry cannot be inspected without unpacking it.
|
|
604
|
+
else if (version.endsWith(".zip"))
|
|
605
|
+
fail(`for ${name}, which has a zipped copy in ${dir} relay cannot inspect`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
catch {
|
|
610
|
+
fail(`for ${name}, and relay could not read the Claude Code plugin cache in ${cache}`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
roots.push(...(installs.get(name) ?? []));
|
|
614
|
+
for (const root of new Set(roots)) {
|
|
615
|
+
let real;
|
|
616
|
+
try {
|
|
617
|
+
real = fs.realpathSync(root);
|
|
618
|
+
}
|
|
619
|
+
catch (e) {
|
|
620
|
+
if (e.code !== "ENOENT")
|
|
621
|
+
fail(`for ${name} in ${root}, which relay could not read`);
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
// The copy's default components load alongside the declared skills, manifest or not.
|
|
625
|
+
plugin(root);
|
|
626
|
+
for (const declared of paths) {
|
|
627
|
+
const at = path.resolve(root, declared);
|
|
628
|
+
if (!inside(path.resolve(root), at)) {
|
|
629
|
+
fail(`for ${name} at ${declared}, outside its plugin directory ${root}`);
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
// Claude loads nothing from a declared path that is not there.
|
|
633
|
+
walk(at, (file) => {
|
|
634
|
+
let target;
|
|
635
|
+
try {
|
|
636
|
+
target = fs.realpathSync(file);
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
fail(`for ${name}, and relay could not read ${file}`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
if (!inside(real, target)) {
|
|
643
|
+
fail(`for ${name}, and ${file} leads outside its plugin directory ${root}`);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
definition(file, "skill");
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
const pluginTree = (root) => walk(root, (file) => {
|
|
652
|
+
if (path.basename(file) === "plugin.json" && path.basename(path.dirname(file)) === ".claude-plugin")
|
|
653
|
+
plugin(path.dirname(path.dirname(file)));
|
|
654
|
+
if (path.basename(file) === "hooks.json" && path.basename(path.dirname(file)) === "hooks")
|
|
655
|
+
hooksFile(file);
|
|
656
|
+
if (path.basename(file) === "marketplace.json" && path.basename(path.dirname(file)) === ".claude-plugin")
|
|
657
|
+
marketplace(file);
|
|
658
|
+
}, new Set(), 0, new Set([".git", "node_modules"]));
|
|
659
|
+
for (const config of configs) {
|
|
660
|
+
const plugins = path.join(config, "plugins");
|
|
661
|
+
// Include all on-disk versions, plus local/in-place installs outside the cache.
|
|
662
|
+
pluginTree(plugins);
|
|
663
|
+
// Every cached version is a plugin root, with or without a plugin.json: a marketplace entry
|
|
664
|
+
// can stand in for the manifest, and Claude still loads the default skills/, agents/,
|
|
665
|
+
// commands/ and hooks/hooks.json of the copy. Older versions stay loaded in running sessions.
|
|
666
|
+
const cache = path.join(plugins, "cache");
|
|
667
|
+
try {
|
|
668
|
+
for (const market of present(cache) ? fs.readdirSync(cache).sort() : []) {
|
|
669
|
+
if (!fs.statSync(path.join(cache, market)).isDirectory())
|
|
670
|
+
continue;
|
|
671
|
+
for (const name of fs.readdirSync(path.join(cache, market)).sort()) {
|
|
672
|
+
const dir = path.join(cache, market, name);
|
|
673
|
+
if (!fs.statSync(dir).isDirectory())
|
|
674
|
+
continue;
|
|
675
|
+
for (const version of fs.readdirSync(dir).sort()) {
|
|
676
|
+
if (fs.statSync(path.join(dir, version)).isDirectory())
|
|
677
|
+
plugin(path.join(dir, version));
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
catch {
|
|
683
|
+
blocked(`relay could not read the Claude Code plugin cache in ${cache}`);
|
|
684
|
+
}
|
|
685
|
+
for (const name of ["known_marketplaces.json", "known_marketplaces_claudeai.json"]) {
|
|
686
|
+
const registry = path.join(plugins, name);
|
|
687
|
+
try {
|
|
688
|
+
if (!present(registry))
|
|
689
|
+
continue;
|
|
690
|
+
const raw = read(registry);
|
|
691
|
+
if (!object(raw))
|
|
692
|
+
throw new Error("invalid marketplace registry");
|
|
693
|
+
for (const row of Object.values(raw)) {
|
|
694
|
+
if (!object(row) || typeof row.installLocation !== "string" || !path.isAbsolute(row.installLocation))
|
|
695
|
+
throw new Error("missing marketplace location");
|
|
696
|
+
pluginTree(row.installLocation);
|
|
697
|
+
const manifest = path.join(row.installLocation, ".claude-plugin/marketplace.json");
|
|
698
|
+
if (!present(manifest))
|
|
699
|
+
throw new Error("missing marketplace manifest");
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
catch {
|
|
703
|
+
blocked(`relay could not read the Claude Code marketplace registry in ${registry}`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const installed = path.join(plugins, "installed_plugins.json");
|
|
707
|
+
try {
|
|
708
|
+
if (present(installed)) {
|
|
709
|
+
const raw = read(installed);
|
|
710
|
+
if (!object(raw) || !object(raw.plugins))
|
|
711
|
+
throw new Error("invalid plugin registry");
|
|
712
|
+
for (const [key, rows] of Object.entries(raw.plugins)) {
|
|
713
|
+
if (!Array.isArray(rows))
|
|
714
|
+
throw new Error("invalid plugin installs");
|
|
715
|
+
for (const row of rows) {
|
|
716
|
+
if (!object(row) || typeof row.installPath !== "string" || !path.isAbsolute(row.installPath))
|
|
717
|
+
throw new Error("missing install path");
|
|
718
|
+
plugin(row.installPath);
|
|
719
|
+
const name = key.split("@")[0];
|
|
720
|
+
installs.set(name, [...(installs.get(name) ?? []), row.installPath]);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
blocked(`relay could not read the Claude Code installed plugin manifest in ${installed}`);
|
|
727
|
+
}
|
|
728
|
+
definitions(path.join(config, "skills"), "skill");
|
|
729
|
+
definitions(path.join(config, "commands"), "command");
|
|
730
|
+
}
|
|
731
|
+
for (const declared of declaredSkills)
|
|
732
|
+
marketplaceSkills(declared);
|
|
733
|
+
// Personal and repository skill roots are independent of the settings hook files.
|
|
734
|
+
for (let dir = path.resolve(cwd);; dir = path.dirname(dir)) {
|
|
735
|
+
definitions(path.join(dir, ".claude/skills"), "skill");
|
|
736
|
+
definitions(path.join(dir, ".claude/commands"), "command");
|
|
737
|
+
if (dir === home || fs.existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir)
|
|
738
|
+
break;
|
|
739
|
+
}
|
|
740
|
+
// Claude lazily discovers nested .claude/skills when it reads files in that subtree. Those
|
|
741
|
+
// hooks can already exist when this server starts even though no init report names them yet.
|
|
742
|
+
const nested = (dir, visited = new Set(), depth = 0) => {
|
|
743
|
+
try {
|
|
744
|
+
const real = fs.realpathSync(dir);
|
|
745
|
+
if (visited.has(real))
|
|
746
|
+
return;
|
|
747
|
+
visited.add(real);
|
|
748
|
+
if (depth > 32)
|
|
749
|
+
throw new Error("directory nesting exceeds scan bound");
|
|
750
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
751
|
+
if (entry.name === ".git")
|
|
752
|
+
continue; // Git metadata is never a project skill root.
|
|
753
|
+
const at = path.join(dir, entry.name);
|
|
754
|
+
if (!entry.isDirectory() && !(entry.isSymbolicLink() && fs.statSync(at).isDirectory()))
|
|
755
|
+
continue;
|
|
756
|
+
if (entry.name === ".claude") {
|
|
757
|
+
definitions(path.join(at, "skills"), "skill");
|
|
758
|
+
definitions(path.join(at, "commands"), "command");
|
|
759
|
+
}
|
|
760
|
+
else
|
|
761
|
+
nested(at, visited, depth + 1);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
blocked(`relay could not inspect nested Claude Code skill roots in ${dir}`);
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
// A home-directory session has no bounded project tree to inspect safely: its own roots were
|
|
769
|
+
// checked above, but nested roots cannot be ruled out without scanning the person's home.
|
|
770
|
+
if (path.resolve(cwd) === path.resolve(home))
|
|
771
|
+
blocked("relay cannot rule out nested Claude Code skill hooks for a session started in the home directory");
|
|
772
|
+
else
|
|
773
|
+
nested(path.resolve(cwd));
|
|
774
|
+
for (const line of commandLines) {
|
|
775
|
+
// ps joins argv with spaces. Quoting/archives/URLs cannot be established as an inspectable
|
|
776
|
+
// directory; fail closed rather than mistaking a partial argument for the plugin root.
|
|
777
|
+
// ps has lost argv boundaries: a valid directory prefix cannot prove the full argument.
|
|
778
|
+
// Withhold for any CLI-only plugin rather than trusting a possibly truncated path.
|
|
779
|
+
if (/(?:^|\s)--plugin-dir(?:=|\s|$)/.test(line))
|
|
780
|
+
blocked("relay could not inspect a Claude Code --plugin-dir argument with certainty from its command line");
|
|
781
|
+
if (/(?:^|\s)--plugin-url(?:=|\s)/.test(line))
|
|
782
|
+
blocked("relay could not inspect a Claude Code --plugin-url argument");
|
|
783
|
+
}
|
|
784
|
+
if (env.CLAUDE_CODE_PLUGIN_DIRS) {
|
|
785
|
+
// The CLI's environment form has varied between releases; do not guess its delimiter.
|
|
786
|
+
blocked("relay could not inspect Claude Code plugins supplied by CLAUDE_CODE_PLUGIN_DIRS");
|
|
787
|
+
}
|
|
788
|
+
// Both move plugin files out of the plugins directories scanned above: CLAUDE_CODE_PLUGIN_CACHE_DIR
|
|
789
|
+
// relocates the whole plugins root (cache, registries, marketplaces), and a seed directory
|
|
790
|
+
// supplies pre-installed plugins.
|
|
791
|
+
for (const name of ["CLAUDE_CODE_PLUGIN_CACHE_DIR", "CLAUDE_CODE_PLUGIN_SEED_DIR"]) {
|
|
792
|
+
if (env[name])
|
|
793
|
+
blocked(`relay could not inspect Claude Code plugins under ${name}`);
|
|
794
|
+
}
|
|
795
|
+
return out;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Whether Claude Code could read a top-level `hooks` key from a definition's frontmatter block, or
|
|
799
|
+
* relay cannot rule one out. Claude Code (2.1.326) ends the block at the first `---` anywhere, not
|
|
800
|
+
* only at a delimiter line, parses it with Bun's YAML parser, and when that throws, parses it once
|
|
801
|
+
* more after double-quoting the value of each `key: value` line at column 0. A definition's hooks
|
|
802
|
+
* are the `hooks` property of the result. In each of those readings a top-level key is an implicit
|
|
803
|
+
* key that starts at column 0, so this check's safety rests on two rules:
|
|
804
|
+
* 1. no `hooks` followed by `:` anywhere in the block, even quoted, folded or nested; and
|
|
805
|
+
* 2. every line that starts at column 0 is a comment, a `- ` entry of the sequence under the key
|
|
806
|
+
* before it, or a plain `key:` entry whose key is not `hooks`, and none continues a quoted
|
|
807
|
+
* scalar or flow sequence left open by an earlier line.
|
|
808
|
+
* The rest is margin. Relay withholds for YAML it does not model, rather than reason about how Bun
|
|
809
|
+
* reads it: flow mappings, anchors, aliases, tags, directives, quoted and explicit keys, duplicate
|
|
810
|
+
* top-level keys, nested flow collections, and comments or implicit pairs inside a flow sequence.
|
|
811
|
+
* A `:` not followed by a space, as in `Bash(git add:*)`, is part of a plain scalar, as in YAML.
|
|
812
|
+
*/
|
|
813
|
+
export function hookedFrontmatter(front) {
|
|
814
|
+
if (/(?:^|[^A-Za-z0-9_-])hooks["']?\s*:/im.test(front))
|
|
815
|
+
return true;
|
|
816
|
+
const KEY = /^([A-Za-z_][A-Za-z0-9_-]*):(?: +(.*))?$/;
|
|
817
|
+
const ITEM = /^-(?: |$)/;
|
|
818
|
+
const keys = new Set();
|
|
819
|
+
// A quoted scalar or flow sequence that continues on the next line.
|
|
820
|
+
let open = null;
|
|
821
|
+
// Lines indented beyond this continue a plain or block scalar.
|
|
822
|
+
let cont = null;
|
|
823
|
+
// The last top-level key's value is on the indented lines (or `- ` entries) after it; `node`
|
|
824
|
+
// while the next such line may be that value itself (`description:\n "text"`).
|
|
825
|
+
let nested = false, node = false;
|
|
826
|
+
const closed = (rest) => /^(?: +#.*| *)$/.test(rest);
|
|
827
|
+
/** A value's node: false when relay does not model it. */
|
|
828
|
+
const value = (v, parent, top = false) => {
|
|
829
|
+
if (!v || v.startsWith("#"))
|
|
830
|
+
return true;
|
|
831
|
+
if (v[0] === "|" || v[0] === ">") {
|
|
832
|
+
cont = parent;
|
|
833
|
+
return /^[|>](?:[1-9][+-]?|[+-][1-9]?)?(?: +#.*| *)$/.test(v);
|
|
834
|
+
}
|
|
835
|
+
if (v[0] === '"' || v[0] === "'" || v[0] === "[") {
|
|
836
|
+
const r = scanNode(v.slice(1), v[0] === "[" ? { quote: null, flow: true, sep: false } : { quote: v[0], flow: false, sep: false });
|
|
837
|
+
if (r === null)
|
|
838
|
+
return false;
|
|
839
|
+
// Text after a node that closes on a top-level key line (`argument-hint: [a] [b]`) makes
|
|
840
|
+
// Bun's parse throw, and Claude's retry then quotes the whole value or reads no keys at all.
|
|
841
|
+
if (typeof r === "string")
|
|
842
|
+
return closed(r) || top;
|
|
843
|
+
open = r;
|
|
844
|
+
return true;
|
|
845
|
+
}
|
|
846
|
+
// A plain scalar. A `: ` in it can at most nest a key under this one (or, in Claude's retry,
|
|
847
|
+
// be quoted), never add a top-level key; a `hooks:` in it is caught above.
|
|
848
|
+
if (/^(?:[\]{}&*!%@`#,]|[?:-](?: |$))/.test(v))
|
|
849
|
+
return false;
|
|
850
|
+
cont = parent;
|
|
851
|
+
return true;
|
|
852
|
+
};
|
|
853
|
+
/** A block sequence entry or nested mapping entry. */
|
|
854
|
+
const entry = (text, indent) => {
|
|
855
|
+
const item = ITEM.test(text);
|
|
856
|
+
const rest = item ? text.replace(/^- */, "") : text;
|
|
857
|
+
const pair = KEY.exec(rest);
|
|
858
|
+
if (pair)
|
|
859
|
+
return value(pair[2] ?? "", indent);
|
|
860
|
+
return item && !ITEM.test(rest) && value(rest, indent);
|
|
861
|
+
};
|
|
862
|
+
for (const line of front.split(/\r\n|\r|\n/)) {
|
|
863
|
+
const indent = /^ */.exec(line)[0].length;
|
|
864
|
+
const text = line.slice(indent);
|
|
865
|
+
if (open) {
|
|
866
|
+
if (indent === 0 && text)
|
|
867
|
+
return true;
|
|
868
|
+
const r = scanNode(text, open);
|
|
869
|
+
if (r === null)
|
|
870
|
+
return true;
|
|
871
|
+
if (typeof r === "string") {
|
|
872
|
+
open = null;
|
|
873
|
+
if (!closed(r))
|
|
874
|
+
return true;
|
|
875
|
+
}
|
|
876
|
+
else
|
|
877
|
+
open = r;
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
if (!text)
|
|
881
|
+
continue;
|
|
882
|
+
if (cont !== null && indent > cont)
|
|
883
|
+
continue;
|
|
884
|
+
cont = null;
|
|
885
|
+
if (text.startsWith("#"))
|
|
886
|
+
continue;
|
|
887
|
+
if (indent === 0 && nested && ITEM.test(text)) {
|
|
888
|
+
node = false;
|
|
889
|
+
if (!entry(text, 0))
|
|
890
|
+
return true;
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
if (indent === 0) {
|
|
894
|
+
const pair = KEY.exec(text);
|
|
895
|
+
if (!pair || pair[1].toLowerCase() === "hooks" || keys.has(pair[1]))
|
|
896
|
+
return true;
|
|
897
|
+
keys.add(pair[1]);
|
|
898
|
+
const v = pair[2] ?? "";
|
|
899
|
+
nested = node = !v || v.startsWith("#");
|
|
900
|
+
if (!value(v, 0, true))
|
|
901
|
+
return true;
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
if (!nested)
|
|
905
|
+
return true;
|
|
906
|
+
if (node) {
|
|
907
|
+
node = false;
|
|
908
|
+
if (!ITEM.test(text) && !KEY.test(text)) {
|
|
909
|
+
nested = false;
|
|
910
|
+
if (!value(text, 0))
|
|
911
|
+
return true;
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
if (!entry(text, indent))
|
|
916
|
+
return true;
|
|
917
|
+
}
|
|
918
|
+
return open !== null;
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Scan a quoted scalar or a flat flow sequence of scalars from just after its opening character,
|
|
922
|
+
* or onward from `from` on a later line. Returns the state when the node runs past the end of the
|
|
923
|
+
* text, the text after it when it closes, or null for anything else (nested collections, anchors,
|
|
924
|
+
* aliases, tags, comments, implicit pairs).
|
|
925
|
+
*/
|
|
926
|
+
function scanNode(text, from) {
|
|
927
|
+
const s = { ...from };
|
|
928
|
+
let i = 0;
|
|
929
|
+
for (;;) {
|
|
930
|
+
if (s.quote) {
|
|
931
|
+
for (; i < text.length; i++) {
|
|
932
|
+
if (s.quote === '"' && text[i] === "\\")
|
|
933
|
+
i++;
|
|
934
|
+
else if (s.quote === "'" && text[i] === "'" && text[i + 1] === "'")
|
|
935
|
+
i++;
|
|
936
|
+
else if (text[i] === s.quote)
|
|
937
|
+
break;
|
|
938
|
+
}
|
|
939
|
+
if (i >= text.length)
|
|
940
|
+
return s;
|
|
941
|
+
i++;
|
|
942
|
+
s.quote = null;
|
|
943
|
+
if (!s.flow)
|
|
944
|
+
return text.slice(i);
|
|
945
|
+
s.sep = true;
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
while (text[i] === " ")
|
|
949
|
+
i++;
|
|
950
|
+
if (i >= text.length)
|
|
951
|
+
return s;
|
|
952
|
+
const c = text[i];
|
|
953
|
+
if (s.sep) {
|
|
954
|
+
if (c === ",") {
|
|
955
|
+
s.sep = false;
|
|
956
|
+
i++;
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
return c === "]" ? text.slice(i + 1) : null;
|
|
960
|
+
}
|
|
961
|
+
if (c === "]")
|
|
962
|
+
return text.slice(i + 1);
|
|
963
|
+
if (c === '"' || c === "'") {
|
|
964
|
+
s.quote = c;
|
|
965
|
+
i++;
|
|
966
|
+
continue;
|
|
967
|
+
}
|
|
968
|
+
if (/[[\]{},&*!|>%@`#]/.test(c) || (/[?:-]/.test(c) && /^[ ,\]]?$/.test(text[i + 1] ?? "")))
|
|
969
|
+
return null;
|
|
970
|
+
const plain = /^[^,[\]{}]*/.exec(text.slice(i))[0];
|
|
971
|
+
i += plain.length;
|
|
972
|
+
// In a flow sequence a `:` before a space, `,`, `]` or the line's end would make a pair.
|
|
973
|
+
if (/ #|:(?: |$)/.test(plain.trimEnd()) || (i < text.length && text[i] !== "," && text[i] !== "]"))
|
|
974
|
+
return null;
|
|
975
|
+
s.sep = true;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
/** Only the leading frontmatter block, capped at 64 KiB; never parse or retain the agent body. */
|
|
979
|
+
function subagentFrontmatter(file) {
|
|
980
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
|
|
981
|
+
try {
|
|
982
|
+
if (!fs.fstatSync(fd).isFile())
|
|
983
|
+
throw new Error("not a regular definition file");
|
|
984
|
+
let bytes = Buffer.alloc(0);
|
|
985
|
+
for (;;) {
|
|
986
|
+
const chunk = Buffer.alloc(4096);
|
|
987
|
+
const n = fs.readSync(fd, chunk, 0, chunk.length, null);
|
|
988
|
+
bytes = Buffer.concat([bytes, chunk.subarray(0, n)]);
|
|
989
|
+
// Locate ASCII delimiters before decoding, so an odd encoding or malformed UTF-8 fails
|
|
990
|
+
// rather than silently replacing bytes. Decode the frontmatter only, not a chunk of body.
|
|
991
|
+
const raw = bytes.toString("latin1");
|
|
992
|
+
const start = /^---\r?\n/.exec(raw);
|
|
993
|
+
if (!start)
|
|
994
|
+
throw new Error("missing leading delimiter");
|
|
995
|
+
const end = /(?:^|\n)---(?:\r?\n|$)/g;
|
|
996
|
+
end.lastIndex = start[0].length;
|
|
997
|
+
const close = end.exec(raw);
|
|
998
|
+
if (close) {
|
|
999
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(start[0].length, close.index));
|
|
1000
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u0085\u2028\u2029\ufeff\t]/.test(text))
|
|
1001
|
+
throw new Error("odd encoding or tabs");
|
|
1002
|
+
return text;
|
|
1003
|
+
}
|
|
1004
|
+
if (!n || bytes.length >= 65536)
|
|
1005
|
+
throw new Error("unterminated or oversized frontmatter");
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
finally {
|
|
1009
|
+
fs.closeSync(fd);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
export function subagentHooksProblem(env, cwd, localDirs = localSettingsDirs(cwd)) {
|
|
1013
|
+
const home = env.HOME || os.homedir();
|
|
1014
|
+
const dirs = [...new Set([
|
|
1015
|
+
...(env.CLAUDE_CONFIG_DIR ? [path.join(env.CLAUDE_CONFIG_DIR, "agents")] : []),
|
|
1016
|
+
path.join(home, ".claude", "agents"),
|
|
1017
|
+
...localDirs.map((d) => path.join(d, ".claude", "agents")),
|
|
1018
|
+
])];
|
|
1019
|
+
for (const dir of dirs) {
|
|
1020
|
+
let files;
|
|
1021
|
+
try {
|
|
1022
|
+
files = fs.readdirSync(dir).filter((n) => n.endsWith(".md")).sort();
|
|
1023
|
+
}
|
|
1024
|
+
catch (err) {
|
|
1025
|
+
if (err.code === "ENOENT")
|
|
1026
|
+
continue;
|
|
1027
|
+
return `relay could not read the Claude Code subagent definitions in ${dir}`;
|
|
1028
|
+
}
|
|
1029
|
+
for (const name of files) {
|
|
1030
|
+
const file = path.join(dir, name);
|
|
1031
|
+
let front;
|
|
1032
|
+
try {
|
|
1033
|
+
front = subagentFrontmatter(file);
|
|
1034
|
+
}
|
|
1035
|
+
catch {
|
|
1036
|
+
return `relay could not read the Claude Code subagent frontmatter in ${file}`;
|
|
1037
|
+
}
|
|
1038
|
+
// A hooks key, or YAML that relay does not model and so cannot rule one out (see hookedFrontmatter).
|
|
1039
|
+
if (hookedFrontmatter(front)) {
|
|
1040
|
+
return `the Claude Code subagent definition ${file} has hooks or frontmatter relay cannot rule out as hooked; conservatively withholding the confirm and adopt permission prompts`;
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
return null;
|
|
1045
|
+
}
|