pwn 0.5.804 → 0.5.806

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.
Files changed (114) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +8 -8
  3. data/documentation/AI-Integration.md +27 -1
  4. data/documentation/Contributing.md +1 -1
  5. data/documentation/Diagrams.md +1 -1
  6. data/documentation/General-PWN-Usage.md +1 -1
  7. data/documentation/Home.md +2 -2
  8. data/documentation/How-PWN-Works.md +1 -1
  9. data/documentation/Mission-Cancellation.md +4 -3
  10. data/documentation/Persistence.md +1 -1
  11. data/documentation/Plugins.md +3 -2
  12. data/documentation/Runtime-Source-Protection.md +20 -2
  13. data/documentation/Skills-Memory-Learning.md +15 -1
  14. data/documentation/What-is-PWN.md +1 -1
  15. data/documentation/diagrams/dot/plugin-ecosystem.dot +1 -1
  16. data/documentation/diagrams/plugin-ecosystem.svg +1 -1
  17. data/etc/default_skills/pwn/ai/agent/submission/SKILL.md +23 -0
  18. data/etc/default_skills/pwn/ai/sandbox/SKILL.md +59 -0
  19. data/lib/pwn/ai/agent/confirmation.rb +1 -1
  20. data/lib/pwn/ai/agent/dispatch.rb +55 -2
  21. data/lib/pwn/ai/agent/learning.rb +7 -3
  22. data/lib/pwn/ai/agent/loop.rb +388 -251
  23. data/lib/pwn/ai/agent/mission_namespace.rb +52 -14
  24. data/lib/pwn/ai/agent/open_goal.rb +36 -9
  25. data/lib/pwn/ai/agent/policy.rb +37 -10
  26. data/lib/pwn/ai/agent/prompt_builder.rb +15 -8
  27. data/lib/pwn/ai/agent/request_runtime.rb +106 -13
  28. data/lib/pwn/ai/agent/submission.rb +367 -0
  29. data/lib/pwn/ai/agent/swarm.rb +2 -2
  30. data/lib/pwn/ai/agent/task_dag.rb +1 -1
  31. data/lib/pwn/ai/agent/task_summarizer.rb +47 -13
  32. data/lib/pwn/ai/agent/tools/memory.rb +6 -11
  33. data/lib/pwn/ai/agent/tools/ruby_eval.rb +1 -1
  34. data/lib/pwn/ai/agent/tools/shell.rb +1 -1
  35. data/lib/pwn/ai/agent/tools/skills.rb +5 -5
  36. data/lib/pwn/ai/agent/turn_finalizer.rb +659 -27
  37. data/lib/pwn/ai/agent.rb +1 -0
  38. data/lib/pwn/ai/cli.rb +2 -0
  39. data/lib/pwn/ai/grok.rb +106 -1
  40. data/lib/pwn/{plugins/ai_sandbox.rb → ai/sandbox.rb} +116 -32
  41. data/lib/pwn/ai.rb +1 -0
  42. data/lib/pwn/config.rb +36 -32
  43. data/lib/pwn/memory.rb +9 -4
  44. data/lib/pwn/plugins/log.rb +15 -1
  45. data/lib/pwn/plugins/repl/ai.rb +3 -7
  46. data/lib/pwn/plugins/repl/ai_console.rb +234 -41
  47. data/lib/pwn/plugins/repl/ai_swarm.rb +1 -1
  48. data/lib/pwn/plugins.rb +0 -1
  49. data/lib/pwn/sessions.rb +9 -1
  50. data/lib/pwn/version.rb +1 -1
  51. data/pwn_upgrade-aarch64.txt +9533 -0
  52. data/spec/conventions_spec.rb +9 -7
  53. data/spec/integration/controller_spill_spec.rb +8 -2
  54. data/spec/integration/harness_evaluation_spec.rb +16 -24
  55. data/spec/integration/harness_package_spec.rb +17 -6
  56. data/spec/integration/mission_cancel_spec.rb +2 -2
  57. data/spec/integration/reinforced_feedback_loop_spec.rb +1 -1
  58. data/spec/landlock_capability_spec.rb +23 -0
  59. data/spec/lib/pwn/ai/agent/chat_deliverable_spec.rb +188 -0
  60. data/spec/lib/pwn/ai/agent/dispatch_spec.rb +82 -2
  61. data/spec/lib/pwn/ai/agent/loop_artifacts_spec.rb +102 -1
  62. data/spec/lib/pwn/ai/agent/loop_partial_delivery_spec.rb +62 -0
  63. data/spec/lib/pwn/ai/agent/loop_permission_spec.rb +152 -0
  64. data/spec/lib/pwn/ai/agent/loop_spec.rb +100 -23
  65. data/spec/lib/pwn/ai/agent/loop_submission_spec.rb +271 -0
  66. data/spec/lib/pwn/ai/agent/mission_namespace_spec.rb +78 -4
  67. data/spec/lib/pwn/ai/agent/policy_spec.rb +3 -2
  68. data/spec/lib/pwn/ai/agent/provider_window_timing_spec.rb +63 -0
  69. data/spec/lib/pwn/ai/agent/request_runtime_spec.rb +142 -1
  70. data/spec/lib/pwn/ai/agent/result_spec.rb +6 -1
  71. data/spec/lib/pwn/ai/agent/reward_dispatch_review_spec.rb +1 -1
  72. data/spec/lib/pwn/ai/agent/solve_spec.rb +1 -1
  73. data/spec/lib/pwn/ai/agent/submission_spec.rb +81 -0
  74. data/spec/lib/pwn/ai/agent/task_summarizer_spec.rb +29 -0
  75. data/spec/lib/pwn/ai/agent/tools/memory_spec.rb +7 -0
  76. data/spec/lib/pwn/ai/agent/tools/skills_spec.rb +23 -0
  77. data/spec/lib/pwn/ai/agent/turn_finalizer_spec.rb +384 -1
  78. data/spec/lib/pwn/ai/cli_spec.rb +17 -0
  79. data/spec/lib/pwn/ai/grok_spec.rb +153 -0
  80. data/spec/lib/pwn/ai/sandbox_boundary_review_spec.rb +231 -0
  81. data/spec/lib/pwn/{plugins/ai_sandbox_spec.rb → ai/sandbox_spec.rb} +29 -14
  82. data/spec/lib/pwn/ai_spec.rb +5 -0
  83. data/spec/lib/pwn/banner_spec.rb +67 -38
  84. data/spec/lib/pwn/config_skills_regression_spec.rb +78 -20
  85. data/spec/lib/pwn/memory_spec.rb +46 -0
  86. data/spec/lib/pwn/plugins/android_review_fixes_spec.rb +15 -8
  87. data/spec/lib/pwn/plugins/android_transport_audit_spec.rb +2 -1
  88. data/spec/lib/pwn/plugins/artifact_registry_spec.rb +7 -3
  89. data/spec/lib/pwn/plugins/jobs_spec.rb +10 -1
  90. data/spec/lib/pwn/plugins/log_spec.rb +95 -0
  91. data/spec/lib/pwn/plugins/plugins_b_operational_regression_spec.rb +1 -1
  92. data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +551 -40
  93. data/spec/lib/pwn/plugins/repl/ai_legacy_containment_spec.rb +25 -10
  94. data/spec/lib/pwn/sdr/decoder/lora_spec.rb +36 -27
  95. data/spec/lib/pwn/sessions_lifecycle_supplement_spec.rb +50 -0
  96. data/spec/spec_helper.rb +8 -4
  97. data/spec/support/harness/cli_faults.rb +2 -1
  98. data/spec/support/harness/controller_spill.rb +2 -2
  99. data/spec/support/harness/controller_state.rb +3 -3
  100. data/spec/support/harness/evaluate.rb +21 -15
  101. data/spec/support/harness/mission_dispatch.rb +2 -2
  102. data/spec/support/harness/mission_job_lifetime.rb +2 -2
  103. data/spec/support/harness/mission_normal_exit.rb +1 -1
  104. data/spec/support/harness/mission_unsupported.rb +2 -2
  105. data/spec/support/harness/package_acceptance.rb +25 -4
  106. data/spec/support/harness/package_sandbox_rejection.rb +21 -0
  107. data/spec/support/harness/swarm_control.rb +5 -5
  108. data/spec/support/landlock.rb +23 -0
  109. data/spec/support/mission_pipe_queue.rb +12 -1
  110. data/spec/support/sandbox.rb +4 -0
  111. data/third_party/pwn_rdoc.jsonl +138 -48
  112. metadata +34 -22
  113. data/etc/default_skills/pwn/plugins/ai_sandbox/SKILL.md +0 -52
  114. data/spec/lib/pwn/plugins/ai_sandbox_boundary_review_spec.rb +0 -57
