pikuri-core 0.1.0 → 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 (56) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +16 -29
  3. data/lib/pikuri/agent/chat_transport.rb +114 -33
  4. data/lib/pikuri/agent/configurator.rb +191 -110
  5. data/lib/pikuri/agent/control/cancellable.rb +25 -16
  6. data/lib/pikuri/agent/control/handoff.rb +75 -0
  7. data/lib/pikuri/agent/control/interloper.rb +87 -120
  8. data/lib/pikuri/agent/control.rb +9 -11
  9. data/lib/pikuri/agent/event.rb +73 -61
  10. data/lib/pikuri/agent/extension.rb +45 -81
  11. data/lib/pikuri/agent/history.rb +91 -497
  12. data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
  13. data/lib/pikuri/agent/listener/terminal.rb +115 -108
  14. data/lib/pikuri/agent/listener/token_log.rb +21 -55
  15. data/lib/pikuri/agent/listener.rb +4 -4
  16. data/lib/pikuri/agent/listener_list.rb +19 -13
  17. data/lib/pikuri/agent/request_instrumenter.rb +102 -0
  18. data/lib/pikuri/agent.rb +624 -448
  19. data/lib/pikuri/attachment.rb +65 -0
  20. data/lib/pikuri/extractor/passthrough.rb +5 -2
  21. data/lib/pikuri/extractor.rb +43 -12
  22. data/lib/pikuri/file_type.rb +4 -4
  23. data/lib/pikuri/finalizers.rb +2 -2
  24. data/lib/pikuri/paths.rb +1 -1
  25. data/lib/pikuri/sanitizer.rb +4 -3
  26. data/lib/pikuri/subprocess.rb +17 -5
  27. data/lib/pikuri/testing.rb +122 -49
  28. data/lib/pikuri/tool/calculator.rb +134 -30
  29. data/lib/pikuri/tool/execute_context.rb +2 -2
  30. data/lib/pikuri/tool/parameters.rb +10 -0
  31. data/lib/pikuri/tool/result.rb +164 -0
  32. data/lib/pikuri/tool/trifecta_legs.rb +52 -21
  33. data/lib/pikuri/tool.rb +298 -24
  34. data/lib/pikuri/trifecta/report.rb +28 -30
  35. data/lib/pikuri/trifecta.rb +1 -2
  36. data/lib/pikuri/version.rb +1 -1
  37. data/lib/pikuri-core.rb +5 -11
  38. metadata +16 -73
  39. data/lib/pikuri/agent/context_window_detector.rb +0 -181
  40. data/lib/pikuri/agent/control/step_limit.rb +0 -95
  41. data/lib/pikuri/agent/extension_context.rb +0 -120
  42. data/lib/pikuri/agent/listener/rate_limited.rb +0 -146
  43. data/lib/pikuri/agent/synthesizer.rb +0 -129
  44. data/lib/pikuri/extractor/html.rb +0 -256
  45. data/lib/pikuri/ruby_llm_patches.rb +0 -106
  46. data/lib/pikuri/tool/fetch.rb +0 -146
  47. data/lib/pikuri/tool/scraper.rb +0 -144
  48. data/lib/pikuri/tool/search/brave.rb +0 -170
  49. data/lib/pikuri/tool/search/duckduckgo.rb +0 -175
  50. data/lib/pikuri/tool/search/engines.rb +0 -319
  51. data/lib/pikuri/tool/search/exa.rb +0 -195
  52. data/lib/pikuri/tool/search/rate_limiter.rb +0 -115
  53. data/lib/pikuri/tool/search/result.rb +0 -24
  54. data/lib/pikuri/tool/web_scrape.rb +0 -105
  55. data/lib/pikuri/tool/web_search.rb +0 -133
  56. data/lib/pikuri/url_cache.rb +0 -96
@@ -2,119 +2,93 @@
2
2
 
3
3
  module Pikuri
4
4
  class Agent
