Module: PWN::AI::Agent::PromptBuilder

Defined in:
lib/pwn/ai/agent/prompt_builder.rb

Overview

Assembles the system prompt for every Loop.run invocation from durable on-disk state: PWN::Env persona, host environment probe, PWN::Memory facts, and PWN::Skills index.

Re-injection IS the persistence mechanism: this is rebuilt fresh on every user turn, so a memory_remember / skill_create from the prior turn shows up here with no extra wiring.

ENGINE-AWARE BUDGETING

Local models (Ollama) drown when handed the same 6-8 KB of MEMORY / METRICS / MISTAKES / EXTROSPECTION context that a frontier model shrugs off. .budget shrinks each block for :ollama (or whatever PWN::Env[][:prompt_budget] says) so the small model spends its attention on the request, not the harness.

RELEVANCE-RANKED MEMORY

When Loop.run passes request: through, the MEMORY block is populated by PWN::MemoryIndex.recall_semantic (embedding cosine over ~/.pwn/memory.idx) instead of a recency dump — the 6 memories a small model can afford are the 6 that actually matter for THIS turn.

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. support@0dayinc.com



313
314
315
# File 'lib/pwn/ai/agent/prompt_builder.rb', line 313

public_class_method def self.authors
  "AUTHOR(S):\n  0day Inc. <support@0dayinc.com>\n"
end

.budgetObject

Supported Method Parameters

b = PWN::AI::Agent::PromptBuilder.budget

Per-engine caps for each injected block. Override any key via PWN::Env[][:prompt_budget][:memory|:metrics|:mistakes| :learning|:extro]. :extro is a Boolean gate — Extrospection is the heaviest block and rarely useful to a local model.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/pwn/ai/agent/prompt_builder.rb', line 134

public_class_method def self.budget
  eng = active_engine
  b   = (PWN::Env.dig(:ai, eng, :prompt_budget) if defined?(PWN::Env)) || {}
  local = %i[ollama openwebui].include?(eng)
  {
    memory: (b[:memory] || (local ? 6 : 25)).to_i,
    metrics: (b[:metrics] || (local ? 3 : 8)).to_i,
    mistakes: (b[:mistakes] || (local ?  3 :  6)).to_i,
    learning: (b[:learning] || (local ?  2 :  5)).to_i,
    # Always inject last user/assistant pair(s); local keeps it tiny.
    recent_turns: (b[:recent_turns] || (local ? 1 : 2)).to_i,
    policy: (b[:policy] || 1).to_i,
    extro: b[:extro].nil? ? !local : b[:extro]
  }
rescue StandardError
  { memory: 25, metrics: 8, mistakes: 6, learning: 5, recent_turns: 2, policy: 1, extro: true }
end

.build(opts = {}) ⇒ Object

Supported Method Parameters

system_prompt = PWN::AI::Agent::PromptBuilder.build( session_id: 'optional - PWN::Sessions id to embed in the ENV block', request: 'optional - user request; enables relevance-ranked MEMORY when provided' )



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/pwn/ai/agent/prompt_builder.rb', line 35

