pikuri-core 0.0.7 → 0.2.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/README.md +17 -30
  3. data/lib/pikuri/agent/chat_transport.rb +168 -107
  4. data/lib/pikuri/agent/configurator.rb +194 -173
  5. data/lib/pikuri/agent/control/cancellable.rb +100 -70
  6. data/lib/pikuri/agent/control/handoff.rb +75 -0
  7. data/lib/pikuri/agent/control/interloper.rb +107 -118
  8. data/lib/pikuri/agent/control.rb +13 -35
  9. data/lib/pikuri/agent/event.rb +144 -197
  10. data/lib/pikuri/agent/extension.rb +83 -95
  11. data/lib/pikuri/agent/history.rb +247 -0
  12. data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
  13. data/lib/pikuri/agent/listener/terminal.rb +169 -136
  14. data/lib/pikuri/agent/listener/token_log.rb +84 -157
  15. data/lib/pikuri/agent/listener.rb +24 -44
  16. data/lib/pikuri/agent/listener_list.rb +32 -47
  17. data/lib/pikuri/agent/request_instrumenter.rb +102 -0
  18. data/lib/pikuri/agent.rb +1095 -577
  19. data/lib/pikuri/attachment.rb +65 -0
  20. data/lib/pikuri/bundler_env.rb +68 -0
  21. data/lib/pikuri/extractor/passthrough.rb +24 -31
  22. data/lib/pikuri/extractor.rb +125 -155
  23. data/lib/pikuri/file_type.rb +64 -136
  24. data/lib/pikuri/finalizers.rb +32 -47
  25. data/lib/pikuri/paths.rb +104 -13
  26. data/lib/pikuri/sanitizer.rb +46 -67
  27. data/lib/pikuri/subprocess.rb +86 -118
  28. data/lib/pikuri/testing.rb +369 -0
  29. data/lib/pikuri/tool/calculator.rb +168 -74
  30. data/lib/pikuri/tool/execute_context.rb +42 -0
  31. data/lib/pikuri/tool/parameters.rb +31 -29
  32. data/lib/pikuri/tool/result.rb +164 -0
  33. data/lib/pikuri/tool/trifecta_legs.rb +248 -0
  34. data/lib/pikuri/tool.rb +416 -67
  35. data/lib/pikuri/trifecta/contribution.rb +43 -0
  36. data/lib/pikuri/trifecta/node.rb +47 -0
  37. data/lib/pikuri/trifecta/report.rb +228 -0
  38. data/lib/pikuri/trifecta.rb +126 -0
  39. data/lib/pikuri/version.rb +1 -1
  40. data/lib/pikuri-core.rb +70 -92
  41. data/prompts/agent-loop.txt +5 -0
  42. data/prompts/pikuri-chat.txt +3 -12
  43. metadata +26 -72
  44. data/lib/pikuri/agent/context_window_detector.rb +0 -222
  45. data/lib/pikuri/agent/control/step_limit.rb +0 -111
  46. data/lib/pikuri/agent/extension_context.rb +0 -147
  47. data/lib/pikuri/agent/listener/rate_limited.rb +0 -172
  48. data/lib/pikuri/agent/synthesizer.rb +0 -171
  49. data/lib/pikuri/extractor/html.rb +0 -303
  50. data/lib/pikuri/tool/fetch.rb +0 -172
  51. data/lib/pikuri/tool/scraper.rb +0 -186
  52. data/lib/pikuri/tool/search/brave.rb +0 -198
  53. data/lib/pikuri/tool/search/duckduckgo.rb +0 -207
  54. data/lib/pikuri/tool/search/engines.rb +0 -186
  55. data/lib/pikuri/tool/search/exa.rb +0 -229
  56. data/lib/pikuri/tool/search/rate_limiter.rb +0 -92
  57. data/lib/pikuri/tool/search/result.rb +0 -29
  58. data/lib/pikuri/tool/web_scrape.rb +0 -121
  59. data/lib/pikuri/tool/web_search.rb +0 -57
  60. data/lib/pikuri/url_cache.rb +0 -112
@@ -3,114 +3,144 @@
3
3
  module Pikuri
4
4
  class Agent
5
5
  module Control
