pikuri-core 0.0.7 → 0.1.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 +1 -1
  3. data/lib/pikuri/agent/chat_transport.rb +73 -93
  4. data/lib/pikuri/agent/configurator.rb +46 -106
  5. data/lib/pikuri/agent/context_window_detector.rb +44 -85
  6. data/lib/pikuri/agent/control/cancellable.rb +87 -66
  7. data/lib/pikuri/agent/control/interloper.rb +127 -105
  8. data/lib/pikuri/agent/control/step_limit.rb +25 -41
  9. data/lib/pikuri/agent/control.rb +14 -34
  10. data/lib/pikuri/agent/event.rb +123 -188
  11. data/lib/pikuri/agent/extension.rb +118 -94
  12. data/lib/pikuri/agent/extension_context.rb +50 -77
  13. data/lib/pikuri/agent/history.rb +653 -0
  14. data/lib/pikuri/agent/listener/rate_limited.rb +40 -66
  15. data/lib/pikuri/agent/listener/terminal.rb +143 -117
  16. data/lib/pikuri/agent/listener/token_log.rb +101 -140
  17. data/lib/pikuri/agent/listener.rb +23 -43
  18. data/lib/pikuri/agent/listener_list.rb +26 -47
  19. data/lib/pikuri/agent/synthesizer.rb +45 -87
  20. data/lib/pikuri/agent.rb +816 -474
  21. data/lib/pikuri/bundler_env.rb +68 -0
  22. data/lib/pikuri/extractor/html.rb +63 -110
  23. data/lib/pikuri/extractor/passthrough.rb +20 -30
  24. data/lib/pikuri/extractor.rb +93 -154
  25. data/lib/pikuri/file_type.rb +63 -135
  26. data/lib/pikuri/finalizers.rb +32 -47
  27. data/lib/pikuri/paths.rb +104 -13
  28. data/lib/pikuri/ruby_llm_patches.rb +106 -0
  29. data/lib/pikuri/sanitizer.rb +45 -67
  30. data/lib/pikuri/subprocess.rb +75 -119
  31. data/lib/pikuri/testing.rb +296 -0
  32. data/lib/pikuri/tool/calculator.rb +56 -66
  33. data/lib/pikuri/tool/execute_context.rb +42 -0
  34. data/lib/pikuri/tool/fetch.rb +51 -77
  35. data/lib/pikuri/tool/parameters.rb +21 -29
  36. data/lib/pikuri/tool/scraper.rb +55 -97
  37. data/lib/pikuri/tool/search/brave.rb +52 -80
  38. data/lib/pikuri/tool/search/duckduckgo.rb +59 -91
  39. data/lib/pikuri/tool/search/engines.rb +230 -97
  40. data/lib/pikuri/tool/search/exa.rb +56 -90
  41. data/lib/pikuri/tool/search/rate_limiter.rb +61 -38
  42. data/lib/pikuri/tool/search/result.rb +10 -15
  43. data/lib/pikuri/tool/trifecta_legs.rb +217 -0
  44. data/lib/pikuri/tool/web_scrape.rb +38 -54
  45. data/lib/pikuri/tool/web_search.rb +100 -24
  46. data/lib/pikuri/tool.rb +140 -65
  47. data/lib/pikuri/trifecta/contribution.rb +43 -0
  48. data/lib/pikuri/trifecta/node.rb +47 -0
  49. data/lib/pikuri/trifecta/report.rb +230 -0
  50. data/lib/pikuri/trifecta.rb +127 -0
  51. data/lib/pikuri/url_cache.rb +33 -49
  52. data/lib/pikuri/version.rb +1 -1
  53. data/lib/pikuri-core.rb +72 -88
  54. data/prompts/agent-loop.txt +5 -0
  55. data/prompts/pikuri-chat.txt +3 -12
  56. metadata +14 -3
@@ -2,38 +2,28 @@
2
2
 
3
3
  module Pikuri
4
4
  class Tool
