pikuri-core 0.0.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +17 -30
  3. data/lib/pikuri/agent/chat_transport.rb +168 -107
  4. data/lib/pikuri/agent/configurator.rb +194 -173
  5. data/lib/pikuri/agent/control/cancellable.rb +100 -70
  6. data/lib/pikuri/agent/control/handoff.rb +75 -0
  7. data/lib/pikuri/agent/control/interloper.rb +107 -118
  8. data/lib/pikuri/agent/control.rb +13 -35
  9. data/lib/pikuri/agent/event.rb +144 -197
  10. data/lib/pikuri/agent/extension.rb +83 -95
  11. data/lib/pikuri/agent/history.rb +247 -0
  12. data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
  13. data/lib/pikuri/agent/listener/terminal.rb +169 -136
  14. data/lib/pikuri/agent/listener/token_log.rb +84 -157
  15. data/lib/pikuri/agent/listener.rb +24 -44
  16. data/lib/pikuri/agent/listener_list.rb +32 -47
  17. data/lib/pikuri/agent/request_instrumenter.rb +102 -0
  18. data/lib/pikuri/agent.rb +1095 -577
  19. data/lib/pikuri/attachment.rb +65 -0
  20. data/lib/pikuri/bundler_env.rb +68 -0
  21. data/lib/pikuri/extractor/passthrough.rb +24 -31
  22. data/lib/pikuri/extractor.rb +125 -155
  23. data/lib/pikuri/file_type.rb +64 -136
  24. data/lib/pikuri/finalizers.rb +32 -47
  25. data/lib/pikuri/paths.rb +104 -13
  26. data/lib/pikuri/sanitizer.rb +46 -67
  27. data/lib/pikuri/subprocess.rb +86 -118
  28. data/lib/pikuri/testing.rb +369 -0
  29. data/lib/pikuri/tool/calculator.rb +168 -74
  30. data/lib/pikuri/tool/execute_context.rb +42 -0
  31. data/lib/pikuri/tool/parameters.rb +31 -29
  32. data/lib/pikuri/tool/result.rb +164 -0
  33. data/lib/pikuri/tool/trifecta_legs.rb +248 -0
  34. data/lib/pikuri/tool.rb +416 -67
  35. data/lib/pikuri/trifecta/contribution.rb +43 -0
  36. data/lib/pikuri/trifecta/node.rb +47 -0
  37. data/lib/pikuri/trifecta/report.rb +228 -0
  38. data/lib/pikuri/trifecta.rb +126 -0
  39. data/lib/pikuri/version.rb +1 -1
  40. data/lib/pikuri-core.rb +70 -92
  41. data/prompts/agent-loop.txt +5 -0
  42. data/prompts/pikuri-chat.txt +3 -12
  43. metadata +26 -72
  44. data/lib/pikuri/agent/context_window_detector.rb +0 -222
  45. data/lib/pikuri/agent/control/step_limit.rb +0 -111
  46. data/lib/pikuri/agent/extension_context.rb +0 -147
  47. data/lib/pikuri/agent/listener/rate_limited.rb +0 -172
  48. data/lib/pikuri/agent/synthesizer.rb +0 -171
  49. data/lib/pikuri/extractor/html.rb +0 -303
  50. data/lib/pikuri/tool/fetch.rb +0 -172
  51. data/lib/pikuri/tool/scraper.rb +0 -186
  52. data/lib/pikuri/tool/search/brave.rb +0 -198
  53. data/lib/pikuri/tool/search/duckduckgo.rb +0 -207
  54. data/lib/pikuri/tool/search/engines.rb +0 -186
  55. data/lib/pikuri/tool/search/exa.rb +0 -229
  56. data/lib/pikuri/tool/search/rate_limiter.rb +0 -92
  57. data/lib/pikuri/tool/search/result.rb +0 -29
  58. data/lib/pikuri/tool/web_scrape.rb +0 -121
  59. data/lib/pikuri/tool/web_search.rb +0 -57
  60. data/lib/pikuri/url_cache.rb +0 -112
@@ -2,231 +2,178 @@
2
2
 
3
3
  module Pikuri
4
4
  class Agent
5
- # Sealed value-object hierarchy describing a single event in the
6
- # +Agent+'s normalized stream. Every listener consumes these through
7
- # one {Listener::Base#on_event} entry point and pattern-matches on
8
- # the variant.
5
+ # Sealed value-object hierarchy for the +Agent+'s normalized event
6
+ # stream. Listeners consume every variant through one
7
+ # {Listener::Base#on_event} and +case+-match on it.
9
8
  #