6
- # Cooperative cancellation token. The instance is normally
7
- # constructed on the main thread and handed to
8
- # {Agent#initialize} via the +cancellable:+ kwarg; an
9
- # out-of-band caller (a SIGINT trap, a TUI key binding, an
10
- # IPC handler) calls {#cancel!} to flip the flag, and the
11
- # next {#check!} on the run thread raises {Cancelled} —
12
- # which {Agent#run_loop} catches, normalizes into an
13
- # {Event::Cancelled} on the listener stream, and re-raises
14
- # so the caller's REPL can return control to the user.
6
+ # Cooperative cancellation token. Built on the main thread and handed to
7
+ # {Agent#initialize} via +cancellable:+; an out-of-band caller (a SIGINT
8
+ # trap, a TUI key, an IPC handler) calls {#cancel!} to flip the flag, and
9
+ # the next {#check!} on the run thread raises {Cancelled} — which
10
+ # {Agent#run_loop} catches, emits as {Event::Cancelled}, and re-raises so
11
+ # the REPL returns control to the user.
15
12
  #
16
- # == Cancellation boundary
13
+ # The host resets it each time it starts a turn, on its own thread, before
14
+ # it hands the turn to a worker:
15
+ #
16
+ # cancellable.reset!
17
+ # Thread.new { agent.run_loop(user_message: message) }
18
+ # # Escape, any time from here on: cancellable.cancel!
17
19
  #
18
- # The +Agent+ calls {#check!} from its +before_tool_call+
19
- # wiring — between an LLM response that requested a tool
20
- # and the actual tool invocation — which is the only point
21
- # at which the conversation state is consistent (no
22
- # in-flight subprocess, no half-applied write). An in-flight
23
- # LLM HTTP call is *not* interrupted; the response lands,
24
- # then the next tool-call boundary trips. An in-flight tool
25
- # (notably +Bash+) is also not interrupted — cancellation
26
- # lands after the tool returns. Both are intentional v1
27
- # scope: the "gentle cancel" semantic that pikuri promises.
20
+ # A cancel sent before the worker reaches {Agent#run_loop} then still
21
+ # ends that turn. A host that forgets {#reset!} sees every turn after the
22
+ # first cancel end at once.
28
23
  #
29
- # == Thread safety
24
+ # == Cancellation boundary
30
25
  #
31
- # {#cancel!} is intended to be called from a thread other
32
- # than the one running {Agent#run_loop} (the typical case
33
- # is a SIGINT trap handler on the main thread while the
34
- # agent runs on a worker, or vice versa). A plain boolean
35
- # ivar is sufficient under MRI: writes and reads of a
36
- # single reference are atomic with respect to the GVL, and
37
- # the only state transition we care about is +false → true+
38
- # before the next {#check!} fires. There is no double-cancel
39
- # hazard; repeated {#cancel!} calls are idempotent.
26
+ # The +Agent+ calls {#check!} from +before_tool_call+ — between an LLM
27
+ # response requesting a tool and the tool invocation — the only point
28
+ # where conversation state is consistent (no in-flight subprocess, no
29
+ # half-applied write). An in-flight LLM HTTP call is *not* interrupted
30
+ # (the response lands, then the next boundary trips), nor is an in-flight
31
+ # tool (notably +Bash+). Both are the intentional "gentle cancel" v1 scope.
32
+ #
33
+ # {#sleep} and {Handoff#await} widen that boundary to code *waiting* inside
34
+ # a tool — pacing, or a confirmer waiting on a human — which waits through
35
+ # them instead of +Kernel#sleep+ or a +Queue+ and becomes interruptible.
36
+ # They reach waits only — a thread blocked in IO (a Faraday read,
37
+ # +Subprocess#wait+) is still uninterruptible, so most of a tool's blocking
38
+ # is untouched by design.
40
39
  #
41
40
  # == Sub-agent semantics
42
41
  #
