pwn 0.5.800 → 0.5.803

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 56a736106e65e77d80e40f36fbe1769a6a781c0238f32d4a1b2b167057799c71
4
- data.tar.gz: 21ff5fbd244d4d43fc7a089a12e6f6cd20552964d09b40d6d7e2ef81bc107dec
3
+ metadata.gz: 084348206227df7ff3160a96ab3a4dffbd7cfb9a5ffb2b7cd11d61ecd3b8222e
4
+ data.tar.gz: 226f2583c220b01014152a1eb8fb57d6379470f00bd30267957b654643ea7e5a
5
5
  SHA512:
6
- metadata.gz: b3058ac66d77c60c5cd44c695d7d1a26e77c715c1210c4f9c41ed414c2dca5dd4b4ed9ee0650b07f5df3222d522d8f07b9f813d8ad8934a729659f1a1a7f2d15
7
- data.tar.gz: 40ae8191eba1dcecdbb9ca0543b09493d1365129b0048a11629ecccc48defb94b5156235cf57777e8acaf8fd737639c3f487d5865e6358fd99d6528a27e6b265
6
+ metadata.gz: 552132ef9ae49b21ae58e3021c44e64c21e5f4dc2a844be9d8b82d4b6ca9bd9d4d4e585d1bd6fe52d22abe2ec1105c552077dfd75521459602f2d285aa509381
7
+ data.tar.gz: 85ff41569586d1a5b4e024784a73c27d54da09c01ece7196981c4f81829f26ffba6aad01bb889b17495cbda80cd82fee826a2b2cf73513dd5bc735b9091c5bec
data/.ruby-version CHANGED
@@ -1 +1 @@
1
- 4.0.9
1
+ 4.0.10
data/Gemfile CHANGED
@@ -18,7 +18,7 @@ gem 'aws-sdk', '3.3.0'
18
18
  gem 'barby', '0.7.0'
19
19
  gem 'base32', '0.3.4'
20
20
  gem 'bitcoin-ruby', '0.0.20'
21
- gem 'brakeman', '8.1.0'
21
+ gem 'brakeman', '8.1.1'
22
22
  gem 'bson', '5.2.0'
23
23
  gem 'bundler', '>=4.1.0'
24
24
  gem 'bundler-audit', '>=0.9.3'
@@ -50,7 +50,7 @@ gem 'libusb', '0.8.0'
50
50
  gem 'luhn', '3.0.0'
51
51
  gem 'mail', '2.9.1'
52
52
  gem 'mcp', '1.11.0'
53
- gem 'meshtastic', '0.0.193'
53
+ gem 'meshtastic', '0.0.194'
54
54
  gem 'metasm', '1.0.6'
55
55
  gem 'mongo', '2.26.2'
56
56
  gem 'msfrpc-client', '1.1.2'
data/Rakefile CHANGED
@@ -27,7 +27,7 @@ class DiagnosticSpecTask < RSpec::Core::RakeTask
27
27
  end
28
28
 
29
29
  DiagnosticSpecTask.new(:spec) do |task|
30
- task.rspec_opts = "#{task.rspec_opts} --require ./spec/support/gate_failure_formatter.rb --format progress --format GateFailureFormatter"
30
+ task.rspec_opts = "#{task.rspec_opts} --require ./spec/support/gate_failure_formatter.rb --format GateFailureFormatter"
31
31
  end
32
32
  task :silence_rspec_filter_banner do
33
33
  ENV['PWN_RAKE_SPEC'] = '1'
@@ -285,6 +285,13 @@ module PWN
285
285
  body = opts[:body].to_s
286
286
  rest_call = opts[:rest_call].to_s
287
287
 
288
+ # Net::HTTP can deliver valid UTF-8 tagged as binary, even across character boundaries.
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
288
295
  records = stream_records(body: body, rest_call: rest_call)
289
296
  done = false
290
297
  payloads = records.filter_map do |record|
@@ -300,6 +307,8 @@ module PWN
300
307
  payload = parse_stream_payload(data: data, rest_call: rest_call)
301
308
  error = payload[:error] || (payload if record[:event] == 'error')
302
309
  if error
310
+ raise "ERROR: Open WebUI stream error for #{rest_call}" if preview
311
+
303
312
  detail = error.is_a?(Hash) ? (error[:message] || error) : error
304
313
  raise "ERROR: Open WebUI stream error for #{rest_call}: #{detail}"
305
314
  end
@@ -312,15 +321,39 @@ module PWN
312
321
  finished = payloads.any? { |p| Array(p[:choices]).any? { |ch| ch[:finish_reason] } }
313
322
  raise "ERROR: Open WebUI incomplete stream for #{rest_call}: missing terminal event" unless done || finished
314
323
 
324
+ return preview_stream!(payloads: payloads, sse: true) if preview
325
+
315
326
  assemble_openai_compat_stream(payloads: payloads)
316
327
  else
317
328
  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) }
318
329
  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 }
319
330
 
331
+ return preview_stream!(payloads: payloads, sse: false) if preview
332
+
320
333
  assemble_native_chat_stream(payloads: payloads)
321
334
  end
322
335
  end