5
- # Evaluates a basic arithmetic expression with Python operator
6
- # syntax and semantics, via the hand-rolled recursive-descent
7
- # {Parser} below.
5
+ # Evaluates a basic arithmetic expression with Python operator syntax and
6
+ # semantics, via the hand-rolled recursive-descent {Parser} below.
8
7
  #
9
- # Why hand-rolled rather than a gem: the previous backend, dentaku,
10
- # pulled in concurrent-ruby (~16k lines of Ruby — the single
11
- # heaviest audit item in pikuri's whole dependency closure) plus
12
- # bigdecimal and tsort, all to evaluate four-function arithmetic.
13
- # The ~100 lines here implement Python's expression grammar
14
- # directly, which also retires the old preprocessing step that
15
- # rewrote Python's +**+ into dentaku's +^+ dialect — the model's
16
- # native syntax is now simply the grammar.
8
+ # Hand-rolled rather than a gem: the previous backend (dentaku) pulled in
9
+ # concurrent-ruby (~16k lines — pikuri's single heaviest audit item) plus
10
+ # bigdecimal and tsort just for four-function arithmetic. The ~100 lines
11
+ # here implement Python's grammar directly, which also retires the old
12
+ # +**+→+^+ preprocessing (the model's native syntax is now the grammar).
17
13
  #
18
- # Scope is intentionally narrow: operators (+, -, *, /, //, %, **),
19
- # unary minus, parentheses, and integer / decimal / e-notation
20
- # literals. No variables, functions, or booleans — those would mean
21
- # teaching the model a dialect, which we specifically want to avoid
22
- # for this tool.
14
+ # Scope is intentionally narrow: operators (+, -, *, /, //, %, **), unary
15
+ # minus, parentheses, and integer/decimal/e-notation literals. No variables,
16
+ # functions, or booleans — those would teach the model a dialect.
23
17
  module Calculator
24
- # Raised internally for anything {.calculate} should hand back to
25
- # the model as an +"Error: ..."+ observation rather than crash
26
- # the agent loop: parse failures, division by zero, complex or
27
- # non-finite results. The message always names the offending
28
- # token or operands.
18
+ # Raised internally for anything {.calculate} should return as an
19
+ # +"Error: ..."+ observation rather than crash the loop: parse failures,
20
+ # division by zero, complex or non-finite results. Names the offending
21
+ # token/operands.
29
22
  class Error < StandardError; end
30
23
 
31
- # Evaluate +expression+ and return the result formatted as a
32
- # String. Parse and arithmetic failures (division by zero,
33
- # overflow to infinity, complex results) are caught and returned
34
- # as +"Error: ..."+ strings so the model can read the failure as
35
- # the next observation and self-correct rather than crashing the
36
- # agent loop.
24
+ # Evaluate +expression+ and return the result as a String. Parse and
25
+ # arithmetic failures (division by zero, overflow to infinity, complex
26
+ # results) come back as +"Error: ..."+ so the model self-corrects.
37
27
  #
38
28
  # @param expression [String] Python-syntax arithmetic expression
39
29
  # @return [String] numeric result, or +"Error: ..."+ on failure
@@ -48,11 +38,9 @@ module Pikuri
48
38
  "Error: #{e.message}"
49
39
  end
50
40
 
51
- # Integers (never produced by division — +/+ is Python-3-style
52
- # true division) pass through exact. Floats are rounded to 3
53
- # places so the model sees a short readable number, and
54
- # whole-valued floats drop the trailing +.0+ (+4 / 2+ renders as
55
- # +"2"+, not +"2.0"+).
41
+ # Integers pass through exact (division never produces them — +/+ is
42
+ # Python-3 true division). Floats round to 3 places, and whole-valued
43
+ # floats drop the +.0+ (+4 / 2+ → +"2"+).
56
44
  def self.format_result(result)
57
45
  return result.to_s if result.is_a?(Integer)
58
46
 
@@ -61,8 +49,7 @@ module Pikuri
61
49
  end
62
50
  private_class_method :format_result
63
51
 
64
- # Recursive-descent parser-evaluator for Python's arithmetic
65
- # expression grammar:
52
+ # Recursive-descent parser-evaluator for Python's arithmetic grammar:
66
53
  #