43
- # Cancellation is a global "stop the whole tree" signal —
44
- # the +agent+ tool from +pikuri-subagents+ shares the
45
- # parent's +Cancellable+ by reference when spawning a child,
46
- # so one {#cancel!} call stops the parent, every running
47
- # sub-agent, and the synthesizer rescue. The sharing rule
48
- # lives at the spawn site (sub-agent code), not on this
49
- # class.
42
+ # Cancellation is a global "stop the whole tree" signal — the +agent+ tool
43
+ # shares the parent's +Cancellable+ by reference with each child, so one
44
+ # {#cancel!} stops the parent, every sub-agent, and the synthesizer. The
45
+ # sharing rule lives at the spawn site, not here.
46
+ #
47
+ # Thread-safe: {#cancel!} is meant to run on a thread other than the loop's
48
+ # (a SIGINT trap while the agent runs on a worker). A plain boolean ivar
49
+ # suffices under MRI — the only transition that matters is +false → true+
50
+ # before the next {#check!}, and repeated {#cancel!} is idempotent.
50
51
  class Cancellable
51
- # Raised by {#check!} once {#cancel!} has been called.
52
- # Carries no fields; the cancellation reason ("the user
53
- # asked us to stop") is implicit in the exception class.
54
- # {Agent#run_loop} catches this, emits {Event::Cancelled},
55
- # and re-raises so the caller (typically a REPL) can
56
- # return control to the user.
52
+ # Raised by {#check!} once {#cancel!} has been called; carries no fields.
53
+ # {Agent#run_loop} catches it, emits {Event::Cancelled}, and re-raises.
57
54
  class Cancelled < StandardError
58
55
  def initialize
59
56
  super('Agent loop cancelled')
60
57
  end
61
58
  end
62
59
 
60
+ # Longest a {#sleep} or {Handoff#await} stays unresponsive to a {#cancel!}: it wakes on
61
+ # this cadence to re-check the flag. Polling rather than a
62
+ # +ConditionVariable+ because {#cancel!} must stay callable from a
63
+ # SIGINT trap, where taking a +Mutex+ raises +ThreadError+ — so the
64
+ # waking side pays, and the signalling side stays a bare flag write.
65
+ #
66
+ # @return [Float] seconds
67
+ SLICE_SECONDS = 0.1
68
+
63
69
  def initialize
64
70
  @cancelled = false
65
71
  end
66
72
 
67
- # Flip the flag. Safe to call from a thread other than
68
- # the one running the agent loop, and safe to call
69
- # multiple times (idempotent). Takes effect at the next
70
- # {#check!} on the run thread — see the class header for
71
- # the "gentle cancel" caveats.
73
+ # A token that never trips — the null object for code that structurally
74
+ # needs one (a {#sleep} to wait through, a +cancellable:+ parameter) when
75
+ # the host wired no cancellation. Frozen, so a stray {#cancel!} raises
76
+ # +FrozenError+ rather than silently cancelling every agent that
77
+ # defaulted to it. Defined below {#initialize} so +@cancelled+ is set.
78
+ #
79
+ # @return [Cancellable]
80
+ NEVER = new.freeze
81
+
82
+ # Flip the flag. Safe off the loop thread and idempotent. Takes effect
83
+ # at the next {#check!} — see the class header for the gentle-cancel
84
+ # caveats.
72
85
  #
73
86
  # @return [void]
74
87
  def cancel!
75
88
  @cancelled = true
76
89
  end
77
90
 
78
- # @return [Boolean] whether {#cancel!} has been called
79
- # since the last {#reset!}; observable from any thread.
91
+ # @return [Boolean] whether {#cancel!} has been called since the last
92
+ # {#reset!}; observable from any thread.
80
93
  def cancelled?
81
94
  @cancelled
82
95
  end
83
96
 
84
- # Raise {Cancelled} when the flag is set; otherwise no-op.
85
- # Called by {Agent} from its +before_tool_call+ wiring.
97
+ # Raise {Cancelled} when the flag is set, else no-op. Called from
98
+ # {Agent}'s +before_tool_call+ wiring.
86
99
  #
87
100
  # @return [void]
88
- # @raise [Cancelled] when {#cancel!} has been called since
89
- # the last {#reset!}
101
+ # @raise [Cancelled] when {#cancel!} has been called since {#reset!}
90
102
  def check!
91
103
  raise Cancelled if @cancelled
92
104
  end
93
105
 
