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
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pikuri-core
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Martin Vysny
@@ -23,20 +23,6 @@ dependencies:
23
23
  - - "~>"
24
24
  - !ruby/object:Gem::Version
25
25
  version: '2.9'
26
- - !ruby/object:Gem::Dependency
27
- name: nokogiri
28
- requirement: !ruby/object:Gem::Requirement
29
- requirements:
30
- - - "~>"
31
- - !ruby/object:Gem::Version
32
- version: '1.19'
33
- type: :runtime
34
- prerelease: false
35
- version_requirements: !ruby/object:Gem::Requirement
36
- requirements:
37
- - - "~>"
38
- - !ruby/object:Gem::Version
39
- version: '1.19'
40
26
  - !ruby/object:Gem::Dependency
41
27
  name: rainbow
42
28
  requirement: !ruby/object:Gem::Requirement
@@ -51,48 +37,20 @@ dependencies:
51
37
  - - "~>"
52
38
  - !ruby/object:Gem::Version
53
39
  version: '3.1'
54
- - !ruby/object:Gem::Dependency
55
- name: reverse_markdown
56
- requirement: !ruby/object:Gem::Requirement
57
- requirements:
58
- - - "~>"
59
- - !ruby/object:Gem::Version
60
- version: '3.0'
61
- type: :runtime
62
- prerelease: false
63
- version_requirements: !ruby/object:Gem::Requirement
64
- requirements:
65
- - - "~>"
66
- - !ruby/object:Gem::Version
67
- version: '3.0'
68
- - !ruby/object:Gem::Dependency
69
- name: ruby-readability
70
- requirement: !ruby/object:Gem::Requirement
71
- requirements:
72
- - - "~>"
73
- - !ruby/object:Gem::Version
74
- version: '0.7'
75
- type: :runtime
76
- prerelease: false
77
- version_requirements: !ruby/object:Gem::Requirement
78
- requirements:
79
- - - "~>"
80
- - !ruby/object:Gem::Version
81
- version: '0.7'
82
40
  - !ruby/object:Gem::Dependency
83
41
  name: ruby_llm
84
42
  requirement: !ruby/object:Gem::Requirement
85
43
  requirements:
86
44
  - - "~>"
87
45
  - !ruby/object:Gem::Version
88
- version: '1.16'
46
+ version: '2.2'
89
47
  type: :runtime
90
48
  prerelease: false
91
49
  version_requirements: !ruby/object:Gem::Requirement
92
50
  requirements:
93
51
  - - "~>"
94
52
  - !ruby/object:Gem::Version
95
- version: '1.16'
53
+ version: '2.2'
96
54
  - !ruby/object:Gem::Dependency
97
55
  name: zeitwerk
98
56
  requirement: !ruby/object:Gem::Requirement
@@ -111,12 +69,11 @@ description: |
111
69
  pikuri-core is the lean, audit-friendly foundation of the pikuri family:
