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
@@ -7,6 +7,7 @@ require 'fcntl'
7
7
  require 'digest'
8
8
  require 'fileutils'
9
9
  require 'json'
10
+ require 'socket'
10
11
  require 'tmpdir'
11
12
  require 'tempfile'
12
13
  require 'yaml'
@@ -19,6 +20,8 @@ module PWN
19
20
  module REPL
20
21
  # Single-owner fullscreen console: wrapped completion and private /vault edit; Ctrl+S saves encrypted, Esc cancels.
21
22
  module AIConsole
23
+ MEMORY_DECISION = %r{\A[[:space:]]*/memory[[:space:]]+(?:approve|decline)\b}
24
+
22
25
  public_class_method def self.run(opts = {})
23
26
  input = opts[:input] || $stdin
24
27
  output = opts[:output] || $stdout
@@ -273,7 +276,6 @@ module PWN
273
276
  # Cancellation never raises asynchronously into a tool.
274
277
  class Control < PWN::AI::Agent::Loop::Steering
275
278
  class Stopped < Exception; end # rubocop:disable Lint/InheritException
276
- class PreviewShown < Stopped; end
277
279
 
278
280
  def stopping?
279
281
  @stopping == true
@@ -386,7 +388,7 @@ module PWN
386
388
 
387
389
  def preload(lines)
388
390
  Array(lines).each do |line|
389
- next if line.to_s.strip.empty? || line.match?(%r{\A\s*/input(?:\s|\z)}) || @history.last == line
391
+ next if line.to_s.strip.empty? || line.match?(%r{\A\s*/input(?:\s|\z)}) || line.match?(MEMORY_DECISION) || @history.last == line
390
392
 
391
393
  @history << line.dup
392
394
  end
@@ -457,7 +459,7 @@ module PWN
457
459
 
458
460
  def submit
459
461
  line = @text.dup
460
- @history << line.dup unless line.strip.empty? || @history.last == line || line.match?(%r{\A\s*/input(?:\s|\z)})
462
+ @history << line.dup unless line.strip.empty? || @history.last == line || line.match?(%r{\A\s*/input(?:\s|\z)}) || line.match?(MEMORY_DECISION)
461
463
  @index = @history.length
462
464
  replace('')
463
465
  line
@@ -481,7 +483,62 @@ module PWN
481
483
  end
482
484
  end
483
485
 
484
- # Parent-side steering endpoint; cancellation belongs to the process owner.
486
+ # Child-side rendezvous for one exact memory_remember call, never tool stdin.
487
+ class MemoryReview
488
+ WAIT_SECONDS = 180
489
+
490
+ def initialize(events, generation)
491
+ @events = events
492
+ @generation = generation
493
+ @lock = Mutex.new
494
+ end
495
+
496
+ def call(fields)
497
+ return false unless fields.is_a?(Hash) && fields.size == 3 && %i[key value category].all? { |key| fields[key].is_a?(String) }
498
+ return false unless PWN::Redaction.redact(value: fields) == fields
499
+
500
+ # No indentation: wrap_command must not insert spaces into a continued value.
501
+ display = JSON.pretty_generate(fields, ascii_only: true, indent: '').gsub("\x7f", '\\u007f')
502
+ return false unless PWN::Redaction.redact(value: display) == display
503
+
504
+ ticket = SecureRandom.hex(8)
505
+ reply = Queue.new
506
+ @lock.synchronize do
507
+ return false if @closed || @reply
508
+
509
+ @ticket = ticket
510
+ @reply = reply
511
+ end
512
+ begin
513
+ @events << [:memory_review, { ticket: ticket, display: display }]
514
+ approved = reply.pop(timeout: WAIT_SECONDS) == true
515
+ @events << [:memory_review_closed, ticket]
516
+ approved
517
+ ensure
518
+ @lock.synchronize { @reply = @ticket = nil }
519
+ end
520
+ rescue IOError, SystemCallError, JSON::GeneratorError, ArgumentError
521
+ false
522
+ end
523
+
524
+ def decide(frame)
525
+ @lock.synchronize do
526
+ return unless @reply && !@reply.closed? && frame[:type] == 'memory_decision' && frame[:generation] == @generation && frame[:ticket] == @ticket && %w[approve decline].include?(frame[:decision])
527
+
528
+ @reply << (frame[:decision] == 'approve')
529
+ @reply.close
530
+ end
531
+ end
532
+
533
+ def close
534
+ @lock.synchronize do
535
+ @closed = true
536
+ @reply&.close
537
+ end
538
+ end
539
+ end
540
+
541
+ # Parent-side control endpoint; cancellation belongs to the process owner.
485
542
  class MissionControl
