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.
- checksums.yaml +4 -4
- data/README.md +17 -30
- data/lib/pikuri/agent/chat_transport.rb +168 -107
- data/lib/pikuri/agent/configurator.rb +194 -173
- data/lib/pikuri/agent/control/cancellable.rb +100 -70
- data/lib/pikuri/agent/control/handoff.rb +75 -0
- data/lib/pikuri/agent/control/interloper.rb +107 -118
- data/lib/pikuri/agent/control.rb +13 -35
- data/lib/pikuri/agent/event.rb +144 -197
- data/lib/pikuri/agent/extension.rb +83 -95
- data/lib/pikuri/agent/history.rb +247 -0
- data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
- data/lib/pikuri/agent/listener/terminal.rb +169 -136
- data/lib/pikuri/agent/listener/token_log.rb +84 -157
- data/lib/pikuri/agent/listener.rb +24 -44
- data/lib/pikuri/agent/listener_list.rb +32 -47
- data/lib/pikuri/agent/request_instrumenter.rb +102 -0
- data/lib/pikuri/agent.rb +1095 -577
- data/lib/pikuri/attachment.rb +65 -0
- data/lib/pikuri/bundler_env.rb +68 -0
- data/lib/pikuri/extractor/passthrough.rb +24 -31
- data/lib/pikuri/extractor.rb +125 -155
- data/lib/pikuri/file_type.rb +64 -136
- data/lib/pikuri/finalizers.rb +32 -47
- data/lib/pikuri/paths.rb +104 -13
- data/lib/pikuri/sanitizer.rb +46 -67
- data/lib/pikuri/subprocess.rb +86 -118
- data/lib/pikuri/testing.rb +369 -0
- data/lib/pikuri/tool/calculator.rb +168 -74
- data/lib/pikuri/tool/execute_context.rb +42 -0
- data/lib/pikuri/tool/parameters.rb +31 -29
- data/lib/pikuri/tool/result.rb +164 -0
- data/lib/pikuri/tool/trifecta_legs.rb +248 -0
- data/lib/pikuri/tool.rb +416 -67
- data/lib/pikuri/trifecta/contribution.rb +43 -0
- data/lib/pikuri/trifecta/node.rb +47 -0
- data/lib/pikuri/trifecta/report.rb +228 -0
- data/lib/pikuri/trifecta.rb +126 -0
- data/lib/pikuri/version.rb +1 -1
- data/lib/pikuri-core.rb +70 -92
- data/prompts/agent-loop.txt +5 -0
- data/prompts/pikuri-chat.txt +3 -12
- metadata +26 -72
- data/lib/pikuri/agent/context_window_detector.rb +0 -222
- data/lib/pikuri/agent/control/step_limit.rb +0 -111
- data/lib/pikuri/agent/extension_context.rb +0 -147
- data/lib/pikuri/agent/listener/rate_limited.rb +0 -172
- data/lib/pikuri/agent/synthesizer.rb +0 -171
- data/lib/pikuri/extractor/html.rb +0 -303
- data/lib/pikuri/tool/fetch.rb +0 -172
- data/lib/pikuri/tool/scraper.rb +0 -186
- data/lib/pikuri/tool/search/brave.rb +0 -198
- data/lib/pikuri/tool/search/duckduckgo.rb +0 -207
- data/lib/pikuri/tool/search/engines.rb +0 -186
- data/lib/pikuri/tool/search/exa.rb +0 -229
- data/lib/pikuri/tool/search/rate_limiter.rb +0 -92
- data/lib/pikuri/tool/search/result.rb +0 -29
- data/lib/pikuri/tool/web_scrape.rb +0 -121
- data/lib/pikuri/tool/web_search.rb +0 -57
- data/lib/pikuri/url_cache.rb +0 -112
data/lib/pikuri/tool.rb
CHANGED
|
@@ -5,45 +5,122 @@ require 'ruby_llm'
|
|
|
5
5
|
module Pikuri
|
|
6
6
|
# A tool the LLM can request via OpenAI-style tool calling.
|
|
7
7
|
#
|
|
8
|
-
#
|
|
9
|
-
#
|
|
10
|
-
#
|
|
11
|
-
# the +Agent+
|
|
12
|
-
#
|
|
13
|
-
#
|
|
14
|
-
#
|
|
15
|
-
# Bundled tool implementations live under +lib/tool/+ and are required
|
|
16
|
-
# explicitly by the scripts that use them; +lib/tool.rb+ itself only
|
|
17
|
-
# introduces the {Tool} class and {Tool::Parameters} machinery.
|
|
8
|
+
# A plain value object — +name+, +description+, +parameters+, and an
|
|
9
|
+
# +execute+ Proc that produces the observation. Pikuri's code talks to this
|
|
10
|
+
# surface; conversion to ruby_llm's runtime shape happens at exactly one seam,
|
|
11
|
+
# {#to_ruby_llm_tool}, which the +Agent+ calls when wiring tools into the
|
|
12
|
+
# +RubyLLM::Chat+. Bundled implementations live under +lib/tool/+ and are
|
|
13
|
+
# required explicitly by the scripts that use them.
|
|
18
14
|
#
|
|
19
15
|
# == Validation ordering
|
|
20
16
|
#
|
|
21
|
-
# Pikuri's {Parameters#validate}
|
|
22
|
-
# all-errors-collected
|
|
23
|
-
#
|
|
24
|
-
#
|
|
25
|
-
#
|
|
26
|
-
#
|
|
27
|
-
# pikuri's validator runs inside {#run} before any user code does.
|
|
17
|
+
# Pikuri's {Parameters#validate} (DidYouMean suggestions, type coercion,
|
|
18
|
+
# all-errors-collected) is what the LLM must see on bad arguments, not
|
|
19
|
+
# ruby_llm's keyword-presence checker. The synthetic class from
|
|
20
|
+
# {#to_ruby_llm_tool} defines +execute(**args)+: the keyrest signature makes
|
|
21
|
+
# +RubyLLM::Tool#validate_keyword_arguments+ no-op, so pikuri's validator runs
|
|
22
|
+
# inside {#run} before any user code.
|
|
28
23
|
#
|
|
29
24
|
# == Error handling convention
|
|
30
25
|
#
|
|
31
|
-
#
|
|
32
|
-
#
|
|
33
|
-
#
|
|
34
|
-
#
|
|
35
|
-
#
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
#
|
|
40
|
-
#
|
|
41
|
-
#
|
|
42
|
-
#
|
|
43
|
-
#
|
|
44
|
-
#
|
|
45
|
-
#
|
|
46
|
-
#
|
|
26
|
+
# * *Recoverable* failures (bad arguments, HTTP 4xx/5xx, network blips,
|
|
27
|
+
# rate-limits, division by zero, ...) come back as +"Error: <message>"+
|
|
28
|
+
# Strings and become the next observation, so the model self-corrects.
|
|
29
|
+
# * *Bugs* in pikuri's own code (parser regressions, schema misuse, ...) keep
|
|
30
|
+
# raising — the LLM can't fix them.
|
|
31
|
+
#
|
|
32
|
+
# {#run} catches {Parameters#validate} failures into +"Error: ..."+; the
|
|
33
|
+
# +execute+ Proc follows the same convention for its own recoverable failures
|
|
34
|
+
# and lets bugs raise.
|
|
35
|
+
#
|
|
36
|
+
# == Display lines
|
|
37
|
+
#
|
|
38
|
+
# A chrome shows one call as three short strings it styles, caps and defangs
|
|
39
|
+
# but never composes:
|
|
40
|
+
#
|
|
41
|
+
# Write(lib/shared/config.rb)
|
|
42
|
+
# Added 2 lines, removed 3 lines
|
|
43
|
+
#
|
|
44
|
+
# The tool owns all three, because at +execute+ time it still holds the
|
|
45
|
+
# structure it is about to flatten for the model — 23 result structs, a line
|
|
46
|
+
# count, an exit status — which no renderer can recover from the Markdown it
|
|
47
|
+
# gets. {#display_name} and {#describe_call} answer the call side;
|
|
48
|
+
# {Result#summary} answers the result side. Each default is mechanical
|
|
49
|
+
# ({.display_name_for}, the first required parameter, {.describe_content}), so
|
|
50
|
+
# a tool declaring nothing — every MCP tool, every third-party +Tool+ — still
|
|
51
|
+
# renders.
|
|
52
|
+
#
|
|
53
|
+
# Never the *model*: a narrated status line is steerable through a fetched
|
|
54
|
+
# page. {Result} carries the two rules a summary obeys.
|
|
55
|
+
#
|
|
56
|
+
# == One return type
|
|
57
|
+
#
|
|
58
|
+
# An +execute+ returns a {Result}, always — the observation plus its display
|
|
59
|
+
# line, with {Result.error} for a recoverable failure. {#run} enforces it,
|
|
60
|
+
# wrapping a bare String from a third-party +Tool+ rather than refusing it.
|
|
61
|
+
#
|
|
62
|
+
# There is no second success shape to choose between: an *attachment*
|
|
63
|
+
# observation (the image {Pikuri::Workspace::Read} answers for a PNG) is a
|
|
64
|
+
# +Result+ with non-empty {Result#attachments}, and the sole place that
|
|
65
|
+
# distinction is visible is the four-line wrapper in
|
|
66
|
+
# {#to_ruby_llm_tool}, which no tool reads.
|
|
67
|
+
#
|
|
68
|
+
# == Sharing: may one instance serve two agents?
|
|
69
|
+
#
|
|
70
|
+
# {Pikuri::Agent} is thread-unsafe, so a host running ten agents in one VM
|
|
71
|
+
# serializes each agent's own calls — usually a thread apiece. That makes
|
|
72
|
+
# "may a second agent have this tool?" and "is this reachable from two
|
|
73
|
+
# threads?" one question. Every tool answers it, as a +Sharing:+ tail or a
|
|
74
|
+
# +== Sharing+ section, naming one posture:
|
|
75
|
+
#
|
|
76
|
+
# * *P_stateless* — no mutable state. Share freely.
|
|
77
|
+
# * *P_shared_locked* — process-wide mutable state under a lock. Sharing is
|
|
78
|
+
# intended, and for anything pacing a shared *external* resource it is
|
|
79
|
+
# mandatory: a per-agent rate limiter (pikuri-web's search engines) would let ten agents fire
|
|
80
|
+
# ten simultaneous requests from one IP and earn the ban it exists to
|
|
81
|
+
# avoid.
|
|
82
|
+
# * *P_shared_benign* — unprotected process-wide state whose race is
|
|
83
|
+
# harmless; the doc names the race (pikuri-web's on-disk URL cache: both callers
|
|
84
|
+
# compute a cold key and write identical bytes).
|
|
85
|
+
# * *P_one_agent* — agent-scoped state, so exactly one agent. It needs no
|
|
86
|
+
# lock because its only caller is that agent, whose calls are already
|
|
87
|
+
# serialized; wire it twice and you lose that for free. And the first
|
|
88
|
+
# failure isn't a race but a correctness bug — agent A would read agent B's
|
|
89
|
+
# facts single-threaded too.
|
|
90
|
+
#
|
|
91
|
+
# +P_one_agent+ is a fine answer, not a defect: most of what a tool knows is
|
|
92
|
+
# one conversation's business. Nothing enforces it, so the doc *is* the
|
|
93
|
+
# contract. The two axes stay independent — a tool can take a lock *and* hold
|
|
94
|
+
# per-agent state, so "thread-safe" is no licence to share.
|
|
95
|
+
#
|
|
96
|
+
# A +Tool+ is a value object holding a +Proc+, so its posture is its
|
|
97
|
+
# collaborators': each tool names the one that owns the state, which is also
|
|
98
|
+
# where any lock lives.
|
|
99
|
+
#
|
|
100
|
+
# The one way to break the premise from outside pikuri: ruby_llm's
|
|
101
|
+
# +tool_concurrency+ config (default +false+) makes +Chat+ run a tool batch on
|
|
102
|
+
# threads, so a *single* agent would enter its own +P_one_agent+ tools
|
|
103
|
+
# concurrently. Leave it off.
|
|
104
|
+
#
|
|
105
|
+
# == Cancellation
|
|
106
|
+
#
|
|
107
|
+
# A tool that *waits* can opt into being interrupted: pass
|
|
108
|
+
# +wants_context: true+ and take a +context:+ keyword, then wait through
|
|
109
|
+
# {Pikuri::Agent::Control::Cancellable#sleep} on the {ExecuteContext} handed
|
|
110
|
+
# in.
|
|
111
|
+
#
|
|
112
|
+
# wants_context: true,
|
|
113
|
+
# execute: ->(query:, context:) { backend.search(query, cancellable: context.cancellable) }
|
|
114
|
+
#
|
|
115
|
+
# Opt-in rather than universal because most tools have nothing to cancel, and
|
|
116
|
+
# because a token only reaches *waits* — a tool blocked in IO (a Faraday read,
|
|
117
|
+
# +Subprocess#wait+) stays uninterruptible however many tokens it holds.
|
|
118
|
+
#
|
|
119
|
+
# Per *call*, not per construction, and that is the point: {#to_ruby_llm_tool}
|
|
120
|
+
# mints a fresh wrapper per agent, so even a +P_shared_locked+ tool shared by
|
|
121
|
+
# ten agents honours whichever one is actually waiting. The context is always
|
|
122
|
+
# a real object ({ExecuteContext.default}, whose cancellation never trips,
|
|
123
|
+
# when the host wired none), so an +execute+ never nil-checks it.
|
|
47
124
|
class Tool
|
|
48
125
|
# @return [String] function name advertised to the LLM
|
|
49
126
|
attr_reader :name
|
|
@@ -57,70 +134,342 @@ module Pikuri
|
|
|
57
134
|
# LLM
|
|
58
135
|
attr_reader :parameters
|
|
59
136
|
|
|
60
|
-
# @return [Proc] callable invoked
|
|
61
|
-
#
|
|
62
|
-
# The usual return is a +String+; tools that want to deliver
|
|
63
|
-
# multimodal observations (e.g. {Pikuri::Workspace::Read} on a
|
|
64
|
-
# PNG) may instead return a +RubyLLM::Content+ with attachments,
|
|
65
|
-
# which +RubyLLM::Chat#handle_tool_calls+ accepts via its
|
|
66
|
-
# +content_like?+ check and the per-provider Media formatters turn
|
|
67
|
-
# into the right image / document blocks inside +tool_result+.
|
|
137
|
+
# @return [Proc] callable invoked with validated keyword arguments,
|
|
138
|
+
# returning the observation as a {Result} — see +== One return type+.
|
|
68
139
|
attr_reader :execute
|
|
69
140
|
|
|
141
|
+
# @return [Tool::TrifectaLegs] which lethal-trifecta legs this tool
|
|
142
|
+
# contributes, for {Pikuri::Trifecta}
|
|
143
|
+
attr_reader :trifecta_legs
|
|
144
|
+
|
|
70
145
|
# @param name [String] function name advertised to the LLM
|
|
71
146
|
# @param description [String] human-readable description used by the LLM
|
|
72
147
|
# to decide when to call the tool
|
|
73
148
|
# @param parameters [Tool::Parameters] declared schema
|
|
74
|
-
# @param execute [Proc] callable invoked with validated keyword arguments
|
|
75
|
-
#
|
|
76
|
-
#
|
|
77
|
-
#
|
|
78
|
-
#
|
|
149
|
+
# @param execute [Proc] callable invoked with validated keyword arguments,
|
|
150
|
+
# returning a {Result} (see {#execute}). Recoverable failures answer
|
|
151
|
+
# {Result.error} rather than raise.
|
|
152
|
+
# @param trifecta_legs [Tool::TrifectaLegs] legs this tool contributes.
|
|
153
|
+
# Compute them here rather than at a later resolution pass: construction
|
|
154
|
+
# *is* wiring time, since every collaborator that decides a leg (the
|
|
155
|
+
# workspace, the sandbox, the confirmer) is already a kwarg of the tool
|
|
156
|
+
# that uses it. Defaults to {TrifectaLegs::ASSUMED} — an undeclared tool is
|
|
157
|
+
# presumed hostile on both axes the framework could have determined.
|
|
158
|
+
# @param wants_context [Boolean] when +true+, {#run} additionally passes a
|
|
159
|
+
# +context:+ keyword carrying this call's {ExecuteContext} — so +execute+
|
|
160
|
+
# must declare one. Declared rather than inferred from the Proc, and both
|
|
161
|
+
# halves are mandatory, so either without the other is an +ArgumentError+
|
|
162
|
+
# on the first call rather than a silent +nil+.
|
|
79
163
|
# @return [Tool]
|
|
80
|
-
def initialize(name:, description:, parameters:, execute
|
|
164
|
+
def initialize(name:, description:, parameters:, execute:,
|
|
165
|
+
trifecta_legs: TrifectaLegs::ASSUMED, wants_context: false)
|
|
81
166
|
@name = name
|
|
82
167
|
@description = description
|
|
83
168
|
@parameters = parameters
|
|
84
169
|
@execute = execute
|
|
170
|
+
@trifecta_legs = trifecta_legs
|
|
171
|
+
@wants_context = wants_context
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# @return [Boolean] whether {#run} hands +execute+ a +context:+ keyword
|
|
175
|
+
# carrying the {ExecuteContext} for this call. Declared at construction,
|
|
176
|
+
# never inferred from the Proc's signature — see the +== Cancellation+
|
|
177
|
+
# section.
|
|
178
|
+
attr_reader :wants_context
|
|
179
|
+
|
|
180
|
+
# CamelCase display form of a *raw* tool name, for the three cases with no
|
|
181
|
+
# +Tool+ instance to ask: a raw tool from {Agent::Configurator#add_raw_tool}
|
|
182
|
+
# (an MCP server's, which bypasses {Pikuri::Tool}),
|
|
183
|
+
# ruby_llm's unavailable-tool error, a replayed history.
|
|
184
|
+
#
|
|
185
|
+
# Tool.display_name_for('web_search') # => "WebSearch"
|
|
186
|
+
# Tool.display_name_for('openlibrary__search_books') # => "Openlibrary::SearchBooks"
|
|
187
|
+
#
|
|
188
|
+
# +__+ separates an MCP server's name from its tool's, so the halves CamelCase
|
|
189
|
+
# and join with +::+; inside a half any non-alphanumeric run is a word break
|
|
190
|
+
# (an MCP name may carry +-+ or +.+, which ruby_llm sanitizes to +_+).
|
|
191
|
+
#
|
|
192
|
+
# Deterministic beats pretty — +fileindex_search+ becomes +FileindexSearch+
|
|
193
|
+
# and a tool wanting +LSP+ overrides {#display_name}.
|
|
194
|
+
#
|
|
195
|
+
# @param name [String] the function name advertised to the LLM
|
|
196
|
+
# @return [String] display form; +""+ for a blank name
|
|
197
|
+
def self.display_name_for(name)
|
|
198
|
+
name.to_s.split('__').filter_map { |segment|
|
|
199
|
+
words = segment.split(/[^A-Za-z0-9]+/).reject(&:empty?)
|
|
200
|
+
words.map { |w| w[0].upcase + w[1..] }.join unless words.empty?
|
|
201
|
+
}.join('::')
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# Every supplied argument as +k=v+ — the display line for a tool whose
|
|
205
|
+
# {Parameters} are unknown (an MCP tool, a replayed call) or which declares
|
|
206
|
+
# no required parameter.
|
|
207
|
+
#
|
|
208
|
+
# Tool.describe_arguments('from' => 'bob', 'after' => '2026-09')
|
|
209
|
+
# # => "from=bob after=2026-09"
|
|
210
|
+
#
|
|
211
|
+
# @param arguments [Hash] raw tool-call arguments
|
|
212
|
+
# @return [String] one line; +""+ for no arguments or a non-Hash
|
|
213
|
+
def self.describe_arguments(arguments)
|
|
214
|
+
return '' unless arguments.is_a?(Hash)
|
|
215
|
+
|
|
216
|
+
one_line(arguments.map { |k, v| "#{k}=#{describe_value(v)}" }.join(' '))
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# Generic structural summary of an observation — the result line for a tool
|
|
220
|
+
# that returned a bare String rather than a {Result}.
|
|
221
|
+
#
|
|
222
|
+
# Tool.describe_content("a\nb\nc") # => "Returned 3 lines"
|
|
223
|
+
# Tool.describe_content('Error: no such file') # => "Error: no such file"
|
|
224
|
+
#
|
|
225
|
+
# An +"Error: ..."+ observation shows its own first line, because that *is*
|
|
226
|
+
# the status the reader needs. ruby_llm's unavailable-tool +Hash+ passes its
|
|
227
|
+
# +:error+ through the same way.
|
|
228
|
+
#
|
|
229
|
+
# @param content [String, Array<String, RubyLLM::Attachment>, Hash]
|
|
230
|
+
# whatever reached +after_tool_result+ — an Array is an attachment
|
|
231
|
+
# observation as {#to_ruby_llm_tool} hands it over
|
|
232
|
+
# @return [String] one line
|
|
233
|
+
def self.describe_content(content)
|
|
234
|
+
return one_line(content[:error].to_s) if content.is_a?(Hash) && content[:error]
|
|
235
|
+
return describe_attachments(content) if content.is_a?(Array) && content.any?(RubyLLM::Attachment)
|
|
236
|
+
|
|
237
|
+
text = content.to_s
|
|
238
|
+
return one_line(text.lines.first.to_s) if text.start_with?('Error:')
|
|
239
|
+
|
|
240
|
+
lines = text.lines.size
|
|
241
|
+
lines > 1 ? "Returned #{lines} lines" : "Returned #{text.bytesize} bytes"
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# Flatten +text+ to one line — every display string a tool composes goes
|
|
245
|
+
# through this, since a summary or an argument spanning two lines would
|
|
246
|
+
# break the one-call-one-line shape every renderer assumes.
|
|
247
|
+
#
|
|
248
|
+
# @param text [String, nil]
|
|
249
|
+
# @return [String] whitespace runs collapsed to single spaces, stripped
|
|
250
|
+
def self.one_line(text)
|
|
251
|
+
text.to_s.gsub(/\s+/, ' ').strip
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# A count with its noun pluralized — display lines are mostly counting.
|
|
255
|
+
#
|
|
256
|
+
# "Matched #{Tool.pluralize(1, 'file')}" # => "Matched 1 file"
|
|
257
|
+
# "Matched #{Tool.pluralize(7, 'match', 'matches')}" # => "Matched 7 matches"
|
|
258
|
+
#
|
|
259
|
+
# @param number [Integer]
|
|
260
|
+
# @param singular [String]
|
|
261
|
+
# @param plural [String, nil] defaults to +singular+ + +"s"+
|
|
262
|
+
# @return [String]
|
|
263
|
+
def self.pluralize(number, singular, plural = nil)
|
|
264
|
+
number == 1 ? "#{number} #{singular}" : "#{number} #{plural || "#{singular}s"}"
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# Byte count in the largest unit that keeps it short.
|
|
268
|
+
#
|
|
269
|
+
# Tool.format_bytes(3_162) # => "3.1 kB"
|
|
270
|
+
#
|
|
271
|
+
# @param bytes [Integer]
|
|
272
|
+
# @return [String]
|
|
273
|
+
def self.format_bytes(bytes)
|
|
274
|
+
return "#{bytes} B" if bytes < 1024
|
|
275
|
+
return format('%.1f kB', bytes / 1024.0) if bytes < 1024 * 1024
|
|
276
|
+
|
|
277
|
+
format('%.1f MB', bytes / (1024.0 * 1024))
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# @param value [String, Numeric, Boolean, Array, nil] one argument value,
|
|
281
|
+
# as ruby_llm parsed it out of the model's JSON
|
|
282
|
+
# @return [String] +to_s+, except an Array, which joins with +", "+ so a
|
|
283
|
+
# list argument reads as a list rather than as +["a", "b"]+
|
|
284
|
+
def self.describe_value(value)
|
|
285
|
+
value.is_a?(Array) ? value.join(', ') : value.to_s
|
|
85
286
|
end
|
|
86
287
|
|
|
87
|
-
#
|
|
88
|
-
#
|
|
89
|
-
#
|
|
90
|
-
#
|
|
288
|
+
# @param parts [Array<String, RubyLLM::Attachment>] holding at least one
|
|
289
|
+
# attachment
|
|
290
|
+
# @return [String] +"Returned image/png, 40.2 kB"+, or the mime alone when
|
|
291
|
+
# the size isn't free
|
|
292
|
+
def self.describe_attachments(parts)
|
|
293
|
+
attachment = parts.find { |p| p.is_a?(RubyLLM::Attachment) }
|
|
294
|
+
|
|
295
|
+
size = attachment_bytesize(attachment)
|
|
296
|
+
size ? "Returned #{attachment.mime_type}, #{format_bytes(size)}" : "Returned #{attachment.mime_type}"
|
|
297
|
+
end
|
|
298
|
+
private_class_method :describe_attachments
|
|
299
|
+
|
|
300
|
+
# @param attachment [RubyLLM::Attachment]
|
|
301
|
+
# @return [Integer, nil] the attachment's size, or +nil+ when reading it
|
|
302
|
+
# would cost more than a display line is worth
|
|
303
|
+
def self.attachment_bytesize(attachment)
|
|
304
|
+
# +Attachment#content+ fetches a URL-backed source over the network — a
|
|
305
|
+
# display line must never do that, and no test would catch it.
|
|
306
|
+
return File.size(attachment.source.to_s) if attachment.path?
|
|
307
|
+
return attachment.content&.bytesize if attachment.io_like?
|
|
308
|
+
|
|
309
|
+
nil
|
|
310
|
+
rescue SystemCallError
|
|
311
|
+
nil
|
|
312
|
+
end
|
|
313
|
+
private_class_method :attachment_bytesize
|
|
314
|
+
|
|
315
|
+
# This tool's name as a chrome shows it — {.display_name_for} of {#name}.
|
|
316
|
+
# Override where the mechanical form misreads it:
|
|
317
|
+
#
|
|
318
|
+
# class LspTool < Pikuri::Tool
|
|
319
|
+
# def display_name = 'LSP'
|
|
320
|
+
# end
|
|
321
|
+
#
|
|
322
|
+
# @return [String]
|
|
323
|
+
def display_name
|
|
324
|
+
Tool.display_name_for(@name)
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
# The one argument worth showing beside {#display_name} — by default the
|
|
328
|
+
# value of the first *required* parameter, which is the primary argument for
|
|
329
|
+
# most tools (+path+ for read/write/edit, +query+ for web_search, +command+
|
|
330
|
+
# for bash):
|
|
331
|
+
#
|
|
332
|
+
# read.describe_call('path' => 'lib/code/app.rb') # => "lib/code/app.rb"
|
|
333
|
+
# # → Read(lib/code/app.rb)
|
|
334
|
+
#
|
|
335
|
+
# Override when that parameter is the wrong one to show — an enum, an
|
|
336
|
+
# integer id, a whole Markdown plan:
|
|
337
|
+
#
|
|
338
|
+
# def describe_call(arguments)
|
|
339
|
+
# Tool.one_line("#{arguments['operation']} #{arguments['symbol']}")
|
|
340
|
+
# end
|
|
341
|
+
#
|
|
342
|
+
# Runs on the *unvalidated* arguments ruby_llm parsed from the model's JSON,
|
|
343
|
+
# before +execute+, so an override tolerates a missing or wrong-typed value.
|
|
344
|
+
# Neither capped nor sanitized here: only the renderer knows its width, and
|
|
345
|
+
# defanging is its job too.
|
|
346
|
+
#
|
|
347
|
+
# @param arguments [Hash] raw tool-call arguments; keys String or Symbol
|
|
348
|
+
# @return [String] one line; +""+ renders the call bare (just the display name)
|
|
349
|
+
def describe_call(arguments)
|
|
350
|
+
key = @parameters.required.first
|
|
351
|
+
return Tool.describe_arguments(arguments) if key.nil? || !arguments.is_a?(Hash)
|
|
352
|
+
|
|
353
|
+
value = arguments.key?(key) ? arguments[key] : arguments[key.to_sym]
|
|
354
|
+
return Tool.describe_arguments(arguments) if value.nil?
|
|
355
|
+
|
|
356
|
+
Tool.one_line(Tool.describe_value(value))
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
# The display line for an observation this tool returned as a bare String —
|
|
360
|
+
# Validate +args+ against {#parameters} and forward them as kwargs to
|
|
361
|
+
# {#execute}, always answering a {Result}. Validation failures come back as
|
|
362
|
+
# {Result.error} for the next observation; everything else bubbles up.
|
|
363
|
+
#
|
|
364
|
+
# A bare String from +execute+ is wrapped here, with
|
|
365
|
+
# {.describe_content}'s generic display line — that is the floor a
|
|
366
|
+
# third-party +Tool+ subclass lands on, not a shape pikuri's own tools use.
|
|
91
367
|
#
|
|
92
368
|
# @param args [Hash] raw arguments supplied by the LLM
|
|
93
|
-
# @
|
|
94
|
-
#
|
|
95
|
-
#
|
|
96
|
-
#
|
|
97
|
-
|
|
369
|
+
# @param context [ExecuteContext] this invocation's environment, forwarded
|
|
370
|
+
# as a +context:+ keyword only when {#wants_context}. Never part of
|
|
371
|
+
# +args+ — the LLM cannot supply it, since {Parameters#validate} refuses
|
|
372
|
+
# unknown keys. Positional against the house style on purpose: give this
|
|
373
|
+
# method *any* keyword and Ruby 3 re-reads the bare hash in
|
|
374
|
+
# +run('text' => 'hi')+ as keywords, so +args+ arrives empty at every
|
|
375
|
+
# existing call site.
|
|
376
|
+
# @return [Result] tool observation.
|
|
377
|
+
def run(args, context = ExecuteContext.default)
|
|
98
378
|
validated = @parameters.validate(args)
|
|
99
|
-
@
|
|
379
|
+
raw = if @wants_context
|
|
380
|
+
@execute.call(**validated, context: context)
|
|
381
|
+
else
|
|
382
|
+
@execute.call(**validated)
|
|
383
|
+
end
|
|
384
|
+
raw.is_a?(Result) ? raw : Result.new(content: raw, summary: Tool.describe_content(raw))
|
|
100
385
|
rescue Tool::Parameters::ValidationError => e
|
|
101
|
-
|
|
386
|
+
Result.error(e.message)
|
|
102
387
|
end
|
|
103
388
|
|
|
104
|
-
# Build a synthetic +RubyLLM::Tool+ subclass
|
|
105
|
-
#
|
|
106
|
-
#
|
|
107
|
-
#
|
|
108
|
-
#
|
|
389
|
+
# Build a synthetic +RubyLLM::Tool+ subclass wrapping this Tool — what
|
|
390
|
+
# +RubyLLM::Chat#with_tools+ accepts. ruby_llm instantiates it and routes
|
|
391
|
+
# tool calls through +#execute(**args)+, which delegates to {#run}.
|
|
392
|
+
#
|
|
393
|
+
# A wrapper is per *agent* even when this +Tool+ is shared between several,
|
|
394
|
+
# which is what lets it close over one agent's cancellation token.
|
|
395
|
+
#
|
|
396
|
+
# The wrapper instance answers +#pikuri_tool+ with this Tool, so a holder of
|
|
397
|
+
# ruby_llm's +Chat#tools+ table can get from a called name back to
|
|
398
|
+
# {#display_name} / {#describe_call}.
|
|
399
|
+
#
|
|
400
|
+
# == The one place a Result is unwrapped
|
|
401
|
+
#
|
|
402
|
+
# ruby_llm hands the *same* value to +after_tool_result+ and to the +:tool+
|
|
403
|
+
# message it builds, and sends attachments only for a value that *is* an
|
|
404
|
+
# Array of Strings and +RubyLLM::Attachment+s — a test a {Result} cannot
|
|
405
|
+
# pass. So an attachment Result crosses as +[content, *attachments]+, each
|
|
406
|
+
# {Pikuri::Attachment} converted by {Pikuri::Attachment#to_ruby_llm}, and
|
|
407
|
+
# its display line is derived ({.describe_content}: mime plus size, which
|
|
408
|
+
# is all the structure there is); text keeps the +Result+, which ruby_llm
|
|
409
|
+
# stores as {Result#to_s}, so {Result#summary} reaches the listeners
|
|
410
|
+
# verbatim. That one line below is the whole boundary — {#run} answers a
|
|
411
|
+
# +Result+ either way, and no tool sees this.
|
|
109
412
|
#
|
|
413
|
+
# On the wire, a Chat Completions +:tool+ message is text only, so ruby_llm
|
|
414
|
+
# sends the attachments as a +:user+ message ("Attachments from tool call
|
|
415
|
+
# <id>:") right after the batch's results — never +:system+, so nothing
|
|
416
|
+
# needs fixing here.
|
|
417
|
+
#
|
|
418
|
+
# == An attachment the model can't take
|
|
419
|
+
#
|
|
420
|
+
# Before that, +refusal+ may withhold an attachment — an image a text-only
|
|
421
|
+
# model would answer with HTTP 500, on this request and every later one
|
|
422
|
+
# that replays it. A withheld one becomes a line of +content+ instead, so
|
|
423
|
+
# the model learns why it sees nothing:
|
|
424
|
+
#
|
|
425
|
+
# Read image: shot.png (27731 bytes, image/png)
|
|
426
|
+
#
|
|
427
|
+
# [shot.png not shown: model Qwen3.8-Dense-text takes no vision input]
|
|
428
|
+
#
|
|
429
|
+
# The tool never knows: the model's capabilities are stated on the
|
|
430
|
+
# agent's transport ({Agent::ChatTransport#modalities}), and a tool
|
|
431
|
+
# returning an image need not ask.
|
|
432
|
+
#
|
|
433
|
+
# @param context [ExecuteContext] passed to {#run} on every call; see the
|
|
434
|
+
# +== Cancellation+ section.
|
|
435
|
+
# @param refusal [#call] given each {Pikuri::Attachment}, answers why it
|
|
436
|
+
# must be withheld, or +nil+ to send it. Called per tool call, so it may
|
|
437
|
+
# follow a model switch.
|
|
110
438
|
# @return [Class] anonymous +RubyLLM::Tool+ subclass
|
|
111
|
-
def to_ruby_llm_tool
|
|
439
|
+
def to_ruby_llm_tool(context: ExecuteContext.default, refusal: ->(_) {})
|
|
112
440
|
pikuri_tool = self
|
|
113
|
-
schema = @parameters.
|
|
441
|
+
schema = @parameters.to_openai
|
|
114
442
|
tool_name = @name
|
|
115
443
|
tool_desc = @description
|
|
116
444
|
|
|
117
445
|
Class.new(RubyLLM::Tool) do
|
|
118
446
|
description(tool_desc)
|
|
119
|
-
|
|
447
|
+
parameters(schema)
|
|
120
448
|
|
|
121
449
|
define_singleton_method(:name) { tool_name }
|
|
122
|
-
define_method(:execute)
|
|
450
|
+
define_method(:execute) do |**args|
|
|
451
|
+
result = Tool.withhold_refused(pikuri_tool.run(args, context), refusal)
|
|
452
|
+
result.attachment? ? [result.content, *result.attachments.map(&:to_ruby_llm)] : result
|
|
453
|
+
end
|
|
454
|
+
define_method(:pikuri_tool) { pikuri_tool }
|
|
123
455
|
end
|
|
124
456
|
end
|
|
457
|
+
|
|
458
|
+
# +result+ without the attachments +refusal+ withholds, each replaced by a
|
|
459
|
+
# note in its content; see {#to_ruby_llm_tool}.
|
|
460
|
+
#
|
|
461
|
+
# @param result [Result]
|
|
462
|
+
# @param refusal [#call] see {#to_ruby_llm_tool}
|
|
463
|
+
# @return [Result] +result+ itself when nothing is withheld
|
|
464
|
+
def self.withhold_refused(result, refusal)
|
|
465
|
+
notes = result.attachments.filter_map do |a|
|
|
466
|
+
reason = refusal.call(a)
|
|
467
|
+
[a, a.withheld_note(reason)] if reason
|
|
468
|
+
end
|
|
469
|
+
return result if notes.empty?
|
|
470
|
+
|
|
471
|
+
result.with(content: [result.content, *notes.map(&:last)].join("\n\n"),
|
|
472
|
+
attachments: result.attachments - notes.map(&:first))
|
|
473
|
+
end
|
|
125
474
|
end
|
|
126
475
|
end
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pikuri
|
|
4
|
+
module Trifecta
|
|
5
|
+
# What an extension adds to the tree, returned from
|
|
6
|
+
# {Pikuri::Agent::Extension#trifecta_contribution}. Two independent things,
|
|
7
|
+
# either of which may be empty:
|
|
8
|
+
#
|
|
9
|
+
# # a sub-agent extension: one child per persona, nothing of its own
|
|
10
|
+
# Contribution.new(legs: Pikuri::Tool::TrifectaLegs::NONE, children: nodes)
|
|
11
|
+
#
|
|
12
|
+
# # an MCP extension: legs no tool can declare, no children
|
|
13
|
+
# Contribution.new(label: '(mcp)', legs: assumed_with_private, children: [])
|
|
14
|
+
#
|
|
15
|
+
# Needed because two things in the tree are invisible to per-tool tagging:
|
|
16
|
+
# a sub-agent is a whole node the tools cannot describe, and a foreign tool
|
|
17
|
+
# surface (MCP) arrives as raw +RubyLLM::Tool+ subclasses with no leg
|
|
18
|
+
# surface at all.
|
|
19
|
+
#
|
|
20
|
+
# Immutable.
|
|
21
|
+
#
|
|
22
|
+
# @!attribute [r] label
|
|
23
|
+
# @return [String] name of the row these +legs+ appear under in the
|
|
24
|
+
# report, parenthesized to mark it as not-a-tool. It is what
|
|
25
|
+
# {Pikuri::Trifecta::Report#attribution} points the reader at, so it
|
|
26
|
+
# has to name the surface they can actually go and change — two
|
|
27
|
+
# extensions declaring under one label would blame each other's
|
|
28
|
+
# wiring.
|
|
29
|
+
# @!attribute [r] legs
|
|
30
|
+
# @return [Pikuri::Tool::TrifectaLegs] legs this extension adds to the
|
|
31
|
+
# node it is wired into, over and above that node's own tools
|
|
32
|
+
# @!attribute [r] children
|
|
33
|
+
# @return [Array<Node>] child nodes this extension introduces
|
|
34
|
+
class Contribution < Data.define(:label, :legs, :children)
|
|
35
|
+
# @param label [String] row name for +legs+; ignored when they are +NONE+
|
|
36
|
+
# @param legs [Pikuri::Tool::TrifectaLegs]
|
|
37
|
+
# @param children [Array<Node>]
|
|
38
|
+
def initialize(label: '(extension)', legs: Pikuri::Tool::TrifectaLegs::NONE, children: [])
|
|
39
|
+
super
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pikuri
|
|
4
|
+
module Trifecta
|
|
5
|
+
# One agent in the tree the detector walks: the main agent at the root, a
|
|
6
|
+
# persona per sub-agent below it. Assembled from a wired +Agent+ (its tools
|
|
7
|
+
# plus every extension's
|
|
8
|
+
# {Pikuri::Agent::Extension#trifecta_contribution}), and hand-built in
|
|
9
|
+
# specs — which is the point of carrying plain data rather than live
|
|
10
|
+
# objects:
|
|
11
|
+
#
|
|
12
|
+
# Node.new(label: 'demo',
|
|
13
|
+
# tool_legs: { 'read' => read_legs },
|
|
14
|
+
# children: [Node.new(label: 'RESEARCHER',
|
|
15
|
+
# tool_legs: { 'fetch' => fetch_legs },
|
|
16
|
+
# channel_egress: :human_reviewed)])
|
|
17
|
+
#
|
|
18
|
+
# Immutable.
|
|
19
|
+
#
|
|
20
|
+
# @!attribute [r] label
|
|
21
|
+
# @return [String] name shown in the report — the binary/agent name at the
|
|
22
|
+
# root, the persona name for a sub-agent
|
|
23
|
+
# @!attribute [r] tool_legs
|
|
24
|
+
# @return [Hash{String=>Pikuri::Tool::TrifectaLegs}] this agent's own
|
|
25
|
+
# tools, in wiring order. The per-tool breakdown is kept rather than
|
|
26
|
+
# pre-unioned so the rendered tree can show *which* tool contributes a
|
|
27
|
+
# leg instead of a bare total.
|
|
28
|
+
# @!attribute [r] children
|
|
29
|
+
# @return [Array<Node>] sub-agents this agent can dispatch to
|
|
30
|
+
# @!attribute [r] channel_egress
|
|
31
|
+
# @return [Symbol, nil] how much egress the delegation channel *from the
|
|
32
|
+
# parent* permits, on the {Pikuri::Tool::TrifectaLegs} review axis —
|
|
33
|
+
# +:human_reviewed+ when a human gates the hand-off, +:unreviewed+
|
|
34
|
+
# otherwise. A property of the edge, stored on the child
|
|
35
|
+
# because every child has exactly one parent edge; +nil+ at the root,
|
|
36
|
+
# which has none.
|
|
37
|
+
class Node < Data.define(:label, :tool_legs, :children, :channel_egress)
|
|
38
|
+
# @param label [String]
|
|
39
|
+
# @param tool_legs [Hash{String=>Pikuri::Tool::TrifectaLegs}]
|
|
40
|
+
# @param children [Array<Node>]
|
|
41
|
+
# @param channel_egress [Symbol, nil]
|
|
42
|
+
def initialize(label:, tool_legs: {}, children: [], channel_egress: nil)
|
|
43
|
+
super
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|