data/lib/pwn/ai/agent.rb CHANGED
@@ -22,6 +22,7 @@ module PWN
22
22
  # ---- pwn-ai native tool-calling harness ----
23
23
  autoload :Registry, 'pwn/ai/agent/registry'
24
24
  autoload :RequestRuntime, 'pwn/ai/agent/request_runtime'
25
+ autoload :Submission, 'pwn/ai/agent/submission'
25
26
  autoload :Profiles, 'pwn/ai/agent/profiles'
26
27
  autoload :EngagementMemory, 'pwn/ai/agent/engagement_memory'
27
28
  autoload :Dispatch, 'pwn/ai/agent/dispatch'
data/lib/pwn/ai/cli.rb CHANGED
@@ -147,6 +147,8 @@ module PWN
147
147
  outcome = nil
148
148
  final = PWN::AI::Agent::Loop.run(opts.fetch(:options).merge(on_outcome: ->(row) { outcome = row }))
149
149
  writer.write(JSON.generate(final: final, outcome: outcome))
150
+ rescue PWN::AI::Grok::AccessDenied => e
151
+ writer.write(JSON.generate(final: e.message, outcome: outcome))
150
152
  rescue StandardError => e
151
153
  writer.write(JSON.generate(error: "#{e.class}: #{e.message}"))
152
154
  ensure
data/lib/pwn/ai/grok.rb CHANGED
@@ -12,6 +12,95 @@ module PWN
12
12
  # API documentation: https://docs.x.ai/docs
13
13
  # Obtain an API key from https://x.ai/api
14
14
  module Grok