94
- # Reset the flag back to armed. Called by {Agent} at the
95
- # start of each turn so a stale cancellation from a prior
96
- # turn does not poison the next one. Mid-loop
97
- # {Control::Interloper} injections deliberately do *not*
98
- # trigger a reset — otherwise the cancel-then-inject
99
- # ordering would lose the cancellation: +cancel!+ sets
100
- # the flag, the injection lands and resets it, and the
101
- # next +before_tool_call+ no longer raises.
106
+ # Wait +seconds+, cutting the wait short with {Cancelled} if {#cancel!}
107
+ # lands while waiting — the drop-in for +Kernel#sleep+ anywhere a tool
108
+ # paces or polls:
109
+ #
110
+ # cancellable.sleep(2.0) # returns after 2s, or raises on a cancel
102
111
  #
112
+ # Checks the flag before waiting at all, so an already-cancelled token
113
+ # raises without a delay, and a non-positive +seconds+ is still a
114
+ # cancellation check rather than a no-op. Wakes every {SLICE_SECONDS} to
115
+ # look, so a cancel is honoured within that.
116
+ #
117
+ # @param seconds [Float] how long to wait; +<= 0+ returns at once.
103
118
  # @return [void]
104
- def reset!
105
- @cancelled = false
119
+ # @raise [Cancelled] if {#cancel!} has been called, before or during
120
+ # the wait.
121
+ def sleep(seconds)
122
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
123
+ loop do
124
+ check!
125
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
126
+ return if remaining <= 0
127
+
128
+ # Kernel., or this recurses into itself.
129
+ Kernel.sleep([remaining, SLICE_SECONDS].min)
130
+ end
106
131
  end
107
132
 
108
- # @return [String] short label for {Agent#to_s}; reflects
109
- # the current flag state so a startup banner or debug
110
- # print can tell an armed token apart from one that has
111
- # already tripped.
112
- def to_s
113
- "Cancellable(#{@cancelled ? 'cancelled' : 'armed'})"
133
+ # Clear the flag for a new turn. The host calls it where it decides a
134
+ # turn starts, under whatever guards its "running" state — never the
135
+ # agent: {Agent#run_loop} can't tell a cancel left over from the last
136
+ # turn from one sent early for this one. The agent's own boundaries
137
+ # (a mid-loop {Control::Interloper} injection, a sub-agent's turn on
138
+ # the shared token) leave it alone, or they would swallow a pending
139
+ # cancel. +design/decisions.md+ +D_host_resets_cancel+.
140
+ #
141
+ # @return [void]
142
+ def reset!
143
+ @cancelled = false
114
144
  end
115
145
  end
116
146
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pikuri
4
+ class Agent
5
+ module Control
6
+ # A one-shot slot that one thread waits on until another fills it, or
7
+ # until the turn is cancelled. Built for a host confirmer whose human
8
+ # answers on another thread (a TUI's UI thread, a web request):
9
+ #
10
+ # def ask(request:, cancellable:)
11
+ # handoff = Pikuri::Agent::Control::Handoff.new(cancellable)
12
+ # ui.submit { show_dialog(request) { |decision| handoff.complete(decision) } }
13
+ # handoff.await # the decision, or Cancellable::Cancelled on a cancel
14
+ # ensure
15
+ # ui.submit { close_dialog }
16
+ # end
17
+ #
18
+ # Any {Cancellable#cancel!} reaches the parked {#await}, wherever it was
19
+ # issued, so the host needs no cancel hook of its own on the confirmer.
20
+ #
21
+ # == Implementation details
22
+ #
23
+ # {#complete} wakes {#await} through a +ConditionVariable+; a cancel is
24
+ # polled every {Cancellable::SLICE_SECONDS} instead, so {Cancellable#cancel!}
25
+ # stays a bare flag write that is safe from a SIGINT trap. A cancel wins over
26
+ # an answer landing in the same slice, as in {Cancellable#sleep}.
27
+ #
28
+ # Thread-safe.
29
+ class Handoff
30
+ # @param cancellable [Cancellable] the turn's token; {#await} raises
31
+ # once it trips.
32
+ def initialize(cancellable)
33
+ @cancellable = cancellable
34
+ @mutex = Mutex.new
35
+ @filled = ConditionVariable.new
36
+ @done = false
37
+ @value = nil
38
+ end
39
+
40
+ # Fill the slot and wake {#await}. Callable from any thread except a
41
+ # signal trap, since it takes a lock.
42
+ #
43
+ # @param value [Object] what {#await} answers; may be +nil+.
44
+ # @return [void]
45
+ # @raise [RuntimeError] when already completed — one answer per wait.
46
+ def complete(value)
47
+ @mutex.synchronize do
48
+ raise "#{self.class} already completed with #{@value.inspect}" if @done
49
+
50
+ @value = value
51
+ @done = true
52
+ @filled.signal
53
+ end
54
+ end
55
+
56
+ # Block until {#complete} is called, and answer its value. Returns at
57
+ # once when the slot is already filled.
58
+ #
59
+ # @return [Object] the value {#complete} was given.
60
+ # @raise [Cancellable::Cancelled] when the token trips, before or
61
+ # during the wait.
62
+ def await
63
+ @mutex.synchronize do
64
+ loop do
65
+ @cancellable.check!
66
+ return @value if @done
67
+
68
+ @filled.wait(@mutex, Cancellable::SLICE_SECONDS)
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -3,160 +3,149 @@
3
3
  module Pikuri