public_class_method def self.build(opts = {})
  session_id = opts[:session_id]
  request = opts[:request]
  engine = active_engine
  # thin: greeting/statement/howto/recall — base + ENV + optional recent turns.
  # Full MEMORY/METRICS/MISTAKES/EXTRO only for act/recon (default).
  thin = opts[:thin] == true || opts[:mode].to_s == 'thin'
  b = budget
  base = (PWN::Env.dig(:ai, engine, :system_role_content) if defined?(PWN::Env)) || 'You are a world-class introspective offensive cyber security and research engineer.  You specialize in discovering zero day vulnerabilities focused on responsible disclosure prior to threat actors discovering and exploiting.  You are self-aware of your harness, pwn which begins with the ruby namespace `PWN` operating inside the pwn REPL.  For every request you first begin by determining if PWN has a module capable of satisfying the request.'

  if thin
    recent = recent_turns_block(session_id: session_id, request: request, limit: [b[:recent_turns].to_i, 2].min)
    return <<~PROMPT
      #{base}

      ENVIRONMENT
        host       : #{host_line}
        cwd        : #{Dir.pwd}
        ruby       : #{RUBY_VERSION}
        pwn        : #{pwn_version}
        session_id : #{session_id || '(none)'}

      #{recent}TOOL USE
        No tools on this turn unless a single factual lookup is already in
        context. Answer concisely in plain US English. Do not plan multi-step
        work, invent task traces, or run live recon.
    PROMPT
  end

  # Heredoc (not a "..." literal): an unescaped "..." inside a
  # double-quoted string is parsed as Range (begin..."...end).
  # Skills sit in the STATIC prefix (Hermes index) so prompt-cache
  # breakpoints can pin the persona + SKILLS list; MEMORY/LEARNING
  # remain in the dynamic tail. Mid-turn lean: request + CORE_TOOLS +
  # known-fix. Expand MEMORY/SKILLS/LEARNING/METRICS/POLICY/EXTRO
  # only when the turn is stuck or the operator asked for the full harness.
  expand = opts[:expand_harness] == true || opts[:stuck] == true
  harness = if expand
              "#{skills_block}#{memory_block(limit: b[:memory], request: request)}#{recent_turns_block(session_id: session_id, request: request, limit: b[:recent_turns])}#{learning_block(limit: b[:learning])}#{mistakes_block(limit: b[:mistakes], request: request)}#{metrics_block(limit: b[:metrics], engine: engine)}#{policy_block if b[:policy].to_i.positive?}#{extrospection_block if b[:extro]}"
            else
              "#{recent_turns_block(session_id: session_id, request: request, limit: [b[:recent_turns].to_i, 1].max)}#{mistakes_block(limit: b[:mistakes], request: request)}"
            end
  <<~PROMPT
    #{base}

    ENVIRONMENT
      host       : #{host_line}
      cwd        : #{Dir.pwd}
      ruby       : #{RUBY_VERSION}
      pwn        : #{pwn_version}
      session_id : #{session_id || '(none)'}

    #{harness}TOOL USE
      Use the provided function tools to act on the host via NATIVE
      tool_calls / function calling — never print tool invocations as
      plain text (e.g. do NOT write shell(command="...") as your answer).
      Never narrate the next step in prose ("Wait, let's try hping3…",
    "I will run…", "one more thing…") — that is treated as an incomplete
    reply. Emit a real tool_call instead, or a complete final answer
    with evidence. A reply with no tool_calls is your FINAL answer to the user.
      Prefer `pwn_eval` for anything in the PWN:: namespace and `shell`
      for OS commands. Save durable facts with `memory_remember`.

    AUTONOMY
      Multi-step goals must be finished in one Loop.run. Keep calling
      CORE_TOOLS until the original request is done or truly blocked.
      English tasks are an advisory compass, not a gate. Do NOT stop to
      ask the user to confirm the next step, approve a partial plan, or
      green-light the obvious continuation. Only ask when a credential,
      irreversible destructive action, or missing external decision is
      strictly required. Partial progress reports without completing the
      goal are incorrect behavior.

    INTENT AND SCOPE
      Every user request is an autonomous goal. Finish it in this run
      with CORE_TOOLS. English tasks are an advisory compass only.
      Pure how-to / syntax / usage questions get a concise explanation
      with example commands only — no invented planner monologue.
      Pure prior-turn recall ("what did I just say?") is answered from the
      RECENT TURNS block or one memory_recall — never a multi-tool plan.
      Pure greetings / light smalltalk short-circuit to a fixed ack — never
      echo weather or invent social filler ("noted, cloudy out there").
      Do not treat process_sop_* or operator_pref_* memory about code
      hygiene as the current user goal unless they asked to change code.
      Live subnet sweeps, raw-socket discovery (hping3/nmap -sn mass
      probes, etc.) require explicit in-scope / authorized engagement
      language from the user. Without it, refuse the live scan and offer
      the command syntax instead.
  PROMPT
end

.helpObject

Display Usage for this Module



319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/pwn/ai/agent/prompt_builder.rb', line 319

public_class_method def self.help
  puts <<~USAGE
    USAGE:
      system_prompt = PWN::AI::Agent::PromptBuilder.build(session_id: 'abc', request: 'nmap sweep 10/8')
      PWN::AI::Agent::PromptBuilder.budget   # => {memory:, metrics:, mistakes:, learning:, extro:}

      Override per-engine via:
        PWN::Env[:ai][:ollama][:prompt_budget] = { memory: 4, extro: false }

      #{self}.authors
  USAGE
end