323
336
 
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
+
324
357
  # SSE dispatches at blank lines, joining every data field with a newline.
325
358
  # Native NDJSON accepts a complete last record without a trailing newline.
326
359
  private_class_method def self.stream_records(opts = {})
@@ -16,6 +16,25 @@ module PWN
16
16
  module Jobs
17
17
  JOBS_DIR = File.join(Dir.home, '.pwn', 'jobs')
18
18
 
19
+ # Do not start the command until its process group is owned and its deadline is still live.
20
+ # FD 3 reports launch failures only; successful exec closes it before any job code runs.
21
+ GRAPH_LAUNCH = <<~RUBY
22
+ status = IO.for_fd(3)
23
+ status.close_on_exec = true
24
+ exit! 124 unless STDIN.getbyte == 1
25
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= Float(ARGV.fetch(0))
26
+ status.syswrite('timeout')
27
+ exit! 124
28
+ end
29
+ begin
30
+ exec(ARGV.fetch(1))
31
+ rescue SystemCallError => e
32
+ status.syswrite(e.errno.to_s)
33
+ exit! 127
34
+ end
35
+ RUBY
36
+ private_constant :GRAPH_LAUNCH
37
+
19
38
  public_class_method def self.required_bins
20
39
  []
21
40
  end
@@ -209,8 +228,6 @@ module PWN
209
228
  Thread.new do
210
229
  timeout = (job[:timeout] || opts[:timeout]).to_f
211
230
  timeout = 3_600 if timeout <= 0
212
- out = err = ''
213
- st = nil
214
231
  signaled = false
215
232
  notify = lambda do
216
233
  next if signaled
@@ -219,12 +236,10 @@ module PWN
219
236
  started << true
220
237
  end
221
238
  begin
222
- Timeout.timeout(timeout) do
223
- out, err, st = capture_graph(command: job[:command].to_s, dir: dir, groups: groups, started: notify)
224
- end
239
+ out, err, st = capture_graph(command: job[:command].to_s, dir: dir, groups: groups, started: notify, timeout: timeout)
225
240
  { id: job[:id], ok: st.success?, stdout: out, stderr: err, exit: st.exitstatus }
226
241
  rescue Timeout::Error
227
- { id: job[:id], ok: false, stdout: out, stderr: 'timeout', exit: 124, timeout: true }
242
+ { id: job[:id], ok: false, stdout: '', stderr: 'timeout', exit: 124, timeout: true }
228
243
  ensure
229
244
  notify.call
230
245
  end
@@ -250,29 +265,46 @@ module PWN
250
265
  end
251
266
 
252
267
  private_class_method def self.capture_graph(opts = {})
253
- Open3.popen3(opts[:command], chdir: opts[:dir], pgroup: true) do |stdin, stdout, stderr, waiter|
254
- stdin.close
255
- Array(opts[:groups]) << waiter.pid
256
- opts[:started]&.call
257
- readers = [Thread.new { stdout.read }, Thread.new { stderr.read }]
258
- begin
259
- [readers[0].value, readers[1].value, waiter.value]
260
- ensure
261
- if waiter.alive? || readers.any?(&:alive?)
262
- begin
263
- Process.kill('KILL', -waiter.pid)
264
- rescue Errno::ESRCH, Errno::EPERM
265
- nil
266
- end
267
- end
268
- readers.each do |thread|
269
- thread.kill if thread.alive?
270
- thread.join
271
- end
268
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + opts.fetch(:timeout)
269
+ launcher = [RbConfig.ruby, '--disable=gems,rubyopt', '-e', GRAPH_LAUNCH, '--', deadline.to_s, opts.fetch(:command)]
270
+ IO.pipe do |status, writer|
271
+ Open3.popen3(*launcher, 3 => writer, chdir: opts[:dir], pgroup: true) do |stdin, stdout, stderr, waiter|
272
+ writer.close
273
+ capture_owned_graph(opts.merge(deadline: deadline, stdin: stdin, outputs: [stdout, stderr], waiter: waiter, status: status))
272
274
  end
273
275
  end
274
276
  end
275
277
 
278
+ private_class_method def self.capture_owned_graph(opts = {})
279
+ waiter = opts.fetch(:waiter)
280
+ deadline = opts.fetch(:deadline)
281
+ readers = []
282
+ finished = false
283
+ opts.fetch(:groups) << waiter.pid
284
+ opts.fetch(:started).call
285
+ raise Timeout::Error if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
286
+
287
+ opts[:stdin].write("\x01")
288
+ opts[:stdin].close
289
+ readers = opts[:outputs].map { |io| Thread.new { io.read } }
290
+ [*readers, waiter].each do |thread|
291
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
292
+ raise Timeout::Error unless remaining.positive? && thread.join(remaining)
293
+ end
294
+ finished = true
295
+ status = opts[:status].read
296
+ raise Timeout::Error if status == 'timeout'
297
+ raise SystemCallError.new(opts[:command], Integer(status)) unless status.empty?
298
+
299
+ [readers[0].value, readers[1].value, waiter.value]
300
+ ensure
301
+ cancel_graph(groups: [waiter.pid]) if waiter && !finished
302
+ readers&.each do |thread|
303
+ thread.kill if thread.alive?
304
+ thread.join
305
+ end
306
+ end
307
+
276
308
  private_class_method def self.cancel_graph(opts = {})