486
543
  def initialize(io)
487
544
  @io = io
@@ -492,6 +549,20 @@ module PWN
492
549
  @io.flush
493
550
  end
494
551
 
552
+ def memory_decision(generation, ticket, decision)
553
+ frame = "#{JSON.generate(type: 'memory_decision', generation: generation, ticket: ticket, decision: decision)}\n"
554
+ return if @io.write_nonblock(frame, exception: false) == frame.bytesize
555
+
556
+ close
557
+ raise IOError, 'Incomplete memory decision'
558
+ end
559
+
560
+ def close
561
+ @io.shutdown(Socket::SHUT_WR) unless @io.closed?
562
+ ensure
563
+ @io.close unless @io.closed?
564
+ end
565
+
495
566
  def phase
496
567
  'mission process'
497
568
  end
@@ -501,6 +572,40 @@ module PWN
501
572
  end
502
573
  end
503
574
 
575
+ # Parent-only observation. A receipt write never owns the request or its text.
576
+ class SubmissionDelivery
577
+ attr_reader :id
578
+
579
+ def initialize
580
+ @store = PWN::AI::Agent::Submission
581
+ @id = @store.optional { @store.open! }
582
+ end
583
+
584
+ def displayed!
585
+ @displayed = true
586
+ acknowledge
587
+ end
588
+
589
+ # Only recover a pending outcome, never replace the child's decision.
590
+ def finish!(status: :incomplete, stage: :controller)
591
+ return unless @id
592
+
593
+ @store.optional { @store.abandon!(submission_id: @id, status: status, stage: stage) }
594
+ acknowledge
595
+ end
596
+
597
+ private
598
+
599
+ def acknowledge
600
+ return unless @id && !@acknowledged
601
+
602
+ @acknowledged = @store.optional do
603
+ @store.delivery!(submission_id: @id, delivery: @displayed ? :displayed : :not_displayed)
604
+ true
605
+ end
606
+ end
607
+ end
608
+
504
609
  # Own the terminal, event pump and the lifetime of exactly one request.
505
610
  class Console # rubocop:disable Metrics/ClassLength -- cohesive single-owner terminal state machine
506
611
  COLORS = { operator: :operator, task: :task, thinking: :notice, tool: :tool, result: :result, assistant: :assistant, notice: :notice, warning: :warning }.freeze
@@ -657,6 +762,15 @@ module PWN
657
762
  next if generation && generation != @mission_generation && generation != @swarm_generation
658
763
 
659
764
  case type
765
+ when :memory_review, :memory_review_closed
766
+ next unless generation && generation == @mission_generation && @running && !@command && !@cancelling && !@leaving
767
+
768
+ if type == :memory_review
769
+ present_memory_review(text, generation)
770
+ elsif @memory_review == [generation, text]
771
+ @memory_review = nil
772
+ add(:command_notice, 'Memory review closed without a decision.')
773
+ end
660
774
  when :command_state
661
775
  if text[:ai].is_a?(Hash)
662
776
  text[:ai][:active] = text[:ai][:active].to_sym if PWN::Env.dig(:ai, :active).is_a?(Symbol) && text[:ai][:active].is_a?(String)
@@ -665,15 +779,29 @@ module PWN
665
779
  text.fetch(:config, {}).each do |key, value|
666
780
  @pry.config.public_send("#{key}=", value) if %i[pwn_ai_session_id pwn_ai_debug pwn_ai_trace].include?(key)