112
70
  Pikuri::Agent (a thin wrapper around ruby_llm's chat loop) with its
113
71
  Configurator + Extension protocol, the strict Pikuri::Tool framework, a
114
- listener surface for rendering / budgets / sub-agents, and four bundled
115
- stateless tools (calculator, web search, web scrape, fetch). Extensions
116
- (skills, MCP, workspace, coding stack, named-agent personas) live in
72
+ listener surface for rendering / budgets / sub-agents, and a calculator
73
+ as the one bundled example tool. Extensions (web tools, skills, MCP,
74
+ workspace, coding stack, named-agent personas) live in
117
75
  sibling gems so a privacy-conscious user can install just this core and
118
- audit a minimal dependency tree. For the convenience bundle that pulls
119
- in everything, see the +pikuri+ metagem.
76
+ audit a minimal dependency tree.
120
77
  email:
121
78
  - martin@vysny.me
122
79
  executables: []
@@ -128,63 +85,49 @@ files:
128
85
  - lib/pikuri/agent.rb
129
86
  - lib/pikuri/agent/chat_transport.rb
130
87
  - lib/pikuri/agent/configurator.rb
131
- - lib/pikuri/agent/context_window_detector.rb
132
88
  - lib/pikuri/agent/control.rb
133
89
  - lib/pikuri/agent/control/cancellable.rb
90
+ - lib/pikuri/agent/control/handoff.rb
134
91
  - lib/pikuri/agent/control/interloper.rb
135
- - lib/pikuri/agent/control/step_limit.rb
136
92
  - lib/pikuri/agent/event.rb
137
93
  - lib/pikuri/agent/extension.rb
138
- - lib/pikuri/agent/extension_context.rb
139
94
  - lib/pikuri/agent/history.rb
140
95
  - lib/pikuri/agent/listener.rb
141
96
  - lib/pikuri/agent/listener/in_memory_event_list.rb
142
- - lib/pikuri/agent/listener/rate_limited.rb
143
97
  - lib/pikuri/agent/listener/terminal.rb
144
98
  - lib/pikuri/agent/listener/token_log.rb
145
99
  - lib/pikuri/agent/listener_list.rb
146
- - lib/pikuri/agent/synthesizer.rb
100
+ - lib/pikuri/agent/request_instrumenter.rb
101
+ - lib/pikuri/attachment.rb
147
102
  - lib/pikuri/bundler_env.rb
148
103
  - lib/pikuri/extractor.rb
149
- - lib/pikuri/extractor/html.rb
150
104
  - lib/pikuri/extractor/passthrough.rb
151
105
  - lib/pikuri/file_type.rb
152
106
  - lib/pikuri/finalizers.rb
153
107
  - lib/pikuri/paths.rb
154
- - lib/pikuri/ruby_llm_patches.rb
155
108
  - lib/pikuri/sanitizer.rb
156
109
  - lib/pikuri/subprocess.rb
157
110
  - lib/pikuri/testing.rb
158
111
  - lib/pikuri/tool.rb
159
112
  - lib/pikuri/tool/calculator.rb
160
113
  - lib/pikuri/tool/execute_context.rb
161
- - lib/pikuri/tool/fetch.rb
162
114
  - lib/pikuri/tool/parameters.rb
163
- - lib/pikuri/tool/scraper.rb
164
- - lib/pikuri/tool/search/brave.rb
165
- - lib/pikuri/tool/search/duckduckgo.rb
166
- - lib/pikuri/tool/search/engines.rb
167
- - lib/pikuri/tool/search/exa.rb
168
- - lib/pikuri/tool/search/rate_limiter.rb
169
- - lib/pikuri/tool/search/result.rb
115
+ - lib/pikuri/tool/result.rb
170
116
  - lib/pikuri/tool/trifecta_legs.rb
171
- - lib/pikuri/tool/web_scrape.rb
172
- - lib/pikuri/tool/web_search.rb
173
117
  - lib/pikuri/trifecta.rb
174
118
  - lib/pikuri/trifecta/contribution.rb
175
119
  - lib/pikuri/trifecta/node.rb
176
120
  - lib/pikuri/trifecta/report.rb
177
- - lib/pikuri/url_cache.rb
178
121
  - lib/pikuri/version.rb
179
122
  - prompts/agent-loop.txt
180
123
  - prompts/pikuri-chat.txt
181
- homepage: https://codeberg.org/mvysny/pikuri
124
+ homepage: https://github.com/mvysny/pikuri
182
125
  licenses:
183
126
  - MIT
184
127
  metadata:
185
- source_code_uri: https://codeberg.org/mvysny/pikuri/src/branch/master
186
- changelog_uri: https://codeberg.org/mvysny/pikuri/src/branch/master/CHANGELOG.md
187
- bug_tracker_uri: https://codeberg.org/mvysny/pikuri/issues
128
+ source_code_uri: https://github.com/mvysny/pikuri/tree/master
129
+ changelog_uri: https://github.com/mvysny/pikuri/blob/master/CHANGELOG.md
130
+ bug_tracker_uri: https://github.com/mvysny/pikuri/issues
188
131
  rubygems_mfa_required: 'true'
189
132
  rdoc_options: []
190
133
  require_paths:
@@ -203,5 +146,5 @@ requirements: []
203
146
  rubygems_version: 3.6.7
204
147
  specification_version: 4
205
148
  summary: The minimal core of the pikuri AI-assistant toolkit (Agent, Tool framework,
206
- web tools, bin/pikuri-chat).
149
+ bin/pikuri-chat).
207
150
  test_files: []