10
- # Each variant is a +Data.define+ with the minimal fields it needs;
11
- # value equality and pattern-matching support come for free.
12
- #
13
- # == One stream, no side channels
14
- #
15
- # Provider-reported token usage rides as {Tokens}; the detected
16
- # context-window cap rides as a one-shot {ContextCap} emitted by
17
- # {Agent#initialize}; everything else maps to a turn-or-tool-call
18
- # variant. Listeners override a single +on_event+ method and
19
- # +case+-match on the variant they care about. The per-variant
20
- # docs below name the emission site for each (which {Agent}
21
- # callback wires it and what payload it carries).
22
- #
23
- # == Sealed for loop narration; gems add domain events
24
- #
25
- # "Sealed" applies to the *loop-narration* vocabulary: the
26
- # variants below are the complete set, all emitted by {Agent},
27
- # and new chat-loop observability belongs here, not in a gem.
28
- # Gems may define their own *domain* events in their own
29
- # namespace (e.g. +Pikuri::Tasks::ListChanged+) and emit them
30
- # via {ExtensionContext#emit_event}; they ride the same stream.
31
- # Listeners must no-op on variants they don't recognize —
32
- # {Listener::Base#on_event}'s default plus +case+-fallthrough
33
- # give that for free.
9
+ # "Sealed" scopes the *loop-narration* vocabulary: the variants below
10
+ # are the complete set, all emitted by {Agent}, and new chat-loop
11
+ # observability belongs here. Gems define their own *domain* events in
12
+ # their own namespace (e.g. a task list's +ListChanged+) and emit
13
+ # them via {Configurator#emit_event} onto the same stream;
14
+ # listeners must no-op on variants they don't recognize. A domain event's
15
+ # +#to_s+ is its whole rendering in a generic listener, which never reads
16
+ # its fields — that keeps core ignorant of a gem's payload. Why one open
17
+ # stream: +design/decisions.md+ +D_domain_events+.
34
18
  module Event
35
- # User's input for a turn (+mid_loop: false+, the default) or a
36
- # host-supplied injection delivered while the loop is running
37
- # (+mid_loop: true+, drained from {Control::Interloper}). The
38
- # flag exists so listeners that treat the +UserTurn+ as a turn
39
- # boundary can distinguish a fresh turn from an in-loop
40
- # injection (additional context for the same turn, not a new
41
- # one). Controls themselves no longer see this event — the
42
- # +Agent+ pokes their +reset!+ / +tick!+ entry points directly
43
- # at the right boundaries.
19
+ # User input for a turn (+mid_loop: false+, the default) or a host
20
+ # injection delivered mid-loop (+mid_loop: true+, drained from
21
+ # {Control::Interloper}). The flag lets a listener treating
22
+ # +UserTurn+ as a turn boundary tell a fresh turn from an in-loop
23
+ # injection. Emitted by {Agent#run_loop} at turn start, and when an
24
+ # interloper item drains in after a tool batch.
44
25
  #
45
- # Emitted in two places: by {Agent#run_loop} at the start of
46
- # each turn (with +mid_loop: false+), and by {Agent}'s
47
- # +after_tool_result+ wiring when a queued
48
- # {Control::Interloper} item drains into the chat history
49
- # (with +mid_loop: true+).
50
- UserTurn = Data.define(:content, :mid_loop) do
51
- # @param content [String] user-supplied text
52
- # @param mid_loop [Boolean] +false+ for a turn-starting message
53
- # (the default); +true+ when drained from
54
- # {Control::Interloper}
55
- def initialize(content:, mid_loop: false)
56
- super
26
+ # Carries the attachments themselves, not a handle to look up: a
27
+ # listener has no {Agent::History} to resolve one against, and the bytes are
28
+ # shared with the chat, not copied.
29
+ UserTurn = Data.define(:content, :attachments, :mid_loop) do
30
+ # @param content [String] user-supplied text; +""+ on an
31
+ # attachment-only turn
32
+ # @param attachments [Array<Pikuri::Attachment>] what the model was
33
+ # shown; mid-loop, without any it can't take, whose notes are then in
34
+ # +content+
35
+ # @param mid_loop [Boolean] +true+ when drained from
36
+ # {Control::Interloper}; default +false+
37
+ def initialize(content:, attachments: [], mid_loop: false)
38
+ super(content: content, attachments: attachments.dup.freeze, mid_loop: mid_loop)
57
39
  end
58
40
  end
59
41
 
