返回 DeepSeek-Reasonix
extensions_test.go
根目录 / internal / agent / extensions_test.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "strings"
8 "sync"
9 "testing"
10 "time"
11
12 "reasonix/internal/event"
13 "reasonix/internal/extension"
14 "reasonix/internal/extension/dispatch"
15 "reasonix/internal/extension/protocol"
16 "reasonix/internal/provider"
17 "reasonix/internal/tool"
18 )
19
20 // Stage 6b2 agent-loop wiring tests. The dispatcher under test is real; only
21 // its sidecar client is faked, so every assertion exercises the actual
22 // dispatch ruling logic (chain walk, strict replacement decode, error
23 // policy). Each intercept point is covered for: continue (no-op), block,
24 // replace (the substituted value is what the host uses), a required
25 // extension's failure (operation fails), and an optional extension's failure
26 // (warn + continue).
27
28 const extTestPlugin = "fake"
29
30 type extRecordedCall struct {
31 event protocol.InterceptEvent
32 payload json.RawMessage
33 }
34
35 // fakeDispatchClient is a scriptable dispatch.Client recording every call.
36 // A nil interceptFn answers continue.
37 type fakeDispatchClient struct {
38 mu sync.Mutex
39 interceptFn func(event protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error)
40 intercepts []extRecordedCall
41 notifies []extRecordedCall
42 }
43
44 func (f *fakeDispatchClient) Intercept(_ context.Context, event protocol.InterceptEvent, payload json.RawMessage, _ time.Duration) (protocol.InterceptResult, error) {
45 f.mu.Lock()
46 f.intercepts = append(f.intercepts, extRecordedCall{event: event, payload: append(json.RawMessage(nil), payload...)})
47 fn := f.interceptFn
48 f.mu.Unlock()
49 if fn == nil {
50 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
51 }
52 return fn(event, payload)
53 }
54
55 func (f *fakeDispatchClient) TryNotifyEvent(event protocol.InterceptEvent, payload json.RawMessage) error {
56 f.mu.Lock()
57 defer f.mu.Unlock()
58 f.notifies = append(f.notifies, extRecordedCall{event: event, payload: append(json.RawMessage(nil), payload...)})
59 return nil
60 }
61
62 func (f *fakeDispatchClient) notifyCountFor(event protocol.InterceptEvent) int {
63 f.mu.Lock()
64 defer f.mu.Unlock()
65 n := 0
66 for _, call := range f.notifies {
67 if call.event == event {
68 n++
69 }
70 }
71 return n
72 }
73
74 // interceptPayloadFor returns the decoded payload of the first intercept call
75 // for event, for assertions about what the host sent.
76 func (f *fakeDispatchClient) interceptPayloadFor(event protocol.InterceptEvent, out any) bool {
77 f.mu.Lock()
78 defer f.mu.Unlock()
79 for _, call := range f.intercepts {
80 if call.event == event {
81 return json.Unmarshal(call.payload, out) == nil
82 }
83 }
84 return false
85 }
86
87 // extWarnRecorder collects dispatcher warnings (optional-extension failures).
88 type extWarnRecorder struct {
89 mu sync.Mutex
90 msgs []string
91 }
92
93 func (w *extWarnRecorder) warn(msg string) {
94 w.mu.Lock()
95 defer w.mu.Unlock()
96 w.msgs = append(w.msgs, msg)
97 }
98
99 func (w *extWarnRecorder) contains(substr string) bool {
100 w.mu.Lock()
101 defer w.mu.Unlock()
102 for _, msg := range w.msgs {
103 if strings.Contains(msg, substr) {
104 return true
105 }
106 }
107 return false
108 }
109
110 // newExtDispatcher builds a dispatcher whose chain lists the fake plugin at
111 // every given point. required=true marks the plugin required-class (manifest
112 // required:true), so its failures fail the operation.
113 func newExtDispatcher(client dispatch.Client, required bool, warn func(string), points ...extension.InterceptorPoint) *dispatch.Dispatcher {
114 return newExtSlotDispatcher(client, required, warn, points, nil)
115 }
116
117 // newExtSlotDispatcher builds a dispatcher with the fake plugin chained at
118 // the given points and owning the given replacement slots (slot → plugin ID).
119 // A slot owner is required-class by definition, independent of required.
120 func newExtSlotDispatcher(client dispatch.Client, required bool, warn func(string), points []extension.InterceptorPoint, slots map[extension.Slot]string) *dispatch.Dispatcher {
121 chain := map[extension.InterceptorPoint][]extension.Contribution{}
122 for _, point := range points {
123 chain[point] = []extension.Contribution{{
124 Kind: extension.KindInterceptor,
125 ID: string(point),
126 Source: extension.ContributionSource{Scope: extension.ScopePlugin, PluginID: extTestPlugin},
127 }}
128 }
129 replacements := map[extension.Slot]extension.ContributionSource{}
130 for slot, plugin := range slots {
131 replacements[slot] = extension.ContributionSource{Scope: extension.ScopePlugin, PluginID: plugin}
132 }
133 requiredSet := map[string]bool{}
134 if required {
135 requiredSet[extTestPlugin] = true
136 }
137 return dispatch.New(chain, replacements, func(string) dispatch.Client { return client }, requiredSet, dispatch.Options{Warn: warn})
138 }
139
140 // replaceWith marshals v as the replacement payload of a replace ruling.
141 func replaceWith(t *testing.T, v any) protocol.InterceptResult {
142 t.Helper()
143 raw, err := json.Marshal(v)
144 if err != nil {
145 t.Fatalf("marshal replacement: %v", err)
146 }
147 return protocol.InterceptResult{Decision: protocol.DecisionReplace, Replacement: raw}
148 }
149
150 func blockWith(reason string) protocol.InterceptResult {
151 return protocol.InterceptResult{Decision: protocol.DecisionBlock, Reason: reason}
152 }
153
154 // recordingTool is a Tool stand-in that records the args it executed with.
155 type recordingTool struct {
156 name string
157 readOnly bool
158 execs int
159 gotArgs string
160 }
161
162 func (r *recordingTool) Name() string { return r.name }
163 func (r *recordingTool) Description() string { return "" }
164 func (r *recordingTool) Schema() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
165 func (r *recordingTool) ReadOnly() bool { return r.readOnly }
166 func (r *recordingTool) Execute(_ context.Context, args json.RawMessage) (string, error) {
167 r.execs++
168 r.gotArgs = string(args)
169 return r.name + " ok", nil
170 }
171
172 // sessionContents flattens the session's message contents for substring
173 // assertions.
174 func sessionContents(s *Session) string {
175 var b strings.Builder
176 for _, m := range s.Messages {
177 b.WriteString(m.Content)
178 b.WriteByte('\n')
179 }
180 return b.String()
181 }
182
183 func assistantMessages(s *Session) []provider.Message {
184 var out []provider.Message
185 for _, m := range s.Messages {
186 if m.Role == provider.RoleAssistant {
187 out = append(out, m)
188 }
189 }
190 return out
191 }
192
193 func requestContents(req provider.Request) string {
194 var b strings.Builder
195 for _, m := range req.Messages {
196 b.WriteString(string(m.Role))
197 b.WriteByte(':')
198 b.WriteString(m.Content)
199 b.WriteByte('\n')
200 }
201 return b.String()
202 }
203
204 // agent.before_start
205
206 func TestAgentBeforeStartContinue(t *testing.T) {
207 client := &fakeDispatchClient{}
208 d := newExtDispatcher(client, true, nil, extension.PointAgentBeforeStart)
209 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
210 {Type: provider.ChunkText, Text: "hi"}, {Type: provider.ChunkDone},
211 }}
212 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
213 if err := a.Run(context.Background(), "hello"); err != nil {
214 t.Fatalf("Run: %v", err)
215 }
216 if len(mp.requests) != 1 {
217 t.Fatalf("requests = %d, want 1", len(mp.requests))
218 }
219 var payload dispatch.AgentStartPayload
220 if !client.interceptPayloadFor(protocol.EventAgentBeforeStart, &payload) {
221 t.Fatal("agent.before_start intercept did not fire")
222 }
223 if payload.Model != "p" || payload.ToolCount != 0 {
224 t.Fatalf("payload = %+v, want model p and 0 tools", payload)
225 }
226 if n := client.notifyCountFor(protocol.EventAgentBeforeStart); n != 1 {
227 t.Fatalf("before_start events = %d, want 1", n)
228 }
229 }
230
231 func TestAgentBeforeStartBlock(t *testing.T) {
232 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
233 if ev == protocol.EventAgentBeforeStart {
234 return blockWith("no runs today"), nil
235 }
236 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
237 }}
238 d := newExtDispatcher(client, true, nil, extension.PointAgentBeforeStart)
239 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
240 {Type: provider.ChunkText, Text: "hi"}, {Type: provider.ChunkDone},
241 }}
242 sess := NewSession("sys")
243 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
244 err := a.Run(context.Background(), "hello")
245 if err == nil || !strings.Contains(err.Error(), "no runs today") {
246 t.Fatalf("Run err = %v, want the block reason", err)
247 }
248 if len(mp.requests) != 0 {
249 t.Fatalf("blocked run still hit the provider: %d requests", len(mp.requests))
250 }
251 if len(sess.Messages) != 1 {
252 t.Fatalf("session = %d messages, want only the system message (turn never appended)", len(sess.Messages))
253 }
254 }
255
256 func TestAgentBeforeStartReplace(t *testing.T) {
257 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
258 if ev == protocol.EventAgentBeforeStart {
259 return replaceWith(t, dispatch.AgentStartPayload{Model: "other", ToolCount: 3, SessionID: "s1"}), nil
260 }
261 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
262 }}
263 d := newExtDispatcher(client, true, nil, extension.PointAgentBeforeStart)
264 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
265 {Type: provider.ChunkText, Text: "hi"}, {Type: provider.ChunkDone},
266 }}
267 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
268 // The payload is informational: a replacement validates but does not alter
269 // the run.
270 if err := a.Run(context.Background(), "hello"); err != nil {
271 t.Fatalf("Run: %v", err)
272 }
273 }
274
275 func TestAgentBeforeStartFailurePolicy(t *testing.T) {
276 boom := errors.New("sidecar timeout")
277 t.Run("required fails the run", func(t *testing.T) {
278 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
279 return protocol.InterceptResult{}, boom
280 }}
281 d := newExtDispatcher(client, true, nil, extension.PointAgentBeforeStart)
282 mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}}
283 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
284 err := a.Run(context.Background(), "hello")
285 if err == nil || !strings.Contains(err.Error(), "extension fake failed at agent.before_start") {
286 t.Fatalf("Run err = %v, want the required failure", err)
287 }
288 if len(mp.requests) != 0 {
289 t.Fatalf("failed run still hit the provider: %d requests", len(mp.requests))
290 }
291 })
292 t.Run("optional warns and proceeds", func(t *testing.T) {
293 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
294 return protocol.InterceptResult{}, boom
295 }}
296 warns := &extWarnRecorder{}
297 d := newExtDispatcher(client, false, warns.warn, extension.PointAgentBeforeStart)
298 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
299 {Type: provider.ChunkText, Text: "hi"}, {Type: provider.ChunkDone},
300 }}
301 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
302 if err := a.Run(context.Background(), "hello"); err != nil {
303 t.Fatalf("Run: %v", err)
304 }
305 if !warns.contains("skipping this optional extension") {
306 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
307 }
308 })
309 }
310
311 func TestSetExtensionsInstallsAfterConstruction(t *testing.T) {
312 client := &fakeDispatchClient{}
313 d := newExtDispatcher(client, true, nil, extension.PointAgentBeforeStart)
314 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
315 {Type: provider.ChunkText, Text: "hi"}, {Type: provider.ChunkDone},
316 }}
317 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{}, event.Discard)
318 a.SetExtensions(d)
319 if err := a.Run(context.Background(), "hello"); err != nil {
320 t.Fatalf("Run: %v", err)
321 }
322 var payload dispatch.AgentStartPayload
323 if !client.interceptPayloadFor(protocol.EventAgentBeforeStart, &payload) {
324 t.Fatal("SetExtensions-installed dispatcher did not fire")
325 }
326 }
327
328 // context.prepare
329
330 func TestContextPrepareReplaceIsEphemeral(t *testing.T) {
331 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
332 if ev == protocol.EventContextPrepare {
333 return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{
334 {Role: protocol.ProviderRoleSystem, Content: "REPLACED SYS"},
335 {Role: protocol.ProviderRoleUser, Content: "REPLACED USER"},
336 }}), nil
337 }
338 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
339 }}
340 d := newExtDispatcher(client, true, nil, extension.PointContextPrepare)
341 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
342 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
343 }}
344 sess := NewSession("sys")
345 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
346 if err := a.Run(context.Background(), "hello"); err != nil {
347 t.Fatalf("Run: %v", err)
348 }
349 if len(mp.requests) != 1 {
350 t.Fatalf("requests = %d, want 1", len(mp.requests))
351 }
352 got := requestContents(mp.requests[0])
353 if !strings.Contains(got, "REPLACED USER") || strings.Contains(got, "hello") {
354 t.Fatalf("request messages = %q, want the replacement only", got)
355 }
356 // Ephemerality: the session log keeps the original history untouched.
357 sc := sessionContents(sess)
358 if strings.Contains(sc, "REPLACED USER") || strings.Contains(sc, "REPLACED SYS") {
359 t.Fatalf("session mutated by context.prepare replacement:\n%s", sc)
360 }
361 if !strings.Contains(sc, "hello") {
362 t.Fatalf("session lost the user turn:\n%s", sc)
363 }
364 }
365
366 func TestContextPrepareBlock(t *testing.T) {
367 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
368 if ev == protocol.EventContextPrepare {
369 return blockWith("context denied"), nil
370 }
371 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
372 }}
373 d := newExtDispatcher(client, true, nil, extension.PointContextPrepare)
374 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
375 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
376 }}
377 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
378 err := a.Run(context.Background(), "hello")
379 if err == nil || !strings.Contains(err.Error(), "context denied") {
380 t.Fatalf("Run err = %v, want the block reason", err)
381 }
382 if len(mp.requests) != 0 {
383 t.Fatalf("blocked request still hit the provider: %d requests", len(mp.requests))
384 }
385 }
386
387 func TestContextPrepareFailurePolicy(t *testing.T) {
388 boom := errors.New("sidecar timeout")
389 t.Run("required fails the turn", func(t *testing.T) {
390 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
391 return protocol.InterceptResult{}, boom
392 }}
393 d := newExtDispatcher(client, true, nil, extension.PointContextPrepare)
394 mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}}
395 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
396 err := a.Run(context.Background(), "hello")
397 if err == nil || !strings.Contains(err.Error(), "extension fake failed at context.prepare") {
398 t.Fatalf("Run err = %v, want the required failure", err)
399 }
400 })
401 t.Run("optional warns and proceeds", func(t *testing.T) {
402 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
403 return protocol.InterceptResult{}, boom
404 }}
405 warns := &extWarnRecorder{}
406 d := newExtDispatcher(client, false, warns.warn, extension.PointContextPrepare)
407 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
408 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
409 }}
410 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
411 if err := a.Run(context.Background(), "hello"); err != nil {
412 t.Fatalf("Run: %v", err)
413 }
414 if !warns.contains("skipping this optional extension") {
415 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
416 }
417 })
418 }
419
420 // provider.request
421
422 func TestProviderRequestReplace(t *testing.T) {
423 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
424 if ev == protocol.EventProviderRequest {
425 var in dispatch.ProviderRequestPayload
426 if err := json.Unmarshal(payload, &in); err != nil {
427 return protocol.InterceptResult{}, err
428 }
429 in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{
430 Role: protocol.ProviderRoleUser, Content: "EXTENSION INJECTED",
431 })
432 return replaceWith(t, in), nil
433 }
434 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
435 }}
436 d := newExtDispatcher(client, true, nil, extension.PointProviderRequest)
437 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
438 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
439 }}
440 sess := NewSession("sys")
441 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
442 if err := a.Run(context.Background(), "hello"); err != nil {
443 t.Fatalf("Run: %v", err)
444 }
445 if got := requestContents(mp.requests[0]); !strings.Contains(got, "EXTENSION INJECTED") {
446 t.Fatalf("request = %q, want the injected message", got)
447 }
448 if sc := sessionContents(sess); strings.Contains(sc, "EXTENSION INJECTED") {
449 t.Fatalf("session mutated by provider.request replacement:\n%s", sc)
450 }
451 if n := client.notifyCountFor(protocol.EventProviderRequest); n != 1 {
452 t.Fatalf("provider.request events = %d, want 1", n)
453 }
454 }
455
456 func TestProviderRequestBlock(t *testing.T) {
457 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
458 if ev == protocol.EventProviderRequest {
459 return blockWith("request denied"), nil
460 }
461 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
462 }}
463 d := newExtDispatcher(client, true, nil, extension.PointProviderRequest)
464 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
465 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
466 }}
467 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
468 err := a.Run(context.Background(), "hello")
469 if err == nil || !strings.Contains(err.Error(), "request denied") {
470 t.Fatalf("Run err = %v, want the block reason", err)
471 }
472 if len(mp.requests) != 0 {
473 t.Fatalf("blocked request still hit the provider: %d requests", len(mp.requests))
474 }
475 }
476
477 func TestProviderRequestFailurePolicy(t *testing.T) {
478 boom := errors.New("sidecar timeout")
479 t.Run("required fails the turn", func(t *testing.T) {
480 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
481 return protocol.InterceptResult{}, boom
482 }}
483 d := newExtDispatcher(client, true, nil, extension.PointProviderRequest)
484 mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}}
485 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
486 err := a.Run(context.Background(), "hello")
487 if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.request") {
488 t.Fatalf("Run err = %v, want the required failure", err)
489 }
490 })
491 t.Run("optional warns and proceeds", func(t *testing.T) {
492 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
493 return protocol.InterceptResult{}, boom
494 }}
495 warns := &extWarnRecorder{}
496 d := newExtDispatcher(client, false, warns.warn, extension.PointProviderRequest)
497 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
498 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
499 }}
500 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
501 if err := a.Run(context.Background(), "hello"); err != nil {
502 t.Fatalf("Run: %v", err)
503 }
504 if !warns.contains("skipping this optional extension") {
505 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
506 }
507 })
508 }
509
510 // TestProviderRequestReplacementCacheEphemerality is the cache contract: a
511 // replacement shapes only the request it ruled on. Two identical agents — one
512 // with an extension that injects a message into run 1's request only, one
513 // without — must send byte-identical requests on run 2.
514 func TestProviderRequestReplacementCacheEphemerality(t *testing.T) {
515 streams := func() [][]provider.Chunk {
516 return [][]provider.Chunk{
517 {{Type: provider.ChunkText, Text: "one"}, {Type: provider.ChunkDone}},
518 {{Type: provider.ChunkText, Text: "two"}, {Type: provider.ChunkDone}},
519 }
520 }
521 client := &fakeDispatchClient{}
522 replaced := 0
523 client.interceptFn = func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
524 if ev == protocol.EventProviderRequest && replaced == 0 {
525 replaced++
526 var in dispatch.ProviderRequestPayload
527 if err := json.Unmarshal(payload, &in); err != nil {
528 return protocol.InterceptResult{}, err
529 }
530 in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{
531 Role: protocol.ProviderRoleUser, Content: "RUN-1 ONLY",
532 })
533 return replaceWith(t, in), nil
534 }
535 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
536 }
537 d := newExtDispatcher(client, true, nil, extension.PointProviderRequest)
538
539 withExt := &mockProvider{name: "p", streams: streams()}
540 a := New(withExt, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
541 for _, input := range []string{"first", "second"} {
542 if err := a.Run(context.Background(), input); err != nil {
543 t.Fatalf("Run(%q): %v", input, err)
544 }
545 }
546 if len(withExt.requests) != 2 {
547 t.Fatalf("requests = %d, want 2", len(withExt.requests))
548 }
549 if got := requestContents(withExt.requests[0]); !strings.Contains(got, "RUN-1 ONLY") {
550 t.Fatalf("run 1 request = %q, want the injected message", got)
551 }
552 if got := requestContents(withExt.requests[1]); strings.Contains(got, "RUN-1 ONLY") {
553 t.Fatalf("run 2 request leaked the run-1 replacement:\n%s", got)
554 }
555
556 baseline := &mockProvider{name: "p", streams: streams()}
557 b := New(baseline, tool.NewRegistry(), NewSession("sys"), Options{}, event.Discard)
558 for _, input := range []string{"first", "second"} {
559 if err := b.Run(context.Background(), input); err != nil {
560 t.Fatalf("baseline Run(%q): %v", input, err)
561 }
562 }
563 gotRun2 := requestContents(withExt.requests[1])
564 wantRun2 := requestContents(baseline.requests[1])
565 if gotRun2 != wantRun2 {
566 t.Fatalf("run 2 request differs from the no-extension baseline:\ngot:\n%s\nwant:\n%s", gotRun2, wantRun2)
567 }
568 }
569
570 // provider.response
571
572 func TestProviderResponseReplaceIsTranscript(t *testing.T) {
573 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
574 if ev == protocol.EventProviderResponse {
575 return replaceWith(t, dispatch.ProviderResponsePayload{Text: "REPLACED ANSWER", Reasoning: "replaced reasoning"}), nil
576 }
577 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
578 }}
579 d := newExtDispatcher(client, true, nil, extension.PointProviderResponse)
580 mp := &mockProvider{name: "p", streams: [][]provider.Chunk{
581 {
582 {Type: provider.ChunkReasoning, Text: "ORIGINAL REASONING", ReasoningID: "rs_original", ReasoningStatus: "completed"},
583 {Type: provider.ChunkText, Text: "ORIGINAL ANSWER"},
584 {Type: provider.ChunkDone},
585 },
586 {{Type: provider.ChunkText, Text: "second"}, {Type: provider.ChunkDone}},
587 }}
588 sess := NewSession("sys")
589 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
590 if err := a.Run(context.Background(), "one"); err != nil {
591 t.Fatalf("Run one: %v", err)
592 }
593 assistants := assistantMessages(sess)
594 if len(assistants) != 1 || assistants[0].Content != "REPLACED ANSWER" {
595 t.Fatalf("assistant turn = %+v, want the replaced answer persisted", assistants)
596 }
597 if assistants[0].ReasoningContent != "replaced reasoning" {
598 t.Fatalf("assistant reasoning = %q, want the replaced reasoning", assistants[0].ReasoningContent)
599 }
600 if assistants[0].ReasoningID != "" || assistants[0].ReasoningStatus != "" {
601 t.Fatalf("replaced reasoning retained provider metadata = (%q, %q)", assistants[0].ReasoningID, assistants[0].ReasoningStatus)
602 }
603 // The transcript contract: the next request replays the replaced turn,
604 // never the provider's original text.
605 if err := a.Run(context.Background(), "two"); err != nil {
606 t.Fatalf("Run two: %v", err)
607 }
608 got := requestContents(mp.requests[1])
609 if !strings.Contains(got, "REPLACED ANSWER") {
610 t.Fatalf("run 2 request = %q, want the replaced turn replayed", got)
611 }
612 if strings.Contains(got, "ORIGINAL ANSWER") {
613 t.Fatalf("run 2 request leaked the original provider text:\n%s", got)
614 }
615 }
616
617 func TestProviderResponseBlock(t *testing.T) {
618 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
619 if ev == protocol.EventProviderResponse {
620 return blockWith("response denied"), nil
621 }
622 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
623 }}
624 d := newExtDispatcher(client, true, nil, extension.PointProviderResponse)
625 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
626 {Type: provider.ChunkText, Text: "ORIGINAL ANSWER"}, {Type: provider.ChunkDone},
627 }}
628 sess := NewSession("sys")
629 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
630 err := a.Run(context.Background(), "one")
631 if err == nil || !strings.Contains(err.Error(), "response denied") {
632 t.Fatalf("Run err = %v, want the block reason", err)
633 }
634 if n := len(assistantMessages(sess)); n != 0 {
635 t.Fatalf("blocked response persisted %d assistant turns, want 0", n)
636 }
637 }
638
639 func TestProviderResponseFailurePolicy(t *testing.T) {
640 boom := errors.New("sidecar timeout")
641 t.Run("required fails the turn", func(t *testing.T) {
642 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
643 return protocol.InterceptResult{}, boom
644 }}
645 d := newExtDispatcher(client, true, nil, extension.PointProviderResponse)
646 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
647 {Type: provider.ChunkText, Text: "ORIGINAL ANSWER"}, {Type: provider.ChunkDone},
648 }}
649 sess := NewSession("sys")
650 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
651 err := a.Run(context.Background(), "one")
652 if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.response") {
653 t.Fatalf("Run err = %v, want the required failure", err)
654 }
655 if n := len(assistantMessages(sess)); n != 0 {
656 t.Fatalf("failed response persisted %d assistant turns, want 0", n)
657 }
658 })
659 t.Run("optional warns and persists the original", func(t *testing.T) {
660 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
661 return protocol.InterceptResult{}, boom
662 }}
663 warns := &extWarnRecorder{}
664 d := newExtDispatcher(client, false, warns.warn, extension.PointProviderResponse)
665 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
666 {Type: provider.ChunkText, Text: "ORIGINAL ANSWER"}, {Type: provider.ChunkDone},
667 }}
668 sess := NewSession("sys")
669 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
670 if err := a.Run(context.Background(), "one"); err != nil {
671 t.Fatalf("Run: %v", err)
672 }
673 assistants := assistantMessages(sess)
674 if len(assistants) != 1 || assistants[0].Content != "ORIGINAL ANSWER" {
675 t.Fatalf("assistant turn = %+v, want the original answer persisted", assistants)
676 }
677 if !warns.contains("skipping this optional extension") {
678 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
679 }
680 })
681 }
682
683 // tool.before
684
685 func TestToolBeforeContinue(t *testing.T) {
686 client := &fakeDispatchClient{}
687 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
688 rec := &recordingTool{name: "read_file", readOnly: true}
689 reg := tool.NewRegistry()
690 reg.Add(rec)
691 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
692 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
693 if out.errMsg != "" || !strings.Contains(out.output, "read_file ok") {
694 t.Fatalf("outcome = %+v, want the tool to run", out)
695 }
696 if rec.gotArgs != `{"path":"/x"}` {
697 t.Fatalf("tool args = %q, want the original call args", rec.gotArgs)
698 }
699 if n := client.notifyCountFor(protocol.EventToolBefore); n != 1 {
700 t.Fatalf("tool.before events = %d, want 1", n)
701 }
702 }
703
704 func TestToolBeforeBlock(t *testing.T) {
705 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
706 if ev == protocol.EventToolBefore {
707 return blockWith("tool denied"), nil
708 }
709 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
710 }}
711 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
712 rec := &recordingTool{name: "read_file", readOnly: true}
713 reg := tool.NewRegistry()
714 reg.Add(rec)
715 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
716 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
717 if !out.blocked || out.output != "blocked: tool denied" {
718 t.Fatalf("outcome = %+v, want a blocked tool result with the reason", out)
719 }
720 if rec.execs != 0 {
721 t.Fatalf("blocked tool executed %d times", rec.execs)
722 }
723 }
724
725 func TestToolBeforeReplaceArgs(t *testing.T) {
726 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
727 if ev == protocol.EventToolBefore {
728 return replaceWith(t, dispatch.ToolBeforePayload{Name: "read_file", Arguments: `{"path":"/substituted"}`}), nil
729 }
730 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
731 }}
732 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
733 rec := &recordingTool{name: "read_file", readOnly: true}
734 reg := tool.NewRegistry()
735 reg.Add(rec)
736 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
737 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/original"}`})
738 if out.errMsg != "" {
739 t.Fatalf("outcome = %+v, want success", out)
740 }
741 if rec.gotArgs != `{"path":"/substituted"}` {
742 t.Fatalf("tool args = %q, want the extension-substituted args", rec.gotArgs)
743 }
744 }
745
746 func TestToolBeforeReplaceName(t *testing.T) {
747 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
748 if ev == protocol.EventToolBefore {
749 return replaceWith(t, dispatch.ToolBeforePayload{Name: "grep", Arguments: `{"pattern":"x"}`}), nil
750 }
751 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
752 }}
753 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
754 orig := &recordingTool{name: "read_file", readOnly: true}
755 substituted := &recordingTool{name: "grep", readOnly: true}
756 reg := tool.NewRegistry()
757 reg.Add(orig)
758 reg.Add(substituted)
759 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
760 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
761 if out.errMsg != "" || !strings.Contains(out.output, "grep ok") {
762 t.Fatalf("outcome = %+v, want the substituted tool to run", out)
763 }
764 if orig.execs != 0 || substituted.execs != 1 {
765 t.Fatalf("execs = %d/%d, want the substituted tool only", orig.execs, substituted.execs)
766 }
767 }
768
769 func TestToolBeforeInvalidReplacements(t *testing.T) {
770 cases := []struct {
771 name string
772 replacement dispatch.ToolBeforePayload
773 want string
774 }{
775 {"empty arguments", dispatch.ToolBeforePayload{Name: "read_file", Arguments: ""}, "arguments must decode as a JSON object"},
776 {"unresolvable name", dispatch.ToolBeforePayload{Name: "no_such_tool", Arguments: `{}`}, "does not resolve"},
777 }
778 for _, tc := range cases {
779 t.Run(tc.name, func(t *testing.T) {
780 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
781 if ev == protocol.EventToolBefore {
782 return replaceWith(t, tc.replacement), nil
783 }
784 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
785 }}
786 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
787 rec := &recordingTool{name: "read_file", readOnly: true}
788 reg := tool.NewRegistry()
789 reg.Add(rec)
790 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
791 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
792 if out.errMsg == "" || !strings.Contains(out.output, "violated the intercept contract") || !strings.Contains(out.output, tc.want) {
793 t.Fatalf("outcome = %+v, want a contract-violation error result containing %q", out, tc.want)
794 }
795 if rec.execs != 0 {
796 t.Fatalf("invalid replacement still executed the tool")
797 }
798 })
799 }
800 // A replacement that fails the point's DTO (arguments not a JSON object)
801 // is a dispatch-level violation: for a required extension the call fails.
802 t.Run("DTO violation", func(t *testing.T) {
803 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
804 if ev == protocol.EventToolBefore {
805 return protocol.InterceptResult{Decision: protocol.DecisionReplace, Replacement: json.RawMessage(`{"name":"read_file","arguments":"[1,2]"}`)}, nil
806 }
807 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
808 }}
809 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
810 rec := &recordingTool{name: "read_file", readOnly: true}
811 reg := tool.NewRegistry()
812 reg.Add(rec)
813 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
814 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
815 if out.errMsg == "" || !strings.Contains(out.output, "violated the intercept contract") {
816 t.Fatalf("outcome = %+v, want a dispatch violation error result", out)
817 }
818 if rec.execs != 0 {
819 t.Fatal("DTO-violating replacement still executed the tool")
820 }
821 })
822 }
823
824 func TestToolBeforeFailurePolicy(t *testing.T) {
825 boom := errors.New("sidecar timeout")
826 t.Run("required fails the call", func(t *testing.T) {
827 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
828 return protocol.InterceptResult{}, boom
829 }}
830 d := newExtDispatcher(client, true, nil, extension.PointToolBefore)
831 rec := &recordingTool{name: "read_file", readOnly: true}
832 reg := tool.NewRegistry()
833 reg.Add(rec)
834 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
835 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
836 if out.errMsg == "" || !strings.Contains(out.output, "extension fake failed at tool.before") {
837 t.Fatalf("outcome = %+v, want the required failure as the tool result", out)
838 }
839 if rec.execs != 0 {
840 t.Fatal("failed extension still let the tool run")
841 }
842 })
843 t.Run("optional warns and runs", func(t *testing.T) {
844 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
845 return protocol.InterceptResult{}, boom
846 }}
847 warns := &extWarnRecorder{}
848 d := newExtDispatcher(client, false, warns.warn, extension.PointToolBefore)
849 rec := &recordingTool{name: "read_file", readOnly: true}
850 reg := tool.NewRegistry()
851 reg.Add(rec)
852 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
853 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
854 if out.errMsg != "" || rec.execs != 1 {
855 t.Fatalf("outcome = %+v execs = %d, want the tool to run", out, rec.execs)
856 }
857 if !warns.contains("skipping this optional extension") {
858 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
859 }
860 })
861 }
862
863 // permission.decision
864
865 func TestPermissionDecisionExtensionAllowOverridesHostDeny(t *testing.T) {
866 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
867 if ev == protocol.EventPermissionDecision {
868 var in dispatch.PermissionPayload
869 if err := json.Unmarshal(payload, &in); err != nil {
870 return protocol.InterceptResult{}, err
871 }
872 if in.HostDecision != "deny" {
873 t.Errorf("host decision = %q, want deny (host computes first)", in.HostDecision)
874 }
875 return protocol.InterceptResult{Decision: protocol.DecisionAllow}, nil
876 }
877 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
878 }}
879 d := newExtDispatcher(client, true, nil, extension.PointPermissionDecision)
880 rec := &recordingTool{name: "edit_file", readOnly: false}
881 reg := tool.NewRegistry()
882 reg.Add(rec)
883 gate := &stubGate{deny: map[string]bool{"edit_file": true}}
884 var events []event.Event
885 sink := event.FuncSink(func(e event.Event) { events = append(events, e) })
886 a := New(nil, reg, NewSession(""), Options{Gate: gate, Extensions: d}, sink)
887 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
888 if out.errMsg != "" || rec.execs != 1 {
889 t.Fatalf("outcome = %+v execs = %d, want the full-trust override to execute", out, rec.execs)
890 }
891 audit := false
892 for _, e := range events {
893 if e.Kind == event.Notice && strings.Contains(e.Text, "allowed the tool overriding the host deny") {
894 audit = true
895 }
896 }
897 if !audit {
898 t.Fatal("full-trust override produced no audit notice")
899 }
900 if n := client.notifyCountFor(protocol.EventPermissionDecision); n != 1 {
901 t.Fatalf("permission.decision events = %d, want 1", n)
902 }
903 }
904
905 func TestPermissionDecisionExtensionDenyOverridesHostAllow(t *testing.T) {
906 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
907 if ev == protocol.EventPermissionDecision {
908 return protocol.InterceptResult{Decision: protocol.DecisionDeny}, nil
909 }
910 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
911 }}
912 d := newExtDispatcher(client, true, nil, extension.PointPermissionDecision)
913 rec := &recordingTool{name: "edit_file", readOnly: false}
914 reg := tool.NewRegistry()
915 reg.Add(rec)
916 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
917 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
918 if !out.blocked || !strings.Contains(out.output, "denied by extension permission policy") {
919 t.Fatalf("outcome = %+v, want an extension denial", out)
920 }
921 if rec.execs != 0 {
922 t.Fatal("extension-denied tool executed")
923 }
924 }
925
926 func TestPermissionDecisionContinueKeepsHostDeny(t *testing.T) {
927 client := &fakeDispatchClient{}
928 d := newExtDispatcher(client, true, nil, extension.PointPermissionDecision)
929 rec := &recordingTool{name: "edit_file", readOnly: false}
930 reg := tool.NewRegistry()
931 reg.Add(rec)
932 gate := &stubGate{deny: map[string]bool{"edit_file": true}}
933 a := New(nil, reg, NewSession(""), Options{Gate: gate, Extensions: d}, event.Discard)
934 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
935 if !out.blocked || !strings.Contains(out.output, "denied by test policy") {
936 t.Fatalf("outcome = %+v, want the host denial to stand", out)
937 }
938 if rec.execs != 0 {
939 t.Fatal("host-denied tool executed")
940 }
941 }
942
943 func TestPermissionDecisionBlockAndFailure(t *testing.T) {
944 t.Run("block denies", func(t *testing.T) {
945 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
946 if ev == protocol.EventPermissionDecision {
947 return blockWith("policy says no"), nil
948 }
949 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
950 }}
951 d := newExtDispatcher(client, true, nil, extension.PointPermissionDecision)
952 rec := &recordingTool{name: "edit_file", readOnly: false}
953 reg := tool.NewRegistry()
954 reg.Add(rec)
955 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
956 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
957 if !out.blocked || !strings.Contains(out.output, "policy says no") {
958 t.Fatalf("outcome = %+v, want the block reason", out)
959 }
960 })
961 t.Run("required failure denies", func(t *testing.T) {
962 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
963 return protocol.InterceptResult{}, errors.New("sidecar timeout")
964 }}
965 d := newExtDispatcher(client, true, nil, extension.PointPermissionDecision)
966 rec := &recordingTool{name: "edit_file", readOnly: false}
967 reg := tool.NewRegistry()
968 reg.Add(rec)
969 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
970 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
971 if !out.blocked || !strings.Contains(out.output, "extension fake failed at permission.decision") {
972 t.Fatalf("outcome = %+v, want the required failure", out)
973 }
974 if rec.execs != 0 {
975 t.Fatal("failed extension still let the tool run")
976 }
977 })
978 t.Run("optional failure keeps the host allow", func(t *testing.T) {
979 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
980 return protocol.InterceptResult{}, errors.New("sidecar timeout")
981 }}
982 warns := &extWarnRecorder{}
983 d := newExtDispatcher(client, false, warns.warn, extension.PointPermissionDecision)
984 rec := &recordingTool{name: "edit_file", readOnly: false}
985 reg := tool.NewRegistry()
986 reg.Add(rec)
987 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
988 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
989 if out.errMsg != "" || rec.execs != 1 {
990 t.Fatalf("outcome = %+v execs = %d, want the host allow to stand", out, rec.execs)
991 }
992 if !warns.contains("skipping this optional extension") {
993 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
994 }
995 })
996 }
997
998 // tool.after
999
1000 func TestToolAfterReplaceResult(t *testing.T) {
1001 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1002 if ev == protocol.EventToolAfter {
1003 return replaceWith(t, dispatch.ToolAfterPayload{
1004 Name: "read_file", Arguments: `{"path":"/x"}`, Result: "EXTENSION RESULT",
1005 }), nil
1006 }
1007 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1008 }}
1009 d := newExtDispatcher(client, true, nil, extension.PointToolAfter)
1010 rec := &recordingTool{name: "read_file", readOnly: true}
1011 reg := tool.NewRegistry()
1012 reg.Add(rec)
1013 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
1014 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
1015 if out.errMsg != "" || !strings.Contains(out.output, "EXTENSION RESULT") {
1016 t.Fatalf("outcome = %+v, want the replaced result", out)
1017 }
1018 if strings.Contains(out.output, "read_file ok") {
1019 t.Fatalf("outcome leaked the original result: %q", out.output)
1020 }
1021 }
1022
1023 func TestToolAfterReplaceClearsError(t *testing.T) {
1024 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1025 if ev == protocol.EventToolAfter {
1026 var in dispatch.ToolAfterPayload
1027 if err := json.Unmarshal(payload, &in); err != nil {
1028 return protocol.InterceptResult{}, err
1029 }
1030 if !in.IsError {
1031 t.Errorf("payload IsError = false, want true for a failed tool")
1032 }
1033 return replaceWith(t, dispatch.ToolAfterPayload{
1034 Name: "read_file", Arguments: `{"path":"/x"}`, Result: "RECOVERED BY EXTENSION",
1035 }), nil
1036 }
1037 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1038 }}
1039 d := newExtDispatcher(client, true, nil, extension.PointToolAfter)
1040 reg := tool.NewRegistry()
1041 reg.Add(fakeTool{name: "read_file", readOnly: true, err: errors.New("boom")})
1042 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
1043 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
1044 if out.errMsg != "" || !strings.Contains(out.output, "RECOVERED BY EXTENSION") {
1045 t.Fatalf("outcome = %+v, want the failure converted to the replaced success", out)
1046 }
1047 }
1048
1049 func TestToolAfterBlock(t *testing.T) {
1050 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1051 if ev == protocol.EventToolAfter {
1052 return blockWith("result withheld"), nil
1053 }
1054 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1055 }}
1056 d := newExtDispatcher(client, true, nil, extension.PointToolAfter)
1057 rec := &recordingTool{name: "read_file", readOnly: true}
1058 reg := tool.NewRegistry()
1059 reg.Add(rec)
1060 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
1061 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
1062 if out.errMsg == "" || !strings.Contains(out.output, "result withheld") {
1063 t.Fatalf("outcome = %+v, want an error tool result with the reason", out)
1064 }
1065 if rec.execs != 1 {
1066 t.Fatalf("the tool itself must still have run (block only withholds the result), execs = %d", rec.execs)
1067 }
1068 }
1069
1070 func TestToolAfterFailurePolicy(t *testing.T) {
1071 boom := errors.New("sidecar timeout")
1072 t.Run("required converts the result to the failure", func(t *testing.T) {
1073 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1074 return protocol.InterceptResult{}, boom
1075 }}
1076 d := newExtDispatcher(client, true, nil, extension.PointToolAfter)
1077 rec := &recordingTool{name: "read_file", readOnly: true}
1078 reg := tool.NewRegistry()
1079 reg.Add(rec)
1080 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
1081 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
1082 if out.errMsg == "" || !strings.Contains(out.output, "extension fake failed at tool.after") {
1083 t.Fatalf("outcome = %+v, want the required failure as the tool result", out)
1084 }
1085 })
1086 t.Run("optional warns and keeps the result", func(t *testing.T) {
1087 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1088 return protocol.InterceptResult{}, boom
1089 }}
1090 warns := &extWarnRecorder{}
1091 d := newExtDispatcher(client, false, warns.warn, extension.PointToolAfter)
1092 rec := &recordingTool{name: "read_file", readOnly: true}
1093 reg := tool.NewRegistry()
1094 reg.Add(rec)
1095 a := New(nil, reg, NewSession(""), Options{Extensions: d}, event.Discard)
1096 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "read_file", Arguments: `{"path":"/x"}`})
1097 if out.errMsg != "" || !strings.Contains(out.output, "read_file ok") {
1098 t.Fatalf("outcome = %+v, want the original result", out)
1099 }
1100 if !warns.contains("skipping this optional extension") {
1101 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
1102 }
1103 })
1104 }
1105
1106 // compaction.prepare / compaction.complete
1107
1108 // newCompactionAgent builds an agent whose session has a foldable middle
1109 // (large assistant turns) so CompactNow always finds a region, with the
1110 // summarizer scripted to answer "SUMMARY TEXT". The recent tail stays small so
1111 // the content-driven candidate lands under compact_ratio.
1112 func newCompactionAgent(t *testing.T, d *dispatch.Dispatcher) (*mockProvider, *Agent) {
1113 t.Helper()
1114 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1115 {Type: provider.ChunkText, Text: "SUMMARY TEXT"}, {Type: provider.ChunkDone},
1116 }}
1117 sess := NewSession("sys")
1118 big := strings.Repeat("a", 8000)
1119 sess.Add(provider.Message{Role: provider.RoleUser, Content: "task"})
1120 sess.Add(provider.Message{Role: provider.RoleAssistant, Content: big})
1121 sess.Add(provider.Message{Role: provider.RoleUser, Content: "more"})
1122 sess.Add(provider.Message{Role: provider.RoleAssistant, Content: big})
1123 sess.Add(provider.Message{Role: provider.RoleUser, Content: "next"})
1124 sess.Add(provider.Message{Role: provider.RoleAssistant, Content: "ok"})
1125 return mp, New(mp, tool.NewRegistry(), sess, Options{
1126 ContextWindow: 50_000, CompactRatio: 0.85, RecentKeep: 2, Extensions: d,
1127 }, event.Discard)
1128 }
1129
1130 func TestCompactionPrepareBlock(t *testing.T) {
1131 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1132 if ev == protocol.EventCompactionPrepare {
1133 return blockWith("compaction denied"), nil
1134 }
1135 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1136 }}
1137 d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare)
1138 mp, a := newCompactionAgent(t, d)
1139 before := len(a.Session().Messages)
1140 err := a.CompactNow(context.Background(), "")
1141 if err == nil || !strings.Contains(err.Error(), "compaction denied") {
1142 t.Fatalf("CompactNow err = %v, want the block reason", err)
1143 }
1144 if len(mp.requests) != 0 {
1145 t.Fatalf("blocked compaction still called the summarizer: %d requests", len(mp.requests))
1146 }
1147 if len(a.Session().Messages) != before {
1148 t.Fatal("blocked compaction rewrote the session")
1149 }
1150 }
1151
1152 func TestCompactionPrepareFailurePolicy(t *testing.T) {
1153 boom := errors.New("sidecar timeout")
1154 t.Run("required skips the pass with the failure", func(t *testing.T) {
1155 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1156 return protocol.InterceptResult{}, boom
1157 }}
1158 d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare)
1159 mp, a := newCompactionAgent(t, d)
1160 before := len(a.Session().Messages)
1161 err := a.CompactNow(context.Background(), "")
1162 if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.prepare") {
1163 t.Fatalf("CompactNow err = %v, want the required failure", err)
1164 }
1165 if len(mp.requests) != 0 || len(a.Session().Messages) != before {
1166 t.Fatal("failed compaction still ran the summarizer or rewrote the session")
1167 }
1168 })
1169 t.Run("optional warns and folds", func(t *testing.T) {
1170 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1171 return protocol.InterceptResult{}, boom
1172 }}
1173 warns := &extWarnRecorder{}
1174 d := newExtDispatcher(client, false, warns.warn, extension.PointCompactionPrepare)
1175 _, a := newCompactionAgent(t, d)
1176 if err := a.CompactNow(context.Background(), ""); err != nil {
1177 t.Fatalf("CompactNow: %v", err)
1178 }
1179 if sc := joinContents(visibleContext(a)); !strings.Contains(sc, "SUMMARY TEXT") {
1180 t.Fatalf("projection missing the summary:\n%.200q", sc)
1181 }
1182 if !warns.contains("skipping this optional extension") {
1183 t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs)
1184 }
1185 })
1186 }
1187
1188 func TestCompactionCompleteReplace(t *testing.T) {
1189 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1190 if ev == protocol.EventCompactionComplete {
1191 var in dispatch.CompactionCompletePayload
1192 if err := json.Unmarshal(payload, &in); err != nil {
1193 return protocol.InterceptResult{}, err
1194 }
1195 if in.Summary != "SUMMARY TEXT" {
1196 t.Errorf("complete payload summary = %q, want the produced summary", in.Summary)
1197 }
1198 return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "EXTENSION SUMMARY"}), nil
1199 }
1200 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1201 }}
1202 d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete)
1203 _, a := newCompactionAgent(t, d)
1204 if err := a.CompactNow(context.Background(), ""); err != nil {
1205 t.Fatalf("CompactNow: %v", err)
1206 }
1207 sc := joinContents(visibleContext(a))
1208 if !strings.Contains(sc, "EXTENSION SUMMARY") {
1209 t.Fatalf("projection missing the replaced summary:\n%.200q", sc)
1210 }
1211 if strings.Contains(sc, "SUMMARY TEXT") {
1212 t.Fatalf("session leaked the original summary:\n%.200q", sc)
1213 }
1214 }
1215
1216 func TestCompactionCompleteBlock(t *testing.T) {
1217 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1218 if ev == protocol.EventCompactionComplete {
1219 return blockWith("summary denied"), nil
1220 }
1221 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1222 }}
1223 d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete)
1224 _, a := newCompactionAgent(t, d)
1225 before := len(a.Session().Messages)
1226 err := a.CompactNow(context.Background(), "")
1227 if err == nil || !strings.Contains(err.Error(), "summary denied") {
1228 t.Fatalf("CompactNow err = %v, want the block reason", err)
1229 }
1230 if len(a.Session().Messages) != before {
1231 t.Fatal("blocked compaction rewrote the session")
1232 }
1233 }
1234
1235 func TestCompactionCompleteRequiredFailure(t *testing.T) {
1236 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1237 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1238 }}
1239 d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete)
1240 _, a := newCompactionAgent(t, d)
1241 before := len(a.Session().Messages)
1242 err := a.CompactNow(context.Background(), "")
1243 if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.complete") {
1244 t.Fatalf("CompactNow err = %v, want the required failure", err)
1245 }
1246 if len(a.Session().Messages) != before {
1247 t.Fatal("failed compaction rewrote the session")
1248 }
1249 }
1250
1251 // --- slot-owner strategy phase (two-phase ruling: chain walk, then the slot
1252 // owner's RunStrategy as the final replacement phase) ---
1253
1254 func TestContextPrepareSlotOwnerConsulted(t *testing.T) {
1255 // The owner declared ONLY replaces (no intercepts): the chain is empty,
1256 // yet its strategy ruling must drive the request.
1257 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1258 if ev == protocol.EventContextPrepare {
1259 return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{
1260 {Role: protocol.ProviderRoleSystem, Content: "OWNER SYS"},
1261 {Role: protocol.ProviderRoleUser, Content: "OWNER USER"},
1262 }}), nil
1263 }
1264 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1265 }}
1266 d := newExtSlotDispatcher(client, false, nil, nil,
1267 map[extension.Slot]string{extension.SlotContext: extTestPlugin})
1268 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1269 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
1270 }}
1271 sess := NewSession("sys")
1272 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
1273 if err := a.Run(context.Background(), "hello"); err != nil {
1274 t.Fatalf("Run: %v", err)
1275 }
1276 if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER USER") || strings.Contains(got, "hello") {
1277 t.Fatalf("request = %q, want the slot owner's replacement", got)
1278 }
1279 if sc := sessionContents(sess); strings.Contains(sc, "OWNER USER") {
1280 t.Fatalf("session mutated by the owner's replacement:\n%s", sc)
1281 }
1282 }
1283
1284 func TestContextPrepareSlotOwnerFinalSayAfterChain(t *testing.T) {
1285 // The owner declared BOTH intercepts and replaces: it participates as a
1286 // chain interceptor first, then as the slot strategy — and the strategy
1287 // sees the chain's output.
1288 calls := 0
1289 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1290 if ev != protocol.EventContextPrepare {
1291 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1292 }
1293 calls++
1294 var in dispatch.ContextPayload
1295 if err := json.Unmarshal(payload, &in); err != nil {
1296 return protocol.InterceptResult{}, err
1297 }
1298 if calls == 1 {
1299 return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{
1300 {Role: protocol.ProviderRoleUser, Content: "CHAIN VALUE"},
1301 }}), nil
1302 }
1303 if got := in.Messages[0].Content; got != "CHAIN VALUE" {
1304 t.Errorf("strategy phase received %q, want the chain's output", got)
1305 }
1306 return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{
1307 {Role: protocol.ProviderRoleUser, Content: "OWNER VALUE"},
1308 }}), nil
1309 }}
1310 d := newExtSlotDispatcher(client, false, nil,
1311 []extension.InterceptorPoint{extension.PointContextPrepare},
1312 map[extension.Slot]string{extension.SlotContext: extTestPlugin})
1313 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1314 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
1315 }}
1316 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
1317 if err := a.Run(context.Background(), "hello"); err != nil {
1318 t.Fatalf("Run: %v", err)
1319 }
1320 if calls != 2 {
1321 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1322 }
1323 if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER VALUE") || strings.Contains(got, "CHAIN VALUE") {
1324 t.Fatalf("request = %q, want the strategy ruling to win", got)
1325 }
1326 }
1327
1328 func TestContextPrepareSlotOwnerFailureIsFatal(t *testing.T) {
1329 // Slot ownership alone makes the extension required-class (required=false
1330 // here): its timeout fails the operation.
1331 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1332 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1333 }}
1334 d := newExtSlotDispatcher(client, false, nil, nil,
1335 map[extension.Slot]string{extension.SlotContext: extTestPlugin})
1336 mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}}
1337 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
1338 err := a.Run(context.Background(), "hello")
1339 if err == nil || !strings.Contains(err.Error(), "extension fake failed at context.prepare") {
1340 t.Fatalf("Run err = %v, want the owner failure", err)
1341 }
1342 }
1343
1344 func TestProviderRequestSlotOwnerConsulted(t *testing.T) {
1345 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1346 if ev == protocol.EventProviderRequest {
1347 var in dispatch.ProviderRequestPayload
1348 if err := json.Unmarshal(payload, &in); err != nil {
1349 return protocol.InterceptResult{}, err
1350 }
1351 in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{
1352 Role: protocol.ProviderRoleUser, Content: "OWNER INJECTED",
1353 })
1354 return replaceWith(t, in), nil
1355 }
1356 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1357 }}
1358 d := newExtSlotDispatcher(client, false, nil, nil,
1359 map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin})
1360 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1361 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
1362 }}
1363 sess := NewSession("sys")
1364 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
1365 if err := a.Run(context.Background(), "hello"); err != nil {
1366 t.Fatalf("Run: %v", err)
1367 }
1368 if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER INJECTED") {
1369 t.Fatalf("request = %q, want the slot owner's replacement", got)
1370 }
1371 if sc := sessionContents(sess); strings.Contains(sc, "OWNER INJECTED") {
1372 t.Fatalf("session mutated by the owner's replacement:\n%s", sc)
1373 }
1374 }
1375
1376 func TestProviderRequestSlotOwnerFinalSayAfterChain(t *testing.T) {
1377 calls := 0
1378 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1379 if ev != protocol.EventProviderRequest {
1380 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1381 }
1382 calls++
1383 var in dispatch.ProviderRequestPayload
1384 if err := json.Unmarshal(payload, &in); err != nil {
1385 return protocol.InterceptResult{}, err
1386 }
1387 marker := "CHAIN MARKER"
1388 if calls == 2 {
1389 var last string
1390 if n := len(in.Request.Messages); n > 0 {
1391 last = in.Request.Messages[n-1].Content
1392 }
1393 if last != "CHAIN MARKER" {
1394 t.Errorf("strategy phase last message = %q, want the chain's output", last)
1395 }
1396 marker = "OWNER MARKER"
1397 }
1398 in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{
1399 Role: protocol.ProviderRoleUser, Content: marker,
1400 })
1401 return replaceWith(t, in), nil
1402 }}
1403 d := newExtSlotDispatcher(client, false, nil,
1404 []extension.InterceptorPoint{extension.PointProviderRequest},
1405 map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin})
1406 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1407 {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone},
1408 }}
1409 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
1410 if err := a.Run(context.Background(), "hello"); err != nil {
1411 t.Fatalf("Run: %v", err)
1412 }
1413 if calls != 2 {
1414 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1415 }
1416 got := requestContents(mp.requests[0])
1417 if !strings.Contains(got, "OWNER MARKER") || !strings.Contains(got, "CHAIN MARKER") {
1418 t.Fatalf("request = %q, want both chain and owner replacements", got)
1419 }
1420 }
1421
1422 func TestProviderRequestSlotOwnerFailureIsFatal(t *testing.T) {
1423 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1424 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1425 }}
1426 d := newExtSlotDispatcher(client, false, nil, nil,
1427 map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin})
1428 mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}}
1429 a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
1430 err := a.Run(context.Background(), "hello")
1431 if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.request") {
1432 t.Fatalf("Run err = %v, want the owner failure", err)
1433 }
1434 }
1435
1436 func TestProviderResponseSlotOwnerConsulted(t *testing.T) {
1437 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1438 if ev == protocol.EventProviderResponse {
1439 return replaceWith(t, dispatch.ProviderResponsePayload{Text: "OWNER ANSWER"}), nil
1440 }
1441 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1442 }}
1443 d := newExtSlotDispatcher(client, false, nil, nil,
1444 map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin})
1445 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1446 {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone},
1447 }}
1448 sess := NewSession("sys")
1449 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
1450 if err := a.Run(context.Background(), "hello"); err != nil {
1451 t.Fatalf("Run: %v", err)
1452 }
1453 assistants := assistantMessages(sess)
1454 if len(assistants) != 1 || assistants[0].Content != "OWNER ANSWER" {
1455 t.Fatalf("assistant turn = %+v, want the slot owner's replacement persisted", assistants)
1456 }
1457 }
1458
1459 func TestProviderResponseSlotOwnerFinalSayAfterChain(t *testing.T) {
1460 calls := 0
1461 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1462 if ev != protocol.EventProviderResponse {
1463 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1464 }
1465 calls++
1466 var in dispatch.ProviderResponsePayload
1467 if err := json.Unmarshal(payload, &in); err != nil {
1468 return protocol.InterceptResult{}, err
1469 }
1470 if calls == 1 {
1471 return replaceWith(t, dispatch.ProviderResponsePayload{Text: "CHAIN TEXT"}), nil
1472 }
1473 if in.Text != "CHAIN TEXT" {
1474 t.Errorf("strategy phase received %q, want the chain's output", in.Text)
1475 }
1476 return replaceWith(t, dispatch.ProviderResponsePayload{Text: "OWNER TEXT"}), nil
1477 }}
1478 d := newExtSlotDispatcher(client, false, nil,
1479 []extension.InterceptorPoint{extension.PointProviderResponse},
1480 map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin})
1481 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1482 {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone},
1483 }}
1484 sess := NewSession("sys")
1485 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
1486 if err := a.Run(context.Background(), "hello"); err != nil {
1487 t.Fatalf("Run: %v", err)
1488 }
1489 if calls != 2 {
1490 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1491 }
1492 assistants := assistantMessages(sess)
1493 if len(assistants) != 1 || assistants[0].Content != "OWNER TEXT" {
1494 t.Fatalf("assistant turn = %+v, want the strategy ruling persisted", assistants)
1495 }
1496 }
1497
1498 func TestProviderResponseSlotOwnerFailureIsFatal(t *testing.T) {
1499 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1500 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1501 }}
1502 d := newExtSlotDispatcher(client, false, nil, nil,
1503 map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin})
1504 mp := &mockProvider{name: "p", chunks: []provider.Chunk{
1505 {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone},
1506 }}
1507 sess := NewSession("sys")
1508 a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard)
1509 err := a.Run(context.Background(), "hello")
1510 if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.response") {
1511 t.Fatalf("Run err = %v, want the owner failure", err)
1512 }
1513 if n := len(assistantMessages(sess)); n != 0 {
1514 t.Fatalf("failed owner ruling persisted %d assistant turns, want 0", n)
1515 }
1516 }
1517
1518 func TestPermissionDecisionSlotOwnerVeto(t *testing.T) {
1519 // The owner declared ONLY replaces. Its block vetoes even a chain allow —
1520 // and here even the host allow.
1521 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1522 if ev == protocol.EventPermissionDecision {
1523 return blockWith("owner policy says no"), nil
1524 }
1525 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1526 }}
1527 d := newExtSlotDispatcher(client, false, nil, nil,
1528 map[extension.Slot]string{extension.SlotPermission: extTestPlugin})
1529 rec := &recordingTool{name: "edit_file", readOnly: false}
1530 reg := tool.NewRegistry()
1531 reg.Add(rec)
1532 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
1533 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
1534 if !out.blocked || !strings.Contains(out.output, "owner policy says no") {
1535 t.Fatalf("outcome = %+v, want the owner's veto", out)
1536 }
1537 if rec.execs != 0 {
1538 t.Fatal("owner-vetoed tool executed")
1539 }
1540 }
1541
1542 func TestPermissionDecisionSlotOwnerFinalAfterChainAllow(t *testing.T) {
1543 // Both phases: the chain's allow overrides the host deny first, then the
1544 // owner's strategy block vetoes the call — strategy is the final phase.
1545 calls := 0
1546 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1547 if ev != protocol.EventPermissionDecision {
1548 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1549 }
1550 calls++
1551 if calls == 1 {
1552 return protocol.InterceptResult{Decision: protocol.DecisionAllow}, nil
1553 }
1554 return blockWith("owner vetoes the chain allow"), nil
1555 }}
1556 d := newExtSlotDispatcher(client, false, nil,
1557 []extension.InterceptorPoint{extension.PointPermissionDecision},
1558 map[extension.Slot]string{extension.SlotPermission: extTestPlugin})
1559 rec := &recordingTool{name: "edit_file", readOnly: false}
1560 reg := tool.NewRegistry()
1561 reg.Add(rec)
1562 gate := &stubGate{deny: map[string]bool{"edit_file": true}}
1563 a := New(nil, reg, NewSession(""), Options{Gate: gate, Extensions: d}, event.Discard)
1564 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
1565 if calls != 2 {
1566 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1567 }
1568 if !out.blocked || !strings.Contains(out.output, "owner vetoes the chain allow") {
1569 t.Fatalf("outcome = %+v, want the owner's final veto", out)
1570 }
1571 if rec.execs != 0 {
1572 t.Fatal("owner-vetoed tool executed")
1573 }
1574 }
1575
1576 func TestPermissionDecisionSlotOwnerFailureIsFatal(t *testing.T) {
1577 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1578 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1579 }}
1580 d := newExtSlotDispatcher(client, false, nil, nil,
1581 map[extension.Slot]string{extension.SlotPermission: extTestPlugin})
1582 rec := &recordingTool{name: "edit_file", readOnly: false}
1583 reg := tool.NewRegistry()
1584 reg.Add(rec)
1585 a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard)
1586 out := a.executeOne(context.Background(), &a.turn, provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`})
1587 if !out.blocked || !strings.Contains(out.output, "extension fake failed at permission.decision") {
1588 t.Fatalf("outcome = %+v, want the owner failure", out)
1589 }
1590 if rec.execs != 0 {
1591 t.Fatal("failed owner still let the tool run")
1592 }
1593 }
1594
1595 func TestCompactionPrepareSlotOwnerConsulted(t *testing.T) {
1596 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1597 if ev == protocol.EventCompactionPrepare {
1598 var in dispatch.CompactionPreparePayload
1599 if err := json.Unmarshal(payload, &in); err != nil {
1600 return protocol.InterceptResult{}, err
1601 }
1602 in.Guidance = "OWNER GUIDANCE"
1603 return replaceWith(t, in), nil
1604 }
1605 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1606 }}
1607 d := newExtSlotDispatcher(client, false, nil, nil,
1608 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1609 mp, a := newCompactionAgent(t, d)
1610 if err := a.CompactNow(context.Background(), ""); err != nil {
1611 t.Fatalf("CompactNow: %v", err)
1612 }
1613 if instruction := mp.requests[0].Messages[len(mp.requests[0].Messages)-1].Content; !strings.Contains(instruction, "OWNER GUIDANCE") {
1614 t.Fatalf("final summary instruction missing the owner's guidance:\n%.200q", instruction)
1615 }
1616 }
1617
1618 func TestCompactionPrepareSlotOwnerFinalSayAfterChain(t *testing.T) {
1619 calls := 0
1620 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1621 if ev != protocol.EventCompactionPrepare {
1622 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1623 }
1624 calls++
1625 var in dispatch.CompactionPreparePayload
1626 if err := json.Unmarshal(payload, &in); err != nil {
1627 return protocol.InterceptResult{}, err
1628 }
1629 if calls == 1 {
1630 in.Guidance = "CHAIN GUIDANCE"
1631 return replaceWith(t, in), nil
1632 }
1633 if in.Guidance != "CHAIN GUIDANCE" {
1634 t.Errorf("strategy phase guidance = %q, want the chain's output", in.Guidance)
1635 }
1636 in.Guidance = "OWNER GUIDANCE"
1637 return replaceWith(t, in), nil
1638 }}
1639 d := newExtSlotDispatcher(client, false, nil,
1640 []extension.InterceptorPoint{extension.PointCompactionPrepare},
1641 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1642 mp, a := newCompactionAgent(t, d)
1643 if err := a.CompactNow(context.Background(), ""); err != nil {
1644 t.Fatalf("CompactNow: %v", err)
1645 }
1646 if calls != 2 {
1647 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1648 }
1649 instruction := mp.requests[0].Messages[len(mp.requests[0].Messages)-1].Content
1650 if !strings.Contains(instruction, "OWNER GUIDANCE") || strings.Contains(instruction, "CHAIN GUIDANCE") {
1651 t.Fatalf("final summary instruction = %.200q, want the strategy ruling to win", instruction)
1652 }
1653 }
1654
1655 func TestCompactionPrepareSlotOwnerFailureIsFatal(t *testing.T) {
1656 client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) {
1657 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1658 }}
1659 d := newExtSlotDispatcher(client, false, nil, nil,
1660 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1661 mp, a := newCompactionAgent(t, d)
1662 before := len(a.Session().Messages)
1663 err := a.CompactNow(context.Background(), "")
1664 if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.prepare") {
1665 t.Fatalf("CompactNow err = %v, want the owner failure", err)
1666 }
1667 if len(mp.requests) != 0 || len(a.Session().Messages) != before {
1668 t.Fatal("failed owner still ran the summarizer or rewrote the session")
1669 }
1670 }
1671
1672 func TestCompactionCompleteSlotOwnerConsulted(t *testing.T) {
1673 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1674 if ev == protocol.EventCompactionComplete {
1675 return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "OWNER SUMMARY"}), nil
1676 }
1677 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1678 }}
1679 d := newExtSlotDispatcher(client, false, nil, nil,
1680 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1681 _, a := newCompactionAgent(t, d)
1682 if err := a.CompactNow(context.Background(), ""); err != nil {
1683 t.Fatalf("CompactNow: %v", err)
1684 }
1685 if sc := joinContents(visibleContext(a)); !strings.Contains(sc, "OWNER SUMMARY") {
1686 t.Fatalf("projection missing the owner's summary:\n%.200q", sc)
1687 }
1688 }
1689
1690 func TestCompactionCompleteSlotOwnerFinalSayAfterChain(t *testing.T) {
1691 calls := 0
1692 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) {
1693 if ev != protocol.EventCompactionComplete {
1694 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1695 }
1696 calls++
1697 var in dispatch.CompactionCompletePayload
1698 if err := json.Unmarshal(payload, &in); err != nil {
1699 return protocol.InterceptResult{}, err
1700 }
1701 if calls == 1 {
1702 return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "CHAIN SUMMARY"}), nil
1703 }
1704 if in.Summary != "CHAIN SUMMARY" {
1705 t.Errorf("strategy phase summary = %q, want the chain's output", in.Summary)
1706 }
1707 return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "OWNER SUMMARY"}), nil
1708 }}
1709 d := newExtSlotDispatcher(client, false, nil,
1710 []extension.InterceptorPoint{extension.PointCompactionComplete},
1711 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1712 _, a := newCompactionAgent(t, d)
1713 if err := a.CompactNow(context.Background(), ""); err != nil {
1714 t.Fatalf("CompactNow: %v", err)
1715 }
1716 if calls != 2 {
1717 t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls)
1718 }
1719 sc := joinContents(visibleContext(a))
1720 if !strings.Contains(sc, "OWNER SUMMARY") || strings.Contains(sc, "CHAIN SUMMARY") {
1721 t.Fatalf("projection = %.200q, want the strategy ruling persisted", sc)
1722 }
1723 }
1724
1725 func TestCompactionCompleteSlotOwnerFailureIsFatal(t *testing.T) {
1726 client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) {
1727 if ev == protocol.EventCompactionComplete {
1728 return protocol.InterceptResult{}, errors.New("sidecar timeout")
1729 }
1730 return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil
1731 }}
1732 d := newExtSlotDispatcher(client, false, nil, nil,
1733 map[extension.Slot]string{extension.SlotCompaction: extTestPlugin})
1734 _, a := newCompactionAgent(t, d)
1735 before := len(a.Session().Messages)
1736 err := a.CompactNow(context.Background(), "")
1737 if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.complete") {
1738 t.Fatalf("CompactNow err = %v, want the owner failure", err)
1739 }
1740 if len(a.Session().Messages) != before {
1741 t.Fatal("failed owner still rewrote the session")
1742 }
1743 }
1744
1745 // TestSlotUnownedKeepsFastPath pins the no-owner case: a chain-only plugin
1746 // (intercepts but no replaces) leaves the slot unowned, and the original
1747 // values reach the provider byte-identically.
1748 func TestSlotUnownedKeepsFastPath(t *testing.T) {
1749 client := &fakeDispatchClient{}
1750 d := newExtSlotDispatcher(client, false, nil,
1751 []extension.InterceptorPoint{extension.PointContextPrepare, extension.PointProviderRequest}, nil)
1752 streams := [][]provider.Chunk{
1753 {{Type: provider.ChunkText, Text: "one"}, {Type: provider.ChunkDone}},
1754 {{Type: provider.ChunkText, Text: "two"}, {Type: provider.ChunkDone}},
1755 }
1756 withExt := &mockProvider{name: "p", streams: streams}
1757 a := New(withExt, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard)
1758 baseline := &mockProvider{name: "p", streams: streams}
1759 b := New(baseline, tool.NewRegistry(), NewSession("sys"), Options{}, event.Discard)
1760 for _, input := range []string{"first", "second"} {
1761 if err := a.Run(context.Background(), input); err != nil {
1762 t.Fatalf("Run(%q): %v", input, err)
1763 }
1764 if err := b.Run(context.Background(), input); err != nil {
1765 t.Fatalf("baseline Run(%q): %v", input, err)
1766 }
1767 }
1768 for i := range baseline.requests {
1769 if got, want := requestContents(withExt.requests[i]), requestContents(baseline.requests[i]); got != want {
1770 t.Fatalf("request %d differs from the no-extension baseline:\ngot:\n%s\nwant:\n%s", i+1, got, want)
1771 }
1772 }
1773 }
1774
1774 lines GO