67
54
  # additive := multiplicative (('+' | '-') multiplicative)*
68
55
  # multiplicative := unary (('*' | '/' | '//' | '%') unary)*
@@ -70,22 +57,19 @@ module Pikuri
70
57
  # power := atom ('**' unary)?
71
58
  # atom := NUMBER | '(' additive ')'
72
59
  #
73
- # The +power+ → +unary+ recursion on the right operand is what
74
- # makes +**+ right-associative (+2**3**2+ is 512) and lets a sign
75
- # follow it (+2**-3+); +unary+ sitting *above* +power+ on the
76
- # left is what makes +-2**2+ evaluate to -4 — both exactly as
77
- # Python parses them.
60
+ # The +power+→+unary+ recursion on the right operand makes +**+
61
+ # right-associative (+2**3**2+ is 512) and lets a sign follow it
62
+ # (+2**-3+); +unary+ *above* +power+ on the left makes +-2**2+ evaluate to
63
+ # -4 — both as Python parses them.
78
64
  #
79
- # Semantics follow Python 3 where Ruby differs: +/+ is always
80
- # true (float) division, +//+ floors, +2**-1+ is the Float 0.5
81
- # (Ruby would return a Rational), and a negative base under a
82
- # fractional exponent is rejected (Ruby would return a Complex).
65
+ # Semantics follow Python 3 where Ruby differs: +/+ is always true (float)
66
+ # division, +//+ floors, +2**-1+ is Float 0.5 (not a Rational), and a
67
+ # negative base under a fractional exponent is rejected (not a Complex).
83
68
  class Parser