277
309
  Array(opts[:groups]).uniq.each do |pid|
278
310
  Process.kill('KILL', -pid)
@@ -273,6 +273,7 @@ module PWN
273
273
  # Cancellation never raises asynchronously into a tool.
274
274
  class Control < PWN::AI::Agent::Loop::Steering
275
275
  class Stopped < Exception; end # rubocop:disable Lint/InheritException
276
+ class PreviewShown < Stopped; end
276
277
 
277
278
  def stopping?
278
279
  @stopping == true
@@ -769,6 +770,19 @@ module PWN
769
770
  %i[pwn_ai_session_id pwn_ai_debug pwn_ai_trace pwn_ai_speak pwn_ai_agent].to_h { |key| [key, @pry.config.public_send(key)] }
770
771
  end
771
772
 
773
+ def with_stream_preview(events)
774
+ previous = Thread.current[:pwn_openwebui_preview]
775
+ Thread.current[:pwn_openwebui_preview] = lambda do |text, pending|
776
+ visible = text.gsub(/[\x00-\x08\x0B-\x1F\x7F-\u009F]/, '')
777
+ events << [:assistant, visible] unless visible.empty?
778
+ status = pending ? 'A requested action was not processed.' : 'No actions from this reply were processed.'
779
+ raise Control::PreviewShown, "Open WebUI reply recovered for display only. #{status} This turn has ended."
780
+ end
781
+ yield
782
+ ensure
783
+ Thread.current[:pwn_openwebui_preview] = previous
784
+ end
785
+
772
786
  def mission_request_child(data, writer, commands)
773
787
  request, generation, session_id, title_config = data.values_at(:request, :generation, :session_id, :title_config)
774
788
  events = MissionEvents.new(writer, generation)
@@ -797,14 +811,18 @@ module PWN
797
811
  events << [:result, result.to_s]
798
812
  end
799
813
  end
800
- final = PWN::AI::Agent::Loop.run(request: request, session_id: session_id,
801
- enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets),
802
- on_tool: on_tool, steering: control, debug: @pry.config.pwn_ai_debug,
803
- trace: @pry.config.pwn_ai_trace, debug_tee: output)
814
+ final = with_stream_preview(events) do
815
+ PWN::AI::Agent::Loop.run(request: request, session_id: session_id,
816
+ enabled_toolsets: PWN::Env.dig(:ai, :agent, :toolsets),
817
+ on_tool: on_tool, steering: control, debug: @pry.config.pwn_ai_debug,
818
+ trace: @pry.config.pwn_ai_trace, debug_tee: output)
819
+ end
804
820
  promoted = Thread.current[:pwn_thinking_promoted] && final.to_s.strip == Thread.current[:pwn_last_thinking].to_s.strip
805
821
  events << [:assistant, final.to_s] unless promoted
806
822
  events << [:session_title, PWN::Sessions.refresh_title(session_id: session_id, ai_config: title_config, on_error: ->(kind) { events << [:warning, "Session title refresh unavailable (#{kind}); previous title retained."] })]
807
823
  end
824
+ rescue Control::PreviewShown => e
825
+ events << [:warning, e.message]
808
826
  rescue StandardError, Interrupt, Control::Stopped => e
809
827
  warning = if e.respond_to?(:http_code) && e.http_code == 403
810
828
  'Access denied (HTTP 403). Check that your account can use the selected model and endpoint.'
data/lib/pwn/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PWN
4
- VERSION = '0.5.800'
4
+ VERSION = '0.5.803'
5
5
  end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+ require 'json'