@@ -1,181 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'ruby_llm'
4
- require 'faraday'
5
- require 'json'
6
- require 'cgi'
7
-
8
- module Pikuri
9
- class Agent
10
- # Resolves the model's context-window cap by asking the server that serves
11
- # it. The only authoritative runtime source is llama.cpp's non-standard
12
- # +/props+ endpoint, reporting the server's *launched* +n_ctx+ (the real
13
- # window — possibly smaller than the model's max, e.g. +llama-server -c
14
- # 8192+ on a 128k model). Returns +nil+ — an honest "we don't know" — for
15
- # anything else. {Agent#detect_and_emit_context_cap!} calls it only when
16
- # the transport carries no explicit {ChatTransport#context_window}.
17
- #
18
- # This probe and an explicit {ChatTransport#context_window} are the *only*
19
- # sources: +RubyLLM::Model::Info#context_window+ is deliberately never
20
- # consulted (why: +DECISIONS.md+ +D_context_window_sources+).
21
- #
22
- # == The openai-provider gate + auto-derived URL
23
- #
24
- # The probe only makes sense against an OpenAI-compatible local server
25
- # (llama.cpp) via ruby_llm's +:openai+ provider, so {.detect} runs only for
26
- # +transport.provider == :openai+ and derives the URL from the *same*
27
- # +RubyLLM.config.openai_api_base+ the chat uses (+/props+ is at the host
28
- # root, so the +/v1+ suffix is stripped) — so it can't target a different
29
- # server than the chat. A bare +:openai+ at real +api.openai.com+ gets one
30
- # fast +/props+ 404 that degrades to +nil+.
31
- #
32
- # == llama.cpp router mode
33
- #
34
- # A llama.cpp *router* (the multi-instance front) answers a bare +/props+
35
- # with +{"role":"router", ..., "n_ctx":0}+ — no single loaded model. The
36
- # real per-model cap is one hop away: +GET /props?model=<id>+ routes to that
37
- # model's instance. So when the bare probe reports +role: router+ and a
38
- # +model_id+ is known, this re-probes with the id. A plain single-model
39
- # server (bare +/props+ already positive) never hits this branch.
40
- #
41
- # == Failure handling
42
- #
43
- # Best-effort: HTTP error, timeout, non-JSON body, or a missing/invalid
44
- # +n_ctx+ all return +nil+ with one +warn+ line. The CLAUDE.md
45
- # "secondary to the loop" carve-out — a wedged or non-llama.cpp server must
46
- # not abort agent construction over a cosmetic readout.
47
- class ContextWindowDetector
48
- # Subsystem logger; set its level with
49
- # +PIKURI_LOG_CONTEXTWINDOWDETECTOR+ or the global +PIKURI_LOG+.
50
- #
51
- # @return [Logger]
52
- LOGGER = Pikuri.logger_for('ContextWindowDetector')
53
-
54
- # Connect timeout (s) for the +/props+ probe. Short: a server that isn't
55
- # listening should fail fast rather than stall {Agent} construction.
56
- #
57
- # @return [Integer]
58
- OPEN_TIMEOUT = 2
59
- # Read timeout (s) for the +/props+ probe — generous, unlike
60
- # {OPEN_TIMEOUT}: a router answers +/props?model=<id>+ only after spinning
61
- # up that model's instance, and a cold load can take 10+s (which the next
62
- # chat turn must wait for anyway). A shorter timeout would lose the cap
63
- # exactly when switching to a cold model.
64
- #
65
- # @return [Integer]
66
- READ_TIMEOUT = 30
67
-
68
- # Resolve the context-window cap for +transport+ by probing its server.
69
- #
70
- # @param transport [Agent::ChatTransport] +provider+ gates the probe,
71
- # +model+ drives the router +?model=+ hop
72
- # @param openai_base [String, nil] base URL the probe URL derives from;
73
- # defaults to the live +RubyLLM.config.openai_api_base+ (passed
74
- # explicitly only by tests, to avoid mutating global config)
75
- # @return [Integer, nil] the launched +n_ctx+, or +nil+ for a
76
- # non-+:openai+ transport, unconfigured base, or any probe failure
77
- def self.detect(transport, openai_base: RubyLLM.config.openai_api_base)
78
- return nil unless transport.provider == :openai
79
-
80
- url = props_url(openai_base)
81
- return nil if url.nil?
82
-
83
- new(probe_url: url, model_id: transport.model).probe
84
- end
85
-
86
- # Derive the +/props+ URL from the OpenAI-compatible base (+/props+ is at
87
- # the host root, so a trailing +/v1+ is stripped).
88
- #
89
- # @param openai_base [String, nil]
90
- # @return [String, nil] the +/props+ URL, or +nil+ when the base is blank
91
- def self.props_url(openai_base)
92
- base = openai_base.to_s.strip.chomp('/')
93
- return nil if base.empty?
94
-
95
- "#{base.delete_suffix('/v1')}/props"
96
- end
97
-
98
- # @param probe_url [String] full URL to llama.cpp +/props+
99
- # @param model_id [String, nil] the chat model id, used to follow a
100
- # llama.cpp router via +/props?model=<id>+ when the bare probe
101
- # reports +role: router+. +nil+ or empty disables that second hop.
102
- def initialize(probe_url:, model_id:)
103
- @probe_url = probe_url
104
- @model_id = model_id
105
- end
106
-
107
- # @return [Integer, nil] resolved cap, or +nil+ if the probe
108
- # produced none
109
- def probe
110
- probe_llama_cpp
111
- end
112
-
113
- private
114
-
115
- def probe_llama_cpp
116
- data = fetch_props(@probe_url)
117
- return nil if data.nil?
118
-
119
- n_ctx = positive_n_ctx(data)
120
- return n_ctx if n_ctx
121
-
122
- # llama.cpp router: the bare /props carries no model, so its
123
- # n_ctx is 0. Follow the router to the model's own instance.
124
- return probe_router_model if data['role'] == 'router' && model_id_present?
125
-
126
- warn_and_nil(
127
- "no positive integer at default_generation_settings.n_ctx in #{@probe_url} response"
128
- )
129
- end
130
-
131
- def probe_router_model
132
- url = "#{@probe_url}?model=#{CGI.escape(@model_id)}"
133
- data = fetch_props(url)
134
- return nil if data.nil?
135
-
136
- n_ctx = positive_n_ctx(data)
137
- return n_ctx if n_ctx
138
-
139
- warn_and_nil(
140
- "no positive integer at default_generation_settings.n_ctx in router probe #{url}"
141
- )
142
- end
143
-
144
- # GETs +url+ and parses its JSON body.
145
- #
146
- # @param url [String] a llama.cpp +/props+ URL
147
- # @return [Hash, nil] the parsed body, or +nil+ (after one +warn+
148
- # line) on non-200, timeout, transport error, or non-JSON body
149
- def fetch_props(url)
150
- response = Faraday.new(
151
- request: { open_timeout: OPEN_TIMEOUT, timeout: READ_TIMEOUT }
152
- ).get(url) do |req|
153
- req.headers['Accept'] = 'application/json'
154
- end
155
-
156
- return warn_and_nil("HTTP #{response.status} from #{url}") unless response.status == 200
157
-
158
- JSON.parse(response.body)
159
- rescue Faraday::Error, JSON::ParserError => e
160
- warn_and_nil("#{e.class.name.split('::').last}: #{e.message}")
161
- end
162
-
163
- # @param data [Hash] a parsed +/props+ body
164
- # @return [Integer, nil] the launched +n_ctx+ when present and
165
- # positive, else +nil+
166
- def positive_n_ctx(data)
167
- n_ctx = data.dig('default_generation_settings', 'n_ctx')
168
- n_ctx if n_ctx.is_a?(Integer) && n_ctx.positive?
169
- end
170
-
171
- def model_id_present?
172
- !@model_id.nil? && !@model_id.empty?
173
- end
174
-
175
- def warn_and_nil(reason)
176
- LOGGER.warn("llama.cpp /props probe failed: #{reason}")
177
- nil
178
- end
179
- end
180
- end
181
- end
@@ -1,95 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Pikuri
4
- class Agent
5
- module Control
6
- # Caps the number of tool calls per {Agent#run_loop}. ruby_llm has no
7
- # step budget; the +Agent+ pokes {#tick!} on every +before_tool_call+ and
8
- # {#reset!} at turn start. Once the count exceeds the cap, {#tick!} raises
9
- # {Exceeded} and the +Agent+ applies {#on_exhausted}: re-raise to the host
10
- # (default), or run the synthesizer to salvage a partial answer.
11
- #
12
- # == Why the policy lives here, not on +Agent+
13
- #
14
- # Synthesis can only fire off a tripped step limit, so an
15
- # +Agent.new(synthesize: ...)+ kwarg would be meaningless when
16
- # +step_limit:+ is +nil+ — an invalid combination. Attaching the policy to
17
- # the budget makes "what happens when it runs out" travel with the budget,
18
- # and that nonsense state unrepresentable. Hosts pick per wiring: a Q&A
19
- # REPL wants +:synthesize+ (salvage from evidence so far); a coding agent
20
- # wants +:raise+ (a tools-free pass can't finish code — stop, let the user
21
- # say "continue"; {#reset!} refreshes the budget next turn).
22
- class StepLimit
23
- # Valid {#on_exhausted} policies.
24
- ON_EXHAUSTED = %i[raise synthesize].freeze
25
- # Raised by {#tick!} once the tool-call count exceeds +max+; carries the
26
- # tripped budget for user-facing messages.
27
- class Exceeded < StandardError
28
- # @return [Integer]
29
- attr_reader :max_steps
30
-
31
- # @param max_steps [Integer]
32
- def initialize(max_steps)
33
- @max_steps = max_steps
34
- super("Agent loop exceeded #{max_steps} steps")
35
- end
36
- end
37
-
38
- # @return [Integer] the configured cap
39
- attr_reader :max
40
-
41
- # @return [Symbol] what {Agent#run_loop} does when this
42
- # budget trips: +:raise+ lets {Exceeded} propagate to the
43
- # host; +:synthesize+ runs the tools-free synthesizer
44
- # rescue. See the class header for how to pick.
45
- attr_reader :on_exhausted
46
-
47
- # @param max [Integer] hard cap on tool-call rounds; must
48
- # be positive
49
- # @param on_exhausted [Symbol] +:raise+ (default) or
50
- # +:synthesize+ — see {#on_exhausted}
51
- # @raise [ArgumentError] if +max+ is zero or negative, or
52
- # +on_exhausted+ is not one of {ON_EXHAUSTED}
53
- def initialize(max:, on_exhausted: :raise)
54
- raise ArgumentError, "max must be positive, got #{max}" if max <= 0
55
- raise ArgumentError, "on_exhausted must be one of #{ON_EXHAUSTED.inspect}, got #{on_exhausted.inspect}" \
56
- unless ON_EXHAUSTED.include?(on_exhausted)
57
-
58
- @max = max
59
- @on_exhausted = on_exhausted
60
- @step = 0
61
- end
62
-
63
- # Increment the counter; raise {Exceeded} once it crosses {#max}. Called
64
- # from {Agent}'s +before_tool_call+ wiring.
65
- #
66
- # @return [void]
67
- # @raise [Exceeded] when the counter now exceeds {#max}
68
- def tick!
69
- @step += 1
70
- raise Exceeded, @max if @step > @max
71
- end
72
-
73
- # Reset the counter to zero. Called by {Agent} at each turn start so one
74
- # instance governs many turns. Mid-loop {Control::Interloper} injections
75
- # deliberately do *not* reset — they're context for the same turn, and a
76
- # chatty user could otherwise refresh the budget forever by injecting.
77
- #
78
- # @return [void]
79
- def reset!
80
- @step = 0
81
- end
82
-
83
- # @return [Integer] current step count.
84
- attr_reader :step
85
-
86
- # @return [String] short config dump for {Agent#to_s}; the policy
87
- # renders only when the non-default +:synthesize+.
88
- def to_s
89
- policy = @on_exhausted == :raise ? '' : ", on_exhausted=#{@on_exhausted}"
90
- "StepLimit(max=#{@max}#{policy})"
91
- end
92
- end
93
- end
94
- end
95
- end
@@ -1,120 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Pikuri
4
- class Agent
5
- # Capability facade handed to {Extension#bind} and
6
- # {Extension#on_user_message} — the runtime counterpart of {Configurator}.
7
- # Where the Configurator collects *build-time* declarations, this grants
8
- # the *runtime* capabilities an extension needs once the agent is wired:
9
- # emitting domain events, registering raw per-agent tools, deriving
10
- # sub-agent listener lists.
11
- #
12
- # == Why a handed object, not a getter on Agent
13
- #
14
- # {Agent} exposes NO public path to these capabilities (no +listeners+ /
15
- # +chat+ reader, no emit method): holding an agent grants read access to
16
- # its config and nothing more. The only way to obtain this object is to be
17
- # an {Extension} receiving +bind+ / +on_user_message+ — or to be handed it
18
- # onward by one ({Pikuri::SubAgent::SubAgentTool} and
19
- # {Pikuri::Mcp::Servers::Connect} both capture the context their +bind+
20
- # received). Capabilities flow by explicit handoff, never by fetching from
21
- # a globally reachable object. The boundary is the API contract, not a
22
- # mechanical seal — same as every seam in CLAUDE.md.
23
- #
24
- # == Boundary rule
25
- #
26
- # Operations that *act on* the live agent's wiring live here; passive
27
- # readers of constructor-given config (+transport+, +id+, +tools+, ...)
28
- # stay on {Agent}, reachable via {#agent}. Don't move readers in; don't add
29
- # capabilities to Agent.
30
- #
31
- # == Audit
32
- #
33
- # One context per agent, built by {Agent#initialize} before the +bind+
34
- # sweep. {ListenerList#emit} has exactly two callers: {Agent} (loop
35
- # narration) and this class (domain events). Capability-user roster:
36
- # +grep -rn 'emit_event\|add_raw_tool\|sub_agent_listeners' pikuri-*/lib/+.
37
- class ExtensionContext
38
- # @param agent [Agent] the live, fully wired agent.
39
- # @param chat [RubyLLM::Chat] the agent's underlying chat —
40
- # target of {#add_raw_tool}.
41
- # @param listeners [ListenerList] the agent's listener list —
42
- # target of {#emit_event} / {#sub_agent_listeners}.
43
- # @param on_close_sink [Array<Proc>] the agent's live
44
- # +@on_close_handlers+ array, which {#on_close} appends to —
45
- # same live-sink shape as {Configurator}'s +on_close_sink:+.
46
- def initialize(agent:, chat:, listeners:, on_close_sink:)
47
- @agent = agent
48
- @chat = chat
49
- @listeners = listeners
50
- @on_close_handlers = on_close_sink
51
- end
52
-
53
- # @return [Agent] the live agent, for read access to its
54
- # configuration (tools, transport, id, streaming, ...).
55
- attr_reader :agent
56
-
57
- # Emit a domain event onto the agent's listener stream. Core {Event}
58
- # variants narrate the loop ({Agent}-emitted); gems define their own
59
- # (e.g. +Pikuri::Tasks::ListChanged+) and emit them here. Listeners must
60
- # no-op on variants they don't recognize (the {Listener::Base#on_event}
61
- # default gives that for free).
62
- #
63
- # Called on the agent's thread (typically inside a tool's +execute+,
64
- # landing between {Event::ToolCall} and {Event::ToolResult}); listeners
65
- # doing cross-thread handoff snapshot inside +on_event+.
66
- #
67
- # @param event [Object] an immutable event value (by convention a +Data+)
68
- # @return [void]
69
- def emit_event(event)
70
- @listeners.emit(event)
71
- nil
72
- end
73
-
74
- # Register a raw +RubyLLM::Tool+ subclass on the agent's chat, bypassing
75
- # the {Pikuri::Tool} strict-validation seam — hence "raw" (native tools
76
- # go through {Configurator#add_tool} for {Tool::Parameters} validation).
77
- # Callers: {Pikuri::Mcp::Servers} (MCP tools deliberately bypass) and
78
- # {Pikuri::SubAgent::Extension} (the +agent+ tool registers after the
79
- # parent's tool list is final).
80
- #
81
- # The tool does NOT enter {Agent#tools}, only the chat's list — so
82
- # sub-agents can't snapshot it, which is the point: activation is strictly
83
- # per-agent.
84
- #
85
- # @param ruby_llm_tool [Class] subclass of +RubyLLM::Tool+
86
- # @return [void]
87
- def add_raw_tool(ruby_llm_tool)
88
- @chat.with_tool(ruby_llm_tool)
89
- nil
90
- end
91
-
92
- # Derive a listener list for a spawned sub-agent via
93
- # {ListenerList#for_sub_agent}. Sole caller:
94
- # {Pikuri::SubAgent::SubAgentTool}, once per spawn. The derived list
95
- # aliases the parent's listener *instances* where a listener opts to
96
- # share by reference — see {ListenerList#for_sub_agent}.
97
- #
98
- # @param params [Hash{Symbol => Object}] forwarded to each listener's
99
- # +for_sub_agent+ hook (currently +id:+).
100
- # @return [ListenerList]
101
- def sub_agent_listeners(**params)
102
- @listeners.for_sub_agent(**params)
103
- end
104
-
105
- # Register a handler called by {Agent#close} — symmetric to
106
- # {Configurator#on_close} (LIFO, per-handler rescue, idempotent) but
107
- # available post-construction, so an {Extension}'s +bind+ can install
108
- # per-agent cleanup (Memory arms its recorder's bounded flush here).
109
- #
110
- # @yield called with no arguments at close time
111
- # @return [void]
112
- def on_close(&blk)
113
- raise ArgumentError, 'on_close requires a block' unless block_given?
114
-
115
- @on_close_handlers << blk
116
- nil
117
- end
118
- end
119
- end
120
- end