pikuri-workspace 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.
@@ -1,156 +1,217 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'rainbow'
4
-
5
3
  module Pikuri
6
4
  module Workspace
7
- # Port for asking the user to confirm a potentially destructive tool
8
- # operation — currently {Pikuri::Code::Bash} (every command) and
9
- # {Write} (overwrite of an existing file with non-identical
10
- # content). Subclass and implement {#confirm?}.
5
+ # Port for resolving a "may I do this?" confirmation to a decision — in
6
+ # pikuri, {Write}, the +agent+ tool's delegation gate and +web_search+'s
7
+ # query gate; downstream, a shell tool's commands. Subclass and implement
8
+ # {#ask}.
9
+ #
10
+ # == The one job: resolve a {Request} to a decision
11
+ #
12
+ # A Confirmer takes a semantic {Request} and returns {Approved},
13
+ # {Rejected} or {Redirected}. That is *all*: it carries **no tool policy** and never
14
+ # classifies the request's *content* (no filesystem reads, no command
15
+ # parsing, no notion of "passive"). Two shipped implementations:
16
+ #
17
+ # * {Terminal} — the human *chrome*: shows the request and reads the answer.
18
+ # In +confirmer/terminal.rb+ so this seam file stays free of rendering deps.
19
+ # Written for pikuri's own single-threaded +bin/+ scripts and best read as
20
+ # the worked example — a TUI or web host implements this seam itself.
21
+ # * {AutoApprove} — the headless stance: ignores the request and
22
+ # blanket-approves (+--yolo+ / dev-container). Request-independent, so it
23
+ # encodes no policy either.
24
+ #
25
+ # Sharing is per implementation, and the two shipped ones differ:
26
+ # {AutoApprove} is +P_stateless+ and shares freely, while {Terminal} is
27
+ # +P_one_agent+ because concurrent agents fight over one human's keystrokes.
28
+ # A confirmer written for a multi-agent host owns that queueing — and owns
29
+ # naming which agent is asking, which is why the queue can't usefully live
30
+ # down here.
31
+ #
32
+ # Content classification ("is this bash command provably passive, skip the
33
+ # prompt?") deliberately does *not* live here — it's a tool concern (a
34
+ # shell tool takes its own "provably passive" predicate, falling through to
35
+ # this confirmer only for commands it can't pre-approve).
36
+ # Keeping them apart lets one stateless chrome serve every tool.
37
+ #
38
+ # == The return type: {Approved} / {Rejected} / {Redirected}
39
+ #
40
+ # The human's gesture picks one of three; callers pattern-match, and a
41
+ # decline answers the model through the decision's own {Rejected#observation}
42
+ # / {Redirected#observation}:
11
43
  #
12
- # == Why a Boolean return
44
+ # case decision = confirmer.ask(request: request, cancellable: context.cancellable)
45
+ # in Confirmer::Approved(new_request_detail:) then ...act on it...
46
+ # in Confirmer::Rejected | Confirmer::Redirected
47
+ # return decision.observation('the bash command')
48
+ # end
13
49
  #
14
- # v1 returns +true+ or +false+. Two paths-not-taken worth recording
15
- # so a future reader knows the design space was considered:
50
+ # * {Approved} — approve, carrying the possibly-edited {Request#detail}.
51
+ # * {Rejected} — a plain "no": final for this action, the model stops.
52
+ # * {Redirected} — the human typed words ("make it Wednesday", "too
53
+ # risky"): the model follows them, and may propose again — which asks again.
16
54
  #
17
- # 1. Richer return (+:once+ / +:always+ / +:reject+) — rejected
18
- # because it creates decision fatigue, and the long-term answer
19
- # is to make confirmations rare rather than smart (sandboxing,
20
- # agentic destructiveness analysis).
21
- # 2. Agentic destructive-or-not classifier — deferred to v2.
55
+ # Editing is opt-in via {Request#editable}: when +detail+ is the verbatim
56
+ # actionable payload (the +agent+ task), a confirmer may let the human
57
+ # *rewrite* it — "human as author, not approver". Bash's +"$ <command>"+ is
58
+ # a decorated display string, so it stays non-editable.
22
59
  #