84
- # One number or operator. +**+ / +//+ listed before their
85
- # single-character prefixes so the two-character operators win;
86
- # number literals cover +42+, +4.2+, +5.+, +.5+, and e-notation
87
- # on any of them. +\G+ anchors each match at the scan position
88
- # so nothing between tokens goes unnoticed.
69
+ # One number or operator. +**+/+//+ listed before their single-char
70
+ # prefixes so the two-char operators win; number literals cover +42+,
71
+ # +4.2+, +5.+, +.5+, and e-notation. +\G+ anchors each match at the scan
72
+ # position so nothing between tokens is missed.
89
73
  TOKEN_RE = %r{\G\s*(\*\*|//|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[-+*/%()])}
90
74
 
91
75
  # @param expression [String] raw expression as the model wrote it
@@ -190,11 +174,9 @@ module Pikuri
190
174
  token
191
175
  end
192
176
 
193
- # +/+ is Python-3 true division (always Float); +//+ floors
194
- # (kept exact in Ruby's arbitrary-precision Integer division
195
- # when both operands are Integers — Ruby's +Integer#/+ already
196
- # floors like Python's +//+); +%+ delegates to Ruby's +%+,
197
- # whose sign-of-divisor semantics match Python's exactly.
177
+ # +/+ is Python-3 true division (always Float); +//+ floors (Ruby's
178
+ # +Integer#/+ already floors like Python's +//+ for two Integers); +%+
179
+ # delegates to Ruby's +%+, whose sign-of-divisor matches Python's.
198
180
  def apply_multiplicative(op, lhs, rhs)
199
181
  return lhs * rhs if op == '*'
200
182
  raise Error, 'division by zero' if rhs.zero?
@@ -206,10 +188,9 @@ module Pikuri
206
188
  end
207
189
  end
208
190
 
209
- # Two Python-compatibility shims over Ruby's +**+: an Integer
210
- # raised to a negative Integer yields a Float (Ruby would
211
- # return a Rational), and a Complex result — negative base
212
- # under a fractional exponent — is rejected loudly.
191
+ # Two Python-compat shims over Ruby's +**+: an Integer to a negative
192
+ # Integer yields a Float (Ruby → Rational), and a Complex result
193
+ # (negative base, fractional exponent) is rejected loudly.
213
194
  def apply_power(base, exponent)
214
195
  if base.is_a?(Integer) && exponent.is_a?(Integer) && exponent.negative?
215
196
  raise Error, 'division by zero' if base.zero?
@@ -226,10 +207,17 @@ module Pikuri
226
207
  end
227
208
  end
228
209
 
229
- # Arithmetic-evaluation tool backed by {Tool::Calculator.calculate}.
230
- # Accepts Python expression syntax (+, -, *, /, //, %, ** for
231
- # exponentiation, unary minus, parentheses, decimals) so the model
232
- # can emit the syntax it already knows.
210
+ # Arithmetic-evaluation tool backed by {Tool::Calculator.calculate}. Accepts
211
+ # Python expression syntax (+, -, *, /, //, %, **, unary minus, parentheses,
212
+ # decimals) so the model emits syntax it already knows.
213
+ #
214
+ # Stays wired even in shells that have +bash+: it is the only *unconfirmed*
215
+ # float arithmetic there, since a shell's own +$((…))+ is integer-only and
216
+ # every interpreter that isn't must stay off the passive allowlist. See
217
+ # +DECISIONS.md+ +D_keep_calculator+.
218
+ #
219
+ # Sharing: +P_stateless+ — arithmetic over the argument, no I/O, no state.
220
+ # Hand this one constant to every agent in the VM.
233
221
  #
234
222
  # @return [Tool]
235
223
  CALCULATOR = new(
@@ -239,16 +227,18 @@ module Pikuri
239
227
 
240
228
  Usage:
241
229
  - Use this for any arithmetic beyond simple mental math — do not eyeball multi-digit work.
242
- - Python expression syntax: +, -, *, / (true division), // (floor division), % (modulo), ** (exponentiation), unary minus, parentheses, decimal numbers.
243
230
  - Decimal results are rounded to 3 places; integer results are exact.
244
- - Failures (parse error, division by zero) come back as "Error: ..." — read the message and re-call with a corrected expression.
245
231
  DESC
246
232
  parameters: Parameters.build { |p|
247
233
  p.required_string :expression,
248
- 'Arithmetic expression to evaluate, e.g. ' \
249
- '"155 / (58 * 1000.0 / 3600)" or "2**10".'
234
+ 'Arithmetic expression in Python syntax: + - * ' \
235
+ '/ (true division), // (floor division), % (modulo), ' \
236
+ '** (exponentiation), unary minus, parentheses, ' \
237
+ 'decimals. E.g. "155 / (58 * 1000.0 / 3600)" or "2**10".'
250
238
  },
251
- execute: ->(expression:) { Calculator.calculate(expression) }
239
+ execute: ->(expression:) { Calculator.calculate(expression) },
240
+ # No legs: pure arithmetic over the argument, no I/O of any kind.
241
+ trifecta_legs: Pikuri::Tool::TrifectaLegs::NONE
252
242
  )
253
243
  end
254
244
  end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pikuri
4
+ class Tool
5
+ # The per-call environment handed to an +execute+ Proc alongside its
6
+ # validated arguments — everything a tool might need to know about *this
7
+ # invocation* that the LLM did not supply.
8
+ #
9
+ # Tool.new(
10
+ # name: 'web_search', description: DESCRIPTION, parameters: params,
11
+ # wants_context: true,
12
+ # execute: ->(query:, context:) { cascade.search(query, cancellable: context.cancellable) }
13
+ # )
14
+ #
15
+ # A tool opts in with +wants_context: true+ and takes a +context:+ keyword;
16
+ # both halves are required, so getting one without the other is an
17
+ # +ArgumentError+ on the first call rather than a silent +nil+. Most tools
18
+ # want neither.
19
+ #
20
+ # == Why the arguments are *not* in here
21
+ #
22
+ # The obvious shape is +context.args[:query]+, with one object carrying
23
+ # everything. It loses to a plain fact about {Parameters#validate}: it
24
+ # returns only the keys the model actually sent and applies no defaults, so
25
+ # half the bundled tools declare theirs in the +execute+ signature
26
+ # (+max_results: 10+). Fold the arguments in here and every one of those
27
+ # defaults has to be re-expressed. Arguments therefore stay kwargs, and this
28
+ # object carries only what has no other home.
29
+ #
30
+ # Growing it is the point: a new field is added here and read by the tools
31
+ # that care, with no signature change anywhere else.
32
+ ExecuteContext = Data.define(:cancellable) do
33
+ # The context a {Tool#run} with no caller-supplied one uses: cancellation
34
+ # that never trips. Frozen like every +Data+, so it is safe to share.
35
+ #
36
+ # @return [ExecuteContext]
37
+ def self.default
38
+ @default ||= new(cancellable: Pikuri::Agent::Control::Cancellable::NEVER)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -2,33 +2,26 @@
2
2
 
3
3
  module Pikuri
4
4
  class Tool
5
- # Truncation policy and Tool spec for the +fetch+ tool. The HTTP work
6
- # lives in {Tool::Scraper.fetch}; this module is a thin
7
- # wrapper that accepts only textual content-types, applies a character
8
- # cap so the LLM doesn't drown in long-form bodies, and exposes the
9
- # result to the agent loop in OpenAI tool-call shape.
10
- #
11
- # Sister of {Tool::WebScrape}, but with no extraction pass
12
- # (HTML→Markdown, or whatever plug-in extractors are registered):
13
- # bodies are returned verbatim. Useful for raw textual
14
- # data — JSON APIs, CSV files, +robots.txt+, sitemaps, source files —
15
- # where any rendering pass would corrupt the payload.
5
+ # Truncation policy and Tool spec for the +fetch+ tool. HTTP work lives in
6
+ # {Tool::Scraper.fetch}; this wrapper accepts only textual content-types,
7
+ # applies a character cap, and exposes the result in OpenAI tool-call shape.
8
+ # Sister of {Tool::WebScrape} but with no extraction pass — bodies are
9
+ # returned verbatim, for raw textual data (JSON APIs, CSV, +robots.txt+,
10
+ # sitemaps, source files) where a rendering pass would corrupt the payload.
16
11
  module Fetch
17
- # @return [Integer] default character cap on the body returned by
18
- # {.fetch}. Smaller than {Tool::WebScrape::DEFAULT_MAX_CHARS}
19
- # because fetch's content profile is bimodal — most JSON/XML/CSV
20
- # responses are tiny, and the long-tail (large data dumps) is
12
+ # @return [Integer] default character cap on the body from {.fetch}.
13
+ # Smaller than {Tool::WebScrape::DEFAULT_MAX_CHARS} because fetch's
14
+ # content is bimodal — most JSON/XML/CSV is tiny, and large dumps are
21
15
  # better re-requested deliberately than padded into every default.
22
16
  DEFAULT_MAX_CHARS = 5_000
23
17
 
24
- # @return [Integer] hard ceiling on the +max_chars+ argument to
25
- # {.fetch}. Matches {Tool::WebScrape::MAX_MAX_CHARS}.
18
+ # @return [Integer] hard ceiling on {.fetch}'s +max_chars+; matches
19
+ # {Tool::WebScrape::MAX_MAX_CHARS}.
26
20
  MAX_MAX_CHARS = 100_000
27
21
 
28
- # Application content-types that are textual in practice and so
29
- # safe to return verbatim to the LLM, despite their +application/+
30
- # prefix making them fail the +text/*+ check. Anything outside
31
- # +text/*+ and this allowlist is refused.
22
+ # Application content-types that are textual in practice, so safe to
23
+ # return verbatim despite failing the +text/*+ check. Anything outside
24
+ # +text/*+ and this list is refused.
32
25
  # @return [Array<String>]
33
26
  TEXTUAL_APPLICATION_TYPES = %w[
34
27
  application/json
@@ -39,50 +32,33 @@ module Pikuri
39
32
  application/atom+xml
40
33
  ].freeze
41
34
 
42
- # On-disk cache used by {.fetch} to memoize downloads. Defined as a
43
- # method so specs can swap it for an isolated cache or
44
- # {UrlCache::NULL} without touching the shared instance. Lives in
45
- # its own subdir under {UrlCache::ROOT_DIR} so a +fetch+ on a URL
46
- # and a +web_scrape+ on the same URL cannot collide on the same
47
- # cache file (one returns the raw body, the other returns extracted
48
- # Markdown).
35
+ # On-disk cache for {.fetch}, in its own subdir so a +fetch+ and a
36
+ # +web_scrape+ on the same URL don't collide (raw body vs extracted
37
+ # Markdown). A method so specs can swap {UrlCache::NULL}.
49
38
  #
50
39
  # @return [UrlCache, #fetch]
51
40
  CACHE = UrlCache.new(ttl: UrlCache::DEFAULT_TTL, dir: "#{UrlCache::ROOT_DIR}/fetch")
52
- # Accessor for {CACHE}; specs override this to swap in
53
- # {UrlCache::NULL} or an isolated cache.
41
+ # Accessor for {CACHE}; specs swap in {UrlCache::NULL} or an isolated cache.
54
42
  #
55
43
  # @return [UrlCache, #fetch]
56
44
  def self.cache
57
45
  CACHE
58
46
  end
59
47
 
60
- # Download +url+ via {Tool::Scraper.fetch} and return the
61
- # response body verbatim, provided the content-type is one we deem
62
- # textual (any +text/*+, plus the formats listed in
63
- # {TEXTUAL_APPLICATION_TYPES}). Anything else — PDFs, images, other
64
- # binaries — produces an +"Error: ..."+ string in the calculator-
65
- # style convention so the agent loop feeds the failure back to the
66
- # model as the next observation.
67
- #
68
- # The body is cached on disk via {.cache}, keyed by URL, so repeat
69
- # fetches within the cache TTL skip the network. +max_chars+ is not
70
- # part of the cache key — different values for the same URL share
71
- # one entry, and truncation runs after the cache lookup. The cache
72
- # is only populated on success: {Scraper::FetchError} (HTTP non-2xx,
73
- # network failure, redirect-loop exhaustion, refused content-type)
74
- # is caught outside the +cache.fetch+ block, so failure strings are
75
- # never persisted and a retry on the next call hits the network
76
- # again. Other exceptions (parser bugs in our own code) bubble up
77
- # unchanged.
48
+ # Download +url+ via {Tool::Scraper.fetch} and return the body verbatim,
49
+ # if the content-type is textual (any +text/*+ plus
50
+ # {TEXTUAL_APPLICATION_TYPES}); anything else (PDF, image, binary) yields
51
+ # an +"Error: ..."+ string. Cached on disk keyed by URL; +max_chars+ is
52
+ # *not* in the key (values share one entry, truncation runs after the
53
+ # lookup). Cached only on success — {Scraper::FetchError} is caught
54
+ # outside +cache.fetch+, so failures are never persisted; other
55
+ # exceptions bubble up.
78
56
  #
79
- # @param url [String] absolute HTTP(S) URL to download
80
- # @param max_chars [Integer] character cap on the returned body.
81
- # Clamped to +[1, {MAX_MAX_CHARS}]+; defaults to
82
- # {DEFAULT_MAX_CHARS}. When the body exceeds the cap, output is
83
- # cut and a marker noting the original length is appended.
84
- # @return [String] response body, possibly truncated, or
85
- # +"Error: ..."+ on a recoverable failure
57
+ # @param url [String] absolute HTTP(S) URL
58
+ # @param max_chars [Integer] body cap, clamped to +[1, {MAX_MAX_CHARS}]+;
59
+ # default {DEFAULT_MAX_CHARS}. Over the cap, output is cut with a marker.
60
+ # @return [String] body, possibly truncated, or +"Error: ..."+ on a
61
+ # recoverable failure
86
62
  def self.fetch(url, max_chars: DEFAULT_MAX_CHARS)
87
63
  max_chars = max_chars.clamp(1, MAX_MAX_CHARS)
88
64
  body = cache.fetch(url) { download(url) }
@@ -91,15 +67,13 @@ module Pikuri
91
67
  "Error: #{e.message}"
92
68
  end
93
69
 
94
- # GET +url+ and verify the response's content-type is textual.
95
- # Caller is responsible for caching and truncation; this method
96
- # always hits the network.
70
+ # GET +url+ and verify the content-type is textual. Always hits the
71
+ # network (caller caches/truncates).
97
72
  #
98
73
  # @param url [String]
99
74
  # @return [String] response body
100
- # @raise [Scraper::FetchError] on HTTP non-2xx, network failure,
101
- # redirect-loop exhaustion, missing +Location+ on a 3xx, or a
102
- # non-textual content-type
75
+ # @raise [Scraper::FetchError] on HTTP non-2xx, network failure, redirect
76
+ # exhaustion, missing +Location+, or a non-textual content-type
103
77
  def self.download(url)
104
78
  fetched = Scraper.fetch(url)
105
79
  return fetched.body if textual?(fetched.content_type)
@@ -109,23 +83,18 @@ module Pikuri
109
83
  'is not textual (use web_scrape for rendered pages)'
110
84
  end
111
85
 
112
- # @param content_type [String] normalized content-type (no +charset+
113
- # parameter, lowercased) as produced by {Scraper.fetch}
114
- # @return [Boolean] true when the content-type is +text/*+ or one
115
- # of {TEXTUAL_APPLICATION_TYPES}
86
+ # @param content_type [String] normalized content-type from {Scraper.fetch}
87
+ # @return [Boolean] true when +text/*+ or in {TEXTUAL_APPLICATION_TYPES}
116
88
  def self.textual?(content_type)
117
89
  content_type.start_with?('text/') ||
118
90
  TEXTUAL_APPLICATION_TYPES.include?(content_type)
119
91
  end
120
92
 
121
- # Cut +body+ to at most +max_chars+ characters, appending a marker
122
- # describing the original length when truncation actually happens.
123
- # Returns +body+ unchanged if it already fits. Same shape as
124
- # {Tool::WebScrape.truncate} so the LLM sees a consistent
125
- # truncation marker across both tools.
93
+ # Cut +body+ to at most +max_chars+, appending a marker with the original
94
+ # length when truncation happens. Same shape as {Tool::WebScrape.truncate}.
126
95
  #
127
96
  # @param body [String] full response body
128
- # @param max_chars [Integer] character cap; assumed already clamped
97
+ # @param max_chars [Integer] cap; assumed already clamped
129
98
  # @return [String]
130
99
  def self.truncate(body, max_chars)
131
100
  return body if body.length <= max_chars
@@ -136,11 +105,14 @@ module Pikuri
136
105
  end
137
106
  end
138
107
 
139
- # Verbatim URL download tool. Thin wrapper over {Tool::Fetch.fetch}
140
- # that exposes it to the agent loop in OpenAI tool-call shape. Use for
141
- # raw textual payloads (JSON APIs, CSV files, +robots.txt+, source
142
- # files); use {Tool::WEB_SCRAPE} for rendered web pages where
143
- # readability extraction makes the result usable.
108
+ # Verbatim URL download tool — a thin wrapper over {Tool::Fetch.fetch} in
109
+ # OpenAI tool-call shape. Use for raw textual payloads (JSON, CSV,
110
+ # +robots.txt+, source files); use {Tool::WEB_SCRAPE} for rendered pages.
111
+ #
112
+ # Sharing: +P_shared_benign+ — no per-agent state, but {Fetch::CACHE} is
113
+ # process-wide (and on disk, so cross-process too): agent B's +fetch+ can
114
+ # be answered from agent A's download within the TTL. See
115
+ # {Pikuri::UrlCache} for the race and why it's harmless.
144
116
  #
145
117
  # @return [Tool]
146
118
  FETCH = new(
@@ -166,7 +138,9 @@ module Pikuri
166
138
  },
167
139
  execute: ->(url:, max_chars: Fetch::DEFAULT_MAX_CHARS) {
168
140
  Fetch.fetch(url, max_chars: max_chars)
169
- }
141
+ },
142
+ # As {WEB_SCRAPE}: attacker-choosable host, attacker-authored response.
143
+ trifecta_legs: Pikuri::Tool::TrifectaLegs::ASSUMED
170
144
  )