4
4
  class Agent
5
5
  module Control
6
- # Mid-loop user-input queue. A host (TUI, web client)
7
- # constructs an +Interloper+, hands it to {Agent#initialize}
8
- # via the +interloper:+ kwarg, and calls
9
- # {#inject_user_message} from any thread while the agent
10
- # is running. The +Agent+ drains the queue at the next
11
- # +after_tool_result+ boundary — the only point inside
12
- # ruby_llm's loop where the conversation state is
13
- # consistent — and emits each item into the chat history
14
- # plus the listener stream. The agent's next round-trip
15
- # then sees the injected user message and reacts to it on
16
- # its own.
6
+ # Mid-loop host→agent injection queue. Every {Agent} builds its own, and
7
+ # a host (TUI, web client) enqueues from any thread while the agent runs:
17
8
  #
18
- # +Interloper+ is groundwork for downstream TUI/web hosts;
19
- # the bundled +bin/pikuri-*+ entry-point scripts do *not*
20
- # wire one up, since they keep stdin synchronous and have
21
- # no way for a user to type while a turn is in flight.
22
- # Downstream hosts that *do* run the agent on a worker
23
- # thread can wire one in with no other changes to pikuri.
9
+ # agent.interloper.inject_user_message('also check the tests') # a user turn
10
+ # agent.interloper.inject_system_message('<skill name="tdd">…</skill>') # reference text
24
11
  #
25
- # == Delivery boundary and side effects
12
+ # The agent drains it at turn start and once each tool batch is
13
+ # answered: an injection made while idle lands ahead of the next turn's
14
+ # message, one made mid-turn reaches the next round-trip.
15
+ # {Agent#drain_interloper} says how each {Item#kind} lands. A host
16
+ # showing what's queued — a "2 queued" badge, the pending messages
17
+ # themselves — sets {#on_change}, which hands it the items. Why a
18
+ # running turn takes a user message at all: +design/decisions.md+
19
+ # +D_mid_turn_user_message+.
26
20
  #
27
- # When the +Agent+'s +after_tool_result+ wiring fires, it
28
- # calls {#drain!} on the interloper (if any) and, for each
29
- # returned item:
21
+ # Sub-agents are private to the parent, so a child's queue stays empty —
22
+ # injection is directed at the main agent, where {Control::Cancellable}
23
+ # is shared by the whole tree.
30
24
  #
31
- # 1. Appends a +role: :user+ message to the chat history so
32
- # the next +complete+ round-trip's request includes it.
33
- # 2. Emits +Event::UserTurn(content:, mid_loop: true)+
34
- # through the listener stream so other listeners
35
- # (Terminal renderer, in-memory recorder, future logging)
36
- # see the injection as a normal +UserTurn+ event with the
37
- # +mid_loop:+ flag set.
25
+ # == Implementation details
38
26
  #
39
- # Controls do not respond to events; the +Agent+ pokes
40
- # {Control::StepLimit#reset!} and {Control::Cancellable#reset!}
41
- # only at the start of each turn — never on a mid-loop
42
- # injection — so the "cancel-then-inject" hazard and the
43
- # "refresh-budget-by-injecting" hazard cannot arise.
27
+ # Never drained *inside* a tool batch: an assistant message carrying
28
+ # tool_calls and the +:tool+ messages answering it are one unit on the
29
+ # wire, and a message appended between them is rejected or mangled (see
30
+ # {Agent#tool_batch_complete?}).
44
31
  #