5
+ require 'open3'
6
+
7
+ RSpec.describe 'rake spec timing output' do
8
+ it 'prints one timed stdout row per selected example and keeps failure diagnostics' do
9
+ Dir.mktmpdir('pwn-rake-timing') do |dir|
10
+ file = File.join(dir, 'timing_spec.rb')
11
+ report = File.join(dir, 'results.json')
12
+ File.write(file, <<~RUBY)
13
+ require 'spec_helper'
14
+ RSpec.configure { |c| c.add_formatter('json', ENV.fetch('TIMING_REPORT')) }
15
+ RSpec.describe 'formatter fixture' do
16
+ it 'passes', :measured do
17
+ sleep 0.01
18
+ STDOUT.puts 'fixture output must stay hidden'
19
+ end
20
+ it('fails', :measured) { raise 'timing fixture failure' }
21
+ it('is pending', :measured)
22
+ it('is filtered out') { raise 'unexpected execution' }
23
+ end
24
+ RUBY
25
+ env = {
26
+ 'SPEC' => file, 'PWN_SPEC_VERBOSE' => nil, 'TIMING_REPORT' => report,
27
+ 'SPEC_OPTS' => '--tag measured --order defined'
28
+ }
29
+ stdout, stderr, status = Open3.capture3(env, RbConfig.ruby, Gem.bin_path('rake', 'rake'), 'spec', chdir: File.expand_path('../..', __dir__))
30
+ expect(status.exitstatus).to eq(1), stderr
31
+ results = JSON.parse(File.read(report)).fetch('examples')
32
+ expect(results.map { |ex| ex.fetch('status') }).to eq(%w[passed failed pending])
33
+ expect(results.first.fetch('run_time')).to be >= 0.01
34
+ rows = results.map.with_index(1) do |ex, n|
35
+ format("[#{n}/3] #{file}:#{ex.fetch('line_number')} %<seconds>.6fs", seconds: ex.fetch('run_time'))
36
+ end
37
+ expect(stdout.lines.map(&:chomp).grep(%r{^\[\d+/})).to eq(rows)
38
+ expect(stdout).not_to include('fixture output must stay hidden')
39
+ expect(stdout).not_to match(/^[.F*]+$/)
40
+ expect(stdout.index('timing fixture failure')).to be < stdout.index(rows.last)
41
+ expect(stdout).to include('3 examples, 1 failure, 1 pending')
42
+ end
43
+ end
44
+ end
45
+
46
+ RSpec.describe GateFailureFormatter do
47
+ it 'colors only the duration on a terminal, using the unrounded runtime for both thresholds' do
48
+ stream = StringIO.new
49
+ allow(stream).to receive(:tty?).and_return(true)
50
+ allow(RSpec.configuration).to receive(:color_mode).and_return(:automatic)
51
+ allow(ENV).to receive(:[]).and_call_original
52
+ allow(ENV).to receive(:[]).with('NO_COLOR').and_return(nil)
53
+ formatter = described_class.new(stream)
54
+ cases = [[0.9999999, 32], [1.0, 33], [5.0, 33], [10.0, 33], [10.0000001, 31]]
55
+ formatter.start(RSpec::Core::Notifications::StartNotification.new(cases.size, 0))
56
+ expected = cases.map.with_index(1) do |(seconds, code), n|
57
+ result = instance_double(RSpec::Core::Example::ExecutionResult, run_time: seconds)
58
+ example = instance_double(RSpec::Core::Example, metadata: { absolute_file_path: __FILE__, line_number: n }, execution_result: result)
59
+ formatter.example_finished(RSpec::Core::Notifications::ExampleNotification.new(example))
60
+ format("[#{n}/#{cases.size}] #{__FILE__}:#{n} \e[#{code}m%<seconds>.6fs\e[0m", seconds: seconds)
61
+ end
62
+ expect(stream.string.lines.map(&:chomp)).to eq(expected)
63
+ end
64
+ end
@@ -344,3 +344,38 @@ describe PWN::AI::OpenWebUI do
344
344
  expect(described_class).not_to respond_to(:get_plan_usage)
345
345
  end
346
346
  end
347
+
348
+ describe PWN::AI::OpenWebUI, 'binary stream display recovery' do
349
+ let(:previews) { [] }
350
+
351
+ around do |example|
352
+ previous = Thread.current[:pwn_openwebui_preview]
353
+ Thread.current[:pwn_openwebui_preview] = ->(text, pending) { previews << [text, pending] }
354
+ example.run
355
+ ensure
356
+ Thread.current[:pwn_openwebui_preview] = previous
357
+ end
358
+
359
+ it 'recovers only visible assistant text, without returning a provider response' do
360
+ event = JSON.generate(message: { role: 'assistant', thinking: 'private', content: 'Café' }, done: true)
361
+ wire = "\uFEFF#{event}".b.freeze
362
+ expect { described_class.send(:assemble_openwebui_stream, body: wire, rest_call: 'ollama/api/chat') }.to raise_error(RuntimeError, /display.only/i)
363
+ expect(previews).to eq([['Café', false]])
364
+ expect(wire.encoding).to eq(Encoding::BINARY)
365
+ end
366
+
367
+ it 'reports an SSE action without displaying its arguments or returning it to the caller' do
368
+ delta = { role: 'assistant', content: 'Résumé', function_call: { name: 'fixture', arguments: 'private' } }
369
+ event = JSON.generate(choices: [{ delta: delta, finish_reason: 'function_call' }])
370
+ wire = "data: #{event}\r\n\r\ndata: [DONE]\r\n\r\n".b
371
+ expect { described_class.send(:assemble_openwebui_stream, body: wire, rest_call: 'api/v1/chat/completions') }.to raise_error(RuntimeError, /display.only/i)
372
+ expect(previews).to eq([['Résumé', true]])
373
+ end
374
+
375
+ it 'does not preview invalid bytes or an incomplete reply' do
376
+ wire = JSON.generate(message: { content: 'Café' }, done: false).b
377
+ expect { described_class.send(:assemble_openwebui_stream, body: wire + "\xFF".b, rest_call: 'ollama/api/chat') }.to raise_error(RuntimeError, /invalid UTF-8/)
378
+ expect { described_class.send(:assemble_openwebui_stream, body: wire, rest_call: 'ollama/api/chat') }.to raise_error(RuntimeError, /incomplete/)
379
+ expect(previews).to be_empty
380
+ end
381
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'spec_helper'
4
+ require 'shellwords'
4
5
  require 'tmpdir'
5
6
 
6
7
  RSpec.describe PWN::Plugins::DAOLDAP do
@@ -286,11 +287,34 @@ RSpec.describe PWN::Plugins::BinaryParser do
286
287
  end
287
288
 
288
289
  RSpec.describe PWN::Plugins::Jobs do
289
- it '[B025] terminates a timed-out graph command before its later write' do
290
- Dir.mktmpdir('pwn-graph-deadline-') do |dir|
291
- graph = described_class.graph(artifact_dir: dir, jobs: [{ id: 'slow', command: 'sleep 0.4; printf late > marker; sleep 0.5', timeout: 0.05 }])
292
- expect(graph[:jobs]['slow']).to include(timeout: true, exit: 124)
293
- expect(File.exist?(File.join(dir, 'marker'))).to be(false)
290
+ %i[capture spawn_handoff].each do |phase|
291
+ it "[B025] terminates a timed-out graph command before its later write (#{phase})" do
292
+ Dir.mktmpdir('pwn-graph-deadline-') do |dir|
293
+ File.write(File.join(dir, 'slow.rb'), <<~RUBY)
294
+ require 'timeout'
295
+ Timeout.timeout(5) { sleep 0.01 until File.exist?('release') }
296
+ File.write('marker', 'late')
297
+ RUBY
298
+ waiter = nil
299
+ allow(Open3).to receive(:popen3).and_wrap_original do |open, *args, **opts, &capture|
300
+ open.call(*args, **opts) do |*handles|
301
+ waiter = handles.last
302
+ if phase == :spawn_handoff
303
+ sleep 0.1 # The deadline expires while Open3 still owns the handles.
304
+ File.write(File.join(dir, 'release'), 'go')
305
+ waiter.join(0.3) # An unguarded payload can write and exit before capture is called.
306
+ end
307
+ capture.call(*handles)
308
+ ensure
309
+ # Also expose a survivor of normal capture cleanup before Open3 joins it.
310
+ File.write(File.join(dir, 'release'), 'go')
311
+ end
312
+ end
313
+ graph = described_class.graph(artifact_dir: dir, jobs: [{ id: 'slow', command: Shellwords.join([RbConfig.ruby, 'slow.rb']), timeout: 0.05 }])
314
+ expect(graph[:jobs]['slow']).to include(ok: false, timeout: true, exit: 124)
315
+ expect(File.exist?(File.join(dir, 'marker'))).to be(false)
316
+ expect(waiter.value).to be_signaled.or have_attributes(exitstatus: 124)
317
+ end
294
318
  end
295
319
  end
296
320
  end
@@ -2812,6 +2812,54 @@ describe 'pwn-ai curses launch' do # rubocop:disable Metrics/BlockLength -- publ
2812
2812
  expect(events.none? { |type, *| type == :assistant }).to be(true)
2813
2813
  end
2814
2814
 
2815
+ it 'shows a split UTF-8 Open WebUI preview once without returning actions to the worker' do
2816
+ require 'rest-client'
2817
+ PWN::Env[:ai] = { active: :openwebui, openwebui: { model: 'fixture', base_uri: 'https://example.invalid', key: 'fixture-key' }, agent: { toolsets: [], plan_first: false } }
2818
+ calls = File.join(@tmp, 'preview-calls')
2819
+ answer = 'Café — ready.'
2820
+ msg = { role: 'assistant', content: answer, tool_calls: [{ function: { name: 'fixture', arguments: { value: 'private-fixture' } } }] }
2821
+ wire = JSON.generate(message: msg, done: true).b
2822
+ cut = wire.index('é'.b) + 1
2823
+ allow(PWN::AI::Router).to receive(:summarize).and_return('{"title":"Preview","summary":"A text preview."}')
2824
+ allow(PWN::AI::OpenWebUI).to receive(:chat_with_tools).and_wrap_original do |chat, opts|
2825
+ chat.call(opts.merge(tools: [{ type: 'function', function: { name: 'fixture', parameters: { type: 'object' } } }]))
2826
+ File.open(calls, 'a') { |file| file.puts 'returned to caller' }
2827
+ raise 'Unexpected normal return'
2828
+ end
2829
+ allow(PWN::Plugins::TransparentBrowser).to receive(:open).and_return(browser: RestClient)
2830
+ allow(RestClient::Request).to receive(:execute) do |args|
2831
+ next '{}' if args.fetch(:url).end_with?('/show')
2832
+
2833
+ File.open(calls, 'a') { |file| file.puts 'read' }
2834
+ response = double('offline stream', code: '200')
2835
+ allow(response).to receive(:read_body).and_yield(wire.byteslice(0, cut)).and_yield(wire.byteslice(cut..))
2836
+ args.fetch(:block_response).call(response)
2837
+ end
2838
+ allow(PWN::AI::Agent::Dispatch).to receive(:call) do
2839
+ File.open(calls, 'a') { |file| file.puts 'unexpected dispatch' }
2840
+ raise 'Action must not be dispatched'
2841
+ end
2842
+ launch("what color is a lemon?\n".chars) { "\u0004" unless @console.send(:busy?) }
2843
+ events = @console.instance_variable_get(:@timeline)
2844
+ expect(events.filter_map { |type, text, *| text if type == :assistant }).to contain_exactly(answer)
2845
+ expect(events.filter_map { |type, text, *| text if type == :warning }).to contain_exactly(a_string_matching(/action.*not processed/i))
2846
+ expect(events.to_s).not_to include('private-fixture')
2847
+ expect(File.readlines(calls, chomp: true)).to eq(['read'])
2848
+ end
2849
+
2850
+ it 'states that instructions in preview text were not run even without structured actions' do
2851
+ console = PWN::Plugins::REPL::AIConsole::Console.new(pry: Pry.new, input: StringIO.new, curses: nil, getch: nil)
2852
+ events = []
2853
+ text = 'Please highlight the word café.'
2854
+ wire = JSON.generate(message: { role: 'assistant', content: text }, done: true).b
2855
+ expect do
2856
+ console.send(:with_stream_preview, events) do
2857
+ PWN::AI::OpenWebUI.send(:assemble_openwebui_stream, body: wire, rest_call: 'ollama/api/chat')
2858
+ end
2859
+ end.to raise_error(PWN::Plugins::REPL::AIConsole::Control::PreviewShown, /No actions from this reply were processed/)
2860
+ expect(events).to eq([[:assistant, text]])
2861
+ end
2862
+
2815
2863
  it 'delivers and saves a split UTF-8 text reply in a session with debugging off' do
2816
2864
  require 'rest-client'
2817
2865
  PWN::Env[:ai] = { active: :ollama, ollama: { model: 'fixture', base_uri: 'https://example.invalid' }, agent: { toolsets: [], plan_first: false } }
@@ -18,6 +18,7 @@ describe PWN::Plugins::REPL, 'mesh DM transport replay' do
18
18
  packet = nil
19
19
  allow(Meshtastic::Serial).to receive(:send_to_radio) do |opts|
20
20
  packet = Meshtastic::ToRadio.decode(opts[:to_radio]).packet
21
+ sender[:proto_data] << { packet: { decoded: { portnum: :ROUTING_APP, request_id: packet.id, payload: { error_reason: :NONE } } } }
21
22
  end
22
23
 
23
24
  described_class.pwn_mesh_dispatch_slash!(request: '/msg !bbccddee hello receiver', env: env, pry: :fixture)
@@ -27,6 +27,8 @@ describe PWN::Plugins::REPL, 'mesh DM key exchange' do
27
27
  expect(packet.decoded.want_response).to eq(true)
28
28
  expect(Meshtastic::User.decode(packet.decoded.payload).public_key).to eq('a' * 32)
29
29
  obj[:proto_data] << { packet: { from: 0xbbccddee, decoded: { portnum: 4, payload: Meshtastic::User.new(remote_user).to_proto } } }
30
+ elsif packet.decoded.portnum == :TEXT_MESSAGE_APP
31
+ obj[:proto_data] << { packet: { decoded: { portnum: :ROUTING_APP, request_id: packet.id, payload: { error_reason: :NONE } } } }
30
32
  end
31
33
  end
32
34
  described_class.send(:mesh_send_text, env: env, obj: obj, to: '!bbccddee', text: 'private', channel_name: 'LongFast')
@@ -60,6 +62,7 @@ describe PWN::Plugins::REPL, 'mesh DM key exchange' do
60
62
  packet = Meshtastic::ToRadio.decode(opts[:to_radio]).packet
61
63
  expect(packet.pki_encrypted).to eq(true)
62
64
  expect(packet.decoded.payload).to eq('retained text')
65
+ obj[:proto_data] << { packet: { decoded: { portnum: :ROUTING_APP, request_id: packet.id, payload: { error_reason: :NONE } } } }
63
66
  end
64
67
  described_class.send(:pwn_mesh_run_msg, env: env, args: [])
65
68
  expect(PWN::MeshPendingDm).to be_nil
@@ -748,6 +748,7 @@ describe PWN::Plugins::REPL do # rubocop:disable Metrics/BlockLength
748
748
  require 'meshtastic'
749
749
  obj = { proto_data: [{ channel: { index: 3, role: :SECONDARY, settings: { name: 'LongFast' } } }] }
750
750
  env = { transport: 'serial', channel: { active: 'LongFast', LongFast: { channel_num: 99 } } }
751
+ allow(described_class).to receive(:mesh_wait_tx_slot).and_return(:ok)
751
752
  expect(Meshtastic::Serial).to receive(:send_text).with(hash_including(channel: 3))
752
753
  described_class.send(:mesh_send_text, env: env, obj: obj, channel: 99, text: 'slot three')
753
754
  end
@@ -764,6 +765,7 @@ describe PWN::Plugins::REPL do # rubocop:disable Metrics/BlockLength
764
765
  transport: 'serial',
765
766
  channel: { active: 'LongFast', LongFast: { psk: 'AQ==', channel_num: 8, topic: '2/e/LongFast/#' } }
766
767
  }