23
- # The intended escape from confirmation prompts today is sandboxing
24
- # (docker / dev-container) plus the +--yolo+ flag on +bin/pikuri-code+
25
- # (which wires {AUTO_APPROVE} instead of {TERMINAL}).
60
+ # == Cancelling a parked ask
61
+ #
62
+ # {#ask} gets the turn's {Pikuri::Agent::Control::Cancellable}, which the
63
+ # tool takes from its {Pikuri::Tool::ExecuteContext}. A confirmer whose
64
+ # human answers on another thread waits in a
65
+ # {Pikuri::Agent::Control::Handoff} built on it, so any +cancel!+ — the
66
+ # cancel key, a shutdown, another tab — makes the parked {#ask} raise
67
+ # {Pikuri::Agent::Control::Cancellable::Cancelled}: the tool lets it
68
+ # through, the agent ends the turn, and the stranded call is answered
69
+ # +[Cancelled by the user]+. Answering {Rejected} instead is not a cancel:
70
+ # the turn runs on for one more model reply. {Terminal} ignores the token —
71
+ # Ctrl+C reaches its +gets+ as +SIGINT+. +D_confirmer_sees_the_cancel+.
72
+ #
73
+ # A +:once+/+:always+ scope knob was *rejected*: it manages decision
74
+ # *fatigue*, a distinct axis, and the long-term answer to fatigue is making
75
+ # confirmations rare (sandboxing, +--yolo+, the +passive_detector+ skip),
76
+ # not smarter approval modes. (An agentic destructive-or-not classifier is a
77
+ # deferred v2.)
26
78
  #
27
79
  # == Seam discipline
28
80
  #
29
- # Tools that need confirmation take a {Confirmer} via constructor and
30
- # invoke {#confirm?} with a semantic {Request} — *what* is being
31
- # asked, never *how* it should look. All presentation belongs to the
32
- # confirmer implementation: color, the answer cue, answer parsing,
33
- # and — security-relevant — neutralizing hostile bytes in
34
- # LLM-supplied text. The chrome-independent half of that (escape
35
- # control bytes, flag bidi / zero-width / homoglyph spoofs) is the
36
- # shared {Pikuri::Sanitizer}; the medium-specific half stays with the
37
- # renderer that knows its medium (a terminal prints the sanitized
38
- # text directly; a web client wraps it in HTML-escaping). Tools do *not*
39
- # call +gets+ / +puts+ directly — same lesson as listeners, keep IO
40
- # at the seam so a TUI / web client can plug a different
41
- # implementation in without touching tool code.
81
+ # Tools take a {Confirmer} via constructor and invoke {#ask} with a semantic
82
+ # {Request} — *what* is asked, never *how* it looks. All presentation
83
+ # belongs to the confirmer: color, the answer cue, parsing, the edit
84
+ # affordance, and — security-relevant — neutralizing hostile bytes in
85
+ # LLM-supplied text. The chrome-independent half (escape control bytes, flag
86
+ # bidi/zero-width/homoglyph spoofs) is the shared {Pikuri::Sanitizer}; the
87
+ # medium-specific half stays with the renderer (a terminal prints sanitized
88
+ # text; a web client HTML-escapes). Tools never call +gets+/+puts+ directly
89
+ # — keep IO at the seam so a TUI/web client plugs in without touching tools.
42
90
  class Confirmer
43
- # The semantic payload of one confirmation. Two fields:
91
+ # The semantic payload of one confirmation:
44
92
  #
45
- # * +question+ — one-line headline composed by the calling tool,
46
- # e.g. +"OK to overwrite foo.rb: 120 → 245 bytes?"+. The caller
47
- # owns the phrasing and punctuation; the renderer owns the
48
- # answer cue (+"(y/n)?"+, buttons, ...).
49
- # * +detail+ — optional preformatted body, possibly multi-line:
50
- # the raw bash command for {Pikuri::Code::Bash}, +nil+ for
51
- # {Write}. Renderers typically display it monospaced / dimmed.
93
+ # * +question+ — one-line headline the tool composes (e.g. +"OK to
94
+ # overwrite foo.rb: 120 → 245 bytes?"+); the caller owns phrasing, the
95
+ # renderer owns the answer cue.
96
+ # * +detail+ — optional preformatted body: the raw bash command, the
97
+ # +agent+ task, +nil+ for {Write}. When +editable+, the exact text the
98
+ # human may rewrite, returned as {Approved#new_request_detail}.
99
+ # * +editable+ — whether the human may edit +detail+ (default +false+);
100
+ # +true+ only when +detail+ is the verbatim payload (the +agent+ task),
101
+ # never a decorated string (bash's +"$ <command>"+).
52
102
  #
53
- # Both fields are RAW, straight from tool arguments the LLM
54
- # composed (+detail+ is the command verbatim; +question+ may embed
55
- # an LLM-written description). Renderers MUST neutralize them before
56
- # display — route through {Pikuri::Sanitizer} (see {Terminal}), and
57
- # additionally HTML-escape in a web client.
58
- Request = Data.define(:question, :detail) do
103
+ # +question+/+detail+ are RAW LLM-composed text — renderers MUST neutralize
104
+ # them via {Pikuri::Sanitizer} (see {Terminal}), plus HTML-escape in a web
105
+ # client.
106
+ Request = Data.define(:question, :detail, :editable, :change) do
59
107
  # @param question [String] one-line headline; caller owns phrasing