45
- # == Boundary caveats
46
- #
47
- # The delivery point is +after_tool_result+, *not* the LLM
48
- # HTTP call. Injections placed while the model is
49
- # mid-response take effect on the *next* round-trip — by
50
- # the time the queue drains, the model has already
51
- # committed to whichever tool calls were in that response.
52
- # The agent therefore typically observes an injection at
53
- # the tool-batch boundary *after* the one during which the
54
- # host called {#inject_user_message}. This is the same
55
- # "gentle" semantic that {Control::Cancellable} promises
56
- # and is the cleanest cross-provider point: no in-flight
57
- # subprocess, no half-applied write, no half-built response.
58
- #
59
- # == Thread safety
60
- #
61
- # {#inject_user_message}, {#peek}, {#pending?}, and
62
- # {#drain!} are safe to call from any thread; the internal
63
- # queue is a +Mutex+-guarded +Array+. The +Agent+'s drain
64
- # runs on the run thread (whatever thread invoked
65
- # +Chat#ask+). +Mutex+ was chosen over +Thread::Queue+
66
- # because +Thread::Queue+ exposes no snapshot read, and
67
- # {#peek} is part of the surface (the host wants to render
68
- # "feedback received, will deliver shortly" in its UI
69
- # before the agent actually consumes the injection).
70
- #
71
- # == Sub-agent semantics
72
- #
73
- # Sub-agents are private to the parent agent; the host has
74
- # no handle to them, so a child +Interloper+ would be
75
- # unreachable. The +agent+ tool from +pikuri-subagents+
76
- # therefore omits the kwarg when spawning a child, leaving
77
- # the sub-agent's +interloper+ at its default +nil+. The
78
- # behavior contrasts with {Control::Cancellable}, which is
79
- # shared by reference so the parent's signal propagates to
80
- # children — cancellation is a global "stop the whole tree"
81
- # event, whereas injection is a directed "talk to the main
82
- # agent" event.
32
+ # Thread-safe: a +Mutex+-guarded +Array+. {#on_change} fires outside the
33
+ # lock, so a callback may re-enter the interloper.
83
34
  class Interloper
35
+ # A queued injection: +kind+ (+:user+ or +:system+) selects the drain
36
+ # path; +content+ is the message text (+""+ for an attachment-only
37
+ # user message), +attachments+ the files shown with it, always empty
38
+ # for +:system+.
39
+ Item = Data.define(:kind, :content, :attachments) do
40
+ # @param kind [Symbol]
41
+ # @param content [String]
42
+ # @param attachments [Array<Pikuri::Attachment>]
43
+ def initialize(kind:, content:, attachments: [])
44
+ super(kind: kind, content: content, attachments: attachments.dup.freeze)
45
+ end
46
+ end
47
+
84
48
  def initialize
85
49
  @mutex = Mutex.new
86
50
  @items = []
51
+ @on_change = nil
87
52
  end
88
53
 
89
- # Push +content+ onto the delivery queue. Safe from any
90
- # thread; the queue is +Mutex+-guarded.
54
+ # Called with a frozen snapshot of the queue after each injection, and
55
+ # with +[]+ after a {#drain!} that empties a non-empty queue (an empty
56
+ # drain, the hot path, stays silent); +nil+ disables it:
57
+ #
58
+ # interloper.on_change = ->(items) { badge.text = "#{items.size} queued" }
59
+ #
60
+ # The snapshot is the queue as this change left it, taken under the
61
+ # same lock; {#size} read from the callback may already see a later
62
+ # change. Runs on the mutating thread; the frozen snapshot of frozen
63
+ # {Item}s may be handed to another thread as is.
64
+ #
65
+ # @return [Proc, nil] called with an +Array<Item>+ in delivery order
66
+ attr_accessor :on_change
67
+
68
+ # Enqueue a +:user+ mid-loop turn, the same message {Agent#run_loop}
69
+ # takes, e.g. an image dropped while the agent works:
91
70
  #