768
+ allow(described_class).to receive(:mesh_wait_tx_slot).and_return(:ok)
767
769
  expect(Meshtastic::Serial).to receive(:send_text).with(hash_including(channel: 2, text: 'hello LongFast'))
768
770
  described_class.send(:mesh_send_text, env: env, obj: obj, text: 'hello LongFast')
769
771
  end
@@ -781,6 +783,7 @@ describe PWN::Plugins::REPL do # rubocop:disable Metrics/BlockLength
781
783
  transport: 'serial',
782
784
  channel: { active: 'LongFast', LongFast: { psk: 'AQ==', channel_num: 8 } }
783
785
  }
786
+ allow(described_class).to receive(:mesh_wait_tx_slot).and_return(:ok)
784
787
  expect(Meshtastic::Serial).to receive(:send_text).with(hash_including(channel: 2, text: 'hello LongFast'))
785
788
  described_class.send(:mesh_send_text, env: env, obj: obj, text: 'hello LongFast')
786
789
  end
@@ -439,6 +439,8 @@ describe PWN::SDR::Decoder::Base do
439
439
  end
440
440
 
441
441
  it 'emits IQ frames before pipe EOF and exits on EOF without ENTER' do
442
+ # Keep interactive mode on, but model an idle keyboard, not the rake terminal.
443
+ allow($stdin).to receive(:read_nonblock).with(1, exception: false).and_return(:wait_readable)
442
444
  reader, writer = IO.pipe
