Module: PWN::Plugins::REPL
- Defined in:
- lib/pwn/plugins/repl.rb,
lib/pwn/plugins/repl/ai.rb,
lib/pwn/plugins/repl/asm.rb,
lib/pwn/plugins/repl/irc.rb,
lib/pwn/plugins/repl/mesh.rb,
lib/pwn/plugins/repl/vault.rb
Overview
This module contains methods related to the pwn REPL Driver.
Defined Under Namespace
Modules: AI, ASM, IRC, Mesh, Vault Classes: PWNMultiLineInput
Constant Summary collapse
- PWN_MESH_SLASH_COMMANDS =
%w[ /back /channel /device /help /menu /msg /status /toggle-dispatch-to-pwn-ai /transport ].freeze
- PWN_MESH_SLASH_SUBCOMMANDS =
{ '/channel' => %w[list], '/device' => %w[list], '/msg' => [], '/help' => [], '/back' => [], '/status' => [], '/toggle-dispatch-to-pwn-ai' => [], '/transport' => %w[list auto serial bluetooth tcp mqtt] }.freeze
Class Method Summary collapse
- .add_commands ⇒ Object
-
.add_hooks ⇒ Object
- Supported Method Parameters
PWN::Plugins::REPL.add_hooks.
-
.authors ⇒ Object
- Author(s)
0day Inc.
-
.compact_context_tokens(opts = {}) ⇒ Object
Compact token-count formatter for the pwn.ai PS1 (e.g. 0, 843, 12K, 250K, 1M).
-
.enable_autocomplete(opts = {}) ⇒ Object
Consume a CLI-prepared session once; ordinary activation creates one.
-
.help ⇒ Object
Display Usage for this Module.
-
.install_pwn_ai_completer!(opts = {}) ⇒ Object
Install Reline dropdown for pwn-ai (commands / paths / Ruby).
-
.install_pwn_mesh_completer!(opts = {}) ⇒ Object
Install Reline dropdown for pwn-mesh slash commands.
-
.leave_special_mode!(opts = {}) ⇒ Object
Leave pwn-ai / pwn-asm / pwn-mesh and restore the host REPL (also CTRL+D).
- .mesh_active_psks(opts = {}) ⇒ Object
- .mesh_ai_prompt(opts = {}) ⇒ Object
- .mesh_ai_whitelisted?(opts = {}) ⇒ Boolean
-
.mesh_bound_transport(opts = {}) ⇒ Object
Live radio kind after connect (MeshTransport) or the pinned / first-probe kind.
-
.mesh_box!(opts = {}) ⇒ Object
Explicit Unicode avoids ACS falling back to ASCII on some terminals.
- .mesh_broadcast?(opts = {}) ⇒ Boolean
- .mesh_channel_name_for_index(opts = {}) ⇒ Object
- .mesh_channel_name_from_topic(opts = {}) ⇒ Object
-
.mesh_channel_names(opts = {}) ⇒ Object
Named Meshtastic channel keys from plugins.meshtastic.channel (not :active).
- .mesh_channel_psks(opts = {}) ⇒ Object
- .mesh_channel_securely_encrypted?(opts = {}) ⇒ Boolean
-
.mesh_compose_send(opts = {}) ⇒ Object
Send compose text on the active channel, or a @!nodeid DM.
-
.mesh_connect(opts = {}) ⇒ Object
Open a Meshtastic session.
-
.mesh_connect_one(opts = {}) ⇒ Object
Open one Meshtastic backend (serial, bluetooth, tcp, or mqtt).
-
.mesh_console_loop(opts = {}) ⇒ Object
Workers enqueue RX; curses alone owns terminal input and drawing.
- .mesh_decorate_local_id(opts = {}) ⇒ Object
- .mesh_device_channel_meta(opts = {}) ⇒ Object
- .mesh_device_channels(opts = {}) ⇒ Object
-
.mesh_disconnect(opts = {}) ⇒ Object
Close the Meshtastic session opened by #mesh_connect.
- .mesh_drain_events ⇒ Object
- .mesh_draw_input(opts = {}) ⇒ Object
- .mesh_env_channel_name_for_psk(opts = {}) ⇒ Object
- .mesh_env_hash(opts = {}) ⇒ Object
- .mesh_handle_rx(opts = {}) ⇒ Object
-
.mesh_layout(opts = {}) ⇒ Object
Row counts for header, CONVERSATION, and COMPOSE so the TUI fits the terminal.
- .mesh_link_label(opts = {}) ⇒ Object
-
.mesh_list_devices(opts = {}) ⇒ Object
Discover radios for the active transport (serial globs, BLE scan, tcp/mqtt config).
- .mesh_maybe_dispatch_to_pwn_ai(opts = {}) ⇒ Object
-
.mesh_menu_pick(opts = {}) ⇒ Object
Curses (or injected getch) picker for pwn-mesh lists.
- .mesh_menu_root(opts = {}) ⇒ Object
-
.mesh_mqtt_region(opts = {}) ⇒ Object
Region is an opaque broker path and may contain multiple components.
-
.mesh_mqtt_tls?(opts = {}) ⇒ Boolean
Treat only explicit true-ish values as MQTT TLS (YAML "false" is a truthy string).
-
.mesh_mqtt_topic(opts = {}) ⇒ Object
Human-readable link for the pwn-mesh RX header.
- .mesh_payload_fits?(opts = {}) ⇒ Boolean
- .mesh_psk_b64(opts = {}) ⇒ Object
- .mesh_psk_same?(opts = {}) ⇒ Boolean
- .mesh_public_psk?(opts = {}) ⇒ Boolean
- .mesh_radio_channel(opts = {}) ⇒ Object
- .mesh_radio_index_for_name(opts = {}) ⇒ Object
-
.mesh_reconnect!(opts = {}) ⇒ Object
Reopen the Meshtastic session after a live /transport /device /channel change.
- .mesh_refresh_ui!(opts = {}) ⇒ Object
- .mesh_reply_target_label(opts = {}) ⇒ Object
-
.mesh_reset_input!(opts = {}) ⇒ Object
Drop the submitted TX buffer so the next prompt is empty (Reline keeps the old line).
- .mesh_rx_text(opts = {}) ⇒ Object
- .mesh_self_node_id(opts = {}) ⇒ Object
- .mesh_send_text(opts = {}) ⇒ Object
-
.mesh_start_rx!(opts = {}) ⇒ Object
Subscribe thread for TEXT_MESSAGE_APP frames (also used after /channel|/transport|/device).
- .mesh_submit(opts = {}) ⇒ Object
-
.mesh_subscribe(opts = {}) ⇒ Object
Subscribe for inbound TEXT_MESSAGE_APP frames.
- .mesh_text_app?(opts = {}) ⇒ Boolean
- .mesh_text_chunks(opts = {}) ⇒ Object
-
.mesh_text_payload_max(opts = {}) ⇒ Object
Send a text frame on the active mesh transport.
-
.mesh_transport(opts = {}) ⇒ Object
rubocop:disable Metrics/ClassLength.
- .mesh_tx_row_ready?(opts = {}) ⇒ Boolean
- .mesh_ui_puts(opts = {}) ⇒ Object
- .mesh_unassigned_slot_map(opts = {}) ⇒ Object
- .mesh_wait_tx_slot(opts = {}) ⇒ Object
- .mesh_whitelist_name_for_index(opts = {}) ⇒ Object
-
.mesh_wrap_text(opts = {}) ⇒ Object
Print slash-menu text into the RX pane when curses is up, else STDOUT.
- .persist_ai_selection(opts = {}) ⇒ Object
-
.persist_mesh_env(opts = {}) ⇒ Object
Write plugins.meshtastic from the live Env into ~/.pwn/pwn.yaml (vault).
- .pwn_ai_activation_session(opts = {}) ⇒ Object
-
.pwn_ai_complete(opts = {}) ⇒ Object
- Supported Method Parameters
hits = PWN::Plugins::REPL.pwn_ai_complete( target: 'required - token Reline is completing', line: 'optional - full line buffer', pry: 'optional - Pry instance for Ruby completion' ).
- .pwn_ai_complete_command(opts = {}) ⇒ Object
-
.pwn_ai_complete_kind(opts = {}) ⇒ Object
rubocop:disable Metrics/ClassLength.
- .pwn_ai_complete_path(opts = {}) ⇒ Object
- .pwn_ai_complete_ruby(opts = {}) ⇒ Object
-
.pwn_ai_dispatch_slash!(opts = {}) ⇒ Object
Run a leading-slash pwn-ai command locally.
- .pwn_ai_engine_model(opts = {}) ⇒ Object
- .pwn_ai_engines(opts = {}) ⇒ Object
- .pwn_ai_list_llms(opts = {}) ⇒ Object
- .pwn_ai_mcp_call_args(opts = {}) ⇒ Object
- .pwn_ai_mcp_coerce(opts = {}) ⇒ Object
-
.pwn_ai_memory_command(opts = {}) ⇒ Object
View/edit the session's pinned block, separate from cross-session facts.
- .pwn_ai_model_ids(opts = {}) ⇒ Object
-
.pwn_ai_profile_command(opts = {}) ⇒ Object
Validate selection before changing request-local routing state.
- .pwn_ai_provider_class(opts = {}) ⇒ Object
- .pwn_ai_run_cron(opts = {}) ⇒ Object
- .pwn_ai_run_learning(opts = {}) ⇒ Object
-
.pwn_ai_run_mcp(opts = {}) ⇒ Object
Run pwn-ai /mcp locally without sending the line through Loop.run.
- .pwn_ai_run_memory(opts = {}) ⇒ Object
- .pwn_ai_run_model(opts = {}) ⇒ Object
- .pwn_ai_run_sessions(opts = {}) ⇒ Object
- .pwn_ai_run_skills(opts = {}) ⇒ Object
-
.pwn_mesh_complete(opts = {}) ⇒ Object
TAB hits for pwn-mesh slash menus (commands, channel names, transports, devices).
- .pwn_mesh_complete_command(opts = {}) ⇒ Object
-
.pwn_mesh_dispatch_slash!(opts = {}) ⇒ Object
Run a leading-slash pwn-mesh command locally.
- .pwn_mesh_help_text(opts = {}) ⇒ Object
-
.pwn_mesh_menu_rows(opts = {}) ⇒ Object
Curses overlay rows for the pwn-mesh slash menu (Reline's dropdown is hidden by ncurses).
- .pwn_mesh_run_channel(opts = {}) ⇒ Object
- .pwn_mesh_run_device(opts = {}) ⇒ Object
- .pwn_mesh_run_msg(opts = {}) ⇒ Object
- .pwn_mesh_run_toggle_dispatch(opts = {}) ⇒ Object
- .pwn_mesh_run_transport(opts = {}) ⇒ Object
- .pwn_mesh_status_text(opts = {}) ⇒ Object
-
.ready_tty!(opts = {}) ⇒ Object
Restore the TTY after a spinner / agent turn so Pry/Reline prints the next PS1 immediately.
- .refresh_ps1_proc(opts = {}) ⇒ Object
- .restore_pwn_ai_completer!(opts = {}) ⇒ Object
-
.start(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Plugins::REPL.start.
Class Method Details
.add_commands ⇒ Object
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/pwn/plugins/repl.rb', line 418 def self.add_commands # Load any existing pwn.yaml configuration file # Define Custom REPL Commands Pry::Commands.create_command 'welcome-banner' do description 'Display the random welcome banner, including basic usage.' def process puts PWN::Banner.welcome end end Pry::Commands.create_command 'toggle-pager' do description 'Toggle less on returned objects surpassing the terminal.' def process pi = pry_instance pi.config.pager ? pi.config.pager = false : pi.config.pager = true end end # class PWNCompleter < Pry::InputCompleter # def call(input) # end # end PWN::Plugins::REPL::ASM.add_commands PWN::Plugins::REPL::AI.add_commands PWN::Plugins::REPL::IRC.add_commands PWN::Plugins::REPL::Mesh.add_commands PWN::Plugins::REPL::Vault.add_commands Pry::Commands.create_command 'back' do description 'Jump back to pwn REPL when in pwn-asm || pwn-ai. CTRL+D does the same in those modes.' def process PWN::Plugins::REPL.leave_special_mode!(pry: pry_instance) end end rescue StandardError => e raise e end |
.add_hooks ⇒ Object
- Supported Method Parameters
PWN::Plugins::REPL.add_hooks
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 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 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 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 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 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 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 |
# File 'lib/pwn/plugins/repl.rb', line 463 public_class_method def self.add_hooks # Define REPL Hooks # Welcome Banner Hook Pry.config.hooks.add_hook(:before_session, :welcome) do |output, _binding, _pi| Pry.config.refresh_pwn_env = false output.puts PWN::Banner.welcome end Pry.config.hooks.add_hook(:after_read, :pwn_asm_hook) do |request, pi| if pi.config.pwn_asm && !request.chomp.empty? request = pi.input.line_buffer arch = PWN::Env[:plugins][:asm][:arch] endian = PWN::Env[:plugins][:asm][:endian] # Analyze request to determine if it should be processed as opcodes or asm. straight_hex = /^[a-fA-F0-9\s]+$/ hex_esc_strings = /\\x[\da-fA-F]{2}/ hex_comma_delim_w_dbl_qt = /"(?:[0-9a-fA-F]{2})",?/ hex_comma_delim_w_sng_qt = /'(?:[0-9a-fA-F]{2})',?/ hex_byte_array_as_str = /^\[\s*(?:"[0-9a-fA-F]{2}",\s*)*"[0-9a-fA-F]{2}"\s*\]$/ if request.match?(straight_hex) || request.match?(hex_esc_strings) || request.match?(hex_comma_delim_w_dbl_qt) || request.match?(hex_comma_delim_w_sng_qt) || request.match?(hex_byte_array_as_str) response = PWN::Plugins::Assembly.opcodes_to_asm( opcodes: request, opcodes_always_strings_obj: true, arch: arch, endian: endian ) else response = PWN::Plugins::Assembly.asm_to_opcodes( asm: request, arch: arch, endian: endian ) end puts "\001\e[31m\002#{response}\001\e[0m\002" end end Pry.config.hooks.add_hook(:after_read, :pwn_ai_hook) do |request, pi| if pi.config.pwn_ai && !request.chomp.empty? orig_request = pi.input.line_buffer.to_s if PWN::Plugins::REPL.pwn_ai_dispatch_slash!(request: orig_request, pry: pi) request.replace('nil') next end # ---------------------------------------------------------------- # NATIVE TOOL-CALLING AGENT LOOP (default path) # # Routes through PWN::AI::Agent::Loop, which uses real # function-calling (tools: array on the chat/completions request, # role:'tool' result messages) instead of the regex-ReAct below. # # Disable by setting in pwn.yaml: # ai: # agent: # native_tools: false # ---------------------------------------------------------------- native = PWN::Env.dig(:ai, :agent, :native_tools) native = true if native.nil? if pi.config.pwn_ai_agent && native begin sess_id = pi.config.pwn_ai_session_id # on_tool UI contract: Loop.run emits ONE name='task' brief # BEFORE each tool *collection* (TaskSummarizer.about_to with # tools: [...]). arg_preview is plain-English what/why for # executives. Task lines never show a result row — results # belong only to the subsequent per-tool lines (one-to-many). on_tool = lambda do |name, args, result| # Task summaries are shown in their entirety (multi-line OK). # Tool request + result are shown in full (no char cap). # Raw ANSI only — PS1 SOH/STX on live stdout swallows later rows. # When debug is on, the same plain text is mirrored into the # open ~/.pwn/logs/pwn-ai-DEBUG-…-RN.log for human troubleshooting. mirror = lambda do |plain| next unless pi.config.pwn_ai_debug && defined?(PWN::Plugins::Log) PWN::Plugins::Log.mirror_tui!(msg: plain) end if name.to_s == 'task' body = args.is_a?(String) ? args.to_s : args.inspect = Time.now.strftime('%Y-%m-%d %H:%M:%S%z') header = "[ #{} → pwn-ai → task ]" print "\e[33m#{header}\e[0m " body_out = +'' body.to_s.each_line do |ln| puts "\e[32m #{ln.rstrip}\e[0m" body_out << " #{ln.rstrip}\n" end mirror.call("#{header}\n#{body_out}") next end argv = args.is_a?(String) ? args.to_s : args.inspect = Time.now.strftime('%Y-%m-%d %H:%M:%S%z') header = "[ #{} → pwn-ai → #{name} ]" puts "\e[33m#{header}\e[0m" argv_out = +'' argv.to_s.each_line do |ln| puts "\e[33m #{ln.rstrip}\e[0m" argv_out << " #{ln.rstrip}\n" end = Time.now.strftime('%Y-%m-%d %H:%M:%S%z') res_header = "#{} → result" puts "\e[36m#{res_header}\e[0m" res_out = +'' result.to_s.each_line do |ln| puts "\e[36m #{ln.rstrip}\e[0m" res_out << " #{ln.rstrip}\n" end puts mirror.call("#{header}\n#{argv_out}#{res_header}\n#{res_out}\n") end final = PWN::AI::Agent::Loop.run( request: orig_request, session_id: sess_id, enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets), on_tool: on_tool, debug: pi.config.pwn_ai_debug, debug_tee: $stdout ) $stdout.flush puts "\n\e[32m#{final}\e[0m\n\n" $stdout.flush PWN::Plugins::Log.mirror_tui!(msg: "\n#{final}\n\n") if pi.config.pwn_ai_debug && defined?(PWN::Plugins::Log) if pi.config.pwn_ai_debug && sess_id && PWN.const_defined?(:Sessions) PWN::Plugins::Log.progress( msg: "session=#{sess_id}", which_self: PWN::Sessions ) end request.replace('nil') next rescue Interrupt Thread.current[:pwn_log_progress] = false PWN::Plugins::Log.note_interrupt!(where: 'CTRL+C', which_self: PWN::Plugins::REPL) if pi.config.pwn_ai_debug && defined?(PWN::Plugins::Log) raise rescue StandardError => e PWN::Plugins::Log.note_exception!(error: e, where: 'native agent loop', which_self: PWN::Plugins::REPL) if defined?(PWN::Plugins::Log) && PWN::Plugins::Log.respond_to?(:note_exception!) warn "[pwn-ai] native agent loop failed (#{e.class}: #{e..to_s.split("\n").first})" request.replace('nil') next ensure PWN::Plugins::REPL.ready_tty! end end # ---------------------------------------------------------------- # LEGACY regex-ReAct path (kept as fallback; remove once all # engines have a working .chat_with_tools and the native loop has had # real-API smoke time on each). # ---------------------------------------------------------------- # Do NOT rebind the 'request' parameter (the string object passed by Pry's after_read hook). # We will mutate it to 'nil' at the end of handling so Pry does not eval the natural-language # prompt text as Ruby (which was causing noisy exceptions *after* the green AI response print). debug = pi.config.pwn_ai_debug engine = PWN::Env[:ai][:active].to_s.downcase.to_sym response_history = PWN::Env[:ai][engine][:response_history] speak_answer = pi.config.pwn_ai_speak is_agent = (pi.config.pwn_ai_agent == true) # pwn-ai agent mode: load skills context for autonomous task carrying skills_context = '' 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) memory_context = '' memory_context = PWN::Memory.to_context(limit: 25) if is_agent && PWN.const_defined?(:Memory) sess_id = begin pi.config.pwn_ai_session_id rescue StandardError nil end # Pre-process for clear CLI execution intent (e.g. "what does `id` return?") # This makes the agent actually *run* commands instead of just explaining them. curr_req = orig_request.chomp if is_agent && sess_id && PWN.const_defined?(:Sessions) begin PWN::Sessions.append(session_id: sess_id, role: 'user', content: orig_request) rescue StandardError nil end end if is_agent && request =~ /`([^`]+)`/ potential = ::Regexp.last_match(1).strip # Looks like a shell command (not PWN ruby) unless potential =~ /^(PWN::|def |class |require |puts |pp )/ curr_req = "The user wants the *actual raw output* of this command (do not just describe it): `#{potential}`. " \ 'To fulfill the request accurately, you MUST immediately output ONLY a bash code block with the exact command. ' \ "Example format: ```bash\n#{potential}\n``` . After the host executes it, you will receive the OBSERVATION with the real output." end end # Strict system prompt for agent mode (forces tool use over explanation) system_role = nil if is_agent base = PWN::Env[:ai][engine][:system_role_content] || 'You are an ethical hacker.' system_role = base + <<~PROMPT You are operating as an autonomous agent inside the PWN REPL driver. PRIMARY RULE FOR CLI AND TOOLS: When the user asks for the output of a command, "what does X return?", "run X", or anything that requires real execution, you MUST use a tool call.#{' '} NEVER just explain what a command does or what its output "would be".#{' '} To execute anything: - Output *exactly and only* a fenced code block. - For shell/CLI: ```bash <exact command here> ``` - For PWN Ruby modules: ```ruby PWN::Plugins::NmapIt.port_scan(...) ``` The host will execute it (Ruby in full PWN context, bash via shell) and reply with an OBSERVATION containing the real result.#{' '} Then continue or give the final answer. Available tools include all PWN::Plugins (NmapIt, TransparentBrowser, etc.), SAST, Reports, and any CLI via bash blocks. Skills available this session:#{skills_context} #{memory_context} PERSISTENT CAPABILITIES (use via ruby code blocks or direct calls): - Memory (cross-session): PWN::Memory.remember(key: :key, value: val, category: :fact|:preference|:lesson) PWN::Memory.recall(query: 'foo'), PWN::Memory.forget(key: key) - Sessions: current session id = #{sess_id}; PWN::Sessions.append(session_id: '#{sess_id}', role: 'observation', content: obs) - Cron: PWN::Cron.create(schedule: '0 * * * *', prompt: 'task here', name: 'foo') PWN::Cron.run(id: 'id'); list with PWN::Cron.list - Agents/Delegation: PWN::AI::Agent::SAST.analyze(request: ...); PWN::AI::Agent::VulnGen etc. For sub-agents use threads or separate eval calls and feed results back as OBS. After receiving an observation, decide the next step or conclude. If you output text without a code block, it will be treated as your final answer to the user. PROMPT end max_turns = is_agent ? 7 : 1 turn = 0 last_response = '' tool_was_executed_this_turn = false while turn < max_turns chat_opts = { request: curr_req, response_history: response_history, speak_answer: speak_answer, spinner: false } chat_opts[:system_role_content] = system_role if system_role case engine when :anthropic response = PWN::AI::Anthropic.chat(chat_opts) when :gemini response = PWN::AI::Gemini.chat(chat_opts) when :grok response = PWN::AI::Grok.chat(chat_opts) when :ollama response = PWN::AI::Ollama.chat(chat_opts) when :openai response = PWN::AI::OpenAI.chat(chat_opts) when :openwebui response = PWN::AI::OpenWebUI.chat(chat_opts) else raise "ERROR: Unsupported AI Engine: #{engine}" end if response.nil? last_response = 'Model not currently supported with API key.' else if response[:choices].last.keys.include?(:text) last_response = response[:choices].last[:text].to_s else last_response = response[:choices].last[:content].to_s end response_history = { id: response[:id], object: response[:object], model: response[:model], usage: response[:usage] } response_history[:choices] ||= response[:choices] end puts "\n\001\e[32m\002#{last_response}\001\e[0m\002\n\n" if is_agent && sess_id && PWN.const_defined?(:Sessions) begin PWN::Sessions.append(session_id: sess_id, role: 'assistant', content: last_response) rescue StandardError nil end end if debug puts 'DEBUG: response_history => ' pp response_history end PWN::Env[:ai][engine][:response_history] = response_history # === Agent tool execution: parse code blocks from *this* response and actually run them === tool_was_executed_this_turn = false if is_agent # Robust regex: tolerate language specifier, extra whitespace, and text around the block last_response.scan(/```(?:\s*(ruby|bash|sh|shell|zsh))?\s*\n?(.*?)\n?```/m).each do |lang, code| code = code.strip next if code.empty? || tool_was_executed_this_turn lang = (lang || 'bash').downcase puts "\001\e[33m\002[ pwn-ai AGENT EXEC #{lang} ]\e[0m\002 #{code[0..90]}..." obs = '' begin if lang == 'ruby' require 'stringio' old_stdout = $stdout $stdout = StringIO.new res = eval(code, TOPLEVEL_BINDING) # rubocop:disable Security/Eval -- intentional for pwn-ai agent to run PWN Ruby modules/tools in REPL context captured = $stdout.string $stdout = old_stdout obs = (captured + "\n=> #{res.inspect}").strip else # CLI execution - use Open3 for cleaner capture (no extra shell if possible, but backticks are simple and work) require 'open3' stdout, stderr, status = Open3.capture3(code) obs = stdout obs += "\n[stderr]\n#{stderr}" unless stderr.to_s.strip.empty? obs += "\n[exit: #{status.exitstatus}]" unless status.success? obs = obs.strip end rescue StandardError => e obs = "ERROR executing #{lang} block: #{e.class} - #{e.}" end puts "\001\e[36m\002[OBSERVATION from #{lang}]\001\e[0m\002\n#{obs[0..700]}\n" if is_agent && sess_id && PWN.const_defined?(:Sessions) begin PWN::Sessions.append(session_id: sess_id, role: 'observation', content: obs) rescue StandardError nil end end # Feed real result back to the model as the next "user" message in the loop curr_req = "OBSERVATION (#{lang} execution result for previous block):\n#{obs}\n\n" \ "Now continue fulfilling the original user request: #{orig_request}. " \ 'If the task is complete, give the final answer (no more code blocks). Otherwise output the next needed tool block.' tool_was_executed_this_turn = true turn += 1 break # one execution per model turn for controlled pacing end end # If we executed something, loop to let the model react to the OBS next if tool_was_executed_this_turn # No tool executed this turn -> this last_response is the final answer break end # If in agent mode and the model never produced an executable block but the query clearly wanted execution, # give one last chance with a strong reminder (helps weaker models like some Ollama ones) if is_agent && !tool_was_executed_this_turn && orig_request =~ /`[^`]+`/ && turn < max_turns reminder = 'The user explicitly asked about the output of a command in backticks. ' \ 'Do not describe the command. Output *only* the corresponding ```bash block now so the host can run it and give you the real result.' curr_req = "#{reminder}\nOriginal: #{orig_request}" # One final direct call (no full re-loop to avoid complexity) # (The main loop already handled most cases; this is a safety net) end request.replace('nil') if request.respond_to?(:replace) PWN::Plugins::REPL.ready_tty! end end Pry.config.hooks.add_hook(:after_read, :pwn_mesh_hook) do |request, pi| if pi.config.pwn_mesh && !request.chomp.empty? orig_request = request.to_s.chomp if PWN::Plugins::REPL.pwn_mesh_dispatch_slash!(request: orig_request, pry: pi) PWN::Plugins::REPL.mesh_reset_input!(pry: pi, submitted: orig_request) request.replace('nil') if request.respond_to?(:replace) next end mqtt_obj = PWN.const_get(:MeshObj) mesh_env = PWN::Env[:plugins][:meshtastic] PWN::Plugins::REPL.send(:mesh_compose_send, env: mesh_env, obj: mqtt_obj, text: orig_request) PWN::Plugins::REPL.mesh_reset_input!(pry: pi, submitted: orig_request) request.replace('nil') if request.respond_to?(:replace) end end rescue StandardError => e raise e end |
.authors ⇒ Object
- Author(s)
0day Inc. [email protected]
1003 1004 1005 1006 1007 |
# File 'lib/pwn/plugins/repl.rb', line 1003 public_class_method def self. "AUTHOR(S): 0day Inc. <[email protected]> " end |
.compact_context_tokens(opts = {}) ⇒ Object
Compact token-count formatter for the pwn.ai PS1 (e.g. 0, 843, 12K, 250K, 1M).
332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/pwn/plugins/repl.rb', line 332 public_class_method def self.compact_context_tokens(opts = {}) n = opts[:tokens].to_i return n.to_s if n < 1_000 if n >= 1_000_000 v = n / 1_000_000.0 s = v >= 10 ? v.round.to_s : format('%.1f', v).sub(/\.0$/, '') "#{s}M" else v = n / 1_000.0 s = v >= 10 ? v.round.to_s : format('%.1f', v).sub(/\.0$/, '') "#{s}K" end end |
.enable_autocomplete(opts = {}) ⇒ Object
Consume a CLI-prepared session once; ordinary activation creates one.
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 |
# File 'lib/pwn/plugins/repl.rb', line 931 public_class_method def self.enable_autocomplete(opts = {}) enabled = opts.fetch(:enabled, true) require 'reline' Pry.config.input = Reline Pry.config.completer = Pry::InputCompleter Reline.autocompletion = enabled if enabled && defined?(Reline::Face) && Reline::Face.respond_to?(:config) # Readable dropdown on dark terminals (matches the pwn red/cyan PS1). Reline::Face.config(:completion_dialog) do |face| face.define :default, foreground: :bright_white, background: :black face.define :enhanced, foreground: :black, background: :bright_cyan face.define :scrollbar, foreground: :bright_red, background: :black end end enabled rescue StandardError => e warn "[pwn] autocomplete unavailable (#{e.class}: #{e.}); falling back to default input." false end |
.help ⇒ Object
Display Usage for this Module
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 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 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 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 |
# File 'lib/pwn/plugins/repl.rb', line 1011 public_class_method def self.help puts "USAGE: # Restore the TTY after a spinner / agent turn so Pry/Reline prints #{self}.ready_tty!( skip: 'optional - skip value consumed by #ready_tty!', io: 'optional - io value consumed by #ready_tty!' ) # Compact token-count formatter for the pwn.ai PS1 (e.g. 0, 843, 12K, 250K, 1M) #{self}.compact_context_tokens( tokens: 'optional - tokens value consumed by #compact_context_tokens' ) # Run refresh ps1 proc and return its result #{self}.refresh_ps1_proc( mode: 'optional - mode value consumed by #refresh_ps1_proc' ) # Run add commands and return its result #{self}.add_commands # Leave pwn-ai, pwn-asm, or pwn-mesh (also invoked by CTRL+D). #{self}.leave_special_mode!( pry: 'required - Pry instance whose special mode should end' ) # Run add hooks and return its result #{self}.add_hooks # Run pwn ai complete kind and return its result #{self}.pwn_ai_complete_kind( line: 'optional - line value consumed by #pwn_ai_complete_kind' ) # Run pwn ai complete and return its result #{self}.pwn_ai_complete( target: 'required - token Reline is completing', line: 'optional - full line buffer', pry: 'optional - Pry instance for Ruby completion' ) # Run pwn ai complete command and return its result #{self}.pwn_ai_complete_command( line: 'optional - line value consumed by #pwn_ai_complete_command', target: 'required - hostname, IP, or CIDR to scan' ) # Run pwn ai complete path and return its result #{self}.pwn_ai_complete_path( target: 'required - hostname, IP, or CIDR to scan', line: 'optional - line value consumed by #pwn_ai_complete_path' ) # Run pwn ai complete ruby and return its result #{self}.pwn_ai_complete_ruby( target: 'optional - hostname, IP, or CIDR to scan', pry: 'optional - pry value consumed by #pwn_ai_complete_ruby (defaults to Thread.current[:pwn_ai_completer_pry])' ) # Install Reline dropdown for pwn-ai (commands / paths / Ruby) #{self}.install_pwn_ai_completer!( pry: 'optional - pry value consumed by #install_pwn_ai_completer!' ) # Run restore pwn ai completer and return its result #{self}.restore_pwn_ai_completer! # Run a leading-slash pwn-ai command locally. Returns true when handled #{self}.pwn_ai_dispatch_slash!( request: 'optional - request value consumed by #pwn_ai_dispatch_slash!', pry: 'optional - pry value consumed by #pwn_ai_dispatch_slash!' ) # Run pwn ai engines and return its result #{self}.pwn_ai_engines # Run pwn ai provider class and return its result #{self}.pwn_ai_provider_class( engine: 'optional - engine value consumed by #pwn_ai_provider_class' ) # Run pwn ai model ids and return its result #{self}.pwn_ai_model_ids( models: 'optional - models value consumed by #pwn_ai_model_ids' ) # Run pwn ai list llms and return its result #{self}.pwn_ai_list_llms( engine: 'required - engine value consumed by #pwn_ai_list_llms' ) # Run pwn ai engine model and return its result #{self}.pwn_ai_engine_model( engine: 'required - engine value consumed by #pwn_ai_engine_model' ) # Run pwn ai run model and return its result #{self}.pwn_ai_run_model( args: 'optional - Array args value consumed by #pwn_ai_run_model' ) # Run persist ai selection and return its result #{self}.persist_ai_selection( engine: 'required - engine value consumed by #persist_ai_selection', model: 'required - model value consumed by #persist_ai_selection' ) # Run pwn ai run cron and return its result #{self}.pwn_ai_run_cron( args: 'optional - Array args value consumed by #pwn_ai_run_cron' ) # Run pwn ai run sessions and return its result #{self}.pwn_ai_run_sessions( args: 'optional - Array args value consumed by #pwn_ai_run_sessions' ) # Run pwn ai run memory and return its result #{self}.pwn_ai_run_memory( args: 'optional - Array args value consumed by #pwn_ai_run_memory' ) # List or requeue conflicted learning outcomes. #{self}.pwn_ai_run_learning( args: 'optional - list [--conflicted] or requeue' ) # Run pwn ai run skills and return its result #{self}.pwn_ai_run_skills( args: 'optional - Array args value consumed by #pwn_ai_run_skills' ) # Run pwn-ai /mcp locally without Loop.run #{self}.pwn_ai_run_mcp( args: 'optional - slash tokens after /mcp such as list tools or call menu_catalog' ) # Curses arrow-key picker for pwn-mesh channel, transport, and device lists #{self}.mesh_menu_pick( title: 'optional - window title drawn on the boxed curses menu', items: 'required - Array of selectable strings such as channel names', current: 'optional - currently selected item to highlight', getch: 'optional - proc returning the next key so specs can drive the menu without a TTY' ) # Clear the pwn-mesh TX buffer after a slash command or sent mesh line #{self}.mesh_reset_input!( pry: 'optional - Pry instance whose Reline/line_buffer should be emptied', submitted: 'optional - the line that was just accepted so the TX pane can hide it' ) # Curses overlay rows for the pwn-mesh slash menu while typing a leading slash #{self}.pwn_mesh_menu_rows( line: 'optional - current TX buffer; leading slash lists matching mesh commands' ) # TAB hits for pwn-mesh slash menus (commands, named channels, transports, devices) #{self}.pwn_mesh_complete( target: 'required - token Reline is completing in pwn-mesh', line: 'optional - full line buffer so /channel P<TAB> can list named channels' ) # Install Reline dropdown for pwn-mesh slash commands #{self}.install_pwn_mesh_completer!( pry: 'optional - Pry instance stored for mesh TAB completion' ) # Run a leading-slash pwn-mesh command locally instead of sending it as mesh text #{self}.pwn_mesh_dispatch_slash!( request: 'optional - full line such as /channel list or /transport serial', pry: 'optional - Pry instance used by /back to leave pwn-mesh' ) # Write plugins.meshtastic from the live Env into the encrypted pwn.yaml vault #{self}.persist_mesh_env( mesh: 'optional - meshtastic Hash to persist (defaults to PWN::Env plugins.meshtastic)' ) # IRB-style suggest-as-you-type for the pwn REPL #{self}.enable_autocomplete( enabled: 'optional - Boolean (default true). false reverts to single-line cycling.', graph: 'optional - constants (PWN::Plugins::Nm<TAB>), instance methods' ) # Consume a prepared CLI session or create a new interactive session. #{self}.pwn_ai_activation_session(pry: 'required - Pry instance') # Validate/select a named model profile without changing provider defaults. #{self}.pwn_ai_profile_command( pry: 'required - Pry instance', args: ['profile-name'], env: 'optional - configuration hash', output: 'optional - output IO' ) # View/edit the current session pinned engagement notes. #{self}.pwn_ai_memory_command( pry: 'required - Pry instance', args: ['edit', 'evidence notes'], root: 'optional - artifacts root', output: 'optional - output IO' ) # Run start and return its result #{self}.start(ai_session_id: 'optional - prepared CLI session id') # Print the AUTHOR(S) string for this module. #{self}.authors " constants.sort end |
.install_pwn_ai_completer!(opts = {}) ⇒ Object
Install Reline dropdown for pwn-ai (commands / paths / Ruby).
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/pwn/plugins/repl/ai.rb', line 391 def install_pwn_ai_completer!(opts = {}) return unless defined?(Reline) Thread.current[:pwn_ai_completer_pry] = opts[:pry] @pwn_ai_prev_completion_proc = Reline.completion_proc if Reline.respond_to?(:completer_word_break_characters) @pwn_ai_prev_word_break = Reline.completer_word_break_characters # Keep '/' inside the token so /cron and /opt/pwn complete as paths/cmds. Reline.completer_word_break_characters = Reline.completer_word_break_characters.to_s.delete('/') end Reline.autocompletion = true Reline.completion_proc = proc do |target| line = Reline.respond_to?(:line_buffer) ? Reline.line_buffer.to_s : target.to_s pwn_ai_complete( target: target, line: line, pry: Thread.current[:pwn_ai_completer_pry] ) end Reline.completion_proc end |
.install_pwn_mesh_completer!(opts = {}) ⇒ Object
Install Reline dropdown for pwn-mesh slash commands.
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1564 def install_pwn_mesh_completer!(opts = {}) return unless defined?(Reline) Thread.current[:pwn_ai_completer_pry] = opts[:pry] @pwn_ai_prev_completion_proc = Reline.completion_proc if Reline.respond_to?(:completer_word_break_characters) @pwn_ai_prev_word_break = Reline.completer_word_break_characters Reline.completer_word_break_characters = Reline.completer_word_break_characters.to_s.delete('/') end # Curses owns the TTY; Reline's completion dialog would paint off-screen. Reline.autocompletion = false Reline.completion_proc = proc do |target| line = Reline.respond_to?(:line_buffer) ? Reline.line_buffer.to_s : target.to_s pwn_mesh_complete(target: target, line: line) end Reline.completion_proc end |
.leave_special_mode!(opts = {}) ⇒ Object
Leave pwn-ai / pwn-asm / pwn-mesh and restore the host REPL (also CTRL+D).
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 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 918 919 920 921 922 923 924 925 926 927 928 |
# File 'lib/pwn/plugins/repl.rb', line 863 public_class_method def self.leave_special_mode!(opts = {}) pi = opts[:pry] return nil unless pi.respond_to?(:config) pi.config.color = true pi.config.pwn_asm = false if pi.config.pwn_asm pi.config.pwn_ai = false if pi.config.pwn_ai pi.config.pwn_ai_agent = false if pi.config.pwn_ai_agent pi.config.pwn_ai_speak = false if pi.config.pwn_ai_speak pi.config.completer = Pry::InputCompleter restore_pwn_ai_completer! if pi.config.pwn_ai_original_input pi.config.input = pi.config.pwn_ai_original_input pi.config.pwn_ai_original_input = nil end return pi unless pi.config.pwn_mesh pi.config.pwn_mesh = false if PWN.const_defined?(:MeshTxEchoThread) PWN.const_get(:MeshTxEchoThread).kill PWN.send(:remove_const, :MeshTxEchoThread) end if PWN.const_defined?(:MeshObj) PWN::Plugins::REPL.send( :mesh_disconnect, env: (defined?(PWN::Env) && PWN::Env.dig(:plugins, :meshtastic)) || {}, obj: PWN.const_get(:MeshObj) ) PWN.send(:remove_const, :MeshObj) end PWN.send(:remove_const, :MqttObj) if PWN.const_defined?(:MqttObj) if PWN.const_defined?(:MeshSubThread) thr = PWN.const_get(:MeshSubThread) thr.kill if thr.respond_to?(:alive?) && thr.alive? PWN.send(:remove_const, :MeshSubThread) end PWN.send(:remove_const, :MeshTransport) if PWN.const_defined?(:MeshTransport) PWN.send(:remove_const, :MeshTxPrompt) if PWN.const_defined?(:MeshTxPrompt) PWN.send(:remove_const, :MeshTxEpoch) if PWN.const_defined?(:MeshTxEpoch) PWN.send(:remove_const, :MeshTxBlank) if PWN.const_defined?(:MeshTxBlank) PWN.send(:remove_const, :MeshLastSubmit) if PWN.const_defined?(:MeshLastSubmit) PWN.send(:remove_const, :MeshRxState) if PWN.const_defined?(:MeshRxState) if PWN.const_defined?(:MeshRxHeaderWin) PWN.const_get(:MeshRxHeaderWin).close PWN.send(:remove_const, :MeshRxHeaderWin) end if PWN.const_defined?(:MeshRxFrameWin) PWN::MeshRxFrameWin.close PWN.send(:remove_const, :MeshRxFrameWin) end if PWN.const_defined?(:MeshRxBodyWin) PWN.const_get(:MeshRxBodyWin).close PWN.send(:remove_const, :MeshRxBodyWin) end if PWN.const_defined?(:MeshTxWin) PWN.const_get(:MeshTxWin).close PWN.send(:remove_const, :MeshTxWin) end PWN.send(:remove_const, :MeshColors) if PWN.const_defined?(:MeshColors) PWN.send(:remove_const, :MeshLastColor) if PWN.const_defined?(:MeshLastColor) PWN.send(:remove_const, :MeshMutex) if PWN.const_defined?(:MeshMutex) PWN.send(:remove_const, :MqttSubThread) if PWN.const_defined?(:MqttSubThread) PWN.send(:remove_const, :MeshEvents) if PWN.const_defined?(:MeshEvents) Curses.close_screen pi end |
.mesh_active_psks(opts = {}) ⇒ Object
246 247 248 249 250 251 252 253 254 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 246 def mesh_active_psks(opts = {}) env = opts[:env] || mesh_env_hash active = env.dig(:channel, :active).to_s slot = env.dig(:channel, active.to_sym) || {} topic = mesh_mqtt_topic(env: env, topic: slot[:topic]) name = topic.split('/')[-2] name = active if name.to_s.empty? || name == 'e' { name.to_sym => slot[:psk] } end |
.mesh_ai_prompt(opts = {}) ⇒ Object
1255 1256 1257 1258 1259 1260 1261 1262 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1255 def mesh_ai_prompt(opts = {}) return unless opts.is_a?(Hash) text = opts[:text].to_s.strip return unless text.match?(/\A@ai(\s|\z)/i) text.sub(/\A@ai\s*/i, '').strip end |
.mesh_ai_whitelisted?(opts = {}) ⇒ Boolean
1245 1246 1247 1248 1249 1250 1251 1252 1253 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1245 def mesh_ai_whitelisted?(opts = {}) return false unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash name = opts[:channel].to_s return false if name.empty? Array(env[:ai_whitelist]).any? { |entry| entry.to_s.casecmp?(name) } end |
.mesh_bound_transport(opts = {}) ⇒ Object
Live radio kind after connect (MeshTransport) or the pinned / first-probe kind.
162 163 164 165 166 167 168 169 170 171 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 162 def mesh_bound_transport(opts = {}) env = opts[:env] || {} if PWN.const_defined?(:MeshTransport) live = PWN.const_get(:MeshTransport).to_s.downcase.to_sym return live if PWN_MESH_TRANSPORTS.include?(live) end t = mesh_transport(env: env) t == :auto ? PWN_MESH_TRANSPORTS.first : t end |
.mesh_box!(opts = {}) ⇒ Object
Explicit Unicode avoids ACS falling back to ASCII on some terminals.
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 209 def mesh_box!(opts = {}) win = opts[:win] width = win.maxx height = win.maxy win.setpos(0, 0) win.addstr("╭#{'─' * (width - 2)}╮") (1...(height - 1)).each do |row| win.setpos(row, 0) win.addstr('│') win.setpos(row, width - 1) win.addstr('│') end win.setpos(height - 1, 0) win.addstr("╰#{'─' * (width - 2)}╯") win end |
.mesh_broadcast?(opts = {}) ⇒ Boolean
1264 1265 1266 1267 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1264 def mesh_broadcast?(opts = {}) to = opts[:to].to_s.downcase.delete('!') to.empty? || to == 'ffffffff' end |
.mesh_channel_name_for_index(opts = {}) ⇒ Object
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 341 def mesh_channel_name_for_index(opts = {}) return '' unless opts.is_a?(Hash) idx = opts[:index] return '' if idx.nil? idx = Integer(idx) return '' unless (0..7).cover?(idx) env = opts[:env] || mesh_env_hash obj = opts[:obj] obj = PWN.const_get(:MeshObj) if obj.nil? && PWN.const_defined?(:MeshObj) = (obj: obj) name = .dig(idx, :name).to_s.strip return name unless name.empty? ch = env[:channel] || {} ch.each do |key, val| next if key.to_s == 'active' next unless val.is_a?(Hash) next if val[:radio_index].nil? return key.to_s if val[:radio_index].to_i == idx end psk_name = mesh_env_channel_name_for_psk(env: env, psk: .dig(idx, :psk)) return psk_name unless psk_name.empty? mesh_unassigned_slot_map(env: env, obj: obj)[idx].to_s end |
.mesh_channel_name_from_topic(opts = {}) ⇒ Object
460 461 462 463 464 465 466 467 468 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 460 def mesh_channel_name_from_topic(opts = {}) return '' unless opts.is_a?(Hash) topic = opts[:topic].to_s return '' if topic.empty? seg = topic.split('/').each_cons(2).find { |a, b| a == 'e' && b && b != '#' } seg ? seg.last.to_s : '' end |
.mesh_channel_names(opts = {}) ⇒ Object
Named Meshtastic channel keys from plugins.meshtastic.channel (not :active).
792 793 794 795 796 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 792 def mesh_channel_names(opts = {}) env = opts[:env] || mesh_env_hash ch = env[:channel] || {} ch.keys.map(&:to_s).reject { |k| k == 'active' } end |
.mesh_channel_psks(opts = {}) ⇒ Object
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1168 def mesh_channel_psks(opts = {}) return {} unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash ch = env[:channel] || {} psks = {} ch.each do |key, val| next if key.to_s == 'active' next unless val.is_a?(Hash) psk = val[:psk].to_s psks[key.to_s.to_sym] = psk unless psk.empty? end psks end |
.mesh_channel_securely_encrypted?(opts = {}) ⇒ Boolean
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1231 def mesh_channel_securely_encrypted?(opts = {}) return false unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash name = opts[:channel].to_s return false if name.empty? slot = env.dig(:channel, name.to_sym) slot = env[:channel][name] if slot.nil? && env[:channel].is_a?(Hash) return false unless slot.is_a?(Hash) !mesh_public_psk?(psk: slot[:psk]) end |
.mesh_compose_send(opts = {}) ⇒ Object
Send compose text on the active channel, or a @!nodeid DM.
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 762 def mesh_compose_send(opts = {}) env = opts[:env] || mesh_env_hash obj = opts[:obj] tx_text = opts[:text].to_s.dup to = '!ffffffff' if tx_text.include?('@!') to_raw = tx_text.split('@').last.chomp[0..8] to = to_raw if to_raw[1..].match?(/^[a-fA-F0-9]{8}$/) tx_text.gsub!("@#{to_raw}", '').strip! end channel_name = (env[:channel] || {})[:active].to_s raise ArgumentError, 'use /msg <channel|!nodeid> <text> or /channel <name>' if to == '!ffffffff' && channel_name.empty? slot = (env[:channel] || {})[channel_name.to_sym] || {} mesh_send_text( env: env, obj: obj, from: mesh_self_node_id(env: env, obj: obj), to: to, region: slot[:region], topic: slot[:topic], channel: slot[:channel_num] || channel_name, channel_name: channel_name, radio: mesh_radio_index_for_name(env: env, obj: obj, name: channel_name), text: tx_text, psks: mesh_channel_psks(env: env) ) end |
.mesh_connect(opts = {}) ⇒ Object
Open a Meshtastic session. auto probes serial → bluetooth → tcp → mqtt.
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 535 def mesh_connect(opts = {}) env = opts[:env] || {} selected = mesh_transport(env: env) kinds = selected == :auto ? PWN_MESH_TRANSPORTS : [selected] errors = [] kinds.each do |kind| obj = mesh_connect_one(env: env, transport: kind) PWN.send(:remove_const, :MeshTransport) if PWN.const_defined?(:MeshTransport) PWN.const_set(:MeshTransport, kind) return obj rescue StandardError => e errors << "#{kind}: #{e.class}: #{e.}" raise unless selected == :auto end raise IOError, "pwn-mesh: no transport connected (#{errors.join('; ')})" if errors.any? raise IOError, 'pwn-mesh: no Meshtastic transport connected' end |
.mesh_connect_one(opts = {}) ⇒ Object
Open one Meshtastic backend (serial, bluetooth, tcp, or mqtt).
487 488 489 490 491 492 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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 487 def mesh_connect_one(opts = {}) env = opts[:env] || {} case opts[:transport] when :serial serial = env[:serial] || {} obj = Meshtastic::Serial.connect( block_dev: serial[:port], baud: serial[:baud], data_bits: serial[:bits], stop_bits: serial[:stop], parity: serial[:parity] ) Meshtastic::Serial.wait_for_config(serial_obj: obj, timeout: 10) obj when :bluetooth obj = Meshtastic::Bluetooth.connect(address: (env[:bluetooth] || {})[:address]) Meshtastic::Bluetooth.wait_for_config(bluetooth_obj: obj, timeout: 30) obj when :tcp tcp = env[:tcp] || {} obj = Meshtastic::TCP.connect(host: tcp[:host], port: tcp[:port]) Meshtastic::TCP.wait_for_config(tcp_obj: obj, timeout: 10) obj else mqtt = env[:mqtt] || {} kwargs = { host: mqtt[:host], port: mqtt[:port], tls: mesh_mqtt_tls?(tls: mqtt[:tls]), username: mqtt[:user], password: mqtt[:pass] } kwargs[:client_id] = mqtt[:client_id] unless mqtt[:client_id].to_s.empty? kwargs[:keep_alive] = mqtt[:keep_alive] unless mqtt[:keep_alive].nil? kwargs[:ack_timeout] = mqtt[:ack_timeout] unless mqtt[:ack_timeout].nil? Meshtastic::MQTT.connect(kwargs) end end |
.mesh_console_loop(opts = {}) ⇒ Object
Workers enqueue RX; curses alone owns terminal input and drawing.
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 823 def mesh_console_loop(opts = {}) pi = opts[:pry] reader = opts[:getch] unless reader PWN::MeshTxWin.keypad(true) PWN::MeshTxWin.timeout = 100 reader = proc { PWN::MeshTxWin.getch } end text = +'' cursor = 0 while pi.config.pwn_mesh mesh_drain_events mesh_draw_input(text: text, cursor: cursor) key = reader.call case key when "\u0004", 4 break if text.empty? when "\n", "\r", 10, 13, Curses::KEY_ENTER submitted = text.dup text.clear cursor = 0 mesh_draw_input(text: text, cursor: cursor) mesh_submit(request: submitted, pry: pi) when "\u007f", "\b", 127, 8, Curses::KEY_BACKSPACE if cursor.positive? cursor -= 1 text.slice!(cursor) end when Curses::KEY_DC text.slice!(cursor) when Curses::KEY_LEFT cursor = [cursor - 1, 0].max when Curses::KEY_RIGHT cursor = [cursor + 1, text.length].min when Curses::KEY_HOME, "\u0001" cursor = 0 when Curses::KEY_END, "\u0005" cursor = text.length when "\u0015" text.clear cursor = 0 when "\t", 9 hits = (line: text) choice = (title: 'Commands', items: hits) unless hits.empty? if choice text = text.include?(' ') ? "#{text.split.first} #{choice}" : choice.dup cursor = text.length end else if key.is_a?(String) && key.ord >= 32 text.insert(cursor, key) cursor += key.length end end end rescue Interrupt nil end |
.mesh_decorate_local_id(opts = {}) ⇒ Object
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1212 def mesh_decorate_local_id(opts = {}) return '' unless opts.is_a?(Hash) id = opts[:id].to_s return id if id.empty? self_id = mesh_self_node_id(env: opts[:env], obj: opts[:obj]) return "#{id} (ME)" if id.downcase == self_id.downcase id end |
.mesh_device_channel_meta(opts = {}) ⇒ Object
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 256 def (opts = {}) obj = opts[:obj] return {} unless obj.is_a?(Hash) rows = if obj[:rx_mutex] obj[:rx_mutex].synchronize { Array(obj[:proto_data]).dup } else Array(obj[:proto_data]) end by_index = {} rows.each do |row| ch = row.is_a?(Hash) ? (row[:channel] || row['channel']) : nil ch = row if ch.nil? && row.is_a?(Hash) && (row[:settings] || row['settings']) ch = ch.to_h if !ch.is_a?(Hash) && ch.respond_to?(:to_h) next unless ch.is_a?(Hash) role = (ch[:role] || ch['role']).to_s.downcase next if %w[disabled 0].include?(role) idx = (ch[:index] || ch['index'] || 0).to_i next unless (0..7).cover?(idx) settings = ch[:settings] || ch['settings'] || {} settings = settings.to_h if !settings.is_a?(Hash) && settings.respond_to?(:to_h) settings = {} unless settings.is_a?(Hash) by_index[idx] = { name: (settings[:name] || settings['name']).to_s.strip, psk: (settings[:psk] || settings['psk']).to_s } end by_index end |
.mesh_device_channels(opts = {}) ⇒ Object
289 290 291 292 293 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 289 def mesh_device_channels(opts = {}) return {} unless opts.is_a?(Hash) (obj: opts[:obj]).transform_values { |row| row[:name].to_s } end |
.mesh_disconnect(opts = {}) ⇒ Object
Close the Meshtastic session opened by #mesh_connect.
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 744 def mesh_disconnect(opts = {}) env = opts[:env] || {} obj = opts[:obj] return if obj.nil? case mesh_bound_transport(env: env) when :serial Meshtastic::Serial.disconnect(serial_obj: obj) when :bluetooth Meshtastic::Bluetooth.disconnect(bluetooth_obj: obj) when :tcp Meshtastic::TCP.disconnect(tcp_obj: obj) else Meshtastic::MQTT.disconnect(mqtt_obj: obj) end end |
.mesh_drain_events ⇒ Object
882 883 884 885 886 887 888 889 890 891 892 893 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 882 def mesh_drain_events return unless PWN.const_defined?(:MeshEvents) loop do event = PWN::MeshEvents.pop(true) next if event[:obj] && (!PWN.const_defined?(:MeshObj) || !event[:obj].equal?(PWN::MeshObj)) event[:msg] ? mesh_handle_rx(msg: event[:msg]) : mesh_ui_puts(text: event[:text]) end rescue ThreadError nil end |
.mesh_draw_input(opts = {}) ⇒ Object
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 895 def mesh_draw_input(opts = {}) win = PWN::MeshTxWin text = opts[:text].to_s cursor = opts[:cursor].to_i width = [win.maxx - 6, 1].max offset = [cursor - width + 1, 0].max win.erase mesh_box!(win: win) win.attron(Curses.color_pair(20) | Curses::A_BOLD) do win.setpos(0, 2) win.addstr(' COMPOSE ') win.setpos(1, 2) win.addstr('› ') end win.setpos(1, 4) win.addstr(text[offset, width].to_s) win.setpos(1, 4 + cursor - offset) win.attron(Curses::A_REVERSE) { win.addstr(text[cursor] || ' ') } hits = (line: text) unless hits.empty? win.setpos(2, 2) win.attron(Curses.color_pair(20)) do win.addstr(hits.join(' ')[0, win.maxx - 4].to_s) end end win.setpos(3, 2) win.addstr('Enter send Tab complete /menu settings Ctrl+D back'[0, win.maxx - 4]) win.refresh end |
.mesh_env_channel_name_for_psk(opts = {}) ⇒ Object
427 428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 427 def mesh_env_channel_name_for_psk(opts = {}) return '' unless opts.is_a?(Hash) psk = opts[:psk].to_s return '' if psk.empty? env = opts[:env] || mesh_env_hash ch = env[:channel] || {} found = ch.find do |key, val| key.to_s != 'active' && val.is_a?(Hash) && mesh_psk_same?(left: psk, right: val[:psk]) end found ? found.first.to_s : '' end |
.mesh_env_hash(opts = {}) ⇒ Object
798 799 800 801 802 803 804 805 806 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 798 def mesh_env_hash(opts = {}) return {} unless opts.is_a?(Hash) env = opts[:env] return env if env.is_a?(Hash) return {} unless defined?(PWN::Env) && PWN::Env.is_a?(Hash) PWN::Env.dig(:plugins, :meshtastic) || {} end |
.mesh_handle_rx(opts = {}) ⇒ Object
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1276 def mesh_handle_rx(opts = {}) return unless opts.is_a?(Hash) msg = opts[:msg] return unless msg.is_a?(Hash) packet = msg[:packet].is_a?(Hash) ? msg[:packet] : msg decoded = packet[:decoded] return unless decoded.is_a?(Hash) && mesh_text_app?(portnum: decoded[:portnum]) env = mesh_env_hash idx = packet[:channel] || packet['channel'] idx = nil unless idx.nil? || idx.is_a?(Integer) || (idx.is_a?(String) && idx.match?(/\A[0-7]\z/)) idx = 0 if idx.nil? && %i[serial bluetooth tcp].include?(mesh_bound_transport(env: env)) idx = idx.to_i unless idx.nil? channel_name = opts[:channel_name].to_s channel_name = mesh_channel_name_for_index(index: idx, env: env) if channel_name.empty? if channel_name.empty? topic = msg[:topic] || packet[:topic] channel_name = mesh_channel_name_from_topic(topic: topic) end channel_name = mesh_whitelist_name_for_index(env: env, index: idx) if channel_name.empty? && !idx.nil? rx_text = mesh_rx_text(payload: decoded[:payload]).to_s return if rx_text.strip.empty? from_id = packet[:node_id_from].to_s from_id = "!#{packet[:from].to_i.to_s(16)}" if from_id.empty? && packet[:from] to = packet[:node_id_to].to_s to = "!#{packet[:to].to_i.to_s(16)}" if to.empty? && packet[:to] unless opts[:local] last = PWN.const_defined?(:MeshLastTx) ? PWN.const_get(:MeshLastTx) : nil if last.is_a?(Hash) && from_id.downcase == last[:from].to_s.downcase && rx_text == last[:text].to_s && last[:at].is_a?(Time) && (Time.now - last[:at]) < 10 return end end from_id = mesh_self_node_id(env: env) if opts[:local] && from_id.empty? dest = to dest = mesh_self_node_id(env: env) if dest.empty? && !opts[:local] dest_label = mesh_reply_target_label(to: dest, env: env, channel_name: channel_name) from = mesh_decorate_local_id(id: from_id, env: env) dest_label = mesh_decorate_local_id(id: dest_label, env: env) unless opts[:local] || mesh_broadcast?(to: to) || from_id.empty? PWN.send(:remove_const, :MeshLastDm) if PWN.const_defined?(:MeshLastDm) PWN.const_set(:MeshLastDm, from_id) end unless opts[:local] || channel_name.empty? PWN.send(:remove_const, :MeshLastChannel) if PWN.const_defined?(:MeshLastChannel) PWN.const_set(:MeshLastChannel, channel_name) end if PWN.const_defined?(:MeshMutex) && PWN.const_defined?(:MeshRxBodyWin) mutex = PWN.const_get(:MeshMutex) state = PWN.const_defined?(:MeshRxState) ? PWN.const_get(:MeshRxState) : {} ts = Time.now.strftime('%H:%M:%S') color = opts[:local] ? 23 : 21 current_line = "#{ts} #{from.strip} #{dest_label}\n#{rx_text}" unless state[:last_line] == current_line rx_body_win = PWN.const_get(:MeshRxBodyWin) mutex.synchronize do width = [rx_body_win.maxx - 2, 1].max rx_body_win.attron(Curses.color_pair(color) | Curses::A_BOLD) rx_body_win.addstr(" #{ts} #{from.strip} · #{dest_label}\n") rx_body_win.attroff(Curses.color_pair(color) | Curses::A_BOLD) rx_body_win.attron(Curses.color_pair(24)) mesh_wrap_text(text: rx_text, width: width - 1).each do |line| rx_body_win.addstr(" #{line}\n") end rx_body_win.addstr("\n") rx_body_win.attroff(Curses.color_pair(24)) rx_body_win.refresh end state[:last_line] = current_line state[:last_from] = from PWN.send(:remove_const, :MeshRxState) if PWN.const_defined?(:MeshRxState) PWN.const_set(:MeshRxState, state) end end unless opts[:local] mesh_maybe_dispatch_to_pwn_ai( text: rx_text, from: from_id, to: to, channel_name: channel_name, radio: idx ) end rescue StandardError => e mesh_ui_puts(text: "RX display failed: #{e.class}: #{e.}") end |
.mesh_layout(opts = {}) ⇒ Object
Row counts for header, CONVERSATION, and COMPOSE so the TUI fits the terminal.
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 174 def mesh_layout(opts = {}) lines = opts[:lines] cols = opts[:cols] lines = lines.nil? ? Curses.lines : Integer(lines) cols = cols.nil? ? Curses.cols : Integer(cols) lines = 1 if lines < 1 cols = 1 if cols < 1 header = 5 tx = 5 min_header = 3 min_tx = 3 min_body = 3 body = lines - header - tx while body < min_body && header > min_header header -= 1 body = lines - header - tx end while body < min_body && tx > min_tx tx -= 1 body = lines - header - tx end body = [body, 1].max overflow = header + body + tx - lines body -= overflow if overflow.positive? && body > 1 body = 1 if body < 1 { header: header, body: body, tx: tx, cols: cols, tx_top: header + body } end |
.mesh_link_label(opts = {}) ⇒ Object
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 470 def mesh_link_label(opts = {}) env = opts[:env] || {} case mesh_bound_transport(env: env) when :serial (env[:serial] || {})[:port].to_s when :bluetooth (env[:bluetooth] || {})[:address].to_s when :tcp tcp = env[:tcp] || {} "#{tcp[:host]}:#{tcp[:port]}" else mqtt = env[:mqtt] || {} "#{mqtt[:host]}:#{mqtt[:port]}" end end |
.mesh_list_devices(opts = {}) ⇒ Object
Discover radios for the active transport (serial globs, BLE scan, tcp/mqtt config).
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1108 def mesh_list_devices(opts = {}) env = opts[:env] || mesh_env_hash case mesh_bound_transport(env: env) when :serial Dir.glob( %w[/dev/ttyUSB* /dev/ttyACM* /dev/cu.usbserial* /dev/cu.usbmodem* /dev/serial/by-id/*] ).uniq.sort when :bluetooth begin require 'meshtastic' unless defined?(Meshtastic) && Meshtastic.const_defined?(:Bluetooth) Array(Meshtastic::Bluetooth.scan(timeout: opts[:timeout] || 3)).map do |row| if row.is_a?(Hash) addr = row[:address] || row['address'] name = row[:name] || row['name'] paired = row[:paired] || row['paired'] [addr, name, paired ? 'paired' : nil].compact.join(' ') else row.to_s end end rescue StandardError => e ["(bluetooth scan failed: #{e.class}: #{e.})"] end when :tcp tcp = env[:tcp] || {} ["#{tcp[:host]}:#{tcp[:port]}"] else mqtt = env[:mqtt] || {} ["#{mqtt[:host]}:#{mqtt[:port]}"] end end |
.mesh_maybe_dispatch_to_pwn_ai(opts = {}) ⇒ Object
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1371 def mesh_maybe_dispatch_to_pwn_ai(opts = {}) return :skipped unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash return :skipped unless env[:dispatch_to_pwn_ai] == true channel_name = opts[:channel_name].to_s if channel_name.empty? && !opts[:radio].nil? channel_name = mesh_channel_name_for_index(index: opts[:radio], env: env) channel_name = mesh_whitelist_name_for_index(env: env, index: opts[:radio]) if channel_name.empty? end return :skipped unless mesh_channel_securely_encrypted?(env: env, channel: channel_name) return :skipped unless mesh_ai_whitelisted?(env: env, channel: channel_name) text = mesh_ai_prompt(text: opts[:text]) from = opts[:from].to_s return :skipped if text.to_s.empty? || from.empty? return :skipped if from.downcase == mesh_self_node_id(env: env).downcase return :skipped if PWN.const_defined?(:MeshDispatchLock) PWN.const_set(:MeshDispatchLock, true) ch = env[:channel] || {} slot = ch[channel_name.to_sym] || ch[channel_name] || {} obj = PWN.const_defined?(:MeshObj) ? PWN.const_get(:MeshObj) : nil dest = mesh_broadcast?(to: opts[:to]) ? '!ffffffff' : from radio = opts[:radio] radio = mesh_radio_index_for_name(env: env, obj: obj, name: channel_name) if radio.nil? raw = defined?(PWN::Env) && PWN::Env.is_a?(Hash) ? PWN::Env.dig(:ai, :active).to_s : '' engine = raw.empty? ? nil : raw.downcase.to_sym Thread.new do Thread.current[:pwn_swarm_engine] = nil reply = PWN::AI::Agent::Loop.run(request: text, nested: true, engine: engine) mesh_send_text( env: env, obj: obj, from: mesh_self_node_id(env: env, obj: obj), to: dest, text: reply.to_s, channel_name: channel_name, radio: radio, region: slot[:region], topic: slot[:topic], channel: slot[:channel_num] || channel_name, psks: mesh_channel_psks(env: env) ) rescue StandardError => e mesh_ui_puts(text: "TX failed: #{e.class}: #{e.}") ensure PWN.send(:remove_const, :MeshDispatchLock) if PWN.const_defined?(:MeshDispatchLock) end :dispatched end |
.mesh_menu_pick(opts = {}) ⇒ Object
Curses (or injected getch) picker for pwn-mesh lists. Esc/q cancels.
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 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 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 997 def (opts = {}) items = Array(opts[:items]).map(&:to_s) title = opts[:title].to_s return nil if items.empty? current = opts[:current].to_s idx = items.index(current) || 0 reader = opts[:getch] live = reader.nil? && PWN.const_defined?(:MeshTxWin) unless live || reader marked = items.map { |item| item == current ? " * #{item}" : " #{item}" } mesh_ui_puts(text: ([title.empty? ? 'pwn-mesh' : title] + marked).join("\n")) return nil end win = nil if live PWN.send(:remove_const, :MeshMenuLock) if PWN.const_defined?(:MeshMenuLock) PWN.const_set(:MeshMenuLock, true) max_h = [Curses.lines - 2, 6].max h = (items.length + 6).clamp(6, max_h) max_w = [Curses.cols - 2, 24].max label_w = [items.map(&:length).max.to_i + 8, title.length + 8, 44].max w = [label_w, max_w].min top = [(Curses.lines - h) / 2, 0].max left = [(Curses.cols - w) / 2, 0].max win = Curses::Window.new(h, w, top, left) win.keypad(true) end up = defined?(Curses::KEY_UP) ? Curses::KEY_UP : 259 down = defined?(Curses::KEY_DOWN) ? Curses::KEY_DOWN : 258 loop do if win mutex = PWN.const_defined?(:MeshMutex) ? PWN.const_get(:MeshMutex) : Mutex.new mutex.synchronize do win.clear mesh_box!(win: win) inner = [win.maxx - 2, 1].max win.attron(Curses.color_pair(20) | Curses::A_BOLD) win.setpos(1, 2) win.addstr(title.upcase[0, inner - 2]) win.attroff(Curses.color_pair(20) | Curses::A_BOLD) visible = [win.maxy - 5, 1].max first = [idx - visible + 1, 0].max items.each_with_index.drop(first).first(visible).each do |item, i| row = i - first + 3 win.setpos(row, 1) mark = i == idx ? '▸' : ' ' line = "#{mark} #{item}" if i == idx win.attron(Curses.color_pair(22) | Curses::A_BOLD) win.addstr(line[0, inner].to_s.ljust(inner)) win.attroff(Curses.color_pair(22) | Curses::A_BOLD) else win.addstr(line[0, inner].to_s.ljust(inner)) end end win.setpos(win.maxy - 2, 2) win.addstr('↑↓ select Enter apply Esc close'[0, inner - 2]) win.refresh end end ch = reader ? reader.call : win.getch return nil if ch.nil? case ch when up, 'k', 'K' idx = (idx - 1) % items.length when down, 'j', 'J' idx = (idx + 1) % items.length when 10, 13, "\n", "\r" return items[idx] when 27, "\e", 'q', 'Q' return nil else enter = defined?(Curses::KEY_ENTER) ? Curses::KEY_ENTER : -1 return items[idx] if ch == enter end end ensure win&.close PWN.send(:remove_const, :MeshMenuLock) if PWN.const_defined?(:MeshMenuLock) if live [PWN::MeshRxHeaderWin, PWN::MeshRxFrameWin, PWN::MeshRxBodyWin, PWN::MeshTxWin].each do |pane| pane.touch pane.refresh end end if PWN.const_defined?(:MeshTxEpoch) epoch = PWN.const_get(:MeshTxEpoch).to_i PWN.send(:remove_const, :MeshTxEpoch) PWN.const_set(:MeshTxEpoch, epoch + 1) end end |
.mesh_menu_root(opts = {}) ⇒ Object
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1095 def (opts = {}) pi = opts[:pry] choice = ( title: 'pwn-mesh', items: %w[channel transport device status toggle-dispatch-to-pwn-ai help back], current: 'channel' ) return nil if choice.nil? pwn_mesh_dispatch_slash!(request: "/#{choice}", pry: pi) end |
.mesh_mqtt_region(opts = {}) ⇒ Object
Region is an opaque broker path and may contain multiple components.
227 228 229 230 231 232 233 234 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 227 def mesh_mqtt_region(opts = {}) raw = opts[:region].to_s if raw.empty? mqtt = (opts[:env] || {})[:mqtt] || {} raw = mqtt[:region].to_s end raw.empty? ? 'US' : raw end |
.mesh_mqtt_tls?(opts = {}) ⇒ Boolean
Treat only explicit true-ish values as MQTT TLS (YAML "false" is a truthy string).
527 528 529 530 531 532 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 527 def mesh_mqtt_tls?(opts = {}) tls = opts[:tls] return false if tls.nil? || tls == false %w[true yes 1].include?(tls.to_s.strip.downcase) end |
.mesh_mqtt_topic(opts = {}) ⇒ Object
Human-readable link for the pwn-mesh RX header.
237 238 239 240 241 242 243 244 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 237 def mesh_mqtt_topic(opts = {}) env = opts[:env] || mesh_env_hash active = env.dig(:channel, :active).to_s topic = opts[:topic].to_s topic = "2/e/#{active}/#" if topic.empty? && !active.empty? topic = topic.sub(%r{/e/#\z}, "/e/#{active}/#") unless active.empty? topic end |
.mesh_payload_fits?(opts = {}) ⇒ Boolean
591 592 593 594 595 596 597 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 591 def mesh_payload_fits?(opts = {}) return false unless opts.is_a?(Hash) text = opts[:text].to_s max = opts[:max] || mesh_text_payload_max text.length <= max && text.bytesize <= max end |
.mesh_psk_b64(opts = {}) ⇒ Object
411 412 413 414 415 416 417 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 411 def mesh_psk_b64(opts = {}) raw = opts[:psk].to_s return '' if raw.empty? return raw if raw.match?(%r{\A[A-Za-z0-9+/]+=*\z}) && (raw.length % 4).zero? Base64.strict_encode64(raw) end |
.mesh_psk_same?(opts = {}) ⇒ Boolean
419 420 421 422 423 424 425 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 419 def mesh_psk_same?(opts = {}) return false unless opts.is_a?(Hash) left = mesh_psk_b64(psk: opts[:left]) right = mesh_psk_b64(psk: opts[:right]) !left.empty? && left == right end |
.mesh_public_psk?(opts = {}) ⇒ Boolean
1224 1225 1226 1227 1228 1229 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1224 def mesh_public_psk?(opts = {}) return true unless opts.is_a?(Hash) psk = opts[:psk].to_s.strip psk.empty? || %w[none default aq==].include?(psk.downcase) end |
.mesh_radio_channel(opts = {}) ⇒ Object
295 296 297 298 299 300 301 302 303 304 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 295 def mesh_radio_channel(opts = {}) return unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash name = opts[:name].to_s name = env.dig(:channel, :active).to_s if name.empty? return if name.empty? mesh_radio_index_for_name(env: env, obj: opts[:obj], name: name) end |
.mesh_radio_index_for_name(opts = {}) ⇒ Object
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 306 def mesh_radio_index_for_name(opts = {}) return unless opts.is_a?(Hash) name = opts[:name].to_s return if name.empty? env = opts[:env] || mesh_env_hash slot = env.dig(:channel, name.to_sym) || env.dig(:channel, name) || {} index = slot[:radio_index] if slot.is_a?(Hash) obj = opts[:obj] obj = PWN.const_get(:MeshObj) if obj.nil? && PWN.const_defined?(:MeshObj) if index.nil? wanted = name.downcase named = mesh_device_channels(obj: obj).select do |_idx, ch_name| n = ch_name.to_s.downcase n == wanted || (wanted == 'longfast' && n.empty?) end index = named.keys.max end if index.nil? found = mesh_unassigned_slot_map(env: env, obj: obj).find do |_i, ch_name| ch_name.to_s.downcase == wanted end index = found&.first end n = slot[:channel_num] if slot.is_a?(Hash) index = n if index.nil? && n.is_a?(Integer) && (0..7).cover?(n) return if index.nil? index = Integer(index) return unless (0..7).cover?(index) index end |
.mesh_reconnect!(opts = {}) ⇒ Object
Reopen the Meshtastic session after a live /transport /device /channel change.
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1468 def mesh_reconnect!(opts = {}) env = opts[:env] || mesh_env_hash return :skipped unless PWN.const_defined?(:MeshObj) old = PWN.const_get(:MeshObj) old_transport = PWN.const_defined?(:MeshTransport) ? PWN.const_get(:MeshTransport) : mesh_transport(env: env) begin mesh_disconnect(env: { transport: old_transport }, obj: old) rescue StandardError => e mesh_ui_puts(text: "[pwn-mesh] disconnect: #{e.class}: #{e.}") end if PWN.const_defined?(:MeshSubThread) thr = PWN.const_get(:MeshSubThread) thr.kill if thr.respond_to?(:alive?) && thr.alive? PWN.send(:remove_const, :MeshSubThread) end PWN.send(:remove_const, :MeshObj) PWN.send(:remove_const, :MqttObj) if PWN.const_defined?(:MqttObj) obj = mesh_connect(env: env) PWN.const_set(:MeshObj, obj) PWN.const_set(:MqttObj, obj) mesh_start_rx!(env: env, obj: obj) mesh_refresh_ui!(env: env) :reconnected rescue StandardError => e mesh_ui_puts(text: "[pwn-mesh] reconnect failed: #{e.class}: #{e.}") :failed end |
.mesh_refresh_ui!(opts = {}) ⇒ Object
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1424 def mesh_refresh_ui!(opts = {}) env = opts[:env] || mesh_env_hash ch = env[:channel] || {} active = ch[:active].to_s.to_sym slot = ch[active] || {} region = slot[:region] topic = slot[:topic] channel_num = slot[:channel_num] link = mesh_link_label(env: env) PWN.send(:remove_const, :MeshTxPrompt) if PWN.const_defined?(:MeshTxPrompt) PWN.const_set(:MeshTxPrompt, 'pwn.mesh › ') epoch = PWN.const_defined?(:MeshTxEpoch) ? PWN.const_get(:MeshTxEpoch).to_i : 0 PWN.send(:remove_const, :MeshTxEpoch) if PWN.const_defined?(:MeshTxEpoch) PWN.const_set(:MeshTxEpoch, epoch + 1) return env unless PWN.const_defined?(:MeshRxHeaderWin) win = PWN.const_get(:MeshRxHeaderWin) mutex = PWN.const_defined?(:MeshMutex) ? PWN.const_get(:MeshMutex) : Mutex.new active = ch[:active].to_s transport = mesh_bound_transport(env: env).to_s.upcase dispatch = env[:dispatch_to_pwn_ai] == true ? 'AI REPLIES ON' : 'AI REPLIES OFF' rx_header = " PWN / MESH #{transport} · #{active} " mutex.synchronize do win.clear mesh_box!(win: win) inner = [win.maxx - 2, 1].max win.attron(Curses.color_pair(20) | Curses::A_BOLD) win.setpos(1, 1) win.addstr(rx_header.to_s[0, inner].ljust(inner)) win.attroff(Curses.color_pair(20) | Curses::A_BOLD) if win.maxy >= 5 win.setpos(2, 2) win.addstr("#{link} / #{region}/#{topic}"[0, inner - 2]) win.setpos(3, 2) win.attron(Curses.color_pair(23)) do win.addstr("CHANNEL #{active} · #{dispatch} · /status"[0, inner - 2]) end end win.refresh end env end |
.mesh_reply_target_label(opts = {}) ⇒ Object
1269 1270 1271 1272 1273 1274 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1269 def mesh_reply_target_label(opts = {}) to = opts[:to].to_s return to unless mesh_broadcast?(to: to) opts[:channel_name].to_s end |
.mesh_reset_input!(opts = {}) ⇒ Object
Drop the submitted TX buffer so the next prompt is empty (Reline keeps the old line).
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 967 def mesh_reset_input!(opts = {}) return opts if PWN.const_defined?(:MeshEvents) pry = opts[:pry] input = pry.respond_to?(:input) ? pry.input : nil submitted = opts[:submitted].to_s submitted = Reline.line_buffer.to_s if submitted.empty? && defined?(Reline) && Reline.respond_to?(:line_buffer) submitted = input.line_buffer.to_s if submitted.empty? && input.respond_to?(:line_buffer) PWN.send(:remove_const, :MeshLastSubmit) if PWN.const_defined?(:MeshLastSubmit) PWN.const_set(:MeshLastSubmit, submitted) PWN.send(:remove_const, :MeshTxBlank) if PWN.const_defined?(:MeshTxBlank) PWN.const_set(:MeshTxBlank, true) if defined?(Reline) begin Reline.delete_text if Reline.respond_to?(:delete_text) Reline.point = 0 if Reline.respond_to?(:point=) rescue StandardError nil end end input.instance_variable_set(:@line_buffer, '') if input.respond_to?(:instance_variable_defined?) && input.instance_variable_defined?(:@line_buffer) if PWN.const_defined?(:MeshTxEpoch) epoch = PWN.const_get(:MeshTxEpoch).to_i PWN.send(:remove_const, :MeshTxEpoch) PWN.const_set(:MeshTxEpoch, epoch + 1) end opts end |
.mesh_rx_text(opts = {}) ⇒ Object
1192 1193 1194 1195 1196 1197 1198 1199 1200 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1192 def mesh_rx_text(opts = {}) return '' unless opts.is_a?(Hash) payload = opts[:payload] return payload.dup.force_encoding(Encoding::UTF_8).scrub if payload.is_a?(String) return payload[:text].to_s if payload.is_a?(Hash) && payload[:text] '' end |
.mesh_self_node_id(opts = {}) ⇒ Object
1202 1203 1204 1205 1206 1207 1208 1209 1210 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1202 def mesh_self_node_id(opts = {}) return '!00000b0b' unless opts.is_a?(Hash) obj = opts[:obj] obj = PWN.const_get(:MeshObj) if obj.nil? && PWN.const_defined?(:MeshObj) return "!#{obj[:my_node_num].to_i.to_s(16)}" if obj.is_a?(Hash) && !obj[:my_node_num].nil? '!00000b0b' end |
.mesh_send_text(opts = {}) ⇒ Object
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 677 def mesh_send_text(opts = {}) env = opts[:env] || {} obj = opts[:obj] from = opts[:from] channel = opts[:channel] psks = opts[:psks] dest = opts[:to].to_s dest = '!ffffffff' if dest.empty? kind = mesh_bound_transport(env: env) channel_name = opts[:channel_name].to_s radio = opts[:radio] radio = mesh_radio_index_for_name(env: env, obj: obj, name: channel_name) if radio.nil? && !channel_name.empty? radio = mesh_radio_channel(env: env, obj: obj) if radio.nil? && %i[serial bluetooth tcp].include?(kind) chunks = mesh_text_chunks(text: opts[:text]) chunks.each_with_index do |piece, idx| since = obj.is_a?(Hash) ? Array(obj[:proto_data]).size : 0 case kind when :serial tx = { serial_obj: obj, to: dest, text: piece, want_ack: true } tx[:channel] = radio unless radio.nil? Meshtastic::Serial.send_text(tx) when :bluetooth tx = { bluetooth_obj: obj, to: dest, text: piece, want_ack: true } tx[:channel] = radio unless radio.nil? Meshtastic::Bluetooth.send_text(tx) when :tcp tx = { tcp_obj: obj, to: dest, text: piece } tx[:channel] = radio unless radio.nil? Meshtastic::TCP.send_text(tx) else send_psks = psks send_psks = mesh_channel_psks(env: env) if send_psks.nil? || send_psks.empty? Meshtastic::MQTT.send_text( mqtt_obj: obj, from: from, to: dest, region: mesh_mqtt_region(region: opts[:region], env: env), topic: mesh_mqtt_topic(env: env, topic: opts[:topic]), channel: channel, text: piece, psks: send_psks ) end from_id = from.to_s from_id = mesh_self_node_id(env: env, obj: obj) if from_id.empty? PWN.send(:remove_const, :MeshLastTx) if PWN.const_defined?(:MeshLastTx) PWN.const_set(:MeshLastTx, { from: from_id, to: dest, text: piece.to_s, at: Time.now }) mesh_handle_rx( local: true, channel_name: channel_name, msg: { packet: { channel: radio, node_id_from: from_id, node_id_to: dest, decoded: { portnum: :TEXT_MESSAGE_APP, payload: piece.to_s } } } ) next unless idx + 1 < chunks.size next unless %i[serial bluetooth tcp].include?(kind) mesh_wait_tx_slot(obj: obj, since: since) end end |
.mesh_start_rx!(opts = {}) ⇒ Object
Subscribe thread for TEXT_MESSAGE_APP frames (also used after /channel|/transport|/device).
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1141 def mesh_start_rx!(opts = {}) env = opts[:env] || mesh_env_hash obj = opts[:obj] ch = env[:channel] || {} active = ch[:active].to_s.to_sym slot = ch[active] || {} psks = mesh_channel_psks(env: env) psks = mesh_active_psks(env: env) if psks.empty? PWN.const_set(:MeshRxState, { last_from: nil, last_line: nil }) unless PWN.const_defined?(:MeshRxState) events = PWN.const_defined?(:MeshEvents) ? PWN::MeshEvents : Queue.new thread = Thread.new do mesh_subscribe( env: env, obj: obj, region: slot[:region], topic: slot[:topic], psks: psks, on_message: proc { |msg| events << { msg: msg, obj: obj } } ) events << { text: 'RX stopped: transport stream closed. Use /transport to reconnect.', obj: obj } rescue StandardError => e events << { text: "RX failed: #{e.class}: #{e.}", obj: obj } end PWN.send(:remove_const, :MeshSubThread) if PWN.const_defined?(:MeshSubThread) PWN.const_set(:MeshSubThread, thread) end |
.mesh_submit(opts = {}) ⇒ Object
808 809 810 811 812 813 814 815 816 817 818 819 820 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 808 def mesh_submit(opts = {}) request = opts[:request].to_s.dup return if request.empty? request = '/back' if request == 'back' if request.start_with?('/') && !PWN_MESH_SLASH_COMMANDS.include?(request.split.first) && request != '/' mesh_ui_puts(text: 'Unknown command. Use /help or /menu.') return end Pry.config.hooks.get_hook(:after_read, :pwn_mesh_hook).call(request, opts[:pry]) rescue StandardError => e mesh_ui_puts(text: "Command failed: #{e.class}: #{e.}") end |
.mesh_subscribe(opts = {}) ⇒ Object
Subscribe for inbound TEXT_MESSAGE_APP frames.
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 555 def mesh_subscribe(opts = {}) env = opts[:env] || {} obj = opts[:obj] psks = opts[:psks] blk = opts[:on_message] case mesh_bound_transport(env: env) when :serial Meshtastic::Serial.subscribe(serial_obj: obj, psks: psks, &blk) when :bluetooth Meshtastic::Bluetooth.subscribe(bluetooth_obj: obj, psks: psks, &blk) when :tcp Meshtastic::TCP.subscribe(tcp_obj: obj, psks: psks, &blk) else Meshtastic::MQTT.subscribe( mqtt_obj: obj, region: mesh_mqtt_region(region: opts[:region], env: env), topic: mesh_mqtt_topic(env: env, topic: opts[:topic]), psks: psks, &blk ) end end |
.mesh_text_app?(opts = {}) ⇒ Boolean
1184 1185 1186 1187 1188 1189 1190 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1184 def mesh_text_app?(opts = {}) return false unless opts.is_a?(Hash) port = opts[:portnum] s = port.to_s %w[TEXT_MESSAGE_APP 1].include?(s) end |
.mesh_text_chunks(opts = {}) ⇒ Object
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 644 def mesh_text_chunks(opts = {}) return [] unless opts.is_a?(Hash) text = opts[:text].to_s max = mesh_text_payload_max return [text] if mesh_payload_fits?(text: text, max: max) n = 2 loop do prefix = "(#{n}/#{n}) " body_max = max - prefix.length raise ArgumentError, "DATA_PAYLOAD_LEN #{max} cannot hold a chunk prefix" if body_max < 1 bodies = [] offset = 0 while offset < text.length take = body_max piece = text[offset, take].to_s while !mesh_payload_fits?(text: "#{prefix}#{piece}", max: max) && take > 1 take -= 1 piece = text[offset, take].to_s end bodies << piece offset += piece.length end if bodies.size <= n total = bodies.size return bodies.each_with_index.map { |body, i| "(#{i + 1}/#{total}) #{body}" } end n = bodies.size end end |
.mesh_text_payload_max(opts = {}) ⇒ Object
Send a text frame on the active mesh transport.
579 580 581 582 583 584 585 586 587 588 589 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 579 def mesh_text_payload_max(opts = {}) return 0 unless opts.is_a?(Hash) cap = opts[:max] || Meshtastic::Constants::DATA_PAYLOAD_LEN # DATA_PAYLOAD_LEN is the protobuf Data.payload max. A MeshPacket # around a full-size payload is ~260 bytes and will not fit a 256-byte # LoRa frame, so the radio accepts ToRadio then silently drops TX. lora = 256 overhead = 32 [cap, lora - overhead].min end |
.mesh_transport(opts = {}) ⇒ Object
rubocop:disable Metrics/ClassLength
152 153 154 155 156 157 158 159 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 152 def mesh_transport(opts = {}) env = opts[:env] || {} name = (env[:transport] || env['transport'] || :auto).to_s.downcase.to_sym return :auto if name.empty? || name == :auto return name if PWN_MESH_TRANSPORTS.include?(name) :auto end |
.mesh_tx_row_ready?(opts = {}) ⇒ Boolean
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 599 def mesh_tx_row_ready?(opts = {}) return false unless opts.is_a?(Hash) row = opts[:row] return false unless row.is_a?(Hash) packet = row[:packet] || row['packet'] return false unless packet.is_a?(Hash) decoded = packet[:decoded] || packet['decoded'] return false unless decoded.is_a?(Hash) port = decoded[:portnum] || decoded['portnum'] %w[5 ROUTING_APP].include?(port.to_s) || port == :ROUTING_APP end |
.mesh_ui_puts(opts = {}) ⇒ Object
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 944 def mesh_ui_puts(opts = {}) text = opts[:text].to_s if PWN.const_defined?(:MeshRxBodyWin) && PWN.const_defined?(:MeshMutex) win = PWN.const_get(:MeshRxBodyWin) mutex = PWN.const_get(:MeshMutex) mutex.synchronize do width = [win.maxx - 1, 1].max win.attron(Curses.color_pair(20) | Curses::A_BOLD) win.addstr(" SYSTEM\n") win.attroff(Curses.color_pair(20) | Curses::A_BOLD) mesh_wrap_text(text: text, width: width - 2).each do |line| win.addstr(" #{line}\n") end win.addstr("\n") win.refresh end else puts text end text end |
.mesh_unassigned_slot_map(opts = {}) ⇒ Object
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 370 def mesh_unassigned_slot_map(opts = {}) return {} unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash obj = opts[:obj] obj = PWN.const_get(:MeshObj) if obj.nil? && PWN.const_defined?(:MeshObj) = (obj: obj) claimed_idx = [] claimed_names = [] .each do |i, info| n = info[:name].to_s.strip next if n.empty? claimed_idx << i claimed_names << n.downcase end ch = env[:channel] || {} ch.each do |key, val| next if key.to_s == 'active' next unless val.is_a?(Hash) next if val[:radio_index].nil? claimed_idx << val[:radio_index].to_i claimed_names << key.to_s.downcase end .each do |i, info| n = mesh_env_channel_name_for_psk(env: env, psk: info[:psk]) next if n.empty? claimed_idx << i claimed_names << n.downcase end unnamed = ([0] + .keys).uniq.sort - claimed_idx.uniq names = mesh_channel_names(env: env) encrypted, rest = names.partition do |n| mesh_channel_securely_encrypted?(env: env, channel: n) end unclaimed = (encrypted + rest).reject { |n| claimed_names.include?(n.downcase) } unnamed.zip(unclaimed).to_h.compact end |
.mesh_wait_tx_slot(opts = {}) ⇒ Object
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 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 615 def mesh_wait_tx_slot(opts = {}) return unless opts.is_a?(Hash) obj = opts[:obj] return unless obj.is_a?(Hash) timeout = opts[:timeout] timeout = 8 if timeout.nil? timeout = Float(timeout) return if timeout <= 0 since = opts[:since].to_i deadline = Time.now + timeout loop do rows = if obj[:rx_mutex] obj[:rx_mutex].synchronize { Array(obj[:proto_data]).dup } else Array(obj[:proto_data]) end ready = rows.drop(since).any? do |row| mesh_tx_row_ready?(row: row) end return if ready return if Time.now >= deadline sleep 0.05 end end |
.mesh_whitelist_name_for_index(opts = {}) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 441 def mesh_whitelist_name_for_index(opts = {}) return '' unless opts.is_a?(Hash) idx = opts[:index] return '' if idx.nil? idx = Integer(idx) return '' unless (0..7).cover?(idx) env = opts[:env] || mesh_env_hash found = Array(env[:ai_whitelist]).find do |entry| n = entry.to_s next if n.empty? mesh_radio_index_for_name(env: env, obj: opts[:obj], name: n) == idx end found.to_s end |
.mesh_wrap_text(opts = {}) ⇒ Object
Print slash-menu text into the RX pane when curses is up, else STDOUT.
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 926 def mesh_wrap_text(opts = {}) width = [opts[:width].to_i, 1].max opts[:text].to_s.split("\n", -1).flat_map do |line| rows = [+''] cells = 0 line.each_char do |char| size = Unicode::DisplayWidth.of(char) if cells + size > width && !rows.last.empty? rows << +'' cells = 0 end rows.last << char cells += size end rows end end |
.persist_ai_selection(opts = {}) ⇒ Object
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
# File 'lib/pwn/plugins/repl/ai.rb', line 669 def persist_ai_selection(opts = {}) engine = opts[:engine].to_s model = opts[:model] return false if engine.empty? env_path = nil dec_path = nil if defined?(PWN::Env) && PWN::Env.is_a?(Hash) env_path = PWN::Env.dig(:driver_opts, :pwn_env_path) dec_path = PWN::Env.dig(:driver_opts, :pwn_dec_path) end env_path = env_path.to_s.strip env_path = File.join(Dir.home, '.pwn', 'pwn.yaml') if env_path.empty? dec_path = dec_path.to_s.strip dec_path = "#{env_path}.decryptor" if dec_path.empty? return false unless File.exist?(env_path) && File.exist?(dec_path) && File.readable?(dec_path) decryptor = YAML.load_file(dec_path, symbolize_names: true) key = decryptor.is_a?(Hash) ? decryptor[:key] : nil iv = decryptor.is_a?(Hash) ? decryptor[:iv] : nil return false if key.to_s.strip.empty? || iv.to_s.strip.empty? PWN::Plugins::Vault.decrypt(file: env_path, key: key, iv: iv) begin cfg = YAML.load_file(env_path, symbolize_names: true) cfg = {} unless cfg.is_a?(Hash) cfg[:ai] = {} unless cfg[:ai].is_a?(Hash) cfg[:ai][:active] = engine unless model.to_s.strip.empty? slot = engine.to_sym cfg[:ai][slot] = {} unless cfg[:ai][slot].is_a?(Hash) cfg[:ai][slot][:model] = model end yaml_env = YAML.dump(cfg).gsub(/^(\s*):/, '\1') File.write(env_path, yaml_env) File.chmod(0o600, env_path) ensure PWN::Plugins::Vault.encrypt(file: env_path, key: key, iv: iv) end true rescue StandardError => e warn "[pwn-ai] /model persist skipped: #{e.class}: #{e.}" false end |
.persist_mesh_env(opts = {}) ⇒ Object
Write plugins.meshtastic from the live Env into ~/.pwn/pwn.yaml (vault).
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1797 def persist_mesh_env(opts = {}) mesh = opts[:mesh] mesh = mesh_env_hash if mesh.nil? return false unless mesh.is_a?(Hash) env_path = nil dec_path = nil if defined?(PWN::Env) && PWN::Env.is_a?(Hash) env_path = PWN::Env.dig(:driver_opts, :pwn_env_path) dec_path = PWN::Env.dig(:driver_opts, :pwn_dec_path) end env_path = env_path.to_s.strip env_path = File.join(Dir.home, '.pwn', 'pwn.yaml') if env_path.empty? dec_path = dec_path.to_s.strip dec_path = "#{env_path}.decryptor" if dec_path.empty? return false unless File.exist?(env_path) && File.exist?(dec_path) && File.readable?(dec_path) decryptor = YAML.load_file(dec_path, symbolize_names: true) key = decryptor.is_a?(Hash) ? decryptor[:key] : nil iv = decryptor.is_a?(Hash) ? decryptor[:iv] : nil return false if key.to_s.strip.empty? || iv.to_s.strip.empty? PWN::Plugins::Vault.decrypt(file: env_path, key: key, iv: iv) begin cfg = YAML.load_file(env_path, symbolize_names: true) cfg = {} unless cfg.is_a?(Hash) cfg[:plugins] = {} unless cfg[:plugins].is_a?(Hash) dst = cfg[:plugins][:meshtastic] dst = {} unless dst.is_a?(Hash) mesh.each do |key, val| k = key.respond_to?(:to_sym) ? key.to_sym : key if dst[k].is_a?(Hash) && val.is_a?(Hash) nested = dst[k].dup val.each do |nk, nv| nested[nk.respond_to?(:to_sym) ? nk.to_sym : nk] = nv end dst[k] = nested else dst[k] = val end end cfg[:plugins][:meshtastic] = dst yaml_env = YAML.dump(cfg).gsub(/^(\s*):/, '\1') File.write(env_path, yaml_env) File.chmod(0o600, env_path) ensure PWN::Plugins::Vault.encrypt(file: env_path, key: key, iv: iv) end true rescue StandardError => e warn "[pwn-mesh] persist skipped: #{e.class}: #{e.}" false end |
.pwn_ai_activation_session(opts = {}) ⇒ Object
423 424 425 426 427 428 429 430 |
# File 'lib/pwn/plugins/repl/ai.rb', line 423 def pwn_ai_activation_session(opts = {}) config = opts[:pry].config sid = config.pwn_ai_startup_session_id config.pwn_ai_startup_session_id = nil return { id: sid } if sid PWN::Sessions.create(title: "pwn-ai #{Time.now.strftime('%Y-%m-%d %H:%M')}", source: 'pwn-ai') end |
.pwn_ai_complete(opts = {}) ⇒ Object
- Supported Method Parameters
hits = PWN::Plugins::REPL.pwn_ai_complete( target: 'required - token Reline is completing', line: 'optional - full line buffer', pry: 'optional - Pry instance for Ruby completion' )
276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/pwn/plugins/repl/ai.rb', line 276 def pwn_ai_complete(opts = {}) target = opts[:target].to_s line = opts[:line].to_s line = target if line.empty? kind = pwn_ai_complete_kind(line: line) case kind when :command pwn_ai_complete_command(target: target, line: line) when :path pwn_ai_complete_path(target: target, line: line) else pwn_ai_complete_ruby(target: target, pry: opts[:pry]) end end |
.pwn_ai_complete_command(opts = {}) ⇒ Object
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 322 323 324 325 326 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 |
# File 'lib/pwn/plugins/repl/ai.rb', line 291 def pwn_ai_complete_command(opts = {}) line = opts[:line].to_s target = opts[:target].to_s tokens = line.split(/\s+/, -1) tokens = [''] if tokens.empty? if tokens.length <= 1 prefix = tokens.first.to_s prefix = '/' if prefix.empty? return PWN_AI_SLASH_COMMANDS.select { |c| c.start_with?(prefix) } end cmd = tokens.first sub_prefix = tokens.last.to_s if cmd == '/model' engines = pwn_ai_engines if tokens.length == 2 pool = (%w[list] + engines) return pool.select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } end return %w[llms].select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } if tokens.length == 3 && tokens[1] == 'list' if tokens.length >= 3 current = pwn_ai_engine_model(engine: tokens[1]).to_s hits = [current].reject(&:empty?).select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } return hits unless hits.empty? end end if cmd == '/mcp' backends = begin PWN::AI::MCP.backends.map { |row| row[:name].to_s } rescue StandardError [] end if tokens.length == 2 pool = (Array(PWN_AI_SLASH_SUBCOMMANDS['/mcp']) + backends).uniq return pool.select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } end return %w[tools].select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } if tokens.length == 3 && tokens[1] == 'list' named = backends.include?(tokens[1]) action = named ? tokens[2] : tokens[1] return Array(PWN_AI_SLASH_SUBCOMMANDS['/mcp']).select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } if named && tokens.length == 3 return backends.select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } if tokens.length >= 3 && %w[use connect disconnect ping tools status].include?(tokens[1]) if action == 'call' && ((named && tokens.length == 4) || (!named && tokens.length == 3)) selected = named ? tokens[1] : PWN::AI::MCP.current.to_s tools = if selected.empty? backends.flat_map do |name| row = PWN::AI::MCP.backends.find { |backend| backend[:name] == name } Array(row && row[:tools]) end else row = PWN::AI::MCP.backends.find { |backend| backend[:name] == selected } Array(row && row[:tools]) end return tools.uniq.map(&:to_s).select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } end end subs = Array(PWN_AI_SLASH_SUBCOMMANDS[cmd]) hits = subs.select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } hits = [target] if hits.empty? && !target.empty? hits end |
.pwn_ai_complete_kind(opts = {}) ⇒ Object
rubocop:disable Metrics/ClassLength
262 263 264 265 266 267 268 |
# File 'lib/pwn/plugins/repl/ai.rb', line 262 def pwn_ai_complete_kind(opts = {}) line = opts[:line].to_s return :command if line.start_with?('/') return :path if line.include?('/') || line.include?('~') :ruby end |
.pwn_ai_complete_path(opts = {}) ⇒ Object
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'lib/pwn/plugins/repl/ai.rb', line 355 def pwn_ai_complete_path(opts = {}) target = opts[:target].to_s line = opts[:line].to_s token = line.split(/\s+/, -1).last.to_s token = target if token.empty? return [] if token.empty? home = Dir.home glob_src = token.sub(%r{\A~(?=/|\z)}, home) pattern = token.end_with?('/') ? File.join(glob_src, '*') : "#{glob_src}*" Dir.glob(pattern).filter_map do |path| shown = if token.start_with?('~/') || token == '~' path.sub(/\A#{Regexp.escape(home)}/, '~') else path end shown = "#{shown}/" if File.directory?(path) shown end rescue StandardError [] end |
.pwn_ai_complete_ruby(opts = {}) ⇒ Object
378 379 380 381 382 383 384 385 386 387 388 |
# File 'lib/pwn/plugins/repl/ai.rb', line 378 def pwn_ai_complete_ruby(opts = {}) target = opts[:target].to_s pry = opts[:pry] || Thread.current[:pwn_ai_completer_pry] return [] unless defined?(Pry::InputCompleter) return Array(pry.complete(target)) if pry.respond_to?(:complete) Array(Pry::InputCompleter.new(pry || Pry.new(quiet: true)).call(target)) rescue StandardError [] end |
.pwn_ai_dispatch_slash!(opts = {}) ⇒ Object
Run a leading-slash pwn-ai command locally. Returns true when handled (caller should not send the line to Loop.run).
481 482 483 484 485 486 487 488 489 490 491 492 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 |
# File 'lib/pwn/plugins/repl/ai.rb', line 481 def pwn_ai_dispatch_slash!(opts = {}) request = opts[:request].to_s if request.strip.match?(/\Aai\.profile(?:\s|$)/) pwn_ai_profile_command(pry: opts[:pry], args: request.strip.split(/\s+/).drop(1)) return true end if request.strip.match?(/\Aai\.memory(?:\s|$)/) pwn_ai_memory_command(pry: opts[:pry], args: request.strip.split(/\s+/).drop(1)) return true end return false unless pwn_ai_complete_kind(line: request) == :command tokens = request.strip.split(/\s+/) cmd = tokens[0].to_s return false unless PWN_AI_SLASH_COMMANDS.include?(cmd) args = tokens[1..] pi = opts[:pry] case cmd when '/help' puts 'pwn-ai commands:' PWN_AI_SLASH_COMMANDS.each do |c| subs = Array(PWN_AI_SLASH_SUBCOMMANDS[c]) puts(subs.empty? ? " #{c}" : " #{c} #{subs.join('|')}") end puts ' TAB: /… command menu · slash later in the line: path nav · else Ruby completion' when '/back' if pi.respond_to?(:eval) pi.eval('back') else puts "[*] Type 'back' to leave pwn-ai." end when '/debug' if pi.respond_to?(:eval) pi.eval('toggle-debug') else puts '[*] toggle-debug' end when '/trace' if pi.respond_to?(:eval) pi.eval('toggle-trace') else puts '[*] toggle-trace' end when '/cron' pwn_ai_run_cron(args: args) when '/sessions' pwn_ai_run_sessions(args: args) when '/memory' pwn_ai_run_memory(args: args) when '/skills' pwn_ai_run_skills(args: args) when '/delegate' puts "[*] Delegating: #{args.join(' ')}" puts ' Use agent_list / agent_debate from pwn-ai, or pwn-ai-delegate in the pwn REPL.' when '/model' pwn_ai_run_model(args: args) when '/mcp' pwn_ai_run_mcp(args: args) when '/learning' pwn_ai_run_learning(args: args) end true rescue StandardError => e warn "[pwn-ai] #{cmd}: #{e.class}: #{e.}" true end |
.pwn_ai_engine_model(opts = {}) ⇒ Object
612 613 614 615 616 617 618 |
# File 'lib/pwn/plugins/repl/ai.rb', line 612 def pwn_ai_engine_model(opts = {}) engine = opts[:engine].to_s.downcase.to_sym return '' if engine.empty? return '' unless defined?(PWN::Env) && PWN::Env.is_a?(Hash) PWN::Env.dig(:ai, engine, :model).to_s end |
.pwn_ai_engines(opts = {}) ⇒ Object
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
# File 'lib/pwn/plugins/repl/ai.rb', line 549 def pwn_ai_engines(opts = {}) return [] unless opts.is_a?(Hash) tmpl = {} tmpl = PWN::Config.env_template[:ai] if defined?(PWN::Config) && PWN::Config.respond_to?(:env_template) keys = tmpl.select { |_k, v| v.is_a?(Hash) && v.key?(:model) }.keys.map(&:to_s) if defined?(PWN::Env) && PWN::Env.is_a?(Hash) && PWN::Env[:ai].is_a?(Hash) PWN::Env[:ai].each do |k, v| next unless v.is_a?(Hash) next if %i[agent driver_opts].include?(k.to_sym) keys << k.to_s if v.key?(:model) || v.key?(:key) || v.key?(:base_uri) end end keys.uniq.sort end |
.pwn_ai_list_llms(opts = {}) ⇒ Object
598 599 600 601 602 603 604 605 606 607 608 609 610 |
# File 'lib/pwn/plugins/repl/ai.rb', line 598 def pwn_ai_list_llms(opts = {}) engine = opts[:engine].to_s engine = PWN::Env.dig(:ai, :active).to_s if engine.empty? && defined?(PWN::Env) raise 'no active engine — /model <engine> first' if engine.empty? klass = pwn_ai_provider_class(engine: engine) raise "#{engine} has no PWN::AI provider with get_models" unless klass.respond_to?(:get_models) ids = pwn_ai_model_ids(models: klass.get_models) puts "[*] #{engine} llms (#{ids.length})" ids.each { |id| puts id } ids end |
.pwn_ai_mcp_call_args(opts = {}) ⇒ Object
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 |
# File 'lib/pwn/plugins/repl/ai.rb', line 877 def pwn_ai_mcp_call_args(opts = {}) tokens = Array(opts[:tokens]).map(&:to_s) joined = tokens.join(' ').strip if joined.start_with?('{') parsed = JSON.parse(joined) raise ArgumentError, 'JSON call args must be an object' unless parsed.is_a?(Hash) return { arguments: parsed } end arguments = {} tokens.each do |tok| next unless tok.include?('=') key, value = tok.split('=', 2) arguments[key] = pwn_ai_mcp_coerce(value: value) end arguments.empty? ? {} : { arguments: arguments } end |
.pwn_ai_mcp_coerce(opts = {}) ⇒ Object
897 898 899 900 901 902 903 904 905 |
# File 'lib/pwn/plugins/repl/ai.rb', line 897 def pwn_ai_mcp_coerce(opts = {}) value = opts[:value].to_s return value if value.match?(/\A\d+\.\d+\z/) return true if value == 'true' return false if value == 'false' return Integer(value) if value.match?(/\A-?\d+\z/) value end |
.pwn_ai_memory_command(opts = {}) ⇒ Object
View/edit the session's pinned block, separate from cross-session facts.
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/pwn/plugins/repl/ai.rb', line 453 def pwn_ai_memory_command(opts = {}) require 'pwn/ai/agent/engagement_memory' sid = opts[:pry]&.config&.pwn_ai_session_id.to_s raise ArgumentError, 'Start pwn-ai before using ai.memory' if sid.empty? goal = PWN::Sessions.load(session_id: sid).find { |entry| entry[:role].to_s == 'user' } settings = { original_goal: goal ? goal[:content] : '', session_id: sid } settings[:root] = opts[:root] if opts[:root] memory = PWN::AI::Agent::EngagementMemory.new(**settings) args = Array(opts[:args]) case args.first when nil, 'view' text = memory.view when 'edit' raise ArgumentError, 'Usage: ai.memory edit TEXT (or ai.memory clear)' if args.length < 2 text = memory.edit(text: args.drop(1).join(' ')) when 'clear' text = memory.edit(text: '') else raise ArgumentError, 'Usage: ai.memory [view|edit TEXT|clear]' end (opts[:output] || $stdout).puts(text) text end |
.pwn_ai_model_ids(opts = {}) ⇒ Object
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
# File 'lib/pwn/plugins/repl/ai.rb', line 582 def pwn_ai_model_ids(opts = {}) raw = opts[:models] rows = case raw when Array then raw when Hash then raw[:data] || raw[:models] || raw['data'] || raw['models'] || [] else [] end Array(rows).filter_map do |row| if row.is_a?(Hash) row[:id] || row['id'] || row[:slug] || row['slug'] || row[:name] || row['name'] || row[:model] || row['model'] else row.to_s end end.map(&:to_s).reject(&:empty?).uniq end |
.pwn_ai_profile_command(opts = {}) ⇒ Object
Validate selection before changing request-local routing state.
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
# File 'lib/pwn/plugins/repl/ai.rb', line 433 def pwn_ai_profile_command(opts = {}) require 'pwn/ai/agent/profiles' env = opts[:env] || PWN::Env profiles = env[:ai_profiles] || {} router = PWN::AI::Agent::Profiles.new(profiles: profiles) args = Array(opts[:args]) output = opts[:output] || $stdout if args.empty? output.puts("AI profiles: #{profiles.keys.map(&:to_s).sort.join(', ')}") return profiles.keys.map(&:to_s).sort end raise ArgumentError, 'Usage: ai.profile NAME' unless args.length == 1 route = router.lookup(name: args.first) opts.fetch(:pry).config.pwn_ai_profile = args.first.to_s output.puts("AI profile: #{route[:name]} (#{route[:provider]} / #{route[:model]})") route end |
.pwn_ai_provider_class(opts = {}) ⇒ Object
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
# File 'lib/pwn/plugins/repl/ai.rb', line 566 def pwn_ai_provider_class(opts = {}) engine = opts[:engine].to_s.downcase map = { 'anthropic' => 'Anthropic', 'gemini' => 'Gemini', 'grok' => 'Grok', 'ollama' => 'Ollama', 'openai' => 'OpenAI', 'openwebui' => 'OpenWebUI' } name = map[engine] return nil if name.nil? || !defined?(PWN::AI) || !PWN::AI.const_defined?(name) PWN::AI.const_get(name) end |
.pwn_ai_run_cron(opts = {}) ⇒ Object
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 |
# File 'lib/pwn/plugins/repl/ai.rb', line 714 def pwn_ai_run_cron(opts = {}) args = Array(opts[:args]) sub = args[0] || 'list' case sub when 'list' puts PWN::Cron.list.inspect when 'create' job = PWN::Cron.create(schedule: args[1], prompt: args[2..].join(' ')) puts "Created #{job}" when 'run' puts PWN::Cron.run(id: args[1]) when 'remove' PWN::Cron.remove(id: args[1]) puts 'Removed' else puts PWN::Cron.help end end |
.pwn_ai_run_learning(opts = {}) ⇒ Object
773 774 775 776 777 778 779 780 781 782 783 784 785 786 |
# File 'lib/pwn/plugins/repl/ai.rb', line 773 def pwn_ai_run_learning(opts = {}) args = Array(opts[:args]) sub = args[0] || 'list' case sub when 'list' flag = args.include?('--conflicted') || args.include?('conflicted') rows = flag ? PWN::AI::Agent::Learning.list_conflicted : PWN::AI::Agent::Learning.outcomes(limit: 20) puts rows.inspect when 'requeue' puts PWN::AI::Agent::Learning.requeue_conflicted.inspect else puts 'Usage: /learning [list [--conflicted]|requeue]' end end |
.pwn_ai_run_mcp(opts = {}) ⇒ Object
Run pwn-ai /mcp locally without sending the line through Loop.run.
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 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 |
# File 'lib/pwn/plugins/repl/ai.rb', line 810 def pwn_ai_run_mcp(opts = {}) args = Array(opts[:args]).map(&:to_s) backends = begin PWN::AI::MCP.backends.map { |row| row[:name].to_s } rescue StandardError [] end backend = nil if backends.include?(args[0].to_s) backend = args[0] args = args[1..] end sub = args[0].to_s rest = args[1..] sub = 'use' if backend && sub.empty? if sub.empty? || sub == 'help' puts 'pwn-ai /mcp — local MCP session broker for every PWN::AI::MCP::* client' puts ' usage: /mcp [list|backends|use|current|connect|disconnect|ping|tools|call|status|help]' puts ' /mcp <backend> [connect|disconnect|ping|tools|call|status]' puts ' /mcp use <backend>' puts ' /mcp call <tool> [key=value|{"k":"v"}]' result = PWN::AI::MCP.invoke(action: 'backends') current = PWN::AI::MCP.current Array(result[:backends]).each do |row| mark = row[:name] == current ? '*' : ' ' puts " #{mark} #{row[:name]} #{row[:constant]}" end return result.merge(current: current) end hardware = rest.intersect?(%w[hardware --hardware --mcp-allow-hardware]) rest = rest.reject { |tok| %w[hardware --hardware --mcp-allow-hardware].include?(tok) } payload = case sub when 'list' rest[0].to_s == 'tools' ? { action: 'list_tools', backend: rest[1] || backend } : { action: 'backends' } when 'backends' { action: 'backends' } when 'use' { action: 'use', backend: rest[0] || backend } when 'current' { action: 'current' } when 'connect' { action: 'connect', backend: rest[0] || backend, allow_hardware: hardware } when 'disconnect', 'close' { action: 'disconnect', backend: rest[0] || backend } when 'ping' { action: 'ping', backend: rest[0] || backend } when 'tools' { action: 'list_tools', backend: rest[0] || backend } when 'status' { action: 'status', backend: rest[0] || backend } when 'call' name = rest[0].to_s raise ArgumentError, 'usage: /mcp call <tool> [key=value]' if name.empty? { action: 'call_tool', backend: backend, name: name }.merge(pwn_ai_mcp_call_args(tokens: rest[1..])) else raise ArgumentError, "unknown /mcp #{sub.inspect}" end payload[:backend] = payload[:backend].to_s payload.delete(:backend) if payload[:backend].empty? result = PWN::AI::MCP.invoke(payload) puts result.inspect result end |
.pwn_ai_run_memory(opts = {}) ⇒ Object
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
# File 'lib/pwn/plugins/repl/ai.rb', line 753 def pwn_ai_run_memory(opts = {}) args = Array(opts[:args]) sub = args[0] || 'list' case sub when 'list', 'recall' puts PWN::Memory.recall(query: args[1]).inspect when 'remember' PWN::Memory.remember(key: args[1], value: args[2..].join(' ')) puts "Remembered #{args[1]}" when 'forget' PWN::Memory.forget(key: args[1]) puts "Forgot #{args[1]}" when 'clear' PWN::Memory.clear(force: true) puts 'Memory cleared' else puts PWN::Memory.help end end |
.pwn_ai_run_model(opts = {}) ⇒ Object
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 664 665 666 667 |
# File 'lib/pwn/plugins/repl/ai.rb', line 620 def pwn_ai_run_model(opts = {}) args = Array(opts[:args]).map(&:to_s) engines = pwn_ai_engines current = defined?(PWN::Env) && PWN::Env.is_a?(Hash) ? PWN::Env.dig(:ai, :active).to_s : '' current_model = pwn_ai_engine_model(engine: current) sub = args[0].to_s if sub.empty? || %w[show status].include?(sub) msg = "active=#{current.empty? ? '(none)' : current} model=#{current_model.empty? ? '(unset)' : current_model}" puts "[*] #{msg}" return msg end if %w[list help].include?(sub) return pwn_ai_list_llms(engine: current) if args[1].to_s == 'llms' puts 'pwn-ai /model — switch provider and model in this session' puts " current: #{current} #{current_model}" puts ' usage: /model [list] | /model list llms | /model <engine> [model] | /model <model>' engines.each do |eng| mark = eng == current ? '*' : ' ' puts " #{mark} #{eng} #{pwn_ai_engine_model(engine: eng)}" end return engines end engine = nil model = nil if engines.include?(sub) engine = sub model = args[1..].join(' ') model = nil if model.strip.empty? else engine = current model = args.join(' ') end raise "no active engine — /model <engine> first (#{engines.join(', ')})" if engine.to_s.empty? raise "unknown engine #{engine.inspect} — try: #{engines.join(', ')}" unless engines.include?(engine.to_s) PWN::Env[:ai] ||= {} PWN::Env[:ai][engine.to_sym] ||= {} PWN::Env[:ai][:active] = engine.to_s PWN::Env[:ai][engine.to_sym][:model] = model unless model.to_s.strip.empty? persisted = persist_ai_selection(engine: engine, model: PWN::Env[:ai][engine.to_sym][:model]) shown = PWN::Env[:ai][engine.to_sym][:model] msg = "active=#{engine} model=#{shown.to_s.empty? ? '(unset)' : shown}" msg = "#{msg} (session only)" unless persisted puts "[*] #{msg}" msg end |
.pwn_ai_run_sessions(opts = {}) ⇒ Object
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 |
# File 'lib/pwn/plugins/repl/ai.rb', line 733 def pwn_ai_run_sessions(opts = {}) args = Array(opts[:args]) sub = args[0] || 'list' case sub when 'list' puts PWN::Sessions.list.inspect when 'resume' sid = args[1] hist = PWN::Sessions.to_response_history(session_id: sid) puts "Loaded session #{sid} with #{hist[:choices].size} entries" when 'delete' PWN::Sessions.delete(session_id: args[1], force: true) puts "Deleted #{args[1]}" when 'stats' puts PWN::Sessions.stats else puts PWN::Sessions.help end end |
.pwn_ai_run_skills(opts = {}) ⇒ Object
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
# File 'lib/pwn/plugins/repl/ai.rb', line 788 def pwn_ai_run_skills(opts = {}) args = Array(opts[:args]) sub = args[0] || 'list' names = if PWN.const_defined?(:Skills) PWN::Skills.keys.map(&:to_s) else [] end case sub when 'list' puts names.sort when 'recall' q = args[1].to_s hits = names.select { |n| n.include?(q) } puts(hits.empty? ? names.sort : hits.sort) else puts 'Usage: /skills [list|recall <query>]' end end |
.pwn_mesh_complete(opts = {}) ⇒ Object
TAB hits for pwn-mesh slash menus (commands, channel names, transports, devices).
1522 1523 1524 1525 1526 1527 1528 1529 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1522 def pwn_mesh_complete(opts = {}) target = opts[:target].to_s line = opts[:line].to_s line = target if line.empty? return [] unless line.start_with?('/') pwn_mesh_complete_command(target: target, line: line) end |
.pwn_mesh_complete_command(opts = {}) ⇒ Object
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1531 def pwn_mesh_complete_command(opts = {}) line = opts[:line].to_s target = opts[:target].to_s tokens = line.split(/\s+/, -1) tokens = [''] if tokens.empty? if tokens.length <= 1 prefix = tokens.first.to_s prefix = '/' if prefix.empty? return PWN_MESH_SLASH_COMMANDS.select { |c| c.start_with?(prefix) } end cmd = tokens.first sub_prefix = tokens.last.to_s env = mesh_env_hash pool = case cmd when '/channel' (%w[list] + mesh_channel_names(env: env)).uniq when '/msg' mesh_channel_names(env: env) when '/transport' %w[list auto serial bluetooth tcp mqtt] when '/device' (%w[list] + mesh_list_devices(env: env).map { |d| d.to_s.split.first }.compact).uniq else Array(PWN_MESH_SLASH_SUBCOMMANDS[cmd]) end hits = pool.select { |s| sub_prefix.empty? || s.start_with?(sub_prefix) } hits = [target] if hits.empty? && !target.empty? hits end |
.pwn_mesh_dispatch_slash!(opts = {}) ⇒ Object
Run a leading-slash pwn-mesh command locally. Returns true when handled (caller should not TX the line as mesh text).
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1584 def pwn_mesh_dispatch_slash!(opts = {}) request = opts[:request].to_s return false unless request.strip.start_with?('/') tokens = request.strip.split(/\s+/) cmd = tokens[0].to_s pi = opts[:pry] env = mesh_env_hash if ['/', '/menu'].include?(cmd) (pry: pi, env: env) return true end return false unless PWN_MESH_SLASH_COMMANDS.include?(cmd) args = tokens[1..] case cmd when '/help' mesh_ui_puts(text: pwn_mesh_help_text) when '/back' if pi.respond_to?(:config) PWN::Plugins::REPL.leave_special_mode!(pry: pi) else mesh_ui_puts(text: "[*] Type 'back' to leave pwn-mesh.") end when '/status' mesh_ui_puts(text: pwn_mesh_status_text(env: env)) when '/channel' pwn_mesh_run_channel(args: args, env: env) when '/msg' pwn_mesh_run_msg(args: args, env: env) when '/transport' pwn_mesh_run_transport(args: args, env: env) when '/device' pwn_mesh_run_device(args: args, env: env) when '/toggle-dispatch-to-pwn-ai' pwn_mesh_run_toggle_dispatch(env: env) end true rescue StandardError => e mesh_ui_puts(text: "[pwn-mesh] #{cmd}: #{e.class}: #{e.}") true end |
.pwn_mesh_help_text(opts = {}) ⇒ Object
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1627 def pwn_mesh_help_text(opts = {}) lines = [opts[:banner] || 'pwn-mesh commands:'] PWN_MESH_SLASH_COMMANDS.each do |c| subs = Array(PWN_MESH_SLASH_SUBCOMMANDS[c]) extra = '' extra = '|<name>' if c == '/channel' extra = ' [!nodeid|channel] <text>' if c == '/msg' extra = '|<path|address|host:port>' if c == '/device' extra = '|mqtt|serial|bluetooth|tcp' if c == '/transport' && !subs.include?('mqtt') lines << (subs.empty? ? " #{c}#{extra}" : " #{c} #{subs.join('|')}#{extra}") end lines << ' TAB: /… command menu · else send as mesh text' lines.join("\n") end |
.pwn_mesh_menu_rows(opts = {}) ⇒ Object
Curses overlay rows for the pwn-mesh slash menu (Reline's dropdown is hidden by ncurses).
1513 1514 1515 1516 1517 1518 1519 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1513 def (opts = {}) line = opts[:line].to_s return [] unless line.start_with?('/') target = line.split(/\s+/, -1).last.to_s pwn_mesh_complete(target: target, line: line) end |
.pwn_mesh_run_channel(opts = {}) ⇒ Object
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1709 def pwn_mesh_run_channel(opts = {}) args = Array(opts[:args]).map(&:to_s) env = opts[:env] || mesh_env_hash env[:channel] ||= {} names = mesh_channel_names(env: env) sub = args.join(' ').strip if sub.empty? || sub == 'list' active = env[:channel][:active].to_s choice = (title: 'pwn-mesh channel', items: names, current: active) return names if choice.nil? sub = choice end raise "unknown channel #{sub.inspect} — try: #{names.join(', ')}" unless names.include?(sub) env[:channel][:active] = sub persisted = persist_mesh_env(mesh: env) mesh_reconnect!(env: env) msg = "active channel=#{sub}" msg = "#{msg} (session only)" unless persisted mesh_ui_puts(text: "[*] #{msg}") sub end |
.pwn_mesh_run_device(opts = {}) ⇒ Object
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1758 def pwn_mesh_run_device(opts = {}) args = Array(opts[:args]).map(&:to_s) env = opts[:env] || mesh_env_hash sub = args.join(' ').strip if sub.empty? || sub == 'list' devices = mesh_list_devices(env: env).map { |d| d.to_s.split.first }.compact choice = (title: 'pwn-mesh device', items: devices, current: mesh_link_label(env: env)) return devices if choice.nil? sub = choice end case mesh_transport(env: env) when :serial env[:serial] ||= {} env[:serial][:port] = sub when :bluetooth env[:bluetooth] ||= {} env[:bluetooth][:address] = sub.split.first when :tcp host, port = sub.split(':', 2) env[:tcp] ||= {} env[:tcp][:host] = host env[:tcp][:port] = port.to_i.positive? ? port.to_i : 4403 else host, port = sub.split(':', 2) env[:mqtt] ||= {} env[:mqtt][:host] = host env[:mqtt][:port] = port.to_i.positive? ? port.to_i : 1883 end persisted = persist_mesh_env(mesh: env) mesh_reconnect!(env: env) msg = "active device=#{mesh_link_label(env: env)}" msg = "#{msg} (session only)" unless persisted mesh_ui_puts(text: "[*] #{msg}") sub end |
.pwn_mesh_run_msg(opts = {}) ⇒ Object
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1669 def pwn_mesh_run_msg(opts = {}) env = opts[:env] || mesh_env_hash tokens = Array(opts[:args]).map(&:to_s) names = mesh_channel_names(env: env) dest = nil channel_name = '' if tokens[0].to_s.match?(/\A![0-9a-fA-F]{8}\z/) dest = tokens.shift elsif names.any? { |n| n.casecmp?(tokens[0].to_s) } channel_name = names.find { |n| n.casecmp?(tokens[0].to_s) }.to_s tokens.shift dest = '!ffffffff' end dest = PWN.const_get(:MeshLastDm).to_s if dest.nil? && PWN.const_defined?(:MeshLastDm) if dest.nil? && PWN.const_defined?(:MeshLastChannel) channel_name = PWN.const_get(:MeshLastChannel).to_s dest = '!ffffffff' end text = tokens.join(' ').strip raise ArgumentError, 'usage: /msg [!nodeid|channel] <text>' if dest.to_s.empty? || text.empty? channel_name = PWN.const_get(:MeshLastChannel).to_s if channel_name.empty? && PWN.const_defined?(:MeshLastChannel) ch = env[:channel] || {} slot = ch[channel_name.to_sym] || ch[channel_name] || {} obj = PWN.const_defined?(:MeshObj) ? PWN.const_get(:MeshObj) : nil mesh_send_text( env: env, obj: obj, from: mesh_self_node_id(env: env, obj: obj), to: dest, text: text, channel_name: channel_name, radio: mesh_radio_index_for_name(env: env, obj: obj, name: channel_name), region: slot[:region], topic: slot[:topic], channel: slot[:channel_num] || channel_name, psks: mesh_channel_psks(env: env) ) end |
.pwn_mesh_run_toggle_dispatch(opts = {}) ⇒ Object
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1657 def pwn_mesh_run_toggle_dispatch(opts = {}) return false unless opts.is_a?(Hash) env = opts[:env] || mesh_env_hash env[:dispatch_to_pwn_ai] = env[:dispatch_to_pwn_ai] != true persist_mesh_env(mesh: env) state = env[:dispatch_to_pwn_ai] ? 'on' : 'off' mesh_refresh_ui!(env: env) mesh_ui_puts(text: "[*] dispatch-to-pwn-ai=#{state} (encrypted + ai_whitelist + @ai; DMs if whitelisted)") env[:dispatch_to_pwn_ai] end |
.pwn_mesh_run_transport(opts = {}) ⇒ Object
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1734 def pwn_mesh_run_transport(opts = {}) args = Array(opts[:args]).map(&:to_s) env = opts[:env] || mesh_env_hash names = %w[auto serial bluetooth tcp mqtt] sub = args[0].to_s.downcase if sub.empty? || sub == 'list' current = mesh_transport(env: env).to_s choice = (title: 'pwn-mesh transport', items: names, current: current) return names if choice.nil? sub = choice end raise "unknown transport #{sub.inspect} — try: #{names.join(', ')}" unless names.include?(sub) env[:transport] = sub persisted = persist_mesh_env(mesh: env) mesh_reconnect!(env: env) msg = "active transport=#{sub} device=#{mesh_link_label(env: env)}" msg = "#{msg} (session only)" unless persisted mesh_ui_puts(text: "[*] #{msg}") sub end |
.pwn_mesh_status_text(opts = {}) ⇒ Object
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 |
# File 'lib/pwn/plugins/repl/mesh.rb', line 1642 def pwn_mesh_status_text(opts = {}) env = opts[:env] || mesh_env_hash ch = env[:channel] || {} active = ch[:active].to_s slot = ch[active.to_sym] || ch[active] || {} transport = mesh_bound_transport(env: env) pin = mesh_transport(env: env) shown = pin == :auto ? "#{transport} (auto)" : transport.to_s [ "active transport=#{shown} device=#{mesh_link_label(env: env)}", "active channel=#{active.empty? ? '(none)' : active} region=#{slot[:region]} topic=#{slot[:topic]} ch=#{slot[:channel_num]}", "dispatch-to-pwn-ai=#{env[:dispatch_to_pwn_ai] == true ? 'on' : 'off'}" ].join("\n") end |
.ready_tty!(opts = {}) ⇒ Object
Restore the TTY after a spinner / agent turn so Pry/Reline prints the next PS1 immediately. hide_cursor + a background worker leave the cursor hidden on $stdout (Reline's stream) even after TTY::Spinner#stop writes show-cursor to $stderr. Reline then waits for a key without redrawing the prompt.
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
# File 'lib/pwn/plugins/repl.rb', line 300 public_class_method def self.ready_tty!(opts = {}) return nil if opts[:skip] PWN::Plugins::TTYSpinner.halt_all! if defined?(PWN::Plugins::TTYSpinner) out = opts[:io] || $stdout return nil unless out.respond_to?(:write) show = defined?(TTY::Cursor) ? TTY::Cursor.show : "\e[?25h" out.write("\e[0m#{show}") $stderr.write("\e[0m#{show}") if $stderr.respond_to?(:write) && $stderr != out out.flush if out.respond_to?(:flush) reset_reline_editor nil rescue StandardError nil end |
.refresh_ps1_proc(opts = {}) ⇒ Object
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 384 385 386 387 388 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 |
# File 'lib/pwn/plugins/repl.rb', line 347 public_class_method def self.refresh_ps1_proc(opts = {}) mode = opts[:mode] proc do |_target_self, _nest_level, pi| PWN::Config.refresh_env(opts) if Pry.config.refresh_pwn_env pi.config.pwn_repl_line += 1 line_pad = format( '%0.3d', pi.config.pwn_repl_line ) pi.config.prompt_name = :pwn name = "\001\e[1m\002\001\e[31m\002#{pi.config.prompt_name}\001\e[0m\002" version = "\001\e[36m\002v#{PWN::VERSION}\001\e[0m\002" line_count = "\001\e[34m\002#{line_pad}\001\e[0m\002" dchars = "\001\e[32m\002>>>\001\e[0m\002" dchars = "\001\e[33m\002***\001\e[0m\002" if mode == :splat if pi.config.pwn_asm arch = PWN::Env[:plugins][:asm][:arch] ||= PWN::Plugins::DetectOS.arch endian = PWN::Env[:plugins][:asm][:endian] ||= PWN::Plugins::DetectOS.endian pi.config.prompt_name = "pwn.asm:#{arch}/#{endian}" name = "\001\e[1m\002\001\e[37m\002#{pi.config.prompt_name}\001\e[0m\002" dchars = "\001\e[32m\002>>>\001\e[33m\002" dchars = "\001\e[33m\002***\001\e[33m\002" if mode == :splat end if pi.config.pwn_ai engine = PWN::Env[:ai][:active].to_s.downcase.to_sym model = PWN::Env[:ai][engine][:model] system_role_content = PWN::Env[:ai][engine][:system_role_content] temp = PWN::Env[:ai][engine][:temp] # Context-window fill indicator (e.g. "250K/1M") sourced from the last # response's usage.total_tokens vs the engine's max_prompt_length. used_tokens = PWN::Env[:ai][engine].dig(:response_history, :usage, :total_tokens).to_i max_context = PWN::Env[:ai][engine][:max_prompt_length].to_i current_context_length = "#{PWN::Plugins::REPL.compact_context_tokens(tokens: used_tokens)}:" \ "#{PWN::Plugins::REPL.compact_context_tokens(tokens: max_context)}" pname = "pwn.ai:#{engine}" pname = "pwn.ai:#{engine}/#{model}/#{current_context_length}" if model pname = "pwn.ai:#{engine}/#{model}/#{current_context_length}.SPEAK" if pi.config.pwn_ai_speak pi.config.prompt_name = pname name = "\001\e[1m\002\001\e[33m\002#{pi.config.prompt_name}\001\e[0m\002" dchars = "\001\e[32m\002>>>\001\e[33m\002" dchars = "\001\e[33m\002***\001\e[33m\002" if mode == :splat if pi.config.pwn_ai_trace dchars = "\001\e[31m\002(TRACE) >>>\001\e[33m\002" dchars = "\001\e[31m\002(TRACE) ***\001\e[33m\002" if mode == :splat elsif pi.config.pwn_ai_debug dchars = "\001\e[32m\002(DEBUG) >>>\001\e[33m\002" dchars = "\001\e[33m\002(DEBUG) ***\001\e[33m\002" if mode == :splat end end ps1_proc = "#{name}[#{version}]:#{line_count} #{dchars} ".to_s.scrub ps1_proc = '' if pi.config.pwn_mesh ps1_proc end rescue StandardError => e raise e end |
.restore_pwn_ai_completer!(opts = {}) ⇒ Object
413 414 415 416 417 418 419 420 421 |
# File 'lib/pwn/plugins/repl/ai.rb', line 413 def restore_pwn_ai_completer!(opts = {}) return unless defined?(Reline) Thread.current[:pwn_ai_completer_pry] = nil Reline.completion_proc = @pwn_ai_prev_completion_proc if @pwn_ai_prev_completion_proc Reline.completer_word_break_characters = @pwn_ai_prev_word_break if @pwn_ai_prev_word_break && Reline.respond_to?(:completer_word_break_characters=) PWN::Plugins::REPL.enable_autocomplete(enabled: opts.fetch(:enabled, true)) Reline.completion_proc end |
.start(opts = {}) ⇒ Object
- Supported Method Parameters
PWN::Plugins::REPL.start
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 |
# File 'lib/pwn/plugins/repl.rb', line 957 public_class_method def self.start(opts = {}) ai_session_id = opts[:ai_session_id] settings = PWN::Env[:driver_opts] # Monkey Patch Pry, add commands, && hooks PWN::Plugins::MonkeyPatch.pry pwn_env_root = "#{Dir.home}/.pwn" Pry.config.history_file = "#{pwn_env_root}/pwn_history" add_commands add_hooks # IRB-style suggest-as-you-type dropdown (off via # PWN::Env[:driver_opts][:autocomplete] = false in pwn.yaml). ac = settings.key?(:autocomplete) ? settings[:autocomplete] : true enable_autocomplete(enabled: ac) # Define PS1 Prompt Pry.config.pwn_repl_line = 0 Pry.config.prompt_name = :pwn arrow_ps1_proc = refresh_ps1_proc(settings) settings[:mode] = :splat splat_ps1_proc = refresh_ps1_proc(settings) ps1 = [arrow_ps1_proc, splat_ps1_proc] prompt = Pry::Prompt.new(:pwn, 'PWN Prototyping REPL', ps1) # Start PWN REPL # Pry.start(self, prompt: prompt) if ai_session_id hooks = Pry.config.hooks.dup hooks.add_hook(:before_session, :pwn_ai_cli) do |_output, _binding, pi| pi.config.pwn_ai_startup_session_id = ai_session_id pi.run_command('pwn-ai') end Pry.start(Pry.main, prompt: prompt, hooks: hooks) else Pry.start(Pry.main, prompt: prompt) end rescue StandardError => e raise e end |