15
+ # A model-request 403 is still a denial. Only publish a fixed explanation,
16
+ # never provider prose (it may contain request data or credentials).
17
+ class AccessDenied < RestClient::Forbidden
18
+ LEVELS = %w[low medium high xhigh].freeze
19
+ PARAMS = %w[reasoning_effort reasoning.effort].freeze
20
+ OTHER_CODES = %w[model_not_found insufficient_quota credit_balance_exhausted billing_not_active content_policy_violation].freeze
21
+ EFFORT = /(?:the |this )?(?:selected |requested |specified )?(?:parameter )?reasoning effort(?: level| setting| parameter)?/
22
+ SCOPE = /(?:your |this |the )?(?:current |selected )?(?<scope>subscription(?: tier| plan| level)?|plan(?: tier)?|tier|model)/
23
+ UNAVAILABLE = /(?:not (?:currently )?(?:available|supported|allowed|enabled|included|permitted)|unavailable|unsupported|disabled)/
24
+ DENIES = /(?:does not|doesnt|cannot|cant) (?:currently )?(?:include|support|allow|enable|use|access|have access to)/
25
+ EFFORT_DISABLED = /\A#{EFFORT} (?:is )?#{UNAVAILABLE} (?:on|for|in|with|by|under) #{SCOPE}\z/
26
+ SCOPE_DENIES = /\A#{SCOPE} #{DENIES} #{EFFORT}\z/
27
+ UPGRADE = /(?:requires|is only available (?:to|on|with|for)) (?:a |an )?(?:(?:higher|paid|upgraded|premium|supergrok(?: heavy)?) )?(?:subscription(?: tier)?|plan|tier|subscribers?)/
28
+
29
+ attr_reader :reason
30
+
31
+ def explain(effort:, model:)
32
+ label = LEVELS.include?(effort) ? "the \"#{effort}\" reasoning effort" : 'the requested reasoning effort'
33
+ @reason = case restriction(effort, model)
34
+ when :subscription then "Your current Grok subscription does not include #{label}. Use /model grok to select a different effort."
35
+ when :model then "The selected Grok model does not support #{label}. Choose a different model or reasoning setting."
36
+ when :effort then "Grok rejected #{label} without specifying why. Use /model grok to select a different effort."
37
+ end
38
+ self.message = "Grok denied the request (HTTP 403). #{@reason || 'Check access to the selected model and endpoint.'}"
39
+ self
40
+ end
41
+
42
+ private
43
+
44
+ def restriction(effort, model)
45
+ return unless effort.is_a?(String) && !effort.empty?
46
+
47
+ body = http_body
48
+ return unless body.is_a?(String) && body.bytesize <= 16_384
49
+
50
+ data = if body.lstrip.start_with?('{')
51
+ JSON.parse(body, max_nesting: 16)
52
+ elsif !body.lstrip.start_with?('[', '<') && http_headers&.[](:content_type).to_s.split(';', 2).first == 'text/plain'
53
+ { 'message' => body }
54
+ end
55
+ return unless data.is_a?(Hash)
56
+
57
+ error = data['error']
58
+ details = error.is_a?(Hash) ? error : data
59
+ param = details['param'] || data['param']
60
+ return if param && !PARAMS.include?(param)
61
+
62
+ codes = [data['code'], details['code'], details['type']].grep(String).map { |s| s.downcase.tr('-', '_') }.uniq
63
+ return if codes.intersect?(OTHER_CODES)
64
+
65
+ fallback = nil
66
+ [*codes, details['message'], error].grep(String).each do |value|
67
+ cause = stated_restriction(effort, model, !param.nil?) { value }
68
+ return cause if %i[subscription model].include?(cause)
69
+
70
+ fallback ||= cause
71
+ end
72
+ fallback
73
+ rescue StandardError
74
+ nil # An unreadable or unexpected error body cannot change the HTTP outcome.
75
+ end
76
+
77
+ # Match an explicit relationship in a single clause, not a bag of
78
+ # words such as "model denied; check subscription; effort=high".
79
+ def stated_restriction(effort, model, scoped)
80
+ text = yield.downcase.delete(%q('"`‘’“”)).gsub('reasoning.effort', 'reasoning effort')
81
+ text = text.gsub(/\b(?:model )?#{Regexp.escape(model)}\b/, 'model') if model.is_a?(String) && model.match?(/\Agrok-[a-z0-9.-]{1,64}\z/)
82
+ fallback = nil
83
+ text.tr('_=:-', ' ').split(/[.;!,?\n]/).each do |part|
84
+ clause = part.split.join(' ').sub(/\A(?:permission denied|access denied|forbidden) /, '')
85
+ clause = clause.gsub(/\b(low|medium|high|xhigh) reasoning effort\b|\breasoning effort (?:level |of )?(low|medium|high|xhigh)\b/) do
86
+ (Regexp.last_match(1) || Regexp.last_match(2)) == effort ? 'reasoning effort' : 'other effort'
87
+ end
88
+ if scoped
89
+ return :subscription if clause.match?(/\A(?:(?:higher |paid )?(?:subscription|plan|tier)(?: tier)? (?:is )?required|insufficient subscription tier)\z/)
90
+
91
+ clause = clause.sub(/\bthis (?:setting|parameter|value)\b/, 'reasoning effort')
92
+ clause = "reasoning effort #{clause}" if clause.match?(/\A(?:#{UNAVAILABLE}|requires)\b/)
93
+ end
94
+ source = clause.match(EFFORT_DISABLED) || clause.match(SCOPE_DENIES)
95
+ return source[:scope] == 'model' ? :model : :subscription if source
96
+ return :subscription if clause.match?(/\A(?:using )?#{EFFORT} #{UPGRADE}\z/)
97
+
98
+ fallback = :effort if clause.match?(/\A(?:unsupported #{EFFORT}|#{EFFORT} (?:is )?#{UNAVAILABLE})\z/)
99
+ end
100
+ fallback
101
+ end
102
+ end
103
+
15
104
  # Internal helper: true when +opts[:value]+ is a *real* configured value coming
16
105
  # from PWN::Config / pwn-vault (i.e. not nil, not blank, and not one of
17
106
  # the "optional - ..." / "required - ..." placeholder strings that
@@ -479,6 +568,8 @@ module PWN
479
568
  nil
480
569
  end
481
570
  rescue RestClient::ExceptionWithResponse => e
571
+ model_denied = e.http_code == 403 && http_method == :post && %w[chat/completions responses].include?(rest_call)
572
+ raise AccessDenied.new(e.response).explain(effort: http_body[:reasoning_effort], model: http_body[:model]) if model_denied
482
573
  raise e if Thread.current[:pwn_provider_attempt_owner]
483
574
 
484
575
  # Keep the HTTP type/response and actionable provider diagnostics.
@@ -542,7 +633,21 @@ module PWN
542
633
  quiet: opts[:quiet]
543
634
  )
544
635
  parsed = JSON.parse(raw.to_s, symbolize_names: true)
545
- text = parsed[:output_text].to_s
636
+ raise 'Grok hosted response did not complete.' if parsed[:status] && parsed[:status] != 'completed'
637
+
638
+ text = parsed[:output_text]
639
+ unless text.is_a?(String) && !text.strip.empty?
640
+ # The REST API returns public text in assistant message blocks. Search
641
+ # calls, reasoning and other output items are not the operator's reply.
642
+ text = Array(parsed[:output]).grep(Hash).filter_map do |item|
643
+ next unless item[:type] == 'message' && item[:role] == 'assistant'
644
+ next if item[:status] && item[:status] != 'completed'
645
+
646
+ Array(item[:content]).grep(Hash).filter_map { |part| part[:text] if part[:type] == 'output_text' && part[:text].is_a?(String) }.join
647
+ end.join
648
+ end
649
+ raise 'Grok returned no public assistant text for the hosted request.' if text.strip.empty?
650
+
546
651
  message = { role: 'assistant', content: text }
547
652
  { choices: [{ message: message }], assistant_message: message }
548
653
  end
@@ -9,14 +9,19 @@ require 'ffi'
9
9
  require 'find'
10
10
  require 'tmpdir'
11
11
  require 'socket'
12
+ require 'pwn/ai/agent/mission_namespace'
12
13
 
13
14
  module PWN
14
- module Plugins
15
+ module AI
15
16
  # Forked worker for model-authored shell/Ruby with Landlock/seccomp profiles.
16
- module AISandbox
17
+ module Sandbox
17
18
  ALIAS_MUTEX = Mutex.new
18
19
  ALIAS_CACHE = {} # rubocop:disable Style/MutableConstant -- host-only inode fingerprint cache
19
20
 
21
+ # WRITE_FILE, REMOVE_DIR/FILE, MAKE_DIR/REG and TRUNCATE. In particular
22
+ # do not allow symlinks, special files, or links/renames from another dir.
23
+ SKILL_DATA_RIGHTS = [1, 4, 5, 7, 8, 14].sum { |bit| 1 << bit }
24
+
20
25
  NotStarted = PWN::AI::Agent::MissionNamespace::Unavailable
21
26
 
22
27
  # One kernel-owned process tree. Namespace PID 1 owns every descendant,
@@ -126,6 +131,9 @@ module PWN
126
131
  # The block runs only in a child; cwd and restrictions never affect the UI.
127
132
  public_class_method def self.protect_call(opts = {})
128
133
  return yield if Thread.current[:pwn_repository_worker]
134
+
135
+ # A delegated prompt is not an operator grant to persistent skill data.
136
+ opts = opts.merge(no_skill_grant: true) if Thread.current[:pwn_loop_nested] || Thread.current[:pwn_solve_tools] || Thread.current[:pwn_curriculum] || Thread.current[:pwn_swarm_depth].to_i.positive?
129
137
  return protect_descriptor(opts) unless PWN::AI::Agent::MissionNamespace.owned || (PWN::AI::Agent::MissionNamespace.prepared? && !PWN::AI::Agent::MissionNamespace.force_exec)
130
138
 
131
139
  roots = Array(opts[:roots] || protected_roots).map { |path| File.realpath(path) }.uniq
@@ -145,14 +153,7 @@ module PWN
145
153
  controller_root = File.dirname(opts[:runtime].checkpoint_path, 2)
146
154
  roots += [File.realpath(controller_root), File.realpath(PWN::AI::Agent::Swarm::SWARM_ROOT), File.realpath(PWN::AI::Agent::Swarm::AGENTS_FILE)]
147
155
  end
148
- roots.concat(controller_state_roots)
149
- explicit = prepare_write_roots(paths: opts[:write_roots])
150
- pinned = pin_named_files(paths: opts[:write_roots], protected: roots)
151
- writable = [scratch, '/dev/null', '/dev/zero', '/dev/random', '/dev/urandom'] + explicit + pinned
152
- writable += prepare_write_roots(paths: state_write_roots) unless opts.dig(:handler, :name).to_s == 'shell'
153
- writable = writable.filter_map { |path| File.realpath(path) if File.exist?(path) && !File.symlink?(path) }.uniq
154
- writable.reject! { |path| %w[/ /proc /sys /dev].include?(path) }
155
- aliases, identities = repository_aliases(roots: roots, writable: writable)
156
+ grants = repository_grants(opts.merge(roots: roots, scratch: scratch))
156
157
 
157
158
  reader, writer = IO.pipe
158
159
  controller, client = UNIXSocket.pair
@@ -164,8 +165,8 @@ module PWN
164
165
  Thread.current[:pwn_swarm_controller] = client if opts[:runtime]
165
166
  Signal.trap('TERM') { raise Interrupt, 'runtime worker cancelled' }
166
167
  begin
167
- repository_restrict!(roots: roots + aliases, writable: writable, explicit: explicit, protected: roots)
168
- repository_metadata_restrict!(roots: roots + aliases, identities: identities)
168
+ repository_restrict!(grants)
169
+ repository_metadata_restrict!(grants)
169
170
  Dir.chdir(task_dir)
170
171
  ENV['TMPDIR'] = scratch
171
172
  Thread.current[:pwn_repository_worker] = true
@@ -377,18 +378,22 @@ module PWN
377
378
  next unless protected.any? { |root| root.start_with?("#{parent}/") }
378
379
  next if protected_path?(path: parent, roots: protected) || File.symlink?(parent)
379
380
 
380
- create_pinned_file(parent: parent, name: File.basename(path))
381
- path
381
+ path if create_pinned_file(parent: parent, name: File.basename(path))
382
382
  end
383
383
  end
384
384
 
385
385
  private_class_method def self.create_pinned_file(opts = {})
386
- flags = File::WRONLY | File::CREAT | File::NOFOLLOW
386
+ flags = File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW | File::NONBLOCK
387
387
  control_directory(path: opts[:parent]) do |directory|
388
- fd = IO.sysopen(File.join(directory, opts[:name]), flags, 0o600)
389
- IO.new(fd).close
388
+ leaf = File.join(directory, opts[:name])
389
+ begin
390
+ IO.new(IO.sysopen(leaf, flags, 0o600)).close
391
+ rescue Errno::EEXIST
392
+ # Inspect the existing inode without opening a link, FIFO or device.
393
+ end
394
+ stat = File.lstat(leaf)
395
+ :pinned if stat.file? && stat.nlink == 1
390
396
  end
391
- :created
392
397
  end
393
398
 
394
399
  # Detect both the conventional checkout and the loaded package source.
@@ -401,9 +406,75 @@ module PWN
401
406
  opts.fetch(:roots).any? { |root| path == root || path.start_with?("#{root}/") }
402
407
  end
403
408
 
409
+ private_class_method def self.repository_grants(opts = {})
410
+ library = PWN::Config.pwn_skills_path
411
+ protected = opts.fetch(:roots) | controller_state_roots(library: library)
412
+ # An ordinary grant (including an explicitly named ancestor) must never
413
+ # supply normal filesystem rights to the library or its canonical alias.
414
+ roots = protected | store_locations(paths: [library])
415
+ documents, ordinary = Array(opts[:write_roots]).map { |p| File.expand_path(p.to_s) }.partition { |p| protected_path?(path: p, roots: [library]) }
416
+ ordinary.reject! { |p| store_locations(paths: [p]).any? { |path| protected_path?(path: path, roots: roots) } }
417
+ destinations = opts[:runtime]&.contract&.fetch(:skill_destinations, {}) || {}
418
+ data = opts[:no_skill_grant] ? {} : skill_data_grants(destinations: destinations.slice(*documents), library: library, protected: protected)
419
+ explicit = prepare_write_roots(paths: ordinary)
420
+ writable = [opts.fetch(:scratch), '/dev/null', '/dev/zero', '/dev/random', '/dev/urandom'] + explicit
421
+ writable += prepare_write_roots(paths: state_write_roots(protected: roots)) unless opts.dig(:handler, :name).to_s == 'shell'
422
+ writable = writable.filter_map { |p| File.realpath(p) if File.exist?(p) && !File.symlink?(p) }.uniq - %w[/ /proc /sys /dev]
423
+ aliases, identities = repository_aliases(roots: roots, writable: writable)
424
+ protected = roots | aliases.reject { |p| File.directory?(p) }
425
+ # Pin after alias discovery: an unrelated protected hardlink rules out
426
+ # granting its directory, but does not rule out the named output file.
427
+ writable |= pin_named_files(paths: ordinary, protected: protected)
428
+ { roots: roots | aliases, protected: protected, writable: writable, explicit: explicit, data: data, identities: identities }
429
+ end
430
+
431
+ # Only paths from the host's original write contract can reach here. Do
432
+ # not inherit a write grant on .pwn when the library does not yet exist.
433
+ private_class_method def self.skill_data_grants(opts = {})
434
+ destinations = opts.fetch(:destinations)
435
+ return {} if destinations.empty?
436
+
437
+ library = opts.fetch(:library)
438
+ # lstat alone cannot distinguish a bind mount of other state from an
439
+ # ordinary directory or file on the same device. mountinfo escapes names.
440
+ mounts = File.readlines('/proc/self/mountinfo').filter_map do |line|
441
+ mount = line.split(' ', 6).fetch(4).gsub(/\\([0-7]{3})/) { Regexp.last_match(1).to_i(8).chr }
442
+ mount if protected_path?(path: mount, roots: [library])
443
+ end
444
+ protected = opts.fetch(:protected) | mounts
445
+ destinations.filter_map do |path, kind|
446
+ next if File.symlink?(path) || protected_path?(path: path, roots: protected) || protected.any? { |root| root.start_with?("#{path}/") }
447
+
448
+ case kind
449
+ when :directory
450
+ control_directory(path: path) { |_fd| nil }
451
+ next unless plain_data_directory?(path: path)
452
+ when :file
453
+ next unless create_pinned_file(parent: File.dirname(path), name: File.basename(path))
454
+ else
455
+ next
456
+ end
457
+ stat = File.lstat(path)
458
+ next unless kind == :directory ? stat.directory? : stat.file? && stat.nlink == 1
459
+
460
+ [path, [stat.dev, stat.ino, stat.ftype]]
461
+ rescue Errno::EACCES, Errno::ELOOP, Errno::ENOTDIR, Errno::ENOENT
462
+ nil
463
+ end.to_h
464
+ end
465
+
466
+ # A directory rule is inherited by every descendant. Refuse the grant if
467
+ # an existing entry isn't private ordinary data; never follow an alias.
468
+ private_class_method def self.plain_data_directory?(opts = {})
469
+ Find.find(opts.fetch(:path), ignore_error: false).all? do |path|
470
+ stat = File.lstat(path)
471
+ stat.directory? || (stat.file? && stat.nlink == 1)
472
+ end
473
+ end
474
+
404
475
  # Plugin records, not the default scratch tree. Shell does not receive these.
405
- private_class_method def self.state_write_roots
406
- denied = controller_state_roots
476
+ private_class_method def self.state_write_roots(opts = {})
477
+ denied = opts.fetch(:protected)
407
478
  %w[jobs cache ghidra redb binws wordlists exports sandbox_snapshots intel].filter_map do |name|
408
479
  path = File.join(Dir.home, '.pwn', name)
409
480
  next if protected_path?(path: path, roots: denied)
@@ -415,7 +486,7 @@ module PWN
415
486
  # Keep controller persistence out of tool grants, including absent paths.
416
487
  # A missing deny still splits its ancestor grant, so tools cannot plant it
417
488
  # before the controller's first append. Honour test/custom store constants.
418
- private_class_method def self.controller_state_roots
489
+ private_class_method def self.controller_state_roots(opts = {})
419
490
  agent = PWN::AI::Agent
420
491
  stores = [PWN::Sessions, PWN::Memory, PWN::MemoryIndex, PWN::Plugins::ArtifactRegistry,
421
492
  agent::Learning, agent::Policy, agent::Metrics, agent::Reward, agent::Mistakes,
@@ -429,16 +500,25 @@ module PWN
429
500
  value if value.is_a?(String) && value.start_with?('/')
430
501
  end
431
502
  end
432
- paths.concat(%w[artifacts logs learning metrics skills .swarm-continuations.lock pwn.yaml pwn.yaml.decryptor vault-secrets.json].map { |name| File.join(Dir.home, '.pwn', name) })
503
+ paths.concat(%w[artifacts logs learning metrics .swarm-continuations.lock pwn.yaml pwn.yaml.decryptor vault-secrets.json].map { |name| File.join(Dir.home, '.pwn', name) })
433
504
  paths << File.join(Dir.home, '.pwn-vault.key')
505
+ library = opts.fetch(:library)
506
+ catalogs = [PWN::Config.active_skill_root].compact
434
507
  if defined?(PWN::Env) && PWN::Env.is_a?(Hash)
435
- %i[pwn_env_path pwn_dec_path pwn_skills_path].each do |key|
508
+ %i[pwn_env_path pwn_dec_path].each do |key|
436
509
  path = PWN::Env.dig(:driver_opts, key)
437
510
  paths << path unless path.to_s.empty?
438
511
  end
512
+ catalogs.concat([PWN::Env[:pwn_skills_path], PWN::Env.dig(:driver_opts, :pwn_skills_path)].reject { |path| path.to_s.empty? })
439
513
  end
440
- paths.concat(PWN::Skills.values.filter_map { |meta| File.dirname(meta[:path]) if meta.is_a?(Hash) && meta[:path].is_a?(String) }) if defined?(PWN::Skills) && PWN::Skills.is_a?(Hash)
441
- paths.flat_map do |path|
514
+ paths.concat(catalogs.reject { |path| File.expand_path(path) == library })
515
+ entries = defined?(PWN::Skills) && PWN::Skills.is_a?(Hash) ? PWN::Skills.values : []
516
+ parents = entries.filter_map { |meta| File.dirname(meta[:path]) if meta.is_a?(Hash) && meta[:path].is_a?(String) }
517
+ store_locations(paths: paths) | store_locations(paths: parents).reject { |path| protected_path?(path: path, roots: [library]) }
518
+ end
519
+
520
+ private_class_method def self.store_locations(opts = {})
521
+ opts.fetch(:paths).flat_map do |path|
442
522
  path = File.expand_path(path)
443
523
  ancestor = path
444
524
  ancestor = File.dirname(ancestor) until File.exist?(ancestor) || File.symlink?(ancestor)
@@ -567,6 +647,9 @@ module PWN
567
647
 
568
648
  repository_allow!(path: path, denied: denied, ancestors: ancestors, ruleset: ruleset, rights: rights, explicit: opts[:explicit], protected: opts[:protected])
569
649
  end
650
+ opts.fetch(:data).each do |path, identity|
651
+ repository_allow!(path: path, denied: {}, ancestors: {}, ruleset: ruleset, rights: SKILL_DATA_RIGHTS, identity: identity)
652
+ end
570
653
  prctl = RUBY_PLATFORM.start_with?('aarch64') ? 167 : 157
571
654
  syscall(prctl, 38, 1, 0, 0, 0)
572
655
  syscall(446, ruleset, 0)
@@ -589,14 +672,15 @@ module PWN
589
672
  if opts.fetch(:ancestors).key?(path) && !force
590
673
  Dir.children(path).each { |name| repository_allow!(opts.merge(path: File.join(path, name), force: false)) }
591
674
  else
592
- rights = opts.fetch(:rights)
593
- rights &= (1 << 1) | (1 << 14) unless File.directory?(path)
594
- fd = IO.sysopen(path, 0x200000 | 0x80000) # O_PATH | O_CLOEXEC
595
- begin
596
- attr = ::FFI::MemoryPointer.from_string([rights, fd].pack('QL'))
675
+ IO.open(IO.sysopen(path, 0x200000 | 0x80000 | File::NOFOLLOW)) do |file| # O_PATH | O_CLOEXEC
676
+ stat = file.stat
677
+ return :denied if stat.symlink?
678
+ return :denied if opts[:identity] && (opts[:identity] != [stat.dev, stat.ino, stat.ftype] || (stat.file? && stat.nlink != 1))
679
+
680
+ rights = opts.fetch(:rights)
681
+ rights &= (1 << 1) | (1 << 14) unless stat.directory?
682
+ attr = ::FFI::MemoryPointer.from_string([rights, file.fileno].pack('QL'))
597
683
  syscall(445, opts.fetch(:ruleset), 1, attr.address, 0)
598
- ensure
599
- IO.new(fd).close
600
684
  end
601
685
  end
602
686
  :allowed
data/lib/pwn/ai.rb CHANGED
@@ -19,6 +19,7 @@ module PWN
19
19
  autoload :OpenWebUI, 'pwn/ai/open_web_ui'
20
20
  autoload :RedTeam, 'pwn/ai/red_team'
21
21
  autoload :Router, 'pwn/ai/router'
22
+ autoload :Sandbox, 'pwn/ai/sandbox'
22
23
  autoload :ServerTools, 'pwn/ai/server_tools'
23
24
 
24
25
  # Ollama and Open WebUI share a wire format. A binary-tagged non-ASCII reply
data/lib/pwn/config.rb CHANGED
@@ -744,11 +744,11 @@ module PWN
744
744
  #
745
745
  # On-disk layout (spec):
746
746
  # ~/.pwn/skills/<name>/SKILL.md ← required entrypoint, YAML frontmatter
747
- # ~/.pwn/skills/<name>/scripts/ ← optional executables (was flat *.rb)
747
+ # ~/.pwn/skills/<name>/scripts/ ← optional files; ignored by the catalog
748
748
  # ~/.pwn/skills/<name>/references/ ← optional supporting docs
749
749
  # ~/.pwn/skills/<name>/assets/ ← optional binary assets
750
750
  #
751
- # Legacy shim (read-only, still loaded so nothing breaks on upgrade):
751
+ # Legacy flat files are cataloged as data, including Ruby source:
752
752
  # ~/.pwn/skills/<name>.{md,txt,rb,skill,yml,yaml}
753
753
  #
754
754
  # Frontmatter (SKILL.md, `---` YAML block at top of file):
@@ -762,6 +762,22 @@ module PWN
762
762
  SKILL_ENTRY = 'SKILL.md'
763
763
  SKILL_NAME_RE = /\A[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\z/
764
764
 
765
+ # Keep the directory with the entries, including when none were found.
766
+ class SkillCatalog < Hash
767
+ attr_reader :root
768
+
769
+ def initialize(root)
770
+ super()
771
+ @root = root.freeze
772
+ end
773
+ end
774
+
775
+ # Returns nil for an absent catalog or a plain Hash supplied by an embedder.
776
+ public_class_method def self.active_skill_root
777
+ catalog = PWN::Skills if defined?(PWN::Skills)
778
+ catalog.root if catalog.is_a?(SkillCatalog)
779
+ end
780
+
765
781
  # Supported Method Parameters::
766
782
  # pwn_skills_path = PWN::Config.pwn_skills_path(
767
783
  # pwn_env_path: 'optional - Path to pwn.yaml file. Defaults to ~/.pwn/pwn.yaml'
@@ -1047,10 +1063,9 @@ module PWN
1047
1063
  fm = parsed[:frontmatter]
1048
1064
  desc = (fm['description'] || fm[:description]).to_s.strip
1049
1065
  desc = parsed[:body].to_s.lines.first.to_s.strip.sub(/^#+\s*/, '')[0, 200] if desc.empty?
1050
- scripts = Dir.glob(File.join(dir, 'scripts', '*.rb'))
1051
1066
  fmt = module_skill_rel?(rel: rel_dir) ? :module : :agentskills
1052
- meta = {
1053
- type: scripts.any? ? :ruby : :instruction,
1067
+ skills[key] = {
1068
+ type: :instruction,
1054
1069
  format: fmt,
1055
1070
  path: entry,
1056
1071
  dir: dir,
@@ -1060,14 +1075,6 @@ module PWN
1060
1075
  references: parse_skill_references(content: content),
1061
1076
  allowed_tools: Array(fm['allowed-tools'] || fm[:'allowed-tools'] || fm['allowed_tools'])
1062
1077
  }
1063
- scripts.each do |rb|
1064
- require rb
1065
- rescue LoadError, SyntaxError, StandardError => e
1066
- meta[:loaded] = false
1067
- meta[:error] = e.message
1068
- end
1069
- meta[:loaded] = true unless meta.key?(:loaded) || scripts.empty?
1070
- skills[key] = meta
1071
1078
  skills
1072
1079
  end
1073
1080
 
@@ -1076,22 +1083,22 @@ module PWN
1076
1083
  # pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills'
1077
1084
  # )
1078
1085
  #
1079
- # Loads skills into the PWN::Skills constant. Two on-disk shapes are
1080
- # accepted so upgrades are seamless:
1086
+ # Indexes skill files as data in PWN::Skills. No Ruby is executed:
1081
1087
  #
1082
1088
  # agentskills.io → <root>/**/SKILL.md (recursive; written by write_skill)
1083
1089
  # module skills → <root>/pwn/**/SKILL.md
1084
1090
  # legacy flat → <root>/<name>.{md,txt,rb,skill,yml,yaml}
1085
1091
  #
1086
- # Each entry: { type:, format:, path:, dir:, content:, description:,
1087
- # references:, frontmatter:, loaded:?, error:? }
1092
+ # Entries include type, format, path, dir, content, description, frontmatter
1093
+ # and references. SKILL.md entries are instructions even when scripts/ exists.
1094
+ # Flat .rb entries retain their source with type: :ruby and loaded: false.
1088
1095
  public_class_method def self.load_skills(opts = {})
1089
1096
  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
1090
1097
  FileUtils.mkdir_p(pwn_skills_path) if pwn_skills_path && !Dir.exist?(pwn_skills_path.to_s)
1091
1098
 
1092
- skills = {}
1093
- return skills unless pwn_skills_path && Dir.exist?(pwn_skills_path.to_s)
1099
+ return {} unless pwn_skills_path && Dir.exist?(pwn_skills_path.to_s)
1094
1100
 
1101
+ skills = SkillCatalog.new(File.realpath(pwn_skills_path))
1095
1102
  each_skill_md(root: pwn_skills_path) do |entry, rel_dir|
1096
1103
  ingest_skill_md(skills: skills, entry: entry, rel_dir: rel_dir)
1097
1104
  end
@@ -1117,16 +1124,11 @@ module PWN
1117
1124
  references: parse_skill_references(content: content)
1118
1125
  }
1119
1126
 
1120
- if ext == '.rb'
1121
- begin
1122
- require skill_file
1123
- skills[key] = base.merge(type: :ruby, loaded: true)
1124
- rescue LoadError, SyntaxError, StandardError => e
1125
- skills[key] = base.merge(type: :ruby, loaded: false, error: e.message)
1126
- end
1127
- else
1128
- skills[key] = base.merge(type: :instruction)
1129
- end
1127
+ skills[key] = if ext == '.rb'
1128
+ base.merge(type: :ruby, loaded: false)
1129
+ else
1130
+ base.merge(type: :instruction)
1131
+ end
1130
1132
  end
1131
1133
 
1132
1134
  PWN.send(:remove_const, :Skills) if PWN.const_defined?(:Skills)
@@ -1252,12 +1254,14 @@ module PWN
1252
1254
  source: 'optional - source value consumed by #install_default_skills'
1253
1255
  )
1254
1256
 
1255
- # Run load skills and return its result
1257
+ # Index skill documents and legacy Ruby source without executing them
1256
1258
  #{self}.load_skills(
1257
- pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills',
1258
- references: 'optional - frontmatter:, loaded:?, error:? }'
1259
+ pwn_skills_path: 'optional - Path to skills folder. Defaults to ~/.pwn/skills'
1259
1260
  )
1260
1261
 
1262
+ # Absolute root of the published skill catalog, or nil if unknown
1263
+ #{self}.active_skill_root
1264
+
1261
1265
  # Run pwn memory path and return its result
1262
1266
  #{self}.pwn_memory_path
1263
1267
 
data/lib/pwn/memory.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'json'
4
4
  require 'fileutils'
5
+ require 'securerandom'
5
6
  require 'time'
6
7
 
7
8
  module PWN
@@ -93,17 +94,21 @@ module PWN
93
94
  private_class_method def self.atomic_write(opts = {})
94
95
  path = opts[:path]
95
96
  body = opts[:body]
96
- tmp = File.join(File.dirname(path), ".#{File.basename(path)}.#{Process.pid}.tmp")
97
- File.open(tmp, File::WRONLY | File::CREAT | File::TRUNC, 0o644) do |f|
97
+ dir = File.dirname(path)
98
+ tmp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(16)}.tmp")
99
+ owned_tmp = nil # Never remove a candidate that we failed to create.
100
+ File.open(tmp, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |f|
101
+ owned_tmp = tmp
98
102
  f.flock(File::LOCK_EX)
99
103
  f.write(body)
100
104
  f.flush
101
105
  f.fsync
102
106
  end
103
107
  File.rename(tmp, path)
104
- File.open(File.dirname(path), File::RDONLY, &:fsync)
108
+ owned_tmp = nil
109
+ File.open(dir, File::RDONLY, &:fsync)
105
110
  ensure
106
- FileUtils.rm_f(tmp) if defined?(tmp) && tmp && File.exist?(tmp)
111
+ FileUtils.rm_f(owned_tmp) if owned_tmp
107
112
  end
108
113
 
109
114
  # Best-effort re-read used by the empty-overwrite guard (no raise).
@@ -472,6 +472,11 @@ module PWN
472
472
  @debug_file = io
473
473
  @debug_path = path
474
474
  path
475
+ rescue SystemCallError, IOError
476
+ io&.close
477
+ close_debug_file!
478
+ @debug_path = nil
479
+ raise
475
480
  end
476
481
 
477
482
  public_class_method def self.quiet_tui!(opts = {})
@@ -709,18 +714,27 @@ module PWN
709
714
  tp = opts[:tp]
710
715
  klass = trace_module_name(tp: tp)
711
716
  meth = tp.method_id
717
+ label = "#{klass}.#{meth}"
718
+ # Trace reply stages by name only: even inspecting the signal can expose presentation data.
719
+ return label if %w[PWN::AI::Agent::Loop::DisplayReply PWN::AI::Agent::Loop::ReplyWindow].include?(klass)
720
+ return label if klass == 'PWN::AI::Agent::Loop' && %i[finish_display_reply empty_final_nudge].include?(meth)
721
+
712
722
  args = trace_arguments(tp: tp)
713
- args.to_s.empty? ? "#{klass}.#{meth}" : "#{klass}.#{meth}(#{args})"
723
+ args.to_s.empty? ? label : "#{label}(#{args})"
714
724
  end
715
725
 
716
726
  private_class_method def self.traceable?(opts = {})
717
727
  tp = opts[:tp]
728
+ return false if tp&.method_id == :cancel_requested? && tp.defined_class.name == 'PWN::AI::Agent::Loop::ProviderWindow'
729
+
718
730
  prefixes = opts[:prefixes] || DEFAULT_TRACE_PREFIXES
719
731
  name = trace_module_name(tp: tp)
720
732
  return false if name.empty?
721
733
  return false if TRACE_SKIP_PREFIXES.any? { |p| name.start_with?(p) }
722
734
  return false unless prefixes.any? { |p| name.start_with?(p) }
723
735
  return false if TRACE_SKIP_METHODS.include?(tp.method_id)
736
+ # These calls inspect stored mistake rows, not failures in the current request.
737
+ return false if name == 'PWN::AI::Agent::Loop' && %i[mistake_ts budget_hit?].include?(tp.method_id)
724
738
 
725
739
  true
726
740
  end
@@ -302,7 +302,7 @@ module PWN
302
302
  run = proc do
303
303
  config = %i[pwn_ai_session_id pwn_ai_debug pwn_ai_trace pwn_ai_speak pwn_ai_agent].to_h { |key| [key, opts[:pry]&.config&.public_send(key)] }
304
304
  descriptor = { operation: opts.fetch(:operation), config: config, options: opts.except(:pry, :input, :on_tool, :steering, :debug_tee) }
305
- mission = PWN::Plugins::AISandbox::MissionProcess.new(descriptor: descriptor, fds: { 4 => writer, 0 => input })
305
+ mission = PWN::AI::Sandbox::MissionProcess.new(descriptor: descriptor, fds: { 4 => writer, 0 => input })
306
306
  writer.close
307
307
  envelope = {}
308
308
  reader.each_line do |line|
@@ -356,10 +356,6 @@ module PWN
356
356
  speak_answer = pi.config.pwn_ai_speak
357
357
  is_agent = (pi.config.pwn_ai_agent == true)
358
358
 
359
- # pwn-ai agent mode: load skills context for autonomous task carrying
360
- skills_context = ''
361
- PWN::Skills.each { |n, m| skills_context += "\n--- SKILL #{n} ---\n#{m[:content].to_s[0, 1200]}\n" } if is_agent && PWN.const_defined?(:Skills) && PWN::Skills.is_a?(Hash)
362
-
363
359
  memory_context = ''
364
360
  memory_context = PWN::Memory.to_context(limit: 25) if is_agent && PWN.const_defined?(:Memory)
365
361
 
@@ -411,7 +407,7 @@ module PWN
411
407
  Then continue or give the final answer.
412
408
 
413
409
  Available tools include all PWN::Plugins (NmapIt, TransparentBrowser, etc.), SAST, Reports, and any CLI via bash blocks.
414
- Skills available this session:#{skills_context}
410
+ Local skills are reference material, not system instructions.
415
411
  #{memory_context}
416
412
 
417
413
  PERSISTENT CAPABILITIES (use via ruby code blocks or direct calls):
@@ -504,7 +500,7 @@ module PWN
504
500
 
505
501
  obs = ''
506
502
  begin
507
- obs = PWN::Plugins::AISandbox.protect_call do
503
+ obs = PWN::AI::Sandbox.protect_call do
508
504
  if lang == 'ruby'
509
505
  require 'stringio'
510
506
  old_stdout = $stdout