60
- # @param detail [String, nil] optional preformatted body
61
- def initialize(question:, detail: nil)
108
+ # @param detail [String, nil] optional preformatted body / editable payload
109
+ # @param editable [Boolean] whether the human may rewrite +detail+
110
+ # @param change [Change, nil] optional structured file change; when
111
+ # present a diff-capable chrome renders a diff of it (see {Change}).
112
+ def initialize(question:, detail: nil, editable: false, change: nil)
62
113
  super
63
114
  end
64
115
  end
65
116
 
66
- # @param request [Request] semantic content composed by the
67
- # calling tool. The confirmer renders it (escaping for its
68
- # medium), poses the question, and parses the answer.
69
- # @return [Boolean] +true+ iff approved
117
+ # A structured file change for a {Write}/{Edit} confirmation: the
118
+ # *semantic* change (path + old bytes + new bytes), not a pre-rendered
119
+ # string, so diff rendering stays the confirmer's job. {Terminal} shells
120
+ # to +diff+; a richer client renders the same {Change} its own way. +old+
121
+ # is the current bytes, or +nil+ for a new file.
122
+ Change = Data.define(:path, :old, :new)
123
+
124
+ # An approval carrying the text to act on: the human-authored (possibly
125
+ # edited) {Request#detail} when editable, else +detail+ verbatim.
126
+ Approved = Data.define(:new_request_detail)
127
+
128
+ # A plain "no", final for this action. It carries no text on purpose:
129
+ # the model sees only the observation, and any words after "declined"
130
+ # read as a hint to work around — every typed word is a {Redirected}.
131
+ # See +D_bare_rejected+.
132
+ Rejected = Data.define do
133
+ # The tool's answer to the model, telling it to stop:
134
+ #
135
+ # Rejected.new.observation('the write to a.txt').content
136
+ # # => "Error: user declined the write to a.txt. Don't retry it or reach the
137
+ # # same end another way; tell the user you stopped."
138
+ #
139
+ # @param action [String] what was declined, as a noun phrase
140
+ # @return [Pikuri::Tool::Result] an error result
141
+ def observation(action)
142
+ Pikuri::Tool::Result.error("user declined #{action}. Don't retry it or reach " \
143
+ 'the same end another way; tell the user you stopped.')
144
+ end
145
+ end
146
+
147
+ # A decline carrying the words the human typed — a different way, or why
148
+ # not. The model follows them, and may propose again.
149
+ Redirected = Data.define(:message) do
150
+ # The tool's answer to the model, quoting the human — deliberately not
151
+ # an error, which would read as a failure to recover from:
152
+ #
153
+ # Redirected.new(message: 'use vim').observation('the write to a.txt').content
154
+ # # => "The user declined the write to a.txt and said: use vim"
155
+ #
156
+ # @param action [String] what was declined, as a noun phrase
157
+ # @return [Pikuri::Tool::Result]
158
+ def observation(action)
159
+ Pikuri::Tool::Result.new(content: "The user declined #{action} and said: #{message}",
160
+ summary: 'Redirected by the user')
161
+ end
162
+ end
163
+
164
+ # @param request [Request] semantic content composed by the calling
165
+ # tool. The confirmer renders it (escaping for its medium), poses
166
+ # the question, and parses the answer.
167
+ # @param cancellable [Pikuri::Agent::Control::Cancellable] the asking
168
+ # turn's token. Per call, never per confirmer: one confirmer serves
169
+ # many agents, each with its own.
170
+ # @return [Approved, Rejected, Redirected]
70
171
  # @raise [NotImplementedError] in the abstract base
71
- def confirm?(request:)
72
- raise NotImplementedError, "#{self.class}#confirm? must be implemented"
172
+ # @raise [Pikuri::Agent::Control::Cancellable::Cancelled] when the turn
173
+ # is cancelled while the question waits — see "Cancelling a parked
174
+ # ask" above
175
+ def ask(request:, cancellable:)
176
+ raise NotImplementedError, "#{self.class}#ask must be implemented"
73
177
  end
74
178
 
75
- # Stdin/stdout implementation. Renders the request as up to several
76
- # lines (a leading +puts+ guarantees separation from any streamed
77
- # output the +Terminal+ listener may have produced just above):
78
- #
79
- # 1. a bold-yellow warning block — one line per
80
- # {Pikuri::Sanitizer::Warning} — shown only when the sanitizer
81
- # flagged something suspicious in the question or detail
82
- # 2. the question, bold
83
- # 3. the detail, dim — omitted when +nil+
84
- # 4. the +(y/n)?+ cue
179
+ # Whether {#ask} can actually stop and wait for a person — the posture
180
+ # {Pikuri::Trifecta} reads when deciding whether a gated tool reaches the
181
+ # approver seat rather than counting as autonomous egress.
85
182
  #