443
445
  output = StringIO.new
444
446
  received = Queue.new
@@ -454,7 +456,7 @@ describe PWN::SDR::Decoder::Base do
454
456
  expect(frame[:samples].length).to eq(2)
455
457
  expect(writer).not_to be_closed
456
458
  writer.close
457
- Timeout.timeout(2) { worker.value }
459
+ expect(Timeout.timeout(2) { worker.value }).to include(reason: :eof, capture_complete: true)
458
460
  expect(JSON.parse(output.string)['samples']).to eq(frame[:samples])
459
461
  expect(reader).to be_closed
460
462
  ensure
@@ -392,6 +392,9 @@ end
392
392
  describe PWN::Sessions do
393
393
  include_context 'pwn tmp sandbox'
394
394
 
395
+ # Dependency discovery uses Dir.home independently of the session directory.
396
+ before { allow(Dir).to receive(:home).and_return(@tmp) }
397
+
395
398
  it 'caps provisional titles at seven Unicode-whitespace words without shortening requests' do
396
399
  sid = described_class.create(id: 'seven_words')[:id]
397
400
  request = "Investigate\u00a0café\u2003login failures and repair expired certificates today"
@@ -17,6 +17,8 @@ RSpec.shared_context 'offline MFA browser' do |selectors|
17
17
  @authenticated = false
