yaic 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. checksums.yaml +4 -4
  2. data/.claude/ralph/bin/dump-pid.sh +3 -0
  3. data/.claude/ralph/bin/kill-claude +6 -0
  4. data/.claude/ralph/bin/start-ralph +44 -0
  5. data/.claude/ralph/bin/stop-hook.sh +9 -0
  6. data/.claude/ralph/bin/stop-ralph +17 -0
  7. data/.claude/ralph/prompt.md +216 -0
  8. data/.claude/settings.json +26 -0
  9. data/.gitmodules +3 -0
  10. data/.ruby-version +1 -1
  11. data/CHANGELOG.md +9 -0
  12. data/CLAUDE.md +70 -0
  13. data/README.md +117 -17
  14. data/Rakefile +8 -0
  15. data/devenv.lock +2 -2
  16. data/devenv.nix +1 -0
  17. data/docs/agents/data-model.md +150 -0
  18. data/docs/agents/ralph/features/01-message-parsing.md.done +160 -0
  19. data/docs/agents/ralph/features/01-tcpsocket-refactor.md.done +109 -0
  20. data/docs/agents/ralph/features/02-connection-socket.md.done +138 -0
  21. data/docs/agents/ralph/features/02-simplified-client-api.md.done +306 -0
  22. data/docs/agents/ralph/features/03-registration.md.done +147 -0
  23. data/docs/agents/ralph/features/04-ping-pong.md.done +109 -0
  24. data/docs/agents/ralph/features/05-event-system.md.done +167 -0
  25. data/docs/agents/ralph/features/06-privmsg-notice.md.done +163 -0
  26. data/docs/agents/ralph/features/07-join-part.md.done +190 -0
  27. data/docs/agents/ralph/features/08-quit.md.done +118 -0
  28. data/docs/agents/ralph/features/09-nick-change.md.done +109 -0
  29. data/docs/agents/ralph/features/10-topic.md.done +145 -0
  30. data/docs/agents/ralph/features/11-kick.md.done +122 -0
  31. data/docs/agents/ralph/features/12-names.md.done +124 -0
  32. data/docs/agents/ralph/features/13-mode.md.done +174 -0
  33. data/docs/agents/ralph/features/14-who-whois.md.done +188 -0
  34. data/docs/agents/ralph/features/15-client-api.md.done +180 -0
  35. data/docs/agents/ralph/features/16-ssl-test-infrastructure.md.done +50 -0
  36. data/docs/agents/ralph/features/17-github-actions-ci.md.done +70 -0
  37. data/docs/agents/ralph/features/18-brakeman-security-scanning.md.done +67 -0
  38. data/docs/agents/ralph/features/19-fix-qa.md.done +73 -0
  39. data/docs/agents/ralph/features/20-test-optimization.md.done +70 -0
  40. data/docs/agents/ralph/features/21-test-parallelization.md.done +56 -0
  41. data/docs/agents/ralph/features/22-wait-until-pattern.md.done +90 -0
  42. data/docs/agents/ralph/features/23-ping-test-optimization.md.done +46 -0
  43. data/docs/agents/ralph/features/24-blocking-who-whois.md.done +159 -0
  44. data/docs/agents/ralph/features/25-verbose-mode.md.done +166 -0
  45. data/docs/agents/ralph/plans/test-optimization-plan.md +172 -0
  46. data/docs/agents/ralph/progress.md +731 -0
  47. data/docs/agents/todo.md +5 -0
  48. data/lib/yaic/channel.rb +22 -0
  49. data/lib/yaic/client.rb +982 -0
  50. data/lib/yaic/event.rb +35 -0
  51. data/lib/yaic/message.rb +119 -0
  52. data/lib/yaic/message_splitter.rb +51 -0
  53. data/lib/yaic/registration.rb +17 -0
  54. data/lib/yaic/socket.rb +152 -0
  55. data/lib/yaic/source.rb +39 -0
  56. data/lib/yaic/version.rb +1 -1
  57. data/lib/yaic/who_result.rb +17 -0
  58. data/lib/yaic/whois_result.rb +20 -0
  59. data/lib/yaic.rb +14 -1
  60. metadata +53 -3