5
- # Build-time collector yielded into the +Pikuri::Agent.new+ block. Hosts
6
- # and {Extension}s call its methods to declare tools, listeners,
7
- # +on_close+ handlers, and extension instances; {Agent#initialize} drains
8
- # the collected state into the agent's wiring before returning, then
9
- # discards the Configurator (it carries no runtime state). System-prompt
10
- # contributions are *not* collected here — the Agent pulls them from each
11
- # extension's {Extension#system_prompt_snippets} at assembly time.
5
+ # The one handle for wiring an {Agent}, yielded into the +Pikuri::Agent.new+
6
+ # block and handed to every {Extension#configure}:
12
7
  #
13
8
  # Pikuri::Agent.new(transport: ..., system_prompt: ...) do |c|
14
9
  # c.add_listener Pikuri::Agent::Listener::Terminal.new
15
- # c.add_tool Pikuri::Tool::WebSearch.build
16
- # c.add_extension Pikuri::Skill::Extension.new(catalog: catalog, root: project_root)
10
+ # c.add_tool Pikuri::Tool::CALCULATOR
11
+ # c.add_extension Pikuri::Workspace::Extension.new(filesystem: fs, confirmer: confirmer)
17
12
  # end
18
13
  #
19
- # Extensions implement +configure(c)+ against this same type, so
20
- # block-users and extensions share one API.
14
+ # Two kinds of call. *Declarations* — {#add_tool}, {#add_listener},
15
+ # {#add_extension}, {#on_close} — shape the agent being built. *Capabilities*
16
+ # — {#emit_event}, {#add_raw_tool}, {#sub_agent_listeners},
17
+ # {#replace_compacted_history} — act on the live
18
+ # agent, so an extension keeps the Configurator and uses them later, from a
19
+ # callback or a tool's +execute+:
20
+ #
21
+ # def configure(c)
22
+ # @list.on_change = -> { c.emit_event(ListChanged.new(items: @list.items)) }
23
+ # end
24
+ #
25
+ # == Why a handed object, not methods on Agent
26
+ #
27
+ # {Agent} has no public path to these capabilities (no +listeners+ or
28
+ # +chat+ reader, no emit method): holding an agent grants read access to
29
+ # its config and nothing more. The way to them is to be handed the
30
+ # Configurator — by +Agent.new+, or onward by whoever was
31
+ # ({Pikuri::SubAgent::SubAgentTool} keeps its extension's). The boundary is
32
+ # the API contract, not a mechanical seal.
21
33
  #
22
34
  # == Two tool pools: regular vs. sub-agent-only
23
35
  #
24
- # {#add_tool} registers a tool the parent agent can call (lands in {#tools},
25
- # handed to ruby_llm). {#add_sub_agent_tool} registers one the parent
26
- # *cannot* call (lands in {#sub_agent_tools}, never sent to ruby_llm for the
27
- # parent) but which {Pikuri::SubAgent::Extension}'s persona-tool-name
28
- # resolution can reach. The use case is the lethal-trifecta defense: keep
29
- # network tools (+web_search+ / +web_scrape+ / +fetch+) off the parent so a
30
- # prompt-injected file read can't egress through it, while the +researcher+
31
- # persona still reaches them via the +agent+ tool. See SECURITY.md.
36
+ # {#add_tool} registers a tool the parent agent can call. {#add_sub_agent_tool}
37
+ # registers one the parent *cannot* call, which only a sub-agent whose
38
+ # persona names it receives. The use case is the lethal-trifecta defense:
39
+ # keep network tools (+web_search+ / +web_scrape+ / +fetch+) off the parent
40
+ # so a prompt-injected file read can't egress through it, while the
41
+ # +researcher+ persona still reaches them via the +agent+ tool. See
42
+ # SECURITY.md.
43
+ #
44
+ # == Implementation details
45
+ #
46
+ # {#add_raw_tool} reaches the chat at once, so a raw tool added inside the
47
+ # block precedes the regular tools, which the Agent registers when the block
48
+ # returns. An event emitted inside the block reaches only the listeners
49
+ # added so far.
32
50
  class Configurator