92
- # @param content [String] non-blank user-supplied text
93
- # @raise [ArgumentError] if +content+ is +nil+, empty, or
94
- # whitespace-only — same rule as {Agent#run_loop}'s
95
- # +user_message:+ argument, since an empty injection
96
- # would poison the chat history just as a blank turn
97
- # would
71
+ # interloper.inject_user_message('and this one?', attachments: [png])
72
+ #
73
+ # Unlike {Agent#run_loop}, nothing here can refuse an attachment the
74
+ # model can't see: this runs on the host's thread with no agent, and
75
+ # raising at the drain would end the running turn over a picture. The
76
+ # drain withholds it instead, with a note in the text the model reads
77
+ # ({ChatTransport#modalities}). A host wanting an error up front checks
78
+ # +agent.transport.modalities+ before injecting.
79
+ #
80
+ # @param content [String, nil] the user's text; may be blank only when
81
+ # +attachments+ are given
82
+ # @param attachments [Array<Pikuri::Attachment>] files shown with it
83
+ # @raise [ArgumentError] if there is neither text nor an attachment — a
84
+ # blank injection would poison the chat history like a blank turn —
85
+ # or an attachment is not a {Pikuri::Attachment}
98
86
  # @return [void]
99
- def inject_user_message(content)
100
- raise ArgumentError, "content must not be blank, got #{content.inspect}" \
101
- if content.nil? || content.to_s.strip.empty?
87
+ def inject_user_message(content = nil, attachments: [])
88
+ unless attachments.all?(Pikuri::Attachment)
89
+ raise ArgumentError, "attachments must be Pikuri::Attachments, got #{attachments.map(&:class)}"
90
+ end
102
91
 
103
- @mutex.synchronize { @items << content }
104
- nil
92
+ content = '' if !attachments.empty? && content.to_s.strip.empty?
93
+ enqueue(:user, content, attachments: attachments)
105
94
  end
106
95
 
107
- # Non-destructive snapshot of the queue, in delivery
108
- # order. Intended for hosts that want to render an
109
- # "ongoing / pending" UI affordance ("3 messages waiting
110
- # to deliver") in parallel with the agent's progress
111
- # stream. Safe to call from any thread.
96
+ # Enqueue a +:system+ reference block — host-loaded skill text or other
97
+ # retrieved context, not a user turn.
112
98
  #
113
- # @return [Array<String>] copy of the pending items;
114
- # never shares state with the internal buffer
115
- def peek
116
- @mutex.synchronize { @items.dup }
99
+ # @param content [String] non-blank reference text; an own semantic tag
100
+ # is kept, the +<system-reminder>+ envelope nests around it
101
+ # @raise [ArgumentError] if +content+ is +nil+/blank
102
+ # @return [void]
103
+ def inject_system_message(content)
104
+ enqueue(:system, content)
117
105
  end
118
106
 
119
- # @return [Boolean] whether the queue currently holds at
120
- # least one pending injection; observable from any
121
- # thread
107
+ # @return [Boolean] whether the queue holds a pending injection
122
108
  def pending?
123
109
  @mutex.synchronize { !@items.empty? }
124
110
  end
125
111
 
126
- # @return [Integer] number of pending injections; like
127
- # {#pending?} and {#peek}, a snapshot observable from
128
- # any thread — by the time the caller reads it the
129
- # queue may already have drained
112
+ # @return [Integer] number of pending injections; a snapshot that may
113
+ # have drained by the time the caller reads it
130
114
  def size
131
115
  @mutex.synchronize { @items.size }
132
116
  end
133
117
 
134
- # Atomically take and remove all pending items. Called by
135
- # {Agent}'s +after_tool_result+ wiring; the +Agent+ then
136
- # appends each item to the chat history and emits an
137
- # {Event::UserTurn} with +mid_loop: true+ for each.
118
+ # Atomically take and remove all pending items.
138
119
  #
139
- # Returns +[]+ when the queue is empty (the hot path —
140
- # every +after_tool_result+ calls this).
141
- #
142
- # @return [Array<String>] items in delivery order; empty
143
- # when the queue is empty
120
+ # @return [Array<Item>] items in delivery order; +[]+ when empty
144
121
  def drain!
145
- @mutex.synchronize do
122
+ items = @mutex.synchronize do
146
123
  next [] if @items.empty?
147
124
 
148
- items = @items.dup
125
+ taken = @items.dup
149
126
  @items.clear
150
- items
127
+ taken
151
128
  end
129
+ @on_change&.call([].freeze) unless items.empty?
130
+ items
152
131
  end
153
132
 