18
18
  @otp_written = false
19
19
  @form_ready = false
20
+ # The fake browser updates its URL on click; it needs no redirect delay.
21
+ allow(described_class).to receive(:sleep).with(3).and_return(3)
20
22
  stub_const('PWN::Plugins::YubiKey', Module.new)
21
23
  allow(PWN::Plugins::YubiKey).to receive(:oath_code) do
22
24
  raise 'OATH requested before the MFA form was ready' unless @form_ready
data/spec/spec_helper.rb CHANGED
@@ -12,7 +12,7 @@ Dir[File.join(__dir__, 'support', '**', '*.rb')].reject { |f| f.include?('/suppo
12
12
  # RSpec binds its formatter to $stdout at configure-time (before any example
13
13
  # runs), so redirecting $stdout / $stderr *inside* each example swallows any
14
14
  # incidental `puts` / `print` / `p` / `warn` emitted by the code under test
15
- # WITHOUT affecting the progress dots or failure reports.
15
+ # WITHOUT affecting the formatter's timing rows or failure reports.
16
16
  #
17
17
  # Escape hatches:
18
18
  # - `PWN_SPEC_VERBOSE=1 rake spec` → no redirection at all
@@ -1,14 +1,39 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rspec/core/formatters/base_formatter'
3
+ require 'rspec/core/formatters/base_text_formatter'
4
4
 
5
- # The normal final summary is still printed. Emit failures immediately too,
6
- # so a later killed example cannot erase the only actionable diagnostic.
7
- class GateFailureFormatter < RSpec::Core::Formatters::BaseFormatter
8
- RSpec::Core::Formatters.register self, :example_failed
5
+ # Show each example's elapsed time, retaining immediate failures and the normal summary.
6
+ class GateFailureFormatter < RSpec::Core::Formatters::BaseTextFormatter
7
+ RSpec::Core::Formatters.register self, :example_finished, :example_failed
8
+
9
+ def start(notification)
10
+ super
11
+ @completed = 0
12
+ end
13
+
14
+ def example_finished(notification)
15
+ example = notification.example
16
+ @completed += 1
17
+ location = "#{example.metadata.fetch(:absolute_file_path)}:#{example.metadata.fetch(:line_number)}"
18
+ output.puts "[#{@completed}/#{@example_count}] #{location} #{formatted_duration(example.execution_result.run_time)}"
19
+ end
9
20
 
10
21
  def example_failed(notification)
11
22
  output.puts notification.fully_formatted(1)
12
23
  output.flush
13
24
  end
25
+
26
+ private
27
+
28
+ def formatted_duration(seconds)
29
+ text = format('%<seconds>.6fs', seconds: seconds)
30
+ return text unless ENV['NO_COLOR'].to_s.empty? && RSpec.configuration.color_enabled?(output)
31
+
32
+ code = case seconds
33
+ when ...1 then 32 # green
34
+ when ..10 then 33 # yellow
35
+ else 31 # red
36
+ end
37
+ "\e[#{code}m#{text}\e[0m"
38
+ end
14
39
  end
@@ -1423,6 +1423,7 @@
1423
1423
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.openwebui_rest_call Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.openwebui_rest_call`: Supported Method Parameters\n\nopenwebui_rest_call(\n\nhttp_method: 'optional HTTP method (defaults to GET)',\nrest_call: 'required rest call path relative to base_uri',\nparams: 'optional params passed in the URI or HTTP Headers',\nhttp_body: 'optional HTTP body sent in HTTP methods that support it e.g. POST',\ntimeout: 'optional timeout in seconds (defaults to 900)',\nspinner: 'optional - display spinner (defaults to false)'\n\n)\n"}]}
1424
1424
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.parse_stream_payload Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.parse_stream_payload`: "}]}
1425
1425
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.parse_tool_arguments_object Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.parse_tool_arguments_object`: "}]}
1426
+ {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.preview_stream! Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.preview_stream!`: "}]}
1426
1427
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.real_config_value? Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.real_config_value?`: "}]}
1427
1428
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.server_tool_ids Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.server_tool_ids`: "}]}
1428
1429
  {"messages":[{"role":"user","content":"PWN::AI::OpenWebUI.stream_records Usage"},{"role":"assistant","content":"`PWN::AI::OpenWebUI.stream_records`: "}]}
@@ -3166,6 +3167,7 @@
3166
3167
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.authors Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.authors`: "}]}
3167
3168
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.cancel_graph Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.cancel_graph`: "}]}
3168
3169
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.capture_graph Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.capture_graph`: "}]}
3170
+ {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.capture_owned_graph Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.capture_owned_graph`: "}]}
3169
3171
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.graph Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.graph`: "}]}
3170
3172
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.harvest Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.harvest`: "}]}
3171
3173
  {"messages":[{"role":"user","content":"PWN::Plugins::Jobs.help Usage"},{"role":"assistant","content":"`PWN::Plugins::Jobs.help`: "}]}
@@ -3711,6 +3713,7 @@
3711
3713
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.toggle_verbose Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.toggle_verbose`: "}]}
3712
3714
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.tone Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.tone`: "}]}
3713
3715
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.width Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.width`: "}]}
3716
+ {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.with_stream_preview Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.with_stream_preview`: "}]}
3714
3717
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.wrap Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.wrap`: "}]}
3715
3718
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Console.wrap_command Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Console.wrap_command`: "}]}
3716
3719
  {"messages":[{"role":"user","content":"PWN::Plugins::REPL::AIConsole::Control.checkpoint Usage"},{"role":"assistant","content":"`PWN::Plugins::REPL::AIConsole::Control.checkpoint`: "}]}
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pwn
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.800
4
+ version: 0.5.803
5
5
  platform: ruby
6
6
  authors:
7
7
  - 0day Inc.
@@ -128,7 +128,7 @@ dependencies:
128
128
  -
129
129
  - "="
130
130
  - !ruby/object:Gem::Version
131
- version: 8.1.0
131
+ version: 8.1.1
132
132
  type: :runtime
133
133
  prerelease: false
134
134
  version_requirements: !ruby/object:Gem::Requirement
@@ -136,7 +136,7 @@ dependencies:
136
136
  -
137
137
  - "="
138
138
  - !ruby/object:Gem::Version
139
- version: 8.1.0
139
+ version: 8.1.1
140
140
  - !ruby/object:Gem::Dependency
141
141
  name: bson
142
142
  requirement: !ruby/object:Gem::Requirement
@@ -592,7 +592,7 @@ dependencies:
592
592
  -
593
593
  - "="
594
594
  - !ruby/object:Gem::Version
595
- version: 0.0.193
595
+ version: 0.0.194
596
596
  type: :development
597
597
  prerelease: false
598
598
  version_requirements: !ruby/object:Gem::Requirement
@@ -600,7 +600,7 @@ dependencies:
600
600
  -
601
601
  - "="
602
602
  - !ruby/object:Gem::Version
603
- version: 0.0.193
603
+ version: 0.0.194
604
604
  - !ruby/object:Gem::Dependency
605
605
  name: metasm
606
606
  requirement: !ruby/object:Gem::Requirement
@@ -6883,6 +6883,7 @@ files:
6883
6883
  - spec/integration/native_ruby_helpers_spec.rb
6884
6884
  - spec/integration/persistence_roundtrip_spec.rb
6885
6885
  - spec/integration/prompt_builder_spec.rb
6886
+ - spec/integration/rake_example_timing_spec.rb
6886
6887
  - spec/integration/readme_security_spec.rb
6887
6888
  - spec/integration/reinforced_feedback_loop_spec.rb
6888
6889
  - spec/integration/reports_spec.rb