@@ -0,0 +1,982 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yaic
4
+ class Client
5
+ STALE_TIMEOUT = 180
6
+ DEFAULT_CONNECT_TIMEOUT = 30
7
+ DEFAULT_OPERATION_TIMEOUT = 10
8
+ MAX_HOST_LENGTH = 63
9
+
10
+ EVENT_MAP = {
11
+ "PRIVMSG" => :message,
12
+ "NOTICE" => :notice,
13
+ "JOIN" => :join,
14
+ "PART" => :part,
15
+ "QUIT" => :quit,
16
+ "KICK" => :kick,
17
+ "NICK" => :nick,
18
+ "TOPIC" => :topic,
19
+ "MODE" => :mode
20
+ }.freeze
21
+
22
+ PREFIX_MODES = {
23
+ "@" => :op,
24
+ "+" => :voice,
25
+ "%" => :halfop,
26
+ "~" => :owner,
27
+ "&" => :admin
28
+ }.freeze
29
+
30
+ attr_reader :server
31
+
32
+ def state
33
+ @monitor.synchronize { @state }
34
+ end
35
+
36
+ def isupport
37
+ @monitor.synchronize { @isupport.dup }
38
+ end
39
+
40
+ def last_received_at
41
+ @monitor.synchronize { @last_received_at }
42
+ end
43
+
44
+ def disconnect_reason
45
+ @monitor.synchronize { @disconnect_reason }
46
+ end
47
+
48
+ def channels
49
+ @monitor.synchronize { @channels.dup }
50
+ end
51
+
52
+ def initialize(port:, host: nil, nick: nil, user: nil, realname: nil, password: nil, ssl: false, verify_ssl: true, server: nil, nickname: nil, username: nil, verbose: false, stale_timeout: STALE_TIMEOUT)
53
+ @server = server || host
54
+ @port = port
55
+ @nick = nickname || nick
56
+ @user = username || user || @nick
57
+ @realname = realname || @nick
58
+ @password = password
59
+ @ssl = ssl
60
+ @verify_ssl = verify_ssl
61
+ @verbose = verbose
62
+ @stale_timeout = stale_timeout
63
+
64
+ @socket = nil
65
+ @state = :disconnected
66
+ @isupport = {}
67
+ @nick_attempts = 0
68
+ @last_received_at = nil
69
+ @last_received_clock = nil
70
+ @ping_sent_clock = nil
71
+ @disconnect_reason = nil
72
+ @handlers = {}
73
+ @channels = {}
74
+ @pending_names = {}
75
+ @pending_whois = {}
76
+ @pending_whois_complete = {}
77
+ @pending_who_results = {}
78
+ @pending_who_complete = {}
79
+ @pending_ison = nil
80
+ @pending_ison_complete = false
81
+ @read_thread = nil
82
+ @monitor = Monitor.new
83
+ end
84
+
85
+ def connect(timeout: DEFAULT_CONNECT_TIMEOUT)
86
+ log "Connecting to #{@server}:#{@port}#{" (SSL)" if @ssl}..."
87
+ sock = @monitor.synchronize do
88
+ @disconnect_reason = nil
89
+ @last_received_at = nil
90
+ @last_received_clock = nil
91
+ @ping_sent_clock = nil
92
+ @socket ||= Socket.new(@server, @port, ssl: @ssl, verify_ssl: @verify_ssl)
93
+ end
94
+ sock.connect
95
+ send_registration
96
+ set_state(:registering)
97
+ start_read_loop
98
+ wait_until(timeout: timeout) { connected? }
99
+ log "Connected"
100
+ end
101
+
102
+ def connected?
103
+ @monitor.synchronize { @state == :connected }
104
+ end
105
+
106
+ def disconnect
107
+ close_connection(nil)
108
+ join_read_thread
109
+ end
110
+
111
+ def handle_message(message)
112
+ @monitor.synchronize do
113
+ @last_received_at = Time.now
114
+ @last_received_clock = clock
115
+ end
116
+
117
+ case message.command
118
+ when "PING"
119
+ handle_ping(message)
120
+ when "ERROR"
121
+ handle_server_error(message)
122
+ when "001"
123
+ handle_rpl_welcome(message)
124
+ when "005"
125
+ handle_rpl_isupport(message)
126
+ when "433"
127
+ handle_err_nicknameinuse(message)
128
+ when "JOIN"
129
+ handle_join(message)
130
+ when "PART"
131
+ handle_part(message)
132
+ when "QUIT"
133
+ handle_quit(message)
134
+ when "NICK"
135
+ handle_nick(message)
136
+ when "KICK"
137
+ handle_kick(message)
138
+ when "TOPIC"
139
+ handle_topic(message)
140
+ when "332"
141
+ handle_rpl_topic(message)
142
+ when "333"
143
+ handle_rpl_topicwhotime(message)
144
+ when "353"
145
+ handle_rpl_namreply(message)
146
+ when "366"
147
+ handle_rpl_endofnames(message)
148
+ when "MODE"
149
+ handle_mode(message)
150
+ when "352"
151
+ handle_rpl_whoreply(message)
152
+ when "315"
153
+ handle_rpl_endofwho(message)
154
+ when "311"
155
+ handle_rpl_whoisuser(message)
156
+ when "319"
157
+ handle_rpl_whoischannels(message)
158
+ when "312"
159
+ handle_rpl_whoisserver(message)
160
+ when "317"
161
+ handle_rpl_whoisidle(message)
162
+ when "330"
163
+ handle_rpl_whoisaccount(message)
164
+ when "301"
165
+ handle_rpl_away(message)
166
+ when "318"
167
+ handle_rpl_endofwhois(message)
168
+ when "303"
169
+ handle_rpl_ison(message)
170
+ end
171
+
172
+ emit_events(message)
173
+ end
174
+
175
+ def connection_stale?
176
+ @monitor.synchronize do
177
+ return false if @last_received_at.nil?
178
+ Time.now - @last_received_at > @stale_timeout
179
+ end
180
+ end
181
+
182
+ def on(event_type, &block)
183
+ @monitor.synchronize do
184
+ @handlers[event_type] ||= []
185
+ @handlers[event_type] << block
186
+ end
187
+ self
188
+ end
189
+
190
+ def off(event_type)
191
+ @monitor.synchronize do
192
+ @handlers.delete(event_type)
193
+ end
194
+ self
195
+ end
196
+
197
+ def privmsg(target, text)
198
+ max = MessageSplitter.max_text_bytes(line_length: line_length, command: "PRIVMSG", target: target, prefix_length: source_prefix_length)
199
+ parts = MessageSplitter.split(text, max_bytes: max)
200
+ parts.each do |part|
201
+ message = Message.new(command: "PRIVMSG", params: [target, part])
202
+ write(message.to_s)
203
+ end
204
+ parts
205
+ end
206
+
207
+ alias_method :msg, :privmsg
208
+
209
+ def notice(target, text)
210
+ max = MessageSplitter.max_text_bytes(line_length: line_length, command: "NOTICE", target: target, prefix_length: source_prefix_length)
211
+ parts = MessageSplitter.split(text, max_bytes: max)
212
+ parts.each do |part|
213
+ message = Message.new(command: "NOTICE", params: [target, part])
214
+ write(message.to_s)
215
+ end
216
+ parts
217
+ end
218
+
219
+ def join(channel, key = nil, timeout: DEFAULT_OPERATION_TIMEOUT)
220
+ log "Joining #{channel}..."
221
+ params = key ? [channel, key] : [channel]
222
+ message = Message.new(command: "JOIN", params: params)
223
+ write(message.to_s)
224
+ wait_until(timeout: timeout) { channel_joined?(channel) }
225
+ log "Joined #{channel}"
226
+ end
227
+
228
+ def part(channel, reason = nil, timeout: DEFAULT_OPERATION_TIMEOUT)
229
+ log "Parting #{channel}..."
230
+ params = reason ? [channel, reason] : [channel]
231
+ message = Message.new(command: "PART", params: params)
232
+ write(message.to_s)
233
+ wait_until(timeout: timeout) { !channel_joined?(channel) }
234
+ log "Parted #{channel}"
235
+ end
236
+
237
+ def quit(reason = nil)
238
+ return unless transition_to_disconnected(reason)
239
+
240
+ params = reason ? [reason] : []
241
+ begin
242
+ socket&.write(Message.new(command: "QUIT", params: params).to_s)
243
+ rescue ConnectionError
244
+ nil
245
+ end
246
+ join_read_thread
247
+ finish_disconnect(reason)
248
+ log "Disconnected"
249
+ end
250
+
251
+ def nick(new_nick = nil, timeout: DEFAULT_OPERATION_TIMEOUT)
252
+ return @monitor.synchronize { @nick } if new_nick.nil?
253
+
254
+ old_nick = @monitor.synchronize { @nick }
255
+ message = Message.new(command: "NICK", params: [new_nick])
256
+ write(message.to_s)
257
+ wait_until(timeout: timeout) { @monitor.synchronize { @nick } != old_nick }
258
+ end
259
+
260
+ def topic(channel, new_topic = nil)
261
+ params = new_topic.nil? ? [channel] : [channel, new_topic]
262
+ message = Message.new(command: "TOPIC", params: params)
263
+ write(message.to_s)
264
+ end
265
+
266
+ def kick(channel, nick, reason = nil)
267
+ params = reason ? [channel, nick, reason] : [channel, nick]
268
+ message = Message.new(command: "KICK", params: params)
269
+ write(message.to_s)
270
+ end
271
+
272
+ def names(channel)
273
+ message = Message.new(command: "NAMES", params: [channel])
274
+ write(message.to_s)
275
+ end
276
+
277
+ def mode(target, modes = nil, *args)
278
+ params = [target]
279
+ params << modes if modes
280
+ params.concat(args) unless args.empty?
281
+ message = Message.new(command: "MODE", params: params)
282
+ write(message.to_s)
283
+ end
284
+
285
+ def who(mask, timeout: DEFAULT_OPERATION_TIMEOUT)
286
+ log "Sending WHO #{mask}..."
287
+ @monitor.synchronize do
288
+ @pending_who_results[mask] = []
289
+ @pending_who_complete[mask] = false
290
+ end
291
+
292
+ message = Message.new(command: "WHO", params: [mask])
293
+ write(message.to_s)
294
+
295
+ wait_until(timeout: timeout) { @monitor.synchronize { @pending_who_complete[mask] } }
296
+
297
+ @monitor.synchronize do
298
+ results = @pending_who_results.delete(mask)
299
+ log "WHO complete (#{results.size} results)"
300
+ results
301
+ end
302
+ ensure
303
+ @monitor.synchronize { @pending_who_complete.delete(mask) }
304
+ end
305
+
306
+ def whois(nick, timeout: DEFAULT_OPERATION_TIMEOUT)
307
+ log "Sending WHOIS #{nick}..."
308
+ @monitor.synchronize { @pending_whois_complete[nick] = false }
309
+
310
+ message = Message.new(command: "WHOIS", params: [nick])
311
+ write(message.to_s)
312
+
313
+ wait_until(timeout: timeout) { @monitor.synchronize { @pending_whois_complete[nick] } }
314
+
315
+ @monitor.synchronize do
316
+ result = @pending_whois.delete(nick)
317
+ log "WHOIS complete"
318
+ result
319
+ end
320
+ ensure
321
+ @monitor.synchronize { @pending_whois_complete.delete(nick) }
322
+ end
323
+
324
+ def raw(command)
325
+ write(command)
326
+ end
327
+
328
+ def ison(*nicks, timeout: DEFAULT_OPERATION_TIMEOUT)
329
+ nicks = nicks.flatten
330
+ return [] if nicks.empty?
331
+
332
+ log "Sending ISON #{nicks.join(" ")}..."
333
+ @monitor.synchronize do
334
+ @pending_ison = nil
335
+ @pending_ison_complete = false
336
+ end
337
+
338
+ message = Message.new(command: "ISON", params: [nicks.join(" ")])
339
+ write(message.to_s)
340
+
341
+ wait_until(timeout: timeout) { @monitor.synchronize { @pending_ison_complete } }
342
+
343
+ @monitor.synchronize do
344
+ result = @pending_ison || []
345
+ log "ISON complete (#{result.size} online)"
346
+ result
347
+ end
348
+ ensure
349
+ @monitor.synchronize { @pending_ison_complete = false }
350
+ end
351
+
352
+ private
353
+
354
+ def socket
355
+ @monitor.synchronize { @socket }
356
+ end
357
+
358
+ def line_length
359
+ @monitor.synchronize do
360
+ value = @isupport["LINELEN"]
361
+ value ? value.to_i : 512
362
+ end
363
+ end
364
+
365
+ def source_prefix_length
366
+ @monitor.synchronize do
367
+ @nick.bytesize + @user.bytesize + MAX_HOST_LENGTH + 4
368
+ end
369
+ end
370
+
371
+ def log(message)
372
+ return unless @verbose
373
+ warn "[YAIC] #{message}"
374
+ end
375
+
376
+ def set_state(new_state)
377
+ @monitor.synchronize { @state = new_state }
378
+ end
379
+
380
+ def channel_joined?(channel)
381
+ @monitor.synchronize { @channels.key?(channel) }
382
+ end
383
+
384
+ def wait_until(timeout:)
385
+ deadline = Time.now + timeout
386
+ until yield
387
+ raise ConnectionError, disconnect_reason || "Not connected" if state == :disconnected
388
+ raise Yaic::TimeoutError, "Operation timed out after #{timeout} seconds" if Time.now > deadline
389
+ sleep 0.01
390
+ end
391
+ end
392
+
393
+ def write(line)
394
+ sock = socket
395
+ raise ConnectionError, "Not connected" unless sock
396
+
397
+ sock.write(line)
398
+ rescue ConnectionError => e
399
+ connection_lost(e.message)
400
+ raise
401
+ end
402
+
403
+ def clock
404
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
405
+ end
406
+
407
+ def transition_to_disconnected(reason)
408
+ @monitor.synchronize do
409
+ return false if @state == :disconnected
410
+
411
+ @state = :disconnected
412
+ @disconnect_reason = reason
413
+ true
414
+ end
415
+ end
416
+
417
+ def finish_disconnect(reason)
418
+ socket&.disconnect
419
+ @monitor.synchronize { @channels.clear }
420
+ emit(:disconnect, nil, reason: reason)
421
+ end
422
+
423
+ def close_connection(reason)
424
+ return false unless transition_to_disconnected(reason)
425
+
426
+ finish_disconnect(reason)
427
+ true
428
+ end
429
+
430
+ def connection_lost(reason)
431
+ log "Connection lost: #{reason}" if close_connection(reason)
432
+ end
433
+
434
+ def join_read_thread
435
+ thread = @read_thread
436
+ thread.join(1) if thread && thread != Thread.current
437
+ end
438
+
439
+ def start_read_loop
440
+ @read_thread = Thread.new do
441
+ loop do
442
+ break if state == :disconnected
443
+ process_incoming
444
+ end
445
+ end
446
+ end
447
+
448
+ def process_incoming
449
+ raw = socket.read
450
+ if raw
451
+ message = Message.parse(raw)
452
+ handle_message(message) if message
453
+ else
454
+ check_keepalive
455
+ socket.wait_readable(keepalive_tick)
456
+ end
457
+ rescue ConnectionError => e
458
+ connection_lost(e.message)
459
+ rescue => e
460
+ emit(:error, nil, exception: e)
461
+ end
462
+
463
+ def keepalive_tick
464
+ [@stale_timeout / 4.0, 1].min
465
+ end
466
+
467
+ def check_keepalive
468
+ action = @monitor.synchronize do
469
+ next if @state != :connected || @last_received_clock.nil?
470
+
471
+ now = clock
472
+ half = @stale_timeout / 2.0
473
+ if @ping_sent_clock && @ping_sent_clock > @last_received_clock
474
+ :timeout if now - @ping_sent_clock > half
475
+ elsif now - @last_received_clock > half
476
+ @ping_sent_clock = now
477
+ :ping
478
+ end
479
+ end
480
+
481
+ case action
482
+ when :ping
483
+ write(Message.new(command: "PING", params: ["yaic"]).to_s)
484
+ when :timeout
485
+ connection_lost("Ping timeout: no response from server in #{@stale_timeout} seconds")
486
+ end
487
+ end
488
+
489
+ def send_registration
490
+ if @password
491
+ write(Registration.pass_message(@password).to_s)
492
+ end
493
+ write(Registration.nick_message(@nick).to_s)
494
+ write(Registration.user_message(@user, @realname).to_s)
495
+ end
496
+
497
+ def handle_rpl_welcome(message)
498
+ @monitor.synchronize do
499
+ @nick = message.params[0] if message.params[0]
500
+ end
501
+ set_state(:connected)
502
+ end
503
+
504
+ def handle_rpl_isupport(message)
505
+ @monitor.synchronize do
506
+ message.params[1..-2].each do |param|
507
+ next unless param
508
+
509
+ if param.include?("=")
510
+ key, value = param.split("=", 2)
511
+ @isupport[key] = value
512
+ else
513
+ @isupport[param] = true
514
+ end
515
+ end
516
+ end
517
+ end
518
+
519
+ def handle_err_nicknameinuse(_message)
520
+ new_nick = @monitor.synchronize do
521
+ next unless @state == :registering
522
+
523
+ @nick_attempts += 1
524
+ @nick = "#{@nick.sub(/_+$/, "")}#{"_" * @nick_attempts}"
525
+ end
526
+ write(Registration.nick_message(new_nick).to_s) if new_nick
527
+ end
528
+
529
+ def handle_ping(message)
530
+ token = message.params[0]
531
+ pong = Message.new(command: "PONG", params: [token])
532
+ write(pong.to_s)
533
+ end
534
+
535
+ def handle_server_error(message)
536
+ connection_lost(message.params.last || "Server closed the connection")
537
+ end
538
+
539
+ def handle_join(message)
540
+ channel_name = message.params[0]
541
+ joiner_nick = message.source&.nick
542
+ return unless joiner_nick && channel_name
543
+
544
+ @monitor.synchronize do
545
+ if joiner_nick == @nick
546
+ @channels[channel_name] = Channel.new(channel_name)
547
+ elsif (channel = @channels[channel_name])
548
+ channel.users[joiner_nick] = Set.new
549
+ end
550
+ end
551
+ end
552
+
553
+ def handle_part(message)
554
+ channel_name = message.params[0]
555
+ parter_nick = message.source&.nick
556
+ return unless parter_nick && channel_name
557
+
558
+ @monitor.synchronize do
559
+ if parter_nick == @nick
560
+ @channels.delete(channel_name)
561
+ else
562
+ channel = @channels[channel_name]
563
+ channel&.users&.delete(parter_nick)
564
+ end
565
+ end
566
+ end
567
+
568
+ def handle_quit(message)
569
+ quitter_nick = message.source&.nick
570
+ return unless quitter_nick
571
+
572
+ @monitor.synchronize do
573
+ @channels.each_value do |channel|
574
+ channel.users.delete(quitter_nick)
575
+ end
576
+ end
577
+ end
578
+
579
+ def handle_nick(message)
580
+ old_nick = message.source&.nick
581
+ new_nick = message.params[0]
582
+ return unless old_nick && new_nick
583
+
584
+ @monitor.synchronize do
585
+ if old_nick == @nick
586
+ @nick = new_nick
587
+ end
588
+
589
+ @channels.each_value do |channel|
590
+ if channel.users.key?(old_nick)
591
+ user_data = channel.users.delete(old_nick)
592
+ channel.users[new_nick] = user_data
593
+ end
594
+ end
595
+ end
596
+ end
597
+
598
+ def handle_kick(message)
599
+ channel_name = message.params[0]
600
+ kicked_nick = message.params[1]
601
+ return unless channel_name && kicked_nick
602
+
603
+ @monitor.synchronize do
604
+ if kicked_nick == @nick
605
+ @channels.delete(channel_name)
606
+ else
607
+ channel = @channels[channel_name]
608
+ channel&.users&.delete(kicked_nick)
609
+ end
610
+ end
611
+ end
612
+
613
+ def handle_topic(message)
614
+ channel_name = message.params[0]
615
+ topic_text = message.params[1]
616
+ setter_nick = message.source&.nick
617
+ return unless channel_name
618
+
619
+ @monitor.synchronize do
620
+ channel = @channels[channel_name]
621
+ channel&.set_topic(topic_text, setter_nick)
622
+ end
623
+ end
624
+
625
+ def handle_rpl_topic(message)
626
+ channel_name = message.params[1]
627
+ topic_text = message.params[2]
628
+ return unless channel_name
629
+
630
+ @monitor.synchronize do
631
+ channel = @channels[channel_name]
632
+ channel&.set_topic(topic_text)
633
+ end
634
+ end
635
+
636
+ def handle_rpl_topicwhotime(message)
637
+ channel_name = message.params[1]
638
+ setter = message.params[2]
639
+ time_str = message.params[3]
640
+ return unless channel_name && setter && time_str
641
+
642
+ @monitor.synchronize do
643
+ channel = @channels[channel_name]
644
+ channel&.set_topic(channel&.topic, setter, Time.at(time_str.to_i))
645
+ end
646
+ end
647
+
648
+ def handle_rpl_namreply(message)
649
+ channel_name = message.params[2]
650
+ users_str = message.params[3]
651
+ return unless channel_name && users_str
652
+
653
+ @monitor.synchronize do
654
+ @pending_names[channel_name] ||= {}
655
+
656
+ users_str.split.each do |user_entry|
657
+ nick, modes = parse_user_with_prefix(user_entry)
658
+ @pending_names[channel_name][nick] = modes
659
+ end
660
+ end
661
+ end
662
+
663
+ def handle_rpl_endofnames(message)
664
+ channel_name = message.params[1]
665
+ return unless channel_name
666
+
667
+ pending = nil
668
+ @monitor.synchronize do
669
+ channel = @channels[channel_name]
670
+ pending = @pending_names.delete(channel_name) || {}
671
+
672
+ if channel
673
+ pending.each do |nick, modes|
674
+ channel.users[nick] = modes
675
+ end
676
+ end
677
+ end
678
+
679
+ emit(:names, message, channel: channel_name, users: pending)
680
+ end
681
+
682
+ def handle_mode(message)
683
+ target = message.params[0]
684
+ return unless target
685
+
686
+ modes_str = message.params[1]
687
+ return unless modes_str
688
+
689
+ @monitor.synchronize do
690
+ channel = @channels[target]
691
+ return unless channel
692
+
693
+ params = message.params[2..] || []
694
+ param_idx = 0
695
+
696
+ adding = true
697
+ modes_str.each_char do |char|
698
+ case char
699
+ when "+"
700
+ adding = true
701
+ when "-"
702
+ adding = false
703
+ when "o", "v", "h", "a", "q"
704
+ nick = params[param_idx]
705
+ param_idx += 1
706
+ apply_user_mode(channel, nick, char, adding) if nick
707
+ when "k"
708
+ if adding
709
+ channel.modes[:key] = params[param_idx]
710
+ param_idx += 1
711
+ else
712
+ channel.modes.delete(:key)
713
+ end
714
+ when "l"
715
+ if adding
716
+ channel.modes[:limit] = params[param_idx].to_i
717
+ param_idx += 1
718
+ else
719
+ channel.modes.delete(:limit)
720
+ end
721
+ when "m"
722
+ channel.modes[:moderated] = adding ? true : nil
723
+ channel.modes.delete(:moderated) unless adding
724
+ when "i"
725
+ channel.modes[:invite_only] = adding ? true : nil
726
+ channel.modes.delete(:invite_only) unless adding
727
+ when "t"
728
+ channel.modes[:topic_protected] = adding ? true : nil
729
+ channel.modes.delete(:topic_protected) unless adding
730
+ when "n"
731
+ channel.modes[:no_external] = adding ? true : nil
732
+ channel.modes.delete(:no_external) unless adding
733
+ when "s"
734
+ channel.modes[:secret] = adding ? true : nil
735
+ channel.modes.delete(:secret) unless adding
736
+ when "p"
737
+ channel.modes[:private] = adding ? true : nil
738
+ channel.modes.delete(:private) unless adding
739
+ when "b"
740
+ param_idx += 1
741
+ end
742
+ end
743
+ end
744
+ end
745
+
746
+ def handle_rpl_whoreply(message)
747
+ channel = message.params[1]
748
+ user = message.params[2]
749
+ host = message.params[3]
750
+ server = message.params[4]
751
+ nick = message.params[5]
752
+ flags = message.params[6]
753
+ hopcount_realname = message.params[7]
754
+
755
+ away = flags&.include?("G") || false
756
+ realname = hopcount_realname&.sub(/^\d+\s*/, "") || ""
757
+
758
+ @monitor.synchronize do
759
+ @pending_who_results.each_key do |mask|
760
+ if who_reply_matches_mask?(mask, channel, nick)
761
+ result = WhoResult.new(
762
+ channel: channel,
763
+ user: user,
764
+ host: host,
765
+ server: server,
766
+ nick: nick,
767
+ away: away,
768
+ realname: realname
769
+ )
770
+ @pending_who_results[mask] << result
771
+ end
772
+ end
773
+ end
774
+
775
+ emit(:who, message, channel: channel, user: user, host: host, server: server,
776
+ nick: nick, away: away, realname: realname)
777
+ end
778
+
779
+ def handle_rpl_endofwho(message)
780
+ mask = message.params[1]
781
+ @monitor.synchronize do
782
+ @pending_who_complete[mask] = true if @pending_who_complete.key?(mask)
783
+ end
784
+ end
785
+
786
+ def who_reply_matches_mask?(mask, channel, nick)
787
+ if mask.start_with?("#")
788
+ channel.casecmp?(mask)
789
+ else
790
+ nick.casecmp?(mask)
791
+ end
792
+ end
793
+
794
+ def handle_rpl_whoisuser(message)
795
+ nick = message.params[1]
796
+ user = message.params[2]
797
+ host = message.params[3]
798
+ realname = message.params[5]
799
+
800
+ @monitor.synchronize do
801
+ @pending_whois[nick] = WhoisResult.new(nick: nick)
802
+ @pending_whois[nick].user = user
803
+ @pending_whois[nick].host = host
804
+ @pending_whois[nick].realname = realname
805
+ end
806
+ end
807
+
808
+ def handle_rpl_whoischannels(message)
809
+ nick = message.params[1]
810
+ channels_str = message.params[2]
811
+
812
+ @monitor.synchronize do
813
+ return unless @pending_whois[nick] && channels_str
814
+
815
+ channels_str.split.each do |chan|
816
+ channel = chan.gsub(/^[@+%~&]+/, "")
817
+ @pending_whois[nick].channels << channel
818
+ end
819
+ end
820
+ end
821
+
822
+ def handle_rpl_whoisserver(message)
823
+ nick = message.params[1]
824
+ server = message.params[2]
825
+
826
+ @monitor.synchronize do
827
+ return unless @pending_whois[nick]
828
+ @pending_whois[nick].server = server
829
+ end
830
+ end
831
+
832
+ def handle_rpl_whoisidle(message)
833
+ nick = message.params[1]
834
+ idle = message.params[2]&.to_i
835
+ signon = message.params[3]&.to_i
836
+
837
+ @monitor.synchronize do
838
+ return unless @pending_whois[nick]
839
+ @pending_whois[nick].idle = idle
840
+ @pending_whois[nick].signon = signon ? Time.at(signon) : nil
841
+ end
842
+ end
843
+
844
+ def handle_rpl_whoisaccount(message)
845
+ nick = message.params[1]
846
+ account = message.params[2]
847
+
848
+ @monitor.synchronize do
849
+ return unless @pending_whois[nick]
850
+ @pending_whois[nick].account = account
851
+ end
852
+ end
853
+
854
+ def handle_rpl_away(message)
855
+ nick = message.params[1]
856
+ away_msg = message.params[2]
857
+
858
+ @monitor.synchronize do
859
+ return unless @pending_whois[nick]
860
+ @pending_whois[nick].away = away_msg
861
+ end
862
+ end
863
+
864
+ def handle_rpl_endofwhois(message)
865
+ nick = message.params[1]
866
+ result = nil
867
+ @monitor.synchronize do
868
+ @pending_whois_complete[nick] = true if @pending_whois_complete.key?(nick)
869
+ result = @pending_whois[nick]
870
+ end
871
+ emit(:whois, message, result: result)
872
+ end
873
+
874
+ def handle_rpl_ison(message)
875
+ nicks_str = message.params[1] || ""
876
+ online_nicks = nicks_str.split
877
+
878
+ @monitor.synchronize do
879
+ @pending_ison = online_nicks
880
+ @pending_ison_complete = true
881
+ end
882
+
883
+ emit(:ison, message, nicks: online_nicks)
884
+ end
885
+
886
+ def apply_user_mode(channel, nick, mode_char, adding)
887
+ return unless channel.users.key?(nick)
888
+
889
+ mode_sym = case mode_char
890
+ when "o" then :op
891
+ when "v" then :voice
892
+ when "h" then :halfop
893
+ when "a" then :admin
894
+ when "q" then :owner
895
+ end
896
+ return unless mode_sym
897
+
898
+ if adding
899
+ channel.users[nick] << mode_sym
900
+ else
901
+ channel.users[nick].delete(mode_sym)
902
+ end
903
+ end
904
+
905
+ def parse_user_with_prefix(user_entry)
906
+ modes = Set.new
907
+ nick = user_entry
908
+
909
+ while nick.length > 0 && PREFIX_MODES.key?(nick[0])
910
+ modes << PREFIX_MODES[nick[0]]
911
+ nick = nick[1..]
912
+ end
913
+
914
+ [nick, modes]
915
+ end
916
+
917
+ def emit_events(message)
918
+ emit(:raw, message, message: message)
919
+
920
+ event_type = determine_event_type(message)
921
+ return unless event_type
922
+
923
+ attributes = build_event_attributes(event_type, message)
924
+ emit(event_type, message, **attributes)
925
+ end
926
+
927
+ def emit(event_type, message, **attributes)
928
+ handlers = @monitor.synchronize { @handlers[event_type]&.dup }
929
+ return unless handlers
930
+
931
+ event = Event.new(type: event_type, message: message, **attributes)
932
+ handlers.each do |handler|
933
+ handler.call(event)
934
+ rescue => e
935
+ warn "Event handler error: #{e.message}"
936
+ end
937
+ end
938
+
939
+ def determine_event_type(message)
940
+ return EVENT_MAP[message.command] if EVENT_MAP.key?(message.command)
941
+
942
+ if message.command == "001"
943
+ :connect
944
+ elsif message.command == "332"
945
+ :topic
946
+ elsif message.command.match?(/\A[45]\d\d\z/)
947
+ :error
948
+ end
949
+ end
950
+
951
+ def build_event_attributes(event_type, message)
952
+ case event_type
953
+ when :connect
954
+ {server: message.source&.raw}
955
+ when :message, :notice
956
+ {source: message.source, target: message.params[0], text: message.params[1]}
957
+ when :join
958
+ {channel: message.params[0], user: message.source}
959
+ when :part
960
+ {channel: message.params[0], user: message.source, reason: message.params[1]}
961
+ when :quit
962
+ {user: message.source, reason: message.params[0]}
963
+ when :kick
964
+ {channel: message.params[0], user: message.params[1], by: message.source, reason: message.params[2]}
965
+ when :nick
966
+ {old_nick: message.source&.nick, new_nick: message.params[0]}
967
+ when :topic
968
+ if message.command == "332"
969
+ {channel: message.params[1], topic: message.params[2], setter: nil}
970
+ else
971
+ {channel: message.params[0], topic: message.params[1], setter: message.source}
972
+ end
973
+ when :mode
974
+ {target: message.params[0], modes: message.params[1], args: message.params[2..]}
975
+ when :error
976
+ {numeric: message.command.to_i, message: message.params.last, params: message.params}
977
+ else
978
+ {}
979
+ end
980
+ end
981
+ end
982
+ end