154
- # @return [String] short label for {Agent#to_s}; reflects
155
- # the pending-count so a debug print or banner can tell
156
- # an idle interloper apart from one with queued items
157
- def to_s
158
- pending = size
159
- pending.zero? ? 'Interloper' : "Interloper(#{pending} pending)"
133
+ private
134
+
135
+ # @param kind [Symbol] +:user+ or +:system+
136
+ # @param content [String, nil]
137
+ # @param attachments [Array<Pikuri::Attachment>] non-empty excuses a
138
+ # blank +content+
139
+ # @raise [ArgumentError] if +content+ is +nil+/blank with no attachments
140
+ # @return [void]
141
+ def enqueue(kind, content, attachments: [])
142
+ raise ArgumentError, "content must not be blank, got #{content.inspect}" \
143
+ if attachments.empty? && (content.nil? || content.to_s.strip.empty?)
144
+
145
+ item = Item.new(kind: kind, content: content, attachments: attachments)
146
+ snapshot = @mutex.synchronize { @items << item; @items.dup.freeze }
147
+ @on_change&.call(snapshot)
148
+ nil
160
149
  end
161
150
  end
162
151
  end
@@ -2,43 +2,21 @@
2
2
 
3
3
  module Pikuri
4
4
  class Agent
5
- # Namespace for the +Agent+'s host-facing controls:
6
- # {StepLimit}, {Cancellable}, and {Interloper}. Each is a small
7
- # value-holder that the +Agent+ reads from (or pokes into the
8
- # event stream from) at well-defined points in ruby_llm's
9
- # chat-callback cycle. They are *not* listeners — they receive
10
- # no events and never appear in a {ListenerList}.
5
+ # Namespace for the +Agent+'s host-facing controls: {Cancellable} and
6
+ # {Interloper}. Each is a small value-holder the +Agent+ reads from (or
7
+ # pokes into the event stream from) at fixed points in ruby_llm's callback
8
+ # cycle. They are *not* listeners — they receive no events and never appear
9
+ # in a {ListenerList}.
11
10
  #
12
- # == Why they're separated
11
+ # The split: listeners are pure consumers of the event stream; controls are
12
+ # host-facing signal holders the +Agent+ reads. The +Agent+ is the only
13
+ # entity that emits events, checks the cancel flag, and drains the
14
+ # interloper queue — "what fires when" is one grep for +@listeners.on_event+ in
15
+ # +agent.rb+.
13
16
  #
14
- # Listeners are pure consumers of the event stream; controls
15
- # are host-facing signal holders that the +Agent+ reads from.
16
- # The +Agent+ is the only entity that emits events, the only
17
- # entity that ticks the step counter, the only entity that
18
- # checks the cancellation flag, and the only entity that drains
19
- # the interloper queue. "What fires when" is a single grep for
20
- # +@listeners.emit+ in +agent.rb+.
21
- #
22
- # == What each control does
23
- #
24
- # * {StepLimit} — caps the number of tool calls per
25
- # {Agent#run_loop}. The +Agent+ calls {StepLimit#tick!} on
26
- # every +before_tool_call+ (raising {StepLimit::Exceeded}
27
- # when over budget) and {StepLimit#reset!} at the start of
28
- # each turn. Sub-agents get their own counter.
29
- # * {Cancellable} — cooperative cancellation flag. The host
30
- # calls {Cancellable#cancel!} from any thread; the +Agent+
31
- # calls {Cancellable#check!} at +before_tool_call+ (raising
32
- # {Cancellable::Cancelled} when the flag is set) and
33
- # {Cancellable#reset!} at the start of each turn. The same
34
- # instance is shared by reference across the parent, every
35
- # sub-agent, and the synthesizer rescue.
36
- # * {Interloper} — mid-loop user-input queue. The host calls
37
- # {Interloper#inject_user_message} from any thread; the
38
- # +Agent+ drains the queue at +after_tool_result+,
39
- # appending each item as a user-role message and emitting
40
- # {Event::UserTurn} with +mid_loop: true+. Not propagated to
41
- # sub-agents (the host has no handle to them).
17
+ # * {Cancellable} — cooperative cancel flag, shared by reference across the
18
+ # parent and its sub-agents.
19
+ # * {Interloper} — mid-loop user-input queue; not propagated to sub-agents.
42
20
  module Control
43
21
  end
44
22
  end