| 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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(), 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". |
| 1111 | func newCompactionAgent(t *testing.T, d *dispatch.Dispatcher) (*mockProvider, *Agent) { |
| 1112 | t.Helper() |
| 1113 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1114 | {Type: provider.ChunkText, Text: "SUMMARY TEXT"}, {Type: provider.ChunkDone}, |
| 1115 | }} |
| 1116 | sess := NewSession("sys") |
| 1117 | big := strings.Repeat("a", 4000) |
| 1118 | sess.Add(provider.Message{Role: provider.RoleUser, Content: "task"}) |
| 1119 | sess.Add(provider.Message{Role: provider.RoleAssistant, Content: big}) |
| 1120 | sess.Add(provider.Message{Role: provider.RoleUser, Content: "more"}) |
| 1121 | sess.Add(provider.Message{Role: provider.RoleAssistant, Content: big}) |
| 1122 | sess.Add(provider.Message{Role: provider.RoleUser, Content: "again"}) |
| 1123 | sess.Add(provider.Message{Role: provider.RoleAssistant, Content: big}) |
| 1124 | return mp, New(mp, tool.NewRegistry(), sess, Options{ContextWindow: 1000, Extensions: d}, event.Discard) |
| 1125 | } |
| 1126 | |
| 1127 | func TestCompactionPrepareReplaceGuidance(t *testing.T) { |
| 1128 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1129 | if ev == protocol.EventCompactionPrepare { |
| 1130 | var in dispatch.CompactionPreparePayload |
| 1131 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1132 | return protocol.InterceptResult{}, err |
| 1133 | } |
| 1134 | in.Guidance = "EXTENSION GUIDANCE" |
| 1135 | return replaceWith(t, in), nil |
| 1136 | } |
| 1137 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1138 | }} |
| 1139 | d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare) |
| 1140 | mp, a := newCompactionAgent(t, d) |
| 1141 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1142 | t.Fatalf("CompactNow: %v", err) |
| 1143 | } |
| 1144 | if len(mp.requests) != 1 { |
| 1145 | t.Fatalf("summarizer requests = %d, want 1", len(mp.requests)) |
| 1146 | } |
| 1147 | sys := mp.requests[0].Messages[0].Content |
| 1148 | if !strings.Contains(sys, "EXTENSION GUIDANCE") { |
| 1149 | t.Fatalf("summarizer system prompt missing the replaced guidance:\n%.200q", sys) |
| 1150 | } |
| 1151 | if sc := sessionContents(a.Session()); !strings.Contains(sc, "SUMMARY TEXT") { |
| 1152 | t.Fatalf("session missing the summary:\n%.200q", sc) |
| 1153 | } |
| 1154 | if n := client.notifyCountFor(protocol.EventCompactionPrepare); n != 1 { |
| 1155 | t.Fatalf("compaction.prepare events = %d, want 1", n) |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | func TestCompactionPrepareReplaceMessages(t *testing.T) { |
| 1160 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1161 | if ev == protocol.EventCompactionPrepare { |
| 1162 | return replaceWith(t, dispatch.CompactionPreparePayload{ |
| 1163 | Messages: []protocol.ProviderMessage{{Role: protocol.ProviderRoleUser, Content: "EXTENSION FOLD"}}, |
| 1164 | }), nil |
| 1165 | } |
| 1166 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1167 | }} |
| 1168 | d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare) |
| 1169 | mp, a := newCompactionAgent(t, d) |
| 1170 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1171 | t.Fatalf("CompactNow: %v", err) |
| 1172 | } |
| 1173 | transcript := mp.requests[0].Messages[1].Content |
| 1174 | if !strings.Contains(transcript, "EXTENSION FOLD") { |
| 1175 | t.Fatalf("summarizer transcript = %.200q, want the replaced fold", transcript) |
| 1176 | } |
| 1177 | } |
| 1178 | |
| 1179 | func TestCompactionPrepareBlock(t *testing.T) { |
| 1180 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1181 | if ev == protocol.EventCompactionPrepare { |
| 1182 | return blockWith("compaction denied"), nil |
| 1183 | } |
| 1184 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1185 | }} |
| 1186 | d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare) |
| 1187 | mp, a := newCompactionAgent(t, d) |
| 1188 | before := len(a.Session().Messages) |
| 1189 | err := a.CompactNow(context.Background(), "") |
| 1190 | if err == nil || !strings.Contains(err.Error(), "compaction denied") { |
| 1191 | t.Fatalf("CompactNow err = %v, want the block reason", err) |
| 1192 | } |
| 1193 | if len(mp.requests) != 0 { |
| 1194 | t.Fatalf("blocked compaction still called the summarizer: %d requests", len(mp.requests)) |
| 1195 | } |
| 1196 | if len(a.Session().Messages) != before { |
| 1197 | t.Fatal("blocked compaction rewrote the session") |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | func TestCompactionPrepareFailurePolicy(t *testing.T) { |
| 1202 | boom := errors.New("sidecar timeout") |
| 1203 | t.Run("required skips the pass with the failure", func(t *testing.T) { |
| 1204 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1205 | return protocol.InterceptResult{}, boom |
| 1206 | }} |
| 1207 | d := newExtDispatcher(client, true, nil, extension.PointCompactionPrepare) |
| 1208 | mp, a := newCompactionAgent(t, d) |
| 1209 | before := len(a.Session().Messages) |
| 1210 | err := a.CompactNow(context.Background(), "") |
| 1211 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.prepare") { |
| 1212 | t.Fatalf("CompactNow err = %v, want the required failure", err) |
| 1213 | } |
| 1214 | if len(mp.requests) != 0 || len(a.Session().Messages) != before { |
| 1215 | t.Fatal("failed compaction still ran the summarizer or rewrote the session") |
| 1216 | } |
| 1217 | }) |
| 1218 | t.Run("optional warns and folds", func(t *testing.T) { |
| 1219 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1220 | return protocol.InterceptResult{}, boom |
| 1221 | }} |
| 1222 | warns := &extWarnRecorder{} |
| 1223 | d := newExtDispatcher(client, false, warns.warn, extension.PointCompactionPrepare) |
| 1224 | _, a := newCompactionAgent(t, d) |
| 1225 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1226 | t.Fatalf("CompactNow: %v", err) |
| 1227 | } |
| 1228 | if sc := sessionContents(a.Session()); !strings.Contains(sc, "SUMMARY TEXT") { |
| 1229 | t.Fatalf("session missing the summary:\n%.200q", sc) |
| 1230 | } |
| 1231 | if !warns.contains("skipping this optional extension") { |
| 1232 | t.Fatalf("warnings = %v, want an optional-extension skip warning", warns.msgs) |
| 1233 | } |
| 1234 | }) |
| 1235 | } |
| 1236 | |
| 1237 | func TestCompactionCompleteReplace(t *testing.T) { |
| 1238 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1239 | if ev == protocol.EventCompactionComplete { |
| 1240 | var in dispatch.CompactionCompletePayload |
| 1241 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1242 | return protocol.InterceptResult{}, err |
| 1243 | } |
| 1244 | if in.Summary != "SUMMARY TEXT" { |
| 1245 | t.Errorf("complete payload summary = %q, want the produced summary", in.Summary) |
| 1246 | } |
| 1247 | return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "EXTENSION SUMMARY"}), nil |
| 1248 | } |
| 1249 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1250 | }} |
| 1251 | d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete) |
| 1252 | _, a := newCompactionAgent(t, d) |
| 1253 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1254 | t.Fatalf("CompactNow: %v", err) |
| 1255 | } |
| 1256 | sc := sessionContents(a.Session()) |
| 1257 | if !strings.Contains(sc, "EXTENSION SUMMARY") { |
| 1258 | t.Fatalf("session missing the replaced summary:\n%.200q", sc) |
| 1259 | } |
| 1260 | if strings.Contains(sc, "SUMMARY TEXT") { |
| 1261 | t.Fatalf("session leaked the original summary:\n%.200q", sc) |
| 1262 | } |
| 1263 | } |
| 1264 | |
| 1265 | func TestCompactionCompleteBlock(t *testing.T) { |
| 1266 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1267 | if ev == protocol.EventCompactionComplete { |
| 1268 | return blockWith("summary denied"), nil |
| 1269 | } |
| 1270 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1271 | }} |
| 1272 | d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete) |
| 1273 | _, a := newCompactionAgent(t, d) |
| 1274 | before := len(a.Session().Messages) |
| 1275 | err := a.CompactNow(context.Background(), "") |
| 1276 | if err == nil || !strings.Contains(err.Error(), "summary denied") { |
| 1277 | t.Fatalf("CompactNow err = %v, want the block reason", err) |
| 1278 | } |
| 1279 | if len(a.Session().Messages) != before { |
| 1280 | t.Fatal("blocked compaction rewrote the session") |
| 1281 | } |
| 1282 | } |
| 1283 | |
| 1284 | func TestCompactionCompleteRequiredFailure(t *testing.T) { |
| 1285 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1286 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1287 | }} |
| 1288 | d := newExtDispatcher(client, true, nil, extension.PointCompactionComplete) |
| 1289 | _, a := newCompactionAgent(t, d) |
| 1290 | before := len(a.Session().Messages) |
| 1291 | err := a.CompactNow(context.Background(), "") |
| 1292 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.complete") { |
| 1293 | t.Fatalf("CompactNow err = %v, want the required failure", err) |
| 1294 | } |
| 1295 | if len(a.Session().Messages) != before { |
| 1296 | t.Fatal("failed compaction rewrote the session") |
| 1297 | } |
| 1298 | } |
| 1299 | |
| 1300 | // --- slot-owner strategy phase (two-phase ruling: chain walk, then the slot |
| 1301 | // owner's RunStrategy as the final replacement phase) --- |
| 1302 | |
| 1303 | func TestContextPrepareSlotOwnerConsulted(t *testing.T) { |
| 1304 | // The owner declared ONLY replaces (no intercepts): the chain is empty, |
| 1305 | // yet its strategy ruling must drive the request. |
| 1306 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1307 | if ev == protocol.EventContextPrepare { |
| 1308 | return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{ |
| 1309 | {Role: protocol.ProviderRoleSystem, Content: "OWNER SYS"}, |
| 1310 | {Role: protocol.ProviderRoleUser, Content: "OWNER USER"}, |
| 1311 | }}), nil |
| 1312 | } |
| 1313 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1314 | }} |
| 1315 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1316 | map[extension.Slot]string{extension.SlotContext: extTestPlugin}) |
| 1317 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1318 | {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}, |
| 1319 | }} |
| 1320 | sess := NewSession("sys") |
| 1321 | a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard) |
| 1322 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1323 | t.Fatalf("Run: %v", err) |
| 1324 | } |
| 1325 | if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER USER") || strings.Contains(got, "hello") { |
| 1326 | t.Fatalf("request = %q, want the slot owner's replacement", got) |
| 1327 | } |
| 1328 | if sc := sessionContents(sess); strings.Contains(sc, "OWNER USER") { |
| 1329 | t.Fatalf("session mutated by the owner's replacement:\n%s", sc) |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | func TestContextPrepareSlotOwnerFinalSayAfterChain(t *testing.T) { |
| 1334 | // The owner declared BOTH intercepts and replaces: it participates as a |
| 1335 | // chain interceptor first, then as the slot strategy — and the strategy |
| 1336 | // sees the chain's output. |
| 1337 | calls := 0 |
| 1338 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1339 | if ev != protocol.EventContextPrepare { |
| 1340 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1341 | } |
| 1342 | calls++ |
| 1343 | var in dispatch.ContextPayload |
| 1344 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1345 | return protocol.InterceptResult{}, err |
| 1346 | } |
| 1347 | if calls == 1 { |
| 1348 | return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{ |
| 1349 | {Role: protocol.ProviderRoleUser, Content: "CHAIN VALUE"}, |
| 1350 | }}), nil |
| 1351 | } |
| 1352 | if got := in.Messages[0].Content; got != "CHAIN VALUE" { |
| 1353 | t.Errorf("strategy phase received %q, want the chain's output", got) |
| 1354 | } |
| 1355 | return replaceWith(t, dispatch.ContextPayload{Messages: []protocol.ProviderMessage{ |
| 1356 | {Role: protocol.ProviderRoleUser, Content: "OWNER VALUE"}, |
| 1357 | }}), nil |
| 1358 | }} |
| 1359 | d := newExtSlotDispatcher(client, false, nil, |
| 1360 | []extension.InterceptorPoint{extension.PointContextPrepare}, |
| 1361 | map[extension.Slot]string{extension.SlotContext: extTestPlugin}) |
| 1362 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1363 | {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}, |
| 1364 | }} |
| 1365 | a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard) |
| 1366 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1367 | t.Fatalf("Run: %v", err) |
| 1368 | } |
| 1369 | if calls != 2 { |
| 1370 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1371 | } |
| 1372 | if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER VALUE") || strings.Contains(got, "CHAIN VALUE") { |
| 1373 | t.Fatalf("request = %q, want the strategy ruling to win", got) |
| 1374 | } |
| 1375 | } |
| 1376 | |
| 1377 | func TestContextPrepareSlotOwnerFailureIsFatal(t *testing.T) { |
| 1378 | // Slot ownership alone makes the extension required-class (required=false |
| 1379 | // here): its timeout fails the operation. |
| 1380 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1381 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1382 | }} |
| 1383 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1384 | map[extension.Slot]string{extension.SlotContext: extTestPlugin}) |
| 1385 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}} |
| 1386 | a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard) |
| 1387 | err := a.Run(context.Background(), "hello") |
| 1388 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at context.prepare") { |
| 1389 | t.Fatalf("Run err = %v, want the owner failure", err) |
| 1390 | } |
| 1391 | } |
| 1392 | |
| 1393 | func TestProviderRequestSlotOwnerConsulted(t *testing.T) { |
| 1394 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1395 | if ev == protocol.EventProviderRequest { |
| 1396 | var in dispatch.ProviderRequestPayload |
| 1397 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1398 | return protocol.InterceptResult{}, err |
| 1399 | } |
| 1400 | in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{ |
| 1401 | Role: protocol.ProviderRoleUser, Content: "OWNER INJECTED", |
| 1402 | }) |
| 1403 | return replaceWith(t, in), nil |
| 1404 | } |
| 1405 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1406 | }} |
| 1407 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1408 | map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin}) |
| 1409 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1410 | {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}, |
| 1411 | }} |
| 1412 | sess := NewSession("sys") |
| 1413 | a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard) |
| 1414 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1415 | t.Fatalf("Run: %v", err) |
| 1416 | } |
| 1417 | if got := requestContents(mp.requests[0]); !strings.Contains(got, "OWNER INJECTED") { |
| 1418 | t.Fatalf("request = %q, want the slot owner's replacement", got) |
| 1419 | } |
| 1420 | if sc := sessionContents(sess); strings.Contains(sc, "OWNER INJECTED") { |
| 1421 | t.Fatalf("session mutated by the owner's replacement:\n%s", sc) |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | func TestProviderRequestSlotOwnerFinalSayAfterChain(t *testing.T) { |
| 1426 | calls := 0 |
| 1427 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1428 | if ev != protocol.EventProviderRequest { |
| 1429 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1430 | } |
| 1431 | calls++ |
| 1432 | var in dispatch.ProviderRequestPayload |
| 1433 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1434 | return protocol.InterceptResult{}, err |
| 1435 | } |
| 1436 | marker := "CHAIN MARKER" |
| 1437 | if calls == 2 { |
| 1438 | var last string |
| 1439 | if n := len(in.Request.Messages); n > 0 { |
| 1440 | last = in.Request.Messages[n-1].Content |
| 1441 | } |
| 1442 | if last != "CHAIN MARKER" { |
| 1443 | t.Errorf("strategy phase last message = %q, want the chain's output", last) |
| 1444 | } |
| 1445 | marker = "OWNER MARKER" |
| 1446 | } |
| 1447 | in.Request.Messages = append(in.Request.Messages, protocol.ProviderMessage{ |
| 1448 | Role: protocol.ProviderRoleUser, Content: marker, |
| 1449 | }) |
| 1450 | return replaceWith(t, in), nil |
| 1451 | }} |
| 1452 | d := newExtSlotDispatcher(client, false, nil, |
| 1453 | []extension.InterceptorPoint{extension.PointProviderRequest}, |
| 1454 | map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin}) |
| 1455 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1456 | {Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}, |
| 1457 | }} |
| 1458 | a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard) |
| 1459 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1460 | t.Fatalf("Run: %v", err) |
| 1461 | } |
| 1462 | if calls != 2 { |
| 1463 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1464 | } |
| 1465 | got := requestContents(mp.requests[0]) |
| 1466 | if !strings.Contains(got, "OWNER MARKER") || !strings.Contains(got, "CHAIN MARKER") { |
| 1467 | t.Fatalf("request = %q, want both chain and owner replacements", got) |
| 1468 | } |
| 1469 | } |
| 1470 | |
| 1471 | func TestProviderRequestSlotOwnerFailureIsFatal(t *testing.T) { |
| 1472 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1473 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1474 | }} |
| 1475 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1476 | map[extension.Slot]string{extension.SlotProviderRequest: extTestPlugin}) |
| 1477 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{{Type: provider.ChunkDone}}} |
| 1478 | a := New(mp, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard) |
| 1479 | err := a.Run(context.Background(), "hello") |
| 1480 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.request") { |
| 1481 | t.Fatalf("Run err = %v, want the owner failure", err) |
| 1482 | } |
| 1483 | } |
| 1484 | |
| 1485 | func TestProviderResponseSlotOwnerConsulted(t *testing.T) { |
| 1486 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1487 | if ev == protocol.EventProviderResponse { |
| 1488 | return replaceWith(t, dispatch.ProviderResponsePayload{Text: "OWNER ANSWER"}), nil |
| 1489 | } |
| 1490 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1491 | }} |
| 1492 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1493 | map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin}) |
| 1494 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1495 | {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone}, |
| 1496 | }} |
| 1497 | sess := NewSession("sys") |
| 1498 | a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard) |
| 1499 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1500 | t.Fatalf("Run: %v", err) |
| 1501 | } |
| 1502 | assistants := assistantMessages(sess) |
| 1503 | if len(assistants) != 1 || assistants[0].Content != "OWNER ANSWER" { |
| 1504 | t.Fatalf("assistant turn = %+v, want the slot owner's replacement persisted", assistants) |
| 1505 | } |
| 1506 | } |
| 1507 | |
| 1508 | func TestProviderResponseSlotOwnerFinalSayAfterChain(t *testing.T) { |
| 1509 | calls := 0 |
| 1510 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1511 | if ev != protocol.EventProviderResponse { |
| 1512 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1513 | } |
| 1514 | calls++ |
| 1515 | var in dispatch.ProviderResponsePayload |
| 1516 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1517 | return protocol.InterceptResult{}, err |
| 1518 | } |
| 1519 | if calls == 1 { |
| 1520 | return replaceWith(t, dispatch.ProviderResponsePayload{Text: "CHAIN TEXT"}), nil |
| 1521 | } |
| 1522 | if in.Text != "CHAIN TEXT" { |
| 1523 | t.Errorf("strategy phase received %q, want the chain's output", in.Text) |
| 1524 | } |
| 1525 | return replaceWith(t, dispatch.ProviderResponsePayload{Text: "OWNER TEXT"}), nil |
| 1526 | }} |
| 1527 | d := newExtSlotDispatcher(client, false, nil, |
| 1528 | []extension.InterceptorPoint{extension.PointProviderResponse}, |
| 1529 | map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin}) |
| 1530 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1531 | {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone}, |
| 1532 | }} |
| 1533 | sess := NewSession("sys") |
| 1534 | a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard) |
| 1535 | if err := a.Run(context.Background(), "hello"); err != nil { |
| 1536 | t.Fatalf("Run: %v", err) |
| 1537 | } |
| 1538 | if calls != 2 { |
| 1539 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1540 | } |
| 1541 | assistants := assistantMessages(sess) |
| 1542 | if len(assistants) != 1 || assistants[0].Content != "OWNER TEXT" { |
| 1543 | t.Fatalf("assistant turn = %+v, want the strategy ruling persisted", assistants) |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | func TestProviderResponseSlotOwnerFailureIsFatal(t *testing.T) { |
| 1548 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1549 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1550 | }} |
| 1551 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1552 | map[extension.Slot]string{extension.SlotProviderResponse: extTestPlugin}) |
| 1553 | mp := &mockProvider{name: "p", chunks: []provider.Chunk{ |
| 1554 | {Type: provider.ChunkText, Text: "ORIGINAL"}, {Type: provider.ChunkDone}, |
| 1555 | }} |
| 1556 | sess := NewSession("sys") |
| 1557 | a := New(mp, tool.NewRegistry(), sess, Options{Extensions: d}, event.Discard) |
| 1558 | err := a.Run(context.Background(), "hello") |
| 1559 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at provider.response") { |
| 1560 | t.Fatalf("Run err = %v, want the owner failure", err) |
| 1561 | } |
| 1562 | if n := len(assistantMessages(sess)); n != 0 { |
| 1563 | t.Fatalf("failed owner ruling persisted %d assistant turns, want 0", n) |
| 1564 | } |
| 1565 | } |
| 1566 | |
| 1567 | func TestPermissionDecisionSlotOwnerVeto(t *testing.T) { |
| 1568 | // The owner declared ONLY replaces. Its block vetoes even a chain allow — |
| 1569 | // and here even the host allow. |
| 1570 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1571 | if ev == protocol.EventPermissionDecision { |
| 1572 | return blockWith("owner policy says no"), nil |
| 1573 | } |
| 1574 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1575 | }} |
| 1576 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1577 | map[extension.Slot]string{extension.SlotPermission: extTestPlugin}) |
| 1578 | rec := &recordingTool{name: "edit_file", readOnly: false} |
| 1579 | reg := tool.NewRegistry() |
| 1580 | reg.Add(rec) |
| 1581 | a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard) |
| 1582 | out := a.executeOne(context.Background(), provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`}) |
| 1583 | if !out.blocked || !strings.Contains(out.output, "owner policy says no") { |
| 1584 | t.Fatalf("outcome = %+v, want the owner's veto", out) |
| 1585 | } |
| 1586 | if rec.execs != 0 { |
| 1587 | t.Fatal("owner-vetoed tool executed") |
| 1588 | } |
| 1589 | } |
| 1590 | |
| 1591 | func TestPermissionDecisionSlotOwnerFinalAfterChainAllow(t *testing.T) { |
| 1592 | // Both phases: the chain's allow overrides the host deny first, then the |
| 1593 | // owner's strategy block vetoes the call — strategy is the final phase. |
| 1594 | calls := 0 |
| 1595 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1596 | if ev != protocol.EventPermissionDecision { |
| 1597 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1598 | } |
| 1599 | calls++ |
| 1600 | if calls == 1 { |
| 1601 | return protocol.InterceptResult{Decision: protocol.DecisionAllow}, nil |
| 1602 | } |
| 1603 | return blockWith("owner vetoes the chain allow"), nil |
| 1604 | }} |
| 1605 | d := newExtSlotDispatcher(client, false, nil, |
| 1606 | []extension.InterceptorPoint{extension.PointPermissionDecision}, |
| 1607 | map[extension.Slot]string{extension.SlotPermission: extTestPlugin}) |
| 1608 | rec := &recordingTool{name: "edit_file", readOnly: false} |
| 1609 | reg := tool.NewRegistry() |
| 1610 | reg.Add(rec) |
| 1611 | gate := &stubGate{deny: map[string]bool{"edit_file": true}} |
| 1612 | a := New(nil, reg, NewSession(""), Options{Gate: gate, Extensions: d}, event.Discard) |
| 1613 | out := a.executeOne(context.Background(), provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`}) |
| 1614 | if calls != 2 { |
| 1615 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1616 | } |
| 1617 | if !out.blocked || !strings.Contains(out.output, "owner vetoes the chain allow") { |
| 1618 | t.Fatalf("outcome = %+v, want the owner's final veto", out) |
| 1619 | } |
| 1620 | if rec.execs != 0 { |
| 1621 | t.Fatal("owner-vetoed tool executed") |
| 1622 | } |
| 1623 | } |
| 1624 | |
| 1625 | func TestPermissionDecisionSlotOwnerFailureIsFatal(t *testing.T) { |
| 1626 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1627 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1628 | }} |
| 1629 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1630 | map[extension.Slot]string{extension.SlotPermission: extTestPlugin}) |
| 1631 | rec := &recordingTool{name: "edit_file", readOnly: false} |
| 1632 | reg := tool.NewRegistry() |
| 1633 | reg.Add(rec) |
| 1634 | a := New(nil, reg, NewSession(""), Options{Gate: &stubGate{}, Extensions: d}, event.Discard) |
| 1635 | out := a.executeOne(context.Background(), provider.ToolCall{Name: "edit_file", Arguments: `{"path":"/x"}`}) |
| 1636 | if !out.blocked || !strings.Contains(out.output, "extension fake failed at permission.decision") { |
| 1637 | t.Fatalf("outcome = %+v, want the owner failure", out) |
| 1638 | } |
| 1639 | if rec.execs != 0 { |
| 1640 | t.Fatal("failed owner still let the tool run") |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | func TestCompactionPrepareSlotOwnerConsulted(t *testing.T) { |
| 1645 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1646 | if ev == protocol.EventCompactionPrepare { |
| 1647 | var in dispatch.CompactionPreparePayload |
| 1648 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1649 | return protocol.InterceptResult{}, err |
| 1650 | } |
| 1651 | in.Guidance = "OWNER GUIDANCE" |
| 1652 | return replaceWith(t, in), nil |
| 1653 | } |
| 1654 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1655 | }} |
| 1656 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1657 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1658 | mp, a := newCompactionAgent(t, d) |
| 1659 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1660 | t.Fatalf("CompactNow: %v", err) |
| 1661 | } |
| 1662 | if sys := mp.requests[0].Messages[0].Content; !strings.Contains(sys, "OWNER GUIDANCE") { |
| 1663 | t.Fatalf("summarizer system prompt missing the owner's guidance:\n%.200q", sys) |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | func TestCompactionPrepareSlotOwnerFinalSayAfterChain(t *testing.T) { |
| 1668 | calls := 0 |
| 1669 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1670 | if ev != protocol.EventCompactionPrepare { |
| 1671 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1672 | } |
| 1673 | calls++ |
| 1674 | var in dispatch.CompactionPreparePayload |
| 1675 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1676 | return protocol.InterceptResult{}, err |
| 1677 | } |
| 1678 | if calls == 1 { |
| 1679 | in.Guidance = "CHAIN GUIDANCE" |
| 1680 | return replaceWith(t, in), nil |
| 1681 | } |
| 1682 | if in.Guidance != "CHAIN GUIDANCE" { |
| 1683 | t.Errorf("strategy phase guidance = %q, want the chain's output", in.Guidance) |
| 1684 | } |
| 1685 | in.Guidance = "OWNER GUIDANCE" |
| 1686 | return replaceWith(t, in), nil |
| 1687 | }} |
| 1688 | d := newExtSlotDispatcher(client, false, nil, |
| 1689 | []extension.InterceptorPoint{extension.PointCompactionPrepare}, |
| 1690 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1691 | mp, a := newCompactionAgent(t, d) |
| 1692 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1693 | t.Fatalf("CompactNow: %v", err) |
| 1694 | } |
| 1695 | if calls != 2 { |
| 1696 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1697 | } |
| 1698 | sys := mp.requests[0].Messages[0].Content |
| 1699 | if !strings.Contains(sys, "OWNER GUIDANCE") || strings.Contains(sys, "CHAIN GUIDANCE") { |
| 1700 | t.Fatalf("summarizer system prompt = %.200q, want the strategy ruling to win", sys) |
| 1701 | } |
| 1702 | } |
| 1703 | |
| 1704 | func TestCompactionPrepareSlotOwnerFailureIsFatal(t *testing.T) { |
| 1705 | client := &fakeDispatchClient{interceptFn: func(protocol.InterceptEvent, json.RawMessage) (protocol.InterceptResult, error) { |
| 1706 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1707 | }} |
| 1708 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1709 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1710 | mp, a := newCompactionAgent(t, d) |
| 1711 | before := len(a.Session().Messages) |
| 1712 | err := a.CompactNow(context.Background(), "") |
| 1713 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.prepare") { |
| 1714 | t.Fatalf("CompactNow err = %v, want the owner failure", err) |
| 1715 | } |
| 1716 | if len(mp.requests) != 0 || len(a.Session().Messages) != before { |
| 1717 | t.Fatal("failed owner still ran the summarizer or rewrote the session") |
| 1718 | } |
| 1719 | } |
| 1720 | |
| 1721 | func TestCompactionCompleteSlotOwnerConsulted(t *testing.T) { |
| 1722 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1723 | if ev == protocol.EventCompactionComplete { |
| 1724 | return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "OWNER SUMMARY"}), nil |
| 1725 | } |
| 1726 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1727 | }} |
| 1728 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1729 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1730 | _, a := newCompactionAgent(t, d) |
| 1731 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1732 | t.Fatalf("CompactNow: %v", err) |
| 1733 | } |
| 1734 | if sc := sessionContents(a.Session()); !strings.Contains(sc, "OWNER SUMMARY") { |
| 1735 | t.Fatalf("session missing the owner's summary:\n%.200q", sc) |
| 1736 | } |
| 1737 | } |
| 1738 | |
| 1739 | func TestCompactionCompleteSlotOwnerFinalSayAfterChain(t *testing.T) { |
| 1740 | calls := 0 |
| 1741 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, payload json.RawMessage) (protocol.InterceptResult, error) { |
| 1742 | if ev != protocol.EventCompactionComplete { |
| 1743 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1744 | } |
| 1745 | calls++ |
| 1746 | var in dispatch.CompactionCompletePayload |
| 1747 | if err := json.Unmarshal(payload, &in); err != nil { |
| 1748 | return protocol.InterceptResult{}, err |
| 1749 | } |
| 1750 | if calls == 1 { |
| 1751 | return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "CHAIN SUMMARY"}), nil |
| 1752 | } |
| 1753 | if in.Summary != "CHAIN SUMMARY" { |
| 1754 | t.Errorf("strategy phase summary = %q, want the chain's output", in.Summary) |
| 1755 | } |
| 1756 | return replaceWith(t, dispatch.CompactionCompletePayload{Summary: "OWNER SUMMARY"}), nil |
| 1757 | }} |
| 1758 | d := newExtSlotDispatcher(client, false, nil, |
| 1759 | []extension.InterceptorPoint{extension.PointCompactionComplete}, |
| 1760 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1761 | _, a := newCompactionAgent(t, d) |
| 1762 | if err := a.CompactNow(context.Background(), ""); err != nil { |
| 1763 | t.Fatalf("CompactNow: %v", err) |
| 1764 | } |
| 1765 | if calls != 2 { |
| 1766 | t.Fatalf("owner consulted %d times, want 2 (chain, then strategy)", calls) |
| 1767 | } |
| 1768 | sc := sessionContents(a.Session()) |
| 1769 | if !strings.Contains(sc, "OWNER SUMMARY") || strings.Contains(sc, "CHAIN SUMMARY") { |
| 1770 | t.Fatalf("session = %.200q, want the strategy ruling persisted", sc) |
| 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | func TestCompactionCompleteSlotOwnerFailureIsFatal(t *testing.T) { |
| 1775 | client := &fakeDispatchClient{interceptFn: func(ev protocol.InterceptEvent, _ json.RawMessage) (protocol.InterceptResult, error) { |
| 1776 | if ev == protocol.EventCompactionComplete { |
| 1777 | return protocol.InterceptResult{}, errors.New("sidecar timeout") |
| 1778 | } |
| 1779 | return protocol.InterceptResult{Decision: protocol.DecisionContinue}, nil |
| 1780 | }} |
| 1781 | d := newExtSlotDispatcher(client, false, nil, nil, |
| 1782 | map[extension.Slot]string{extension.SlotCompaction: extTestPlugin}) |
| 1783 | _, a := newCompactionAgent(t, d) |
| 1784 | before := len(a.Session().Messages) |
| 1785 | err := a.CompactNow(context.Background(), "") |
| 1786 | if err == nil || !strings.Contains(err.Error(), "extension fake failed at compaction.complete") { |
| 1787 | t.Fatalf("CompactNow err = %v, want the owner failure", err) |
| 1788 | } |
| 1789 | if len(a.Session().Messages) != before { |
| 1790 | t.Fatal("failed owner still rewrote the session") |
| 1791 | } |
| 1792 | } |
| 1793 | |
| 1794 | // TestSlotUnownedKeepsFastPath pins the no-owner case: a chain-only plugin |
| 1795 | // (intercepts but no replaces) leaves the slot unowned, and the original |
| 1796 | // values reach the provider byte-identically. |
| 1797 | func TestSlotUnownedKeepsFastPath(t *testing.T) { |
| 1798 | client := &fakeDispatchClient{} |
| 1799 | d := newExtSlotDispatcher(client, false, nil, |
| 1800 | []extension.InterceptorPoint{extension.PointContextPrepare, extension.PointProviderRequest}, nil) |
| 1801 | streams := [][]provider.Chunk{ |
| 1802 | {{Type: provider.ChunkText, Text: "one"}, {Type: provider.ChunkDone}}, |
| 1803 | {{Type: provider.ChunkText, Text: "two"}, {Type: provider.ChunkDone}}, |
| 1804 | } |
| 1805 | withExt := &mockProvider{name: "p", streams: streams} |
| 1806 | a := New(withExt, tool.NewRegistry(), NewSession("sys"), Options{Extensions: d}, event.Discard) |
| 1807 | baseline := &mockProvider{name: "p", streams: streams} |
| 1808 | b := New(baseline, tool.NewRegistry(), NewSession("sys"), Options{}, event.Discard) |
| 1809 | for _, input := range []string{"first", "second"} { |
| 1810 | if err := a.Run(context.Background(), input); err != nil { |
| 1811 | t.Fatalf("Run(%q): %v", input, err) |
| 1812 | } |
| 1813 | if err := b.Run(context.Background(), input); err != nil { |
| 1814 | t.Fatalf("baseline Run(%q): %v", input, err) |
| 1815 | } |
| 1816 | } |
| 1817 | for i := range baseline.requests { |
| 1818 | if got, want := requestContents(withExt.requests[i]), requestContents(baseline.requests[i]); got != want { |
| 1819 | t.Fatalf("request %d differs from the no-extension baseline:\ngot:\n%s\nwant:\n%s", i+1, got, want) |
| 1820 | } |
| 1821 | } |
| 1822 | } |
| 1823 |