33
- # @return [Agent::ChatTransport] same transport the Agent will use, so an
34
- # extension can wire helpers against the same model.
35
- attr_reader :transport
36
-
37
- # @return [String] the +system_prompt:+ kwarg, untouched — the base the
38
- # Agent prepends to the pulled {Extension#system_prompt_snippets}.
39
- attr_reader :system_prompt_base
51
+ # @return [Agent] the agent being built. Its constructor arguments
52
+ # (+transport+, +id+, +cancellable+, +interloper+, ...) are readable at
53
+ # once; what the block declares (+tools+, +system_prompt+) only once
54
+ # +Agent.new+ returns.
55
+ attr_reader :agent
40
56
 
41
- # @return [String] this agent's unique identifier; empty for the
42
- # main agent, persona-rooted (e.g. +"researcher 0"+) for sub-agents.
43
- attr_reader :id
57
+ # @return [History, nil] the conversation +Agent.new(history:)+ resumes,
58
+ # as passed in, or +nil+ for a fresh one — so an extension can rebuild
59
+ # what the transcript implies (MCP re-registers the tools of servers it
60
+ # had connected).
61
+ attr_reader :history
44
62
 
45
- # @return [Boolean] +true+ when the agent opted into chunk-level
46
- # streaming.
47
- attr_reader :streaming
48
-
49
- # @return [Control::StepLimit, nil] step-budget control passed
50
- # to the Agent ctor, or +nil+.
51
- attr_reader :step_limit
52
-
53
- # @return [Control::Cancellable, nil] cancellation control, or +nil+.
54
- # Extensions running sub-LLM calls in +configure+ share it so a user
55
- # cancel during boot propagates.
56
- attr_reader :cancellable
57
-
58
- # @return [Control::Interloper, nil] mid-loop user-input queue
59
- # passed to the Agent ctor, or +nil+.
60
- attr_reader :interloper
61
-
62
- # @return [Array<Tool>] tools added via {#add_tool}, in declaration order;
63
- # drained by {Agent#initialize} and registered with ruby_llm.
63
+ # @return [Array<Tool>] tools added via {#add_tool}, in declaration order.
64
64
  attr_reader :tools
65
65
 
66
66
  # @return [Array<Tool>] tools added via {#add_sub_agent_tool}, in
67
- # declaration order; drained but *not* registered with ruby_llm —
68
- # available only to sub-agents (see the class header).
67
+ # declaration order.
69
68
  attr_reader :sub_agent_tools
70
69
 
71
- # @return [Array<Listener::Base>] listeners added via
72
- # {#add_listener}, in declaration order. Drained by
73
- # {Agent#initialize}.
74
- attr_reader :listeners
75
-
76
- # @return [Array<Proc>] +on_close+ handlers added via
77
- # {#on_close}, in declaration order. Fired by {Agent#close}
78
- # in LIFO order with per-handler rescue.
79
- attr_reader :on_close_handlers
80
-
81
- # @return [Array<#configure>] extension instances added via
82
- # {#add_extension}, in declaration order. The Agent calls +bind+ on
83
- # each after wiring is complete.
70
+ # @return [Array<Extension>] extensions added via {#add_extension}, in
71
+ # declaration order.
84
72
  attr_reader :extensions
85
73
 