667
781
  end
782
+ when :assistant, :terminal_warning
783
+ shown = add(type == :assistant ? :assistant : :warning, text)
784
+ @mission_submission&.displayed! if shown && generation && generation == @mission_generation
785
+ when :workspace_busy
786
+ next unless generation && generation == @mission_generation && @mission_submission
787
+
788
+ reject_submission(@mission_submission, text)
789
+ @mission_submission = nil
668
790
  when :usage
669
791
  @usage.record(text)
670
792
  when :mission_done
793
+ next unless generation && generation == @mission_generation
794
+
671
795
  @worker.join
796
+ @mission_generation = nil
672
797
  finish_request_metrics
673
798
  @running = false
799
+ @memory_review = nil
800
+ @control&.close
674
801
  @control = nil
675
802
  @mission = nil
676
- @mission_commands&.close unless @mission_commands&.closed?
803
+ @mission_submission&.finish!
804
+ @mission_submission = nil
677
805
  when :operator_loaded
678
806
  generation, data = text
679
807
  if @operator_view && @operator_view[:generation] == generation
@@ -729,11 +857,12 @@ module PWN
729
857
  @title_worker.report_on_exception = false
730
858
  end
731
859
 
732
- def add(type, text)
860
+ def add(type, text, exact: false)
733
861
  command_notice = type == :command_notice
734
862
  type = :notice if command_notice
735
863
  clean = PWN::Redaction.redact(value: text.to_s)