86
- # Both question and detail pass through {Pikuri::Sanitizer}, which
87
- # neutralizes control bytes — without it, a model could craft a
88
- # command or description containing +"\rrm -rf ~/"+ that visually
89
- # overwrites the echoed line after the user has already read it —
90
- # and reports *why* it was unsafe so the user reads the warning
91
- # before answering. Colors come from Rainbow (already in the
92
- # dependency closure via pikuri-core), which self-disables on
93
- # non-TTY output; the bold-yellow warning rendering is this
94
- # terminal chrome's call, not the sanitizer's (the +Warning+
95
- # carries plain text only).
183
+ # +true+ on the base class: a confirmer exists to ask, so a subclass that
184
+ # doesn't must say so, and one that forgets is credited with a gate it
185
+ # does not have only if it also forgets to be {AutoApprove}. Override to
186
+ # +false+ for any request-independent auto-answer.
96
187
  #
97
- # Then reads one line from +$stdin+ and parses it strictly:
188
+ # This is what makes +--no-confirm+ re-harden a wiring's verdict on its
189
+ # own, with nothing in the detector special-casing the flag.
98
190
  #
99
- # * +"y"+ / +"yes"+ (case-insensitive, stripped) → +true+
100
- # * +"n"+ / +"no"+ → +false+
101
- # * EOF / Ctrl+D (+gets+ returns +nil+) → +false+, deliberate abort
102
- # * anything else (blank, typo, +"maybe"+) → re-prompt with a short
103
- # "Please answer y or n: " line and loop
104
- #
105
- # No retry cap; EOF eventually breaks adversarial input.
106
- class Terminal < Confirmer
107
- # @param request [Request]
108
- # @return [Boolean]
109
- def confirm?(request:)
110
- question = Pikuri::Sanitizer.sanitize(request.question)
111
- detail = request.detail ? Pikuri::Sanitizer.sanitize(request.detail) : nil
112
- warnings = question.warnings + (detail ? detail.warnings : [])
113
-
114
- puts
115
- unless warnings.empty?
116
- puts Rainbow('⚠ Suspicious content detected — read carefully before approving:').yellow.bold
117
- warnings.each { |w| puts Rainbow(" ! #{w.explanation}").yellow }
118
- end
119
- puts Rainbow(question.text).bold
120
- puts Rainbow(detail.text).dimgray if detail
121
- puts '(y/n)?'
122
- $stdout.flush
123
- loop do
124
- line = $stdin.gets
125
- return false if line.nil?
191
+ # @return [Boolean]
192
+ def blocks_on_human? = true
126
193
 
127
- answer = line.strip.downcase
128
- return true if answer == 'y' || answer == 'yes'
129
- return false if answer == 'n' || answer == 'no'
130
-
131
- print 'Please answer y or n: '
132
- $stdout.flush
133
- end
134
- end
135
- end
136
-
137
- # Approves everything. Used by +bin/pikuri-code --yolo+ (docker /
138
- # dev-container mode) and by tool specs that don't want to
139
- # coordinate stdin. The name +AUTO_APPROVE+ matches the public
140
- # constant {AUTO_APPROVE}.
194
+ # Approves everything unedited — the headless "opted out of dialogs"
195
+ # stance. Request-independent, so it classifies nothing and stays a
196
+ # legitimate Confirmer. Used by hosts' yolo modes and specs that don't want to coordinate stdin.
141
197
  class AutoApprove < Confirmer
142
- # @param request [Request] ignored
143
- # @return [true]
144
- def confirm?(request:)
145
- true
198
+ # @param request [Request]
199
+ # @param cancellable [Pikuri::Agent::Control::Cancellable] unused —
200
+ # nothing waits
201
+ # @return [Approved] always, carrying +detail+ unchanged
202
+ def ask(request:, cancellable:)
203
+ Approved.new(new_request_detail: request.detail)
146
204
  end
147
- end
148
205
 
149
- # Shared singleton instance of {Terminal}. Stateless; reusable
150
- # across tools and sub-agents.
151
- TERMINAL = Terminal.new
206
+ # @return [Boolean] +false+ — nobody is asked, so a tool gated by this
207
+ # confirmer holds autonomous egress however human-gated its wiring
208
+ # looks on paper
209
+ def blocks_on_human? = false
210
+ end
152
211
 
153
- # Shared singleton instance of {AutoApprove}.
212
+ # Shared stateless {AutoApprove} singleton, reusable across tools,
213
+ # sub-agents, and hosts' yolo modes. (No +TERMINAL+ singleton: {Terminal}
214
+ # is a demo chrome, and real front-ends bring their own.)
154
215
  AUTO_APPROVE = AutoApprove.new
155
216
  end
156
217
  end