60
- # A system-role block an {Extension#on_user_message} hook
61
- # injected into the chat log — recalled reference (memory
62
- # context, retrieved snippets) tagged +role: :system+ so the
63
- # model reads it as background, not new user input. Carries
64
- # the injected text verbatim.
42
+ # A reference block injected into the chat log — recalled memory, a
43
+ # host-loaded skill, a path-activation promotion, retrieved snippets.
44
+ # Carries the block *unwrapped*, without the +<system-reminder>+
45
+ # envelope {Agent#append_reference_block} sends it under, so a listener
46
+ # renders what the host wrote rather than pikuri's framing.
65
47
  #
66
- # Emitted by {Agent#dispatch_ext_on_user_message}, once per
67
- # extension that returns a non-empty block, at the same site
68
- # that grows the chat log — so the event stream stays a
69
- # faithful mirror of what the model actually sees. Without it
70
- # an injection is invisible: it never surfaces in the stream,
71
- # only as a secondary echo in the assistant's later reasoning.
72
- # {Listener::Terminal} renders it dim grey with a +⊕+ marker.
48
+ # Named for the *role it plays* (background reference, not new user
49
+ # input), not the wire role it lands under — which is +:user+, because a
50
+ # mid-conversation +:system+ message is unportable.
73
51
  SystemInjected = Data.define(:content)
74
52
 
75
- # Assistant reasoning ("thinking") block, extracted from the
76
- # +thinking.text+ field on a +RubyLLM::Message+ with role
77
- # +:assistant+. Emitted by {Agent}'s +after_message+ wiring;
78
- # empty +thinking.text+ is filtered at the dispatch site so
79
- # listeners never see vacuous events.
53
+ # Assistant reasoning ("thinking") block, from +thinking.text+ on a
54
+ # +RubyLLM::Message+. Emitted by +after_message+; empty text is
55
+ # filtered at the dispatch site.
80
56
  Thinking = Data.define(:content)
81
57
 
82
- # Assistant Markdown content, extracted from a +RubyLLM::Message+
83
- # with role +:assistant+. Emitted by {Agent}'s +after_message+
84
- # wiring; empty +content+ is filtered at the dispatch site
85
- # (pure tool-call turns surface {Tokens} only, no +Assistant+).
58
+ # Assistant Markdown content, from a +RubyLLM::Message+. Emitted by
59
+ # +after_message+; empty content is filtered (pure tool-call turns
60
+ # surface {Tokens} only).
86
61
  Assistant = Data.define(:content)
87
62
 
88
- # Streaming fragment of an assistant reasoning block, pulled
89
- # off a +RubyLLM::Chunk+ during a streaming completion.
90
- # Emitted by the per-chunk streaming block {Agent#run_loop}
91
- # passes to +Chat#complete+ when the agent's +streaming:+
92
- # flag is on; empty fragments are filtered at the dispatch
93
- # site.
94
- #
95
- # Preview-only, not authoritative: the {Thinking} event
96
- # emitted from +after_message+ at the end of the round-trip
97
- # is the final reasoning text. Providers may normalize
98
- # whitespace, and Anthropic thinking blocks include a
99
- # signature that never appears in deltas, so
100
- # +concat(deltas) == final.content+ is not guaranteed.
101
- #
102
- # == Ordering
63
+ # Streaming fragment of a reasoning block, off a +RubyLLM::Chunk+
64
+ # when +streaming:+ is on. Emitted per-chunk by {Agent#run_loop};
65
+ # empty fragments filtered.
103
66
  #
104
- # Per round-trip: all {ThinkingDelta}s (and {AssistantDelta}s)
105
- # for a round arrive before that round's {Thinking} /
106
- # {Assistant} / {Tokens} bookend, because the streaming block
107
- # fires synchronously inside +Chat#ask+'s SSE read and
108
- # +after_message+ fires once the message is complete. Within
109
- # the delta stream itself, ordering between {ThinkingDelta}
110
- # and {AssistantDelta} is provider-dependent (in practice
111
- # non-interleaved on Anthropic and OpenAI reasoning models,
112
- # but pikuri does not enforce it).
67
+ # Preview-only: the {Thinking} from +after_message+ is
68
+ # authoritative. +concat(deltas) == final+ is not guaranteed
69
+ # (whitespace normalization, Anthropic signature blocks). All of a
70
+ # round's deltas arrive before that round's
71
+ # {Thinking}/{Assistant}/{Tokens} bookend; {ThinkingDelta} vs
72
+ # {AssistantDelta} interleave order is provider-dependent.
113
73
  ThinkingDelta = Data.define(:content)
114
74
 