86
- # @param transport [Agent::ChatTransport]
87
- # @param system_prompt_base [String]
88
- # @param id [String]
89
- # @param streaming [Boolean]
90
- # @param step_limit [Control::StepLimit, nil]
91
- # @param cancellable [Control::Cancellable, nil]
92
- # @param interloper [Control::Interloper, nil]
93
- # @param on_close_sink [Array<Proc>, nil] array {#on_close} appends to.
94
- # {Agent#initialize} passes its live +@on_close_handlers+ so a handler
95
- # armed via +c.on_close+ is reachable instantly — what lets the
96
- # constructor close a half-built agent if a later +configure+ raises.
97
- # Defaults to a fresh array (standalone/spec use).
98
- def initialize(transport:, system_prompt_base:, id:, streaming:,
99
- step_limit:, cancellable:, interloper:,
100
- on_close_sink: nil)
101
- @transport = transport
102
- @system_prompt_base = system_prompt_base
103
- @id = id
104
- @streaming = streaming
105
- @step_limit = step_limit
106
- @cancellable = cancellable
107
- @interloper = interloper
108
-
74
+ # @param agent [Agent] the agent under construction
75
+ # @param chat [RubyLLM::Chat] its chat, the target of {#add_raw_tool}
76
+ # @param listeners [ListenerList] its listener list
77
+ # @param history [History, nil]
78
+ # @param on_close_sink [Array<Proc>] the agent's live +on_close+ list, so
79
+ # a handler armed mid-block is there when a later +configure+ raises
80
+ # and the constructor closes the half-built agent.
81
+ def initialize(agent:, chat:, listeners:, history:, on_close_sink:)
82
+ @agent = agent
83
+ @chat = chat
84
+ @listeners = listeners
85
+ @history = history
86
+ @on_close_handlers = on_close_sink
109
87
  @tools = []
110
88
  @sub_agent_tools = []
111
- @listeners = []
112
- @on_close_handlers = on_close_sink || []
113
89
  @extensions = []
114
90
  end
115
91
 
116
- # Append a tool to the agent's static tool list.
117
- #
118
92
  # @param tool [Tool]
119
93
  # @return [void]
120
94
  def add_tool(tool)
@@ -122,20 +96,14 @@ module Pikuri
122
96
  nil
123
97
  end
124
98
 
125
- # Append several tools at once. Equivalent to calling {#add_tool}
126
- # for each element of +tools+; declaration order is preserved.
127
- #
128
99
  # @param tools [Enumerable<Tool>]
129
100
  # @return [void]
130
101
  def add_tools(tools)
131
- tools.each { |t| @tools << t }
102
+ tools.each { |t| add_tool(t) }
132
103
  nil
133
104
  end
134
105
 
135
- # Append a tool to the sub-agent-only pool. The parent LLM
136
- # never sees it; only sub-agents whose persona +tool_names+
137
- # include the tool's +name+ get it in their toolset. See the
138
- # class header for the trifecta-defense rationale.
106
+ # Add a tool only sub-agents can receive; see +== Two tool pools+.
139
107
  #
140
108
  # @param tool [Tool]
141
109
  # @return [void]
@@ -144,33 +112,35 @@ module Pikuri
144
112
  nil
145
113
  end
146
114
 
147
- # Append a listener to the agent's listener list.
148
- #
149
115
  # @param listener [Listener::Base]
150
116
  # @return [void]
151
117
  def add_listener(listener)
152
- @listeners << listener
118
+ @listeners.add(listener)
153
119
  nil
154
120
  end
155
121
 
156
- # Append several listeners at once. Accepts any enumerable
157
- # (Array, {ListenerList}, …); declaration order is preserved.
158
- #
159
122
  # @param listeners [Enumerable<Listener::Base>]
160
123
  # @return [void]
161
124
  def add_listeners(listeners)
162
- listeners.each { |l| @listeners << l }
125
+ listeners.each { |l| add_listener(l) }
163
126
  nil
164
127
  end
165
128
 
166
- # Register an extension: its +configure(self)+ runs immediately (so
167
- # source order matches execution order), and the instance is retained for
168
- # the +bind(ctx)+ sweep at the end of {Agent#initialize}. Both hooks are
169
- # required — +include Pikuri::Agent::Extension+ for no-op defaults.
129
+ # Register an extension and run its +configure(self)+ at once, so source
130
+ # order is execution order: a later extension sees what earlier ones
131
+ # added. +include Pikuri::Agent::Extension+ for no-op defaults.
132
+ #
133
+ # An instance serves one agent ({Extension}), so one already added to
134
+ # any agent — this one included, and even after that agent closed — is
135
+ # refused before its +configure+ runs. Reuse is a host bug that fails
136
+ # quietly otherwise: the second agent would share the first one's
137
+ # per-conversation state and the servers it started.
170
138
  #
171
- # @param extension [Extension, #configure, #bind] extension instance
139
+ # @param extension [Extension, #configure] extension instance
172
140
  # @return [void]