171
145
  end
172
146
  end
@@ -40,6 +40,9 @@ module Pikuri
40
40
  @required = []
41
41
  end
42
42
 
43
+ # @return [Parameters]
44
+ EMPTY = new.freeze
45
+
43
46
  # Freeze the builder along with its internal collections, so post-build
44
47
  # mutation attempts raise +FrozenError+ instead of silently succeeding.
45
48
  #
@@ -68,22 +71,13 @@ module Pikuri
68
71
  add(name, 'string', description, required: false)
69
72
  end
70
73
 
71
- # Add a required +array+-of-+string+ property — JSON-Schema
72
- # +{type: 'array', items: {type: 'string'}}+. The LLM sends a
73
- # native JSON array in the tool-call arguments (the shape its
74
- # training data overwhelmingly uses for list-valued parameters),
75
- # so there is no in-band encoding for it to get wrong.
76
- # The value must arrive as an Array — no
77
- # JSON-encoded-array-in-a-string fallback. Element coercion
78
- # mirrors the scalar fields' one documented leniency, in
79
- # reverse: Integers and finite Floats are converted to their
80
- # +to_s+ form (a model emitting +["Fix issue 12", 42]+ meant a
81
- # string list — the conversion is unambiguous), while booleans,
82
- # +nil+, and nested structures are rejected — those signal a
83
- # genuinely wrong call shape, not a representational quirk.
84
- # An empty array is type-valid; rejecting it (if the tool needs
85
- # at least one element) is the tool's job, with a tool-specific
86
- # error message.
74
+ # Add a required +array+-of-+string+ property (+{type: 'array', items:
75
+ # {type: 'string'}}+). The value must arrive as a native JSON Array — no
76
+ # JSON-in-a-string fallback. Element coercion mirrors the scalars in
77
+ # reverse: Integers and finite Floats become their +to_s+ (a model
78
+ # emitting +["Fix issue 12", 42]+ meant a string list), while booleans,
79
+ # +nil+, and nested structures are rejected. An empty array is type-valid
80
+ # — rejecting it is the tool's job.
87
81
  #