115
- # Streaming fragment of an assistant Markdown content block,
116
- # pulled off a +RubyLLM::Chunk+ during a streaming
117
- # completion. Emitted by the per-chunk streaming block
118
- # {Agent#run_loop} passes to +Chat#complete+ when the
119
- # agent's +streaming:+ flag is on; empty fragments are
120
- # filtered at the dispatch site.
121
- #
122
- # Preview-only, same semantics as {ThinkingDelta}: the
123
- # {Assistant} event emitted from +after_message+ at the end
124
- # of the round-trip is the authoritative final text;
125
- # listeners that need an exact concat of fragments should
126
- # consume {Assistant} instead. Per-round-trip ordering is
127
- # guaranteed; per-modality ordering within the delta stream
128
- # is best-effort.
75
+ # Streaming fragment of assistant Markdown, off a +RubyLLM::Chunk+
76
+ # when +streaming:+ is on. Same preview-only semantics as
77
+ # {ThinkingDelta}; consume {Assistant} for the authoritative text.
129
78
  AssistantDelta = Data.define(:content)
130
79
 
131
- # A tool invocation the LLM has requested but not yet observed.
132
- # Arguments are the raw hash ruby_llm parsed from the model's
133
- # +tool_calls+ JSON — no validation has run yet. Emitted by
134
- # {Agent}'s +before_tool_call+ wiring.
135
- ToolCall = Data.define(:name, :arguments)
136
-
137
- # The observation a tool produced, as returned by {Tool#run}.
138
- # Recoverable failures arrive here as +"Error: ..."+ strings
139
- # (per the pikuri error convention), not as exceptions.
140
- # Emitted by {Agent}'s +after_tool_result+ wiring.
141
- ToolResult = Data.define(:content)
142
-
143
- # Provider-reported token usage for a single assistant turn,
144
- # copied off a +RubyLLM::Message+'s +tokens+ block. Emitted by
145
- # {Agent}'s +after_message+ wiring on every assistant turn,
146
- # including pure tool-call turns where {Assistant} would have
147
- # been filtered for empty content (those are exactly the turns
148
- # where context-window growth matters most).
80
+ # A tool the LLM requested but hasn't observed yet. +display_name+ and
81
+ # +argument+ are what a chrome puts on the screen:
149
82
  #
150
- # All counts are +Integer, nil+. +nil+ means the provider did not
151
- # report that field — common with local llama.cpp / Ollama
152
- # servers that leave parts of the OpenAI +usage+ block empty.
153
- # Listeners treat +nil+ as zero.
83
+ # → Write(lib/shared/config.rb)
154
84
  #
155
- # The fields +input+, +cached+, and +cache_creation+ are
156
- # **exclusive portions of this turn's full prompt** under the
157
- # shape ruby_llm exposes for llama.cpp and Anthropic: they sum
158
- # to the total prompt size processed on this request. OpenAI
159
- # proper nests +cached_tokens+ inside its +prompt_tokens+
160
- # instead — if pikuri ever talks there directly, the sum formula
161
- # needs revisiting.
85
+ # +arguments+ is the raw hash ruby_llm parsed from the model's
86
+ # +tool_calls+ JSON — unvalidated; the two display strings are the tool's
87
+ # own ({Tool#display_name} / {Tool#describe_call}), so every chrome prints
88
+ # the same line and only styles, caps and defangs it. An +argument+ of
89
+ # +""+ renders the call bare — +Name+, not +Name()+.
162
90
  #
163
- # - +input+ — newly-processed (uncached) prompt tokens this turn.
164
- # - +output+ — tokens in this single assistant reply.
165
- # - +cached+ — portion of this turn's prompt served from the
166
- # provider's prompt cache. Still counts against the context
167
- # window (caching is a speed/cost optimization, not a context-
168
- # savings mechanism).
169
- # - +cache_creation+ — portion of this turn's prompt written
170
- # into the prompt cache. Anthropic-specific; usually +nil+ on
171
- # OpenAI-compatible local servers.
172
- # - +thinking+ — extended-thinking (Anthropic) or reasoning
173
- # (OpenAI o-series) tokens produced on this turn. +nil+ on
174
- # providers without a reasoning channel.
175
- # - +model_id+ — provider-side model name as reported on the
176
- # response; useful when a process targets multiple models.
91
+ # Strings rather than a +tool:+ reference a renderer could query: the
92
+ # event must stay plain serializable +Data+, and three cases have no
93
+ # {Pikuri::Tool} to query at all — an MCP tool, ruby_llm's
94
+ # unavailable-tool error, a replayed conversation.
95
+ #
96
+ # Emitted by +before_tool_call+.
97
+ ToolCall = Data.define(:tool_call_id, :name, :arguments, :display_name, :argument)
98
+
99
+ # The observation a tool produced ({Tool#run}'s return), plus the
100
+ # one-line +summary+ a chrome shows in its place (+"Returned 23 search
101
+ # results"+). Recoverable failures arrive as +"Error: ..."+ strings, not
102
+ # exceptions, and their summary is that message. An image observation
103
+ # arrives as its text note (+"Read image: shot.png (2048 bytes, …)"+); the
104
+ # bytes go to the model only.
177
105
  #