141
+ # @raise [ArgumentError] when +extension+ was already added to an agent
173
142
  def add_extension(extension)
143
+ claim(extension)
174
144
  @extensions << extension
175
145
  extension.configure(self)
176
146
  nil
@@ -187,6 +157,117 @@ module Pikuri
187
157
  @on_close_handlers << blk
188
158
  nil
189
159
  end
160
+
161
+ # Emit a domain event onto the agent's listener stream. Core {Event}
162
+ # variants narrate the loop; gems define their own (e.g. a task list's
163
+ # +ListChanged+) and emit them here. Listeners no-op on
164
+ # variants they don't recognize ({Listener::Base#on_event}'s default).
165
+ #
166
+ # Call it on the agent's thread — typically inside a tool's +execute+,
167
+ # landing between {Event::ToolCall} and {Event::ToolResult}.
168
+ #
169
+ # @param event [Object] an immutable event value (by convention a +Data+)
170
+ # @return [void]
171
+ def emit_event(event)
172
+ @listeners.on_event(event)
173
+ nil
174
+ end
175
+
176
+ # Register a raw +RubyLLM::Tool+ subclass on the agent's chat, bypassing
177
+ # {Pikuri::Tool}'s strict validation — MCP's tools, whose schema is the
178
+ # server's. Usable mid-conversation (+mcp_connect+ adds a server's tools
179
+ # when the model asks).
180
+ #
181
+ # The tool does NOT enter {Agent#tools}, so sub-agents can't snapshot it:
182
+ # activation is strictly per-agent.
183
+ #
184
+ # @param ruby_llm_tool [Class] subclass of +RubyLLM::Tool+
185
+ # @return [void]
186
+ def add_raw_tool(ruby_llm_tool)
187
+ @chat.with_tools(ruby_llm_tool)
188
+ nil
189
+ end
190
+
191
+ # Replace the conversation with a shorter rendering of *itself* — the
192
+ # actuator a compaction extension drives, deciding when and how to
193
+ # shorten on its own:
194
+ #
195
+ # def configure(c)
196
+ # @c = c
197
+ # end
198
+ #
199
+ # def on_user_message(_content, _attachments)
200
+ # @c.replace_compacted_history(compact(@c.agent.export_history)) if over_budget?
201
+ # nil
202
+ # end
203
+ #
204
+ # Only the messages change. Tools, MCP connections and the servers
205
+ # behind them, every extension's state (a workspace's read-marks,
206
+ # promoted skills), listeners, the system prompt and the transport all
207
+ # stand, because a compacted conversation is still the same
208
+ # conversation. The incoming messages get {Agent}'s resume repairs.
209
+ #
210
+ # So +history+ must be *this* conversation, shortened: handed a
211
+ # different one, that conversation inherits everything this one built
212
+ # up, the logged-in browser behind an MCP server included. Nothing
213
+ # checks this beyond the shape below; the name is the guard. See
214
+ # +design/decisions.md+ +D_compaction_in_place+.
215
+ #
216
+ # Shape it must keep, enforced:
217
+ #
218
+ # - end with the conversation's current last message, same {History::Message#id};
219
+ # rewriting its content is fine;
220
+ # - keep each tool result right after the assistant turn that made its call.
221
+ #
222
+ # Keep the ids of every other message you carry over too, so state an
223
+ # extension keys on one still finds it. Callable on the agent's thread
224
+ # anywhere outside an open tool batch: between turns, or from
225
+ # {Extension#on_user_message}.
226
+ #
227
+ # @param history [History] typically {Agent#export_history}, shortened
228
+ # @return [void]
229
+ # @raise [ArgumentError] if +history+ breaks the shape above
230
+ # @raise [RuntimeError] inside the +Agent.new+ block, or while a tool
231
+ # batch is open (from a tool's +execute+)
232
+ def replace_compacted_history(history)
233
+ # Private on Agent, so holding an agent doesn't grant it.
234
+ @agent.send(:replace_compacted_history, history)
235
+ nil
236
+ end
237
+
238
+ # A listener list for a spawned sub-agent, via {ListenerList#for_sub_agent}.
239
+ #
240
+ # @param params [Hash{Symbol => Object}] forwarded to each listener's
241
+ # +for_sub_agent+ hook (currently +id:+)
242
+ # @return [ListenerList]
243
+ def sub_agent_listeners(**params)
244
+ @listeners.for_sub_agent(**params)
245
+ end
246
+
247
+ # Every extension ever added, process-wide. Keyed by identity (a
248
+ # +WeakMap+, not a +WeakKeyMap+, so two equal value objects stay two
249
+ # extensions) and weak, so a claim never keeps an extension alive.
250
+ CLAIMED = ObjectSpace::WeakMap.new
251
+ # Agents may be built on several threads; the check and the mark are
252
+ # one step.
253
+ CLAIM_LOCK = Mutex.new
254
+ private_constant :CLAIMED, :CLAIM_LOCK
255
+
256
+ private
257
+
258
+ # @param extension [Object]
259
+ # @return [void]
260
+ # @raise [ArgumentError] when +extension+ is already claimed
261
+ def claim(extension)
262
+ CLAIM_LOCK.synchronize do
263
+ if CLAIMED.key?(extension)
264
+ raise ArgumentError, "#{extension.class} instance is already added to an agent; " \
265
+ 'build a fresh one for every Agent.new'
266
+ end
267
+
268
+ CLAIMED[extension] = true
269
+ end
270
+ end
190
271
  end
