pwn 0.5.803 → 0.5.805
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/Gemfile +4 -4
- data/documentation/Skills-Memory-Learning.md +7 -0
- data/lib/pwn/ai/agent/dispatch.rb +54 -1
- data/lib/pwn/ai/agent/loop.rb +3 -3
- data/lib/pwn/ai/agent/mission_namespace.rb +26 -4
- data/lib/pwn/ai/agent/request_runtime.rb +7 -0
- data/lib/pwn/ai/agent/tools/memory.rb +6 -11
- data/lib/pwn/ai/ollama.rb +10 -2
- data/lib/pwn/ai/open_web_ui.rb +7 -32
- data/lib/pwn/ai.rb +44 -0
- data/lib/pwn/memory.rb +9 -4
- data/lib/pwn/plugins/repl/ai_console.rb +152 -17
- data/lib/pwn/version.rb +1 -1
- data/spec/conventions_spec.rb +9 -7
- data/spec/integration/harness_evaluation_spec.rb +16 -24
- data/spec/lib/pwn/ai/agent/dispatch_spec.rb +80 -0
- data/spec/lib/pwn/ai/agent/mission_namespace_spec.rb +2 -1
- data/spec/lib/pwn/ai/agent/policy_spec.rb +3 -2
- data/spec/lib/pwn/ai/agent/result_spec.rb +6 -1
- data/spec/lib/pwn/ai/agent/tools/memory_spec.rb +7 -0
- data/spec/lib/pwn/ai/ollama_spec.rb +27 -0
- data/spec/lib/pwn/ai/open_web_ui_spec.rb +5 -5
- data/spec/lib/pwn/ai/provider_review_history_stream_regression_spec.rb +32 -0
- data/spec/lib/pwn/banner_spec.rb +67 -38
- data/spec/lib/pwn/cron_spec.rb +2 -39
- data/spec/lib/pwn/memory_spec.rb +46 -0
- data/spec/lib/pwn/plugins/android_review_fixes_spec.rb +14 -6
- data/spec/lib/pwn/plugins/android_transport_audit_spec.rb +2 -1
- data/spec/lib/pwn/plugins/artifact_registry_spec.rb +7 -3
- data/spec/lib/pwn/plugins/jobs_spec.rb +10 -1
- data/spec/lib/pwn/plugins/repl/ai_console_spec.rb +335 -15
- data/spec/lib/pwn/sdr/decoder/lora_spec.rb +36 -27
- data/spec/lib/pwn/setup_spec.rb +4 -19
- data/spec/spec_helper.rb +8 -4
- data/spec/support/harness/cli_faults.rb +2 -1
- data/spec/support/mission_pipe_queue.rb +12 -1
- data/spec/support/sandbox.rb +27 -0
- data/third_party/pwn_rdoc.jsonl +15 -1
- metadata +9 -9
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4c49ea1e0a11b6e4a590478793cccfcded7c6bc35e6c350aea35d4d70105068b
|
|
4
|
+
data.tar.gz: 5728257760ae7f42005b438f2cfcb164c9fb1da71e1653d6d283f6dbd37a4d66
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: ab00b67b6f6e1f8dd1961e1656fd96fd0617589e2234244918e0e30141b773100e115296b74ca7aaf67d956feaf298bd6fd53a8498fff9c39601d53342cc3397
|
|
7
|
+
data.tar.gz: 28e0c26e8e1755f1e205783bb82940cbc19cc9fdec9b467dc3b51990a358185446a7dcd0be00d61cc211e09851f945a0805a43ed210bfe74a0959721e9f38496
|
data/Gemfile
CHANGED
|
@@ -45,7 +45,7 @@ gem 'js-beautify', '0.1.8'
|
|
|
45
45
|
gem 'json', '>=2.13.2'
|
|
46
46
|
gem 'jsonpath', '1.1.5'
|
|
47
47
|
gem 'json_schemer', '2.5.0'
|
|
48
|
-
gem 'jwt', '3.3.
|
|
48
|
+
gem 'jwt', '3.3.1'
|
|
49
49
|
gem 'libusb', '0.8.0'
|
|
50
50
|
gem 'luhn', '3.0.0'
|
|
51
51
|
gem 'mail', '2.9.1'
|
|
@@ -77,7 +77,7 @@ gem 'rbvmomi2', '3.11.0'
|
|
|
77
77
|
gem 'rdoc', '7.0.4'
|
|
78
78
|
gem 'rest-client', '2.1.0'
|
|
79
79
|
gem 'rex', '2.0.13'
|
|
80
|
-
gem 'rmagick', '7.
|
|
80
|
+
gem 'rmagick', '7.3.1'
|
|
81
81
|
gem 'rqrcode', '3.2.0'
|
|
82
82
|
gem 'rspec', '3.13.2'
|
|
83
83
|
gem 'rtesseract', '3.1.4'
|
|
@@ -89,8 +89,8 @@ gem 'ruby-nmap', '1.0.3'
|
|
|
89
89
|
gem 'ruby-saml', '1.18.1'
|
|
90
90
|
gem 'rvm', '1.11.3.9'
|
|
91
91
|
gem 'savon', '2.18.1'
|
|
92
|
-
gem 'selenium-devtools', '0.
|
|
93
|
-
gem 'selenium-webdriver', '4.
|
|
92
|
+
gem 'selenium-devtools', '0.158.0'
|
|
93
|
+
gem 'selenium-webdriver', '4.54.0'
|
|
94
94
|
gem 'slack-ruby-client', '3.3.0'
|
|
95
95
|
gem 'socksify', '1.8.1'
|
|
96
96
|
gem 'spreadsheet', '1.3.5'
|
|
@@ -169,6 +169,13 @@ when deciding which side of the loop to exercise.
|
|
|
169
169
|
|
|
170
170
|
### Memory (`memory_remember`, `memory_recall`, `memory_forget`, `memory_clear`)
|
|
171
171
|
|
|
172
|
+
In the interactive pwn-ai console, `memory_remember` shows the proposed key,
|
|
173
|
+
category, and value. Use the approval or decline command shown with that entry.
|
|
174
|
+
Approval applies to one save, not the session. pwn-ai reports success only after
|
|
175
|
+
reading the saved entry back. Without interactive review, the tool does not
|
|
176
|
+
write; an operator can use `/memory remember KEY VALUE` directly. An older
|
|
177
|
+
save with an unknown outcome is not automatically retried.
|
|
178
|
+
|
|
172
179
|
- "Remember that our preferred AI engine for long recon chains is `grok`."
|
|
173
180
|
- "What do we already know about OpenSSH 8.2p1 from prior sessions?"
|
|
174
181
|
- "Forget the stale fact about the old HackRF serial - it was replaced."
|
|
@@ -72,7 +72,8 @@ module PWN
|
|
|
72
72
|
violation = JSONSchemer.schema(JSON.parse(JSON.generate(type_schema))).validate(JSON.parse(JSON.generate(args))).first
|
|
73
73
|
return schema_denial(violation.transform_keys(&:to_sym)) if violation
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
reviewed_memory = entry.name == 'memory_remember'
|
|
76
|
+
if !reviewed_memory && defined?(PWN::Plugins::Vault)
|
|
76
77
|
begin
|
|
77
78
|
args = expand_vault_args(args: args)
|
|
78
79
|
rescue StandardError
|
|
@@ -128,6 +129,13 @@ module PWN
|
|
|
128
129
|
budget = prepare_budget(opts.merge(entry: entry, args: args))
|
|
129
130
|
return JSON.generate(budget[:denial]) if budget && budget[:denial]
|
|
130
131
|
|
|
132
|
+
# Controller receipts contain no entry contents or external tool output.
|
|
133
|
+
# Reporting a reviewed save must not require opening an operator vault.
|
|
134
|
+
if reviewed_memory
|
|
135
|
+
receipt = review_memory_save(runtime: owner, args: args, action_id: tool_call[:id] || tool_call['id'])
|
|
136
|
+
return JSON.generate(success: receipt[:saved] == true, effect: 'store', result: receipt)
|
|
137
|
+
end
|
|
138
|
+
|
|
131
139
|
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
132
140
|
begin
|
|
133
141
|
runtime = Thread.current[:pwn_request_runtime]
|
|
@@ -213,6 +221,51 @@ module PWN
|
|
|
213
221
|
nil
|
|
214
222
|
end
|
|
215
223
|
|
|
224
|
+
# This one fixed operation uses the controller's writer. Neither a
|
|
225
|
+
# registry handler nor caller-selected paths execute on the controller.
|
|
226
|
+
private_class_method def self.review_memory_save(opts = {})
|
|
227
|
+
runtime = opts[:runtime]
|
|
228
|
+
no_write = { success: false, saved: false, execution_state: 'not_started' }
|
|
229
|
+
return { success: false, error: 'uncertain_side_effect', hint: 'An earlier memory save is unresolved; no new save was attempted.' } if runtime && runtime.blocking_effects.any? { |row| row[:tool] == 'memory_remember' }
|
|
230
|
+
|
|
231
|
+
review = Thread.current[:pwn_review_memory]
|
|
232
|
+
return no_write.merge(error: 'Memory was not saved. Use /memory remember KEY VALUE or review the proposed save in the interactive console.') unless runtime && review && !Thread.current[:pwn_repository_worker]
|
|
233
|
+
|
|
234
|
+
args = opts.fetch(:args)
|
|
235
|
+
fields = { category: 'fact' }.merge(args)
|
|
236
|
+
key, value, category = fields.values_at(:key, :value, :category)
|
|
237
|
+
valid = (fields.keys - %i[key value category]).empty? && %w[fact preference lesson env].include?(category) &&
|
|
238
|
+
key.is_a?(String) && key.bytesize <= 128 && !key.strip.empty? &&
|
|
239
|
+
value.is_a?(String) && value.bytesize <= PWN::Memory::VALUE_MAX_CHARS && !value.strip.empty?
|
|
240
|
+
return no_write.merge(error: 'Invalid memory fields. Supply only a short key, a text value and an optional category.') unless valid
|
|
241
|
+
return no_write.merge(error: 'Cannot save a credential or vault reference to prompt memory.') if fields.values.any? { |text| text.include?('{{vault:') } || PWN::Redaction.redact(value: { key => value }) != { key => value }
|
|
242
|
+
|
|
243
|
+
fields = fields.transform_values { |text| text.dup.freeze }.freeze
|
|
244
|
+
return no_write.merge(error: 'Memory save not approved; nothing was saved.') unless review.call(fields).equal?(true)
|
|
245
|
+
|
|
246
|
+
runtime.execute_tool(name: 'memory_remember', args: args, action_id: opts[:action_id], effect: :store, reviewed_memory: true) { save_reviewed_memory(fields) }
|
|
247
|
+
rescue StandardError => e
|
|
248
|
+
{ success: false, error: "Memory save did not return a verified receipt (#{e.class})." }
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
private_class_method def self.save_reviewed_memory(opts = {})
|
|
252
|
+
admitted = false
|
|
253
|
+
PWN::Memory.transaction do
|
|
254
|
+
admitted = true
|
|
255
|
+
PWN::Memory.remember(**opts)
|
|
256
|
+
stored = PWN::Memory.load
|
|
257
|
+
row = stored.fetch(opts.fetch(:key).to_sym)
|
|
258
|
+
raise IOError, 'memory save could not be verified' unless row[:value] == opts[:value] && row[:category].to_s == opts[:category]
|
|
259
|
+
|
|
260
|
+
{ saved: true }
|
|
261
|
+
end
|
|
262
|
+
rescue SystemCallError => e
|
|
263
|
+
# Once inside the transaction even EACCES could be after rename.
|
|
264
|
+
raise if admitted
|
|
265
|
+
|
|
266
|
+
raise RequestRuntime::MemoryWriteNotStarted, "Memory writer unavailable (#{e.class}); nothing was saved."
|
|
267
|
+
end
|
|
268
|
+
|
|
216
269
|
private_class_method def self.schema_denial(opts = {})
|
|
217
270
|
pointer = opts[:data_pointer].to_s
|
|
218
271
|
message = opts[:error].to_s
|
data/lib/pwn/ai/agent/loop.rb
CHANGED
|
@@ -3181,7 +3181,7 @@ module PWN
|
|
|
3181
3181
|
|
|
3182
3182
|
private_class_method def self.engine_failure_text(opts = {})
|
|
3183
3183
|
attempts = opts[:runtime]&.last_provider_attempts || opts[:attempts]
|
|
3184
|
-
"[pwn-ai] engine hop failed after #{attempts} tries: #{opts[:error].message
|
|
3184
|
+
"[pwn-ai] engine hop failed after #{attempts} tries: #{opts[:error].message}"
|
|
3185
3185
|
end
|
|
3186
3186
|
|
|
3187
3187
|
private_class_method def self.engine_retry_exhausted?(opts = {})
|
|
@@ -3305,7 +3305,7 @@ module PWN
|
|
|
3305
3305
|
final_chars = 0
|
|
3306
3306
|
start_debug_session(opts)
|
|
3307
3307
|
loud_debug_tui!(debug: opts[:debug])
|
|
3308
|
-
debug_progress(msg: "Loop.run start request=#{request
|
|
3308
|
+
debug_progress(msg: "Loop.run start request=#{request}", debug: opts[:debug])
|
|
3309
3309
|
ToolGuard.reset_timeout_budget! if defined?(ToolGuard) && ToolGuard.respond_to?(:reset_timeout_budget!)
|
|
3310
3310
|
nested = opts[:nested] == true || Thread.current[:pwn_swarm_depth].to_i.positive? || (defined?(TurnFinalizer) && TurnFinalizer.user_path?)
|
|
3311
3311
|
TurnFinalizer.enter_user_path! if defined?(TurnFinalizer)
|
|
@@ -3560,7 +3560,7 @@ module PWN
|
|
|
3560
3560
|
rescue StandardError => e
|
|
3561
3561
|
if engine_transient?(error: e)
|
|
3562
3562
|
engine_blips += 1
|
|
3563
|
-
debug_progress(msg: "engine hop failed #{e.class}: #{e.message
|
|
3563
|
+
debug_progress(msg: "engine hop failed #{e.class}: #{e.message} blip=#{engine_blips}")
|
|
3564
3564
|
if engine_retry_exhausted?(runtime: runtime, attempts: engine_blips)
|
|
3565
3565
|
txt = engine_failure_text(runtime: runtime, attempts: engine_blips, error: e)
|
|
3566
3566
|
debug_final_text!(text: txt)
|
|
@@ -23,9 +23,31 @@ module PWN
|
|
|
23
23
|
pwn_reflect_depth pwn_request_intent pwn_loop_budget_s pwn_loop_mutations pwn_loop_tokens].freeze
|
|
24
24
|
attr_reader :status
|
|
25
25
|
|
|
26
|
+
@fork_lock = Mutex.new
|
|
27
|
+
@control_writers = ObjectSpace::WeakMap.new
|
|
28
|
+
|
|
26
29
|
class << self
|
|
27
30
|
attr_accessor :owned, :bootstrap_requires, :force_exec
|
|
28
31
|
|
|
32
|
+
# Register the parent endpoint atomically with respect to all mission
|
|
33
|
+
# forks, including sibling missions started by another console thread.
|
|
34
|
+
def control_socket_pair
|
|
35
|
+
@fork_lock.synchronize do
|
|
36
|
+
UNIXSocket.pair.tap { |_reader, writer| @control_writers[writer] = true }
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def fork_mission
|
|
41
|
+
@fork_lock.synchronize do
|
|
42
|
+
writers = @control_writers.keys # Pin live endpoints across fork, not for the console's lifetime.
|
|
43
|
+
fork do
|
|
44
|
+
@fork_lock = Mutex.new # Nested missions must not use the parent's held lock.
|
|
45
|
+
writers.each(&:close) # Close the copies, never shutdown the shared socket.
|
|
46
|
+
yield
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
29
51
|
def prepared?
|
|
30
52
|
rows = File.readlines('/proc/self/uid_map').map { |line| line.split.map(&:to_i) }
|
|
31
53
|
count = rows.length == 1 ? rows.first.last : nil
|
|
@@ -92,7 +114,7 @@ module PWN
|
|
|
92
114
|
checked(native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace') if pid_namespace
|
|
93
115
|
reader, writer = IO.pipe
|
|
94
116
|
armed, arm = IO.pipe
|
|
95
|
-
init =
|
|
117
|
+
init = fork_mission do
|
|
96
118
|
armed.close
|
|
97
119
|
checked(native('prctl', [Fiddle::TYPE_INT, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]).call(1, Signal.list.fetch('KILL'), 0, 0, 0), 'PR_SET_PDEATHSIG')
|
|
98
120
|
arm.write('1')
|
|
@@ -192,7 +214,7 @@ module PWN
|
|
|
192
214
|
if operation
|
|
193
215
|
raise Unavailable, 'host closures cannot cross an exec boundary; use a mission descriptor or explicitly bootstrap under unshare --user --map-current-user --keep-caps' unless self.class.owned
|
|
194
216
|
|
|
195
|
-
@pid =
|
|
217
|
+
@pid = self.class.fork_mission do
|
|
196
218
|
Thread.handle_interrupt(Exception => :immediate) { operation.call }
|
|
197
219
|
ensure
|
|
198
220
|
exit!
|
|
@@ -320,7 +342,7 @@ module PWN
|
|
|
320
342
|
ready, announce = IO.pipe
|
|
321
343
|
release, gate = IO.pipe
|
|
322
344
|
owner = Process.pid
|
|
323
|
-
@pid =
|
|
345
|
+
@pid = self.class.fork_mission do
|
|
324
346
|
ready.close
|
|
325
347
|
gate.close
|
|
326
348
|
begin
|
|
@@ -328,7 +350,7 @@ module PWN
|
|
|
328
350
|
exit! unless Process.ppid == owner
|
|
329
351
|
self.class.checked(self.class.native('unshare', [Fiddle::TYPE_INT]).call(0x20000000), 'unshare PID namespace')
|
|
330
352
|
armed, arm = IO.pipe
|
|
331
|
-
init =
|
|
353
|
+
init = self.class.fork_mission do
|
|
332
354
|
armed.close
|
|
333
355
|
announce.close
|
|
334
356
|
self.class.checked(self.class.native('prctl', [Fiddle::TYPE_INT, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]).call(1, Signal.list.fetch('KILL'), 0, 0, 0), 'PR_SET_PDEATHSIG')
|
|
@@ -16,6 +16,8 @@ module PWN
|
|
|
16
16
|
module Agent
|
|
17
17
|
# Connect request-scoped routing, evidence context and replay records.
|
|
18
18
|
class RequestRuntime # rubocop:disable Metrics/ClassLength -- one owner for routing, scope and durable evidence
|
|
19
|
+
class MemoryWriteNotStarted < StandardError; end
|
|
20
|
+
|
|
19
21
|
OUTCOMES = %w[complete incomplete blocked cancelled verification_error].freeze
|
|
20
22
|
attr_reader :original_request, :request, :session_id, :request_id, :contract, :amendments, :outcome, :checkpoint_path, :engine, :last_provider_attempts
|
|
21
23
|
|
|
@@ -413,6 +415,11 @@ module PWN
|
|
|
413
415
|
'failed'
|
|
414
416
|
end
|
|
415
417
|
result
|
|
418
|
+
rescue MemoryWriteNotStarted => e
|
|
419
|
+
raise unless opts[:reviewed_memory] && opts[:name] == 'memory_remember'
|
|
420
|
+
|
|
421
|
+
state = 'failed'
|
|
422
|
+
{ success: false, error: e.message, saved: false, execution_state: 'not_started' }
|
|
416
423
|
rescue PWN::Plugins::AISandbox::NotStarted => e
|
|
417
424
|
state = 'rejected'
|
|
418
425
|
action[:diagnostic] = e.message
|
|
@@ -10,11 +10,11 @@ PWN::AI::Agent::Registry.register(
|
|
|
10
10
|
toolset: 'memory',
|
|
11
11
|
schema: {
|
|
12
12
|
name: 'memory_remember',
|
|
13
|
-
description: '
|
|
14
|
-
'
|
|
15
|
-
'prompt of every future pwn-ai session.',
|
|
13
|
+
description: 'Propose a durable fact, preference, or lesson for future sessions. ' \
|
|
14
|
+
'The interactive operator reviews the exact entry before it is saved. Never include credentials.',
|
|
16
15
|
parameters: {
|
|
17
16
|
type: 'object',
|
|
17
|
+
additionalProperties: false,
|
|
18
18
|
properties: {
|
|
19
19
|
key: { type: 'string', description: 'Short unique identifier for this memory.' },
|
|
20
20
|
value: { type: 'string', description: 'The fact / preference / lesson to remember.' },
|
|
@@ -24,14 +24,9 @@ PWN::AI::Agent::Registry.register(
|
|
|
24
24
|
}
|
|
25
25
|
},
|
|
26
26
|
check: -> { defined?(PWN::Memory) },
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
value: args[:value],
|
|
31
|
-
category: (args[:category] || 'fact').to_sym
|
|
32
|
-
)
|
|
33
|
-
{ saved: true, key: args[:key], total: PWN::Memory.load.keys.length }
|
|
34
|
-
}
|
|
27
|
+
# Dispatch owns the reviewed transaction. Never grant an isolated registry
|
|
28
|
+
# handler direct access to the cross-session prompt store.
|
|
29
|
+
handler: ->(_args) { { success: false, saved: false, execution_state: 'not_started', error: 'Memory save requires operator review.' } }
|
|
35
30
|
)
|
|
36
31
|
|
|
37
32
|
PWN::AI::Agent::Registry.register(
|
data/lib/pwn/ai/ollama.rb
CHANGED
|
@@ -4,6 +4,7 @@ require 'json'
|
|
|
4
4
|
require 'base64'
|
|
5
5
|
require 'securerandom'
|
|
6
6
|
require 'uri'
|
|
7
|
+
require 'pwn/ai'
|
|
7
8
|
|
|
8
9
|
module PWN
|
|
9
10
|
module AI
|
|
@@ -269,13 +270,14 @@ module PWN
|
|
|
269
270
|
# SSE on /v1/chat/completions) into a single JSON string matching the
|
|
270
271
|
# non-stream response shape used by #chat / #chat_with_tools.
|
|
271
272
|
private_class_method def self.assemble_ollama_stream(opts = {})
|
|
272
|
-
|
|
273
|
+
preview = StreamPreview.new(body: opts[:body].to_s, provider: 'Ollama')
|
|
273
274
|
rest_call = opts[:rest_call].to_s
|
|
274
275
|
|
|
275
|
-
records = stream_records(body: body, rest_call: rest_call)
|
|
276
|
+
records = stream_records(body: preview.body, rest_call: rest_call)
|
|
276
277
|
done = false
|
|
277
278
|
payloads = records.filter_map do |record|
|
|
278
279
|
raise "ERROR: Ollama incomplete SSE stream for #{rest_call}: unterminated event" if record[:incomplete]
|
|
280
|
+
raise "ERROR: Ollama stream error for #{rest_call}" if preview.required? && record[:event] == 'error'
|
|
279
281
|
|
|
280
282
|
data = record[:data]
|
|
281
283
|
if data == '[DONE]'
|
|
@@ -287,6 +289,8 @@ module PWN
|
|
|
287
289
|
payload = parse_stream_payload(data: data, rest_call: rest_call)
|
|
288
290
|
error = payload[:error] || (payload if record[:event] == 'error')
|
|
289
291
|
if error
|
|
292
|
+
raise "ERROR: Ollama stream error for #{rest_call}" if preview.required?
|
|
293
|
+
|
|
290
294
|
detail = error.is_a?(Hash) ? (error[:message] || error) : error
|
|
291
295
|
raise "ERROR: Ollama stream error for #{rest_call}: #{detail}"
|
|
292
296
|
end
|
|
@@ -299,11 +303,15 @@ module PWN
|
|
|
299
303
|
finished = payloads.any? { |p| Array(p[:choices]).any? { |ch| ch[:finish_reason] } }
|
|
300
304
|
raise "ERROR: Ollama incomplete stream for #{rest_call}: missing terminal event" unless done || finished
|
|
301
305
|
|
|
306
|
+
return preview.display!(payloads: payloads, sse: true, done: done) if preview.required?
|
|
307
|
+
|
|
302
308
|
assemble_openai_compat_stream(payloads: payloads)
|
|
303
309
|
else
|
|
304
310
|
raise "ERROR: Ollama malformed native stream for #{rest_call}: expected message object" unless payloads.any? { |p| p[:message].is_a?(Hash) } && payloads.all? { |p| !p.key?(:message) || p[:message].is_a?(Hash) }
|
|
305
311
|
raise "ERROR: Ollama incomplete native stream for #{rest_call}: missing terminal done frame" unless payloads.last[:done] == true && payloads[0...-1].all? { |p| p[:done] == false }
|
|
306
312
|
|
|
313
|
+
return preview.display!(payloads: payloads, sse: false) if preview.required?
|
|
314
|
+
|
|
307
315
|
assemble_native_chat_stream(payloads: payloads)
|
|
308
316
|
end
|
|
309
317
|
end
|
data/lib/pwn/ai/open_web_ui.rb
CHANGED
|
@@ -4,6 +4,7 @@ require 'json'
|
|
|
4
4
|
require 'base64'
|
|
5
5
|
require 'securerandom'
|
|
6
6
|
require 'uri'
|
|
7
|
+
require 'pwn/ai'
|
|
7
8
|
|
|
8
9
|
module PWN
|
|
9
10
|
module AI
|
|
@@ -282,20 +283,14 @@ module PWN
|
|
|
282
283
|
# OpenAI-compat SSE on /api/v1/chat/completions) into a single JSON string
|
|
283
284
|
# matching the non-stream response shape used by #chat / #chat_with_tools.
|
|
284
285
|
private_class_method def self.assemble_openwebui_stream(opts = {})
|
|
285
|
-
|
|
286
|
+
preview = StreamPreview.new(body: opts[:body].to_s, provider: 'Open WebUI')
|
|
286
287
|
rest_call = opts[:rest_call].to_s
|
|
287
288
|
|
|
288
|
-
|
|
289
|
-
# Decode the complete buffer for a display-only preview, never for action assembly.
|
|
290
|
-
preview = body.encoding == Encoding::BINARY && !body.ascii_only?
|
|
291
|
-
if preview
|
|
292
|
-
body = body.dup.force_encoding(Encoding::UTF_8)
|
|
293
|
-
raise 'ERROR: Open WebUI response contains invalid UTF-8' unless body.valid_encoding?
|
|
294
|
-
end
|
|
295
|
-
records = stream_records(body: body, rest_call: rest_call)
|
|
289
|
+
records = stream_records(body: preview.body, rest_call: rest_call)
|
|
296
290
|
done = false
|
|
297
291
|
payloads = records.filter_map do |record|
|
|
298
292
|
raise "ERROR: Open WebUI incomplete SSE stream for #{rest_call}: unterminated event" if record[:incomplete]
|
|
293
|
+
raise "ERROR: Open WebUI stream error for #{rest_call}" if preview.required? && record[:event] == 'error'
|
|
299
294
|
|
|
300
295
|
data = record[:data]
|
|
301
296
|
if data == '[DONE]'
|
|
@@ -307,7 +302,7 @@ module PWN
|
|
|
307
302
|
payload = parse_stream_payload(data: data, rest_call: rest_call)
|
|
308
303
|
error = payload[:error] || (payload if record[:event] == 'error')
|
|
309
304
|
if error
|
|
310
|
-
raise "ERROR: Open WebUI stream error for #{rest_call}" if preview
|
|
305
|
+
raise "ERROR: Open WebUI stream error for #{rest_call}" if preview.required?
|
|
311
306
|
|
|
312
307
|
detail = error.is_a?(Hash) ? (error[:message] || error) : error
|
|
313
308
|
raise "ERROR: Open WebUI stream error for #{rest_call}: #{detail}"
|
|
@@ -321,39 +316,19 @@ module PWN
|
|
|
321
316
|
finished = payloads.any? { |p| Array(p[:choices]).any? { |ch| ch[:finish_reason] } }
|
|
322
317
|
raise "ERROR: Open WebUI incomplete stream for #{rest_call}: missing terminal event" unless done || finished
|
|
323
318
|
|
|
324
|
-
return
|
|
319
|
+
return preview.display!(payloads: payloads, sse: true, done: done) if preview.required?
|
|
325
320
|
|
|
326
321
|
assemble_openai_compat_stream(payloads: payloads)
|
|
327
322
|
else
|
|
328
323
|
raise "ERROR: Open WebUI malformed native stream for #{rest_call}: expected message object" unless payloads.any? { |p| p[:message].is_a?(Hash) } && payloads.all? { |p| !p.key?(:message) || p[:message].is_a?(Hash) }
|
|
329
324
|
raise "ERROR: Open WebUI incomplete native stream for #{rest_call}: missing terminal done frame" unless payloads.last[:done] == true && payloads[0...-1].all? { |p| p[:done] == false }
|
|
330
325
|
|
|
331
|
-
return
|
|
326
|
+
return preview.display!(payloads: payloads, sse: false) if preview.required?
|
|
332
327
|
|
|
333
328
|
assemble_native_chat_stream(payloads: payloads)
|
|
334
329
|
end
|
|
335
330
|
end
|
|
336
331
|
|
|
337
|
-
# Never return a recovered record to the caller. Do not collect arguments or thinking.
|
|
338
|
-
private_class_method def self.preview_stream!(opts = {})
|
|
339
|
-
text = +''
|
|
340
|
-
role = 'assistant'
|
|
341
|
-
pending = false
|
|
342
|
-
opts[:payloads].each do |payload|
|
|
343
|
-
choices = opts[:sse] ? Array(payload[:choices]) : [{ message: payload[:message], finish_reason: payload[:done_reason] }]
|
|
344
|
-
choices.each_with_index do |choice, index|
|
|
345
|
-
msg = choice[:delta] || choice[:message] || {}
|
|
346
|
-
pending ||= %w[tool_calls function_call].include?(choice[:finish_reason]) || !Array(msg[:tool_calls]).empty? || !msg[:function_call].nil?
|
|
347
|
-
next unless 0.eql?(choice.fetch(:index, index))
|
|
348
|
-
|
|
349
|
-
role = msg[:role] || role
|
|
350
|
-
text << msg[:content] if role == 'assistant' && msg[:content].is_a?(String)
|
|
351
|
-
end
|
|
352
|
-
end
|
|
353
|
-
Thread.current[:pwn_openwebui_preview]&.call(text, pending)
|
|
354
|
-
raise 'Open WebUI reply is display-only; no actions from this reply were submitted.'
|
|
355
|
-
end
|
|
356
|
-
|
|
357
332
|
# SSE dispatches at blank lines, joining every data field with a newline.
|
|
358
333
|
# Native NDJSON accepts a complete last record without a trailing newline.
|
|
359
334
|
private_class_method def self.stream_records(opts = {})
|
data/lib/pwn/ai.rb
CHANGED
|
@@ -21,6 +21,50 @@ module PWN
|
|
|
21
21
|
autoload :Router, 'pwn/ai/router'
|
|
22
22
|
autoload :ServerTools, 'pwn/ai/server_tools'
|
|
23
23
|
|
|
24
|
+
# Ollama and Open WebUI share a wire format. A binary-tagged non-ASCII reply
|
|
25
|
+
# that previously failed framing may be recovered for display, not replayed.
|
|
26
|
+
class StreamPreview
|
|
27
|
+
attr_reader :body
|
|
28
|
+
|
|
29
|
+
def initialize(body:, provider:)
|
|
30
|
+
@provider = provider
|
|
31
|
+
@required = body.encoding == Encoding::BINARY && !body.ascii_only?
|
|
32
|
+
@body = required? ? body.dup.force_encoding(Encoding::UTF_8) : body
|
|
33
|
+
raise "ERROR: #{@provider} response contains invalid UTF-8" if required? && !@body.valid_encoding?
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def required?
|
|
37
|
+
@required
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Only choice 0 is displayed. Another choice cannot finish its text.
|
|
41
|
+
# Never return actions, arguments or reasoning, even without a console.
|
|
42
|
+
def display!(payloads:, sse:, done: false)
|
|
43
|
+
text = +''
|
|
44
|
+
role = 'assistant'
|
|
45
|
+
pending = false
|
|
46
|
+
finish_reason = nil
|
|
47
|
+
payloads.each do |payload|
|
|
48
|
+
choices = sse ? Array(payload[:choices]) : [{ message: payload[:message], finish_reason: payload[:done_reason] }]
|
|
49
|
+
choices.each_with_index do |choice, index|
|
|
50
|
+
msg = choice[:delta] || choice[:message] || {}
|
|
51
|
+
pending ||= %w[tool_calls function_call].include?(choice[:finish_reason]) || !Array(msg[:tool_calls]).empty? || !msg[:function_call].nil?
|
|
52
|
+
next unless 0.eql?(choice.fetch(:index, index))
|
|
53
|
+
|
|
54
|
+
finish_reason = choice[:finish_reason]
|
|
55
|
+
role = msg[:role] || role
|
|
56
|
+
text << msg[:content] if role == 'assistant' && msg[:content].is_a?(String)
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
choice_finished = finish_reason.is_a?(String) && !finish_reason.empty?
|
|
60
|
+
raise "ERROR: #{@provider} incomplete SSE preview: missing finish reason for choice 0" if sse && !done && !choice_finished
|
|
61
|
+
|
|
62
|
+
Thread.current[:pwn_stream_preview]&.call(@provider, text, pending)
|
|
63
|
+
raise "#{@provider} reply is display-only; no actions from this reply were submitted."
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
private_constant :StreamPreview
|
|
67
|
+
|
|
24
68
|
# Display a List of Every PWN::AI Module
|
|
25
69
|
|
|
26
70
|
# Author(s):: 0day Inc. <support@0dayinc.com>
|
data/lib/pwn/memory.rb
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
require 'json'
|
|
4
4
|
require 'fileutils'
|
|
5
|
+
require 'securerandom'
|
|
5
6
|
require 'time'
|
|
6
7
|
|
|
7
8
|
module PWN
|
|
@@ -93,17 +94,21 @@ module PWN
|
|
|
93
94
|
private_class_method def self.atomic_write(opts = {})
|
|
94
95
|
path = opts[:path]
|
|
95
96
|
body = opts[:body]
|
|
96
|
-
|
|
97
|
-
File.
|
|
97
|
+
dir = File.dirname(path)
|
|
98
|
+
tmp = File.join(dir, ".#{File.basename(path)}.#{SecureRandom.hex(16)}.tmp")
|
|
99
|
+
owned_tmp = nil # Never remove a candidate that we failed to create.
|
|
100
|
+
File.open(tmp, File::WRONLY | File::CREAT | File::EXCL | File::NOFOLLOW, 0o600) do |f|
|
|
101
|
+
owned_tmp = tmp
|
|
98
102
|
f.flock(File::LOCK_EX)
|
|
99
103
|
f.write(body)
|
|
100
104
|
f.flush
|
|
101
105
|
f.fsync
|
|
102
106
|
end
|
|
103
107
|
File.rename(tmp, path)
|
|
104
|
-
|
|
108
|
+
owned_tmp = nil
|
|
109
|
+
File.open(dir, File::RDONLY, &:fsync)
|
|
105
110
|
ensure
|
|
106
|
-
FileUtils.rm_f(
|
|
111
|
+
FileUtils.rm_f(owned_tmp) if owned_tmp
|
|
107
112
|
end
|
|
108
113
|
|
|
109
114
|
# Best-effort re-read used by the empty-overwrite guard (no raise).
|