178
- # == Computing "current context window size"
106
+ # +tool_call_id+ pairs this with its {ToolCall} by key, so a renderer
107
+ # needs no assumption about call→result ordering. Both carry the
108
+ # server's id, the one {History} stores.
179
109
  #
180
- # +input + cached + cache_creation+ is the size of the prompt
181
- # processed on this turn. Add +output+ to get tokens consumed by
182
- # the conversation *through* this turn — this turn's prompt plus
183
- # its reply, both of which the model will re-process on the next
184
- # turn. That's what climbs toward
185
- # +RubyLLM::ContextLengthExceededError+ and is the snapshot
186
- # {Listener::TokenLog#context_window_size} tracks.
187
- Tokens = Data.define(:input, :output, :cached, :cache_creation, :thinking, :model_id)
110
+ # Emitted by +after_tool_result+, and by {Agent#run_loop}'s
111
+ # dangling-call repair (summary +"Interrupted"+).
112
+ ToolResult = Data.define(:tool_call_id, :name, :content, :summary)
188
113
 
189
- # Model's resolved context-window cap. Emitted at construction
190
- # by {Agent#initialize}, and again after every model switch
191
- # (see {Agent#run_loop}'s +transport:+) since the cap is a
192
- # property of the model. Carries +nil+ when no source produced
193
- # a value (a non-llama server with no explicit cap). Listeners
194
- # that care — {Listener::TokenLog} renders +ctx=<used>/<cap>+
195
- # when set, +ctx=<used>+ when +nil+ — pick the value off this
196
- # event and cache it; non-caring listeners ignore. A second
197
- # ContextCap simply overwrites the first; the conversation is
198
- # not re-baselined (a switch keeps the running context size).
199
- ContextCap = Data.define(:cap)
114
+ # Provider-reported token usage for one assistant turn, off a
115
+ # +RubyLLM::Message+'s +tokens+ block. Emitted by +after_message+ on
116
+ # every assistant turn (including pure tool-call turns, where
117
+ # context growth matters most).
118
+ #
119
+ # Every count is +Integer, nil+; +nil+ means the provider omitted
120
+ # the field (common on local llama.cpp/Ollama) and is treated as
121
+ # zero. +input+/+cached+/+cache_creation+ are *exclusive* slices of
122
+ # this turn's prompt and sum to its total size (llama.cpp +
123
+ # Anthropic shape; OpenAI nests +cached+ inside +input+, so revisit
124
+ # the sum if pikuri ever targets it directly). +cached+ still counts
125
+ # against the context window.
126
+ #
127
+ # - +input+ — newly-processed (uncached) prompt tokens this turn.
128
+ # - +output+ — tokens in this reply.
129
+ # - +cached+ — prompt tokens served from the provider's cache.
130
+ # - +cache_creation+ — prompt tokens written to the cache (Anthropic).
131
+ # - +thinking+ — reasoning tokens (Anthropic thinking / OpenAI
132
+ # o-series); +nil+ without a reasoning channel.
133
+ # - +model_id+ — provider-side model name on the response.
134
+ Tokens = Data.define(:input, :output, :cached, :cache_creation, :thinking, :model_id)
200
135
 
201
- # The agent switched to a different model mid-conversation,
202
- # emitted by {Agent#run_loop} (via +apply_transport!+) just
203
- # before the matching {ContextCap} for the new model. Carries
204
- # the old and new {Agent::ChatTransport}s verbatim — unformatted
205
- # by design, so each chrome presents them its own way (a TUI
206
- # adds ANSI off +.model+, a web client adds CSS). The cap rides
207
- # on the paired {ContextCap}, not here, so {Listener::TokenLog}
208
- # needs no awareness of this event (its existing {ContextCap}
209
- # arm picks up the new cap); a renderer wanting "switched to X
210
- # (128k)" on one line correlates the two.
136
+ # Agent switched model mid-conversation. Emitted by {Agent#run_loop}
137
+ # ahead of that turn's {UserTurn}. Carries both {Agent::ChatTransport}s
138
+ # verbatim and unformatted — each chrome presents them its own way; the
139
+ # new model's stated cap and modalities ride on +to+.
211
140
  ModelSwitched = Data.define(:from, :to)