191
272
  end
192
273
  end
@@ -10,6 +10,17 @@ module Pikuri
10
10
  # {Agent#run_loop} catches, emits as {Event::Cancelled}, and re-raises so
11
11
  # the REPL returns control to the user.
12
12
  #
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!
19
+ #
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.
23
+ #
13
24
  # == Cancellation boundary
14
25
  #
15
26
  # The +Agent+ calls {#check!} from +before_tool_call+ — between an LLM
@@ -19,11 +30,12 @@ module Pikuri
19
30
  # (the response lands, then the next boundary trips), nor is an in-flight
20
31
  # tool (notably +Bash+). Both are the intentional "gentle cancel" v1 scope.
21
32
  #
22
- # {#sleep} widens that boundary by one case: code *waiting* inside a tool
23
- # can wait through this instead of +Kernel#sleep+ and become
24
- # interruptible. It reaches waits only — a thread blocked in IO (a Faraday
25
- # read, +Subprocess#wait+) is still uninterruptible, so most of a tool's
26
- # blocking is untouched by design.
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.
27
39
  #
28
40
  # == Sub-agent semantics
29
41
  #
@@ -45,7 +57,7 @@ module Pikuri
45
57
  end
46
58
  end
47
59
 
48
- # Longest a {#sleep} stays unresponsive to a {#cancel!}: it wakes on
60
+ # Longest a {#sleep} or {Handoff#await} stays unresponsive to a {#cancel!}: it wakes on
49
61
  # this cadence to re-check the flag. Polling rather than a
50
62
  # +ConditionVariable+ because {#cancel!} must stay callable from a
51
63
  # SIGINT trap, where taking a +Mutex+ raises +ThreadError+ — so the
@@ -118,21 +130,18 @@ module Pikuri
118
130
  end
119
131
  end
120
132
 
121
- # Reset the flag to armed. Called by {Agent} at each turn start so a
122
- # stale cancel doesn't poison the next turn. Mid-loop
123
- # {Control::Interloper} injections deliberately do *not* reset —
124
- # otherwise cancel-then-inject would lose the cancel (the injection
125
- # resets the flag before the next +before_tool_call+ reads it).
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+.
126
140
  #
127
141
  # @return [void]
128
142
  def reset!
129
143
  @cancelled = false
130
144
  end
131
-
132
- # @return [String] short label for {Agent#to_s}, reflecting the flag state.
133
- def to_s
134
- "Cancellable(#{@cancelled ? 'cancelled' : 'armed'})"
135
- end
136
145
  end
137
146
  end
138
147
  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