88
82
  # @param name [Symbol] property name
89
83
  # @param description [String] human-readable description shown to the LLM
@@ -198,24 +192,22 @@ module Pikuri
198
192
  # Schema in OpenAI JSON-Schema shape.
199
193
  #
200
194
  # @return [Hash] +{type: 'object', properties: {...}, required: [...]}+
201
- def to_h
195
+ def to_openai
202
196
  { type: 'object', properties: @properties, required: @required }
203
197
  end
204
198
 
205
- # Validate a tool-call argument hash against the declared schema. Returns
206
- # a symbol-keyed hash safe to splat as kwargs into a tool's +execute+
207
- # Proc; raises {ValidationError} with an LLM-actionable message listing
208
- # every missing/unknown/mistyped field and reprinting the schema.
209
- #
210
- # Strict: unknown keys are rejected (with DidYouMean suggestions), wrong
211
- # types are rejected. All issues are collected and reported together so
212
- # the LLM can fix them in one round trip.
199
+ # Validate a tool-call argument hash against the schema. Returns a
200
+ # symbol-keyed hash safe to splat as kwargs into a tool's +execute+;
201
+ # raises {ValidationError} with an LLM-actionable message listing every
202
+ # missing/unknown/mistyped field and reprinting the schema. Strict:
203
+ # unknown keys rejected (with DidYouMean suggestions), wrong types
204
+ # rejected, all issues collected so the LLM fixes them in one round trip.
213
205
  #
214
- # @param args [Hash] arguments as decoded from the tool-call JSON; keys
215
- # may be Strings or Symbols
206
+ # @param args [Hash] arguments decoded from the tool-call JSON; keys may
207
+ # be Strings or Symbols
216
208
  # @return [Hash{Symbol=>Object}] validated, symbol-keyed arguments
217
- # @raise [ValidationError] if +args+ is not a Hash, contains unknown
218
- # keys, omits a required key, or has a value of the wrong type
209
+ # @raise [ValidationError] if +args+ isn't a Hash, has unknown keys, omits
210
+ # a required key, or has a wrong-typed value
219
211
  def validate(args)
220
212
  raise ValidationError, "Arguments must be an object, got #{args.class}." unless args.is_a?(Hash)
221
213