212
141
 
213
- # Out-of-band notice that the agent had to take a rescue path.
214
- # Emitted by {Agent#run_loop} when {Control::StepLimit} trips
215
- # and the synthesizer fallback runs; carries the reason string
216
- # the listener should surface. Lets listeners (Terminal, future
217
- # web UI) surface the divergence to the user before the
218
- # synthesizer's own assistant output flows through.
219
- FallbackNotice = Data.define(:reason)
220
-
221
- # Out-of-band notice that the user cancelled the in-flight turn
222
- # via {Control::Cancellable}. Emitted by {Agent#run_loop} just
223
- # before the +Cancellable::Cancelled+ exception re-raises out of
224
- # the loop, so listeners (Terminal renderer, structured
225
- # recorders) can mark the turn as user-aborted. Unlike
226
- # {FallbackNotice}, no recovery follows — the exception is
227
- # re-raised and the caller is expected to return control to the
228
- # user (typically the REPL prompt).
142
+ # Out-of-band notice that the user cancelled the in-flight turn via
143
+ # {Control::Cancellable}. Emitted by {Agent#run_loop} just before the
144
+ # +Cancelled+ exception re-raises. No recovery follows; the caller
145
+ # returns control to the user.
229
146
  Cancelled = Data.define
147
+
148
+ # The agent was built with a saved conversation (+Agent.new(history:)+)
149
+ # rather than an empty one. Emitted once, at the end of construction,
150
+ # and carries what a listener needs to stop reporting an empty
151
+ # conversation.
152
+ #
153
+ # +tokens+ is the last assistant message's usage as recorded when the
154
+ # conversation was exported, so a running context readout can pick up
155
+ # where it left off instead of showing +0+ against 40k of restored
156
+ # history. +nil+ when the history holds no assistant turn, or was
157
+ # exported without usage.
158
+ #
159
+ # @!attribute [r] messages
160
+ # @return [Integer] how many messages were restored
161
+ # @!attribute [r] tokens
162
+ # @return [Tokens, nil] usage of the last restored assistant message
163
+ HistoryLoaded = Data.define(:messages, :tokens)
164
+
165
+ # The conversation was swapped for a compacted rendering of itself
166
+ # ({Configurator#replace_compacted_history}); tools, extensions and the
167
+ # system prompt stand as they were.
168
+ #
169
+ # Carries no token counts: what the shorter conversation costs is known
170
+ # only once the next reply reports usage.
171
+ #
172
+ # @!attribute [r] messages_before
173
+ # @return [Integer] how many messages the conversation held
174
+ # @!attribute [r] messages_after
175
+ # @return [Integer] how many it holds now
176
+ HistoryCompacted = Data.define(:messages_before, :messages_after)
230
177
  end
231
178
  end
232
179
  end
@@ -3,120 +3,108 @@
3
3
  module Pikuri
4
4
  class Agent
5
5
  # The Extension protocol — how hosts bolt extra capabilities
6
- # (system-prompt snippets, tools, lifecycle hooks) onto an
7
- # {Agent}. Extensions are added via {Configurator#add_extension}
8
- # inside the +Agent.new+ block; the Agent then drives three hooks
9
- # on each — {#configure} during the block, {#bind} once the agent
10
- # is fully constructed, and {#on_user_message} on every user turn
11
- # thereafter.
6
+ # (system-prompt sections, tools, lifecycle hooks) onto an {Agent}.
7
+ # Added via {Configurator#add_extension} inside the +Agent.new+ block,
8
+ # which calls {#configure} at once; the Agent then pulls
9
+ # {#system_prompt_snippets} when it assembles the prompt and calls
10
+ # {#on_user_message} on every user turn.
12
11
  #
13
- # Each phase receives that phase's context object: +configure+
14
- # gets the build-time {Configurator}; +bind+ and
15
- # +on_user_message+ get the runtime {ExtensionContext} — the
16
- # capability facade for everything that acts on the live agent
17
- # (domain-event emission, raw tool registration, sub-agent
18
- # listener derivation), with the agent itself readable via
19
- # {ExtensionContext#agent}.
20
- #
21
- # Mix this module into an extension class to inherit empty
22
- # default implementations of all three hooks; override the ones
23
- # you need. Extensions that don't +include+ this module still
24
- # work *if they define all three methods themselves* — the Agent
25
- # and Configurator call them by name with no +respond_to?+ guard,
26
- # so a missing one raises. The module exists to make the protocol
27
- # *explicit* and to give "I want to implement just +configure+"
28
- # extensions free no-op +bind+ / +on_user_message+ defaults (and
29
- # any other combination).
30
- #
31
- # == Example
32
- #
33
- # class MyExtension
12
+ # class Reminder
34
13
  # include Pikuri::Agent::Extension
