Module: PWN::Config
- Defined in:
- lib/pwn/config.rb
Overview
Used to manage PWN configuration settings within PWN drivers.
Constant Summary collapse
- SKILL_ENTRY =
────────────────────────────────────────────────────────────────────── SKILLS (agentskills.io/specification conformant, with legacy shim) ──────────────────────────────────────────────────────────────────────
On-disk layout (spec):
~/.pwn/skills/<name>/SKILL.md ← required entrypoint, YAML frontmatter ~/.pwn/skills/<name>/scripts/Legacy shim (read-only, still loaded so nothing breaks on upgrade):
~/.pwn/skills/<name>.{md,txt,rb,skill,yml,yaml}Frontmatter (SKILL.md,
---YAML block at top of file):name: REQUIRED [a-z0-9-]{1,64}, must equal parent dir name description: REQUIRED 1..1024 chars license: optional metadata: optional Hash (pwn stores references here too) allowed-tools: optional Array of toolset names──────────────────────────────────────────────────────────────────────
'SKILL.md'- SKILL_NAME_RE =
/\A[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\z/- DEFAULT_SKILLS_DIR =
File.('../../etc/default_skills', __dir__)
Class Method Summary collapse
-
.authors ⇒ Object
- Author(s)
0day Inc.
-
.default_env(opts = {}) ⇒ Object
- Supported Method Parameters
env = PWN::Config.default_env( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' ).
- .default_skill_names(opts = {}) ⇒ Object
- .default_skills_dir(opts = {}) ⇒ Object
-
.env_template ⇒ Object
- Supported Method Parameters
tmpl = PWN::Config.env_template.
-
.help ⇒ Object
Display Usage for this Module.
-
.init_driver_options ⇒ Object
- Supported Method Parameters
env = PWN::Config.init_driver_options.
-
.install_default_skills(opts = {}) ⇒ Object
Seed bundled skills into ~/.pwn/skills (or pwn_skills_path:).
-
.load_memory ⇒ Object
- Supported Method Parameters
PWN::Config.load_memory.
-
.load_skills(opts = {}) ⇒ Object
- Supported Method Parameters
skills = PWN::Config.load_skills( pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills' ).
-
.migrate_legacy_skills(opts = {}) ⇒ Object
- Supported Method Parameters
report = PWN::Config.migrate_legacy_skills( pwn_skills_path: 'optional - override skills root', delete_legacy: 'optional - remove flat file after migration (default true)' ).
-
.parse_skill_frontmatter(opts = {}) ⇒ Object
- Supported Method Parameters
fm = PWN::Config.parse_skill_frontmatter(content: '...').
-
.parse_skill_references(opts = {}) ⇒ Object
- Supported Method Parameters
refs = PWN::Config.parse_skill_references(content: '...').
-
.pwn_cron_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_cron_path.
-
.pwn_memory_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_memory_path.
-
.pwn_sessions_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_sessions_path.
-
.pwn_skills_path(opts = {}) ⇒ Object
- Supported Method Parameters
pwn_skills_path = PWN::Config.pwn_skills_path( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' ).
-
.redact_sensitive_artifacts(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Config.redact_sensitive_artifacts( config: 'optional - Hash to redact sensitive artifacts from. Defaults to PWN::Env' ).
- .refresh_env(opts = {}) ⇒ Object
-
.sanitize_skill_name(opts = {}) ⇒ Object
- Supported Method Parameters
name = PWN::Config.sanitize_skill_name(name: 'My Cool Skill!').
-
.write_skill(opts = {}) ⇒ Object
- Supported Method Parameters
out = PWN::Config.write_skill( name: 'required - free-form; sanitised to [a-z0-9-]', content: 'required - markdown body (WITHOUT frontmatter)', description: 'optional - 1..1024 chars; derived from body when omitted', references: 'optional - Array of URLs / CWE / CVE / ATT&CK / NIST ids', license: 'optional - SPDX id or free text', metadata: 'optional - Hash of arbitrary metadata', allowed_tools: 'optional - Array of toolset names', pwn_skills_path: 'optional - override skills root' ).
Class Method Details
.authors ⇒ Object
- Author(s)
0day Inc. [email protected]
1088 1089 1090 1091 1092 |
# File 'lib/pwn/config.rb', line 1088 public_class_method def self. "AUTHOR(S): 0day Inc. <[email protected]> " end |
.default_env(opts = {}) ⇒ Object
- Supported Method Parameters
env = PWN::Config.default_env( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' )
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
# File 'lib/pwn/config.rb', line 327 public_class_method def self.default_env(opts = {}) pwn_env_path = opts[:pwn_env_path] pwn_dec_path = "#{pwn_env_path}.decryptor" puts " [*] NOTICE: 1. Writing minimal PWN::Env to: #{pwn_env_path} 2. Your decryptor file will be written to: #{pwn_dec_path} 3. Use the pwn-vault command in the pwn prototyping driver to update: #{pwn_env_path} 4. For optimal security, it's recommended to move: #{pwn_dec_path} to a secure location and use the --pwn-dec parameter for PWN drivers. " env = env_template # Remove beginning colon from key names yaml_env = YAML.dump(env).gsub(/^(\s*):/, '\1') File.write(pwn_env_path, yaml_env) # Change file permission to 600 File.chmod(0o600, pwn_env_path) # Ensure skills dir for pwn-ai agent (in parent of pwn_env_path) pwn_env_root = File.dirname(pwn_env_path) pwn_skills_path = File.join(pwn_env_root, 'skills') FileUtils.mkdir_p(pwn_skills_path) env[:driver_opts] = { pwn_env_path: pwn_env_path, pwn_dec_path: pwn_dec_path } PWN::Plugins::Vault.create( file: pwn_env_path, decryptor_file: pwn_dec_path ) Pry.config.refresh_pwn_env = false if defined?(Pry) env[:pwn_skills_path] = pwn_skills_path PWN::Config.install_default_skills(pwn_skills_path: pwn_skills_path) PWN::Config.load_skills(pwn_skills_path: pwn_skills_path) # pwn-ai agent: memory/sessions/cron paths env[:pwn_memory_path] = PWN::Memory::MEMORY_FILE if defined?(PWN::Memory) env[:pwn_sessions_path] = PWN::Sessions.sessions_dir if defined?(PWN::Sessions) env[:pwn_cron_path] = PWN::Cron.cron_dir if defined?(PWN::Cron) PWN::Cron.install_defaults if defined?(PWN::Cron) && PWN::Cron.respond_to?(:install_defaults) PWN.send(:remove_const, :Env) if PWN.const_defined?(:Env) PWN.const_set(:Env, env.freeze) rescue StandardError => e raise e end |
.default_skill_names(opts = {}) ⇒ Object
869 870 871 872 873 874 |
# File 'lib/pwn/config.rb', line 869 public_class_method def self.default_skill_names(opts = {}) root = opts[:source] || opts[:root] || default_skills_dir names = [] each_skill_md(root: root) { |_path, rel_dir| names << rel_dir } names.sort end |
.default_skills_dir(opts = {}) ⇒ Object
876 877 878 879 880 |
# File 'lib/pwn/config.rb', line 876 public_class_method def self.default_skills_dir(opts = {}) return DEFAULT_SKILLS_DIR if opts.is_a?(Hash) DEFAULT_SKILLS_DIR end |
.env_template ⇒ Object
- Supported Method Parameters
tmpl = PWN::Config.env_template
The canonical current-release ~/.pwn/pwn.yaml shape as a pure Hash (no I/O, no vault write, no puts). Single source of truth used by:
* PWN::Config.default_env
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/pwn/config.rb', line 18 public_class_method def self.env_template { ai: { active: 'grok', module_reflection: false, grok: { base_uri: 'optional - Base URI for Grok - Use private base OR defaults to https://api.x.ai/v1', key: 'required - xAI Grok API Key', model: 'optional - Grok model to use', system_role_content: 'You are an ethically hacking xAI Grok agent.', temp: 'optional - Grok temperature', max_prompt_length: 256_000, reasoning_effort: 'optional - Grok reasoning effort (default medium; none disables)', # OAuth support for xAI SuperGrok subscriptions (in addition to API key) # Populate via pwn-vault command (values stored encrypted in ~/.pwn/pwn.yaml) oauth: { # xAI Grok OAuth uses a PUBLIC client (Grok-CLI, same as hermes-agent) -- # NO client_secret. Run PWN::AI::Grok.obtain_oauth_bearer_token once # (RFC 8628 device flow) then store refresh_token here; PWN refreshes # the short-lived access_token automatically on every run. refresh_token: 'optional - xAI SuperGrok OAuth Refresh Token (durable; enables silent re-auth)', bearer_token: 'optional - xAI SuperGrok OAuth Access Token (short-lived JWT; auto-refreshed if refresh_token set)', client_id: 'optional - override public Grok-CLI client_id (default: b1a00492-073a-47ea-816f-4c329264a828)', scope: 'optional - override OAuth scope (default: openid profile email offline_access grok-cli:access api:access)', token_uri: 'optional - override OAuth token endpoint (default: https://auth.x.ai/oauth2/token)', enroll: 'optional - set true to force device-flow enrollment even when an API key is present' } }, openai: { base_uri: 'optional - Base URI for OpenAI - Use private base OR defaults to https://api.openai.com/v1', key: 'required - OpenAI API Key', model: 'optional - OpenAI model to use', system_role_content: 'You are an ethically hacking OpenAI agent.', temp: 'optional - OpenAI temperature', reasoning_effort: 'optional - OpenAI reasoning effort (default medium)', max_tokens: 'optional - Max output tokens per response (default 16384). Mapped to OpenAI wire param max_completion_tokens.', max_prompt_length: 128_000, # OAuth support for ChatGPT / Codex subscriptions (in addition to API key) # Populate via pwn-vault (values stored encrypted in ~/.pwn/pwn.yaml) oauth: { # OpenAI OAuth uses the PUBLIC Codex client (app_EMoamEEZ73f0CkXaXp7hrann) -- # NO client_secret. Run PWN::AI::OpenAI.obtain_oauth_bearer_token once # (Codex device-code flow) then store refresh_token here; PWN refreshes # the short-lived access_token automatically on every run. refresh_token: 'optional - ChatGPT/Codex OAuth Refresh Token (durable; enables silent re-auth)', bearer_token: 'optional - ChatGPT/Codex OAuth Access Token (short-lived JWT; auto-refreshed if refresh_token set)', client_id: 'optional - override public Codex client_id (default: app_EMoamEEZ73f0CkXaXp7hrann)', account_id: 'optional - ChatGPT account/workspace id (sent as ChatGPT-Account-Id when set)', issuer: 'optional - override OAuth issuer (default: https://auth.openai.com)', token_uri: 'optional - override OAuth token endpoint (default: https://auth.openai.com/oauth/token)', enroll: 'optional - set true to force device-flow enrollment even when an API key is present' } }, ollama: { # Direct Ollama server (stock: http://127.0.0.1:11434). No key required. base_uri: 'optional - Base URI for Ollama server (default http://127.0.0.1:11434)', key: 'optional - bearer token only if a reverse-proxy sits in front of Ollama (stock ollama needs none)', model: 'required - Ollama model tag to use', embed_model: 'optional - embedding model for PWN::MemoryIndex (default nomic-embed-text)', system_role_content: 'You are an ethically hacking Ollama agent.', temp: 'optional - Ollama temperature', tool_temp: 0.1, # lower temperature when tools are present (chat_with_tools) num_ctx: 32_768, # Cap decode length so thinking models cannot stream forever # (Net::HTTP read_timeout only fires on idle gaps between chunks). num_predict: 4_096, think: true, keep_alive: '30m', # tighten each PromptBuilder block for the local model (nil = engine defaults) prompt_budget: { memory: 6, metrics: 3, mistakes: 3, learning: 2, extro: false }, # omit format:'json' when tools present unless explicitly set (see chat_with_tools) # format: nil, result_max: 4_000, # tool-result cap for local models (frontier keeps Result::DEFAULT_MAX) max_prompt_length: 32_000 }, openwebui: { # Open WebUI gateway in front of one or more model backends. base_uri: 'required - Base URI for Open WebUI - e.g. https://openwebui.local', key: 'required - Open WebUI API Key Under Settings >> Account >> JWT Token', model: 'required - model id/tag exposed by Open WebUI', embed_model: 'optional - embedding model for PWN::MemoryIndex when ollama direct is unset (default nomic-embed-text)', system_role_content: 'You are an ethically hacking Open WebUI agent.', temp: 'optional - Open WebUI temperature', tool_temp: 0.1, # lower temperature when tools are present (chat_with_tools) num_ctx: 32_768, num_predict: 4_096, think: true, keep_alive: '30m', prompt_budget: { memory: 6, metrics: 3, mistakes: 3, learning: 2, extro: false }, result_max: 4_000, max_prompt_length: 32_000 }, anthropic: { base_uri: 'optional - Base URI for Anthropic - Use private base OR defaults to https://api.anthropic.com/v1', key: 'required - Anthropic API Key', model: 'optional - Anthropic model id to use (see provider docs for currently-supported ids)', system_role_content: 'You are an ethically hacking Anthropic agent.', temp: 'optional - Anthropic temperature', max_tokens: 'optional - Max output tokens per response (default 8192). Raise if tool calls truncate.', max_prompt_length: 200_000, # OAuth support for Claude Pro/Max subscriptions (in addition to API key) # Populate via pwn-vault (values stored encrypted in ~/.pwn/pwn.yaml) oauth: { # Anthropic OAuth uses the PUBLIC Claude Code client # (9d1c250a-e61b-44d9-88ed-5944d1962f5e) -- NO client_secret. # Run PWN::AI::Anthropic.obtain_oauth_bearer_token once (PKCE paste # flow) then store refresh_token here; PWN refreshes the short-lived # access_token automatically on every run. refresh_token: 'optional - Claude Pro/Max OAuth Refresh Token (durable; enables silent re-auth)', bearer_token: 'optional - Claude Pro/Max OAuth Access Token (short-lived; auto-refreshed if refresh_token set)', client_id: 'optional - override public Claude Code client_id (default: 9d1c250a-e61b-44d9-88ed-5944d1962f5e)', scope: 'optional - override OAuth scope (default: user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload)', authorize_uri: 'optional - override authorize endpoint (default: https://claude.ai/oauth/authorize)', token_uri: 'optional - override token endpoint (default: https://platform.claude.com/v1/oauth/token)', redirect_uri: 'optional - override redirect_uri (default: https://platform.claude.com/oauth/code/callback)', beta_flags: 'optional - anthropic-beta header value for OAuth requests', enroll: 'optional - set true to force PKCE enrollment even when an API key is present' } }, gemini: { base_uri: 'optional - Base URI for Gemini - Use private base OR defaults to https://generativelanguage.googleapis.com/v1beta', key: 'required - Google Gemini API Key', model: 'optional - Gemini model id to use (see provider docs for currently-supported ids)', system_role_content: 'You are an ethically hacking Gemini agent.', temp: 'optional - Gemini temperature', think: true, max_prompt_length: 1_000_000 }, # teacher-student reflection: execute on :active, write durable lessons via this engine (nil = same as :active) reflect_engine: nil, # optional model override on :reflect_engine (nil = engine default) reflect_model: nil, agent: { native_tools: true, max_iters: 777, # Swarm (agent_ask/agent_debate) sub-agent recursion cap max_depth: 3, # run PWN::AI::Agent::Learning.auto_introspect after every final answer auto_introspect: true, # also run PWN::AI::Agent::Extrospection.auto_extrospect from auto_introspect # (host/repo/env probes only — no toolchain/GUI/net side-effects) auto_extrospect: true, # engine-agnostic scaffolding (defaults tuned for local models) plan_first: nil, # nil = auto (true when :active is :ollama or :openwebui) # LLM request-kind classifier (statement|question|autonomous_goal). # nil = follow :task_summary_llm (default on). false = heuristic-only. request_kind_llm: nil, # LLM tangible-task decomposition for autonomous goals (default on). task_summary_llm: nil, tool_router: nil, # nil = auto (true when :active is local :ollama/:openwebui) — cuts ~11k→~3k schema tokens tool_preference: %w[memory_recall session_recall skills_recall pwn_eval shell mistakes_record mistakes_resolve learning_note_outcome memory_remember skills_update], escalation_persona: 'escalator', # Swarm persona for frontier corrective hints when a local model is stuck # sample E3 verify_as_reward: true|false|nil(auto: ~10% local / always frontier when CLAIM_RX hits) verify_as_reward: true, # end-of-turn auto_introspect policy for local: :always | :failure_only | :every_n (with introspect_every_n) local_introspect: :failure_only, introspect_every_n: 3, # Hermes split: run Learning.auto_introspect on a daemon thread after # Loop.run has already decided the user-visible reply (default ON). defer_introspect: true, # Hermes-style prompt-cache breakpoints. Anthropic uses cache_control # system blocks; OpenAI uses prompt_cache_key; Grok uses x-grok-conv-id; # Gemini splits systemInstruction parts for implicit prefix hits. prompt_cache: true, # S2/S3/S4 — nil = auto (ON for remote engines, OFF for ollama cost) critic: true, counterfactual: true, red_team_plan: true, hindsight: true, # nil = auto: ORM/PRM use LLM teacher on remote engines even when # module_reflection is false (keeps local heuristic-only) reward_llm: true, # optional cheaper model id for Reward.judge / .prm (nil = engine default) reward_model: nil, # cheap ORM chat timeout seconds (clamped 2..30) reward_llm_timeout: 12, # history compaction keep last K tool pairs + plan (chars budget for ollama) history_keep_tool_pairs: 6, history_tool_max_chars: 2_000, # R5 — live tabular Q / REINFORCE. nil/true = on; false = off. # Advisory only: never replaces TaskSummarizer / plan_first. policy: true, toolsets: nil, operator_account: nil, sessions_keep_days: 90, artifacts_keep_days: 90, max_total_mb: 512, model_routes: { summarize: nil, judge: nil, act: nil, sensitive: nil } }, reward: { verifier_precedence: true }, engagement: { enforce: 'block' }, taint: { mode: 'enforce' }, learning: { max_baks: 5, compact_after_days: 30 }, capabilities: { grantable: %w[cap_net_raw] } # multi-agent personas : ~/.pwn/agents.yml (see PWN::AI::Agent::Swarm.help) # swarm bus : ~/.pwn/swarm/<swarm_id>/bus.jsonl }, ai_profiles: {}, plugins: { asm: { arch: PWN::Plugins::DetectOS.arch, endian: PWN::Plugins::DetectOS.endian.to_s }, blockchain: { bitcoin: { rpc_host: 'localhost', rpc_port: 8332, rpc_user: 'bitcoin RPC Username', rpc_pass: 'bitcoin RPC Password' } }, hunter: { api_key: 'hunter.how API Key' }, google_workspace: { oauth: { client_id: 'required - Google Cloud OAuth 2.0 client id (Desktop app)', client_secret: 'required - Google Cloud OAuth 2.0 client secret', refresh_token: 'optional - durable Google refresh token (enables silent re-auth)', bearer_token: 'optional - Google access token (short-lived; auto-refreshed)', expires_at: 'optional - unix epoch seconds when bearer_token expires', redirect_uri: 'optional - loopback listener (default http://127.0.0.1:ephemeral/)', scope: 'optional - override space-delimited Google scopes', services: 'optional - email,calendar,drive,docs,sheets or all' } }, jira_data_center: { base_uri: 'Jira Server Base API URI (e.g. https://jira.company.com/rest/api/latest)', token: 'Jira Server API Token' }, meshtastic: { admin_key: 'Public key authorized to send admin messages to nodes', transport: 'auto', dispatch_to_pwn_ai: false, ai_whitelist: [], serial: { port: '/dev/ttyACM0', baud: 115_200, bits: 8, stop: 1, parity: :none }, bluetooth: { address: 'AA:BB:CC:DD:EE:FF' }, tcp: { host: '127.0.0.1', port: 4403 }, mqtt: { host: 'mqtt.meshtastic.org', port: 1883, tls: false, user: 'meshdev', pass: 'large4cats', client_id: '', keep_alive: 60, ack_timeout: 5 }, channel: { active: 'LongFast', LongFast: { psk: 'AQ==', region: 'US/<STATE>', topic: '2/e/#', channel_num: 8 }, PWN: { psk: 'required - PSK for pwn channel', region: 'US/<STATE>', topic: '2/e/PWN/#', channel_num: 99 } } }, shodan: { api_key: 'SHODAN API Key' } }, memory: { enabled: true, provider: 'file' # file | sqlite (future) }, sessions: { enabled: true, provider: 'jsonl' }, cron: { enabled: true, provider: 'yaml' } } rescue StandardError => e raise e end |
.help ⇒ Object
Display Usage for this Module
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 |
# File 'lib/pwn/config.rb', line 1096 public_class_method def self.help puts "USAGE: # Run env template and return its result #{self}.env_template # Run default env and return its result #{self}.default_env( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' ) # Run redact sensitive artifacts and return its result #{self}.redact_sensitive_artifacts( config: 'optional - Hash to redact sensitive artifacts from. Defaults to PWN::Env' ) # Run init driver options and return its result #{self}.init_driver_options # Run refresh env and return its result #{self}.refresh_env( pwn_env_path: 'required - pwn env path value consumed by #refresh_env', pwn_dec_path: 'required - pwn dec path value consumed by #refresh_env', key: 'optional - key value consumed by #refresh_env', iv: 'optional - iv value consumed by #refresh_env' ) # Run pwn skills path and return its result #{self}.pwn_skills_path( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' ) # Run sanitize skill name and return its result #{self}.sanitize_skill_name( name: 'required - binary or identifier name' ) # Run parse skill frontmatter and return its result #{self}.parse_skill_frontmatter( content: 'optional - content value consumed by #parse_skill_frontmatter' ) # Run parse skill references and return its result #{self}.parse_skill_references( content: 'optional - content value consumed by #parse_skill_references' ) # Run write skill and return its result #{self}.write_skill( name: 'required - free-form; sanitised to [a-z0-9-]', content: 'required - markdown body (WITHOUT frontmatter)', description: 'optional - 1..1024 chars; derived from body when omitted', references: 'optional - Array of URLs / CWE / CVE / ATT&CK / NIST ids', license: 'optional - SPDX id or free text', metadata: 'optional - Hash of arbitrary metadata', allowed_tools: 'optional - Array of toolset names', pwn_skills_path: 'optional - override skills root (defaults to pwn_skills_path)' ) # Run migrate legacy skills and return its result #{self}.migrate_legacy_skills( pwn_skills_path: 'optional - override skills root (defaults to pwn_skills_path)', delete_legacy: 'optional - remove flat file after migration (default true)' ) # Run default skill names and return its result #{self}.default_skill_names( source: 'optional - source value consumed by #default_skill_names', root: 'optional - root value consumed by #default_skill_names' ) # Run default skills dir and return its result #{self}.default_skills_dir # Seed bundled skills into ~/.pwn/skills (or pwn_skills_path:) #{self}.install_default_skills( pwn_skills_path: 'optional - pwn skills path value consumed by #install_default_skills', source: 'optional - source value consumed by #install_default_skills' ) # Run load skills and return its result #{self}.load_skills( pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills', references: 'optional - frontmatter:, loaded:?, error:? }' ) # Run pwn memory path and return its result #{self}.pwn_memory_path # Run load memory and return its result #{self}.load_memory # Run pwn sessions path and return its result #{self}.pwn_sessions_path # Run pwn cron path and return its result #{self}.pwn_cron_path # Print the AUTHOR(S) string for this module. #{self}.authors " constants.sort end |
.init_driver_options ⇒ Object
- Supported Method Parameters
env = PWN::Config.init_driver_options
422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/pwn/config.rb', line 422 public_class_method def self. env = { driver_opts: { pwn_env_path: nil, pwn_dec_path: nil } } PWN.const_set(:Env, env) # puts '[*] Loaded driver options.' rescue StandardError => e raise e end |
.install_default_skills(opts = {}) ⇒ Object
Seed bundled skills into ~/.pwn/skills (or pwn_skills_path:). Every SKILL.md under etc/default_skills is copied, preserving relative path. SOP SKILL.md files are left alone so operator edits survive upgrades. Generated module skills under pwn/ are overwritten by ModuleSkills.install. scripts/ are never copied from the gem templates.
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 |
# File 'lib/pwn/config.rb', line 888 public_class_method def self.install_default_skills(opts = {}) root = opts[:pwn_skills_path] || pwn_skills_path src_root = opts[:source] || default_skills_dir return [] if root.to_s.empty? || !Dir.exist?(src_root.to_s) FileUtils.mkdir_p(root) seeded = [] each_skill_md(root: src_root) do |src, rel_dir| next if module_skill_rel?(rel: rel_dir) dest_dir = File.join(root, rel_dir) dest = File.join(dest_dir, SKILL_ENTRY) unless File.file?(dest) FileUtils.mkdir_p(dest_dir) FileUtils.cp(src, dest) seeded << { name: rel_dir, path: dest } end copy_missing_references(source_dir: File.dirname(src), dest_dir: dest_dir) end if defined?(PWN::ModuleSkills) && PWN::ModuleSkills.respond_to?(:install) PWN::ModuleSkills.install( pwn_skills_path: root, source: File.join(src_root, 'pwn') ) end seeded rescue StandardError => e warn "[PWN::Config] install_default_skills failed: #{e.class}: #{e.message}" [] end |
.load_memory ⇒ Object
- Supported Method Parameters
PWN::Config.load_memory
1070 1071 1072 |
# File 'lib/pwn/config.rb', line 1070 public_class_method def self.load_memory defined?(PWN::Memory) ? PWN::Memory.load : {} end |
.load_skills(opts = {}) ⇒ Object
- Supported Method Parameters
skills = PWN::Config.load_skills( pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills' )
Loads skills into the PWN::Skills constant. Two on-disk shapes are accepted so upgrades are seamless:
agentskills.io
Each entry: { type:, format:, path:, dir:, content:, description:, references:, frontmatter:, loaded:?, error:? }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 |
# File 'lib/pwn/config.rb', line 1011 public_class_method def self.load_skills(opts = {}) pwn_skills_path = opts[:pwn_skills_path] || (PWN.const_defined?(:Env) && PWN::Env.is_a?(Hash) && PWN::Env[:pwn_skills_path]) || self.pwn_skills_path FileUtils.mkdir_p(pwn_skills_path) if pwn_skills_path && !Dir.exist?(pwn_skills_path.to_s) skills = {} return skills unless pwn_skills_path && Dir.exist?(pwn_skills_path.to_s) each_skill_md(root: pwn_skills_path) do |entry, rel_dir| ingest_skill_md(skills: skills, entry: entry, rel_dir: rel_dir) end # ── legacy flat files (backward-compat shim) ────────────────────── Dir.glob(File.join(pwn_skills_path, '*.{rb,md,txt,skill,yml,yaml}')).each do |skill_file| key = File.basename(skill_file, '.*').to_sym next if skills.key?(key) # directory format wins on collision content = File.read(skill_file) ext = File.extname(skill_file).downcase parsed = parse_skill_frontmatter(content: content) desc = parsed[:body].to_s.lines.reject { |l| l.strip.empty? || l.strip.start_with?('#', '---') }.first.to_s.strip desc = parsed[:body].to_s.lines.first.to_s.strip.sub(/^#+\s*/, '')[0, 200] if desc.empty? base = { format: :legacy, path: skill_file, dir: pwn_skills_path, content: content, description: desc, frontmatter: parsed[:frontmatter], references: parse_skill_references(content: content) } if ext == '.rb' begin require skill_file skills[key] = base.merge(type: :ruby, loaded: true) rescue StandardError => e skills[key] = base.merge(type: :ruby, loaded: false, error: e.) end else skills[key] = base.merge(type: :instruction) end end PWN.send(:remove_const, :Skills) if PWN.const_defined?(:Skills) PWN.const_set(:Skills, skills.freeze) skills rescue StandardError => e raise e end |
.migrate_legacy_skills(opts = {}) ⇒ Object
- Supported Method Parameters
report = PWN::Config.migrate_legacy_skills( pwn_skills_path: 'optional - override skills root', delete_legacy: 'optional - remove flat file after migration (default true)' )
One-shot converter: every flat ~/.pwn/skills/*.md (etc.) becomes a
spec-conformant
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 |
# File 'lib/pwn/config.rb', line 846 public_class_method def self.migrate_legacy_skills(opts = {}) root = opts[:pwn_skills_path] || pwn_skills_path del = opts.fetch(:delete_legacy, true) migrated = [] Dir.glob(File.join(root, '*.{rb,md,txt,skill,yml,yaml}')).each do |legacy| content = File.read(legacy) base = File.basename(legacy, '.*') out = write_skill(name: base, content: content, pwn_skills_path: root) if File.extname(legacy) == '.rb' FileUtils.mkdir_p(File.join(out[:dir], 'scripts')) FileUtils.cp(legacy, File.join(out[:dir], 'scripts', File.basename(legacy))) end FileUtils.rm_f(legacy) if del migrated << { from: legacy, to: out[:path] } rescue StandardError => e migrated << { from: legacy, error: e. } end load_skills(pwn_skills_path: root) { migrated: migrated.length, details: migrated } end |
.parse_skill_frontmatter(opts = {}) ⇒ Object
- Supported Method Parameters
fm = PWN::Config.parse_skill_frontmatter(content: '...')
→ { frontmatter: Hash(String keys), body: String } Missing / malformed frontmatter returns { frontmatter: {}, body: content }.
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 |
# File 'lib/pwn/config.rb', line 722 public_class_method def self.parse_skill_frontmatter(opts = {}) content = opts[:content].to_s return { frontmatter: {}, body: content } unless content.start_with?("---\n") fm_end = content.index(/^---\s*$/, 4) return { frontmatter: {}, body: content } unless fm_end require 'yaml' raw = content[4...fm_end] fm = YAML.safe_load(raw, permitted_classes: [Symbol, Date, Time], aliases: true) || {} fm = {} unless fm.is_a?(Hash) body = content[fm_end..].to_s.sub(/\A---\s*\n?/, '') { frontmatter: fm, body: body } rescue StandardError { frontmatter: {}, body: content } end |
.parse_skill_references(opts = {}) ⇒ Object
- Supported Method Parameters
refs = PWN::Config.parse_skill_references(content: '...')
Extracts an Array of reference strings (URLs, CWE/CVE/ATT&CK ids, etc.) from a skill body. Supports three sources, merged & uniq'd:
1) frontmatter `references:` (legacy pwn)
2) frontmatter `metadata: { references: [...] }` (spec-conformant slot)
3) markdown `## References` bullet section
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 |
# File 'lib/pwn/config.rb', line 747 public_class_method def self.parse_skill_references(opts = {}) content = opts[:content].to_s parsed = parse_skill_frontmatter(content: content) fm = parsed[:frontmatter] refs = [] refs.concat(Array(fm['references'] || fm[:references]).map(&:to_s)) md = fm['metadata'] || fm[:metadata] refs.concat(Array(md['references'] || md[:references]).map(&:to_s)) if md.is_a?(Hash) if content =~ /^\s*\#{1,3}\s*References\s*$/i in_section = false content.each_line do |line| if line =~ /^\s*\#{1,3}\s*References\s*$/i in_section = true next end next unless in_section break if line =~ /^\s*\#{1,3}\s+\S/ l = line.strip.sub(/^[-*]\s*/, '') refs << l unless l.empty? end end refs.map(&:strip).reject(&:empty?).uniq rescue StandardError [] end |
.pwn_cron_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_cron_path
1082 1083 1084 |
# File 'lib/pwn/config.rb', line 1082 public_class_method def self.pwn_cron_path defined?(PWN::Cron) ? PWN::Cron.cron_dir : File.join(Dir.home, '.pwn', 'cron') end |
.pwn_memory_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_memory_path
1064 1065 1066 |
# File 'lib/pwn/config.rb', line 1064 public_class_method def self.pwn_memory_path defined?(PWN::Memory) ? PWN::Memory::MEMORY_FILE : File.join(Dir.home, '.pwn', 'memory.json') end |
.pwn_sessions_path ⇒ Object
- Supported Method Parameters
path = PWN::Config.pwn_sessions_path
1076 1077 1078 |
# File 'lib/pwn/config.rb', line 1076 public_class_method def self.pwn_sessions_path defined?(PWN::Sessions) ? PWN::Sessions.sessions_dir : File.join(Dir.home, '.pwn', 'sessions') end |
.pwn_skills_path(opts = {}) ⇒ Object
- Supported Method Parameters
pwn_skills_path = PWN::Config.pwn_skills_path( pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml' )
693 694 695 696 |
# File 'lib/pwn/config.rb', line 693 public_class_method def self.pwn_skills_path(opts = {}) pwn_env_path = opts[:pwn_env_path] ||= "#{Dir.home}/.pwn/pwn.yaml" File.join(File.dirname(pwn_env_path), 'skills') end |
.redact_sensitive_artifacts(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Config.redact_sensitive_artifacts( config: 'optional - Hash to redact sensitive artifacts from. Defaults to PWN::Env' )
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/pwn/config.rb', line 389 public_class_method def self.redact_sensitive_artifacts(opts = {}) config = opts[:config] ||= PWN::Env sensitive_keys = i[ admin_key api_key auth_client_secret bearer_token client_secret consumer_key key pass password psk refresh_token secret_key token ] # Transform values at the current level: redact sensitive keys config.transform_values.with_index do |v, k| if sensitive_keys.include?(config.keys[k]) '>>> REDACTED >>> USE `pwn-vault` FOR ADMINISTRATION <<< REDACTED <<<' else v.is_a?(Hash) ? redact_sensitive_artifacts(config: v) : v end end rescue StandardError => e raise e end |
.refresh_env(opts = {}) ⇒ Object
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 |
# File 'lib/pwn/config.rb', line 493 public_class_method def self.refresh_env(opts = {}) pwn_env_root = "#{Dir.home}/.pwn" pwn_env_path = opts[:pwn_env_path] ||= "#{pwn_env_root}/pwn.yaml" pwn_env_root = File.dirname(pwn_env_path) FileUtils.mkdir_p(pwn_env_root) pwn_skills_path = File.join(pwn_env_root, 'skills') FileUtils.mkdir_p(pwn_skills_path) return default_env(pwn_env_path: pwn_env_path) unless File.exist?(pwn_env_path) is_encrypted = PWN::Plugins::Vault.file_encrypted?(file: pwn_env_path) raise "PWN Environment (#{pwn_env_path}) is not encrypted! Use PWN::Vault.create(file: '#{pwn_env_path}', decryptor_file: '#{pwn_env_path}.decryptor') to encrypt it." unless is_encrypted pwn_dec_path = opts[:pwn_dec_path] ||= "#{pwn_env_path}.decryptor" raise "PWN Decryptor (#{pwn_dec_path}) does not exist!" unless File.exist?(pwn_dec_path) pwn_decryptor = YAML.load_file(pwn_dec_path, symbolize_names: true) key = opts[:key] ||= pwn_decryptor[:key] ||= ENV.fetch('PWN_DECRYPTOR_KEY') key = PWN::Plugins::AuthenticationHelper.mask_password(prompt: 'Decryption Key') if key.nil? iv = opts[:iv] ||= pwn_decryptor[:iv] ||= ENV.fetch('PWN_DECRYPTOR_IV') iv = PWN::Plugins::AuthenticationHelper.mask_password(prompt: 'Decryption IV') if iv.nil? env = PWN::Plugins::Vault.dump( file: pwn_env_path, key: key, iv: iv ) valid_ai_engines = PWN::AI.help.reject { |e| e.downcase == :agent }.map(&:downcase) raise "ERROR: PWN Environment (#{pwn_env_path}) is missing ai: Hash" unless env.is_a?(Hash) && env[:ai].is_a?(Hash) engine = env[:ai][:active].to_s.downcase.to_sym raise "ERROR: Unsupported AI Engine: #{engine} in #{pwn_env_path}. Supported AI Engines:\n#{valid_ai_engines.inspect}" unless valid_ai_engines.include?(engine) # Backfill missing ai.<engine> / ai.agent keys from env_template BEFORE # indexing env[:ai][engine][:key]. Older vaults may set ai.active to a # newly supported engine (e.g. ollama) without shipping that engine's # config block yet. merge_ai_defaults!(env: env) # Determine whether the active engine already has usable auth # material so the pwn / pwn-ai REPL driver does not prompt for an # API key when OAuth is configured via pwn-vault. # # A value is considered "real" when it is non-blank AND is not one # of the placeholder strings ("optional - ..." / "required - ...") # written by PWN::Config.default_env into a fresh ~/.pwn/pwn.yaml. real_cfg = lambda do |v| s = v.to_s.strip !(s.empty? || s.match?(/\A(optional|required)\b/i) || s.match?(/REDACTED/i) || s.match?(/\A<{3}.*>{3}\z/)) end key = env[:ai][engine][:key] key = nil unless real_cfg.call(key) oauth_configured = false if i[grok openai anthropic].include?(engine) oauth = env[:ai][engine][:oauth] oauth = env[:ai][engine][:oauth] = {} unless oauth.is_a?(Hash) # OAuth is considered configured when a bearer_token / refresh_token # is stored, enroll is truthy, or a non-placeholder client_id is set # (module will run the singular enrollment flow). oauth_configured = real_cfg.call(oauth[:bearer_token]) || real_cfg.call(oauth[:refresh_token]) || oauth[:enroll] == true || real_cfg.call(oauth[:client_id]) || (real_cfg.call(oauth[:client_id]) && real_cfg.call(oauth[:client_secret])) end # Never block a non-interactive process (backticks, CI, `pwn setup` # under rvmsudo, headless -A) waiting on a TTY::Prompt read — only # solicit an API key when BOTH stdin and stdout are terminals. Set # PWN_NONINTERACTIVE=1 to force-skip even on a real TTY. interactive = $stdin.tty? && $stdout.tty? && ENV['PWN_NONINTERACTIVE'].to_s.empty? if key.nil? && !oauth_configured && interactive enroll_hints = { grok: 'or store ai.grok.oauth.refresh_token via pwn-vault -- run PWN::AI::Grok.obtain_oauth_bearer_token to enroll', openai: 'or store ai.openai.oauth.refresh_token via pwn-vault -- run PWN::AI::OpenAI.obtain_oauth_bearer_token to enroll', anthropic: 'or store ai.anthropic.oauth.refresh_token via pwn-vault -- run PWN::AI::Anthropic.obtain_oauth_bearer_token to enroll' } enroll_hint = enroll_hints[engine] # engine is a Symbol (e.g. :ollama). Compare as Symbol — the old # String check `!= 'ollama'` was ALWAYS true, so active: ollama still # prompted for an API key even though stock ollama needs none. # openwebui still requires a JWT/API key and is NOT skipped here. # Keep this skip list engine-symbol based only. Do not gate on base_uri # hostnames — reverse-proxied ollama may still need no key. if engine != :ollama prompt = enroll_hint ? "#{engine} API Key (#{enroll_hint})" : "#{engine} API Key" key = PWN::Plugins::AuthenticationHelper.mask_password(prompt: prompt) env[:ai][engine][:key] = key end end model = env[:ai][engine][:model] system_role_content = env[:ai][engine][:system_role_content] # Reset the ai response history on env refresh env[:ai][engine][:response_history] = { id: '', object: '', model: model, usage: {}, choices: [ { role: 'system', content: system_role_content } ] } # These two lines should be immutable for the session env[:driver_opts] = { pwn_env_path: pwn_env_path, pwn_dec_path: pwn_dec_path } # Make pwn-ai aware of the skills folder in pwn_env parent (before freeze) env[:pwn_skills_path] = pwn_skills_path if defined?(pwn_skills_path) if defined?(pwn_skills_path) PWN::Config.install_default_skills(pwn_skills_path: pwn_skills_path) PWN::Config.load_skills(pwn_skills_path: pwn_skills_path) end # pwn-ai agent: memory, sessions, cron paths (before freeze) env[:pwn_memory_path] = PWN::Memory::MEMORY_FILE if defined?(PWN::Memory) PWN::Memory.load if defined?(PWN::Memory) env[:pwn_sessions_path] = PWN::Sessions.sessions_dir if defined?(PWN::Sessions) env[:pwn_cron_path] = PWN::Cron.cron_dir if defined?(PWN::Cron) PWN::Cron.install_defaults if defined?(PWN::Cron) && PWN::Cron.respond_to?(:install_defaults) # Fill missing ai.agent / ai.ollama knobs from code defaults so older # vault files pick up Ollama/RL fixes (tool_router nil-auto, tool_preference # memory_recall-first, local introspect policy, history compaction, result_max, # escalation default) without requiring a full pwn-vault rewrite. Explicit # vault values always win — deep_merge only supplies ABSENT keys. merge_ai_defaults!(env: env) # Assign the refreshed env to PWN::Env PWN.send(:remove_const, :Env) if PWN.const_defined?(:Env) PWN.const_set(:Env, env.freeze) # Redact sensitive artifacts from PWN::Env and store in PWN::EnvRedacted env_redacted = redact_sensitive_artifacts(config: env) PWN.send(:remove_const, :EnvRedacted) if PWN.const_defined?(:EnvRedacted) PWN.const_set(:EnvRedacted, env_redacted.freeze) Pry.config.refresh_pwn_env = false if defined?(Pry) puts "[*] PWN::Env loaded via: #{pwn_env_path}\n" # Upgrade drift — cheap schema-stamp check only (no per-file probes). if defined?(PWN::Migrate) && PWN::Migrate.needed? puts "[!] ~/.pwn state predates pwn #{PWN::VERSION} (schema " \ "#{PWN::Migrate.installed_schema} < #{PWN::Migrate::SCHEMA_VERSION}). " \ 'Run `pwn setup --migrate --fix` to autofix (backup taken first).' end rescue StandardError => e raise e end |
.sanitize_skill_name(opts = {}) ⇒ Object
- Supported Method Parameters
name = PWN::Config.sanitize_skill_name(name: 'My Cool Skill!')
Coerce to an agentskills.io-valid identifier:
downcase
Raises ArgumentError when the result is empty.
704 705 706 707 708 709 710 711 712 713 714 715 |
# File 'lib/pwn/config.rb', line 704 public_class_method def self.sanitize_skill_name(opts = {}) n = opts[:name].to_s.downcase .gsub(/[^a-z0-9-]+/, '-') .gsub(/-{2,}/, '-') .gsub(/\A-+|-+\z/, '')[0, 64] .to_s .gsub(/-+\z/, '') # re-strip in case truncation left a trailing '-' raise ArgumentError, "skill name #{opts[:name].inspect} sanitises to empty" if n.empty? raise ArgumentError, "skill name #{n.inspect} !~ #{SKILL_NAME_RE.inspect}" unless n.match?(SKILL_NAME_RE) n end |
.write_skill(opts = {}) ⇒ Object
- Supported Method Parameters
out = PWN::Config.write_skill( name: 'required - free-form; sanitised to [a-z0-9-]', content: 'required - markdown body (WITHOUT frontmatter)', description: 'optional - 1..1024 chars; derived from body when omitted', references: 'optional - Array of URLs / CWE / CVE / ATT&CK / NIST ids', license: 'optional - SPDX id or free text', metadata: 'optional - Hash of arbitrary metadata', allowed_tools: 'optional - Array of toolset names', pwn_skills_path: 'optional - override skills root' )
The single agentskills.io-conformant writer used by skill_create,
learning_distill_skill and migrate_legacy_skills. Always writes
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 |
# File 'lib/pwn/config.rb', line 792 public_class_method def self.write_skill(opts = {}) root = opts[:pwn_skills_path] || pwn_skills_path name = sanitize_skill_name(name: opts[:name]) body = opts[:content].to_s raise ArgumentError, 'content is required' if body.strip.empty? # If caller handed us a body that already has frontmatter, strip & # merge it so we never emit doubled `---` blocks. parsed = parse_skill_frontmatter(content: body) body = parsed[:body].to_s.sub(/\A\n+/, '') merged = parsed[:frontmatter] desc = (opts[:description] || merged['description'] || merged[:description]).to_s.strip if desc.empty? first = body.lines.reject { |l| l.strip.empty? || l.strip.start_with?('#') }.first.to_s.strip first = body.lines.first.to_s.strip.sub(/^#+\s*/, '') if first.empty? desc = first[0, 1024] end desc = desc[0, 1024] raise ArgumentError, 'description could not be derived (empty body?)' if desc.empty? refs = (Array(opts[:references]) + Array(merged['references']) + Array(merged[:references])) .map(&:to_s).map(&:strip).reject(&:empty?).uniq = merged['metadata'] || merged[:metadata] || {} = {} unless .is_a?(Hash) = .merge(opts[:metadata]) if opts[:metadata].is_a?(Hash) ['references'] = refs unless refs.empty? fm = { 'name' => name, 'description' => desc } fm['license'] = opts[:license].to_s if opts[:license] fm['allowed-tools'] = Array(opts[:allowed_tools]).map(&:to_s) if opts[:allowed_tools] fm['metadata'] = unless .empty? require 'yaml' frontmatter = YAML.dump(fm).sub(/\A---\n/, '') # YAML.dump already emits leading --- out = "---\n#{frontmatter}---\n\n#{body.rstrip}\n" out << "\n## References\n#{refs.map { |r| "- #{r}" }.join("\n")}\n" if refs.any? && body !~ /^\#{1,3}\s*References\s*$/i dir = File.join(root, name) path = File.join(dir, SKILL_ENTRY) FileUtils.mkdir_p(dir) File.write(path, out) { name: name, dir: dir, path: path, bytes: out.bytesize, description: desc, references: refs, format: :agentskills } end |