736
864
  clean = clean.gsub(/\e\][^\a]*(?:\a|\e\\)/, '').gsub(%r{\e\[[0-?]*[ -/]*[@-~]}, '').gsub(/[\x00-\x08\x0b-\x1f\x7f]/, '')
865
+ return false if exact && clean != text
737
866
  return if clean.strip.empty?
738
867
 
739
868
  @event_count += 1
@@ -749,6 +878,7 @@ module PWN
749
878
  @scroll = [@scroll - removed[3].fetch(:rows, []).length, 0].max if @scroll
750
879
  end
751
880
  PWN::Plugins::Log.mirror_tui!(msg: "#{type.to_s.upcase}\n#{clean}") if @pry.config.pwn_ai_debug && type != :notice
881
+ true
752
882
  end
753
883
 
754
884
  private_class_method def self.mission_entry(opts = {})
@@ -770,19 +900,6 @@ module PWN
770
900
  %i[pwn_ai_session_id pwn_ai_debug pwn_ai_trace pwn_ai_speak pwn_ai_agent].to_h { |key| [key, @pry.config.public_send(key)] }
771
901
  end
772
902
 
773
- def with_stream_preview(events)
774
- previous = Thread.current[:pwn_stream_preview]
775
- Thread.current[:pwn_stream_preview] = lambda do |provider, text, pending|
776
- visible = text.gsub(/[\x00-\x08\x0B-\x1F\x7F-\u009F]/, '')
777
- events << [:assistant, visible] unless visible.empty?
778
- status = pending ? 'A requested action was not processed.' : 'No actions from this reply were processed.'
779
- raise Control::PreviewShown, "#{provider} reply recovered for display only. #{status} This turn has ended."
780
- end
781
- yield
782
- ensure
783
- Thread.current[:pwn_stream_preview] = previous
784
- end
785
-
786
903
  def mission_request_child(data, writer, commands)
787
904
  request, generation, session_id, title_config = data.values_at(:request, :generation, :session_id, :title_config)
788
905
  events = MissionEvents.new(writer, generation)
@@ -793,14 +910,30 @@ module PWN
793
910
  control = Control.new(input: @input, output: output)
794
911
  Thread.current[:pwn_steering_input] = control
795
912
  Thread.current[:pwn_usage_observer] = ->(usage) { events << [:usage, usage] }
796
- Thread.new do
797
- commands.each_line { |line| control.submit(JSON.parse(line)) }
913
+ review = MemoryReview.new(events, generation)
914
+ command_reader = Thread.new do
915
+ commands.each_line do |line|
916
+ break unless line.end_with?("\n")
917
+
918
+ frame = JSON.parse(line, symbolize_names: true)
919
+ control.submit(frame) if frame.is_a?(String)
920
+ review.decide(frame) if frame.is_a?(Hash)
921
+ end
922
+ rescue IOError, SystemCallError, JSON::ParserError
923
+ # A lost or invalid command channel cannot grant approval.
924
+ nil
925
+ ensure
926
+ review.close
798
927
  end
928
+ error_event = :terminal_warning
799
929
  begin
800
930
  workspace = File.realpath(Dir.pwd)
801
931
  lock_path = File.join(Dir.tmpdir, "pwn-solve-#{Digest::SHA256.hexdigest(workspace)}.lock")
802
932
  File.open(lock_path, File::RDWR | File::CREAT | File::NOFOLLOW, 0o600) do |lease|
803
- raise IOError, 'Workspace busy: another mission owns this directory.' unless lease.flock(File::LOCK_EX | File::LOCK_NB)
933
+ unless lease.flock(File::LOCK_EX | File::LOCK_NB)
934
+ events << [:workspace_busy, 'IOError: Workspace busy: another mission owns this directory.']
935
+ next
936
+ end
804
937
 
805
938
  events << [:session_title, PWN::Sessions.provisional_title(session_id: session_id, request: request)]
806
939
  on_tool = lambda do |name, args, result|
@@ -811,20 +944,30 @@ module PWN
811
944
  events << [:result, result.to_s]
812
945
  end
813
946
  end
814
- final = with_stream_preview(events) do
815
- PWN::AI::Agent::Loop.run(request: request, session_id: session_id,
947
+ previous = Thread.current[:pwn_review_memory]
948
+ final = begin
949
+ Thread.current[:pwn_review_memory] = review.method(:call)
950
+ PWN::AI::Agent::Loop.run(request: request, session_id: session_id, submission_id: data[:submission_id],
816
951
  enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets),
952
+ on_notice: ->(notice) { events << [:warning, notice] },
817
953
  on_tool: on_tool, steering: control, debug: @pry.config.pwn_ai_debug,
818
954
  trace: @pry.config.pwn_ai_trace, debug_tee: output)
955
+ ensure
956
+ Thread.current[:pwn_review_memory] = previous
957
+ end
958
+ if final.is_a?(PWN::AI::Agent::Loop::TurnNotice)
959
+ events << [:terminal_warning, final.to_s]
960
+ next # Do not spend another provider call on a blocked turn.
819
961
  end
820
962
  promoted = Thread.current[:pwn_thinking_promoted] && final.to_s.strip == Thread.current[:pwn_last_thinking].to_s.strip
821
963
  events << [:assistant, final.to_s] unless promoted
964
+ error_event = :warning # Post-turn title failures are diagnostics, not delivery.
822
965
  events << [:session_title, PWN::Sessions.refresh_title(session_id: session_id, ai_config: title_config, on_error: ->(kind) { events << [:warning, "Session title refresh unavailable (#{kind}); previous title retained."] })]
823
966
  end
824
- rescue Control::PreviewShown => e
825
- events << [:warning, e.message]
826
967
  rescue StandardError, Interrupt, Control::Stopped => e
827
- warning = if e.respond_to?(:http_code) && e.http_code == 403
968
+ warning = if e.is_a?(PWN::AI::Grok::AccessDenied)
969
+ e.message
970
+ elsif e.respond_to?(:http_code) && e.http_code == 403
828
971
  'Access denied (HTTP 403). Check that your account can use the selected model and endpoint.'
829
972
  else
830
973
  "#{e.class}: #{e.message}"
@@ -833,8 +976,10 @@ module PWN
833
976
  file = File.basename(origin.path.to_s)
834
977
  warning += " (#{file}:#{origin.lineno})" if file.ascii_only? && file.match?(/\A[\w-]{1,80}\.rb\z/)
835
978
  end
836
- events << [:warning, warning]
979
+ events << [error_event, warning]
837
980
  ensure
981
+ review.close
982
+ command_reader.kill.join
838
983
  output.flush
839
984
  writer.close
840
985
  end
@@ -872,9 +1017,16 @@ module PWN
872
1017
  end
873
1018
  end
874
1019
 
1020
+ def reject_submission(submission, warning, status: :blocked)
1021
+ submission.displayed! if add(:warning, warning)
1022
+ submission.finish!(status: status, stage: :admission)
1023
+ end
1024
+
875
1025
  def start_mission_request(request)
876
- return add(:warning, 'A mission is still running; cancel and reap it first.') if busy?
1026
+ submission = SubmissionDelivery.new
1027
+ return reject_submission(submission, 'A mission is still running; cancel and reap it first.') if busy?
877
1028
 
1029
+ @mission_submission = submission
878
1030
  @mission_generation = SecureRandom.uuid
879
1031
  generation = @mission_generation
880
1032
  session_id = @pry.config.pwn_ai_session_id
@@ -887,20 +1039,22 @@ module PWN
887
1039
  begin_request_metrics
888
1040
  add(:operator, request)
889
1041
  reader, writer = IO.pipe
890
- commands, @mission_commands = IO.pipe
891
- @mission = PWN::Plugins::AISandbox::MissionProcess.new(
892
- descriptor: { operation: :console, request: request, generation: generation, session_id: session_id, title_config: title_config, config: mission_config },
1042
+ commands, sender = PWN::AI::Agent::MissionNamespace.control_socket_pair
1043
+ commands.shutdown(Socket::SHUT_WR)
1044
+ @control = MissionControl.new(sender)
1045
+ @mission = PWN::AI::Sandbox::MissionProcess.new(
1046
+ descriptor: { operation: :console, request: request, generation: generation, session_id: session_id, submission_id: @mission_submission.id, title_config: title_config, config: mission_config },
893
1047
  fds: { 4 => writer, 5 => @input, 6 => commands }
894
1048
  )
895
1049
  writer.close
896
1050
  commands.close
897
- @control = MissionControl.new(@mission_commands)
1051
+
898
1052
  @running = true
899
1053
  mission = @mission
900
1054
  @worker = Thread.new do
901
1055
  reader.each_line do |line|
902
1056
  tag, type, text = JSON.parse(line, symbolize_names: true)
903
- next unless tag == generation && %w[task thinking tool result assistant notice warning session_title usage].include?(type)
1057
+ next unless tag == generation && %w[task thinking tool result assistant notice warning terminal_warning workspace_busy session_title usage memory_review memory_review_closed].include?(type)
904
1058
 
905
1059
  @events << [type.to_sym, text, tag]
906
1060
  end
@@ -913,11 +1067,11 @@ module PWN
913
1067
  end
914
1068
  @worker.report_on_exception = false
915
1069
  rescue StandardError => e
916
- [reader, writer, commands, @mission_commands].compact.each { |io| io.close unless io.closed? }
1070
+ [reader, writer, commands, sender].compact.each { |io| io.close unless io.closed? }
917
1071
  @mission&.close
918
- @mission = nil
1072
+ @mission = @control = @mission_submission = @mission_generation = nil
919
1073
  @running = false
920
- add(:warning, "Mission not started: #{e.message}")
1074
+ reject_submission(submission, "Mission not started: #{e.message}", status: :incomplete)
921
1075
  end
922
1076
 
923
1077
  def cancel_mission
@@ -925,13 +1079,17 @@ module PWN
925
1079
  # reaps namespace PID 1, including all provider and tool descendants.
926
1080
  @cancelling = true
927
1081
  @mission_generation = nil
1082
+ @memory_review = nil
928
1083
  @mission.close
929
1084
  @worker&.join
930
- @mission_commands&.close unless @mission_commands&.closed?
1085
+ @control&.close
931
1086
  @tool_input&.close unless @tool_input&.closed?
932
1087
  @mission = @control = nil
933
1088
  @running = false
934
1089
  finish_request_metrics
1090
+ # The cancellation banner is not delivery of the discarded child reply.
1091
+ @mission_submission&.finish!(status: :cancelled, stage: :cancellation)
1092
+ @mission_submission = nil
935
1093
  add(:warning, 'Mission cancelled; all owned processes reaped. Completed work is not undone.')
936
1094
  end
937
1095
 
@@ -951,7 +1109,7 @@ module PWN
951
1109
  begin_request_metrics
952
1110
  add(:operator, request)
953
1111
  reader, writer = IO.pipe
954
- @mission = PWN::Plugins::AISandbox::MissionProcess.new(
1112
+ @mission = PWN::AI::Sandbox::MissionProcess.new(
955
1113
  descriptor: { operation: :slash, request: request, generation: generation, baseline_ai: baseline_ai, config: mission_config, cleanup: cleanup },
956
1114
  fds: { 4 => writer, 5 => @input }
957
1115
  )
@@ -1029,6 +1187,7 @@ module PWN
1029
1187
  # Preserve normal request text and the exact internal title bytes.
1030
1188
  line = line.gsub(/\A[[:space:]]+|[[:space:]]+\z/, '') if line.match?(%r{\A[[:space:]]*/})
1031
1189
  return if line.strip.empty?
1190
+ return decide_memory(line) if line.match?(MEMORY_DECISION)
1032
1191
 
1033
1192
  # Pry owns the existing pwn_history format, append and deduplication.
1034
1193
  # Curses bypasses Pry's input evaluator, so record once here, not on recall.
@@ -1070,7 +1229,7 @@ module PWN
1070
1229
  open_system_role
1071
1230
  elsif line.match?(%r{\A/(?:maintenance(?:\s|$)|mcp(?:\s|$)|cron\s+run(?:\s|$)|model(?:\s|$)|sessions\s+cleanup(?:\s|$))})
1072
1231
  start_request(line, command: true)
1073
- elsif line.start_with?('/') || line.start_with?('ai.profile ', 'ai.memory ')
1232
+ elsif local_command?(line)
1074
1233
  if line.match?(%r{\A/sessions[[:space:]]+resume(?:[[:space:]]|$)})
1075
1234
  return add(:warning, 'Cannot switch sessions while swarm jobs are active.') if @swarm&.busy?
1076
1235
 
@@ -1087,6 +1246,39 @@ module PWN
1087
1246
  add(:warning, "#{e.class}: #{e.message}")
1088
1247
  end
1089
1248
 
1249
+ def present_memory_review(event, generation)
1250
+ return if @memory_review || !event.is_a?(Hash)
1251
+
1252
+ ticket = event[:ticket]
1253
+ return unless ticket.is_a?(String) && ticket.match?(/\A[0-9a-f]{16}\z/)
1254
+
1255
+ display = event[:display]
1256
+ prompt = "Review this one memory_remember write (escaped JSON):\n#{display}\nType /memory approve #{ticket} or /memory decline #{ticket}."
1257
+ if display.is_a?(String) && display.match?(/\A[\x20-\x7e\n]+\z/) && add(:command_notice, prompt, exact: true)
1258
+ @memory_review = [generation, ticket]
1259
+ else
1260
+ @control.memory_decision(generation, ticket, 'decline')
1261
+ add(:command_notice, 'Memory write declined: the exact proposal could not be displayed.')
1262
+ end
1263
+ rescue IOError, SystemCallError
1264
+ add(:warning, 'Memory review closed: mission control channel disconnected.')
1265
+ end
1266
+
1267
+ def decide_memory(line)
1268
+ decision, ticket = line.match(%r{\A/memory +(approve|decline) +([0-9a-f]{16})\z})&.captures
1269
+ return add(:command_notice, 'No matching pending memory review.') unless ticket && @running && @memory_review == [@mission_generation, ticket]
1270
+
1271
+ @memory_review = nil
1272
+ @control.memory_decision(@mission_generation, ticket, decision)
1273
+ add(:command_notice, 'Memory decision sent.')
1274
+ rescue IOError, SystemCallError
1275
+ add(:warning, 'Memory decision not delivered: mission control channel closed.')
1276
+ end
1277
+
1278
+ def local_command?(line)
1279
+ line.start_with?('/', 'ai.profile ', 'ai.memory ')
1280
+ end
1281
+
1090
1282
  def busy_command(line)
1091
1283
  if line.match?(%r{\A/steer(?:\s|$)})
1092
1284
  if @control.nil?
@@ -1106,7 +1298,8 @@ module PWN
1106
1298
  elsif line.start_with?('/swarm') && %w[status tail steer cancel pause resume help agents].include?(line.split[1])
1107
1299
  run_swarm(line)
1108
1300
  else
1109
- add(:warning, 'Request running. Settings and new requests wait until idle. Use /steer, /input, /swarm status|steer|cancel, /clear, or /verbose.')
1301
+ warning = 'Request running. Settings and new requests wait until idle. Use /steer, /input, /swarm status|steer|cancel, /clear, or /verbose.'
1302
+ local_command?(line) ? add(:warning, warning) : reject_submission(SubmissionDelivery.new, warning)
1110
1303
  end
1111
1304
  end
1112
1305
 
@@ -428,7 +428,7 @@ module PWN
428
428
  @mutex.synchronize { @jobs[id] = job }
429
429
  on_event = opts[:on_event]
430
430
  on_usage = opts[:usage_observer]
431
- job[:mission] = PWN::Plugins::AISandbox::MissionProcess.new(
431
+ job[:mission] = PWN::AI::Sandbox::MissionProcess.new(
432
432
  descriptor: { operation: :swarm, session_id: @session_id, swarm_id: @swarm_id, job: job.slice(:id, :agent, :command), task: task, options: opts.except(:on_event, :usage_observer) },
433
433
  fds: { 4 => writer, 5 => commands }
434
434
  )
data/lib/pwn/plugins.rb CHANGED
@@ -7,7 +7,6 @@ module PWN
7
7
  module Plugins
8
8
  autoload :Android, 'pwn/plugins/android'
9
9
  autoload :AFLplusplus, 'pwn/plugins/aflplusplus'
10
- autoload :AISandbox, 'pwn/plugins/ai_sandbox'
11
10
  autoload :ArtifactRegistry, 'pwn/plugins/artifact_registry'
12
11
  autoload :Assembly, 'pwn/plugins/assembly'
13
12
  autoload :BinaryParser, 'pwn/plugins/binary_parser'
data/lib/pwn/sessions.rb CHANGED
@@ -387,7 +387,8 @@ module PWN
387
387
  opts[:records].each do |row|
388
388
  raise IOError, 'Unsupported request checkpoint version' unless row['version'] == 1
389
389
 
390
- keys = %w[version generation session_id request_id original_request request amendments cwd started_at observations outcome events effects evidence enabled_toolsets verification_contract]
390
+ keys = %w[version generation session_id request_id original_request request amendments cwd started_at observations outcome events effects evidence
391
+ skill_destinations enabled_toolsets verification_contract]
391
392
  raise IOError, 'Unknown request checkpoint fields' unless (row.keys - keys).empty?
392
393
 
393
394
  sid = row['session_id']
@@ -404,6 +405,13 @@ module PWN
404
405
  %w[observations effects].all? { |key| row[key].is_a?(Hash) } &&
405
406
  %w[outcome verification_contract].all? { |key| row[key].nil? || row[key].is_a?(Hash) } &&
406
407
  (row['enabled_toolsets'].nil? || row['enabled_toolsets'].is_a?(Array))
408
+ # Older v1 writers omitted this map. Check path spelling without looking up destinations on disk.
409
+ destinations = row.fetch('skill_destinations', {})
410
+ valid &&= destinations.is_a?(Hash) && destinations.all? do |path, kind|
411
+ next false if path.include?("\0") || path.include?('//')
412
+
413
+ File.absolute_path(path, '/') == path && %w[file directory].include?(kind)
414
+ end
407
415
  raise IOError, 'Invalid request checkpoint schema' unless valid
408
416
  end
409
417
  []
data/lib/pwn/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PWN
4
- VERSION = '0.5.804'
4
+ VERSION = '0.5.806'
5
5
  end