14
+ # def system_prompt_snippets = ["Always be polite."]
15
+ # end
35
16
  #
36
- # def configure(c)
37
- # c.append_system_prompt("Always be polite.")
38
- # end
17
+ # An instance serves one agent, which is one conversation: build a fresh
18
+ # one for every +Agent.new+, so per-conversation state is plain instance
19
+ # state and nothing has to reset it; {Configurator#add_extension} refuses
20
+ # a reused one. A resource that legitimately outlives the conversation is
21
+ # built by the host and passed in.
39
22
  #
40
- # # bind not overridden — inherits the empty default
41
- # end
23
+ # Mix this module in to inherit no-op defaults for every hook, and
24
+ # override what you need. Not including it also works *if the class
25
+ # defines every hook* — the Agent calls them by name with no
26
+ # +respond_to?+ guard, so a missing one raises.
42
27
  #
43
- # See +Pikuri::Mcp::Extension+ and +Pikuri::Skill::Extension+
44
- # (once those land in Steps 2-3 of the gem-split refactor — see
45
- # IDEAS.md §"Extension protocol design") for the canonical
46
- # worked implementations.
28
+ # The whole surface fires on the *parent agent only* — sub-agents do not
29
+ # inherit extensions (each persona owns its toolset and prompt verbatim).
30
+ # See +Pikuri::Workspace::Extension+ / +Pikuri::Thunderbird::Extension+ (sibling
31
+ # gems) for worked implementations.
47
32
  module Extension
48
- # Called immediately by {Configurator#add_extension} during the
49
- # +Agent.new+ block, with the parent agent's {Configurator}.
50
- # Runs exactly once per extension instance, on the parent agent
51
- # only — sub-agents do not re-run +configure+. The default is a
52
- # no-op; override when you need to install *agent-agnostic*
53
- # state. Things you typically do here:
33
+ # Install this extension on the agent being built. Keep +c+ to act on
34
+ # the agent later — {Configurator#emit_event} from a change callback,
35
+ # {Configurator#add_raw_tool} from a tool's +execute+. Default no-op.
54
36
  #
55
- # * append snippets to the system prompt via
56
- # {Configurator#append_system_prompt}
57
- # * register tools via {Configurator#add_tool}
58
- # * register listeners via {Configurator#add_listener}
59
- # * register parent-only +on_close+ handlers via
60
- # {Configurator#on_close} (for cleanup of resources the
61
- # extension created in +configure+)
62
- # * read the agent's transport / cancellable / etc. via the
63
- # Configurator's +attr_reader+s
37
+ # A resumed conversation is {Configurator#history}, so an extension can
38
+ # rebuild what the transcript implies — the tools it had registered
39
+ # mid-conversation.
64
40
  #
65
- # @param c [Configurator] the parent agent's Configurator
41
+ # @param c [Configurator] the agent's Configurator
66
42
  # @return [void]
67
43
  def configure(c); end
68
44
 
69
- # Called by {Agent#initialize} after the block returns and the
70
- # chat is fully wired, with the agent's {ExtensionContext} as
71
- # the argument. Fires once per agent the extension was
72
- # registered to via {Configurator#add_extension} — in the
73
- # typical setup that's the parent agent only, since sub-agents
74
- # do not inherit extensions. The default is a no-op; override
75
- # when you need to install state keyed to the live agent.
76
- # Things you typically do here:
45
+ # Optional per-turn hook fired after a user message is added to the
46
+ # chat. Default no-op returning +nil+; override and return a {String} to
47
+ # have it appended after the user turn as a +<system-reminder>+ reference
48
+ # block (see {Agent#append_reference_block} for the envelope and why it
49
+ # is not a +:system+ message).
77
50
  #
78
- # * register dynamic tools via {ExtensionContext#add_raw_tool}
79
- # (used by {Pikuri::Mcp::Extension} for +mcp_connect+,
80
- # whose +execute+ closure needs the context so activations
81
- # register on the right chat)
82
- # * wire domain-event emission via
83
- # {ExtensionContext#emit_event} (e.g. +Pikuri::Tasks::Extension+
84
- # arms its list's +on_change+ here)
85
- # * register per-agent +on_close+ handlers via
86
- # {ExtensionContext#on_close}
87
- # * stash the +ctx+ if the extension's tools need to act on
88
- # this specific agent later
51
+ # The Agent only ever *appends* the returned block at the tail — never
52
+ # rewrites or removes an earlier one, which would bust the provider
53
+ # prefix cache for everything after the edit. Stale blocks ride the
54
+ # existing context-window machinery, not a per-turn rewrite. Why a hook
55
+ # rather than a listener: +design/decisions.md+ +D_on_user_message_hook+.
89
56
  #
90
- # @param ctx [ExtensionContext] capability facade for the
91
- # live, fully wired agent
92
- # @return [void]
93
- def bind(ctx); end
57
+ # @param content [String] the user message's text (initial or
58
+ # interloper); +""+ when the turn carries only attachments
59
+ # @param attachments [Array<Pikuri::Attachment>] what the model was
60
+ # shown with it. Passed as data, so each extension words it as it
61
+ # needs — a memory extension records a note naming each file, while a
62
+ # reminder that only reacts to the turn ignores them.
63
+ # @return [String, nil] text to append, stripped and wrapped, as a +:user+
64
+ # reference block after the user message; +nil+ or blank injects nothing
65
+ def on_user_message(content, attachments); end
94
66
 
95
- # Optional per-turn hook fired by the {Agent} after a user-message
96
- # is added to the chat. The
97
- # default is a no-op returning +nil+; override and return {String}
98
- # to emit a `:system` message with that text.
67
+ # This extension's system-prompt contributions, as text sections.
68
+ # Default none (+[]+); override to contribute one or more.
69
+ #
70
+ # Pull, not push: the {Agent} assembles its prompt once, at
71
+ # construction, by concatenating the base with what every extension
72
+ # returns here. A section computed from live state (the workspace's file
73
+ # listing, a note read from disk) is therefore as of the conversation's
74
+ # start, and a "/clear" — a new agent — takes it again.
99
75
  #
100
- # == Append-only, never mutate
76
+ # No argument: read instance state populated in {#configure} (which runs
77
+ # first). Producing that state (starting servers, probing a model)
78
+ # belongs in +configure+; this only *reads* it (memoize an expensive
79
+ # one-shot at its source).
80
+ # Sections are joined by the Agent (blank/nil dropped), in registration
81
+ # order.
82
+ #
83
+ # @return [Array<String>] zero or more prompt sections; +[]+ for none
84
+ def system_prompt_snippets = []
85
+
86
+ # What this extension adds to the lethal-trifecta tree
87
+ # ({Pikuri::Trifecta}): legs the wired agent holds beyond its own tools,
88
+ # and child nodes for any sub-agents it introduces. Default none.
101
89
  #
102
- # The Agent only ever *appends* the returned block at the tail; it never
103
- # rewrites or removes an earlier one. Mutating mid-log would bust the
104
- # provider prefix cache for every message after the edit. Stale blocks
105
- # ride the existing context-window machinery, not a per-turn rewrite.
90
+ # Only two kinds of extension owe an answer, and both are things per-tool
91
+ # tagging structurally cannot see: one that introduces **sub-agents** (a
92
+ # whole node, plus the gate on the delegation edge) and one that mounts a
93
+ # **foreign tool surface** whose tools carry no legs of their own.
106
94
  #
107
- # == Not inherited by sub-agents
95
+ # +tools+ is the wired agent's tools plus its sub-agent tools, so an
96
+ # extension resolving a persona's +tool_names+ can select the same
97
+ # objects the sub-agent will actually receive — the resolution and the
98
+ # node it produces stay with whoever owns them.
108
99
  #
109
- # Like the rest of the extension surface, this fires on the parent agent
110
- # only — sub-agents do not inherit extensions, so a persona's turns are
111
- # never prefetched or recorded by the parent's memory.
100
+ # Unlike every other hook here, the Agent calls this **guarded by
101
+ # +respond_to?+**: this protocol permits a class that defines all hooks
102
+ # without including the module, and an unguarded new hook would break
103
+ # those. So a non-including extension may simply not have it.
112
104
  #
113
- # @param ctx [ExtensionContext] capability facade for the live
114
- # agent whose turn this is — same instance +bind+ received
115
- # @param content [String] the user message (initial or interloper) about
116
- # to be sent to the model
117
- # @return [String, nil] an optional block of text to be injected verbatim as
118
- # a system-role message (after the user message), or +nil+ to inject nothing
119
- def on_user_message(ctx, content); end
105
+ # @param tools [Array<Pikuri::Tool>] the agent's tools + sub-agent tools
106
+ # @return [Pikuri::Trifecta::Contribution, nil] +nil+ for none
107
+ def trifecta_contribution(tools) = nil
120
108
  end
121
109
  end
122
110
  end