Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Refactor harness framework (#16271)

Yingfeng706e0d2d0625
diff --git a/internal/harness/README.md b/internal/harness/README.md
index 034fdedad0..6374a5f507 100644
--- a/internal/harness/README.md
+++ b/internal/harness/README.md
@@ -128,8 +128,10 @@ The framework is organized into three logical layers:
├─────────────────────────────────────────────────────────────────┤
│ Layer 2: AgentCore ADK (ReActAgent, Runner, Middleware, Tools) │
│ ├─ ReActAgent with iterate-loop or graph-backed exec │
-│ ├─ Middleware system (9 hook points) │
+│ ├─ Middleware system (5 hooks + ToolContributor) │
│ ├─ Tool system (standard + enhanced + tool_registry) │
+│ │ └─ ToolInvokeMiddleware (onion model: timeout, │
+│ │ retry, fallback, approval, rate-limit) │
│ ├─ flowAgent (sub-agent management, transfer routing) │
│ └─ workflowAgent (Sequential / Parallel / Loop) │
├─────────────────────────────────────────────────────────────────┤
@@ -477,19 +479,27 @@ ToolsConfig: &agentcore.ToolsNodeConfig{
### Middleware System
-**ReActMiddleware** provides 9 hook points:
+**TypedReActMiddleware[M]** — the core middleware interface with 5 hook points:
| Hook | Signature | Purpose |
|---|---|---|
| `BeforeAgent` | `(ctx, *ReActAgentContext)` | Modify instruction, tools, return-directly map |
-| `AfterAgent` | `(ctx, state)` | Post-execution cleanup |
| `BeforeModelRewrite` | `(ctx, state, *ModelContext)` | Transform state before model call |
| `AfterModelRewrite` | `(ctx, state, *ModelContext)` | Transform state after model call |
-| `WrapModel` | `(ctx, ChatModel[M], *ModelContext)` → ChatModel[M] | Wrap the model call |
-| `WrapToolInvoke` | `(ctx, InvokableToolEndpoint, *ToolContext)` | Wrap sync tool invoke |
-| `WrapToolStream` | `(ctx, StreamableToolEndpoint, *ToolContext)` | Wrap streaming tool invoke |
-| `WrapEnhancedInvokableToolCall` | `(ctx, EnhancedInvokableToolEndpoint, *ToolContext)` | Wrap enhanced sync tool |
-| `WrapEnhancedStreamableToolCall` | `(ctx, EnhancedStreamableToolEndpoint, *ToolContext)` | Wrap enhanced streaming tool |
+| `AfterAgent` | `(ctx, state)` | Post-execution cleanup |
+| `WrapModel` | `(ctx, Model[M], *ModelContext)` → Model[M] | Decorate the model call |
+
+**ToolContributor[M]** — an **optional interface** that middlewares can implement to contribute tools to the agent. The agent loop automatically collects contributed tools during build, eliminating the need for manual `BindToConfig` calls:
+
+| Method | Purpose |
+|---|---|
+| `ContributeTools(ctx) []Tool` | Returns tools to add to the agent's tool set |
+| `ContributeToolInfos(ctx) []*schema.ToolInfo` | Returns structured ToolInfo entries to bind to the model |
+| `ContributeReturnDirectly(ctx) map[string]bool` | Returns tool names that cause the agent to exit immediately |
+
+Tool contribution is automatically merged with `config.Tools`. Middleware that contributed tools will have them available in the `ReActAgentContext.Tools` during `BeforeAgent` for inspection.
+
+**ToolInvokeMiddleware** (onion model) — a separate orthogonal system for tool-call level cross-cutting concerns (see [Tools section](#tools)).
Embed `BaseMiddleware[*schema.Message]` and override only needed hooks:
@@ -503,20 +513,39 @@ func (m *LoggingMiddleware) BeforeModelRewrite(ctx, state, mc) (context.Context,
}
```
+For middlewares that contribute tools, implement `ToolContributor` and optionally override `BeforeAgent` for non-tool configuration:
+
+```go
+type FilesystemMiddleware struct {
+ agentcore.BaseMiddleware[*schema.Message]
+ backend Backend
+}
+
+// Tools are auto-collected during agent build.
+func (m *FilesystemMiddleware) ContributeTools(ctx context.Context) []core.Tool {
+ return m.buildTools()
+}
+
+// BeforeAgent is still available for modifying instruction etc.
+func (m *FilesystemMiddleware) BeforeAgent(ctx context.Context, rc *core.ReActAgentContext) (context.Context, *core.ReActAgentContext, error) {
+ // Non-tool modifications go here
+ return ctx, rc, nil
+}
+```
+
**Prebuilt middlewares** (in `agentcore/middlewares/`):
-| Middleware | Purpose |
-|---|---|
-| `subagent` | Injects sub-agents as callable tools (LLM-driven delegation) |
-| `summarization` | Auto-compresses long conversation history on token overflow |
-| `reduction` | Offloads large tool results to backend storage |
-| `filesystem` | Provides read/write/edit/ls/grep/execute tools |
-| `skill` | Loads and executes skills from SKILL.md files |
-| `patchtoolcalls` | Fixes dangling tool calls in message history |
-| `plantask` | Task management CRUD for coding sessions |
-| `agentsmd` | Injects AGENTS.md file contents into model input |
-| `telemetry` | OpenTelemetry tracing/monitoring middleware *(removed in internal copy)* |
-| `dynamictool` | Dynamic tool registration and invocation |
+| Middleware | Tool Contribution | Purpose |
+|---|---|---|
+| `filesystem` | `ContributeTools` | Provides read/write/edit/ls/grep/execute tools |
+| `skill` | `ContributeTools` (Fork mode) + `BeforeAgent` (Inline mode) | Loads and executes skills from SKILL.md files |
+| `dynamictool/toolsearch` | `ContributeTools` + `ContributeToolInfos` | Dynamic tool search for large tool libraries |
+| `subagent` | `ContributeTools` (or `Init` for inheritance) | Injects sub-agents as callable tools |
+| `summarization` | — | Auto-compresses long conversation history |
+| `reduction` | — | Truncates large tool results |
+| `patchtoolcalls` | — | Fixes dangling tool calls in message history |
+| `plantask` | — | Task management CRUD for coding sessions |
+| `telemetry` | — (uses `WrapModel`) | OpenTelemetry tracing/monitoring |
### Runner
@@ -574,9 +603,9 @@ Dynamically injects sub-agents as callable tools that the parent LLM can invoke
```
Parent Agent (ReActAgent)
- ├─ Tools: [..., researcher_AgentTool, coder_AgentTool] ← injected by SubAgentMiddleware
+ ├─ Tools: [..., researcher_AgentTool, coder_AgentTool] ← auto-injected via ToolContributor
├─ Middlewares: [SubAgentMiddleware, ...]
- └─ Tool dispatch: executeInlineTools (ToolsConfig = nil→force inline)
+ └─ Tool dispatch: ToolsNode (merged config + contributed tools)
When LLM calls "researcher":
└─ researcher_AgentTool.Invoke(ctx, args)
@@ -584,6 +613,22 @@ Parent Agent (ReActAgent)
└─ Researcher Agent (independent ReAct loop)
```
+Sub-agent tools are automatically contributed via the `ToolContributor` interface. No manual `BindToConfig` call is needed for basic usage:
+
+```go
+saMW := subagent.New(specs, &subagent.Config{
+ EmitInternalEvents: true,
+ MaxDepth: 5,
+})
+
+// Just add to Middlewares — tools are auto-collected.
+cfg := &agentcore.ReActConfig[*schema.Message]{
+ Model: parentModel,
+ Middlewares: []agentcore.ReActMiddleware{saMW},
+}
+agent := agentcore.NewReActAgent(cfg)
+```
+
Three ways to declare sub-agents:
```go
@@ -626,7 +671,16 @@ mw := subagent.New(specs, &subagent.Config{
})
```
-**Design principle**: `BindToConfig()` sets `config.ToolsConfig = nil` to force inline tool dispatch (the only path that finds middleware-injected tools in `rc.Tools`). Both `BindToConfig` and middleware build are idempotent.
+**Middleware inheritance** — when a spec has `InheritParentMiddlewares: true`, call `Init(ctx, config)` after adding the middleware to `config.Middlewares`:
+
+```go
+saMW := subagent.New(specs, &subagent.Config{MaxDepth: 5})
+cfg.Middlewares = append(cfg.Middlewares, saMW)
+saMW.Init(ctx, cfg) // enables middleware inheritance for sub-agents
+agent := agentcore.NewReActAgent(cfg)
+```
+
+> **Migration note**: The legacy `BindToConfig` method is deprecated and retained for backward compatibility. New code should use the `ToolContributor` interface (automatic) or call `Init(ctx, config)` when middleware inheritance is needed.
### Sub-Agent Architecture: flowAgent vs SubAgentMiddleware
@@ -843,6 +897,7 @@ harness-go/
│ ├── resume_data.go # Resume data types
│ ├── utils.go # AsyncIterator, AsyncGenerator
│ ├── tool.go # AgentTool (sub-agent as Tool), depth guard
+│ ├── tool_contributor.go # ToolContributor interface + collection helpers
│ ├── instruction.go # Instruction management
│ │
│ ├── backend/ # Filesystem backend abstraction
@@ -996,7 +1051,7 @@ cfg := &agentcore.ReActConfig[*schema.Message]{
Model: parentModel,
Middlewares: []agentcore.ReActMiddleware{saMW, filesystem.New(...)},
}
-saMW.BindToConfig(cfg) // mandatory: injects tools, forces inline dispatch
+saMW.Init(ctx, cfg) // enables middleware inheritance
agent := agentcore.NewReActAgent(cfg)
```
diff --git a/internal/harness/core/agent_handoff.go b/internal/harness/core/agent_handoff.go
index f6abfc1da9..63527f8e4f 100644
--- a/internal/harness/core/agent_handoff.go
+++ b/internal/harness/core/agent_handoff.go
@@ -13,9 +13,13 @@ import (
// GenTransferInstruction generates an instruction string for agent transfer.
func GenTransferInstruction(names []string) string {
- if len(names) == 0 { return "" }
+ if len(names) == 0 {
+ return ""
+ }
s := "You can transfer to the following agents:\n"
- for _, n := range names { s += fmt.Sprintf("- %s\n", n) }
+ for _, n := range names {
+ s += fmt.Sprintf("- %s\n", n)
+ }
return s
}
@@ -27,8 +31,14 @@ func GenToolInstruction(name, desc string) string {
// exactRunPathMatch checks if two run paths are exactly equal.
// This prevents sub-agents from forging paths to access restricted agents.
func exactRunPathMatch(a, b []RunStep) bool {
- if len(a) != len(b) { return false }
- for i := range a { if !a[i].Equals(b[i]) { return false } }
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if !a[i].Equals(b[i]) {
+ return false
+ }
+ }
return true
}
@@ -66,9 +76,11 @@ type agentWithDeterministicTransfer struct {
toAgentNames []string
}
-func (a *agentWithDeterministicTransfer) Description(ctx context.Context) string { return a.agent.Description(ctx) }
-func (a *agentWithDeterministicTransfer) Name(ctx context.Context) string { return a.agent.Name(ctx) }
-func (a *agentWithDeterministicTransfer) GetType() string { return "DeterministicTransfer" }
+func (a *agentWithDeterministicTransfer) Description(ctx context.Context) string {
+ return a.agent.Description(ctx)
+}
+func (a *agentWithDeterministicTransfer) Name(ctx context.Context) string { return a.agent.Name(ctx) }
+func (a *agentWithDeterministicTransfer) GetType() string { return "DeterministicTransfer" }
func (a *agentWithDeterministicTransfer) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] {
if fa, ok := a.agent.(*flowAgent); ok {
@@ -85,9 +97,13 @@ type resumableAgentWithDeterministicTransfer struct {
toAgentNames []string
}
-func (a *resumableAgentWithDeterministicTransfer) Description(ctx context.Context) string { return a.agent.Description(ctx) }
-func (a *resumableAgentWithDeterministicTransfer) Name(ctx context.Context) string { return a.agent.Name(ctx) }
-func (a *resumableAgentWithDeterministicTransfer) GetType() string { return "DeterministicTransfer" }
+func (a *resumableAgentWithDeterministicTransfer) Description(ctx context.Context) string {
+ return a.agent.Description(ctx)
+}
+func (a *resumableAgentWithDeterministicTransfer) Name(ctx context.Context) string {
+ return a.agent.Name(ctx)
+}
+func (a *resumableAgentWithDeterministicTransfer) GetType() string { return "DeterministicTransfer" }
func (a *resumableAgentWithDeterministicTransfer) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] {
if fa, ok := a.agent.(*flowAgent); ok {
@@ -120,7 +136,9 @@ func forwardEventsAndAppendTransfer(iter *AsyncIterator[*AgentEvent], generator
var lastEvent *AgentEvent
for {
event, ok := iter.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
generator.Send(event)
lastEvent = event
}
@@ -227,7 +245,9 @@ func handleFlowAgentEvents(ctx context.Context, iter *AsyncIterator[*AgentEvent]
for {
event, ok := iter.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
if parentSession != nil && (event.Action == nil || event.Action.Interrupted == nil) {
copied := copyTypedAgentEvent(event)
@@ -297,19 +317,25 @@ func GenTransferMessages(ctx context.Context, agentName string) (*schema.Message
const EinoMsgIDKey = "_eino_msg_id"
func GetMessageID(extra map[string]any) string {
- if extra == nil { return "" }
+ if extra == nil {
+ return ""
+ }
id, _ := extra[EinoMsgIDKey].(string)
return id
}
func SetMessageID(extra map[string]any, id string) map[string]any {
- if extra == nil { extra = make(map[string]any) }
+ if extra == nil {
+ extra = make(map[string]any)
+ }
extra[EinoMsgIDKey] = id
return extra
}
func EnsureMessageID(extra map[string]any) map[string]any {
- if GetMessageID(extra) != "" { return extra }
+ if GetMessageID(extra) != "" {
+ return extra
+ }
return SetMessageID(extra, uuidV4())
}
diff --git a/internal/harness/core/agent_loop.go b/internal/harness/core/agent_loop.go
index 422bfc397a..890772d1aa 100644
--- a/internal/harness/core/agent_loop.go
+++ b/internal/harness/core/agent_loop.go
@@ -147,6 +147,7 @@ func (l *AgentLoop[T]) Wait() *AgentLoopState[T] {
// 1. A stop was committed AND exit was caused by stop (runErr==nil, CancelError, or capturedCancelErr).
// 2. A business interrupt occurred (InterruptError or interruptContexts).
// 3. Checkpoint is not skipped (skipCheckpoint not set), not idle, and store is available.
+//
// On normal completion (runErr==nil, no stop committed), no checkpoint is saved.
func (l *AgentLoop[T]) shouldSaveCheckpoint() bool {
if l.config.Store == nil || l.config.CheckpointID == "" {
diff --git a/internal/harness/core/agent_loop_config.go b/internal/harness/core/agent_loop_config.go
index cd3cc5323b..9da020177c 100644
--- a/internal/harness/core/agent_loop_config.go
+++ b/internal/harness/core/agent_loop_config.go
@@ -145,11 +145,11 @@ type GenInputResult[T any] struct {
// GenResumeResult contains the result of GenResume processing.
type GenResumeResult[T any] struct {
- RunCtx context.Context
- RunOpts []RunOption
- ResumeParams *ResumeParams
- Consumed []T
- Remaining []T
+ RunCtx context.Context
+ RunOpts []RunOption
+ ResumeParams *ResumeParams
+ Consumed []T
+ Remaining []T
}
type turnRunSpec[T any] struct {
diff --git a/internal/harness/core/agent_loop_stop.go b/internal/harness/core/agent_loop_stop.go
index 0da295e359..07520f0f40 100644
--- a/internal/harness/core/agent_loop_stop.go
+++ b/internal/harness/core/agent_loop_stop.go
@@ -257,4 +257,4 @@ func WithPushStrategy[T any](fn func(ctx context.Context, tc *TurnContext[T]) []
// ---- Deprecated aliases ----
func WithImmediateStop() StopOption { return WithImmediate() }
-func WithGracefulStop() StopOption { return WithGraceful() }
+func WithGracefulStop() StopOption { return WithGraceful() }
diff --git a/internal/harness/core/agent_loop_test.go b/internal/harness/core/agent_loop_test.go
index 911ff0fd66..7c552d9f38 100644
--- a/internal/harness/core/agent_loop_test.go
+++ b/internal/harness/core/agent_loop_test.go
@@ -27,7 +27,9 @@ func (a *turnLoopMockAgent) Description(_ context.Context) string { return "mock
func (a *turnLoopMockAgent) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] {
m := &mockModel{}
response := a.response
- if response == "" { response = "mock" }
+ if response == "" {
+ response = "mock"
+ }
m.addResp(response)
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: m})
agent.name = a.name
@@ -66,7 +68,9 @@ func (m *turnCancellableModel) Generate(ctx context.Context, msgs []Message, opt
func (m *turnCancellableModel) Stream(ctx context.Context, msgs []Message, opts ...modelOption) (*schema.StreamReader[Message], error) {
return m.inner.Stream(ctx, msgs, opts...)
}
-func (m *turnCancellableModel) BindTools(tools []*schema.ToolInfo) error { return m.inner.BindTools(tools) }
+func (m *turnCancellableModel) BindTools(tools []*schema.ToolInfo) error {
+ return m.inner.BindTools(tools)
+}
func newTurnCheckpointStore() *memStore { return &memStore{data: make(map[string][]byte)} }
@@ -74,14 +78,17 @@ func newTurnCheckpointStore() *memStore { return &memStore{data: make(map[string
func simpleTurnLoop(onEvents func(context.Context, *TurnContext[string], *AsyncIterator[*AgentEvent]) error) *AgentLoop[string] {
return NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items[:1], Remaining: items[1:],
}, nil
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
- m := &mockModel{}; m.addResp("Echo: " + consumed[0])
+ m := &mockModel{}
+ m.addResp("Echo: " + consumed[0])
return NewReActAgent(&ReActConfig[*schema.Message]{Model: m}), nil
},
OnAgentEvents: onEvents,
@@ -97,13 +104,17 @@ func newAndRunTurnLoop[T any](ctx context.Context, cfg AgentLoopConfig[T]) *Agen
// genInputConsumeAll consumes all items at once.
func genInputConsumeAll(_ context.Context, _ *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}}, Consumed: items, Remaining: nil}, nil
}
// genInputConsumeFirst consumes the first item, leaves rest for later.
func genInputConsumeFirst(_ context.Context, _ *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: []string{items[0]},
@@ -113,7 +124,9 @@ func genInputConsumeFirst(_ context.Context, _ *AgentLoop[string], items []strin
// genInputConsumeAllWithMsg consumes all items and produces a user message.
func genInputConsumeAllWithMsg(_ context.Context, _ *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items,
@@ -150,11 +163,11 @@ func newTestStore() *memStore {
// turnLoopCancellableMockAgent is a mock Agent that supports cancel observation.
type turnLoopCancellableMockAgent struct {
- name string
- runFunc func(ctx context.Context, input *AgentInput) (*AgentOutput, error)
+ name string
+ runFunc func(ctx context.Context, input *AgentInput) (*AgentOutput, error)
onCancel func(cc *cancelContext)
- cancel context.CancelFunc
- mu sync.Mutex
+ cancel context.CancelFunc
+ mu sync.Mutex
}
func (a *turnLoopCancellableMockAgent) Name(_ context.Context) string { return a.name }
@@ -227,8 +240,10 @@ type turnLoopInterruptAgent struct {
interruptInfo any
}
-func (a *turnLoopInterruptAgent) Name(_ context.Context) string { return "InterruptAgent" }
-func (a *turnLoopInterruptAgent) Description(_ context.Context) string { return "agent that interrupts" }
+func (a *turnLoopInterruptAgent) Name(_ context.Context) string { return "InterruptAgent" }
+func (a *turnLoopInterruptAgent) Description(_ context.Context) string {
+ return "agent that interrupts"
+}
func (a *turnLoopInterruptAgent) Run(ctx context.Context, _ *AgentInput, _ ...RunOption) *AsyncIterator[*AgentEvent] {
iter, gen := NewAsyncIteratorPair[*AgentEvent]()
go func() {
@@ -246,28 +261,37 @@ func containsString(s, substr string) bool {
func TestTurnLoop_NewPanicsWithNilGenInput(t *testing.T) {
defer func() {
- if r := recover(); r == nil { t.Fatal("expected panic") }
+ if r := recover(); r == nil {
+ t.Fatal("expected panic")
+ }
}()
NewAgentLoop[string](AgentLoopConfig[string]{PrepareAgent: func(_ context.Context, _ *AgentLoop[string], _ []string) (Agent, error) { return nil, nil }})
}
func TestTurnLoop_NewPanicsWithNilPrepareAgent(t *testing.T) {
defer func() {
- if r := recover(); r == nil { t.Fatal("expected panic") }
+ if r := recover(); r == nil {
+ t.Fatal("expected panic")
+ }
}()
- NewAgentLoop[string](AgentLoopConfig[string]{GenInput: func(_ context.Context, _ *AgentLoop[string], _ []string) (*GenInputResult[string], error) { return nil, nil }})
+ NewAgentLoop[string](AgentLoopConfig[string]{GenInput: func(_ context.Context, _ *AgentLoop[string], _ []string) (*GenInputResult[string], error) {
+ return nil, nil
+ }})
}
// ======================== Basic Push-Stop-Run ========================
func TestTurnLoop_PushRunAndWait(t *testing.T) {
tl := simpleTurnLoop(nil)
- tl.Push("a"); tl.Push("b")
+ tl.Push("a")
+ tl.Push("b")
ctx := context.Background()
tl.Stop()
tl.Run(ctx)
result := tl.Wait()
- if result == nil { t.Fatal("nil result") }
+ if result == nil {
+ t.Fatal("nil result")
+ }
t.Logf("basic: unhandled=%d", len(result.UnhandledItems))
}
@@ -277,14 +301,22 @@ func TestTurnLoop_StopCause(t *testing.T) {
tl.Stop(WithStopCause("max_tokens"))
tl.Run(context.Background())
result := tl.Wait()
- if result.StopCause != "max_tokens" { t.Errorf("StopCause = %q", result.StopCause) }
+ if result.StopCause != "max_tokens" {
+ t.Errorf("StopCause = %q", result.StopCause)
+ }
}
func TestTurnLoop_OnAgentEventsCalled(t *testing.T) {
var called atomic.Bool
tl := simpleTurnLoop(func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
called.Store(true)
- for { ev, ok := events.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := events.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
return nil
})
ctx := context.Background()
@@ -293,7 +325,9 @@ func TestTurnLoop_OnAgentEventsCalled(t *testing.T) {
time.Sleep(50 * time.Millisecond)
tl.Stop()
tl.Wait()
- if !called.Load() { t.Error("OnAgentEvents not called") }
+ if !called.Load() {
+ t.Error("OnAgentEvents not called")
+ }
}
func TestTurnLoop_OnAgentEventsReturnsError(t *testing.T) {
@@ -316,7 +350,9 @@ func TestTurnLoop_OnAgentEventsReturnsError(t *testing.T) {
func TestTurnLoop_GenInputErrors(t *testing.T) {
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return nil, errors.New("gen_input_err")
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
@@ -327,7 +363,9 @@ func TestTurnLoop_GenInputErrors(t *testing.T) {
tl.Stop()
tl.Run(context.Background())
result := tl.Wait()
- if result.ExitReason == nil { t.Log("no exit error (may not reach GenInput before stop)") }
+ if result.ExitReason == nil {
+ t.Log("no exit error (may not reach GenInput before stop)")
+ }
}
func TestTurnLoop_PrepareAgentErrors(t *testing.T) {
@@ -343,14 +381,18 @@ func TestTurnLoop_PrepareAgentErrors(t *testing.T) {
tl.Stop()
tl.Run(context.Background())
result := tl.Wait()
- if result.ExitReason == nil { t.Log("no exit error (may not reach PrepareAgent)") }
+ if result.ExitReason == nil {
+ t.Log("no exit error (may not reach PrepareAgent)")
+ }
}
// ======================== Multiple Items ========================
func TestTurnLoop_MultipleItems(t *testing.T) {
tl := simpleTurnLoop(nil)
- for i := 0; i < 10; i++ { tl.Push(fmt.Sprintf("item-%d", i)) }
+ for i := 0; i < 10; i++ {
+ tl.Push(fmt.Sprintf("item-%d", i))
+ }
tl.Stop()
tl.Run(context.Background())
result := tl.Wait()
@@ -377,14 +419,17 @@ func TestTurnLoop_WithCheckpoint(t *testing.T) {
store := newTurnCheckpointStore()
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items[:1], Remaining: items[1:],
}, nil
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
- m := &mockModel{}; m.addResp("cp:" + consumed[0])
+ m := &mockModel{}
+ m.addResp("cp:" + consumed[0])
return NewReActAgent(&ReActConfig[*schema.Message]{Model: m}), nil
},
Store: store,
@@ -412,7 +457,9 @@ func TestTurnLoop_StopWithNoItems(t *testing.T) {
tl.Stop(WithStopCause("empty"))
tl.Run(context.Background())
result := tl.Wait()
- if result.StopCause != "empty" { t.Errorf("StopCause = %q", result.StopCause) }
+ if result.StopCause != "empty" {
+ t.Errorf("StopCause = %q", result.StopCause)
+ }
}
func TestTurnLoop_StopMultipleTimes(t *testing.T) {
@@ -442,7 +489,8 @@ func TestTurnLoop_ContextCancel(t *testing.T) {
func TestTurnLoop_PushAfterStop(t *testing.T) {
tl := simpleTurnLoop(nil)
- tl.Push("a"); tl.Push("b")
+ tl.Push("a")
+ tl.Push("b")
tl.Stop()
tl.Push("c")
tl.Run(context.Background())
@@ -455,7 +503,9 @@ func TestTurnLoop_WithToolAgent(t *testing.T) {
tool := &mockTool{name: "calc", desc: "calculator"}
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items[:1], Remaining: items[1:],
@@ -484,15 +534,19 @@ func TestTurnLoop_WithToolAgent(t *testing.T) {
func TestTurnLoop_GenInputAllConsumed(t *testing.T) {
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}}, Consumed: items, Remaining: nil}, nil
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
- m := &mockModel{}; m.addResp("all")
+ m := &mockModel{}
+ m.addResp("all")
return NewReActAgent(&ReActConfig[*schema.Message]{Model: m}), nil
},
})
- tl.Push("1"); tl.Push("2")
+ tl.Push("1")
+ tl.Push("2")
tl.Stop()
tl.Run(context.Background())
tl.Wait()
@@ -501,18 +555,23 @@ func TestTurnLoop_GenInputAllConsumed(t *testing.T) {
func TestTurnLoop_GenInputOneByOne(t *testing.T) {
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
- Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
+ Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items[:1], Remaining: items[1:],
}, nil
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
- m := &mockModel{}; m.addResp("one:" + consumed[0])
+ m := &mockModel{}
+ m.addResp("one:" + consumed[0])
return NewReActAgent(&ReActConfig[*schema.Message]{Model: m}), nil
},
})
- tl.Push("x"); tl.Push("y"); tl.Push("z")
+ tl.Push("x")
+ tl.Push("y")
+ tl.Push("z")
tl.Stop()
tl.Run(context.Background())
result := tl.Wait()
@@ -540,14 +599,17 @@ func TestTurnLoop_GenInputConsumedNone(t *testing.T) {
func TestTurnLoop_InterceptedItems(t *testing.T) {
tl := NewAgentLoop(AgentLoopConfig[string]{
GenInput: func(ctx context.Context, loop *AgentLoop[string], items []string) (*GenInputResult[string], error) {
- if len(items) == 0 { return nil, nil }
+ if len(items) == 0 {
+ return nil, nil
+ }
return &GenInputResult[string]{
Input: &AgentInput{Messages: []Message{schema.UserMessage(items[0])}},
Consumed: items[:1], Remaining: items[1:],
}, nil
},
PrepareAgent: func(ctx context.Context, loop *AgentLoop[string], consumed []string) (Agent, error) {
- m := &mockModel{}; m.addResp("intercepted")
+ m := &mockModel{}
+ m.addResp("intercepted")
return NewReActAgent(&ReActConfig[*schema.Message]{Model: m}), nil
},
})
@@ -565,7 +627,9 @@ func TestTurnLoop_NoPushBeforeRun(t *testing.T) {
tl.Stop()
tl.Run(context.Background())
result := tl.Wait()
- if result == nil { t.Fatal("nil result") }
+ if result == nil {
+ t.Fatal("nil result")
+ }
}
func TestTurnLoop_DoubleRunPanics(t *testing.T) {
@@ -584,7 +648,9 @@ func TestTurnLoop_RunThenStopThenWait(t *testing.T) {
tl.Run(ctx)
tl.Stop()
result := tl.Wait()
- if result == nil { t.Fatal("nil result") }
+ if result == nil {
+ t.Fatal("nil result")
+ }
}
// ======================== edge-case tests ========================
@@ -819,7 +885,9 @@ func TestTurnLoop_OnAgentEventsReceivesEvents(t *testing.T) {
mu.Unlock()
for {
event, ok := events.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
mu.Lock()
receivedEvents = append(receivedEvents, event)
mu.Unlock()
@@ -845,6 +913,7 @@ func TestTurnLoop_OnAgentEventsReceivesEvents(t *testing.T) {
t.Error("should have received consumed items")
}
}
+
// ======================== Stop with Checkpoint Cancel ========================
func TestTurnLoop_StopCheckPointIDInCancelError(t *testing.T) {
@@ -854,7 +923,7 @@ func TestTurnLoop_StopCheckPointIDInCancelError(t *testing.T) {
store := newTestStore()
slowModel := &cancelTestChatModel{
- delayNs: int64(500 * time.Millisecond),
+ delayNs: int64(500 * time.Millisecond),
startedChan: modelStarted,
doneChan: make(chan struct{}, 1),
}
@@ -890,7 +959,7 @@ func TestTurnLoop_CancelError_CapturedIndependentlyOfCallback(t *testing.T) {
store := newTestStore()
slowModel := &cancelTestChatModel{
- delayNs: int64(500 * time.Millisecond),
+ delayNs: int64(500 * time.Millisecond),
startedChan: modelStarted,
doneChan: make(chan struct{}, 1),
}
@@ -909,7 +978,9 @@ func TestTurnLoop_CancelError_CapturedIndependentlyOfCallback(t *testing.T) {
OnAgentEvents: func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
for {
_, ok := events.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
}
return nil // swallow everything
},
@@ -932,7 +1003,7 @@ func TestTurnLoop_StopWithoutCheckpointIDDoesNotPersist(t *testing.T) {
store := newTestStore()
slowModel := &cancelTestChatModel{
- delayNs: int64(500 * time.Millisecond),
+ delayNs: int64(500 * time.Millisecond),
startedChan: modelStarted,
doneChan: make(chan struct{}, 1),
}
@@ -1008,7 +1079,9 @@ func TestTurnLoop_PushFromOnAgentEvents(t *testing.T) {
OnAgentEvents: func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
for {
_, ok := events.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
}
count := atomic.AddInt32(&pushCount, 1)
if count == 1 {
@@ -1051,9 +1124,13 @@ func TestNewTurnLoop_PushBeforeRun(t *testing.T) {
})
ok, _ := loop.Push("msg1")
- if !ok { t.Error("Push returned false") }
+ if !ok {
+ t.Error("Push returned false")
+ }
ok, _ = loop.Push("msg2")
- if !ok { t.Error("Push returned false") }
+ if !ok {
+ t.Error("Push returned false")
+ }
loop.Run(context.Background())
@@ -1216,7 +1293,9 @@ func TestTurnLoop_CtxPropagation(t *testing.T) {
eventsCtxVal = v
}
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
tc.Loop.Stop()
return nil
@@ -1265,7 +1344,9 @@ func TestTurnLoop_TurnContext_StoppedChannel(t *testing.T) {
t.Error("timed out waiting for Stopped channel")
}
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
return nil
},
@@ -1370,7 +1451,9 @@ func TestTurnLoop_StopCause_InTurnContext(t *testing.T) {
t.Error("timed out waiting for Stopped channel")
}
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
return nil
},
@@ -1412,7 +1495,9 @@ func TestTurnLoop_StopCause_FirstNonEmptyWins(t *testing.T) {
OnAgentEvents: func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
close(agentStarted)
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
return nil
},
@@ -1444,9 +1529,13 @@ func TestTurnLoop_StopBeforeRun_PushThenStop(t *testing.T) {
})
ok, _ := loop.Push("item1")
- if !ok { t.Error("Push returned false") }
+ if !ok {
+ t.Error("Push returned false")
+ }
ok, _ = loop.Push("item2")
- if !ok { t.Error("Push returned false") }
+ if !ok {
+ t.Error("Push returned false")
+ }
loop.Stop()
loop.Run(context.Background())
@@ -1481,7 +1570,9 @@ func TestTurnLoop_SkipCheckpoint_Sticky(t *testing.T) {
OnAgentEvents: func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
close(agentStarted)
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
return nil
},
@@ -1497,7 +1588,6 @@ func TestTurnLoop_SkipCheckpoint_Sticky(t *testing.T) {
t.Logf("skip checkpoint sticky: exit=%v", exit.ExitReason)
}
-
// ======================== GenInput Error Recovery ========================
func TestTurnLoop_GenInputError_RecoverItems(t *testing.T) {
@@ -1535,7 +1625,9 @@ func TestTurnLoop_CheckpointNotFound_FreshStart(t *testing.T) {
PrepareAgent: prepareTestAgent,
OnAgentEvents: func(ctx context.Context, tc *TurnContext[string], events *AsyncIterator[*AgentEvent]) error {
for {
- if _, ok := events.Next(); !ok { break }
+ if _, ok := events.Next(); !ok {
+ break
+ }
}
tc.Loop.Stop()
return nil
@@ -1565,7 +1657,9 @@ func TestAttack_TurnBuffer_WakeupDoesNotLoseItems(t *testing.T) {
var got []string
for i := 0; i < 3; i++ {
val, ok := tb.Receive()
- if !ok { t.Fatal("expected ok") }
+ if !ok {
+ t.Fatal("expected ok")
+ }
got = append(got, val)
}
@@ -1575,4 +1669,3 @@ func TestAttack_TurnBuffer_WakeupDoesNotLoseItems(t *testing.T) {
}
// ======================== AgentLoop Preempt During Planning ========================
-
diff --git a/internal/harness/core/agent_tool_test.go b/internal/harness/core/agent_tool_test.go
index d93af838f1..d11448f760 100644
--- a/internal/harness/core/agent_tool_test.go
+++ b/internal/harness/core/agent_tool_test.go
@@ -28,9 +28,9 @@ func TestAgentTool_BasicInvocation(t *testing.T) {
firstCall: true,
}
parent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: parentM,
- Tools: []Tool{agentTool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
+ Model: parentM,
+ Tools: []Tool{agentTool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
MaxIterations: 3,
}).WithName("parent")
@@ -78,9 +78,9 @@ func TestAgentTool_NestedWithCheckpoint(t *testing.T) {
firstCall: true,
}
parent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: parentM,
- Tools: []Tool{agentTool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
+ Model: parentM,
+ Tools: []Tool{agentTool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
MaxIterations: 3,
}).WithName("parent_cp")
@@ -124,9 +124,9 @@ func TestAgentTool_EventForwarding(t *testing.T) {
firstCall: true,
}
parent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: parentM,
- Tools: []Tool{agentTool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
+ Model: parentM,
+ Tools: []Tool{agentTool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
MaxIterations: 3,
}).WithName("forward_parent")
@@ -159,9 +159,9 @@ func TestAgentTool_ResumeAfterInterrupt(t *testing.T) {
}
tool := &mockTool{name: "resume_inner_tool", desc: "tool for resume test"}
innerAgent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: innerM,
- Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ Model: innerM,
+ Tools: []Tool{tool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 3,
}).WithName("resume_inner").WithDescription("interruptible inner agent")
@@ -175,9 +175,9 @@ func TestAgentTool_ResumeAfterInterrupt(t *testing.T) {
firstCall: true,
}
parent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: parentM,
- Tools: []Tool{agentTool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
+ Model: parentM,
+ Tools: []Tool{agentTool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{agentTool}},
MaxIterations: 3,
}).WithName("resume_parent")
diff --git a/internal/harness/core/agentcore_full_test.go b/internal/harness/core/agentcore_full_test.go
index 4c31498e8d..c6a123709d 100644
--- a/internal/harness/core/agentcore_full_test.go
+++ b/internal/harness/core/agentcore_full_test.go
@@ -15,25 +15,34 @@ import (
// reActAgentSetup creates a basic agent with given model and optional tools
func reActAgentSetup(model Model[*schema.Message], tools []Tool) *ReActAgent[*schema.Message] {
cfg := &ReActConfig[*schema.Message]{Model: model}
- if len(tools) > 0 { cfg.Tools = tools }
+ if len(tools) > 0 {
+ cfg.Tools = tools
+ }
a := NewReActAgent(cfg)
a.name = "test_cma"
return a
}
func TestReActAgent_BasicGenerate(t *testing.T) {
- model := &mockModel{}; model.addResp("Hello!")
+ model := &mockModel{}
+ model.addResp("Hello!")
agent := reActAgentSetup(model, nil)
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("Hi")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Fatal("expected events") }
+ if len(events) == 0 {
+ t.Fatal("expected events")
+ }
found := false
for _, e := range events {
if e.Output != nil && e.Output.MessageOutput != nil {
- if e.Output.MessageOutput.Message.Content == "Hello!" { found = true }
+ if e.Output.MessageOutput.Message.Content == "Hello!" {
+ found = true
+ }
}
}
- if !found { t.Error("expected Hello! in output") }
+ if !found {
+ t.Error("expected Hello! in output")
+ }
}
func TestReActAgent_ToolCallAndResponse(t *testing.T) {
@@ -47,7 +56,9 @@ func TestReActAgent_ToolCallAndResponse(t *testing.T) {
agent := reActAgentSetup(wrapperModel, []Tool{tool})
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("Search")}})
drainAgentEvents(t, iter)
- if !tool.executed { t.Error("tool not executed") }
+ if !tool.executed {
+ t.Error("tool not executed")
+ }
}
func TestReActAgent_MaxIterationsExceeded(t *testing.T) {
@@ -59,17 +70,30 @@ func TestReActAgent_MaxIterationsExceeded(t *testing.T) {
agent.config.Model = loopModel
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("Loop")}})
var lastErr error
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { lastErr = ev.Err } }
- if lastErr == nil { t.Error("expected max iterations error") }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
+ }
+ if lastErr == nil {
+ t.Error("expected max iterations error")
+ }
}
func TestReActAgent_ZeroMaxIterations(t *testing.T) {
- model := &mockModel{}; model.addResp("zero iter")
+ model := &mockModel{}
+ model.addResp("zero iter")
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model, MaxIterations: 0})
agent.name = "zero_iter"
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events even with zero iterations") }
+ if len(events) == 0 {
+ t.Error("expected events even with zero iterations")
+ }
}
func TestReActAgent_ReturnDirectly(t *testing.T) {
@@ -85,22 +109,29 @@ func TestReActAgent_ReturnDirectly(t *testing.T) {
agent.name = "rd"
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
}
// ======================== Runner Tests ========================
func TestRunner_CreateAndQuery(t *testing.T) {
- model := &mockModel{}; model.addResp("Runner query")
+ model := &mockModel{}
+ model.addResp("Runner query")
agent := reActAgentSetup(model, nil)
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
iter := runner.Query(context.Background(), "Test query")
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
}
func TestRunner_MultipleRuns(t *testing.T) {
- model := &mockModel{}; model.addResp("1"); model.addResp("2")
+ model := &mockModel{}
+ model.addResp("1")
+ model.addResp("2")
agent := reActAgentSetup(model, nil)
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
@@ -108,11 +139,14 @@ func TestRunner_MultipleRuns(t *testing.T) {
e1 := drainAgentEvents(t, iter1)
iter2 := runner.Run(context.Background(), []Message{schema.UserMessage("B")})
e2 := drainAgentEvents(t, iter2)
- if len(e1) == 0 || len(e2) == 0 { t.Errorf("events: %d %d", len(e1), len(e2)) }
+ if len(e1) == 0 || len(e2) == 0 {
+ t.Errorf("events: %d %d", len(e1), len(e2))
+ }
}
func TestRunner_WithRunOptions(t *testing.T) {
- model := &mockModel{}; model.addResp("Options")
+ model := &mockModel{}
+ model.addResp("Options")
agent := reActAgentSetup(model, nil)
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
iter := runner.Run(context.Background(), []Message{schema.UserMessage("opts")}, WithSessionValues(map[string]any{"k": "v"}))
@@ -120,7 +154,8 @@ func TestRunner_WithRunOptions(t *testing.T) {
}
func TestRunner_WithCheckpoint(t *testing.T) {
- model := &mockModel{}; model.addResp("cp test")
+ model := &mockModel{}
+ model.addResp("cp test")
agent := reActAgentSetup(model, nil)
store := &memStore{}
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent, CheckPointStore: store})
@@ -130,37 +165,48 @@ func TestRunner_WithCheckpoint(t *testing.T) {
func TestRunner_NilAgent(t *testing.T) {
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: nil})
- if runner == nil { t.Fatal("nil runner") }
+ if runner == nil {
+ t.Fatal("nil runner")
+ }
}
// ======================== Agent Tool Tests ========================
func TestAgentTool_Basic(t *testing.T) {
- subModel := &mockModel{}; subModel.addResp("Sub result")
+ subModel := &mockModel{}
+ subModel.addResp("Sub result")
subAgent := reActAgentSetup(subModel, nil)
subAgent.name = "sub_tool"
ctx := context.Background()
agentTool := NewAgentTool(ctx, subAgent)
- if agentTool.Name() != "sub_tool" { t.Errorf("tool name = %s", agentTool.Name()) }
+ if agentTool.Name() != "sub_tool" {
+ t.Errorf("tool name = %s", agentTool.Name())
+ }
result, err := agentTool.Invoke(ctx, `{"query":"test"}`)
- if err != nil { t.Fatalf("invoke: %v", err) }
+ if err != nil {
+ t.Fatalf("invoke: %v", err)
+ }
t.Logf("agent tool result: %q", result)
}
func TestAgentTool_WithFullChatHistory(t *testing.T) {
- subModel := &mockModel{}; subModel.addResp("history result")
+ subModel := &mockModel{}
+ subModel.addResp("history result")
subAgent := reActAgentSetup(subModel, nil)
subAgent.name = "history_tool"
ctx := context.Background()
agentTool := NewAgentTool(ctx, subAgent, WithFullChatHistoryAsInput())
_, err := agentTool.Invoke(ctx, `{"query":"test"}`)
- if err != nil { t.Fatal(err) }
+ if err != nil {
+ t.Fatal(err)
+ }
}
func TestAgentTool_FromRunner(t *testing.T) {
- subModel := &mockModel{}; subModel.addResp("Sub result")
+ subModel := &mockModel{}
+ subModel.addResp("Sub result")
subAgent := reActAgentSetup(subModel, nil)
subAgent.name = "research"
@@ -178,7 +224,9 @@ func TestAgentTool_FromRunner(t *testing.T) {
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: mainAgent})
iter := runner.Query(ctx, "Research AI")
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
}
// ======================== ToolsNode Tests ========================
@@ -192,8 +240,12 @@ func TestToolsNode_Basic(t *testing.T) {
ToolCalls: []schema.ToolCall{{ID: "c1", Function: schema.ToolCallFunction{Name: "greet", Arguments: `{"name":"world"}`}}},
}
results, action, err := tn.Execute(context.Background(), resp, nil, nil)
- if err != nil { t.Fatalf("Execute: %v", err) }
- if len(results) != 1 { t.Errorf("expected 1 result, got %d", len(results)) }
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ if len(results) != 1 {
+ t.Errorf("expected 1 result, got %d", len(results))
+ }
_ = action
}
@@ -201,8 +253,12 @@ func TestToolsNode_NoToolCalls(t *testing.T) {
tn := NewToolsNode[*schema.Message](&ToolsNodeConfig{Tools: []Tool{&mockTool{name: "t", desc: "t"}}})
resp := &schema.Message{Role: schema.RoleAssistant, Content: "Just text"}
results, action, err := tn.Execute(context.Background(), resp, nil, nil)
- if err != nil { t.Fatalf("Execute: %v", err) }
- if len(results) != 0 { t.Errorf("expected 0 results, got %d", len(results)) }
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ if len(results) != 0 {
+ t.Errorf("expected 0 results, got %d", len(results))
+ }
_ = action
}
@@ -213,14 +269,18 @@ func TestToolsNode_ToolNotFound(t *testing.T) {
ToolCalls: []schema.ToolCall{{ID: "c1", Function: schema.ToolCallFunction{Name: "nonexistent", Arguments: "{}"}}},
}
results, action, err := tn.Execute(context.Background(), resp, nil, nil)
- if err != nil { t.Fatalf("unexpected error: %v", err) }
- if len(results) != 1 { t.Errorf("expected 1 result, got %d", len(results)) }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(results) != 1 {
+ t.Errorf("expected 1 result, got %d", len(results))
+ }
_ = action
}
func TestToolsNode_ReturnDirectly(t *testing.T) {
tn := NewToolsNode[*schema.Message](&ToolsNodeConfig{
- Tools: []Tool{&mockTool{name: "quick", desc: "quick"}},
+ Tools: []Tool{&mockTool{name: "quick", desc: "quick"}},
ReturnDirectly: map[string]bool{"quick": true},
})
resp := &schema.Message{
@@ -228,14 +288,17 @@ func TestToolsNode_ReturnDirectly(t *testing.T) {
ToolCalls: []schema.ToolCall{{ID: "c1", Function: schema.ToolCallFunction{Name: "quick", Arguments: "{}"}}},
}
_, action, err := tn.Execute(context.Background(), resp, nil, nil)
- if err != nil { t.Fatalf("Execute: %v", err) }
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
_ = action
}
// ======================== Retry / Failover ========================
func TestReActAgent_RetrySucceeds(t *testing.T) {
- inner := &mockModel{}; inner.addResp("final")
+ inner := &mockModel{}
+ inner.addResp("final")
retryM := &retryModel{inner: inner, failAttempts: 2}
agent := reActAgentSetup(retryM, nil)
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
@@ -243,12 +306,21 @@ func TestReActAgent_RetrySucceeds(t *testing.T) {
}
func TestReActAgent_RetryExhausted(t *testing.T) {
- inner := &mockModel{}; inner.addResp("never")
+ inner := &mockModel{}
+ inner.addResp("never")
retryM := &retryModel{inner: inner, failAttempts: 100}
agent := reActAgentSetup(retryM, nil)
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
var lastErr error
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { lastErr = ev.Err } }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
+ }
_ = lastErr
}
@@ -257,8 +329,18 @@ func TestReActAgent_AlwaysFails(t *testing.T) {
agent := reActAgentSetup(failing, nil)
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("hello")}})
var lastErr error
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { lastErr = ev.Err } }
- if lastErr == nil { t.Error("expected error from failing model") }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
+ }
+ if lastErr == nil {
+ t.Error("expected error from failing model")
+ }
}
// ======================== Interrupt Tests ========================
@@ -284,48 +366,72 @@ func TestInterrupt_WithResumeData(t *testing.T) {
// ======================== Workflow Tests ========================
func TestWorkflow_SequentialAgents(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("A1")
- m2 := &mockModel{}; m2.addResp("A2")
- a1 := reActAgentSetup(m1, nil); a1.name = "a1"
- a2 := reActAgentSetup(m2, nil); a2.name = "a2"
+ m1 := &mockModel{}
+ m1.addResp("A1")
+ m2 := &mockModel{}
+ m2.addResp("A2")
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "a1"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "a2"
ctx := context.Background()
wf, err := NewSequential(ctx, &SequentialConfig{Name: "seq", Description: "test", SubAgents: []Agent{a1, a2}})
- if err != nil { t.Fatalf("NewSequential: %v", err) }
+ if err != nil {
+ t.Fatalf("NewSequential: %v", err)
+ }
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
t.Logf("sequential: %d events", len(events))
}
func TestWorkflow_ParallelAgents(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("P1")
- m2 := &mockModel{}; m2.addResp("P2")
- a1 := reActAgentSetup(m1, nil); a1.name = "p1"
- a2 := reActAgentSetup(m2, nil); a2.name = "p2"
+ m1 := &mockModel{}
+ m1.addResp("P1")
+ m2 := &mockModel{}
+ m2.addResp("P2")
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "p1"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "p2"
ctx := context.Background()
wf, err := NewParallel(ctx, &ParallelConfig{Name: "par", Description: "test", SubAgents: []Agent{a1, a2}})
- if err != nil { t.Fatalf("NewParallel: %v", err) }
+ if err != nil {
+ t.Fatalf("NewParallel: %v", err)
+ }
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
}
func TestWorkflow_LoopAgents(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("Main")
- m2 := &mockModel{}; m2.addResp("Critique")
- a1 := reActAgentSetup(m1, nil); a1.name = "main"
- a2 := reActAgentSetup(m2, nil); a2.name = "critique"
+ m1 := &mockModel{}
+ m1.addResp("Main")
+ m2 := &mockModel{}
+ m2.addResp("Critique")
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "main"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "critique"
ctx := context.Background()
wf, err := NewLoop(ctx, &LoopConfig{
Name: "loop", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 2,
})
- if err != nil { t.Fatalf("NewLoop: %v", err) }
+ if err != nil {
+ t.Fatalf("NewLoop: %v", err)
+ }
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("iterate")}})
events := drainAgentEvents(t, iter)
- if len(events) == 0 { t.Error("expected events") }
+ if len(events) == 0 {
+ t.Error("expected events")
+ }
}
// ======================== Middleware Chain Tests ========================
@@ -354,7 +460,8 @@ func (m *orderedMiddleware) AfterAgent(ctx context.Context, state *ReActAgentSta
}
func TestMiddleware_ChainOrderPreserved(t *testing.T) {
- model := &mockModel{}; model.addResp("chain result")
+ model := &mockModel{}
+ model.addResp("chain result")
m1 := &orderedMiddleware{id: "mw1", executed: make([]string, 0)}
m2 := &orderedMiddleware{id: "mw2", executed: make([]string, 0)}
@@ -371,13 +478,22 @@ func TestMiddleware_ChainOrderPreserved(t *testing.T) {
func TestMiddleware_ErrorPropagation(t *testing.T) {
for _, failAt := range []string{"BeforeAgent", "BeforeModelRewrite", "AfterModelRewrite", "AfterAgent"} {
t.Run(failAt, func(t *testing.T) {
- model := &mockModel{}; model.addResp("err test")
+ model := &mockModel{}
+ model.addResp("err test")
mw := &errorMiddleware{failAt: failAt}
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model, Middlewares: []ReActMiddleware{mw}})
agent.name = "err_" + failAt
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
var lastErr error
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { lastErr = ev.Err } }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
+ }
_ = lastErr
})
}
@@ -387,14 +503,18 @@ func TestMiddleware_WrapModel(t *testing.T) {
var wrapped bool
mw := &testMiddleware{}
mw.wrapModel = func(ctx context.Context, m Model[*schema.Message], mc *ModelContext) (Model[*schema.Message], error) {
- wrapped = true; return m, nil
+ wrapped = true
+ return m, nil
}
- model := &mockModel{}; model.addResp("wrapped")
+ model := &mockModel{}
+ model.addResp("wrapped")
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model, Middlewares: []ReActMiddleware{mw}})
agent.name = "wrap_m"
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("test")}})
drainAgentEvents(t, iter)
- if !wrapped { t.Error("WrapModel not called") }
+ if !wrapped {
+ t.Error("WrapModel not called")
+ }
}
// ======================== Callback Tests ========================
@@ -405,7 +525,8 @@ func TestCallbacks_OnStartOnEnd(t *testing.T) {
onStart: func(ctx context.Context, input *AgentCallbackInput) { onStart = true },
onEnd: func(ctx context.Context, output *AgentCallbackOutput) { onEnd = true },
}
- model := &mockModel{}; model.addResp("cb test")
+ model := &mockModel{}
+ model.addResp("cb test")
agent := reActAgentSetup(model, nil)
agent.name = "cb_agent"
// Callbacks are wired in flowAgent.Run path
@@ -420,40 +541,56 @@ func TestCallbackFilter_AgentNameMatch(t *testing.T) {
opts := []RunOption{WithCallbacks(cb), WithAgentNames("my_agent")}
filtered := filterOptions("my_agent", opts)
o := getCommonOptions(nil, filtered...)
- if len(o.callbacks) == 0 { t.Error("callbacks should pass through for matching agent") }
+ if len(o.callbacks) == 0 {
+ t.Error("callbacks should pass through for matching agent")
+ }
}
// ======================== Callback Infrastructure Tests ========================
func TestInitAgentCallbacks_Nil(t *testing.T) {
ctx := initAgentCallbacks(context.Background(), "test", "ReActAgent")
- if cbs := getCallbacks(ctx); cbs != nil { t.Error("expected nil callbacks") }
+ if cbs := getCallbacks(ctx); cbs != nil {
+ t.Error("expected nil callbacks")
+ }
}
func TestSetRunLocalValue_NoExecCtx(t *testing.T) {
err := SetRunLocalValue(context.Background(), "k", "v")
- if err == nil { t.Error("expected error with no exec ctx") }
+ if err == nil {
+ t.Error("expected error with no exec ctx")
+ }
}
func TestGetRunLocalValue_NoExecCtx(t *testing.T) {
_, _, err := GetRunLocalValue(context.Background(), "k")
- if err == nil { t.Error("expected error") }
+ if err == nil {
+ t.Error("expected error")
+ }
}
func TestDeleteRunLocalValue_NoExecCtx(t *testing.T) {
err := DeleteRunLocalValue(context.Background(), "k")
- if err == nil { t.Error("expected error") }
+ if err == nil {
+ t.Error("expected error")
+ }
}
func TestSendEvent_NoExecCtx(t *testing.T) {
err := SendEvent(context.Background(), nil)
- if err == nil { t.Error("expected error") }
+ if err == nil {
+ t.Error("expected error")
+ }
}
// ======================== Gob Encodability ========================
func TestCheckGobEncodability(t *testing.T) {
- tests := []struct { name string; val any; wantErr bool }{
+ tests := []struct {
+ name string
+ val any
+ wantErr bool
+ }{
{"string", "hello", false},
{"int", 42, false},
{"nil", nil, false},
@@ -462,8 +599,12 @@ func TestCheckGobEncodability(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := checkGobEncodability("key", tt.val)
- if tt.wantErr && err == nil { t.Error("expected error") }
- if !tt.wantErr && err != nil { t.Errorf("unexpected error: %v", err) }
+ if tt.wantErr && err == nil {
+ t.Error("expected error")
+ }
+ if !tt.wantErr && err != nil {
+ t.Errorf("unexpected error: %v", err)
+ }
})
}
}
@@ -472,21 +613,29 @@ func TestCheckGobEncodability(t *testing.T) {
func TestRunOptions(t *testing.T) {
tests := []struct {
- name string
- opt RunOption
+ name string
+ opt RunOption
check func(*testing.T, *runOptions)
}{
{"SessionValues", WithSessionValues(map[string]any{"k": "v"}), func(t *testing.T, o *runOptions) {
- if o.sessionValues["k"] != "v" { t.Error("session value not set") }
+ if o.sessionValues["k"] != "v" {
+ t.Error("session value not set")
+ }
}},
{"SharedParent", WithSharedParentSession(), func(t *testing.T, o *runOptions) {
- if !o.sharedParentSession { t.Error("sharedParentSession not set") }
+ if !o.sharedParentSession {
+ t.Error("sharedParentSession not set")
+ }
}},
{"SkipTransfer", WithSkipTransferMessages(), func(t *testing.T, o *runOptions) {
- if !o.skipTransferMessages { t.Error("skipTransferMessages not set") }
+ if !o.skipTransferMessages {
+ t.Error("skipTransferMessages not set")
+ }
}},
{"AgentNames", WithAgentNames("a1"), func(t *testing.T, o *runOptions) {
- if len(o.agentNames) != 1 || o.agentNames[0] != "a1" { t.Error("agent names not set") }
+ if len(o.agentNames) != 1 || o.agentNames[0] != "a1" {
+ t.Error("agent names not set")
+ }
}},
}
for _, tt := range tests {
@@ -502,15 +651,21 @@ func TestRunOptions(t *testing.T) {
func TestSchemaMessageTypes(t *testing.T) {
t.Run("UserMessage", func(t *testing.T) {
m := schema.UserMessage("Hello")
- if m.Role != schema.RoleUser || m.Content != "Hello" { t.Error("bad user message") }
+ if m.Role != schema.RoleUser || m.Content != "Hello" {
+ t.Error("bad user message")
+ }
})
t.Run("SystemMessage", func(t *testing.T) {
m := schema.SystemMessage("Sys")
- if m.Role != schema.RoleSystem { t.Error("bad system message") }
+ if m.Role != schema.RoleSystem {
+ t.Error("bad system message")
+ }
})
t.Run("ToolMessage", func(t *testing.T) {
m := schema.ToolMessage("Result", "call_1")
- if m.Role != schema.RoleTool || m.Name != "call_1" { t.Error("bad tool message") }
+ if m.Role != schema.RoleTool || m.Name != "call_1" {
+ t.Error("bad tool message")
+ }
})
}
@@ -519,8 +674,12 @@ func TestToolCallConstruction(t *testing.T) {
ID: "call_1", Type: "function",
Function: schema.ToolCallFunction{Name: "search", Arguments: `{"q":"hello"}`},
}
- if tc.ID != "call_1" { t.Errorf("id = %q", tc.ID) }
- if tc.Function.Name != "search" { t.Errorf("name = %q", tc.Function.Name) }
+ if tc.ID != "call_1" {
+ t.Errorf("id = %q", tc.ID)
+ }
+ if tc.Function.Name != "search" {
+ t.Errorf("name = %q", tc.Function.Name)
+ }
}
// ======================== Concurrency Tests ========================
@@ -531,7 +690,8 @@ func TestConcurrentCancel(t *testing.T) {
wg.Add(1)
go func(id int) {
defer wg.Done()
- model := &mockModel{}; model.addResp(fmt.Sprintf("concurrent-%d", id))
+ model := &mockModel{}
+ model.addResp(fmt.Sprintf("concurrent-%d", id))
agent := reActAgentSetup(model, nil)
agent.name = "cc"
opt, cancel := WithCancel()
@@ -562,18 +722,25 @@ func TestConcurrentIterators(t *testing.T) {
// ======================== GetAgentType ========================
type typedAgentMock struct{}
-func (t *typedAgentMock) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] { return nil }
-func (t *typedAgentMock) Name(ctx context.Context) string { return "typed" }
+
+func (t *typedAgentMock) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] {
+ return nil
+}
+func (t *typedAgentMock) Name(ctx context.Context) string { return "typed" }
func (t *typedAgentMock) Description(ctx context.Context) string { return "" }
-func (t *typedAgentMock) GetType() string { return "CustomType" }
+func (t *typedAgentMock) GetType() string { return "CustomType" }
func TestGetAgentType(t *testing.T) {
- if gt := getAgentType(&typedAgentMock{}); gt != "CustomType" { t.Errorf("expected CustomType, got %s", gt) }
+ if gt := getAgentType(&typedAgentMock{}); gt != "CustomType" {
+ t.Errorf("expected CustomType, got %s", gt)
+ }
}
func TestGetAgentType_Default(t *testing.T) {
agent := reActAgentSetup(&mockModel{}, nil)
- if gt := getAgentType(agent); gt != "ReActAgent" { t.Errorf("expected ReActAgent, got %s", gt) }
+ if gt := getAgentType(agent); gt != "ReActAgent" {
+ t.Errorf("expected ReActAgent, got %s", gt)
+ }
}
// ======================== Agent Resume ========================
@@ -592,7 +759,13 @@ func TestRunner_ResumeWithCheckpoint(t *testing.T) {
func drainAgentEvents(t *testing.T, iter *AsyncIterator[*AgentEvent]) []*AgentEvent {
t.Helper()
var events []*AgentEvent
- for { ev, ok := iter.Next(); if !ok { break }; events = append(events, ev) }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ events = append(events, ev)
+ }
return events
}
@@ -606,12 +779,16 @@ type retryModel struct {
func (m *retryModel) Generate(ctx context.Context, msgs []Message, opts ...modelOption) (Message, error) {
cnt := atomicAdd32(&m.callCount)
- if cnt <= m.failAttempts { return nil, errors.New("retryable error") }
+ if cnt <= m.failAttempts {
+ return nil, errors.New("retryable error")
+ }
return m.inner.Generate(ctx, msgs, opts...)
}
func (m *retryModel) Stream(ctx context.Context, msgs []Message, opts ...modelOption) (*schema.StreamReader[Message], error) {
msg, err := m.Generate(ctx, msgs, opts...)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
return schema.StreamReaderFromArray([]Message{msg}), nil
}
func (m *retryModel) BindTools(tools []*schema.ToolInfo) error { return nil }
@@ -632,19 +809,27 @@ type errorMiddleware struct {
}
func (m *errorMiddleware) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) {
- if m.failAt == "BeforeAgent" { return ctx, nil, errors.New("error in BeforeAgent") }
+ if m.failAt == "BeforeAgent" {
+ return ctx, nil, errors.New("error in BeforeAgent")
+ }
return ctx, rc, nil
}
func (m *errorMiddleware) BeforeModelRewrite(ctx context.Context, state *ReActAgentState, mc *ModelContext) (context.Context, *ReActAgentState, error) {
- if m.failAt == "BeforeModelRewrite" { return ctx, nil, errors.New("error in BeforeModelRewrite") }
+ if m.failAt == "BeforeModelRewrite" {
+ return ctx, nil, errors.New("error in BeforeModelRewrite")
+ }
return ctx, state, nil
}
func (m *errorMiddleware) AfterModelRewrite(ctx context.Context, state *ReActAgentState, mc *ModelContext) (context.Context, *ReActAgentState, error) {
- if m.failAt == "AfterModelRewrite" { return ctx, nil, errors.New("error in AfterModelRewrite") }
+ if m.failAt == "AfterModelRewrite" {
+ return ctx, nil, errors.New("error in AfterModelRewrite")
+ }
return ctx, state, nil
}
func (m *errorMiddleware) AfterAgent(ctx context.Context, state *ReActAgentState) (context.Context, error) {
- if m.failAt == "AfterAgent" { return ctx, errors.New("error in AfterAgent") }
+ if m.failAt == "AfterAgent" {
+ return ctx, errors.New("error in AfterAgent")
+ }
return ctx, nil
}
diff --git a/internal/harness/core/agentcore_test.go b/internal/harness/core/agentcore_test.go
index d3473d380f..0f79022145 100644
--- a/internal/harness/core/agentcore_test.go
+++ b/internal/harness/core/agentcore_test.go
@@ -13,10 +13,10 @@ import (
// ---- Mock Model ----
type mockModel struct {
- responses []string
- mu sync.Mutex
- callCount int
- shouldFail bool
+ responses []string
+ mu sync.Mutex
+ callCount int
+ shouldFail bool
}
func (m *mockModel) addResp(r string) {
@@ -41,7 +41,9 @@ func (m *mockModel) Generate(ctx context.Context, msgs []Message, opts ...modelO
func (m *mockModel) Stream(ctx context.Context, msgs []Message, opts ...modelOption) (*schema.StreamReader[Message], error) {
msg, err := m.Generate(ctx, msgs, opts...)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
return schema.StreamReaderFromArray([]Message{msg}), nil
}
@@ -56,8 +58,8 @@ type mockTool struct {
mu sync.Mutex
}
-func (t *mockTool) Name() string { return t.name }
-func (t *mockTool) Description() string { return t.desc }
+func (t *mockTool) Name() string { return t.name }
+func (t *mockTool) Description() string { return t.desc }
func (t *mockTool) Invoke(ctx context.Context, args string, opts ...toolOption) (string, error) {
t.mu.Lock()
t.executed = true
@@ -79,14 +81,18 @@ func (s *memStore) Get(ctx context.Context, key string) ([]byte, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
v, ok := s.data[key]
- if !ok { return nil, false, nil }
+ if !ok {
+ return nil, false, nil
+ }
return v, true, nil
}
func (s *memStore) Set(ctx context.Context, key string, data []byte) error {
s.mu.Lock()
defer s.mu.Unlock()
- if s.data == nil { s.data = make(map[string][]byte) }
+ if s.data == nil {
+ s.data = make(map[string][]byte)
+ }
s.data[key] = data
return nil
}
@@ -146,31 +152,41 @@ func (m *loopToolModel) BindTools(tools []*schema.ToolInfo) error { return nil }
type testMiddleware struct {
BaseMiddleware[*schema.Message]
- beforeAgent func(context.Context, *ReActAgentContext) (context.Context, *ReActAgentContext, error)
- beforeModel func(context.Context, *ReActAgentState, *ModelContext) (context.Context, *ReActAgentState, error)
- afterModel func(context.Context, *ReActAgentState, *ModelContext) (context.Context, *ReActAgentState, error)
- afterAgent func(context.Context, *ReActAgentState) (context.Context, error)
- wrapModel func(context.Context, Model[*schema.Message], *ModelContext) (Model[*schema.Message], error)
+ beforeAgent func(context.Context, *ReActAgentContext) (context.Context, *ReActAgentContext, error)
+ beforeModel func(context.Context, *ReActAgentState, *ModelContext) (context.Context, *ReActAgentState, error)
+ afterModel func(context.Context, *ReActAgentState, *ModelContext) (context.Context, *ReActAgentState, error)
+ afterAgent func(context.Context, *ReActAgentState) (context.Context, error)
+ wrapModel func(context.Context, Model[*schema.Message], *ModelContext) (Model[*schema.Message], error)
}
func (m *testMiddleware) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) {
- if m.beforeAgent != nil { return m.beforeAgent(ctx, rc) }
+ if m.beforeAgent != nil {
+ return m.beforeAgent(ctx, rc)
+ }
return ctx, rc, nil
}
func (m *testMiddleware) BeforeModelRewrite(ctx context.Context, state *ReActAgentState, mc *ModelContext) (context.Context, *ReActAgentState, error) {
- if m.beforeModel != nil { return m.beforeModel(ctx, state, mc) }
+ if m.beforeModel != nil {
+ return m.beforeModel(ctx, state, mc)
+ }
return ctx, state, nil
}
func (m *testMiddleware) AfterModelRewrite(ctx context.Context, state *ReActAgentState, mc *ModelContext) (context.Context, *ReActAgentState, error) {
- if m.afterModel != nil { return m.afterModel(ctx, state, mc) }
+ if m.afterModel != nil {
+ return m.afterModel(ctx, state, mc)
+ }
return ctx, state, nil
}
func (m *testMiddleware) AfterAgent(ctx context.Context, state *ReActAgentState) (context.Context, error) {
- if m.afterAgent != nil { return m.afterAgent(ctx, state) }
+ if m.afterAgent != nil {
+ return m.afterAgent(ctx, state)
+ }
return ctx, nil
}
func (m *testMiddleware) WrapModel(ctx context.Context, c Model[*schema.Message], mc *ModelContext) (Model[*schema.Message], error) {
- if m.wrapModel != nil { return m.wrapModel(ctx, c, mc) }
+ if m.wrapModel != nil {
+ return m.wrapModel(ctx, c, mc)
+ }
return c, nil
}
@@ -273,8 +289,8 @@ func newSlowTool(name string, delay time.Duration, result string) *slowTool {
startedChan: make(chan struct{}, 10),
}
}
-func (t *slowTool) Name() string { return t.name }
-func (t *slowTool) Description() string { return "slow tool: " + t.name }
+func (t *slowTool) Name() string { return t.name }
+func (t *slowTool) Description() string { return "slow tool: " + t.name }
func (t *slowTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
atomic.AddInt32(&t.callCount, 1)
select {
diff --git a/internal/harness/core/agentic_integration_test.go b/internal/harness/core/agentic_integration_test.go
index 15aa8c5ff2..5815e496ab 100644
--- a/internal/harness/core/agentic_integration_test.go
+++ b/internal/harness/core/agentic_integration_test.go
@@ -11,10 +11,14 @@ import (
// ======================== Tests: Sequential Workflow ========================
func TestWorkflow_SequentialAgent(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("A1")
- m2 := &mockModel{}; m2.addResp("A2")
- a1 := reActAgentSetup(m1, nil); a1.name = "seq_a1"
- a2 := reActAgentSetup(m2, nil); a2.name = "seq_a2"
+ m1 := &mockModel{}
+ m1.addResp("A1")
+ m2 := &mockModel{}
+ m2.addResp("A2")
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "seq_a1"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "seq_a2"
ctx := context.Background()
wf, err := NewSequential(ctx, &SequentialConfig{
@@ -32,10 +36,14 @@ func TestWorkflow_SequentialAgent(t *testing.T) {
}
func TestWorkflow_ParallelAgent(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("P1")
- m2 := &mockModel{}; m2.addResp("P2")
- a1 := reActAgentSetup(m1, nil); a1.name = "par_a1"
- a2 := reActAgentSetup(m2, nil); a2.name = "par_a2"
+ m1 := &mockModel{}
+ m1.addResp("P1")
+ m2 := &mockModel{}
+ m2.addResp("P2")
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "par_a1"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "par_a2"
ctx := context.Background()
wf, err := NewParallel(ctx, &ParallelConfig{
@@ -53,12 +61,17 @@ func TestWorkflow_ParallelAgent(t *testing.T) {
}
func TestWorkflow_NestedParallel(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("inner1")
- m2 := &mockModel{}; m2.addResp("inner2")
- m3 := &mockModel{}; m3.addResp("outer")
-
- a1 := reActAgentSetup(m1, nil); a1.name = "inner_a"
- a2 := reActAgentSetup(m2, nil); a2.name = "inner_b"
+ m1 := &mockModel{}
+ m1.addResp("inner1")
+ m2 := &mockModel{}
+ m2.addResp("inner2")
+ m3 := &mockModel{}
+ m3.addResp("outer")
+
+ a1 := reActAgentSetup(m1, nil)
+ a1.name = "inner_a"
+ a2 := reActAgentSetup(m2, nil)
+ a2.name = "inner_b"
innerPar, err := NewParallel(context.Background(), &ParallelConfig{
Name: "inner-par", Description: "inner parallel", SubAgents: []Agent{a1, a2},
@@ -67,7 +80,8 @@ func TestWorkflow_NestedParallel(t *testing.T) {
t.Fatalf("NewParallel: %v", err)
}
- a3 := reActAgentSetup(m3, nil); a3.name = "outer"
+ a3 := reActAgentSetup(m3, nil)
+ a3.name = "outer"
wf, err := NewSequential(context.Background(), &SequentialConfig{
Name: "nested", Description: "nested parallel", SubAgents: []Agent{innerPar, a3},
})
@@ -84,8 +98,10 @@ func TestWorkflow_NestedParallel(t *testing.T) {
}
func TestWorkflow_LoopAgent(t *testing.T) {
- m := &mockModel{}; m.addResp("loop body")
- body := reActAgentSetup(m, nil); body.name = "loop_body"
+ m := &mockModel{}
+ m.addResp("loop body")
+ body := reActAgentSetup(m, nil)
+ body.name = "loop_body"
ctx := context.Background()
wf, err := NewLoop(ctx, &LoopConfig{
@@ -111,7 +127,7 @@ func TestWorkflow_UnsupportedMode(t *testing.T) {
}
if ev.Err == nil {
t.Error("expected error for unsupported mode")
- } else if ev.Err.Error() != "unsupported mode 0" {
+ } else if ev.Err.Error() != "unsupported mode 0" {
t.Errorf("expected 'unsupported mode 0', got %v", ev.Err)
}
}
@@ -119,7 +135,8 @@ func TestWorkflow_UnsupportedMode(t *testing.T) {
// ======================== Tests: Agentic Integration ========================
func TestAgenticIntegration_BasicGenerate(t *testing.T) {
- model := &mockModel{}; model.addResp("Hello!")
+ model := &mockModel{}
+ model.addResp("Hello!")
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model}).WithName("e2e")
iter := agent.Run(context.Background(), &AgentInput{Messages: []Message{schema.UserMessage("Hi")}})
@@ -162,7 +179,8 @@ func TestAgenticIntegration_StreamingOutput(t *testing.T) {
}
func TestAgenticIntegration_EmptyInput(t *testing.T) {
- model := &mockModel{}; model.addResp("response")
+ model := &mockModel{}
+ model.addResp("response")
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model}).WithName("empty")
ctx := context.Background()
diff --git a/internal/harness/core/backend/backend_inmemory.go b/internal/harness/core/backend/backend_inmemory.go
index 8331ed98ec..8db0b52910 100644
--- a/internal/harness/core/backend/backend_inmemory.go
+++ b/internal/harness/core/backend/backend_inmemory.go
@@ -11,14 +11,14 @@ import (
// InMemoryBackend implements Backend using in-memory storage.
// Useful for testing and sandboxed environments.
type InMemoryBackend struct {
- mu sync.RWMutex
- files map[string]*memFile
+ mu sync.RWMutex
+ files map[string]*memFile
}
type memFile struct {
- content string
- modTime time.Time
- isDir bool
+ content string
+ modTime time.Time
+ isDir bool
}
func NewInMemoryBackend() *InMemoryBackend {
@@ -30,8 +30,12 @@ func (b *InMemoryBackend) Read(path string) (string, error) {
b.mu.RLock()
defer b.mu.RUnlock()
f, ok := b.files[filepath.Clean(path)]
- if !ok { return "", fmt.Errorf("file not found: %s", path) }
- if f.isDir { return "", fmt.Errorf("is a directory: %s", path) }
+ if !ok {
+ return "", fmt.Errorf("file not found: %s", path)
+ }
+ if f.isDir {
+ return "", fmt.Errorf("is a directory: %s", path)
+ }
return f.content, nil
}
@@ -44,9 +48,13 @@ func (b *InMemoryBackend) Write(path, content string) error {
func (b *InMemoryBackend) Edit(path, old, new string) error {
content, err := b.Read(path)
- if err != nil { return err }
+ if err != nil {
+ return err
+ }
updated := strings.Replace(content, old, new, 1)
- if updated == content { return fmt.Errorf("text not found in %s", path) }
+ if updated == content {
+ return fmt.Errorf("text not found in %s", path)
+ }
return b.Write(path, updated)
}
@@ -55,17 +63,23 @@ func (b *InMemoryBackend) Glob(pattern string) ([]string, error) {
defer b.mu.RUnlock()
var matches []string
for p := range b.files {
- if matched, _ := filepath.Match(pattern, p); matched { matches = append(matches, p) }
+ if matched, _ := filepath.Match(pattern, p); matched {
+ matches = append(matches, p)
+ }
}
return matches, nil
}
func (b *InMemoryBackend) Grep(pattern, path string) (string, error) {
content, err := b.Read(path)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
var results []string
for i, line := range strings.Split(content, "\n") {
- if strings.Contains(line, pattern) { results = append(results, fmt.Sprintf("%s:%d: %s", path, i+1, line)) }
+ if strings.Contains(line, pattern) {
+ results = append(results, fmt.Sprintf("%s:%d: %s", path, i+1, line))
+ }
}
return strings.Join(results, "\n"), nil
}
@@ -74,7 +88,9 @@ func (b *InMemoryBackend) Stat(path string) (*FileInfo, error) {
b.mu.RLock()
defer b.mu.RUnlock()
f, ok := b.files[filepath.Clean(path)]
- if !ok { return nil, fmt.Errorf("not found: %s", path) }
+ if !ok {
+ return nil, fmt.Errorf("not found: %s", path)
+ }
return &FileInfo{Name: path, Size: int64(len(f.content)), IsDir: f.isDir, ModTime: f.modTime.Format(time.RFC3339)}, nil
}
diff --git a/internal/harness/core/benchmark_test.go b/internal/harness/core/benchmark_test.go
index 3421dd8cb9..0e623d8e7f 100644
--- a/internal/harness/core/benchmark_test.go
+++ b/internal/harness/core/benchmark_test.go
@@ -16,8 +16,8 @@ func BenchmarkReActAgent_ReActLoop(b *testing.B) {
model.addResp("tool")
model.addResp("done")
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: model,
- Tools: []Tool{tool},
+ Model: model,
+ Tools: []Tool{tool},
ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
})
agent.name = "bench"
diff --git a/internal/harness/core/callback.go b/internal/harness/core/callback.go
index 53452a6a1d..6790826608 100644
--- a/internal/harness/core/callback.go
+++ b/internal/harness/core/callback.go
@@ -63,13 +63,17 @@ func propagateCallbacks(ctx context.Context, opts []RunOption) []RunOption {
}
func withCallbacks(ctx context.Context, cbs []callbackHandler) context.Context {
- if len(cbs) == 0 { return ctx }
+ if len(cbs) == 0 {
+ return ctx
+ }
return context.WithValue(ctx, callbackKey{}, cbs)
}
func initAgentCallbacks(ctx context.Context, name, agentType string, opts ...RunOption) context.Context {
o := getCommonOptions(nil, opts...)
- if len(o.callbacks) == 0 { return ctx }
+ if len(o.callbacks) == 0 {
+ return ctx
+ }
cbs := make([]callbackHandler, 0, len(o.callbacks))
for _, cb := range o.callbacks {
switch c := cb.(type) {
@@ -87,7 +91,9 @@ func initAgenticCallbacks(ctx context.Context, name, agentType string, opts ...R
func filterOptions(name string, opts []RunOption) []RunOption {
// Remove callbacks not matching the given agent name from agentNames list
o := getCommonOptions(nil, opts...)
- if len(o.agentNames) == 0 { return opts }
+ if len(o.agentNames) == 0 {
+ return opts
+ }
var filtered []RunOption
for _, opt := range opts {
@@ -98,9 +104,14 @@ func filterOptions(name string, opts []RunOption) []RunOption {
if tmp.agentNames != nil {
match := false
for _, n := range tmp.agentNames {
- if n == name { match = true; break }
+ if n == name {
+ match = true
+ break
+ }
+ }
+ if !match {
+ continue
}
- if !match { continue }
}
}
filtered = append(filtered, opt)
@@ -116,18 +127,24 @@ func filterCancelOption(opts []RunOption) []RunOption {
if fn, ok := opt.(runOptFn); ok {
tmp := &runOptions{}
fn(tmp)
- if tmp.cancelCtx != nil { continue }
+ if tmp.cancelCtx != nil {
+ continue
+ }
}
filtered = append(filtered, opt)
}
- if len(filtered) == len(opts) { return opts }
+ if len(filtered) == len(opts) {
+ return opts
+ }
return filtered
}
func filterCallbackHandlersForNestedAgents(name string, opts []RunOption) []RunOption {
// Remove callback handlers that are scoped to specific agents
o := getCommonOptions(nil, opts...)
- if len(o.agentNames) == 0 { return opts }
+ if len(o.agentNames) == 0 {
+ return opts
+ }
var filtered []RunOption
for _, opt := range opts {
@@ -137,9 +154,14 @@ func filterCallbackHandlersForNestedAgents(name string, opts []RunOption) []RunO
if tmp.agentNames != nil {
match := false
for _, n := range tmp.agentNames {
- if n == name { match = true; break }
+ if n == name {
+ match = true
+ break
+ }
+ }
+ if !match {
+ continue
}
- if !match { continue }
}
}
filtered = append(filtered, opt)
@@ -158,7 +180,9 @@ func getAgentType(a Agent) string {
func SetRunLocalValue(ctx context.Context, key string, val any) error {
// P2: Gob encodability check - catch unregistered types early at Set time
- if err := checkGobEncodability(key, val); err != nil { return err }
+ if err := checkGobEncodability(key, val); err != nil {
+ return err
+ }
rc := getRunCtx(ctx)
if rc == nil || rc.Session == nil {
diff --git a/internal/harness/core/callback_test.go b/internal/harness/core/callback_test.go
index cabca32a67..3c988609de 100644
--- a/internal/harness/core/callback_test.go
+++ b/internal/harness/core/callback_test.go
@@ -78,7 +78,13 @@ func TestCallbacks_WithAgentNamesFilter_CallbackSavedAndFiltered(t *testing.T) {
iter := agent.Run(context.Background(), &AgentInput{
Messages: []Message{schema.UserMessage("test")},
}, opts...)
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCallbacks_EmptyCallbacks(t *testing.T) {
@@ -89,7 +95,13 @@ func TestCallbacks_EmptyCallbacks(t *testing.T) {
iter := agent.Run(context.Background(), &AgentInput{
Messages: []Message{schema.UserMessage("test")},
})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestFilterOptions_Empty(t *testing.T) {
@@ -221,7 +233,9 @@ func TestCheckGobEncodability_NilValue(t *testing.T) {
// ---- AsAgentExecError helper ----
func AsAgentExecError(err error, target **AgentExecError) bool {
- if err == nil { return false }
+ if err == nil {
+ return false
+ }
*target = &AgentExecError{Message: err.Error()}
return true
}
@@ -230,33 +244,45 @@ func AsAgentExecError(err error, target **AgentExecError) bool {
func TestWithSessionValues(t *testing.T) {
o := getCommonOptions(nil, WithSessionValues(map[string]any{"k": "v"}))
- if o.sessionValues["k"] != "v" { t.Error("session value not set") }
+ if o.sessionValues["k"] != "v" {
+ t.Error("session value not set")
+ }
}
func TestWithCheckPointID(t *testing.T) {
o := getCommonOptions(nil, WithCheckPointID("cp1"))
- if *o.checkPointID != "cp1" { t.Error("checkpoint ID not set") }
+ if *o.checkPointID != "cp1" {
+ t.Error("checkpoint ID not set")
+ }
}
func TestWithSkipTransferMessages(t *testing.T) {
o := getCommonOptions(nil, WithSkipTransferMessages())
- if !o.skipTransferMessages { t.Error("skipTransferMessages not set") }
+ if !o.skipTransferMessages {
+ t.Error("skipTransferMessages not set")
+ }
}
func TestWithSharedParentSession(t *testing.T) {
o := getCommonOptions(nil, WithSharedParentSession())
- if !o.sharedParentSession { t.Error("sharedParentSession not set") }
+ if !o.sharedParentSession {
+ t.Error("sharedParentSession not set")
+ }
}
func TestWithAfterToolCallsHook(t *testing.T) {
fn := func(ctx context.Context) error { return nil }
o := getCommonOptions(nil, WithAfterToolCallsHook(fn))
- if o.afterToolCallsHook == nil { t.Error("afterToolCallsHook not set") }
+ if o.afterToolCallsHook == nil {
+ t.Error("afterToolCallsHook not set")
+ }
}
func TestWithCallbacks_Nil(t *testing.T) {
o := getCommonOptions(nil, WithCallbacks())
- if len(o.callbacks) != 0 { t.Error("expected empty callbacks") }
+ if len(o.callbacks) != 0 {
+ t.Error("expected empty callbacks")
+ }
}
// ---- getCallbacks/withCallbacks tests ----
@@ -265,15 +291,21 @@ func TestWithCallbacks_Context(t *testing.T) {
cb := callbackHandler{}
ctx := withCallbacks(context.Background(), []callbackHandler{cb})
cbs := getCallbacks(ctx)
- if len(cbs) != 1 { t.Errorf("expected 1 callback, got %d", len(cbs)) }
+ if len(cbs) != 1 {
+ t.Errorf("expected 1 callback, got %d", len(cbs))
+ }
}
func TestGetCallbacks_NoCallbacks(t *testing.T) {
cbs := getCallbacks(context.Background())
- if cbs != nil { t.Error("expected nil") }
+ if cbs != nil {
+ t.Error("expected nil")
+ }
}
func TestWithCallbacks_Empty(t *testing.T) {
ctx := withCallbacks(context.Background(), nil)
- if ctx != context.Background() { t.Errorf("empty callbacks should return original context") }
+ if ctx != context.Background() {
+ t.Errorf("empty callbacks should return original context")
+ }
}
diff --git a/internal/harness/core/cancel.go b/internal/harness/core/cancel.go
index bc6bbc9e89..3f202d25f0 100644
--- a/internal/harness/core/cancel.go
+++ b/internal/harness/core/cancel.go
@@ -17,13 +17,14 @@ type CancelMode int
const (
CancelImmediate CancelMode = 0
- CancelAfterChatModel CancelMode = 1 << iota
+ CancelAfterChatModel CancelMode = 1 << iota
CancelAfterToolCalls
)
// ---- CancelHandle ----
type CancelHandle struct{ wait func() error }
+
func (h *CancelHandle) Wait() error { return h.wait() }
type AgentCancelFunc func(...CancelOption) (*CancelHandle, bool)
@@ -65,21 +66,22 @@ func (e *CancelError) Error() string {
}
type StreamCanceledError struct{}
+
func (e *StreamCanceledError) Error() string { return "stream canceled" }
var (
- ErrCancelTimeout = errors.New("cancel timed out")
- ErrExecutionEnded = errors.New("execution already ended")
+ ErrCancelTimeout = errors.New("cancel timed out")
+ ErrExecutionEnded = errors.New("execution already ended")
ErrStreamCanceled error = &StreamCanceledError{}
)
// ---- cancelContext state machine ----
const (
- stRunning int32 = 0
- stCancelling int32 = 1
- stDone int32 = 2
- stCancelHandled int32 = 5
+ stRunning int32 = 0
+ stCancelling int32 = 1
+ stDone int32 = 2
+ stCancelHandled int32 = 5
interruptNotSent int32 = 0
interruptImmediate int32 = 1
)
@@ -87,64 +89,86 @@ const (
const cancelGracePeriod = 1 * time.Second
type cancelContext struct {
- mode int32
- cancelChan chan struct{}
- immediateChan chan struct{}
- doneChan chan struct{}
- doneOnce sync.Once
- state int32
- interruptSent int32
- escalated int32
- timeoutEscalated int32
- startedMode int32
- deadlineUnixNano int64
- recursive int32
- recursiveChan chan struct{}
- root bool
- parent *cancelContext
+ mode int32
+ cancelChan chan struct{}
+ immediateChan chan struct{}
+ doneChan chan struct{}
+ doneOnce sync.Once
+ state int32
+ interruptSent int32
+ escalated int32
+ timeoutEscalated int32
+ startedMode int32
+ deadlineUnixNano int64
+ recursive int32
+ recursiveChan chan struct{}
+ root bool
+ parent *cancelContext
agentToolDescendant int32
- cancelMu sync.Mutex
- timeoutOnce sync.Once
- timeoutNotify chan struct{}
- mu sync.Mutex
- interruptFuncs []func(...any)
+ cancelMu sync.Mutex
+ timeoutOnce sync.Once
+ timeoutNotify chan struct{}
+ mu sync.Mutex
+ interruptFuncs []func(...any)
}
func newCancelContext() *cancelContext {
return &cancelContext{
- cancelChan: make(chan struct{}), immediateChan: make(chan struct{}),
+ cancelChan: make(chan struct{}), immediateChan: make(chan struct{}),
doneChan: make(chan struct{}), timeoutNotify: make(chan struct{}, 1),
recursiveChan: make(chan struct{}), root: true,
}
}
-func (cc *cancelContext) isRoot() bool { return cc != nil && cc.root }
-func (cc *cancelContext) isRecursive() bool { return cc != nil && atomic.LoadInt32(&cc.recursive) == 1 }
+func (cc *cancelContext) isRoot() bool { return cc != nil && cc.root }
+func (cc *cancelContext) isRecursive() bool { return cc != nil && atomic.LoadInt32(&cc.recursive) == 1 }
func (cc *cancelContext) shouldCancel() bool {
- if cc == nil { return false }
- select { case <-cc.cancelChan: return true; default: return false }
+ if cc == nil {
+ return false
+ }
+ select {
+ case <-cc.cancelChan:
+ return true
+ default:
+ return false
+ }
}
func (cc *cancelContext) isImmediate() bool {
- if cc == nil { return false }
- select { case <-cc.immediateChan: return true; default: return false }
+ if cc == nil {
+ return false
+ }
+ select {
+ case <-cc.immediateChan:
+ return true
+ default:
+ return false
+ }
}
func (cc *cancelContext) getMode() CancelMode {
- if cc == nil { return CancelImmediate }
+ if cc == nil {
+ return CancelImmediate
+ }
return CancelMode(atomic.LoadInt32(&cc.mode))
}
-func (cc *cancelContext) setMode(m CancelMode) { atomic.StoreInt32(&cc.mode, int32(m)) }
+func (cc *cancelContext) setMode(m CancelMode) { atomic.StoreInt32(&cc.mode, int32(m)) }
func (cc *cancelContext) setRecursive(v bool) {
- if v && atomic.CompareAndSwapInt32(&cc.recursive, 0, 1) { close(cc.recursiveChan) }
+ if v && atomic.CompareAndSwapInt32(&cc.recursive, 0, 1) {
+ close(cc.recursiveChan)
+ }
}
func (cc *cancelContext) markDone() {
- if cc == nil { return }
+ if cc == nil {
+ return
+ }
if atomic.CompareAndSwapInt32(&cc.state, stRunning, stDone) || atomic.CompareAndSwapInt32(&cc.state, stCancelling, stDone) {
cc.doneOnce.Do(func() { close(cc.doneChan) })
}
}
func (cc *cancelContext) markHandled() bool {
- if cc == nil { return false }
+ if cc == nil {
+ return false
+ }
if atomic.CompareAndSwapInt32(&cc.state, stCancelling, stCancelHandled) {
cc.doneOnce.Do(func() { close(cc.doneChan) })
return true
@@ -169,7 +193,9 @@ func (cc *cancelContext) createAndMarkHandled() (*CancelError, bool) {
func (cc *cancelContext) triggerCancel(m CancelMode) {
cc.setMode(m)
- if atomic.CompareAndSwapInt32(&cc.state, stRunning, stCancelling) { close(cc.cancelChan) }
+ if atomic.CompareAndSwapInt32(&cc.state, stRunning, stCancelling) {
+ close(cc.cancelChan)
+ }
}
func (cc *cancelContext) triggerImmediate() {
atomic.StoreInt32(&cc.escalated, 1)
@@ -200,16 +226,23 @@ func (cc *cancelContext) sendInterrupt() bool {
// This is best-effort; cancel() itself returns immediately, the grace wait
// is advisory for the sub-agent to observe the cancellation signal.
if cc.isRecursive() && atomic.LoadInt32(&cc.agentToolDescendant) == 1 {
- select { case <-cc.doneChan: case <-time.After(cancelGracePeriod): }
+ select {
+ case <-cc.doneChan:
+ case <-time.After(cancelGracePeriod):
+ }
}
return true
}
func (cc *cancelContext) markAgentToolDescendant() {
- for cur := cc; cur != nil; cur = cur.parent { atomic.StoreInt32(&cur.agentToolDescendant, 1) }
+ for cur := cc; cur != nil; cur = cur.parent {
+ atomic.StoreInt32(&cur.agentToolDescendant, 1)
+ }
}
func (cc *cancelContext) deriveAgentToolCancelContext(ctx context.Context) *cancelContext {
- if cc == nil { return nil }
+ if cc == nil {
+ return nil
+ }
child := newCancelContext()
child.root = false
child.parent = cc
@@ -260,20 +293,27 @@ func (cc *cancelContext) deriveAgentToolCancelContext(ctx context.Context) *canc
}
func (cc *cancelContext) buildCancelFunc() AgentCancelFunc {
join := func(a, b CancelMode) CancelMode {
- if a == CancelImmediate || b == CancelImmediate { return CancelImmediate }
+ if a == CancelImmediate || b == CancelImmediate {
+ return CancelImmediate
+ }
return a | b
}
parse := func(opts ...CancelOption) *cancelConfig {
c := &cancelConfig{Mode: CancelImmediate}
- for _, o := range opts { o(c) }
+ for _, o := range opts {
+ o(c)
+ }
return c
}
waitDone := func() error {
<-cc.doneChan
switch atomic.LoadInt32(&cc.state) {
- case stDone: return ErrExecutionEnded
+ case stDone:
+ return ErrExecutionEnded
default:
- if atomic.LoadInt32(&cc.timeoutEscalated) == 1 { return ErrCancelTimeout }
+ if atomic.LoadInt32(&cc.timeoutEscalated) == 1 {
+ return ErrCancelTimeout
+ }
return nil
}
}
@@ -281,20 +321,28 @@ func (cc *cancelContext) buildCancelFunc() AgentCancelFunc {
req := parse(callOpts...)
st := atomic.LoadInt32(&cc.state)
switch st {
- case stCancelHandled: return &CancelHandle{func() error { return nil }}, false
- case stDone: return &CancelHandle{func() error { return ErrExecutionEnded }}, false
+ case stCancelHandled:
+ return &CancelHandle{func() error { return nil }}, false
+ case stDone:
+ return &CancelHandle{func() error { return ErrExecutionEnded }}, false
}
cc.cancelMu.Lock()
st = atomic.LoadInt32(&cc.state)
switch st {
- case stCancelHandled: cc.cancelMu.Unlock(); return &CancelHandle{func() error { return nil }}, false
- case stDone: cc.cancelMu.Unlock(); return &CancelHandle{func() error { return ErrExecutionEnded }}, false
+ case stCancelHandled:
+ cc.cancelMu.Unlock()
+ return &CancelHandle{func() error { return nil }}, false
+ case stDone:
+ cc.cancelMu.Unlock()
+ return &CancelHandle{func() error { return ErrExecutionEnded }}, false
}
if st == stRunning {
if !atomic.CompareAndSwapInt32(&cc.state, stRunning, stCancelling) {
st = atomic.LoadInt32(&cc.state)
cc.cancelMu.Unlock()
- if st == stDone { return &CancelHandle{func() error { return ErrExecutionEnded }}, false }
+ if st == stDone {
+ return &CancelHandle{func() error { return ErrExecutionEnded }}, false
+ }
return &CancelHandle{waitDone}, true
}
cc.setMode(req.Mode)
@@ -303,10 +351,13 @@ func (cc *cancelContext) buildCancelFunc() AgentCancelFunc {
close(cc.cancelChan)
} else {
cc.setMode(join(cc.getMode(), req.Mode))
- if req.Recursive { cc.setRecursive(true) }
+ if req.Recursive {
+ cc.setRecursive(true)
+ }
}
var needImmediate, needTimeout bool
- if cc.getMode() == CancelImmediate { needImmediate = true
+ if cc.getMode() == CancelImmediate {
+ needImmediate = true
} else if req.Timeout != nil && *req.Timeout > 0 {
// Use minimum (earliest) non-zero deadline so a later cancel cannot
// extend an earlier timeout.
@@ -316,8 +367,12 @@ func (cc *cancelContext) buildCancelFunc() AgentCancelFunc {
needTimeout = true
}
cc.cancelMu.Unlock()
- if needImmediate { cc.triggerImmediate() }
- if needTimeout { cc.startTimeout() }
+ if needImmediate {
+ cc.triggerImmediate()
+ }
+ if needTimeout {
+ cc.startTimeout()
+ }
return &CancelHandle{waitDone}, true
}
}
@@ -332,7 +387,9 @@ func (cc *cancelContext) startTimeout() {
default:
}
dl := atomic.LoadInt64(&cc.deadlineUnixNano)
- if dl == 0 { return }
+ if dl == 0 {
+ return
+ }
wait := time.Duration(dl - time.Now().UnixNano())
if wait <= 0 {
atomic.StoreInt32(&cc.escalated, 1)
@@ -378,41 +435,52 @@ func (cc *cancelContext) setDeadlineMinUnixNano(next int64) {
}
}
}
-func (cc *cancelContext) agentToolSeen() bool { return cc != nil && atomic.LoadInt32(&cc.agentToolDescendant) == 1 }
+func (cc *cancelContext) agentToolSeen() bool {
+ return cc != nil && atomic.LoadInt32(&cc.agentToolDescendant) == 1
+}
// ---- Context propagation ----
type cancelCtxKey struct{}
func withCancelContext(ctx context.Context, cc *cancelContext) context.Context {
- if cc == nil { return ctx }
+ if cc == nil {
+ return ctx
+ }
return context.WithValue(ctx, cancelCtxKey{}, cc)
}
func getCancelContext(ctx context.Context) *cancelContext {
- if v := ctx.Value(cancelCtxKey{}); v != nil { return v.(*cancelContext) }
+ if v := ctx.Value(cancelCtxKey{}); v != nil {
+ return v.(*cancelContext)
+ }
return nil
}
// ---- Iterator wrapper ----
func wrapIterWithCancelCtx[M MessageType](iter *AsyncIterator[*TypedAgentEvent[M]], cc *cancelContext) *AsyncIterator[*TypedAgentEvent[M]] {
- if cc == nil { return iter }
+ if cc == nil {
+ return iter
+ }
it, gen := NewAsyncIteratorPair[*TypedAgentEvent[M]]()
go func() {
defer gen.Close()
endedByCancel := false
- defer func() {
- // Only mark done on actual cancellation, not on normal completion.
- // This prevents a shared cancelContext from being marked done by a
- // sub-agent that finishes naturally, which would block later cancel calls.
- if endedByCancel || cc.shouldCancel() {
- cc.markDone()
- }
- }()
for {
event, ok := iter.Next()
- if !ok { break }
+ if !ok {
+ // Inner iterator closed. If cancel was requested but no interrupt
+ // event was produced (e.g., the goroutine never started), emit
+ // a CancelError so the caller can detect the cancellation.
+ if cc.isRoot() && cc.shouldCancel() {
+ if err, ok := cc.createAndMarkHandled(); ok {
+ gen.Send(&TypedAgentEvent[M]{Err: err})
+ }
+ endedByCancel = true
+ }
+ break
+ }
if cc.isRoot() && event.Action != nil && event.Action.internalInterrupted != nil && cc.shouldCancel() {
if err, ok := cc.createAndMarkHandled(); ok {
err.interruptSignal = event.Action.internalInterrupted
@@ -423,6 +491,12 @@ func wrapIterWithCancelCtx[M MessageType](iter *AsyncIterator[*TypedAgentEvent[M
}
gen.Send(event)
}
+ // Mark done on cancellation or when requested (not on normal completion,
+ // to avoid prematurely marking a shared cancelContext for a sub-agent
+ // that finishes naturally).
+ if endedByCancel || cc.shouldCancel() {
+ cc.markDone()
+ }
}()
return it
}
@@ -432,16 +506,24 @@ type cancelMonitoredModel[M MessageType] struct {
cc *cancelContext
}
-func (m *cancelMonitoredModel[M]) Generate(ctx context.Context, input []M, opts ...modelOption) (M, error) { return m.inner.Generate(ctx, input, opts...) }
+func (m *cancelMonitoredModel[M]) Generate(ctx context.Context, input []M, opts ...modelOption) (M, error) {
+ return m.inner.Generate(ctx, input, opts...)
+}
func (m *cancelMonitoredModel[M]) Stream(ctx context.Context, input []M, opts ...modelOption) (*schema.StreamReader[M], error) {
s, err := m.inner.Stream(ctx, input, opts...)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
return wrapStreamWithCancel(s, m.cc), nil
}
-func (m *cancelMonitoredModel[M]) BindTools(tools []*schema.ToolInfo) error { return m.inner.BindTools(tools) }
+func (m *cancelMonitoredModel[M]) BindTools(tools []*schema.ToolInfo) error {
+ return m.inner.BindTools(tools)
+}
func wrapStreamWithCancel[T any](s *schema.StreamReader[T], cc *cancelContext) *schema.StreamReader[T] {
- if cc == nil { return s }
+ if cc == nil {
+ return s
+ }
select {
case <-cc.immediateChan:
s.Close()
@@ -456,7 +538,10 @@ func wrapStreamWithCancel[T any](s *schema.StreamReader[T], cc *cancelContext) *
go func() {
defer r.Close()
defer s.Close()
- ch := make(chan struct{ Data T; Err error }, 64)
+ ch := make(chan struct {
+ Data T
+ Err error
+ }, 64)
done := make(chan struct{})
defer close(done)
go func() {
@@ -464,11 +549,16 @@ func wrapStreamWithCancel[T any](s *schema.StreamReader[T], cc *cancelContext) *
for {
d, e := s.Recv()
select {
- case ch <- struct{ Data T; Err error }{d, e}:
+ case ch <- struct {
+ Data T
+ Err error
+ }{d, e}:
case <-done:
return
}
- if e != nil { return }
+ if e != nil {
+ return
+ }
}
}()
for {
@@ -479,7 +569,13 @@ func wrapStreamWithCancel[T any](s *schema.StreamReader[T], cc *cancelContext) *
r.Send(z, ErrStreamCanceled)
return
case v, ok := <-ch:
- if !ok || v.Err != nil { return }
+ if !ok {
+ return
+ }
+ if v.Err != nil {
+ r.Send(v.Data, v.Err)
+ return
+ }
r.Send(v.Data, nil)
}
}
@@ -504,7 +600,9 @@ type CancelFromGraphInfo struct {
// SetGraphInterruptFunc registers a callback invoked on graph interrupt signal.
func (cc *cancelContext) SetGraphInterruptFunc(fn func(...any)) {
- if cc == nil { return }
+ if cc == nil {
+ return
+ }
cc.mu.Lock()
defer cc.mu.Unlock()
cc.interruptFuncs = append(cc.interruptFuncs, fn)
@@ -512,11 +610,15 @@ func (cc *cancelContext) SetGraphInterruptFunc(fn func(...any)) {
// InterruptFromGraph coordinates a graph interrupt with the cancel state machine.
func (cc *cancelContext) InterruptFromGraph(ctx context.Context, info *CancelFromGraphInfo) bool {
- if cc == nil || info == nil { return false }
+ if cc == nil || info == nil {
+ return false
+ }
cc.cancelMu.Lock()
defer cc.cancelMu.Unlock()
st := atomic.LoadInt32(&cc.state)
- if st != stRunning { return false }
+ if st != stRunning {
+ return false
+ }
if !atomic.CompareAndSwapInt32(&cc.state, stRunning, stCancelling) {
return false
}
diff --git a/internal/harness/core/cancel_full_test.go b/internal/harness/core/cancel_full_test.go
index ddb3e604e9..303157dca3 100644
--- a/internal/harness/core/cancel_full_test.go
+++ b/internal/harness/core/cancel_full_test.go
@@ -14,78 +14,156 @@ import (
func assertHasCancelError(t *testing.T, events []*AgentEvent) {
t.Helper()
- for _, e := range events { var ce *CancelError; if e.Err != nil && errors.As(e.Err, &ce) { return } }
+ for _, e := range events {
+ var ce *CancelError
+ if e.Err != nil && errors.As(e.Err, &ce) {
+ return
+ }
+ }
t.Fatal("expected CancelError in events")
}
func drainAndAssertCancelError(t *testing.T, iter *AsyncIterator[*AgentEvent]) {
t.Helper()
- for { ev, ok := iter.Next(); if !ok { break }; var ce *CancelError; if ev.Err != nil && errors.As(ev.Err, &ce) { return } }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ var ce *CancelError
+ if ev.Err != nil && errors.As(ev.Err, &ce) {
+ return
+ }
+ }
t.Fatal("expected CancelError in event stream")
}
func drainEventsAndAssertCancelError(t *testing.T, iter *AsyncIterator[*AgentEvent]) []*AgentEvent {
t.Helper()
- var events []*AgentEvent; hasCancel := false
- for { ev, ok := iter.Next(); if !ok { break }; var ce *CancelError; if ev.Err != nil && errors.As(ev.Err, &ce) { hasCancel = true }; events = append(events, ev) }
- if !hasCancel { t.Fatal("expected CancelError in event stream") }
+ var events []*AgentEvent
+ hasCancel := false
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ var ce *CancelError
+ if ev.Err != nil && errors.As(ev.Err, &ce) {
+ hasCancel = true
+ }
+ events = append(events, ev)
+ }
+ if !hasCancel {
+ t.Fatal("expected CancelError in event stream")
+ }
return events
}
func drainEventsAndHasCancel(iter *AsyncIterator[*AgentEvent]) ([]*AgentEvent, bool) {
- var events []*AgentEvent; hasCancel := false
- for { e, ok := iter.Next(); if !ok { break }; events = append(events, e); var ce *CancelError; if e.Err != nil && errors.As(e.Err, &ce) { hasCancel = true } }
+ var events []*AgentEvent
+ hasCancel := false
+ for {
+ e, ok := iter.Next()
+ if !ok {
+ break
+ }
+ events = append(events, e)
+ var ce *CancelError
+ if e.Err != nil && errors.As(e.Err, &ce) {
+ hasCancel = true
+ }
+ }
return events, hasCancel
}
-type cancelTestStore struct { m map[string][]byte; mu sync.Mutex }
-func newCancelTestStore() *cancelTestStore { return &cancelTestStore{m: make(map[string][]byte)} }
-func (s *cancelTestStore) Set(_ context.Context, key string, value []byte) error { s.mu.Lock(); defer s.mu.Unlock(); s.m[key] = value; return nil }
-func (s *cancelTestStore) Get(_ context.Context, key string) ([]byte, bool, error) { s.mu.Lock(); defer s.mu.Unlock(); v, ok := s.m[key]; return v, ok, nil }
+type cancelTestStore struct {
+ m map[string][]byte
+ mu sync.Mutex
+}
+func newCancelTestStore() *cancelTestStore { return &cancelTestStore{m: make(map[string][]byte)} }
+func (s *cancelTestStore) Set(_ context.Context, key string, value []byte) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.m[key] = value
+ return nil
+}
+func (s *cancelTestStore) Get(_ context.Context, key string) ([]byte, bool, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ v, ok := s.m[key]
+ return v, ok, nil
+}
// ======================== CancelContext State Machine ========================
func TestCancelContext_Basics(t *testing.T) {
cc := newCancelContext()
- if cc.shouldCancel() { t.Error("not cancelled initially") }
- cc.setMode(CancelImmediate); close(cc.cancelChan)
- if !cc.shouldCancel() { t.Error("should cancel after close") }
- if cc.getMode() != CancelImmediate { t.Error("mode") }
+ if cc.shouldCancel() {
+ t.Error("not cancelled initially")
+ }
+ cc.setMode(CancelImmediate)
+ close(cc.cancelChan)
+ if !cc.shouldCancel() {
+ t.Error("should cancel after close")
+ }
+ if cc.getMode() != CancelImmediate {
+ t.Error("mode")
+ }
_ = cc.markHandled()
}
func TestCancelContext_New(t *testing.T) {
cc := newCancelContext()
- if !cc.isRoot() { t.Error("expected root") }
+ if !cc.isRoot() {
+ t.Error("expected root")
+ }
}
func TestCancelContext_Lifecycle(t *testing.T) {
cc := newCancelContext()
cc.triggerCancel(CancelAfterChatModel)
- if !cc.shouldCancel() { t.Error("should cancel") }
- if cc.getMode() != CancelAfterChatModel { t.Error("wrong mode") }
- if cc.isImmediate() { t.Error("should not be immediate") }
+ if !cc.shouldCancel() {
+ t.Error("should cancel")
+ }
+ if cc.getMode() != CancelAfterChatModel {
+ t.Error("wrong mode")
+ }
+ if cc.isImmediate() {
+ t.Error("should not be immediate")
+ }
}
func TestCancelContext_Immediate(t *testing.T) {
cc := newCancelContext()
cc.triggerImmediate()
- if !cc.shouldCancel() { t.Error("should cancel") }
- if !cc.isImmediate() { t.Error("should be immediate") }
+ if !cc.shouldCancel() {
+ t.Error("should cancel")
+ }
+ if !cc.isImmediate() {
+ t.Error("should be immediate")
+ }
}
func TestCancelContext_MarkDone(t *testing.T) {
cc := newCancelContext()
cc.markDone()
- select { case <-cc.doneChan: default: t.Fatal("doneChan not closed") }
+ select {
+ case <-cc.doneChan:
+ default:
+ t.Fatal("doneChan not closed")
+ }
}
func TestCancelContext_MarkHandled(t *testing.T) {
cc := newCancelContext()
cc.triggerCancel(CancelAfterChatModel)
- if !cc.markHandled() { t.Error("first should succeed") }
- if cc.markHandled() { t.Error("second should fail") }
+ if !cc.markHandled() {
+ t.Error("first should succeed")
+ }
+ if cc.markHandled() {
+ t.Error("second should fail")
+ }
}
// ---- BuildCancelFunc ----
@@ -93,24 +171,42 @@ func TestCancelContext_MarkHandled(t *testing.T) {
func TestBuildCancelFunc_Immediate(t *testing.T) {
cc := newCancelContext()
_, ok := cc.buildCancelFunc()()
- if !ok { t.Fatal("should contribute") }
- select { case <-cc.immediateChan: case <-time.After(100 * time.Millisecond): t.Fatal("immediate not triggered") }
+ if !ok {
+ t.Fatal("should contribute")
+ }
+ select {
+ case <-cc.immediateChan:
+ case <-time.After(100 * time.Millisecond):
+ t.Fatal("immediate not triggered")
+ }
}
func TestBuildCancelFunc_SafePoint(t *testing.T) {
cc := newCancelContext()
_, ok := cc.buildCancelFunc()(WithCancelMode(CancelAfterChatModel))
- if !ok { t.Fatal("should contribute") }
- if !cc.shouldCancel() { t.Error("should cancel") }
- select { case <-cc.immediateChan: t.Fatal("should NOT be immediate"); case <-time.After(50 * time.Millisecond): }
+ if !ok {
+ t.Fatal("should contribute")
+ }
+ if !cc.shouldCancel() {
+ t.Error("should cancel")
+ }
+ select {
+ case <-cc.immediateChan:
+ t.Fatal("should NOT be immediate")
+ case <-time.After(50 * time.Millisecond):
+ }
}
func TestBuildCancelFunc_AfterDone(t *testing.T) {
cc := newCancelContext()
cc.markDone()
h, ok := cc.buildCancelFunc()()
- if ok { t.Fatal("should not contribute after done") }
- if !errors.Is(h.Wait(), ErrExecutionEnded) { t.Error("expected ErrExecutionEnded") }
+ if ok {
+ t.Fatal("should not contribute after done")
+ }
+ if !errors.Is(h.Wait(), ErrExecutionEnded) {
+ t.Error("expected ErrExecutionEnded")
+ }
}
func TestBuildCancelFunc_Twice(t *testing.T) {
@@ -118,22 +214,36 @@ func TestBuildCancelFunc_Twice(t *testing.T) {
cf := cc.buildCancelFunc()
h1, ok1 := cf(WithCancelMode(CancelAfterChatModel))
h2, ok2 := cf(WithCancelMode(CancelAfterToolCalls))
- if !ok1 || !ok2 { t.Fatal("both should contribute") }
+ if !ok1 || !ok2 {
+ t.Fatal("both should contribute")
+ }
want := CancelAfterChatModel | CancelAfterToolCalls
- if cc.getMode() != want { t.Errorf("mode=%v want=%v", cc.getMode(), want) }
- cc.markHandled(); _ = h1.Wait(); _ = h2.Wait()
+ if cc.getMode() != want {
+ t.Errorf("mode=%v want=%v", cc.getMode(), want)
+ }
+ cc.markHandled()
+ _ = h1.Wait()
+ _ = h2.Wait()
}
func TestBuildCancelFunc_TimeoutEscalation(t *testing.T) {
cc := newCancelContext()
h, _ := cc.buildCancelFunc()(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(30*time.Millisecond))
time.Sleep(100 * time.Millisecond)
- if !cc.isImmediate() { t.Error("should escalate") }
+ if !cc.isImmediate() {
+ t.Error("should escalate")
+ }
cancelErr := cc.createError()
- if !cancelErr.Info.Timeout { t.Error("expected timeout flag") }
- if !cancelErr.Info.Escalated { t.Error("expected escalated") }
+ if !cancelErr.Info.Timeout {
+ t.Error("expected timeout flag")
+ }
+ if !cancelErr.Info.Escalated {
+ t.Error("expected escalated")
+ }
cc.markHandled()
- if !errors.Is(h.Wait(), ErrCancelTimeout) { t.Error("expected ErrCancelTimeout") }
+ if !errors.Is(h.Wait(), ErrCancelTimeout) {
+ t.Error("expected ErrCancelTimeout")
+ }
}
func TestBuildCancelFunc_StateDoneUnderLock(t *testing.T) {
@@ -142,8 +252,12 @@ func TestBuildCancelFunc_StateDoneUnderLock(t *testing.T) {
cf := cc.buildCancelFunc()
cc.markDone()
h, ok := cf()
- if ok { continue }
- if !errors.Is(h.Wait(), ErrExecutionEnded) { t.Error("expected ErrExecutionEnded") }
+ if ok {
+ continue
+ }
+ if !errors.Is(h.Wait(), ErrExecutionEnded) {
+ t.Error("expected ErrExecutionEnded")
+ }
}
}
@@ -166,27 +280,48 @@ func TestBuildCancelFunc_CASFailStateDone(t *testing.T) {
func TestDeriveAgentToolCancelContext(t *testing.T) {
t.Run("Shallow/DoesNotPropagateSafePoint", func(t *testing.T) {
parent := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
- child := parent.deriveAgentToolCancelContext(ctx); defer child.markDone()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ child := parent.deriveAgentToolCancelContext(ctx)
+ defer child.markDone()
parent.triggerCancel(CancelAfterChatModel)
- select { case <-child.cancelChan: t.Fatal("propagated"); case <-time.After(50 * time.Millisecond): }
+ select {
+ case <-child.cancelChan:
+ t.Fatal("propagated")
+ case <-time.After(50 * time.Millisecond):
+ }
})
t.Run("Shallow/ImmediateDoesNotPropagate", func(t *testing.T) {
parent := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
- child := parent.deriveAgentToolCancelContext(ctx); defer child.markDone()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ child := parent.deriveAgentToolCancelContext(ctx)
+ defer child.markDone()
parent.triggerImmediate()
- select { case <-child.immediateChan: t.Fatal("propagated"); case <-time.After(50 * time.Millisecond): }
+ select {
+ case <-child.immediateChan:
+ t.Fatal("propagated")
+ case <-time.After(50 * time.Millisecond):
+ }
})
t.Run("Shallow/GrandchildNoPropagation", func(t *testing.T) {
a := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
b := a.deriveAgentToolCancelContext(ctx)
c := b.deriveAgentToolCancelContext(ctx)
t.Cleanup(func() { c.markDone(); b.markDone() })
a.triggerCancel(CancelAfterChatModel)
- select { case <-b.cancelChan: t.Fatal("b"); case <-time.After(50 * time.Millisecond): }
- select { case <-c.cancelChan: t.Fatal("c"); case <-time.After(50 * time.Millisecond): }
+ select {
+ case <-b.cancelChan:
+ t.Fatal("b")
+ case <-time.After(50 * time.Millisecond):
+ }
+ select {
+ case <-c.cancelChan:
+ t.Fatal("c")
+ case <-time.After(50 * time.Millisecond):
+ }
})
t.Run("Shallow/GoroutineCleanup", func(t *testing.T) {
before := goroutineCount()
@@ -195,43 +330,79 @@ func TestDeriveAgentToolCancelContext(t *testing.T) {
child := parent.deriveAgentToolCancelContext(ctx)
parent.triggerCancel(CancelAfterChatModel)
time.Sleep(100 * time.Millisecond)
- child.markDone(); cancel()
+ child.markDone()
+ cancel()
time.Sleep(200 * time.Millisecond)
- runtime.GC(); time.Sleep(50 * time.Millisecond)
+ runtime.GC()
+ time.Sleep(50 * time.Millisecond)
after := goroutineCount()
- if after > before+5 { t.Errorf("goroutine leak: %d -> %d", before, after) }
+ if after > before+5 {
+ t.Errorf("goroutine leak: %d -> %d", before, after)
+ }
})
t.Run("Recursive/PropagatesSafePoint", func(t *testing.T) {
- parent, child, cleanup := setupParentChild(t); defer cleanup()
+ parent, child, cleanup := setupParentChild(t)
+ defer cleanup()
parent.setRecursive(true)
parent.triggerCancel(CancelAfterChatModel)
- select { case <-child.cancelChan: case <-time.After(1 * time.Second): t.Fatal("child not cancelled") }
- if !child.shouldCancel() { t.Error("child should cancel") }
+ select {
+ case <-child.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("child not cancelled")
+ }
+ if !child.shouldCancel() {
+ t.Error("child should cancel")
+ }
})
t.Run("Recursive/ImmediatePropagates", func(t *testing.T) {
- parent, child, cleanup := setupParentChild(t); defer cleanup()
+ parent, child, cleanup := setupParentChild(t)
+ defer cleanup()
parent.setRecursive(true)
parent.triggerImmediate()
- select { case <-child.immediateChan: case <-time.After(1 * time.Second): t.Fatal("child not immediate") }
- if !child.isImmediate() { t.Error("child should be immediate") }
+ select {
+ case <-child.immediateChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("child not immediate")
+ }
+ if !child.isImmediate() {
+ t.Error("child should be immediate")
+ }
})
t.Run("Recursive/GrandchildPropagation", func(t *testing.T) {
a := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
b := a.deriveAgentToolCancelContext(ctx)
c := b.deriveAgentToolCancelContext(ctx)
t.Cleanup(func() { c.markDone(); b.markDone() })
a.setRecursive(true)
a.triggerCancel(CancelAfterChatModel)
- select { case <-b.cancelChan: case <-time.After(1 * time.Second): t.Fatal("B not cancelled") }
- select { case <-c.cancelChan: case <-time.After(1 * time.Second): t.Fatal("C not cancelled") }
+ select {
+ case <-b.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("B not cancelled")
+ }
+ select {
+ case <-c.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("C not cancelled")
+ }
})
t.Run("Escalation/EscalateFromNonRecursive", func(t *testing.T) {
- parent, child, cleanup := setupParentChild(t); defer cleanup()
+ parent, child, cleanup := setupParentChild(t)
+ defer cleanup()
parent.triggerCancel(CancelAfterChatModel)
- select { case <-child.cancelChan: t.Fatal("should not propagate"); case <-time.After(50 * time.Millisecond): }
+ select {
+ case <-child.cancelChan:
+ t.Fatal("should not propagate")
+ case <-time.After(50 * time.Millisecond):
+ }
parent.setRecursive(true)
- select { case <-child.cancelChan: case <-time.After(1 * time.Second): t.Fatal("child not cancelled") }
+ select {
+ case <-child.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("child not cancelled")
+ }
})
}
@@ -246,31 +417,46 @@ func TestDeriveAgentToolCancelContext_Race(t *testing.T) {
go func() { defer wg.Done(); parent.setRecursive(true) }()
go func() { defer wg.Done(); parent.triggerCancel(CancelAfterChatModel) }()
wg.Wait()
- select { case <-child.cancelChan: case <-time.After(1 * time.Second): t.Fatal("child not cancelled") }
- child.markDone(); cancel()
+ select {
+ case <-child.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("child not cancelled")
+ }
+ child.markDone()
+ cancel()
}
})
t.Run("ChildCompletesBeforeEscalation", func(t *testing.T) {
parent := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
child := parent.deriveAgentToolCancelContext(ctx)
parent.triggerCancel(CancelAfterChatModel)
time.Sleep(50 * time.Millisecond)
child.markDone()
time.Sleep(50 * time.Millisecond)
parent.setRecursive(true)
- select { case <-child.cancelChan: t.Fatal("child done"); case <-time.After(50 * time.Millisecond): }
+ select {
+ case <-child.cancelChan:
+ t.Fatal("child done")
+ case <-time.After(50 * time.Millisecond):
+ }
})
t.Run("MultipleChildren_PartialCompletion", func(t *testing.T) {
parent := newCancelContext()
- ctx, cancel := context.WithCancel(context.Background()); defer cancel()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
child1 := parent.deriveAgentToolCancelContext(ctx)
child2 := parent.deriveAgentToolCancelContext(ctx)
parent.triggerCancel(CancelAfterChatModel)
time.Sleep(50 * time.Millisecond)
child1.markDone()
parent.setRecursive(true)
- select { case <-child2.cancelChan: case <-time.After(1 * time.Second): t.Fatal("child2 not cancelled") }
+ select {
+ case <-child2.cancelChan:
+ case <-time.After(1 * time.Second):
+ t.Fatal("child2 not cancelled")
+ }
child2.markDone()
})
}
@@ -279,8 +465,12 @@ func TestDeriveAgentToolCancelContext_Race(t *testing.T) {
func TestGraphInterruptFuncs_Parallel(t *testing.T) {
cc := newCancelContext()
- if !cc.sendInterrupt() { t.Error("first should succeed") }
- if cc.sendInterrupt() { t.Error("second should fail") }
+ if !cc.sendInterrupt() {
+ t.Error("first should succeed")
+ }
+ if cc.sendInterrupt() {
+ t.Error("second should fail")
+ }
}
// ---- TestFilterCancelOption ----
@@ -288,7 +478,9 @@ func TestGraphInterruptFuncs_Parallel(t *testing.T) {
func TestFilterCancelOption(t *testing.T) {
opt, _ := WithCancel()
result := filterCancelOption([]RunOption{opt})
- if len(result) != 0 { t.Error("cancel option should be filtered") }
+ if len(result) != 0 {
+ t.Error("cancel option should be filtered")
+ }
}
// ---- TestWrapIterWithMarkDone ----
@@ -301,13 +493,16 @@ func TestWrapIterWithMarkDone(t *testing.T) {
go func() { defer gen.Close(); gen.Send(&TypedAgentEvent[*schema.Message]{}) }()
wrapped := wrapIterWithCancelCtx(it, cc)
_, ok := wrapped.Next()
- cc.markHandled(); _ = ok
+ cc.markHandled()
+ _ = ok
})
t.Run("WithoutCancelContext", func(t *testing.T) {
it, gen := NewAsyncIteratorPair[*TypedAgentEvent[*schema.Message]]()
go func() { defer gen.Close(); gen.Send(&TypedAgentEvent[*schema.Message]{}) }()
wrapped := wrapIterWithCancelCtx(it, nil)
- if _, ok := wrapped.Next(); !ok { t.Fatal("expected event") }
+ if _, ok := wrapped.Next(); !ok {
+ t.Fatal("expected event")
+ }
})
}
@@ -316,8 +511,12 @@ func TestWrapIterWithMarkDone(t *testing.T) {
func TestHandleRunFuncError_AlreadyHandled_NoDuplicate(t *testing.T) {
cc := newCancelContext()
cc.triggerCancel(CancelAfterChatModel)
- if !cc.markHandled() { t.Fatal("first should succeed") }
- if cc.markHandled() { t.Fatal("second should fail") }
+ if !cc.markHandled() {
+ t.Fatal("first should succeed")
+ }
+ if cc.markHandled() {
+ t.Fatal("second should fail")
+ }
}
// ---- TestCancel_SafePointNeverFires ----
@@ -329,7 +528,13 @@ func TestCancel_SafePointNeverFires_ErrExecutionEnded(t *testing.T) {
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("hi")}}, opt)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
// ---- TestCancelContextKey ----
@@ -338,20 +543,30 @@ func TestCancelContextKey(t *testing.T) {
cc := newCancelContext()
ctx := withCancelContext(context.Background(), cc)
got := getCancelContext(ctx)
- if got == nil { t.Fatal("expected cancelContext") }
- if v := getCancelContext(context.Background()); v != nil { t.Error("expected nil") }
+ if got == nil {
+ t.Fatal("expected cancelContext")
+ }
+ if v := getCancelContext(context.Background()); v != nil {
+ t.Error("expected nil")
+ }
}
// ---- Workflow Cancel Tests ----
func TestWithCancel_SequentialAgent(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("A1")
- m2 := &mockModel{}; m2.addResp("A2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "s1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "s2"
+ m1 := &mockModel{}
+ m1.addResp("A1")
+ m2 := &mockModel{}
+ m2.addResp("A2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "s1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "s2"
ctx := context.Background()
wf, err := NewSequential(ctx, &SequentialConfig{Name: "seq", Description: "test", SubAgents: []Agent{a1, a2}})
- if err != nil { t.Fatalf("NewSequential: %v", err) }
+ if err != nil {
+ t.Fatalf("NewSequential: %v", err)
+ }
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel()
@@ -359,13 +574,19 @@ func TestWithCancel_SequentialAgent(t *testing.T) {
}
func TestWithCancel_LoopAgent(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("L1")
- m2 := &mockModel{}; m2.addResp("L2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "l1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "l2"
+ m1 := &mockModel{}
+ m1.addResp("L1")
+ m2 := &mockModel{}
+ m2.addResp("L2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "l1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "l2"
ctx := context.Background()
wf, err := NewLoop(ctx, &LoopConfig{Name: "loop", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 5})
- if err != nil { t.Fatalf("NewLoop: %v", err) }
+ if err != nil {
+ t.Fatalf("NewLoop: %v", err)
+ }
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel()
@@ -373,13 +594,19 @@ func TestWithCancel_LoopAgent(t *testing.T) {
}
func TestWithCancel_ParallelAgent(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("P1")
- m2 := &mockModel{}; m2.addResp("P2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "p1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "p2"
+ m1 := &mockModel{}
+ m1.addResp("P1")
+ m2 := &mockModel{}
+ m2.addResp("P2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "p1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "p2"
ctx := context.Background()
wf, err := NewParallel(ctx, &ParallelConfig{Name: "par", Description: "test", SubAgents: []Agent{a1, a2}})
- if err != nil { t.Fatalf("NewParallel: %v", err) }
+ if err != nil {
+ t.Fatalf("NewParallel: %v", err)
+ }
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel()
@@ -387,61 +614,99 @@ func TestWithCancel_ParallelAgent(t *testing.T) {
}
func TestCheckCancel_Sequential_BetweenSubAgents(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("X1")
- m2 := &mockModel{}; m2.addResp("X2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "x1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "x2"
+ m1 := &mockModel{}
+ m1.addResp("X1")
+ m2 := &mockModel{}
+ m2.addResp("X2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "x1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "x2"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "chk", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCheckCancel_Loop_BetweenIterations(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("Y1")
- m2 := &mockModel{}; m2.addResp("Y2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "y1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "y2"
+ m1 := &mockModel{}
+ m1.addResp("Y1")
+ m2 := &mockModel{}
+ m2.addResp("Y2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "y1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "y2"
ctx := context.Background()
wf, _ := NewLoop(ctx, &LoopConfig{Name: "chk_loop", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 5})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCheckCancel_Parallel_PreSpawn(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("Z1")
- m2 := &mockModel{}; m2.addResp("Z2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "z1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "z2"
+ m1 := &mockModel{}
+ m1.addResp("Z1")
+ m2 := &mockModel{}
+ m2.addResp("Z2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "z1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "z2"
ctx := context.Background()
wf, _ := NewParallel(ctx, &ParallelConfig{Name: "chk_par", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
// ---- Cancel after completion ----
func TestWithCancel_AfterCompletion(t *testing.T) {
- model := &mockModel{}; model.addResp("done")
+ model := &mockModel{}
+ model.addResp("done")
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model})
agent.name = "after"
opt, cancel := WithCancel()
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("hi")}}, opt)
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
h, ok := cancel()
if !ok {
- if !errors.Is(h.Wait(), ErrExecutionEnded) { t.Error("expected ErrExecutionEnded") }
+ if !errors.Is(h.Wait(), ErrExecutionEnded) {
+ t.Error("expected ErrExecutionEnded")
+ }
}
}
-
// ---- Helpers ----
func goroutineCount() int { n := runtime.NumGoroutine(); return n }
@@ -453,14 +718,13 @@ func setupParentChild(t *testing.T) (parent, child *cancelContext, cleanup func(
return parent, child, func() { child.markDone(); cancel() }
}
-
// cancelUnawareAgent is a custom Agent that ignores ctx.Done (doesn't participate in cancel protocol).
type cancelUnawareAgent struct {
name string
desc string
}
-func (a *cancelUnawareAgent) Name(_ context.Context) string { return a.name }
+func (a *cancelUnawareAgent) Name(_ context.Context) string { return a.name }
func (a *cancelUnawareAgent) Description(_ context.Context) string { return a.desc }
func (a *cancelUnawareAgent) Run(ctx context.Context, input *AgentInput, opts ...RunOption) *AsyncIterator[*AgentEvent] {
@@ -487,7 +751,13 @@ func TestCancelWithTools_CancelImmediate(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(50 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelWithTools_CancelAfterChatModel(t *testing.T) {
@@ -504,7 +774,13 @@ func TestCancelWithTools_CancelAfterChatModel(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(50 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelWithTools_CancelAfterToolCalls(t *testing.T) {
@@ -522,7 +798,13 @@ func TestCancelWithTools_CancelAfterToolCalls(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(50 * time.Millisecond)
cancel(WithCancelMode(CancelAfterToolCalls))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestWithCancel_WithCheckpoint(t *testing.T) {
@@ -536,7 +818,13 @@ func TestWithCancel_WithCheckpoint(t *testing.T) {
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent, CheckPointStore: store})
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestWithCancel_Streaming(t *testing.T) {
@@ -550,7 +838,13 @@ func TestWithCancel_Streaming(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}, EnableStreaming: true}, opt)
time.Sleep(30 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
})
t.Run("CancelAfterToolCalls", func(t *testing.T) {
model := newCancelTestChatModel(nil)
@@ -567,7 +861,13 @@ func TestWithCancel_Streaming(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}, EnableStreaming: true}, opt)
time.Sleep(50 * time.Millisecond)
cancel(WithCancelMode(CancelAfterToolCalls))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
})
}
@@ -582,14 +882,24 @@ func TestWithCancel_Resume(t *testing.T) {
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent, CheckPointStore: store})
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancel_SequentialWorkflow_CancelAfterChatModel(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("A1")
- m2 := newCancelTestChatModel(nil); m2.addResp("A2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "s1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "s2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("A1")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("A2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "s1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "s2"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "seq", Description: "test", SubAgents: []Agent{a1, a2}})
store := newCancelTestStore()
@@ -598,92 +908,159 @@ func TestCancel_SequentialWorkflow_CancelAfterChatModel(t *testing.T) {
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancel_ParallelWorkflow_CancelAfterChatModel(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("P1")
- m2 := newCancelTestChatModel(nil); m2.addResp("P2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "p1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "p2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("P1")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("P2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "p1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "p2"
ctx := context.Background()
wf, _ := NewParallel(ctx, &ParallelConfig{Name: "par", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancel_LoopWorkflow_CancelAfterChatModel(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("L1")
- m2 := newCancelTestChatModel(nil); m2.addResp("L2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "l1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "l2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("L1")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("L2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "l1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "l2"
ctx := context.Background()
wf, _ := NewLoop(ctx, &LoopConfig{Name: "loop", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 5})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCheckCancel_Transfer_BeforeTarget(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("route")
- s1 := newCancelTestChatModel(nil); s1.addResp("sub")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "sup"
- sAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: s1}); sAgent.name = "sub1"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("route")
+ s1 := newCancelTestChatModel(nil)
+ s1.addResp("sub")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "sup"
+ sAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: s1})
+ sAgent.name = "sub1"
ctx := context.Background()
sup, err := SetSubAgents(ctx, a1, []Agent{sAgent})
- if err != nil { t.Fatalf("SetSubAgents: %v", err) }
+ if err != nil {
+ t.Fatalf("SetSubAgents: %v", err)
+ }
opt, cancel := WithCancel()
iter := sup.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("transfer")}}, opt)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
-
func TestCancelImmediate_SequentialTransitionBoundary(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("A")
- m2 := newCancelTestChatModel(nil); m2.addResp("B")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "x1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "x2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("A")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("B")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "x1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "x2"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "seq_bound", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelImmediate_LoopTransitionBoundary(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("L")
- m2 := newCancelTestChatModel(nil); m2.addResp("L")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "lx"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "ly"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("L")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("L")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "lx"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "ly"
ctx := context.Background()
wf, _ := NewLoop(ctx, &LoopConfig{Name: "loop_bound", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 5})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelAfterChatModel_SequentialTransitionBoundary(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("A")
- m2 := newCancelTestChatModel(nil); m2.addResp("B")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "t1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "t2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("A")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("B")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "t1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "t2"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "seq_trans", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelImmediate_OrphanedToolGoroutine_NoPanic(t *testing.T) {
@@ -691,27 +1068,46 @@ func TestCancelImmediate_OrphanedToolGoroutine_NoPanic(t *testing.T) {
}
func TestCancelImmediate_MultiLevelNesting(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("root")
- m2 := newCancelTestChatModel(nil); m2.addResp("mid")
- m3 := newCancelTestChatModel(nil); m3.addResp("leaf")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "root"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "mid"
- a3 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m3}); a3.name = "leaf"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("root")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("mid")
+ m3 := newCancelTestChatModel(nil)
+ m3.addResp("leaf")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "root"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "mid"
+ a3 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m3})
+ a3.name = "leaf"
ctx := context.Background()
midFlow, err := SetSubAgents(ctx, a2, []Agent{a3})
- if err != nil { t.Fatalf("SetSubAgents mid: %v", err) }
+ if err != nil {
+ t.Fatalf("SetSubAgents mid: %v", err)
+ }
rootFlow, err := SetSubAgents(ctx, a1, []Agent{midFlow})
- if err != nil { t.Fatalf("SetSubAgents root: %v", err) }
+ if err != nil {
+ t.Fatalf("SetSubAgents root: %v", err)
+ }
opt, cancel := WithCancel()
iter := rootFlow.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("nested")}}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancel_NestedWorkflow_AgentTool_CancelAfterChatModel(t *testing.T) {
- mRoot := newCancelTestChatModel(nil); mRoot.addResp("tool")
- mLeaf := newCancelTestChatModel(nil); mLeaf.addResp("leaf")
- leafAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: mLeaf}); leafAgent.name = "leaf"
+ mRoot := newCancelTestChatModel(nil)
+ mRoot.addResp("tool")
+ mLeaf := newCancelTestChatModel(nil)
+ mLeaf.addResp("leaf")
+ leafAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: mLeaf})
+ leafAgent.name = "leaf"
tool := NewAgentTool(context.Background(), leafAgent)
rootAgent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: mRoot, Tools: []Tool{tool}, ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
@@ -722,25 +1118,41 @@ func TestCancel_NestedWorkflow_AgentTool_CancelAfterChatModel(t *testing.T) {
iter := rootAgent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("start")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancel_CancelAfterToolCalls_InSequentialWorkflow(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("X")
- m2 := newCancelTestChatModel(nil); m2.addResp("Y")
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("X")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("Y")
slow := newSlowTool("slow_tool", 30*time.Millisecond, "result")
a1 := NewReActAgent(&ReActConfig[*schema.Message]{
Model: m1, Tools: []Tool{slow},
ToolsConfig: &ToolsNodeConfig{Tools: []Tool{slow}},
- }); a1.name = "with_tool"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "after_tool"
+ })
+ a1.name = "with_tool"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "after_tool"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "seq_tool", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(50 * time.Millisecond)
cancel(WithCancelMode(CancelAfterToolCalls))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelImmediate_CancelUnawareAgent_GracePeriodFallback(t *testing.T) {
@@ -750,31 +1162,53 @@ func TestCancelImmediate_CancelUnawareAgent_GracePeriodFallback(t *testing.T) {
opt := WrapImplSpecificOptFn(func(o *runOptions) { o.cancelCtx = cc })
iter := ua.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("hi")}}, opt)
cc.triggerImmediate()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelImmediate_ParallelWorkflow_WithAgentTool(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("P1")
- m2 := newCancelTestChatModel(nil); m2.addResp("P2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "pt1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "pt2"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("P1")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("P2")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "pt1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "pt2"
ctx := context.Background()
wf, _ := NewParallel(ctx, &ParallelConfig{Name: "par_tool", Description: "test", SubAgents: []Agent{a1, a2}})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestAgentCancelFuncMultipleCalls(t *testing.T) {
cc := newCancelContext()
cf := cc.buildCancelFunc()
h1, ok1 := cf()
- if !ok1 { t.Fatal("first should contribute") }
+ if !ok1 {
+ t.Fatal("first should contribute")
+ }
cc.markDone()
h2, ok2 := cf()
- if ok2 { t.Fatal("second should not contribute") }
- if !errors.Is(h2.Wait(), ErrExecutionEnded) { t.Error("expected ErrExecutionEnded") }
+ if ok2 {
+ t.Fatal("second should not contribute")
+ }
+ if !errors.Is(h2.Wait(), ErrExecutionEnded) {
+ t.Error("expected ErrExecutionEnded")
+ }
h1.Wait()
}
@@ -783,8 +1217,12 @@ func TestAgentCancelFunc_MultiCall_EscalateToImmediate(t *testing.T) {
cf := cc.buildCancelFunc()
cf(WithCancelMode(CancelAfterChatModel))
cf(WithCancelMode(CancelImmediate))
- if cc.getMode() != CancelImmediate { t.Errorf("expected CancelImmediate, got %v", cc.getMode()) }
- if atomic.LoadInt32(&cc.escalated) != 1 { t.Error("expected escalated") }
+ if cc.getMode() != CancelImmediate {
+ t.Errorf("expected CancelImmediate, got %v", cc.getMode())
+ }
+ if atomic.LoadInt32(&cc.escalated) != 1 {
+ t.Error("expected escalated")
+ }
}
func TestAgentCancelFunc_MultiCall_JoinSafePointModes(t *testing.T) {
@@ -793,28 +1231,42 @@ func TestAgentCancelFunc_MultiCall_JoinSafePointModes(t *testing.T) {
cf(WithCancelMode(CancelAfterChatModel))
cf(WithCancelMode(CancelAfterToolCalls))
want := CancelAfterChatModel | CancelAfterToolCalls
- if cc.getMode() != want { t.Errorf("mode=%v want=%v", cc.getMode(), want) }
+ if cc.getMode() != want {
+ t.Errorf("mode=%v want=%v", cc.getMode(), want)
+ }
}
func TestAgentCancelFunc_MultiCall_TimeoutEscalationReturnsErrCancelTimeout(t *testing.T) {
cc := newCancelContext()
cf := cc.buildCancelFunc()
_, ok := cf(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(20*time.Millisecond))
- if !ok { t.Fatal("first should contribute") }
+ if !ok {
+ t.Fatal("first should contribute")
+ }
time.Sleep(50 * time.Millisecond)
- if !cc.isImmediate() { t.Error("should escalate to immediate") }
- if atomic.LoadInt32(&cc.timeoutEscalated) != 1 { t.Error("expected timeout escalated") }
+ if !cc.isImmediate() {
+ t.Error("should escalate to immediate")
+ }
+ if atomic.LoadInt32(&cc.timeoutEscalated) != 1 {
+ t.Error("expected timeout escalated")
+ }
}
func TestAgentCancelFunc_MultiCall_TimeoutDeadlineJoinUsesAbsoluteTime(t *testing.T) {
cc := newCancelContext()
cf := cc.buildCancelFunc()
_, ok1 := cf(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(200*time.Millisecond))
- if !ok1 { t.Fatal("first should contribute") }
+ if !ok1 {
+ t.Fatal("first should contribute")
+ }
_, ok2 := cf(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(20*time.Millisecond))
- if !ok2 { t.Fatal("second should contribute") }
+ if !ok2 {
+ t.Fatal("second should contribute")
+ }
time.Sleep(50 * time.Millisecond)
- if !cc.isImmediate() { t.Error("should escalate to immediate after short timeout") }
+ if !cc.isImmediate() {
+ t.Error("should escalate to immediate after short timeout")
+ }
}
func TestCancelContext_RecursiveGraceBoundary(t *testing.T) {
@@ -825,11 +1277,17 @@ func TestCancelContext_RecursiveGraceBoundary(t *testing.T) {
c := b.deriveAgentToolCancelContext(ctx)
t.Cleanup(func() { c.markDone(); b.markDone() })
a.setRecursive(true)
- if !a.isRecursive() { t.Error("a should be recursive") }
+ if !a.isRecursive() {
+ t.Error("a should be recursive")
+ }
a.triggerCancel(CancelAfterChatModel)
time.Sleep(100 * time.Millisecond)
- if !b.shouldCancel() { t.Error("b should cancel (propagated)") }
- if !c.shouldCancel() { t.Error("c should cancel (propagated)") }
+ if !b.shouldCancel() {
+ t.Error("b should cancel (propagated)")
+ }
+ if !c.shouldCancel() {
+ t.Error("c should cancel (propagated)")
+ }
}
func TestDeriveAgentToolCancelContext_ContextCancelConcurrentWithRecursive(t *testing.T) {
@@ -863,27 +1321,45 @@ func TestDeriveAgentToolCancelContext_ConcurrentSetRecursive(t *testing.T) {
}
func TestWithCancel_SupervisorAgent(t *testing.T) {
- mSup := newCancelTestChatModel(nil); mSup.addResp("sup")
- mSub := newCancelTestChatModel(nil); mSub.addResp("sub")
- sup := NewReActAgent(&ReActConfig[*schema.Message]{Model: mSup}); sup.name = "supervisor"
- sub := NewReActAgent(&ReActConfig[*schema.Message]{Model: mSub}); sub.name = "sub1"
+ mSup := newCancelTestChatModel(nil)
+ mSup.addResp("sup")
+ mSub := newCancelTestChatModel(nil)
+ mSub.addResp("sub")
+ sup := NewReActAgent(&ReActConfig[*schema.Message]{Model: mSup})
+ sup.name = "supervisor"
+ sub := NewReActAgent(&ReActConfig[*schema.Message]{Model: mSub})
+ sub.name = "sub1"
ctx := context.Background()
flow, err := SetSubAgents(ctx, sup, []Agent{sub})
- if err != nil { t.Fatalf("SetSubAgents: %v", err) }
+ if err != nil {
+ t.Fatalf("SetSubAgents: %v", err)
+ }
opt, cancel := WithCancel()
iter := flow.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("route")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelAfterChatModel_Sequential_Agent1CompletesCancelBeforeAgent2Resume(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("A")
- m2 := newCancelTestChatModel(nil); m2.addResp("B")
- m3 := newCancelTestChatModel(nil); m3.addResp("C")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "a"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "b"
- a3 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m3}); a3.name = "c"
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("A")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("B")
+ m3 := newCancelTestChatModel(nil)
+ m3.addResp("C")
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "a"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "b"
+ a3 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m3})
+ a3.name = "c"
ctx := context.Background()
wf, _ := NewSequential(ctx, &SequentialConfig{Name: "seq3", Description: "test", SubAgents: []Agent{a1, a2, a3}})
store := newCancelTestStore()
@@ -892,13 +1368,22 @@ func TestCancelAfterChatModel_Sequential_Agent1CompletesCancelBeforeAgent2Resume
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterChatModel))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelImmediate_AgentTool_PreservesChildCheckpoint(t *testing.T) {
- mRoot := newCancelTestChatModel(nil); mRoot.addResp("tool")
- mLeaf := newCancelTestChatModel(nil); mLeaf.addResp("leaf")
- leafAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: mLeaf}); leafAgent.name = "leaf"
+ mRoot := newCancelTestChatModel(nil)
+ mRoot.addResp("tool")
+ mLeaf := newCancelTestChatModel(nil)
+ mLeaf.addResp("leaf")
+ leafAgent := NewReActAgent(&ReActConfig[*schema.Message]{Model: mLeaf})
+ leafAgent.name = "leaf"
agt := NewAgentTool(context.Background(), leafAgent)
root := NewReActAgent(&ReActConfig[*schema.Message]{
Model: mRoot, Tools: []Tool{agt},
@@ -912,26 +1397,43 @@ func TestCancelImmediate_AgentTool_PreservesChildCheckpoint(t *testing.T) {
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
time.Sleep(50 * time.Millisecond)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
func TestCancelAfterToolCalls_LoopTransitionBoundary(t *testing.T) {
- m1 := newCancelTestChatModel(nil); m1.addResp("tool")
+ m1 := newCancelTestChatModel(nil)
+ m1.addResp("tool")
tool := newSlowTool("slow_tool", 50*time.Millisecond, "result")
- m2 := newCancelTestChatModel(nil); m2.addResp("L2")
+ m2 := newCancelTestChatModel(nil)
+ m2.addResp("L2")
l1 := NewReActAgent(&ReActConfig[*schema.Message]{
Model: m1, Tools: []Tool{tool},
ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
- }); l1.name = "l_tool"
- l2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); l2.name = "l_done"
+ })
+ l1.name = "l_tool"
+ l2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ l2.name = "l_done"
ctx := context.Background()
wf, _ := NewLoop(ctx, &LoopConfig{Name: "loop_tool", Description: "test", SubAgents: []Agent{l1, l2}, MaxIterations: 5})
opt, cancel := WithCancel()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(100 * time.Millisecond)
cancel(WithCancelMode(CancelAfterToolCalls))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
+
// ================================================================
// Edge-case tests from the ADK cancel_edge_test.go / cancel_multicall_test.go
// ================================================================
@@ -946,7 +1448,13 @@ func TestCancel_BeforeExecutionStarts(t *testing.T) {
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("fail")}}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
// TestCancel_AfterBusinessInterrupt verifies that cancelling after a
@@ -965,7 +1473,13 @@ func TestCancel_AfterBusinessInterrupt(t *testing.T) {
}).WithName("biz_interrupt")
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
opt, cancel := WithCancel()
h, ok := cancel()
if !ok {
@@ -983,7 +1497,13 @@ func TestCancel_AfterError(t *testing.T) {
opt, cancel := WithCancel()
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("fail")}}, opt)
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
h, ok := cancel()
if !ok {
if !errors.Is(h.Wait(), ErrExecutionEnded) {
@@ -999,7 +1519,13 @@ func TestCancel_ModelError(t *testing.T) {
opt, cancel := WithCancel()
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("fail")}}, opt)
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
h, ok := cancel()
if !ok {
if !errors.Is(h.Wait(), ErrExecutionEnded) {
@@ -1018,7 +1544,13 @@ func TestCancel_NoCheckpointStore(t *testing.T) {
ctx := context.Background()
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("run")}, opt)
cancel()
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
// TestCancel_MultipleToolsConcurrent verifies CancelAfterToolCalls waits
@@ -1038,7 +1570,13 @@ func TestCancel_MultipleToolsConcurrent(t *testing.T) {
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}}, opt)
time.Sleep(30 * time.Millisecond)
cancel(WithCancelMode(CancelAfterToolCalls))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
}
// TestCancel_TimeoutEscalation_Flags verifies CancelError has correct flags.
@@ -1048,8 +1586,12 @@ func TestCancel_TimeoutEscalation_Flags(t *testing.T) {
cc.timeoutEscalated = 1
cc.escalated = 1
cancelErr := cc.createError()
- if !cancelErr.Info.Timeout { t.Error("expected Timeout flag") }
- if !cancelErr.Info.Escalated { t.Error("expected Escalated flag") }
+ if !cancelErr.Info.Timeout {
+ t.Error("expected Timeout flag")
+ }
+ if !cancelErr.Info.Escalated {
+ t.Error("expected Escalated flag")
+ }
}
// TestCancel_MultiCall_TimeoutDeadlineJoinAbsolute verifies absolute time join.
@@ -1057,10 +1599,18 @@ func TestCancel_MultiCall_TimeoutDeadlineJoinAbsolute(t *testing.T) {
cc := newCancelContext()
cf := cc.buildCancelFunc()
_, ok1 := cf(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(200*time.Millisecond))
- if !ok1 { t.Fatal("first should contribute") }
+ if !ok1 {
+ t.Fatal("first should contribute")
+ }
_, ok2 := cf(WithCancelMode(CancelAfterChatModel), WithCancelTimeout(20*time.Millisecond))
- if !ok2 { t.Fatal("second should contribute") }
+ if !ok2 {
+ t.Fatal("second should contribute")
+ }
time.Sleep(50 * time.Millisecond)
- if !cc.isImmediate() { t.Error("should escalate to immediate after short timeout") }
- if atomic.LoadInt32(&cc.timeoutEscalated) != 1 { t.Error("expected timeout escalated") }
+ if !cc.isImmediate() {
+ t.Error("should escalate to immediate after short timeout")
+ }
+ if atomic.LoadInt32(&cc.timeoutEscalated) != 1 {
+ t.Error("expected timeout escalated")
+ }
}
diff --git a/internal/harness/core/contracts.go b/internal/harness/core/contracts.go
index ad19eb6a28..882488a5ca 100644
--- a/internal/harness/core/contracts.go
+++ b/internal/harness/core/contracts.go
@@ -52,9 +52,9 @@ type Tool interface {
type ToolCapability int
const (
- ToolCapReadOnly ToolCapability = iota // Safe to run in parallel
- ToolCapWritesFiles // File mutation, serialize
- ToolCapExecutesCode // Code execution, serialize
+ ToolCapReadOnly ToolCapability = iota // Safe to run in parallel
+ ToolCapWritesFiles // File mutation, serialize
+ ToolCapExecutesCode // Code execution, serialize
ToolCapNetwork // Network access, serialize
)
@@ -88,17 +88,19 @@ type ToolInfoProvider interface {
// BaseTool provides a simple Tool implementation from a function.
type BaseTool struct {
- name string
- desc string
+ name string
+ desc string
invokeFn func(ctx context.Context, args string) (string, error)
}
func NewBaseTool(name, desc string, fn func(ctx context.Context, args string) (string, error)) *BaseTool {
return &BaseTool{name: name, desc: desc, invokeFn: fn}
}
-func (t *BaseTool) Name() string { return t.name }
-func (t *BaseTool) Description() string { return t.desc }
-func (t *BaseTool) Invoke(ctx context.Context, args string, opts ...toolOption) (string, error) { return t.invokeFn(ctx, args) }
+func (t *BaseTool) Name() string { return t.name }
+func (t *BaseTool) Description() string { return t.desc }
+func (t *BaseTool) Invoke(ctx context.Context, args string, opts ...toolOption) (string, error) {
+ return t.invokeFn(ctx, args)
+}
func (t *BaseTool) Stream(ctx context.Context, args string, opts ...toolOption) (*schema.StreamReader[string], error) {
return schema.StreamReaderFromArray([]string{""}), nil
}
@@ -152,8 +154,18 @@ type (
// Embed in custom middlewares to only override needed methods.
type BaseMiddleware[M MessageType] struct{}
-func (b *BaseMiddleware[M]) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) { return ctx, rc, nil }
-func (b *BaseMiddleware[M]) AfterAgent(ctx context.Context, state *TypedReActAgentState[M]) (context.Context, error) { return ctx, nil }
-func (b *BaseMiddleware[M]) BeforeModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) { return ctx, state, nil }
-func (b *BaseMiddleware[M]) AfterModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) { return ctx, state, nil }
-func (b *BaseMiddleware[M]) WrapModel(_ context.Context, m Model[M], _ *TypedModelContext[M]) (Model[M], error) { return m, nil }
+func (b *BaseMiddleware[M]) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) {
+ return ctx, rc, nil
+}
+func (b *BaseMiddleware[M]) AfterAgent(ctx context.Context, state *TypedReActAgentState[M]) (context.Context, error) {
+ return ctx, nil
+}
+func (b *BaseMiddleware[M]) BeforeModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) {
+ return ctx, state, nil
+}
+func (b *BaseMiddleware[M]) AfterModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) {
+ return ctx, state, nil
+}
+func (b *BaseMiddleware[M]) WrapModel(_ context.Context, m Model[M], _ *TypedModelContext[M]) (Model[M], error) {
+ return m, nil
+}
diff --git a/internal/harness/core/contracts_test.go b/internal/harness/core/contracts_test.go
index 1c5983c3c1..f25cf7e5f1 100644
--- a/internal/harness/core/contracts_test.go
+++ b/internal/harness/core/contracts_test.go
@@ -298,8 +298,12 @@ func TestMiddleware_WrapModelReturnsError(t *testing.T) {
var lastErr error
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { lastErr = ev.Err }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
}
if lastErr == nil {
t.Error("expected error from WrapModel middleware")
@@ -307,4 +311,3 @@ func TestMiddleware_WrapModelReturnsError(t *testing.T) {
}
// ---- Tool integration with middleware chain ----
-
diff --git a/internal/harness/core/deterministic_transfer_test.go b/internal/harness/core/deterministic_transfer_test.go
index 34e702f7a2..c89286cdc8 100644
--- a/internal/harness/core/deterministic_transfer_test.go
+++ b/internal/harness/core/deterministic_transfer_test.go
@@ -12,8 +12,14 @@ import (
type dtTestStore struct{ data map[string][]byte }
func newDTTestStore() *dtTestStore { return &dtTestStore{data: make(map[string][]byte)} }
-func (s *dtTestStore) Set(_ context.Context, key string, value []byte) error { s.data[key] = value; return nil }
-func (s *dtTestStore) Get(_ context.Context, key string) ([]byte, bool, error) { v, ok := s.data[key]; return v, ok, nil }
+func (s *dtTestStore) Set(_ context.Context, key string, value []byte) error {
+ s.data[key] = value
+ return nil
+}
+func (s *dtTestStore) Get(_ context.Context, key string) ([]byte, bool, error) {
+ v, ok := s.data[key]
+ return v, ok, nil
+}
type dtTestAgent struct {
name string
@@ -27,7 +33,9 @@ func (a *dtTestAgent) Run(ctx context.Context, input *AgentInput, options ...Run
return a.runFn(ctx, input, options...)
}
func (a *dtTestAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...RunOption) *AsyncIterator[*AgentEvent] {
- if a.resumeFn != nil { return a.resumeFn(ctx, info, opts...) }
+ if a.resumeFn != nil {
+ return a.resumeFn(ctx, info, opts...)
+ }
return a.runFn(ctx, &AgentInput{}, opts...)
}
@@ -53,7 +61,9 @@ func TestDeterministicTransfer_Basic(t *testing.T) {
},
resumeFn: func(ctx context.Context, info *ResumeInfo, opts ...RunOption) *AsyncIterator[*AgentEvent] {
runCount++
- if !info.WasInterrupted { t.Error("should be interrupted") }
+ if !info.WasInterrupted {
+ t.Error("should be interrupted")
+ }
runCtx := getRunCtx(ctx)
_ = runCtx
iter, gen := NewAsyncIteratorPair[*AgentEvent]()
diff --git a/internal/harness/core/evals/coding/coding_evals_test.go b/internal/harness/core/evals/coding/coding_evals_test.go
index f5ed939a02..7f6a01a347 100644
--- a/internal/harness/core/evals/coding/coding_evals_test.go
+++ b/internal/harness/core/evals/coding/coding_evals_test.go
@@ -94,12 +94,12 @@ type localBackend struct {
func (b *localBackend) Read(path string) (string, error) {
return "", nil
}
-func (b *localBackend) Write(path, content string) error { return nil }
-func (b *localBackend) Edit(path, old, new string) error { return nil }
-func (b *localBackend) Ls(path string) ([]string, error) { return nil, nil }
-func (b *localBackend) Glob(pattern string) ([]string, error) { return nil, nil }
+func (b *localBackend) Write(path, content string) error { return nil }
+func (b *localBackend) Edit(path, old, new string) error { return nil }
+func (b *localBackend) Ls(path string) ([]string, error) { return nil, nil }
+func (b *localBackend) Glob(pattern string) ([]string, error) { return nil, nil }
func (b *localBackend) Grep(pattern, path string) (string, error) { return "", nil }
-func (b *localBackend) Execute(command string) (string, error) { return "", nil }
+func (b *localBackend) Execute(command string) (string, error) { return "", nil }
// ---- E2E Tests ----
@@ -233,7 +233,7 @@ func TestE2E_MultipleCases(t *testing.T) {
MaxConcurrency: 2,
Cases: []evals.EvalCase{
{
- Name: "write_main",
+ Name: "write_main",
Query: "create main.go",
Agent: coding.New(&coding.Config{
Model: newScriptedModel(
@@ -245,7 +245,7 @@ func TestE2E_MultipleCases(t *testing.T) {
Scorers: []evals.Scorer{evals.ToolCalled("write_file")},
},
{
- Name: "list_files",
+ Name: "list_files",
Query: "show files",
Agent: coding.New(&coding.Config{
Model: newScriptedModel(
diff --git a/internal/harness/core/evals/evals.go b/internal/harness/core/evals/evals.go
index 401673cfde..527409e377 100644
--- a/internal/harness/core/evals/evals.go
+++ b/internal/harness/core/evals/evals.go
@@ -81,7 +81,7 @@ type EvalResult struct {
Messages []*schema.Message // full conversation trajectory
Events []*core.AgentEvent
Duration time.Duration
- Err error // agent execution error (if any)
+ Err error // agent execution error (if any)
Snapshot map[string]string // file snapshots after execution
}
diff --git a/internal/harness/core/event_sender.go b/internal/harness/core/event_sender.go
index 14043b624a..04b6d35efd 100644
--- a/internal/harness/core/event_sender.go
+++ b/internal/harness/core/event_sender.go
@@ -20,15 +20,25 @@ type eventSenderModelHandler[M MessageType] struct{}
func (h *eventSenderModelHandler[M]) WrapModel(ctx context.Context, m Model[M], mc *TypedModelContext[M]) (Model[M], error) {
ec := getReActExecCtx[M](ctx)
- if ec == nil { return m, nil }
+ if ec == nil {
+ return m, nil
+ }
return wrapModelWithEventSender(m, ec), nil
}
// All other middleware methods are no-op
-func (h *eventSenderModelHandler[M]) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) { return ctx, rc, nil }
-func (h *eventSenderModelHandler[M]) AfterAgent(ctx context.Context, state *TypedReActAgentState[M]) (context.Context, error) { return ctx, nil }
-func (h *eventSenderModelHandler[M]) BeforeModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) { return ctx, state, nil }
-func (h *eventSenderModelHandler[M]) AfterModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) { return ctx, state, nil }
+func (h *eventSenderModelHandler[M]) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) {
+ return ctx, rc, nil
+}
+func (h *eventSenderModelHandler[M]) AfterAgent(ctx context.Context, state *TypedReActAgentState[M]) (context.Context, error) {
+ return ctx, nil
+}
+func (h *eventSenderModelHandler[M]) BeforeModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) {
+ return ctx, state, nil
+}
+func (h *eventSenderModelHandler[M]) AfterModelRewrite(ctx context.Context, state *TypedReActAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedReActAgentState[M], error) {
+ return ctx, state, nil
+}
// HasUserEventSenderModelWrapper checks if the handlers list contains a user-provided
// NewEventSenderModelWrapper. When present, the framework skips its internal default
diff --git a/internal/harness/core/failover.go b/internal/harness/core/failover.go
index cc8fd873a0..ed016d0194 100644
--- a/internal/harness/core/failover.go
+++ b/internal/harness/core/failover.go
@@ -48,7 +48,9 @@ func (m *failoverModel[M]) Generate(ctx context.Context, input []M, opts ...Mode
return zero, fmt.Errorf("failover skipped: %w", lastErr)
}
r, err := model.Generate(ctx, input, opts...)
- if err == nil { return r, nil }
+ if err == nil {
+ return r, nil
+ }
lastErr = fmt.Errorf("model[%d]: %w", i, err)
}
var zero M
@@ -62,7 +64,9 @@ func (m *failoverModel[M]) Stream(ctx context.Context, input []M, opts ...ModelO
return nil, fmt.Errorf("failover skipped: %w", lastErr)
}
s, err := model.Stream(ctx, input, opts...)
- if err == nil { return s, nil }
+ if err == nil {
+ return s, nil
+ }
lastErr = fmt.Errorf("model[%d]: %w", i, err)
}
return nil, fmt.Errorf("all %d models failed to stream: %w", len(m.models), lastErr)
@@ -70,7 +74,9 @@ func (m *failoverModel[M]) Stream(ctx context.Context, input []M, opts ...ModelO
func (m *failoverModel[M]) BindTools(tools []*schema.ToolInfo) error {
for _, model := range m.models {
- if err := model.BindTools(tools); err != nil { return err }
+ if err := model.BindTools(tools); err != nil {
+ return err
+ }
}
return nil
}
diff --git a/internal/harness/core/flow.go b/internal/harness/core/flow.go
index d6e0eef0b1..6cf04b2648 100644
--- a/internal/harness/core/flow.go
+++ b/internal/harness/core/flow.go
@@ -39,7 +39,9 @@ func (a *flowAgent) deepCopy() *flowAgent {
cp := &flowAgent{Agent: a.Agent, parentAgent: a.parentAgent,
disallowTransferToParent: a.disallowTransferToParent, historyRewriter: a.historyRewriter,
checkPointStore: a.checkPointStore}
- for _, sa := range a.subAgents { cp.subAgents = append(cp.subAgents, sa.deepCopy()) }
+ for _, sa := range a.subAgents {
+ cp.subAgents = append(cp.subAgents, sa.deepCopy())
+ }
return cp
}
@@ -52,7 +54,9 @@ func SetSubAgents(ctx context.Context, agent Agent, subs []Agent) (ResumableAgen
if fa.historyRewriter == nil {
fa.historyRewriter = defaultHistoryRewriter(agent.Name(ctx))
}
- if len(fa.subAgents) > 0 { return nil, errors.New("sub-agents already set") }
+ if len(fa.subAgents) > 0 {
+ return nil, errors.New("sub-agents already set")
+ }
for _, s := range subs {
fa.subAgents = append(fa.subAgents, toFlowAgent(ctx, s, WithDisallowTransferToParent()))
}
@@ -80,16 +84,24 @@ func toFlowAgent(ctx context.Context, agent Agent, opts ...AgentOption) *flowAge
} else {
fa = fa.deepCopy()
}
- for _, o := range opts { o(fa) }
- if fa.historyRewriter == nil { fa.historyRewriter = defaultHistoryRewriter(agent.Name(ctx)) }
+ for _, o := range opts {
+ o(fa)
+ }
+ if fa.historyRewriter == nil {
+ fa.historyRewriter = defaultHistoryRewriter(agent.Name(ctx))
+ }
return fa
}
func (a *flowAgent) getAgent(ctx context.Context, name string) *flowAgent {
for _, sa := range a.subAgents {
- if sa.Name(ctx) == name { return sa }
+ if sa.Name(ctx) == name {
+ return sa
+ }
+ }
+ if a.parentAgent != nil && a.parentAgent.Name(ctx) == name {
+ return a.parentAgent
}
- if a.parentAgent != nil && a.parentAgent.Name(ctx) == name { return a.parentAgent }
return nil
}
@@ -101,7 +113,9 @@ func defaultHistoryRewriter(name string) HistoryRewriter {
if !e.IsUserInput && e.AgentName != name {
m = rewriteMsg(m, e.AgentName)
}
- if m != nil { msgs = append(msgs, m) }
+ if m != nil {
+ msgs = append(msgs, m)
+ }
}
return msgs, nil
}
@@ -117,7 +131,9 @@ func rewriteMsg(msg Message, agentName string) Message {
var sb strings.Builder
sb.WriteString("For context:")
if msg.Role == schema.RoleAssistant {
- if msg.Content != "" { sb.WriteString(fmt.Sprintf(" [%s] said: %s.", agentName, msg.Content)) }
+ if msg.Content != "" {
+ sb.WriteString(fmt.Sprintf(" [%s] said: %s.", agentName, msg.Content))
+ }
for _, tc := range msg.ToolCalls {
sb.WriteString(fmt.Sprintf(" [%s] called tool `%s` args: %s.", agentName, tc.Function.Name, tc.Function.Arguments))
}
@@ -125,7 +141,9 @@ func rewriteMsg(msg Message, agentName string) Message {
sb.WriteString(fmt.Sprintf(" [%s] `%s` returned: %s.", agentName, msg.ToolName, msg.Content))
}
r := schema.UserMessage(sb.String())
- if msg.Extra != nil { r.Extra = copyMap(msg.Extra) }
+ if msg.Extra != nil {
+ r.Extra = copyMap(msg.Extra)
+ }
return r
}
@@ -145,7 +163,9 @@ func (a *flowAgent) genInput(ctx context.Context, rc *runContext, skipTransfer b
}
for _, ev := range rc.Session.getEvents() {
ae, ok := ev.(*AgentEvent)
- if !ok { continue }
+ if !ok {
+ continue
+ }
if skipTransfer && ae.Action != nil && ae.Action.TransferToAgent != nil {
if ae.Output != nil && ae.Output.MessageOutput != nil && ae.Output.MessageOutput.Role == schema.RoleTool && len(entries) > 0 {
entries = entries[:len(entries)-1]
@@ -153,19 +173,27 @@ func (a *flowAgent) genInput(ctx context.Context, rc *runContext, skipTransfer b
continue
}
msg := msgFromEvent(ae)
- if msg == nil { continue }
+ if msg == nil {
+ continue
+ }
entries = append(entries, &HistoryEntry{AgentName: ae.AgentName, Message: msg})
}
msgs, err := a.historyRewriter(ctx, entries)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
input.Messages = msgs
return input, nil
}
func msgFromEvent(ev *AgentEvent) Message {
- if ev == nil || ev.Output == nil || ev.Output.MessageOutput == nil { return nil }
+ if ev == nil || ev.Output == nil || ev.Output.MessageOutput == nil {
+ return nil
+ }
mv := ev.Output.MessageOutput
- if mv.IsStreaming { return nil }
+ if mv.IsStreaming {
+ return nil
+ }
return mv.Message
}
@@ -178,7 +206,9 @@ func (a *flowAgent) Run(ctx context.Context, input *AgentInput, opts ...RunOptio
pi, err := a.genInput(ctx, rc, o.skipTransferMessages)
if err != nil {
- if cc != nil { cc.markDone() }
+ if cc != nil {
+ cc.markDone()
+ }
_ = &AgentCallbackInput{Input: input}
return wrapIterEnd(ctx, errorIterMsg(err))
}
@@ -201,23 +231,36 @@ func (a *flowAgent) runLoop(ctx, subCtx context.Context, rc *runContext, ai *Asy
var lastAction *AgentAction
for {
ev, ok := ai.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
curRunPath := rc.getRunPath()
- if len(ev.RunPath) == 0 { ev.AgentName = a.Name(ctx); ev.RunPath = curRunPath }
+ if len(ev.RunPath) == 0 {
+ ev.AgentName = a.Name(ctx)
+ ev.RunPath = curRunPath
+ }
if (ev.Action == nil || ev.Action.Interrupted == nil) && pathMatch(curRunPath, ev.RunPath) {
cp := copyTypedAgentEvent(ev)
- setAutomaticClose(cp); setAutomaticClose(ev)
+ setAutomaticClose(cp)
+ setAutomaticClose(ev)
rc.Session.addEvent(cp)
}
- if pathMatch(curRunPath, ev.RunPath) { lastAction = ev.Action }
+ if pathMatch(curRunPath, ev.RunPath) {
+ lastAction = ev.Action
+ }
cp := copyTypedAgentEvent(ev)
- setAutomaticClose(cp); setAutomaticClose(ev)
+ setAutomaticClose(cp)
+ setAutomaticClose(ev)
gen.Send(cp)
}
var dest string
if lastAction != nil {
- if lastAction.Interrupted != nil || lastAction.Exit { return }
- if lastAction.TransferToAgent != nil { dest = lastAction.TransferToAgent.DestAgentName }
+ if lastAction.Interrupted != nil || lastAction.Exit {
+ return
+ }
+ if lastAction.TransferToAgent != nil {
+ dest = lastAction.TransferToAgent.DestAgentName
+ }
}
if dest != "" {
if cc := getCancelContext(subCtx); cc != nil && cc.shouldCancel() {
@@ -230,7 +273,9 @@ func (a *flowAgent) runLoop(ctx, subCtx context.Context, rc *runContext, ai *Asy
}
for {
se, ok := next.Run(subCtx, nil, opts...).Next()
- if !ok { break }
+ if !ok {
+ break
+ }
setAutomaticClose(se)
if se.Action == nil || se.Action.Interrupted == nil {
rc.Session.addEvent(copyTypedAgentEvent(se))
@@ -254,12 +299,16 @@ func (a *flowAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...RunOpt
go a.runLoop(withCancelContext(ctx, cc), withCancelContext(ctx, cc), getRunCtx(ctx), ai, gen, filterCancelOption(opts)...)
return wrapIterWithCancelCtx(it, cc)
}
- if cc != nil { cc.markDone() }
+ if cc != nil {
+ cc.markDone()
+ }
return wrapIterEnd(ctx, errorIterMsg(fmt.Errorf("agent '%s' not ResumableAgent", name)))
}
next, err := getNextResumeAgent(ctx, info)
if err != nil {
- if cc != nil { cc.markDone() }
+ if cc != nil {
+ cc.markDone()
+ }
return wrapIterEnd(ctx, errorIterMsg(err))
}
sa := a.getAgent(ctx, next)
@@ -271,7 +320,9 @@ func (a *flowAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...RunOpt
}
return wrapIterEnd(ctx, errorIterMsg(fmt.Errorf("agent '%s' has no sub-agents and not ResumableAgent", name)))
}
- if cc != nil { cc.markDone() }
+ if cc != nil {
+ cc.markDone()
+ }
return wrapIterEnd(ctx, errorIterMsg(fmt.Errorf("sub-agent '%s' not found", next)))
}
inner := sa.Resume(withCancelContext(ctx, cc), info, filterCancelOption(opts)...)
@@ -279,8 +330,14 @@ func (a *flowAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...RunOpt
}
func pathMatch(a, b []RunStep) bool {
- if len(a) != len(b) { return false }
- for i := range a { if !a[i].Equals(b[i]) { return false } }
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if !a[i].Equals(b[i]) {
+ return false
+ }
+ }
return true
}
@@ -290,8 +347,12 @@ func wrapIterEnd(ctx context.Context, iter *AsyncIterator[*AgentEvent]) *AsyncIt
defer gen.Close()
for {
ev, ok := iter.Next()
- if !ok { break }
- if !gen.SendCtx(ctx, ev) { return }
+ if !ok {
+ break
+ }
+ if !gen.SendCtx(ctx, ev) {
+ return
+ }
}
}()
return it
@@ -312,7 +373,9 @@ type typedFlowAgent[M MessageType] struct {
}
func toTypedFlowAgent[M MessageType](a TypedAgent[M]) *typedFlowAgent[M] {
- if fa, ok := a.(*typedFlowAgent[M]); ok { return fa }
+ if fa, ok := a.(*typedFlowAgent[M]); ok {
+ return fa
+ }
return &typedFlowAgent[M]{TypedAgent: a}
}
@@ -342,12 +405,18 @@ func (a *typedFlowAgent[M]) runLoop(ctx context.Context, rc *runContext, ai *Asy
}()
for {
ev, ok := ai.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
curRunPath := rc.getRunPath()
- if len(ev.RunPath) == 0 { ev.AgentName = a.Name(ctx); ev.RunPath = curRunPath }
+ if len(ev.RunPath) == 0 {
+ ev.AgentName = a.Name(ctx)
+ ev.RunPath = curRunPath
+ }
if (ev.Action == nil || ev.Action.Interrupted == nil) && pathMatch(curRunPath, ev.RunPath) {
cp := copyTypedAgentEvent(ev)
- typedSetAutomaticClose(cp); typedSetAutomaticClose(ev)
+ typedSetAutomaticClose(cp)
+ typedSetAutomaticClose(ev)
addTypedEvent(rc.Session, cp)
}
gen.Send(ev)
@@ -366,7 +435,9 @@ func (a *typedFlowAgent[M]) Resume(ctx context.Context, info *ResumeInfo, opts .
go a.runLoop(withCancelContext(ctx, cc), getRunCtx(ctx), ai, gen)
return wrapIterWithCancelCtx(it, cc)
}
- if cc != nil { cc.markDone() }
+ if cc != nil {
+ cc.markDone()
+ }
return typedErrorIterEnd[M](ctx, fmt.Errorf("agent '%s' not ResumableAgent", name))
}
if ra, ok := a.TypedAgent.(TypedResumableAgent[M]); ok {
@@ -392,8 +463,12 @@ func typedWrapIterEnd[M MessageType](ctx context.Context, iter *AsyncIterator[*T
defer gen.Close()
for {
ev, ok := iter.Next()
- if !ok { break }
- if !gen.SendCtx(ctx, ev) { return }
+ if !ok {
+ break
+ }
+ if !gen.SendCtx(ctx, ev) {
+ return
+ }
}
}()
return it
diff --git a/internal/harness/core/graph_integration_test.go b/internal/harness/core/graph_integration_test.go
index d1ef215ca1..d949a9a9af 100644
--- a/internal/harness/core/graph_integration_test.go
+++ b/internal/harness/core/graph_integration_test.go
@@ -211,9 +211,9 @@ func TestGraphIntegration_ReActWithCheckpointResume(t *testing.T) {
tool := &mockTool{name: "calculator", desc: "math tool"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: model,
- Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ Model: model,
+ Tools: []Tool{tool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 3,
}).WithName("react_cp_agent")
@@ -222,7 +222,7 @@ func TestGraphIntegration_ReActWithCheckpointResume(t *testing.T) {
Checkpointer: saver,
InterruptBefore: []string{"execute_tools"},
RecursionLimit: 20,
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -304,4 +304,3 @@ func TestGraphIntegration_WorkflowGraphCompile(t *testing.T) {
t.Fatal("Compile() returned nil")
}
}
-
diff --git a/internal/harness/core/integration_test.go b/internal/harness/core/integration_test.go
index 8e21eec745..eb388354ff 100644
--- a/internal/harness/core/integration_test.go
+++ b/internal/harness/core/integration_test.go
@@ -489,15 +489,30 @@ func TestIntegration_LoopAgentSimple(t *testing.T) {
// 2 iterations * 1 call each = 2 calls
m2.addResp("loop_a2")
m2.addResp("loop_a2")
- a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}); a1.name = "la1"
- a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}); a2.name = "la2"
+ a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1})
+ a1.name = "la1"
+ a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2})
+ a2.name = "la2"
ctx := context.Background()
wf, err := NewLoop(ctx, &LoopConfig{Name: "loop_simple", Description: "test", SubAgents: []Agent{a1, a2}, MaxIterations: 2})
- if err != nil { t.Fatalf("NewLoop: %v", err) }
+ if err != nil {
+ t.Fatalf("NewLoop: %v", err)
+ }
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("go")}})
var count int
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { t.Fatalf("err: %v", ev.Err) }; count++ }
- if count == 0 { t.Error("expected events from loop") }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
+ count++
+ }
+ if count == 0 {
+ t.Error("expected events from loop")
+ }
}
func TestIntegration_PlanExecuteSimple(t *testing.T) {
@@ -509,7 +524,15 @@ func TestIntegration_PlanExecuteSimple(t *testing.T) {
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent, CheckPointStore: store})
ctx := context.Background()
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("test")})
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { t.Fatalf("err: %v", ev.Err) } }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
+ }
}
// ---- Runner-level integration tests ----
@@ -536,8 +559,12 @@ func TestIntegration_RunnerToolCall(t *testing.T) {
var lastContent string
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { t.Fatalf("err: %v", ev.Err) }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
if ev.Output != nil && ev.Output.MessageOutput != nil && !ev.Output.MessageOutput.IsStreaming && ev.Output.MessageOutput.Message != nil {
lastContent = ev.Output.MessageOutput.Message.Content
}
@@ -560,13 +587,21 @@ func TestIntegration_RunnerSimple(t *testing.T) {
var found bool
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { t.Fatalf("err: %v", ev.Err) }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
if ev.Output != nil && ev.Output.MessageOutput != nil && !ev.Output.MessageOutput.IsStreaming && ev.Output.MessageOutput.Message != nil {
- if ev.Output.MessageOutput.Message.Content == "hello world" { found = true }
+ if ev.Output.MessageOutput.Message.Content == "hello world" {
+ found = true
+ }
}
}
- if !found { t.Error("expected 'hello world' in output") }
+ if !found {
+ t.Error("expected 'hello world' in output")
+ }
}
// TestIntegration_RunnerResume verifies the full cancel-then-resume cycle.
@@ -587,7 +622,12 @@ func TestIntegration_RunnerResume(t *testing.T) {
time.Sleep(10 * time.Millisecond)
cancelFunc(WithCancelMode(CancelImmediate))
- for { _, ok := iter.Next(); if !ok { break } }
+ for {
+ _, ok := iter.Next()
+ if !ok {
+ break
+ }
+ }
// Resume from the known checkpoint ID.
resumedIter, err := runner.Resume(ctx, cid)
@@ -598,8 +638,12 @@ func TestIntegration_RunnerResume(t *testing.T) {
var outputs []string
for {
ev, ok := resumedIter.Next()
- if !ok { break }
- if ev.Err != nil { break }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ break
+ }
if ev.Output != nil && ev.Output.MessageOutput != nil && ev.Output.MessageOutput.Message != nil {
outputs = append(outputs, ev.Output.MessageOutput.Message.Content)
}
@@ -626,14 +670,20 @@ func TestIntegration_RunnerCancel(t *testing.T) {
var gotCancel bool
for {
ev, ok := iter.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
if ev.Err != nil {
var ce *CancelError
- if errors.As(ev.Err, &ce) { gotCancel = true }
+ if errors.As(ev.Err, &ce) {
+ gotCancel = true
+ }
break
}
}
- if !gotCancel { t.Log("cancel may not have been delivered (expected with non-graceful cancel)") }
+ if !gotCancel {
+ t.Log("cancel may not have been delivered (expected with non-graceful cancel)")
+ }
}
// TestIntegration_RunnerStreamMode verifies that streaming events are received.
@@ -649,8 +699,12 @@ func TestIntegration_RunnerStreamMode(t *testing.T) {
var streamingEvents int
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { t.Fatalf("err: %v", ev.Err) }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
if ev.Output != nil && ev.Output.MessageOutput != nil && ev.Output.MessageOutput.IsStreaming {
streamingEvents++
}
@@ -682,8 +736,12 @@ func TestIntegration_AgentToolViaRunner(t *testing.T) {
var lastContent string
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { t.Fatalf("err: %v", ev.Err) }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Fatalf("err: %v", ev.Err)
+ }
if ev.Output != nil && ev.Output.MessageOutput != nil && !ev.Output.MessageOutput.IsStreaming && ev.Output.MessageOutput.Message != nil {
lastContent = ev.Output.MessageOutput.Message.Content
}
diff --git a/internal/harness/core/interface.go b/internal/harness/core/interface.go
index 26d9167446..5e00e79b48 100644
--- a/internal/harness/core/interface.go
+++ b/internal/harness/core/interface.go
@@ -138,7 +138,6 @@ type TypedAgent[M MessageType] interface {
type Agent = TypedAgent[*schema.Message]
-
type TypedResumableAgent[M MessageType] interface {
TypedAgent[M]
Resume(ctx context.Context, info *ResumeInfo, opts ...RunOption) *AsyncIterator[*TypedAgentEvent[M]]
@@ -231,6 +230,7 @@ func concatMessageStream[M MessageType](stream *schema.StreamReader[M]) (M, erro
type typedModelOption[M MessageType] struct {
f func(o *modelOptions[M])
}
+
func (o *typedModelOption[M]) applyModel() {}
// modelOptions holds all model call options.
diff --git a/internal/harness/core/middleware_integration_test.go b/internal/harness/core/middleware_integration_test.go
index e7592fe7eb..3a47a9a87a 100644
--- a/internal/harness/core/middleware_integration_test.go
+++ b/internal/harness/core/middleware_integration_test.go
@@ -96,7 +96,9 @@ func TestMiddleware_ChainErrorRecovery(t *testing.T) {
found := false
for _, s := range order {
- if s == "failing_beforeAgent" { found = true }
+ if s == "failing_beforeAgent" {
+ found = true
+ }
}
if !found {
t.Error("failingMW.BeforeAgent should have been called")
@@ -178,7 +180,13 @@ func TestSession_ConcurrentValueAccess(t *testing.T) {
ctx := context.Background()
iter := agent.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("test")}})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
var wg sync.WaitGroup
errs := make(chan error, 20)
diff --git a/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch.go b/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch.go
index 52d1cd0487..9c56599e4a 100644
--- a/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch.go
+++ b/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch.go
@@ -17,7 +17,7 @@ import (
type TypedConfig[M core.MessageType] struct {
AllTools []core.Tool
MaxResults int
- SearchThreshold int // Pass all directly if <= threshold; otherwise use search
+ SearchThreshold int // Pass all directly if <= threshold; otherwise use search
UseDeferred bool // Use DeferredToolInfos for model-native search
}
@@ -28,9 +28,15 @@ type middleware[M core.MessageType] struct {
}
func NewTyped[M core.MessageType](cfg *TypedConfig[M]) core.TypedReActMiddleware[M] {
- if cfg == nil { cfg = &TypedConfig[M]{MaxResults: 5, SearchThreshold: 10} }
- if cfg.MaxResults <= 0 { cfg.MaxResults = 5 }
- if cfg.SearchThreshold <= 0 { cfg.SearchThreshold = 10 }
+ if cfg == nil {
+ cfg = &TypedConfig[M]{MaxResults: 5, SearchThreshold: 10}
+ }
+ if cfg.MaxResults <= 0 {
+ cfg.MaxResults = 5
+ }
+ if cfg.SearchThreshold <= 0 {
+ cfg.SearchThreshold = 10
+ }
return &middleware[M]{cfg: cfg}
}
@@ -38,45 +44,48 @@ func New(cfg *TypedConfig[*schema.Message]) core.TypedReActMiddleware[*schema.Me
return NewTyped[*schema.Message](cfg)
}
-func (m *middleware[M]) BeforeAgent(ctx context.Context, rc *core.ReActAgentContext) (context.Context, *core.ReActAgentContext, error) {
- m.initOnce.Do(func() {})
- // initOnce ensures tools are loaded into rc at least once per middleware instance.
- // If a previous run already loaded tools, skip re-adding to avoid duplicates.
- if len(rc.Tools) > 0 || rc.ToolSearchTool != nil {
- return ctx, rc, nil
- }
-
+func (m *middleware[M]) ContributeTools(ctx context.Context) []core.Tool {
if len(m.cfg.AllTools) <= m.cfg.SearchThreshold {
- // Small toolset: pass all directly
- rc.Tools = append(rc.Tools, m.cfg.AllTools...)
- return ctx, rc, nil
+ return m.cfg.AllTools
}
-
- // Large toolset: search or deferred mode
if m.cfg.UseDeferred {
- // Model-native search mode
- rc.ToolSearchTool = &schema.ToolInfo{
+ return nil // tools are searched via meta-tool
+ }
+ // Client-side search mode: add search meta-tool + pass some directly
+ tools := []core.Tool{m.newSearchTool()}
+ passDirect := m.cfg.SearchThreshold / 2
+ if passDirect > len(m.cfg.AllTools) {
+ passDirect = len(m.cfg.AllTools)
+ }
+ tools = append(tools, m.cfg.AllTools[:passDirect]...)
+ return tools
+}
+
+func (m *middleware[M]) ContributeToolInfos(ctx context.Context) []*schema.ToolInfo {
+ if m.cfg.UseDeferred && len(m.cfg.AllTools) > m.cfg.SearchThreshold {
+ return []*schema.ToolInfo{{
Name: "search_tools",
Description: "Search for available tools by keyword",
- }
- return ctx, rc, nil
+ }}
}
+ return nil
+}
- // Client-side search mode: add search meta-tool + pass some directly
- rc.Tools = append(rc.Tools, m.newSearchTool())
-
- // Pass the first threshold/2 tools directly (commonly needed)
- passDirect := m.cfg.SearchThreshold / 2
- if passDirect > len(m.cfg.AllTools) { passDirect = len(m.cfg.AllTools) }
- rc.Tools = append(rc.Tools, m.cfg.AllTools[:passDirect]...)
+func (m *middleware[M]) ContributeReturnDirectly(ctx context.Context) map[string]bool { return nil }
+func (m *middleware[M]) BeforeAgent(ctx context.Context, rc *core.ReActAgentContext) (context.Context, *core.ReActAgentContext, error) {
+ // Tool contribution is now handled via ToolContributor.
+ // BeforeAgent is kept for backward compatibility: if tools are already
+ // present (set by user or another middleware), skip re-initialization.
return ctx, rc, nil
}
func (m *middleware[M]) BeforeModelRewrite(ctx context.Context, state *core.TypedReActAgentState[M], mc *core.TypedModelContext[M]) (context.Context, *core.TypedReActAgentState[M], error) {
- if !m.cfg.UseDeferred { return ctx, state, nil }
+ if !m.cfg.UseDeferred {
+ return ctx, state, nil
+ }
- // Deferred mode: build tool info list
+ // Deferred mode: build tool info list for all available tools.
infos := make([]*schema.ToolInfo, 0, len(m.cfg.AllTools))
for _, t := range m.cfg.AllTools {
infos = append(infos, &schema.ToolInfo{Name: t.Name(), Description: t.Description()})
@@ -94,7 +103,9 @@ func (m *middleware[M]) newSearchTool() core.Tool {
// Direct selection syntax
if strings.HasPrefix(args, "select:") {
selected := strings.Split(args[7:], ",")
- for i := range selected { selected[i] = strings.TrimSpace(selected[i]) }
+ for i := range selected {
+ selected[i] = strings.TrimSpace(selected[i])
+ }
var results []string
for _, t := range m.cfg.AllTools {
for _, s := range selected {
@@ -103,13 +114,17 @@ func (m *middleware[M]) newSearchTool() core.Tool {
}
}
}
- if len(results) == 0 { return "No selected tools found.", nil }
+ if len(results) == 0 {
+ return "No selected tools found.", nil
+ }
return "Selected tools:\n" + strings.Join(results, "\n"), nil
}
// Keyword search
keywords := strings.Fields(args)
- if len(keywords) == 0 { return "Please provide keywords to search.", nil }
+ if len(keywords) == 0 {
+ return "Please provide keywords to search.", nil
+ }
// Separate required (+prefix) and optional keywords
var required, optional []string
@@ -136,20 +151,36 @@ func (m *middleware[M]) newSearchTool() core.Tool {
// Check required keywords
allMatched := true
for _, r := range required {
- if !strings.Contains(name, r) && !strings.Contains(desc, r) { allMatched = false; break }
+ if !strings.Contains(name, r) && !strings.Contains(desc, r) {
+ allMatched = false
+ break
+ }
+ }
+ if !allMatched {
+ continue
}
- if !allMatched { continue }
// Score optional keywords
for _, kw := range optional {
nameParts := splitToolName(t.Name())
for _, part := range nameParts {
- if strings.EqualFold(part, kw) { score += 10; continue }
- if strings.Contains(strings.ToLower(part), kw) { score += 5 }
+ if strings.EqualFold(part, kw) {
+ score += 10
+ continue
+ }
+ if strings.Contains(strings.ToLower(part), kw) {
+ score += 5
+ }
+ }
+ if strings.EqualFold(t.Name(), kw) {
+ score += 10
+ }
+ if strings.Contains(name, kw) {
+ score += 3
+ }
+ if strings.Contains(desc, kw) {
+ score += 2
}
- if strings.EqualFold(t.Name(), kw) { score += 10 }
- if strings.Contains(name, kw) { score += 3 }
- if strings.Contains(desc, kw) { score += 2 }
}
if score > 0 || len(optional) == 0 {
scored = append(scored, scoredTool{name: t.Name(), desc: t.Description(), score: score})
@@ -161,10 +192,14 @@ func (m *middleware[M]) newSearchTool() core.Tool {
return scored[i].score > scored[j].score
})
- if len(scored) == 0 { return "No tools found for: " + args, nil }
+ if len(scored) == 0 {
+ return "No tools found for: " + args, nil
+ }
// Limit results
- if len(scored) > m.cfg.MaxResults { scored = scored[:m.cfg.MaxResults] }
+ if len(scored) > m.cfg.MaxResults {
+ scored = scored[:m.cfg.MaxResults]
+ }
var results []string
for _, s := range scored {
results = append(results, s.name+": "+s.desc)
@@ -183,7 +218,9 @@ func splitToolName(name string) []string {
// Further split camelCase
var result []string
for _, part := range parts {
- if part == "" { continue }
+ if part == "" {
+ continue
+ }
var current strings.Builder
for i, r := range part {
if i > 0 && r >= 'A' && r <= 'Z' {
@@ -200,4 +237,3 @@ func splitToolName(name string) []string {
}
return result
}
-
diff --git a/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch_test.go b/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch_test.go
index 4eea7bd818..6ae8a6a8bf 100644
--- a/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch_test.go
+++ b/internal/harness/core/middlewares/dynamictool/toolsearch/toolsearch_test.go
@@ -16,8 +16,8 @@ type searchableTool struct {
desc string
}
-func (t *searchableTool) Name() string { return t.name }
-func (t *searchableTool) Description() string { return t.desc }
+func (t *searchableTool) Name() string { return t.name }
+func (t *searchableTool) Description() string { return t.desc }
func (t *searchableTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
return "result", nil
}
@@ -38,7 +38,9 @@ func TestNew_SmallToolset(t *testing.T) {
})
rc := &core.ReActAgentContext{Instruction: "Help", Tools: make([]core.Tool, 0)}
_, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeAgent: %v", err)
+ }
// With small toolset (<= threshold), all tools are passed through
t.Logf("tools count for small set: %d", len(newRc.Tools))
_ = newRc
@@ -57,7 +59,9 @@ func TestNew_LargeToolset(t *testing.T) {
})
rc := &core.ReActAgentContext{Instruction: "Help", Tools: make([]core.Tool, 0)}
_, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeAgent: %v", err)
+ }
// With large toolset, middleware registers a search tool
t.Logf("tools count for large set: %d", len(newRc.Tools))
_ = newRc
@@ -122,7 +126,9 @@ func TestToolNames(t *testing.T) {
})
rc := &core.ReActAgentContext{Instruction: "Help", Tools: make([]core.Tool, 0)}
_, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeAgent: %v", err)
+ }
if len(newRc.Tools) > 0 {
t.Logf("search tool added: %q", newRc.Tools[0].Name())
}
diff --git a/internal/harness/core/middlewares/filesystem/filesystem.go b/internal/harness/core/middlewares/filesystem/filesystem.go
index e0db78e8c7..f4d5d582fd 100644
--- a/internal/harness/core/middlewares/filesystem/filesystem.go
+++ b/internal/harness/core/middlewares/filesystem/filesystem.go
@@ -46,16 +46,33 @@ type middleware[M core.MessageType] struct {
}
func NewTyped[M core.MessageType](cfg *Config) *middleware[M] {
- if cfg == nil { cfg = &Config{ReadBytes: 1 << 20} }
- if cfg.ReadBytes <= 0 { cfg.ReadBytes = 1 << 20 }
+ if cfg == nil {
+ cfg = &Config{ReadBytes: 1 << 20}
+ }
+ if cfg.ReadBytes <= 0 {
+ cfg.ReadBytes = 1 << 20
+ }
return &middleware[M]{cfg: cfg}
}
func New(cfg *Config) *middleware[*schema.Message] { return NewTyped[*schema.Message](cfg) }
+func (m *middleware[M]) ContributeTools(ctx context.Context) []core.Tool {
+ if m.cfg.Backend == nil {
+ return nil
+ }
+ return m.buildTools()
+}
+
+func (m *middleware[M]) ContributeToolInfos(ctx context.Context) []*schema.ToolInfo { return nil }
+
+func (m *middleware[M]) ContributeReturnDirectly(ctx context.Context) map[string]bool { return nil }
+
+// BeforeAgent is retained for backward compatibility with code that calls
+// BeforeAgent directly (e.g., existing tests). The preferred path is
+// ToolContributor (ContributeTools), which is automatically collected
+// during agent build.
func (m *middleware[M]) BeforeAgent(ctx context.Context, rc *core.ReActAgentContext) (context.Context, *core.ReActAgentContext, error) {
- if m.cfg.Backend == nil { return ctx, rc, nil }
- rc.Tools = append(rc.Tools, m.buildTools()...)
return ctx, rc, nil
}
@@ -88,12 +105,20 @@ func (m *middleware[M]) buildTools() []core.Tool {
func (m *middleware[M]) maybeTool(name, defaultDesc string, defaultFn func(ctx context.Context, args string) (string, error)) core.Tool {
if m.cfg.ToolConfig != nil {
if tc, ok := m.cfg.ToolConfig[name]; ok {
- if tc.Disabled { return nil }
+ if tc.Disabled {
+ return nil
+ }
desc := defaultDesc
- if tc.Description != "" { desc = tc.Description }
- if tc.Custom != nil { return core.NewBaseTool(tc.Name, desc, tc.Custom) }
+ if tc.Description != "" {
+ desc = tc.Description
+ }
+ if tc.Custom != nil {
+ return core.NewBaseTool(tc.Name, desc, tc.Custom)
+ }
toolName := name
- if tc.Name != "" { toolName = tc.Name }
+ if tc.Name != "" {
+ toolName = tc.Name
+ }
return core.NewBaseTool(toolName, desc, defaultFn)
}
}
@@ -103,7 +128,9 @@ func (m *middleware[M]) maybeTool(name, defaultDesc string, defaultFn func(ctx c
func (m *middleware[M]) newReadTool() func(ctx context.Context, args string) (string, error) {
return func(ctx context.Context, args string) (string, error) {
content, err := m.cfg.Backend.Read(args)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
if len(content) > m.cfg.ReadBytes {
content = content[:m.cfg.ReadBytes] + "\n...(truncated)"
}
@@ -129,7 +156,9 @@ func (m *middleware[M]) newWriteTool() func(ctx context.Context, args string) (s
return fmt.Sprintf("OK: wrote %d bytes to %s", len(jsonArgs.Content), jsonArgs.Path), nil
}
parts := strings.SplitN(args, "|", 2)
- if len(parts) < 2 { return "", fmt.Errorf("expected path|content or JSON with 'path' and 'content'") }
+ if len(parts) < 2 {
+ return "", fmt.Errorf("expected path|content or JSON with 'path' and 'content'")
+ }
if err := m.cfg.Backend.Write(parts[0], parts[1]); err != nil {
return "", err
}
@@ -148,7 +177,9 @@ func (m *middleware[M]) newEditTool() func(ctx context.Context, args string) (st
return "", m.cfg.Backend.Edit(jsonArgs.Path, jsonArgs.Old, jsonArgs.New)
}
parts := strings.SplitN(args, "|", 3)
- if len(parts) < 3 { return "", fmt.Errorf("expected path|old|new or JSON with 'path', 'old', 'new'") }
+ if len(parts) < 3 {
+ return "", fmt.Errorf("expected path|old|new or JSON with 'path', 'old', 'new'")
+ }
return "", m.cfg.Backend.Edit(parts[0], parts[1], parts[2])
}
}
@@ -156,8 +187,12 @@ func (m *middleware[M]) newEditTool() func(ctx context.Context, args string) (st
func (m *middleware[M]) newLsTool() func(ctx context.Context, args string) (string, error) {
return func(ctx context.Context, args string) (string, error) {
results, err := m.cfg.Backend.Ls(args)
- if err != nil { return "", err }
- if len(results) == 0 { return "(empty directory)", nil }
+ if err != nil {
+ return "", err
+ }
+ if len(results) == 0 {
+ return "(empty directory)", nil
+ }
return strings.Join(results, "\n"), nil
}
}
@@ -165,8 +200,12 @@ func (m *middleware[M]) newLsTool() func(ctx context.Context, args string) (stri
func (m *middleware[M]) newGlobTool() func(ctx context.Context, args string) (string, error) {
return func(ctx context.Context, args string) (string, error) {
results, err := m.cfg.Backend.Glob(args)
- if err != nil { return "", err }
- if len(results) == 0 { return "No matches", nil }
+ if err != nil {
+ return "", err
+ }
+ if len(results) == 0 {
+ return "No matches", nil
+ }
return strings.Join(results, "\n"), nil
}
}
@@ -180,18 +219,26 @@ func (m *middleware[M]) newGrepTool() func(ctx context.Context, args string) (st
}
if err := json.Unmarshal([]byte(args), &jsonArgs); err == nil && jsonArgs.Pattern != "" {
result, err := m.cfg.Backend.Grep(jsonArgs.Pattern, jsonArgs.Path)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
return formatGrepResult(result, jsonArgs.OutputMode)
}
// Fall back to | separator
parts := strings.SplitN(args, "|", 3)
pattern, path := parts[0], "."
- if len(parts) > 1 { path = parts[1] }
+ if len(parts) > 1 {
+ path = parts[1]
+ }
outputMode := "content"
- if len(parts) > 2 { outputMode = parts[2] }
+ if len(parts) > 2 {
+ outputMode = parts[2]
+ }
result, err := m.cfg.Backend.Grep(pattern, path)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
return formatGrepResult(result, outputMode)
}
}
@@ -199,18 +246,26 @@ func (m *middleware[M]) newGrepTool() func(ctx context.Context, args string) (st
func formatGrepResult(result, outputMode string) (string, error) {
switch outputMode {
case "count":
- if result == "" { return "0 matches", nil }
+ if result == "" {
+ return "0 matches", nil
+ }
lines := strings.Count(result, "\n") + 1
return fmt.Sprintf("%d matches", lines), nil
case "files":
unique := make(map[string]bool)
for _, line := range strings.Split(result, "\n") {
- if line == "" { continue }
+ if line == "" {
+ continue
+ }
parts := strings.SplitN(line, ":", 2)
- if len(parts) > 0 { unique[parts[0]] = true }
+ if len(parts) > 0 {
+ unique[parts[0]] = true
+ }
}
names := make([]string, 0, len(unique))
- for n := range unique { names = append(names, n) }
+ for n := range unique {
+ names = append(names, n)
+ }
return strings.Join(names, "\n"), nil
default:
return result, nil
diff --git a/internal/harness/core/middlewares/filesystem/filesystem_test.go b/internal/harness/core/middlewares/filesystem/filesystem_test.go
index 5766076360..fb92f5df74 100644
--- a/internal/harness/core/middlewares/filesystem/filesystem_test.go
+++ b/internal/harness/core/middlewares/filesystem/filesystem_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"ragflow/internal/harness/core"
+ "ragflow/internal/harness/core/schema"
)
// ---- Test Backend ----
@@ -21,54 +22,63 @@ type testBackend struct {
func (b *testBackend) Read(path string) (string, error) { return b.readResult, b.readErr }
func (b *testBackend) Write(path, content string) error {
- if b.written == nil { b.written = make(map[string]string) }
+ if b.written == nil {
+ b.written = make(map[string]string)
+ }
b.written[path] = content
return nil
}
func (b *testBackend) Edit(path, old, new string) error {
- if b.written == nil { b.written = make(map[string]string) }
+ if b.written == nil {
+ b.written = make(map[string]string)
+ }
b.written[path+"_edit"] = new
return nil
}
-func (b *testBackend) Ls(path string) ([]string, error) { return b.lsResult, nil }
+func (b *testBackend) Ls(path string) ([]string, error) { return b.lsResult, nil }
func (b *testBackend) Glob(pattern string) ([]string, error) { return []string{"a.txt", "b.go"}, nil }
func (b *testBackend) Grep(pattern, path string) (string, error) {
- if b.grepResult != "" { return b.grepResult, nil }
+ if b.grepResult != "" {
+ return b.grepResult, nil
+ }
return "match1\nmatch2", nil
}
func (b *testBackend) Execute(command string) (string, error) { return "done", nil }
// ---- Tests ----
+// getTools is a helper that calls ContributeTools and returns the tool list.
+func getTools(mw *middleware[*schema.Message]) []core.Tool {
+ return mw.ContributeTools(context.Background())
+}
+
func TestNew_NilBackend(t *testing.T) {
mw := New(nil)
- rc := &core.ReActAgentContext{Instruction: "base", Tools: make([]core.Tool, 0)}
- _, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
- if len(newRc.Tools) != 0 {
+ tools := getTools(mw)
+ if len(tools) != 0 {
t.Error("nil backend should not add tools")
}
}
func TestNew_AddsAllTools(t *testing.T) {
mw := New(&Config{Backend: &testBackend{readResult: "hello"}})
- rc := &core.ReActAgentContext{Instruction: "base", Tools: make([]core.Tool, 0)}
- _, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
- if len(newRc.Tools) != 7 {
- t.Errorf("expected 7 tools, got %d", len(newRc.Tools))
+ tools := getTools(mw)
+ if len(tools) != 7 {
+ t.Errorf("expected 7 tools, got %d", len(tools))
}
}
func TestTool_Read_Function(t *testing.T) {
mw := New(&Config{Backend: &testBackend{readResult: "file content"}})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "read_file" {
result, err := tool.Invoke(context.Background(), "test.txt")
- if err != nil { t.Fatalf("read_file: %v", err) }
- if !strings.Contains(result, "file content") { t.Errorf("got %q", result) }
+ if err != nil {
+ t.Fatalf("read_file: %v", err)
+ }
+ if !strings.Contains(result, "file content") {
+ t.Errorf("got %q", result)
+ }
return
}
}
@@ -78,12 +88,12 @@ func TestTool_Read_Function(t *testing.T) {
func TestTool_Write_Function(t *testing.T) {
backend := &testBackend{}
mw := New(&Config{Backend: backend})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "write_file" {
result, err := tool.Invoke(context.Background(), "file.txt|Hello World")
- if err != nil { t.Fatalf("write_file: %v", err) }
+ if err != nil {
+ t.Fatalf("write_file: %v", err)
+ }
t.Logf("write result: %q", result)
return
}
@@ -94,12 +104,12 @@ func TestTool_Write_Function(t *testing.T) {
func TestTool_Edit_Function(t *testing.T) {
backend := &testBackend{}
mw := New(&Config{Backend: backend})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "edit_file" {
result, err := tool.Invoke(context.Background(), "file.txt|old text|new text")
- if err != nil { t.Fatalf("edit_file: %v", err) }
+ if err != nil {
+ t.Fatalf("edit_file: %v", err)
+ }
t.Logf("edit result: %q", result)
return
}
@@ -110,13 +120,15 @@ func TestTool_Edit_Function(t *testing.T) {
func TestTool_Ls_Function(t *testing.T) {
backend := &testBackend{lsResult: []string{"a.txt", "b.txt"}}
mw := New(&Config{Backend: backend})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "ls" {
result, err := tool.Invoke(context.Background(), ".")
- if err != nil { t.Fatalf("ls: %v", err) }
- if !strings.Contains(result, "a.txt") { t.Errorf("got %q", result) }
+ if err != nil {
+ t.Fatalf("ls: %v", err)
+ }
+ if !strings.Contains(result, "a.txt") {
+ t.Errorf("got %q", result)
+ }
return
}
}
@@ -125,13 +137,15 @@ func TestTool_Ls_Function(t *testing.T) {
func TestTool_Glob_Function(t *testing.T) {
mw := New(&Config{Backend: &testBackend{}})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "glob" {
result, err := tool.Invoke(context.Background(), "*.txt")
- if err != nil { t.Fatalf("glob: %v", err) }
- if !strings.Contains(result, "a.txt") { t.Errorf("got %q", result) }
+ if err != nil {
+ t.Fatalf("glob: %v", err)
+ }
+ if !strings.Contains(result, "a.txt") {
+ t.Errorf("got %q", result)
+ }
return
}
}
@@ -140,13 +154,15 @@ func TestTool_Glob_Function(t *testing.T) {
func TestTool_Grep_Function(t *testing.T) {
mw := New(&Config{Backend: &testBackend{}})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "grep" {
result, err := tool.Invoke(context.Background(), "pattern|.")
- if err != nil { t.Fatalf("grep: %v", err) }
- if !strings.Contains(result, "match1") { t.Errorf("got %q", result) }
+ if err != nil {
+ t.Fatalf("grep: %v", err)
+ }
+ if !strings.Contains(result, "match1") {
+ t.Errorf("got %q", result)
+ }
return
}
}
@@ -155,13 +171,15 @@ func TestTool_Grep_Function(t *testing.T) {
func TestTool_Execute_Function(t *testing.T) {
mw := New(&Config{Backend: &testBackend{}})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "execute" {
result, err := tool.Invoke(context.Background(), "ls -la")
- if err != nil { t.Fatalf("execute: %v", err) }
- if result != "done" { t.Errorf("got %q", result) }
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ if result != "done" {
+ t.Errorf("got %q", result)
+ }
return
}
}
@@ -170,9 +188,7 @@ func TestTool_Execute_Function(t *testing.T) {
func TestTool_ReadError(t *testing.T) {
mw := New(&Config{Backend: &testBackend{readErr: errors.New("permission denied")}})
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "read_file" {
_, err := tool.Invoke(context.Background(), "secret.txt")
if err != nil {
@@ -191,9 +207,7 @@ func TestTool_Config_DisableTool(t *testing.T) {
},
}
mw := New(cfg)
- rc := &core.ReActAgentContext{Tools: make([]core.Tool, 0)}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "execute" {
t.Error("execute tool should be disabled")
}
@@ -206,12 +220,12 @@ func TestTool_ReadBytesLimit(t *testing.T) {
ReadBytes: 100,
}
mw := New(cfg)
- rc := &core.ReActAgentContext{}
- _, newRc, _ := mw.BeforeAgent(context.Background(), rc)
- for _, tool := range newRc.Tools {
+ for _, tool := range getTools(mw) {
if tool.Name() == "read_file" {
result, err := tool.Invoke(context.Background(), "short.txt")
- if err != nil { t.Fatalf("read_file: %v", err) }
+ if err != nil {
+ t.Fatalf("read_file: %v", err)
+ }
if !strings.Contains(result, "short file") {
t.Errorf("unexpected result: %q", result)
}
diff --git a/internal/harness/core/middlewares/patchtoolcalls/patchtoolcalls_test.go b/internal/harness/core/middlewares/patchtoolcalls/patchtoolcalls_test.go
index d57e58e78b..505d0f9635 100644
--- a/internal/harness/core/middlewares/patchtoolcalls/patchtoolcalls_test.go
+++ b/internal/harness/core/middlewares/patchtoolcalls/patchtoolcalls_test.go
@@ -24,7 +24,9 @@ func TestBeforeModelRewrite_InsertsPlaceholders(t *testing.T) {
}
state := core.NewReActAgentState(msgs, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
// Should have inserted a placeholder for the missing tool result
foundPlaceholder := false
@@ -54,7 +56,9 @@ func TestBeforeModelRewrite_CompleteToolCall(t *testing.T) {
}
state := core.NewReActAgentState(msgs, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
// Should NOT insert a placeholder since the tool result exists
placeholderCount := 0
@@ -76,7 +80,9 @@ func TestBeforeModelRewrite_NoToolCalls(t *testing.T) {
}
state := core.NewReActAgentState(msgs, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
if len(newState.Messages) != 2 {
t.Errorf("expected no changes, got %d messages", len(newState.Messages))
}
@@ -99,15 +105,21 @@ func TestBeforeModelRewrite_MultipleMissingCalls(t *testing.T) {
}
state := core.NewReActAgentState(msgs, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
// Should have inserted placeholders for both missing calls
foundA := false
foundB := false
for _, m := range newState.Messages {
if m.Role == schema.RoleTool {
- if m.Name == "call_a" { foundA = true }
- if m.Name == "call_b" { foundB = true }
+ if m.Name == "call_a" {
+ foundA = true
+ }
+ if m.Name == "call_b" {
+ foundB = true
+ }
}
}
if !foundA || !foundB {
@@ -119,6 +131,8 @@ func TestBeforeModelRewrite_EmptyState(t *testing.T) {
mw := New[*schema.Message](nil)
state := core.NewReActAgentState[*schema.Message](nil, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
_ = newState
}
diff --git a/internal/harness/core/middlewares/plantask/plantask.go b/internal/harness/core/middlewares/plantask/plantask.go
index 1d0068d54a..5d95e20e62 100644
--- a/internal/harness/core/middlewares/plantask/plantask.go
+++ b/internal/harness/core/middlewares/plantask/plantask.go
@@ -30,22 +30,22 @@ const (
// Task represents a unit of work managed by plantask.
type Task struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Description string `json:"description"`
- State TaskState `json:"state"`
- Result string `json:"result,omitempty"`
- Error string `json:"error,omitempty"`
- ParentID string `json:"parent_id,omitempty"`
- Dependencies []string `json:"dependencies,omitempty"`
- Metadata map[string]any `json:"metadata,omitempty"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ State TaskState `json:"state"`
+ Result string `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+ ParentID string `json:"parent_id,omitempty"`
+ Dependencies []string `json:"dependencies,omitempty"`
+ Metadata map[string]any `json:"metadata,omitempty"`
}
// Manager manages tasks for an agent run session.
type Manager struct {
- mu sync.RWMutex
- tasks map[string]*taskInternal
- nextID int64
+ mu sync.RWMutex
+ tasks map[string]*taskInternal
+ nextID int64
}
type taskInternal struct {
@@ -64,7 +64,9 @@ func NewManager() *Manager {
// as a subtask of the parent within the same lock (TOCTOU-safe).
func (m *Manager) Create(ctx context.Context, title, desc string, opts ...CreateOption) (*Task, error) {
cfg := &createConfig{State: TaskPending}
- for _, o := range opts { o(cfg) }
+ for _, o := range opts {
+ o(cfg)
+ }
m.mu.Lock()
defer m.mu.Unlock()
@@ -95,7 +97,9 @@ func (m *Manager) Get(id string) (*Task, error) {
m.mu.RLock()
defer m.mu.RUnlock()
t, ok := m.tasks[id]
- if !ok { return nil, fmt.Errorf("task '%s' not found", id) }
+ if !ok {
+ return nil, fmt.Errorf("task '%s' not found", id)
+ }
return t.Task, nil
}
@@ -115,9 +119,15 @@ func (m *Manager) List() ([]*Task, error) {
// ListByState returns tasks filtered by state.
func (m *Manager) ListByState(state TaskState) ([]*Task, error) {
all, err := m.List()
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
var result []*Task
- for _, t := range all { if t.State == state { result = append(result, t) } }
+ for _, t := range all {
+ if t.State == state {
+ result = append(result, t)
+ }
+ }
return result, nil
}
@@ -126,8 +136,12 @@ func (m *Manager) Update(id string, opts ...UpdateOption) (*Task, error) {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tasks[id]
- if !ok { return nil, fmt.Errorf("task '%s' not found", id) }
- for _, o := range opts { o(t.Task) }
+ if !ok {
+ return nil, fmt.Errorf("task '%s' not found", id)
+ }
+ for _, o := range opts {
+ o(t.Task)
+ }
return t.Task, nil
}
@@ -136,7 +150,9 @@ func (m *Manager) SetState(id string, state TaskState) error {
m.mu.Lock()
defer m.mu.Unlock()
t, ok := m.tasks[id]
- if !ok { return fmt.Errorf("task '%s' not found", id) }
+ if !ok {
+ return fmt.Errorf("task '%s' not found", id)
+ }
t.State = state
return nil
}
@@ -157,7 +173,9 @@ func (m *Manager) SetError(id, errMsg string) error {
func (m *Manager) Delete(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
- if _, ok := m.tasks[id]; !ok { return fmt.Errorf("task '%s' not found", id) }
+ if _, ok := m.tasks[id]; !ok {
+ return fmt.Errorf("task '%s' not found", id)
+ }
delete(m.tasks, id)
return nil
}
@@ -173,9 +191,13 @@ func (m *Manager) GetSubtasks(parentID string) ([]*Task, error) {
m.mu.RLock()
defer m.mu.RUnlock()
pt, ok := m.tasks[parentID]
- if !ok { return nil, fmt.Errorf("task '%s' not found", parentID) }
+ if !ok {
+ return nil, fmt.Errorf("task '%s' not found", parentID)
+ }
var subs []*Task
- for _, st := range pt.subtasks { subs = append(subs, st.Task) }
+ for _, st := range pt.subtasks {
+ subs = append(subs, st.Task)
+ }
return subs, nil
}
@@ -212,11 +234,11 @@ func WithTaskMetadata(md map[string]any) CreateOption {
type UpdateOption func(*Task)
-func WithTitle(t string) UpdateOption { return func(task *Task) { task.Title = t } }
-func WithDescription(d string) UpdateOption { return func(task *Task) { task.Description = d } }
-func WithState(s TaskState) UpdateOption { return func(task *Task) { task.State = s } }
-func WithResult(r string) UpdateOption { return func(task *Task) { task.Result = r } }
-func WithError(e string) UpdateOption { return func(task *Task) { task.Error = e } }
+func WithTitle(t string) UpdateOption { return func(task *Task) { task.Title = t } }
+func WithDescription(d string) UpdateOption { return func(task *Task) { task.Description = d } }
+func WithState(s TaskState) UpdateOption { return func(task *Task) { task.State = s } }
+func WithResult(r string) UpdateOption { return func(task *Task) { task.Result = r } }
+func WithError(e string) UpdateOption { return func(task *Task) { task.Error = e } }
func WithMetadata(md map[string]any) UpdateOption { return func(task *Task) { task.Metadata = md } }
// ---- Tools ----
@@ -225,8 +247,12 @@ func WithMetadata(md map[string]any) UpdateOption { return func(task *Task) { ta
// Returns nil if not found or if called outside agent execution.
func GetManagerFromContext(ctx context.Context) *Manager {
val, ok, _ := core.GetRunLocalValue(ctx, plantaskSessionKey)
- if !ok { return nil }
- if m, ok := val.(*Manager); ok { return m }
+ if !ok {
+ return nil
+ }
+ if m, ok := val.(*Manager); ok {
+ return m
+ }
return nil
}
@@ -236,7 +262,9 @@ const plantaskSessionKey = "_plantask_manager"
// Call this in BeforeAgent middleware before tools that need task management are used.
func InitManager(ctx context.Context) (*Manager, error) {
m := NewManager()
- if err := core.SetRunLocalValue(ctx, plantaskSessionKey, m); err != nil { return nil, err }
+ if err := core.SetRunLocalValue(ctx, plantaskSessionKey, m); err != nil {
+ return nil, err
+ }
return m, nil
}
@@ -247,17 +275,25 @@ func ToolCreateTask() core.Tool {
"Create a new task. Args JSON: {\"title\":\"...\",\"description\":\"...\",\"parent_id?\":\"...\"}",
func(ctx context.Context, args string) (string, error) {
m := GetManagerFromContext(ctx)
- if m == nil { return "", fmt.Errorf("plantask manager not initialized") }
+ if m == nil {
+ return "", fmt.Errorf("plantask manager not initialized")
+ }
var in struct {
Title string `json:"title"`
Description string `json:"description"`
ParentID string `json:"parent_id,omitempty"`
}
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
opts := []CreateOption{}
- if in.ParentID != "" { opts = append(opts, WithParentID(in.ParentID)) }
+ if in.ParentID != "" {
+ opts = append(opts, WithParentID(in.ParentID))
+ }
t, err := m.Create(ctx, in.Title, in.Description, opts...)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
b, _ := json.Marshal(t)
return string(b), nil
},
@@ -271,8 +307,12 @@ func ToolListTasks() core.Tool {
"List all tasks. Optionally filter by state. Args JSON: {\"state?\":\"pending|running|completed|failed\"}",
func(ctx context.Context, args string) (string, error) {
m := GetManagerFromContext(ctx)
- if m == nil { return "", fmt.Errorf("plantask manager not initialized") }
- var in struct { State *string `json:"state,omitempty"` }
+ if m == nil {
+ return "", fmt.Errorf("plantask manager not initialized")
+ }
+ var in struct {
+ State *string `json:"state,omitempty"`
+ }
json.Unmarshal([]byte(args), &in) // ignore error - optional field
var tasks []*Task
var err error
@@ -281,7 +321,9 @@ func ToolListTasks() core.Tool {
} else {
tasks, err = m.List()
}
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
b, _ := json.Marshal(tasks)
return string(b), nil
},
@@ -295,11 +337,19 @@ func ToolGetTask() core.Tool {
"Get task details by ID. Args JSON: {\"id\":\"task_1\"}",
func(ctx context.Context, args string) (string, error) {
m := GetManagerFromContext(ctx)
- if m == nil { return "", fmt.Errorf("plantask manager not initialized") }
- var in struct{ ID string `json:"id"` }
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
+ if m == nil {
+ return "", fmt.Errorf("plantask manager not initialized")
+ }
+ var in struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
t, err := m.Get(in.ID)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
b, _ := json.Marshal(t)
return string(b), nil
},
@@ -313,7 +363,9 @@ func ToolUpdateTask() core.Tool {
"Update a task. Args JSON: {\"id\":\"...\",\"state?\":\"completed\",\"result?\":\"...\"}",
func(ctx context.Context, args string) (string, error) {
m := GetManagerFromContext(ctx)
- if m == nil { return "", fmt.Errorf("plantask manager not initialized") }
+ if m == nil {
+ return "", fmt.Errorf("plantask manager not initialized")
+ }
var in struct {
ID string `json:"id"`
State string `json:"state,omitempty"`
@@ -321,14 +373,26 @@ func ToolUpdateTask() core.Tool {
Error string `json:"error,omitempty"`
Title string `json:"title,omitempty"`
}
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
var opts []UpdateOption
- if in.State != "" { opts = append(opts, WithState(TaskState(in.State))) }
- if in.Result != "" { opts = append(opts, WithResult(in.Result)) }
- if in.Error != "" { opts = append(opts, WithError(in.Error)) }
- if in.Title != "" { opts = append(opts, WithTitle(in.Title)) }
+ if in.State != "" {
+ opts = append(opts, WithState(TaskState(in.State)))
+ }
+ if in.Result != "" {
+ opts = append(opts, WithResult(in.Result))
+ }
+ if in.Error != "" {
+ opts = append(opts, WithError(in.Error))
+ }
+ if in.Title != "" {
+ opts = append(opts, WithTitle(in.Title))
+ }
t, err := m.Update(in.ID, opts...)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
b, _ := json.Marshal(t)
return string(b), nil
},
@@ -342,10 +406,18 @@ func ToolDeleteTask() core.Tool {
"Delete a task by ID. Args JSON: {\"id\":\"task_1\"}",
func(ctx context.Context, args string) (string, error) {
m := GetManagerFromContext(ctx)
- if m == nil { return "", fmt.Errorf("plantask manager not initialized") }
- var in struct{ ID string `json:"id"` }
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
- if err := m.Delete(in.ID); err != nil { return "", err }
+ if m == nil {
+ return "", fmt.Errorf("plantask manager not initialized")
+ }
+ var in struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
+ if err := m.Delete(in.ID); err != nil {
+ return "", err
+ }
return fmt.Sprintf(`{"deleted":true,"id":"%s"}`, in.ID), nil
},
)
diff --git a/internal/harness/core/middlewares/plantask/plantask_test.go b/internal/harness/core/middlewares/plantask/plantask_test.go
index ff60af0f82..166049851e 100644
--- a/internal/harness/core/middlewares/plantask/plantask_test.go
+++ b/internal/harness/core/middlewares/plantask/plantask_test.go
@@ -236,7 +236,9 @@ func TestAllTools(t *testing.T) {
t.Errorf("AllTools returned %d, want 5", len(tools))
}
names := map[string]bool{}
- for _, t := range tools { names[t.Name()] = true }
+ for _, t := range tools {
+ names[t.Name()] = true
+ }
for _, name := range []string{"create_task", "list_tasks", "get_task", "update_task", "delete_task"} {
if !names[name] {
t.Errorf("missing tool: %s", name)
diff --git a/internal/harness/core/middlewares/reduction/reduction.go b/internal/harness/core/middlewares/reduction/reduction.go
index 492e794098..b2ee8a9fa5 100644
--- a/internal/harness/core/middlewares/reduction/reduction.go
+++ b/internal/harness/core/middlewares/reduction/reduction.go
@@ -37,16 +37,24 @@ type Config = TypedConfig[*schema.Message]
type middleware[M core.MessageType] struct {
core.BaseMiddleware[M]
- cfg *TypedConfig[M]
- mu sync.Mutex
+ cfg *TypedConfig[M]
+ mu sync.Mutex
keyCounter int
}
func NewTyped[M core.MessageType](cfg *TypedConfig[M]) core.TypedReActMiddleware[M] {
- if cfg == nil { cfg = &TypedConfig[M]{} }
- if cfg.MaxToolOutputLen <= 0 { cfg.MaxToolOutputLen = 2000 }
- if cfg.MaxToolCalls <= 0 { cfg.MaxToolCalls = 20 }
- if cfg.MaxTokensForClear <= 0 { cfg.MaxTokensForClear = 100000 }
+ if cfg == nil {
+ cfg = &TypedConfig[M]{}
+ }
+ if cfg.MaxToolOutputLen <= 0 {
+ cfg.MaxToolOutputLen = 2000
+ }
+ if cfg.MaxToolCalls <= 0 {
+ cfg.MaxToolCalls = 20
+ }
+ if cfg.MaxTokensForClear <= 0 {
+ cfg.MaxTokensForClear = 100000
+ }
return &middleware[M]{cfg: cfg}
}
@@ -54,7 +62,6 @@ func New(cfg *Config) core.TypedReActMiddleware[*schema.Message] {
return NewTyped[*schema.Message](cfg)
}
-
// ---- Clear Phase (BeforeModelRewrite) ----
func (mw *middleware[M]) BeforeModelRewrite(ctx context.Context, state *core.TypedReActAgentState[M], mc *core.TypedModelContext[M]) (context.Context, *core.TypedReActAgentState[M], error) {
@@ -76,7 +83,9 @@ func (mw *middleware[M]) truncateToolOutputs(state *core.TypedReActAgentState[M]
toolCount := 0
for i, msg := range state.Messages {
m, ok := any(msg).(*schema.Message)
- if !ok || m == nil || m.Role != schema.RoleTool { continue }
+ if !ok || m == nil || m.Role != schema.RoleTool {
+ continue
+ }
toolCount++
if mw.cfg.MaxToolCalls > 0 && toolCount > mw.cfg.MaxToolCalls {
m.Content = "..."
@@ -94,22 +103,30 @@ func (mw *middleware[M]) truncateToolOutputs(state *core.TypedReActAgentState[M]
}
func (mw *middleware[M]) clearOldToolCalls(state *core.TypedReActAgentState[M], totalTokens int) {
- if mw.cfg.ClearAtLeast <= 0 { return }
+ if mw.cfg.ClearAtLeast <= 0 {
+ return
+ }
targetTokens := mw.cfg.MaxTokensForClear - mw.cfg.ClearAtLeast
- if totalTokens <= targetTokens { return }
+ if totalTokens <= targetTokens {
+ return
+ }
freed := 0
toolCount := 0
for i, msg := range state.Messages {
m, ok := any(msg).(*schema.Message)
- if !ok || m == nil || m.Role != schema.RoleTool { continue }
+ if !ok || m == nil || m.Role != schema.RoleTool {
+ continue
+ }
toolCount++
if mw.cfg.MaxToolCalls > 0 && toolCount > mw.cfg.MaxToolCalls {
before := len([]rune(m.Content))
m.Content = "..."
freed += before - 3
state.Messages[i] = any(m).(M)
- if totalTokens-freed <= targetTokens { break }
+ if totalTokens-freed <= targetTokens {
+ break
+ }
}
}
}
@@ -131,7 +148,9 @@ func (mw *middleware[M]) estimateTokens(msgs []M) int {
}
func (mw *middleware[M]) isExcluded(name string) bool {
- if mw.cfg.ExcludeTools == nil { return false }
+ if mw.cfg.ExcludeTools == nil {
+ return false
+ }
return mw.cfg.ExcludeTools[name]
}
@@ -143,6 +162,8 @@ func (mw *middleware[M]) nextKey() int {
}
func truncateText(s string, maxLen int) string {
- if len(s) <= maxLen { return s }
+ if len(s) <= maxLen {
+ return s
+ }
return s[:maxLen]
}
diff --git a/internal/harness/core/middlewares/reduction/reduction_test.go b/internal/harness/core/middlewares/reduction/reduction_test.go
index dc6dd8db8a..4052d73859 100644
--- a/internal/harness/core/middlewares/reduction/reduction_test.go
+++ b/internal/harness/core/middlewares/reduction/reduction_test.go
@@ -15,12 +15,16 @@ type memoryBackend struct {
}
func (b *memoryBackend) Store(key, content string) error {
- if b.data == nil { b.data = make(map[string]string) }
+ if b.data == nil {
+ b.data = make(map[string]string)
+ }
b.data[key] = content
return nil
}
func (b *memoryBackend) Load(key string) (string, error) {
- if b.data == nil { return "", nil }
+ if b.data == nil {
+ return "", nil
+ }
return b.data[key], nil
}
@@ -28,7 +32,9 @@ func (b *memoryBackend) Load(key string) (string, error) {
func TestNew_NilConfig(t *testing.T) {
mw := NewTyped[*schema.Message](nil)
- if mw == nil { t.Fatal("expected non-nil middleware") }
+ if mw == nil {
+ t.Fatal("expected non-nil middleware")
+ }
}
func TestBeforeModelRewrite_Truncation(t *testing.T) {
@@ -43,7 +49,9 @@ func TestBeforeModelRewrite_Truncation(t *testing.T) {
}
state := core.NewReActAgentState(msgs, nil, 10)
_, newState, err := mw.BeforeModelRewrite(context.Background(), state, nil)
- if err != nil { t.Fatalf("BeforeModelRewrite: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeModelRewrite: %v", err)
+ }
found := false
for _, m := range newState.Messages {
@@ -57,12 +65,13 @@ func TestBeforeModelRewrite_Truncation(t *testing.T) {
}
}
-
func TestNewWithConfig_DefaultValues(t *testing.T) {
cfg := &TypedConfig[*schema.Message]{
MaxToolOutputLen: 0,
MaxToolCalls: 0,
}
mw := NewTyped[*schema.Message](cfg)
- if mw == nil { t.Fatal("nil middleware") }
+ if mw == nil {
+ t.Fatal("nil middleware")
+ }
}
diff --git a/internal/harness/core/middlewares/skill/skill.go b/internal/harness/core/middlewares/skill/skill.go
index 7d0d6c4c70..5d259530f1 100644
--- a/internal/harness/core/middlewares/skill/skill.go
+++ b/internal/harness/core/middlewares/skill/skill.go
@@ -15,9 +15,9 @@ import (
type ExecMode int
const (
- ModeInline ExecMode = iota // Skill content injected into instruction
- ModeFork // Skill loaded via a tool
- ModeForkWithContext // Skill loaded via a tool with parent context
+ ModeInline ExecMode = iota // Skill content injected into instruction
+ ModeFork // Skill loaded via a tool
+ ModeForkWithContext // Skill loaded via a tool with parent context
)
// FileSystemBackend reads skill definitions from a file system.
@@ -38,13 +38,13 @@ type Config struct {
// TypedConfig configures the skill middleware.
type TypedConfig[M core.MessageType] struct {
- Skills []Config
- Backend FileSystemBackend
- CustomSystemPrompt func(name, desc string) string
- CustomToolParams func(name string) string
- BuildContent func(ctx context.Context, cfg Config) (string, error)
- BuildForkMessages func(ctx context.Context, cfg Config, request string) (string, error)
- FormatForkResult func(ctx context.Context, result string) (string, error)
+ Skills []Config
+ Backend FileSystemBackend
+ CustomSystemPrompt func(name, desc string) string
+ CustomToolParams func(name string) string
+ BuildContent func(ctx context.Context, cfg Config) (string, error)
+ BuildForkMessages func(ctx context.Context, cfg Config, request string) (string, error)
+ FormatForkResult func(ctx context.Context, result string) (string, error)
}
type middleware[M core.MessageType] struct {
@@ -60,15 +60,49 @@ func New(cfg *TypedConfig[*schema.Message]) core.TypedReActMiddleware[*schema.Me
return NewTyped[*schema.Message](cfg)
}
+func (m *middleware[M]) ContributeTools(ctx context.Context) []core.Tool {
+ if m.cfg == nil {
+ return nil
+ }
+ var tools []core.Tool
+ for _, s := range m.loadSkills() {
+ switch s.ExecutionMode {
+ case ModeFork, ModeForkWithContext:
+ tools = append(tools, m.newSkillTool(s))
+ }
+ }
+ return tools
+}
+
+func (m *middleware[M]) ContributeToolInfos(ctx context.Context) []*schema.ToolInfo { return nil }
+func (m *middleware[M]) ContributeReturnDirectly(ctx context.Context) map[string]bool { return nil }
+
func (m *middleware[M]) BeforeAgent(ctx context.Context, rc *core.ReActAgentContext) (context.Context, *core.ReActAgentContext, error) {
- if m.cfg == nil { return ctx, rc, nil }
+ if m.cfg == nil {
+ return ctx, rc, nil
+ }
+ for _, s := range m.loadSkills() {
+ if s.ExecutionMode == ModeInline {
+ rc.Instruction = applyCustomInstruction(rc.Instruction, s, m.cfg.CustomSystemPrompt)
+ }
+ }
+ return ctx, rc, nil
+}
+
+// loadSkills returns all skills from config and backend.
+func (m *middleware[M]) loadSkills() []Config {
+ if m.cfg == nil {
+ return nil
+ }
skills := m.cfg.Skills
if len(skills) == 0 && m.cfg.Backend != nil {
names, err := m.cfg.Backend.List()
if err == nil {
for _, name := range names {
content, err := m.cfg.Backend.Read(name)
- if err != nil { continue }
+ if err != nil {
+ continue
+ }
parsed := parseSkill(content)
if parsed != nil {
skills = append(skills, *parsed)
@@ -76,16 +110,7 @@ func (m *middleware[M]) BeforeAgent(ctx context.Context, rc *core.ReActAgentCont
}
}
}
-
- for _, s := range skills {
- switch s.ExecutionMode {
- case ModeInline:
- rc.Instruction = applyCustomInstruction(rc.Instruction, s, m.cfg.CustomSystemPrompt)
- case ModeFork, ModeForkWithContext:
- rc.Tools = append(rc.Tools, m.newSkillTool(s))
- }
- }
- return ctx, rc, nil
+ return skills
}
func (m *middleware[M]) newSkillTool(s Config) core.Tool {
@@ -94,7 +119,9 @@ func (m *middleware[M]) newSkillTool(s Config) core.Tool {
func(ctx context.Context, args string) (string, error) {
if m.cfg.BuildContent != nil {
content, err := m.cfg.BuildContent(ctx, s)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
if m.cfg.FormatForkResult != nil {
return m.cfg.FormatForkResult(ctx, content)
}
@@ -103,11 +130,15 @@ func (m *middleware[M]) newSkillTool(s Config) core.Tool {
content := s.Content
if content == "" && m.cfg.Backend != nil {
loaded, err := m.cfg.Backend.Read(s.Name)
- if err == nil { content = loaded }
+ if err == nil {
+ content = loaded
+ }
}
if m.cfg.BuildForkMessages != nil {
result, err := m.cfg.BuildForkMessages(ctx, s, args)
- if err != nil { return "", err }
+ if err != nil {
+ return "", err
+ }
return result, nil
}
if m.cfg.FormatForkResult != nil {
@@ -156,6 +187,8 @@ func applyCustomInstruction(instruction string, s Config, customFn func(name, de
}
func truncate(s string, n int) string {
- if len(s) <= n { return s }
+ if len(s) <= n {
+ return s
+ }
return s[:n] + "\n...(truncated)"
}
diff --git a/internal/harness/core/middlewares/skill/skill_test.go b/internal/harness/core/middlewares/skill/skill_test.go
index b09dc51b5c..82405d42aa 100644
--- a/internal/harness/core/middlewares/skill/skill_test.go
+++ b/internal/harness/core/middlewares/skill/skill_test.go
@@ -16,7 +16,7 @@ type testBackend struct {
}
func (b *testBackend) Read(path string) (string, error) { return b.content, nil }
-func (b *testBackend) List() ([]string, error) { return nil, nil }
+func (b *testBackend) List() ([]string, error) { return nil, nil }
type testModel struct{}
@@ -38,7 +38,9 @@ func TestBeforeAgent_InlineSkill(t *testing.T) {
})
rc := &core.ReActAgentContext{Instruction: "Base instruction", Tools: make([]core.Tool, 0)}
_, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeAgent: %v", err)
+ }
// Inline skill should modify instruction
if !strings.Contains(newRc.Instruction, "test_skill") && !strings.Contains(newRc.Instruction, "test assistant") {
@@ -54,7 +56,9 @@ func TestBeforeAgent_ForkSkill(t *testing.T) {
})
rc := &core.ReActAgentContext{Instruction: "Base", Tools: make([]core.Tool, 0)}
_, newRc, err := mw.BeforeAgent(context.Background(), rc)
- if err != nil { t.Fatalf("BeforeAgent: %v", err) }
+ if err != nil {
+ t.Fatalf("BeforeAgent: %v", err)
+ }
// Fork skills should add a tool
if len(newRc.Tools) == 0 {
t.Log("fork skill should add a tool to the tool list")
@@ -68,20 +72,34 @@ description: My custom skill
---
This is the skill content.`
skill := parseSkill(content)
- if skill == nil { t.Fatal("nil skill") }
- if skill.Name != "my_skill" { t.Errorf("name = %q", skill.Name) }
- if skill.Description != "My custom skill" { t.Errorf("desc = %q", skill.Description) }
+ if skill == nil {
+ t.Fatal("nil skill")
+ }
+ if skill.Name != "my_skill" {
+ t.Errorf("name = %q", skill.Name)
+ }
+ if skill.Description != "My custom skill" {
+ t.Errorf("desc = %q", skill.Description)
+ }
}
func TestParseSkill_NoFrontmatter(t *testing.T) {
content := "Simple skill without frontmatter"
skill := parseSkill(content)
- if skill == nil { t.Fatal("nil skill") }
- if skill.Name != "" { t.Error("expected empty name for no frontmatter") }
- if skill.Content != content { t.Errorf("content = %q", skill.Content) }
+ if skill == nil {
+ t.Fatal("nil skill")
+ }
+ if skill.Name != "" {
+ t.Error("expected empty name for no frontmatter")
+ }
+ if skill.Content != content {
+ t.Errorf("content = %q", skill.Content)
+ }
}
func TestBeforeAgent_NilConfig(t *testing.T) {
mw := NewTyped[*schema.Message](nil)
- if mw == nil { t.Fatal("nil middleware") }
+ if mw == nil {
+ t.Fatal("nil middleware")
+ }
}
diff --git a/internal/harness/core/middlewares/subagent/subagent.go b/internal/harness/core/middlewares/subagent/subagent.go
index b0373a13e4..3dd7416156 100644
--- a/internal/harness/core/middlewares/subagent/subagent.go
+++ b/internal/harness/core/middlewares/subagent/subagent.go
@@ -126,23 +126,24 @@ type Config struct {
// SubAgentMiddleware injects sub-agents as dynamic tools into a parent ReAct agent.
//
-// Key design: AgentTool wrappers are created in BindToConfig (not lazily),
-// and added to the parent's Tools list. ToolsConfig is set to nil to force
-// inline tool dispatch (executeInlineTools), which searches rc.Tools and
-// can find middleware-injected tools.
+// Tool contribution is now handled via the ToolContributor interface (ContributeTools).
+// This eliminates the need to call BindToConfig in most cases. For specs that need
+// middleware inheritance (InheritParentMiddlewares), call Init(ctx, parentConfig)
+// after adding the middleware to the config's Middlewares slice.
//
-// BeforeModelRewrite injects ToolInfo entries so the LLM sees sub-agents as
-// available tools.
+// Deprecated: BindToConfig is retained for backward compatibility. Prefer using
+// Init or the ToolContributor interface directly.
type SubAgentMiddleware struct {
core.BaseMiddleware[*schema.Message]
- cfg *Config
- specs []SubAgentSpec
- mu sync.Mutex
- tools []core.Tool // AgentTool wrappers, built in ensureBuilt
- infos []*schema.ToolInfo
+ cfg *Config
+ specs []SubAgentSpec
+ mu sync.Mutex
+ tools []core.Tool // AgentTool wrappers, built in ensureBuilt
+ infos []*schema.ToolInfo
builtInfos []*schema.ToolInfo // only specs that were actually built
- built bool
+ built bool
+ parentCfg *core.ReActConfig[*schema.Message] // stored by Init for middleware inheritance
}
// New creates a SubAgentMiddleware. Pass nil for cfg to use defaults.
@@ -169,17 +170,105 @@ func New(specs []SubAgentSpec, cfg *Config) *SubAgentMiddleware {
}
}
+// ---- ToolContributor interface ----
+//
+// ContributeTools returns AgentTool wrappers for all specs that can be built
+// without middleware inheritance. For specs needing InheritParentMiddlewares,
+// call Init(ctx, parentConfig) before the agent is built.
+func (m *SubAgentMiddleware) ContributeTools(ctx context.Context) []core.Tool {
+ // If Init was called with a parent config, ensureBuilt handles inheritance.
+ if m.parentCfg != nil {
+ m.ensureBuilt(ctx, m.parentCfg)
+ } else {
+ // No parent config: build simple agents (no middleware inheritance).
+ m.ensureBuiltSimple(ctx)
+ }
+ m.mu.Lock()
+ tools := make([]core.Tool, len(m.tools))
+ copy(tools, m.tools)
+ m.mu.Unlock()
+ return tools
+}
+
+func (m *SubAgentMiddleware) ContributeToolInfos(ctx context.Context) []*schema.ToolInfo {
+ if m.parentCfg != nil {
+ m.ensureBuilt(ctx, m.parentCfg)
+ } else {
+ m.ensureBuiltSimple(ctx)
+ }
+ m.mu.Lock()
+ infos := make([]*schema.ToolInfo, len(m.builtInfos))
+ copy(infos, m.builtInfos)
+ m.mu.Unlock()
+ return infos
+}
+
+func (m *SubAgentMiddleware) ContributeReturnDirectly(ctx context.Context) map[string]bool {
+ // Sub-agent tools should not cause the parent to return directly.
+ return nil
+}
+
+// ensureBuiltSimple builds all specs without middleware inheritance.
+func (m *SubAgentMiddleware) ensureBuiltSimple(ctx context.Context) {
+ m.mu.Lock()
+ if m.built {
+ m.mu.Unlock()
+ return
+ }
+ m.built = true
+ m.mu.Unlock()
+
+ for _, spec := range m.specs {
+ agent := m.resolveAgent(ctx, spec, nil)
+ if agent == nil {
+ continue
+ }
+ m.mu.Lock()
+ m.builtInfos = append(m.builtInfos, &schema.ToolInfo{
+ Name: spec.Name, Description: spec.Description,
+ })
+ opts := []core.AgentToolOption{}
+ if m.cfg.EmitInternalEvents {
+ opts = append(opts, core.WithEmitInternalEvents())
+ }
+ if m.cfg.MaxDepth > 0 {
+ opts = append(opts, core.WithMaxDepth(m.cfg.MaxDepth))
+ }
+ tool := core.NewAgentTool(ctx, agent, opts...)
+ m.tools = append(m.tools, tool)
+ m.mu.Unlock()
+ }
+}
+
+// Init initializes the middleware with the parent agent config, enabling
+// middleware inheritance for SubAgentSpecs with InheritParentMiddlewares.
+// Call this after adding the middleware to config.Middlewares, but before
+// calling NewReActAgent.
+//
+// Example:
+//
+// mw := subagent.New(specs, &subagent.Config{EmitInternalEvents: true, MaxDepth: 5})
+// cfg.Middlewares = append(cfg.Middlewares, mw)
+// mw.Init(ctx, cfg)
+// agent := core.NewReActAgent(cfg)
+func (m *SubAgentMiddleware) Init(ctx context.Context, config *core.ReActConfig[*schema.Message]) {
+ m.parentCfg = config
+ // ensureBuilt is deferred to ContributeTools (called during agent build).
+}
+
// BindToConfig adds sub-agent tools to the parent agent config.
//
+// Deprecated: Prefer using Init(ctx, config) or relying on the ToolContributor
+// interface (which is automatically collected during agent build). BindToConfig
+// has a timing dependency (must be called before NewReActAgent) and sets
+// config.ToolsConfig = nil as a side effect.
+//
// For each spec, it:
// 1. Builds the Agent from AgentConfig (if provided) or uses pre-built Agent.
// 2. Applies middleware inheritance if InheritParentMiddlewares is true.
// 3. Creates an AgentTool wrapper with MaxDepth and EmitInternalEvents.
// 4. Appends the tool to config.Tools.
//
-// It also sets config.ToolsConfig = nil to force inline tool dispatch,
-// which searches rc.Tools (including middleware-injected tools).
-//
// MUST be called before agent.Run().
// The ctx is used for sub-agent construction (AgentFactory calls, AgentTool wrapping).
// Pass the parent agent's build context or context.Background() if none is available.
@@ -257,7 +346,7 @@ func (m *SubAgentMiddleware) resolveAgent(ctx context.Context, spec SubAgentSpec
}
// buildConfig creates a ReActConfig from an AgentConfig, applying middleware
-// inheritance when InheritParentMiddlewares is true.
+// inheritance when InheritParentMiddlewares is true and parentCfg is non-nil.
func (m *SubAgentMiddleware) buildConfig(spec SubAgentSpec, parentCfg *core.ReActConfig[*schema.Message]) *core.ReActConfig[*schema.Message] {
cfg := spec.AgentConfig
subCfg := &core.ReActConfig[*schema.Message]{
@@ -267,8 +356,8 @@ func (m *SubAgentMiddleware) buildConfig(spec SubAgentSpec, parentCfg *core.ReAc
MaxIterations: cfg.MaxIterations,
}
- // Apply middleware inheritance.
- if spec.InheritParentMiddlewares {
+ // Apply middleware inheritance when parent config is available.
+ if spec.InheritParentMiddlewares && parentCfg != nil {
subCfg.Middlewares = m.inheritedMiddlewares(parentCfg, spec.ExcludedParentMiddlewareNames)
}
// Append sub-agent's own middlewares.
diff --git a/internal/harness/core/middlewares/subagent/subagent_test.go b/internal/harness/core/middlewares/subagent/subagent_test.go
index 7c57eecdea..454e89f77b 100644
--- a/internal/harness/core/middlewares/subagent/subagent_test.go
+++ b/internal/harness/core/middlewares/subagent/subagent_test.go
@@ -99,8 +99,8 @@ type mockTool struct {
mu sync.Mutex
}
-func (t *mockTool) Name() string { return t.name }
-func (t *mockTool) Description() string { return t.desc }
+func (t *mockTool) Name() string { return t.name }
+func (t *mockTool) Description() string { return t.desc }
func (t *mockTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
t.mu.Lock()
t.executed = true
@@ -161,8 +161,8 @@ type panicTool struct {
desc string
}
-func (t *panicTool) Name() string { return t.name }
-func (t *panicTool) Description() string { return t.desc }
+func (t *panicTool) Name() string { return t.name }
+func (t *panicTool) Description() string { return t.desc }
func (t *panicTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
panic("unexpected error in tool execution")
}
@@ -178,8 +178,8 @@ type slowTool struct {
delay time.Duration
}
-func (t *slowTool) Name() string { return t.name }
-func (t *slowTool) Description() string { return t.desc }
+func (t *slowTool) Name() string { return t.name }
+func (t *slowTool) Description() string { return t.desc }
func (t *slowTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
select {
case <-ctx.Done():
@@ -195,15 +195,15 @@ func (t *slowTool) Stream(ctx context.Context, args string, opts ...core.ToolOpt
// ---- Enhanced Error Tool ----
type enhancedErrorTool struct {
- name string
- desc string
- errMsg string
- executed bool
- mu sync.Mutex
+ name string
+ desc string
+ errMsg string
+ executed bool
+ mu sync.Mutex
}
-func (t *enhancedErrorTool) Name() string { return t.name }
-func (t *enhancedErrorTool) Description() string { return t.desc }
+func (t *enhancedErrorTool) Name() string { return t.name }
+func (t *enhancedErrorTool) Description() string { return t.desc }
func (t *enhancedErrorTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
return "", nil
}
@@ -732,7 +732,7 @@ func TestSubAgent_MiddlewareInheritance(t *testing.T) {
AgentConfig: &AgentConfig{
Model: func() *mockModel { m := &mockModel{}; m.addResp("inheritor done"); return m }(),
},
- InheritParentMiddlewares: true,
+ InheritParentMiddlewares: true,
ExcludedParentMiddlewareNames: nil,
},
}, nil)
@@ -871,7 +871,7 @@ func TestSubAgent_SubAgentOwnMiddlewares(t *testing.T) {
Name: "tracked",
Description: "Tracked sub-agent",
AgentConfig: &AgentConfig{
- Model: func() *mockModel { m := &mockModel{}; m.addResp("tracked done"); return m }(),
+ Model: func() *mockModel { m := &mockModel{}; m.addResp("tracked done"); return m }(),
Middlewares: []core.ReActMiddleware{subTracker},
},
InheritParentMiddlewares: true,
@@ -1350,7 +1350,7 @@ func TestSubAgent_ParallelToolCallsOneFails(t *testing.T) {
// sub-agent's internal error events without panicking or deadlocking.
func TestSubAgent_EmitInternalEventsWithError(t *testing.T) {
failTool := &mockTool{
- name: "flaky", desc: "Flaky tool",
+ name: "flaky", desc: "Flaky tool",
invokeErr: errors.New("internal error"),
}
diff --git a/internal/harness/core/middlewares/summarization/prompt.go b/internal/harness/core/middlewares/summarization/prompt.go
index 72f815f606..1b8812dbde 100644
--- a/internal/harness/core/middlewares/summarization/prompt.go
+++ b/internal/harness/core/middlewares/summarization/prompt.go
@@ -3,7 +3,7 @@ package summarization
// Action types for EmitInternalEvents
const (
- ActionTypeBeforeSummarize = "summarize:before"
- ActionTypeAfterSummarize = "summarize:after"
- ActionTypeGenerateSummary = "summarize:generate"
+ ActionTypeBeforeSummarize = "summarize:before"
+ ActionTypeAfterSummarize = "summarize:after"
+ ActionTypeGenerateSummary = "summarize:generate"
)
diff --git a/internal/harness/core/middlewares/summarization/summarization.go b/internal/harness/core/middlewares/summarization/summarization.go
index 000633513e..dc81dbce30 100644
--- a/internal/harness/core/middlewares/summarization/summarization.go
+++ b/internal/harness/core/middlewares/summarization/summarization.go
@@ -16,8 +16,8 @@ import (
// TriggerCondition defines when summarization activates.
type TriggerCondition struct {
- MaxTokens int // Trigger when estimated tokens exceed this
- MaxMessages int // Trigger when message count exceeds this (0 = no limit)
+ MaxTokens int // Trigger when estimated tokens exceed this
+ MaxMessages int // Trigger when message count exceeds this (0 = no limit)
}
// TypedConfig configures the summarization middleware.
@@ -69,7 +69,7 @@ func NewTyped[M core.MessageType](cfg *TypedConfig[M]) core.TypedReActMiddleware
}
if cfg.CompactionCfg == nil {
cfg.CompactionCfg = &CompactionConfig{
- TriggerTokens: 100000,
+ TriggerTokens: 100000,
PreserveRecent: 4,
}
}
diff --git a/internal/harness/core/model_chain.go b/internal/harness/core/model_chain.go
index 73d71a191e..9d483da398 100644
--- a/internal/harness/core/model_chain.go
+++ b/internal/harness/core/model_chain.go
@@ -23,7 +23,9 @@ func (w *eventSenderModelWrapper[M]) Generate(ctx context.Context, msgs []M, opt
return w.inner.Generate(ctx, msgs, opts...)
}
resp, err := w.inner.Generate(ctx, msgs, opts...)
- if err != nil { return resp, err }
+ if err != nil {
+ return resp, err
+ }
if w.execCtx != nil && w.execCtx.generator != nil && !isNilMessage(resp) {
w.execCtx.send(typedModelOutputEvent(resp, nil))
}
@@ -32,7 +34,9 @@ func (w *eventSenderModelWrapper[M]) Generate(ctx context.Context, msgs []M, opt
func (w *eventSenderModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts ...ModelOption) (*schema.StreamReader[M], error) {
s, err := w.inner.Stream(ctx, msgs, opts...)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
if w.execCtx != nil && w.execCtx.suppressEventSend {
return s, nil
}
@@ -43,8 +47,13 @@ func (w *eventSenderModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts
var chunks []M
for {
c, err := s.Recv()
- if err == io.EOF { break }
- if err != nil { r.Send(c, err); return }
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ r.Send(c, err)
+ return
+ }
chunks = append(chunks, c)
r.Send(c, nil)
}
@@ -57,7 +66,9 @@ func (w *eventSenderModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts
return r, nil
}
-func (w *eventSenderModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error { return w.inner.BindTools(tools) }
+func (w *eventSenderModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error {
+ return w.inner.BindTools(tools)
+}
// ---- CallbackInjectionModelWrapper (for tracing/monitoring) ----
@@ -74,17 +85,23 @@ func (w *callbackModelWrapper[M]) Generate(ctx context.Context, msgs []M, opts .
switch any(msgs[0]).(type) {
case *schema.Message:
msgSlice := make([]Message, len(msgs))
- for i, m := range msgs { msgSlice[i] = any(m).(*schema.Message) }
+ for i, m := range msgs {
+ msgSlice[i] = any(m).(*schema.Message)
+ }
input.Input = &AgentInput{Messages: msgSlice}
}
}
- for _, cb := range cbs { cb.onStart(ctx, input) }
+ for _, cb := range cbs {
+ cb.onStart(ctx, input)
+ }
}
resp, err := w.inner.Generate(ctx, msgs, opts...)
if len(cbs) > 0 {
if err != nil {
for _, cb := range cbs {
- if cb.onError != nil { cb.onError(ctx, err) }
+ if cb.onError != nil {
+ cb.onError(ctx, err)
+ }
}
}
evIter, evGen := NewAsyncIteratorPair[*AgentEvent]()
@@ -97,7 +114,9 @@ func (w *callbackModelWrapper[M]) Generate(ctx context.Context, msgs []M, opts .
}
evGen.Close()
output := &AgentCallbackOutput{Events: evIter}
- for _, cb := range cbs { cb.onEnd(ctx, output) }
+ for _, cb := range cbs {
+ cb.onEnd(ctx, output)
+ }
}
return resp, err
}
@@ -109,23 +128,31 @@ func (w *callbackModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts ...
switch any(msgs[0]).(type) {
case *schema.Message:
msgSlice := make([]Message, len(msgs))
- for i, m := range msgs { msgSlice[i] = any(m).(*schema.Message) }
+ for i, m := range msgs {
+ msgSlice[i] = any(m).(*schema.Message)
+ }
input.Input = &AgentInput{Messages: msgSlice}
}
}
- for _, cb := range cbs { cb.onStart(ctx, input) }
+ for _, cb := range cbs {
+ cb.onStart(ctx, input)
+ }
}
s, err := w.inner.Stream(ctx, msgs, opts...)
if err != nil {
if len(cbs) > 0 {
for _, cb := range cbs {
- if cb.onError != nil { cb.onError(ctx, err) }
+ if cb.onError != nil {
+ cb.onError(ctx, err)
+ }
}
evIter, evGen := NewAsyncIteratorPair[*AgentEvent]()
evGen.Send(&AgentEvent{Err: err})
evGen.Close()
output := &AgentCallbackOutput{Events: evIter}
- for _, cb := range cbs { cb.onEnd(ctx, output) }
+ for _, cb := range cbs {
+ cb.onEnd(ctx, output)
+ }
}
return nil, err
}
@@ -137,8 +164,13 @@ func (w *callbackModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts ...
var allChunks []M
for {
c, e := s.Recv()
- if e == io.EOF { break }
- if e != nil { r.Send(c, e); return }
+ if e == io.EOF {
+ break
+ }
+ if e != nil {
+ r.Send(c, e)
+ return
+ }
allChunks = append(allChunks, c)
r.Send(c, nil)
}
@@ -150,12 +182,16 @@ func (w *callbackModelWrapper[M]) Stream(ctx context.Context, msgs []M, opts ...
})
evGen.Close()
output := &AgentCallbackOutput{Events: evIter}
- for _, cb := range cbs { cb.onEnd(ctx, output) }
+ for _, cb := range cbs {
+ cb.onEnd(ctx, output)
+ }
}
}()
return r, nil
}
-func (w *callbackModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error { return w.inner.BindTools(tools) }
+func (w *callbackModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error {
+ return w.inner.BindTools(tools)
+}
// ---- Model Wrapper Chain Builder ----
@@ -164,7 +200,8 @@ func (w *callbackModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error { re
// base → failover → retry → eventSender → user wrappers → callback
//
// The chain is built from innermost (closest to model) to outermost.
-func BuildModelWrapperChain[M MessageType](base Model[M], ec *reActExecCtx, cfg *ReActConfig[M]) Model[M] {
+// allToolInfos contains the merged tool infos from config.Tools + ToolContributor middlewares.
+func BuildModelWrapperChain[M MessageType](base Model[M], ec *reActExecCtx, cfg *ReActConfig[M], allToolInfos []*schema.ToolInfo) Model[M] {
model := base
// 1. Event sender (skip if user middlewares provide their own to avoid duplicates)
@@ -185,19 +222,25 @@ func BuildModelWrapperChain[M MessageType](base Model[M], ec *reActExecCtx, cfg
// 4. User middleware wrappers (outermost)
for _, mw := range cfg.Middlewares {
- if mw == nil { continue }
+ if mw == nil {
+ continue
+ }
mc := &TypedModelContext[M]{
- Tools: toolsToInfosTyped[M](cfg.Tools),
+ Tools: allToolInfos,
ModelRetryConfig: cfg.RetryConfig,
ModelFailoverConfig: cfg.FailoverConfig,
}
wrapped, err := mw.WrapModel(context.Background(), model, mc)
- if err == nil && wrapped != nil { model = wrapped }
+ if err == nil && wrapped != nil {
+ model = wrapped
+ }
}
// 5. State wrapper: message deep copy + ID injection + cancel check (guards against middleware side-effects)
var cancelCtx *cancelContext
- if ec != nil { cancelCtx = ec.cancelCtx }
+ if ec != nil {
+ cancelCtx = ec.cancelCtx
+ }
model = newTypedStateModelWrapper(model, cancelCtx)
// 6. Callback injection (outermost — wraps everything)
diff --git a/internal/harness/core/model_chain_retry_failover_test.go b/internal/harness/core/model_chain_retry_failover_test.go
index 330de99c8d..d0570724e7 100644
--- a/internal/harness/core/model_chain_retry_failover_test.go
+++ b/internal/harness/core/model_chain_retry_failover_test.go
@@ -285,7 +285,7 @@ func TestBuildModelWrapperChain_RetryThenFailover_Integration(t *testing.T) {
FailoverConfig: &FailoverConfig[Message]{Models: []Model[Message]{m2}},
}
- wrapped := BuildModelWrapperChain(m1, nil, cfg)
+ wrapped := BuildModelWrapperChain(m1, nil, cfg, nil)
ctx := context.Background()
resp, err := wrapped.Generate(ctx, []Message{schema.UserMessage("test")})
diff --git a/internal/harness/core/model_chain_test.go b/internal/harness/core/model_chain_test.go
index 5228928512..78d8926502 100644
--- a/internal/harness/core/model_chain_test.go
+++ b/internal/harness/core/model_chain_test.go
@@ -13,11 +13,17 @@ import (
func TestBuildModelWrapperChain_NoConfig(t *testing.T) {
base := &mockModel{}
base.addResp("raw")
- model := BuildModelWrapperChain(base, nil, DefaultReActConfig[*schema.Message]())
- if model == nil { t.Fatal("nil model") }
+ model := BuildModelWrapperChain(base, nil, DefaultReActConfig[*schema.Message](), nil)
+ if model == nil {
+ t.Fatal("nil model")
+ }
resp, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "raw" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "raw" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestBuildModelWrapperChain_WithRetry(t *testing.T) {
@@ -25,11 +31,17 @@ func TestBuildModelWrapperChain_WithRetry(t *testing.T) {
base.addResp("retry-ok")
cfg := DefaultReActConfig[*schema.Message]()
cfg.RetryConfig = &ModelRetryConfig{MaxRetries: 2}
- model := BuildModelWrapperChain(base, nil, cfg)
- if model == nil { t.Fatal("nil model") }
+ model := BuildModelWrapperChain(base, nil, cfg, nil)
+ if model == nil {
+ t.Fatal("nil model")
+ }
resp, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "retry-ok" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "retry-ok" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestBuildModelWrapperChain_WithFailover(t *testing.T) {
@@ -40,10 +52,14 @@ func TestBuildModelWrapperChain_WithFailover(t *testing.T) {
cfg := DefaultReActConfig[*schema.Message]()
cfg.FailoverConfig = &FailoverConfigMsg{Models: []Model[*schema.Message]{fallback}}
- model := BuildModelWrapperChain(primary, nil, cfg)
+ model := BuildModelWrapperChain(primary, nil, cfg, nil)
resp, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "primary-ok" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "primary-ok" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestBuildModelWrapperChain_WithMiddleware(t *testing.T) {
@@ -57,10 +73,14 @@ func TestBuildModelWrapperChain_WithMiddleware(t *testing.T) {
base.addResp("mw-ok")
cfg := DefaultReActConfig[*schema.Message]()
cfg.Middlewares = []ReActMiddleware{mw}
- model := BuildModelWrapperChain(base, nil, cfg)
+ model := BuildModelWrapperChain(base, nil, cfg, nil)
resp, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if !wrapCalled { t.Error("middleware WrapModel not called") }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if !wrapCalled {
+ t.Error("middleware WrapModel not called")
+ }
_ = resp
}
@@ -82,10 +102,14 @@ func TestBuildModelWrapperChain_WithFullChain(t *testing.T) {
cfg.FailoverConfig = &FailoverConfigMsg{Models: []Model[*schema.Message]{fallback}}
cfg.Middlewares = []ReActMiddleware{mw}
- model := BuildModelWrapperChain(primary, nil, cfg)
+ model := BuildModelWrapperChain(primary, nil, cfg, nil)
resp, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if !wrapCalled { t.Error("middleware WrapModel not called in chain") }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if !wrapCalled {
+ t.Error("middleware WrapModel not called in chain")
+ }
_ = resp
}
@@ -94,9 +118,11 @@ func TestBuildModelWrapperChain_NilMiddleware(t *testing.T) {
base.addResp("nil-mw")
cfg := DefaultReActConfig[*schema.Message]()
cfg.Middlewares = []ReActMiddleware{nil, nil}
- model := BuildModelWrapperChain(base, nil, cfg)
+ model := BuildModelWrapperChain(base, nil, cfg, nil)
_, err := model.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
}
// ---- eventSenderModelWrapper tests ----
@@ -111,12 +137,18 @@ func TestEventSenderModelWrapper_GenerateSendsEvent(t *testing.T) {
go func() {
defer gen.Close()
resp, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Errorf("Generate: %v", err) }
- if resp.Content != "event-test" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Errorf("Generate: %v", err)
+ }
+ if resp.Content != "event-test" {
+ t.Errorf("content = %s", resp.Content)
+ }
}()
ev, ok := it.Next()
- if !ok { t.Fatal("expected event from wrapper") }
+ if !ok {
+ t.Fatal("expected event from wrapper")
+ }
if ev.Output == nil || ev.Output.MessageOutput == nil {
t.Error("expected message output event")
}
@@ -132,16 +164,25 @@ func TestEventSenderModelWrapper_StreamSendsEvent(t *testing.T) {
go func() {
defer gen.Close()
s, err := wrapped.Stream(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Errorf("Stream: %v", err) }
+ if err != nil {
+ t.Errorf("Stream: %v", err)
+ }
for {
_, err := s.Recv()
- if err == io.EOF { break }
- if err != nil { t.Errorf("Recv: %v", err); return }
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Errorf("Recv: %v", err)
+ return
+ }
}
}()
ev, ok := it.Next()
- if !ok { t.Fatal("expected event from stream wrapper") }
+ if !ok {
+ t.Fatal("expected event from stream wrapper")
+ }
if ev.Output == nil || ev.Output.MessageOutput == nil {
t.Error("expected message output event from stream")
}
@@ -159,7 +200,9 @@ func TestEventSenderModelWrapper_SuppressEventSend(t *testing.T) {
defer close(done)
defer gen.Close()
_, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Errorf("Generate: %v", err) }
+ if err != nil {
+ t.Errorf("Generate: %v", err)
+ }
}()
// After Generate returns, check that the channel has no events
@@ -178,8 +221,12 @@ func TestEventSenderModelWrapper_NilExecCtx(t *testing.T) {
base.addResp("nil-ec")
wrapped := wrapModelWithEventSender(base, nil)
resp, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "nil-ec" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "nil-ec" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestEventSenderModelWrapper_NilGenerator(t *testing.T) {
@@ -188,15 +235,21 @@ func TestEventSenderModelWrapper_NilGenerator(t *testing.T) {
ec := &reActExecCtx{generator: nil}
wrapped := wrapModelWithEventSender(base, ec)
resp, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "nil-gen" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "nil-gen" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestEventSenderModelWrapper_BindTools(t *testing.T) {
base := &mockModel{}
wrapped := wrapModelWithEventSender(base, nil)
err := wrapped.BindTools([]*schema.ToolInfo{{Name: "test"}})
- if err != nil { t.Fatalf("BindTools: %v", err) }
+ if err != nil {
+ t.Fatalf("BindTools: %v", err)
+ }
}
func TestEventSenderModelWrapper_IsNilMessage(t *testing.T) {
@@ -210,7 +263,9 @@ func TestEventSenderModelWrapper_IsNilMessage(t *testing.T) {
go func() {
defer gen.Close()
_, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Errorf("Generate: %v", err) }
+ if err != nil {
+ t.Errorf("Generate: %v", err)
+ }
close(done)
}()
// Empty content might still send the event because it's not nil
@@ -223,8 +278,6 @@ func TestEventSenderModelWrapper_IsNilMessage(t *testing.T) {
_ = hasEvent
}
-
-
// ---- callbackModelWrapper tests ----
func TestCallbackModelWrapper_Basic(t *testing.T) {
@@ -232,8 +285,12 @@ func TestCallbackModelWrapper_Basic(t *testing.T) {
inner.addResp("cb-ok")
wrapped := &callbackModelWrapper[*schema.Message]{inner: inner}
resp, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Generate: %v", err) }
- if resp.Content != "cb-ok" { t.Errorf("content = %s", resp.Content) }
+ if err != nil {
+ t.Fatalf("Generate: %v", err)
+ }
+ if resp.Content != "cb-ok" {
+ t.Errorf("content = %s", resp.Content)
+ }
}
func TestCallbackModelWrapper_Stream(t *testing.T) {
@@ -241,17 +298,25 @@ func TestCallbackModelWrapper_Stream(t *testing.T) {
inner.addResp("cb-stream")
wrapped := &callbackModelWrapper[*schema.Message]{inner: inner}
s, err := wrapped.Stream(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Fatalf("Stream: %v", err) }
+ if err != nil {
+ t.Fatalf("Stream: %v", err)
+ }
chunk, err := s.Recv()
- if err != nil { t.Fatalf("Recv: %v", err) }
- if chunk.Content != "cb-stream" { t.Errorf("content = %s", chunk.Content) }
+ if err != nil {
+ t.Fatalf("Recv: %v", err)
+ }
+ if chunk.Content != "cb-stream" {
+ t.Errorf("content = %s", chunk.Content)
+ }
}
func TestCallbackModelWrapper_BindTools(t *testing.T) {
inner := &mockModel{}
wrapped := &callbackModelWrapper[*schema.Message]{inner: inner}
err := wrapped.BindTools([]*schema.ToolInfo{{Name: "test"}})
- if err != nil { t.Fatalf("BindTools: %v", err) }
+ if err != nil {
+ t.Fatalf("BindTools: %v", err)
+ }
}
// ---- HasUserEventSenderModelWrapper tests ----
@@ -278,7 +343,6 @@ func TestHasUserEventSenderModelWrapper_WithoutWrapper(t *testing.T) {
}
}
-
// ---- Wrapper behavior with ExecCtx integration ----
func TestEventSenderModelWrapper_WithExecCtxGenerator(t *testing.T) {
@@ -291,12 +355,16 @@ func TestEventSenderModelWrapper_WithExecCtxGenerator(t *testing.T) {
go func() {
defer gen.Close()
_, err := wrapped.Generate(context.Background(), []Message{schema.UserMessage("hi")})
- if err != nil { t.Errorf("Generate: %v", err) }
+ if err != nil {
+ t.Errorf("Generate: %v", err)
+ }
}()
// Read event from iterator to verify generator integration works
ev, ok := it.Next()
- if !ok { t.Fatal("expected event via generator") }
+ if !ok {
+ t.Fatal("expected event via generator")
+ }
if ev.Output == nil || ev.Output.MessageOutput == nil {
t.Error("expected message output event")
}
diff --git a/internal/harness/core/multi_turn_integration_test.go b/internal/harness/core/multi_turn_integration_test.go
index b17108ad4a..7d020278ba 100644
--- a/internal/harness/core/multi_turn_integration_test.go
+++ b/internal/harness/core/multi_turn_integration_test.go
@@ -862,11 +862,11 @@ func TestMultiTurn_ContextTimeout(t *testing.T) {
// Helper: alternatingToolModel for testing tool call -> tool result -> response flow.
type alternatingToolModel struct {
- inner *mockModel
- toolCalls []schema.ToolCall
- responses []string
- callCount int
- mu sync.Mutex
+ inner *mockModel
+ toolCalls []schema.ToolCall
+ responses []string
+ callCount int
+ mu sync.Mutex
}
func (m *alternatingToolModel) Generate(ctx context.Context, msgs []Message, opts ...modelOption) (Message, error) {
diff --git a/internal/harness/core/options.go b/internal/harness/core/options.go
index b0078daca6..e460ad2653 100644
--- a/internal/harness/core/options.go
+++ b/internal/harness/core/options.go
@@ -90,7 +90,9 @@ func WithToolOptions(opts []ToolOption) RunOption {
// WithAgentToolOptions passes agent-level options to a specific sub-agent identified by name.
func WithAgentToolOptions(agentName string, opts []RunOption) RunOption {
return WrapImplSpecificOptFn(func(o *runOptions) {
- if o.agentToolOptions == nil { o.agentToolOptions = make(map[string][]RunOption) }
+ if o.agentToolOptions == nil {
+ o.agentToolOptions = make(map[string][]RunOption)
+ }
o.agentToolOptions[agentName] = opts
})
}
diff --git a/internal/harness/core/prebuilt/coding/coding.go b/internal/harness/core/prebuilt/coding/coding.go
index c629736d3c..5ba6ab5a42 100644
--- a/internal/harness/core/prebuilt/coding/coding.go
+++ b/internal/harness/core/prebuilt/coding/coding.go
@@ -149,7 +149,8 @@ func New(cfg *Config) *core.ReActAgent[*schema.Message] {
saMW := subagent.New(cfg.SubAgentSpecs, saCfg)
middlewares = append(middlewares, saMW)
- // Build react config with BindToConfig.
+ // Build react config — Init() prepares the sub-agent for middleware
+ // inheritance, while ToolContributor handles automatic tool injection.
reactCfg := &core.ReActConfig[*schema.Message]{
Model: cfg.Model,
Instruction: instruction,
@@ -157,7 +158,7 @@ func New(cfg *Config) *core.ReActAgent[*schema.Message] {
Middlewares: middlewares,
Tools: cfg.Tools,
}
- saMW.BindToConfig(context.Background(), reactCfg)
+ saMW.Init(context.Background(), reactCfg)
return core.NewReActAgent(reactCfg)
}
@@ -259,8 +260,8 @@ func (b *localShellBackend) Execute(command string) (string, error) {
type execTool struct{}
-func (t *execTool) Name() string { return "_bootstrap_tool" }
-func (t *execTool) Description() string { return "Internal bootstrap tool" }
+func (t *execTool) Name() string { return "_bootstrap_tool" }
+func (t *execTool) Description() string { return "Internal bootstrap tool" }
func (t *execTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
return "", nil
}
diff --git a/internal/harness/core/prebuilt/deep/deep.go b/internal/harness/core/prebuilt/deep/deep.go
index 730b4ceaf6..d9712e6bd2 100644
--- a/internal/harness/core/prebuilt/deep/deep.go
+++ b/internal/harness/core/prebuilt/deep/deep.go
@@ -28,11 +28,11 @@ type Config struct {
Model core.Model[*schema.Message]
Tools []core.Tool
MaxIterations int
- Instruction string // Custom system prompt (overrides default)
- EnableShell bool // Enable shell command execution tool
- SubAgents []SubAgentSpec // NEW: Sub-agents for task delegation
+ Instruction string // Custom system prompt (overrides default)
+ EnableShell bool // Enable shell command execution tool
+ SubAgents []SubAgentSpec // NEW: Sub-agents for task delegation
FailoverModel core.Model[*schema.Message] // NEW: Failover model
- OutputKey string // NEW: Session output storage key
+ OutputKey string // NEW: Session output storage key
}
func DefaultConfig() *Config {
@@ -46,9 +46,15 @@ func DefaultConfig() *Config {
// NewTyped creates a new DeepAgent as a TypedReActAgent.
func NewTyped(cfg *Config) *core.ReActAgent[*schema.Message] {
- if cfg == nil { cfg = DefaultConfig() }
- if cfg.MaxIterations <= 0 { cfg.MaxIterations = 20 }
- if cfg.Name == "" { cfg.Name = "deep_agent" }
+ if cfg == nil {
+ cfg = DefaultConfig()
+ }
+ if cfg.MaxIterations <= 0 {
+ cfg.MaxIterations = 20
+ }
+ if cfg.Name == "" {
+ cfg.Name = "deep_agent"
+ }
instruction := cfg.Instruction
if instruction == "" {
@@ -100,7 +106,9 @@ func NewTyped(cfg *Config) *core.ReActAgent[*schema.Message] {
// The deep agent can transfer tasks to sub-agents and receive results.
// If no sub-agents are configured, returns the plain deep agent.
func NewWithSubAgents(ctx context.Context, cfg *Config) (core.ResumableAgent, error) {
- if cfg == nil { cfg = DefaultConfig() }
+ if cfg == nil {
+ cfg = DefaultConfig()
+ }
deep := NewTyped(cfg)
if cfg == nil || len(cfg.SubAgents) == 0 {
return deep, nil
@@ -127,11 +135,17 @@ func ShellTool(workDir string) core.Tool {
"shell",
"Execute a shell command and return its output. Args: {\"command\":\"ls -la\"}",
func(ctx context.Context, args string) (string, error) {
- var in struct{ Command string `json:"command"` }
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
+ var in struct {
+ Command string `json:"command"`
+ }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
cmd := exec.CommandContext(ctx, "sh", "-c", in.Command)
- if workDir != "" { cmd.Dir = workDir }
+ if workDir != "" {
+ cmd.Dir = workDir
+ }
output, err := cmd.CombinedOutput()
result := shellResult{
Command: in.Command,
@@ -161,15 +175,21 @@ func StreamingShellTool(workDir string) core.Tool {
"streaming_shell",
"Execute a shell command with streaming output. Args: {\"command\":\"tail -f log.txt\"}",
func(ctx context.Context, args string) (string, error) {
- var in struct{ Command string `json:"command"` }
+ var in struct {
+ Command string `json:"command"`
+ }
json.Unmarshal([]byte(args), &in) // ignore error
cmd := exec.CommandContext(ctx, "sh", "-c", in.Command)
- if workDir != "" { cmd.Dir = workDir }
+ if workDir != "" {
+ cmd.Dir = workDir
+ }
output, err := cmd.CombinedOutput()
if err != nil {
exitCode := -1
- if ee, ok := err.(*exec.ExitError); ok { exitCode = ee.ExitCode() }
+ if ee, ok := err.(*exec.ExitError); ok {
+ exitCode = ee.ExitCode()
+ }
return fmt.Sprintf(`{"exit_code":%d,"error":"%s","output":"%s"}`, exitCode, err, escapeShell(string(output))), nil
}
return fmt.Sprintf(`{"exit_code":0,"output":%q}`, escapeShell(string(output))), nil
@@ -199,12 +219,12 @@ const (
// Task is a unit of work tracked by the Deep Agent's task manager.
type Task struct {
- ID string `json:"id"`
- Description string `json:"description"`
- State TaskState `json:"state"`
- Result string `json:"result,omitempty"`
- Error string `json:"error,omitempty"`
- Dependencies []string `json:"dependencies,omitempty"`
+ ID string `json:"id"`
+ Description string `json:"description"`
+ State TaskState `json:"state"`
+ Result string `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+ Dependencies []string `json:"dependencies,omitempty"`
}
// TaskManager tracks sub-tasks within a Deep Agent session.
@@ -214,7 +234,7 @@ func NewTaskManager() *TaskManager { return &TaskManager{} }
func (m *TaskManager) Create(desc string, deps ...string) *Task {
t := &Task{
- ID: fmt.Sprintf("task_%d", len(m.tasks)+1),
+ ID: fmt.Sprintf("task_%d", len(m.tasks)+1),
Description: desc, State: TaskPending,
Dependencies: deps,
}
@@ -224,13 +244,19 @@ func (m *TaskManager) Create(desc string, deps ...string) *Task {
func (m *TaskManager) List() []*Task { return m.tasks }
func (m *TaskManager) Get(id string) (*Task, error) {
- for _, t := range m.tasks { if t.ID == id { return t, nil } }
+ for _, t := range m.tasks {
+ if t.ID == id {
+ return t, nil
+ }
+ }
return nil, fmt.Errorf("task %q not found", id)
}
func (m *TaskManager) Update(id, result string, state TaskState) error {
t, err := m.Get(id)
- if err != nil { return err }
+ if err != nil {
+ return err
+ }
t.Result = result
t.State = state
return nil
@@ -244,11 +270,13 @@ func TaskCreateTool(m *TaskManager) core.Tool {
func(ctx context.Context, args string) (string, error) {
var in struct {
Todos []struct {
- Desc string `json:"desc"`
- Depends []string `json:"deps,omitempty"`
+ Desc string `json:"desc"`
+ Depends []string `json:"deps,omitempty"`
} `json:"todos"`
}
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
var created []*Task
for _, td := range in.Todos {
t := m.Create(td.Desc, td.Depends...)
@@ -283,8 +311,12 @@ func TaskUpdateTool(m *TaskManager) core.Tool {
Result string `json:"result,omitempty"`
Status string `json:"status"`
}
- if err := json.Unmarshal([]byte(args), &in); err != nil { return "", err }
- if err := m.Update(in.ID, in.Result, TaskState(in.Status)); err != nil { return "", err }
+ if err := json.Unmarshal([]byte(args), &in); err != nil {
+ return "", err
+ }
+ if err := m.Update(in.ID, in.Result, TaskState(in.Status)); err != nil {
+ return "", err
+ }
b, _ := json.Marshal(map[string]string{"updated": in.ID})
return string(b), nil
},
@@ -310,7 +342,7 @@ Guidelines:
- Each sub-task should be specific, actionable, ordered logically
- After completing each sub-task, verify the output is correct`
-var prompts = map[string]struct{ System, TaskPrompt, VerifyPrompt, TransferDesc string}{
+var prompts = map[string]struct{ System, TaskPrompt, VerifyPrompt, TransferDesc string }{
"en": {systemPrompt, "Each sub-task should be specific, actionable, ordered logically.", "After completing each sub-task, verify the output is correct.", "Transfer the question to another agent."},
"zh": {`你是一个深度代理 —— 一个深度优先的任务分解和执行代理。
@@ -331,6 +363,8 @@ var prompts = map[string]struct{ System, TaskPrompt, VerifyPrompt, TransferDesc
}
func SelectPrompt(lang string) string {
- if p, ok := prompts[lang]; ok { return p.System }
+ if p, ok := prompts[lang]; ok {
+ return p.System
+ }
return systemPrompt
}
diff --git a/internal/harness/core/prebuilt/deep/deep_test.go b/internal/harness/core/prebuilt/deep/deep_test.go
index c211cb62ce..907d75ed21 100644
--- a/internal/harness/core/prebuilt/deep/deep_test.go
+++ b/internal/harness/core/prebuilt/deep/deep_test.go
@@ -39,7 +39,9 @@ func TestNewTyped_WithModel(t *testing.T) {
cfg := DefaultConfig()
cfg.Model = &mockModel{}
agent := NewTyped(cfg)
- if agent == nil { t.Fatal("nil agent") }
+ if agent == nil {
+ t.Fatal("nil agent")
+ }
name := agent.Name(context.Background())
if name != "deep_agent" {
t.Errorf("name = %q", name)
@@ -50,7 +52,9 @@ func TestNew(t *testing.T) {
cfg := DefaultConfig()
cfg.Model = &mockModel{}
agent := New(cfg)
- if agent == nil { t.Fatal("nil agent") }
+ if agent == nil {
+ t.Fatal("nil agent")
+ }
_ = agent
}
@@ -139,10 +143,10 @@ func TestWithFailoverModel(t *testing.T) {
func TestNewWithSubAgents_BasicCreation(t *testing.T) {
subAgent := core.NewReActAgent(&core.ReActConfig[*schema.Message]{
- Model: &mockModel{},
+ Model: &mockModel{},
Instruction: "You handle data processing.",
}).WithName("data_processor")
-
+
cfg := &Config{
Model: &mockModel{},
SubAgents: []SubAgentSpec{
diff --git a/internal/harness/core/prebuilt/planexecute/plan_execute.go b/internal/harness/core/prebuilt/planexecute/plan_execute.go
index a0e036edbc..1a5b4df83b 100644
--- a/internal/harness/core/prebuilt/planexecute/plan_execute.go
+++ b/internal/harness/core/prebuilt/planexecute/plan_execute.go
@@ -51,10 +51,14 @@ type defaultPlan struct {
func (p *defaultPlan) Steps() []string { return p.StepList }
func (p *defaultPlan) MarshalJSON() ([]byte, error) {
- return json.Marshal(struct{ Steps []string `json:"steps"` }{Steps: p.StepList})
+ return json.Marshal(struct {
+ Steps []string `json:"steps"`
+ }{Steps: p.StepList})
}
func (p *defaultPlan) UnmarshalJSON(data []byte) error {
- var aux struct{ Steps []string `json:"steps"` }
+ var aux struct {
+ Steps []string `json:"steps"`
+ }
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
@@ -234,9 +238,9 @@ func New(ctx context.Context, cfg *Config) (core.ResumableAgent, error) {
}
planner := core.NewReActAgent(&core.ReActConfig[*schema.Message]{
- Model: cfg.Planner.Model,
- Instruction: plannerInstruction,
- Tools: []core.Tool{planToolDef},
+ Model: cfg.Planner.Model,
+ Instruction: plannerInstruction,
+ Tools: []core.Tool{planToolDef},
MaxIterations: 5,
GenModelInput: genPlannerInput,
}).WithName(agentNamePlanner).WithDescription("Generates a step-by-step plan")
@@ -271,12 +275,12 @@ func New(ctx context.Context, cfg *Config) (core.ResumableAgent, error) {
returnDirectly := map[string]bool{toolRespond: true}
replanner := core.NewReActAgent(&core.ReActConfig[*schema.Message]{
- Model: cfg.Replanner.Model,
- Instruction: replannerInstruction,
- Tools: replannerTools,
+ Model: cfg.Replanner.Model,
+ Instruction: replannerInstruction,
+ Tools: replannerTools,
ReturnDirectly: returnDirectly,
- MaxIterations: 5,
- GenModelInput: genReplannerInput,
+ MaxIterations: 5,
+ GenModelInput: genReplannerInput,
}).WithName(agentNameReplanner).WithDescription("Evaluates progress and replans or responds")
// ---- Compose: Sequential(Planner, Loop(Executor, Replanner)) ----
diff --git a/internal/harness/core/prebuilt/planexecute/plan_execute_test.go b/internal/harness/core/prebuilt/planexecute/plan_execute_test.go
index db2eddb922..6b3c76ca68 100644
--- a/internal/harness/core/prebuilt/planexecute/plan_execute_test.go
+++ b/internal/harness/core/prebuilt/planexecute/plan_execute_test.go
@@ -256,8 +256,6 @@ func TestNew_CustomReplannerPrompt(t *testing.T) {
// Test custom NewPlan factory
// ============================================================
-
-
// ============================================================
// Test Executor with tools
// ============================================================
@@ -275,8 +273,8 @@ func TestNew_ExecutorWithTools(t *testing.T) {
)
flow, err := New(ctx, &Config{
- Planner: &PlannerConfig{Model: model},
- Executor: &ExecutorConfig{Model: model, Tools: []core.Tool{tool}},
+ Planner: &PlannerConfig{Model: model},
+ Executor: &ExecutorConfig{Model: model, Tools: []core.Tool{tool}},
Replanner: &ReplannerConfig{Model: model},
})
if err != nil {
@@ -346,6 +344,7 @@ func TestPlanExecute_Integration(t *testing.T) {
}
t.Logf("integration test: final content=%q", lastContent)
}
+
// ============================================================
func TestPlanJSON_Marshal(t *testing.T) {
@@ -487,5 +486,3 @@ func TestReplannerPrompt(t *testing.T) {
t.Error("ReplannerPrompt should mention respond_tool")
}
}
-
-
diff --git a/internal/harness/core/prebuilt/supervisor/supervisor.go b/internal/harness/core/prebuilt/supervisor/supervisor.go
index 29b2622d5a..fa82520814 100644
--- a/internal/harness/core/prebuilt/supervisor/supervisor.go
+++ b/internal/harness/core/prebuilt/supervisor/supervisor.go
@@ -17,8 +17,8 @@ type Config struct {
Name string
Description string
Model core.Model[*schema.Message]
- Agents []AgentSpec // Available sub-agents
- OutputKey string // Store final answer to session under this key
+ Agents []AgentSpec // Available sub-agents
+ OutputKey string // Store final answer to session under this key
}
// AgentSpec defines a sub-agent available to the supervisor.
@@ -30,15 +30,19 @@ type AgentSpec struct {
func DefaultConfig() *Config {
return &Config{
- Name: "supervisor",
+ Name: "supervisor",
Description: "A supervisor agent that routes tasks to specialized sub-agents",
}
}
// New creates a new Supervisor as a flow agent with transfer capability.
func New(ctx context.Context, cfg *Config) (core.ResumableAgent, error) {
- if cfg == nil { cfg = DefaultConfig() }
- if cfg.Model == nil { return nil, fmt.Errorf("supervisor requires a Model") }
+ if cfg == nil {
+ cfg = DefaultConfig()
+ }
+ if cfg.Model == nil {
+ return nil, fmt.Errorf("supervisor requires a Model")
+ }
// Build agent descriptions for the prompt
agentDescs := buildAgentDescriptions(cfg.Agents)
@@ -69,13 +73,17 @@ func New(ctx context.Context, cfg *Config) (core.ResumableAgent, error) {
// easily add a GetType() method to identify the supervisor.
flow, err := core.SetSubAgents(ctx, supAgent, wrappedSubs)
- if err != nil { return nil, fmt.Errorf("set sub-agents: %w", err) }
+ if err != nil {
+ return nil, fmt.Errorf("set sub-agents: %w", err)
+ }
return flow, nil
}
func buildAgentDescriptions(agents []AgentSpec) string {
- if len(agents) == 0 { return "" }
+ if len(agents) == 0 {
+ return ""
+ }
var sb strings.Builder
for _, a := range agents {
sb.WriteString(fmt.Sprintf("- %s: %s\n", a.Name, a.Description))
diff --git a/internal/harness/core/prebuilt/supervisor/supervisor_test.go b/internal/harness/core/prebuilt/supervisor/supervisor_test.go
index fff80c0dfb..484e1fd917 100644
--- a/internal/harness/core/prebuilt/supervisor/supervisor_test.go
+++ b/internal/harness/core/prebuilt/supervisor/supervisor_test.go
@@ -111,7 +111,9 @@ func TestDeterministicTransfer(t *testing.T) {
var events []*core.AgentEvent
for {
ev, ok := iter.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
events = append(events, ev)
}
if len(events) == 0 {
@@ -145,7 +147,9 @@ func (m *mockSupervisorModel) BindTools(tools []*schema.ToolInfo) error { return
func contains(s, sub string) bool {
for i := 0; i <= len(s)-len(sub); i++ {
- if s[i:i+len(sub)] == sub { return true }
+ if s[i:i+len(sub)] == sub {
+ return true
+ }
}
return false
}
@@ -154,10 +158,10 @@ func TestDeterministicTransferConstraint(t *testing.T) {
ctx := context.Background()
model := &mockSupervisorModel{}
subAgent := core.NewReActAgent(&core.ReActConfig[*schema.Message]{
- Model: model,
+ Model: model,
Instruction: "You are a coder.",
}).WithName("coder")
-
+
// Verify that the sub-agent can be wrapped with deterministic transfer
wrapped := core.AgentWithDeterministicTransfer(ctx, &core.DeterministicTransferConfig{
Agent: subAgent,
diff --git a/internal/harness/core/profile/profile.go b/internal/harness/core/profile/profile.go
index 29ca736a63..a83ddcf542 100644
--- a/internal/harness/core/profile/profile.go
+++ b/internal/harness/core/profile/profile.go
@@ -242,7 +242,7 @@ func NewAgent(ctx context.Context, cfg *AgentConfig) (core.Agent, error) {
}
}
- // 6. Handle SubAgentSpecs — create SubAgentMiddleware and bind.
+ // 6. Handle SubAgentSpecs — create SubAgentMiddleware and init.
if len(cfg.SubAgentSpecs) > 0 {
subCfg := &subagent.Config{}
if harness := lookupHarness(cfg.HarnessProfileName); harness != nil && harness.RecursionDepth > 0 {
@@ -250,7 +250,7 @@ func NewAgent(ctx context.Context, cfg *AgentConfig) (core.Agent, error) {
}
saMW := subagent.New(cfg.SubAgentSpecs, subCfg)
reactCfg.Middlewares = append(reactCfg.Middlewares, saMW)
- saMW.BindToConfig(ctx, reactCfg)
+ saMW.Init(ctx, reactCfg)
}
return core.NewReActAgent(reactCfg), nil
diff --git a/internal/harness/core/profile/profile_test.go b/internal/harness/core/profile/profile_test.go
index 21878459ed..7e85777d87 100644
--- a/internal/harness/core/profile/profile_test.go
+++ b/internal/harness/core/profile/profile_test.go
@@ -328,8 +328,12 @@ func TestValidate(t *testing.T) {
func TestFilterMiddlewareByTypeName(t *testing.T) {
defer resetRegistries()
- type mockMW struct{ core.BaseMiddleware[*schema.Message] }
- type excludedMW struct{ core.BaseMiddleware[*schema.Message] }
+ type mockMW struct {
+ core.BaseMiddleware[*schema.Message]
+ }
+ type excludedMW struct {
+ core.BaseMiddleware[*schema.Message]
+ }
mws := []core.ReActMiddleware{
&mockMW{},
@@ -488,7 +492,7 @@ func TestExcludedToolNames(t *testing.T) {
},
})
RegisterHarness(&HarnessProfile{
- Name: "limited",
+ Name: "limited",
ExcludedToolNames: []string{"dangerous_tool"},
})
@@ -514,8 +518,8 @@ type simpleTool struct {
desc string
}
-func (t *simpleTool) Name() string { return t.name }
-func (t *simpleTool) Description() string { return t.desc }
+func (t *simpleTool) Name() string { return t.name }
+func (t *simpleTool) Description() string { return t.desc }
func (t *simpleTool) Invoke(ctx context.Context, args string, opts ...core.ToolOption) (string, error) {
return "result", nil
}
diff --git a/internal/harness/core/profile/providers/providers.go b/internal/harness/core/profile/providers/providers.go
index cb06843787..34a3285667 100644
--- a/internal/harness/core/profile/providers/providers.go
+++ b/internal/harness/core/profile/providers/providers.go
@@ -151,8 +151,8 @@ type anthropicToolDef struct {
}
type anthropicResponse struct {
- Content []contentBlock `json:"content"`
- StopReason string `json:"stop_reason"`
+ Content []contentBlock `json:"content"`
+ StopReason string `json:"stop_reason"`
}
func (m *anthropicModel) Generate(ctx context.Context, msgs []*schema.Message, opts ...core.ModelOption) (*schema.Message, error) {
@@ -338,10 +338,10 @@ type openAIModel struct {
// ---- OpenAI API types ----
type openAIMessage struct {
- Role string `json:"role"`
- Content any `json:"content,omitempty"` // string or []contentPart
- ToolCalls []openAIToolCall `json:"tool_calls,omitempty"`
- ToolCallID string `json:"tool_call_id,omitempty"`
+ Role string `json:"role"`
+ Content any `json:"content,omitempty"` // string or []contentPart
+ ToolCalls []openAIToolCall `json:"tool_calls,omitempty"`
+ ToolCallID string `json:"tool_call_id,omitempty"`
}
type contentPart struct {
@@ -350,9 +350,9 @@ type contentPart struct {
}
type openAIToolCall struct {
- ID string `json:"id"`
- Type string `json:"type"`
- Function openAIFunction `json:"function"`
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Function openAIFunction `json:"function"`
}
type openAIFunction struct {
@@ -361,16 +361,16 @@ type openAIFunction struct {
}
type openAIRequest struct {
- Model string `json:"model"`
- Messages []openAIMessage `json:"messages"`
- Temperature float64 `json:"temperature,omitempty"`
- MaxTokens int `json:"max_tokens,omitempty"`
- Tools []openAIToolDef `json:"tools,omitempty"`
+ Model string `json:"model"`
+ Messages []openAIMessage `json:"messages"`
+ Temperature float64 `json:"temperature,omitempty"`
+ MaxTokens int `json:"max_tokens,omitempty"`
+ Tools []openAIToolDef `json:"tools,omitempty"`
}
type openAIToolDef struct {
- Type string `json:"type"`
- Function openAIFuncDef `json:"function"`
+ Type string `json:"type"`
+ Function openAIFuncDef `json:"function"`
}
type openAIFuncDef struct {
diff --git a/internal/harness/core/prompt_builder.go b/internal/harness/core/prompt_builder.go
index 81fba35667..f01611a10c 100644
--- a/internal/harness/core/prompt_builder.go
+++ b/internal/harness/core/prompt_builder.go
@@ -23,17 +23,25 @@ func NewPromptBuilder() *PromptBuilder {
// PromptBudget defines character limits for prompt sections.
type PromptBudget struct {
- PerFile int // Max chars per instruction file (default: 4000)
- TotalFiles int // Max total chars from all instruction files (default: 12000)
- GitDiff int // Max chars for git diff (default: 50000)
- MaxSections int // Max number of sections (default: 20)
+ PerFile int // Max chars per instruction file (default: 4000)
+ TotalFiles int // Max total chars from all instruction files (default: 12000)
+ GitDiff int // Max chars for git diff (default: 50000)
+ MaxSections int // Max number of sections (default: 20)
}
func (b *PromptBudget) defaults() {
- if b.PerFile <= 0 { b.PerFile = 4000 }
- if b.TotalFiles <= 0 { b.TotalFiles = 12000 }
- if b.GitDiff <= 0 { b.GitDiff = 50000 }
- if b.MaxSections <= 0 { b.MaxSections = 20 }
+ if b.PerFile <= 0 {
+ b.PerFile = 4000
+ }
+ if b.TotalFiles <= 0 {
+ b.TotalFiles = 12000
+ }
+ if b.GitDiff <= 0 {
+ b.GitDiff = 50000
+ }
+ if b.MaxSections <= 0 {
+ b.MaxSections = 20
+ }
}
// Build constructs the final prompt string.
@@ -63,10 +71,10 @@ func (pb *PromptBuilder) Build(parts []PromptSection, budget *PromptBudget) stri
// PromptSection is a named section of the prompt.
type PromptSection struct {
- Name string
- Content string
- TruncateTo int // Max chars for this section (0 = no limit)
- AppendNewline bool
+ Name string
+ Content string
+ TruncateTo int // Max chars for this section (0 = no limit)
+ AppendNewline bool
PrependNewline bool
}
@@ -140,9 +148,9 @@ func InstructionFileSections(files []InstructionFile, budget *PromptBudget) []Pr
name := filepath.Base(f.Path)
sections = append(sections, PromptSection{
- Name: "Instruction: " + name,
- Content: content,
- AppendNewline: true,
+ Name: "Instruction: " + name,
+ Content: content,
+ AppendNewline: true,
PrependNewline: true,
})
}
@@ -161,7 +169,7 @@ func EnvSection() PromptSection {
Name: "Environment",
Content: fmt.Sprintf("Date: %s\nOS: %s/%s\nHost: %s\nCWD: %s",
now, runtime.GOOS, runtime.GOARCH, hostname, cwd),
- AppendNewline: true,
+ AppendNewline: true,
PrependNewline: true,
}
}
diff --git a/internal/harness/core/react.go b/internal/harness/core/react.go
index a55b6fec22..44445c0830 100644
--- a/internal/harness/core/react.go
+++ b/internal/harness/core/react.go
@@ -22,8 +22,8 @@ func NewReActAgentState[M MessageType](msgs []M, tools []*schema.ToolInfo, maxIt
// ReActAgentContext is passed to BeforeAgent middlewares.
type ReActAgentContext struct {
- Instruction string
- Tools []Tool
+ Instruction string
+ Tools []Tool
ReturnDirectly map[string]bool
ToolSearchTool *schema.ToolInfo
}
diff --git a/internal/harness/core/react_agent.go b/internal/harness/core/react_agent.go
index 986fe8dc5a..cbe88ab7da 100644
--- a/internal/harness/core/react_agent.go
+++ b/internal/harness/core/react_agent.go
@@ -7,8 +7,8 @@ import (
"sync"
"sync/atomic"
- "ragflow/internal/harness/core/schema"
"ragflow/internal/harness/core/internal"
+ "ragflow/internal/harness/core/schema"
"ragflow/internal/harness/graph/graph"
)
@@ -62,9 +62,9 @@ type ReActAgentResumeData struct {
// - ResumeWithData / HistoryModifier for resume customization
// - gob encodability check on SetRunLocalValue
type ReActAgent[M MessageType] struct {
- name string
- desc string
- config *ReActConfig[M]
+ name string
+ desc string
+ config *ReActConfig[M]
once sync.Once
frozen uint32
@@ -92,28 +92,34 @@ func defaultGenModelInput(ctx context.Context, instruction string, input *AgentI
func resolveTemplate(tmpl string, ctx context.Context) string {
s := getSession(ctx)
- if s == nil { return tmpl }
+ if s == nil {
+ return tmpl
+ }
result := tmpl
for k, v := range s.Values {
repl := fmt.Sprintf("{%s}", k)
- if sv, ok := v.(string); ok { result = strings.ReplaceAll(result, repl, sv) }
+ if sv, ok := v.(string); ok {
+ result = strings.ReplaceAll(result, repl, sv)
+ }
}
return result
}
func NewReActAgent[M MessageType](cfg *ReActConfig[M]) *ReActAgent[M] {
- if cfg == nil { cfg = DefaultReActConfig[M]() }
+ if cfg == nil {
+ cfg = DefaultReActConfig[M]()
+ }
a := &ReActAgent[M]{name: "react_agent", desc: "ReAct agent using a chat model", config: cfg}
if cfg.ToolsConfig == nil && len(cfg.Tools) > 0 {
cfg.ToolsConfig = &ToolsNodeConfig{Tools: cfg.Tools, ReturnDirectly: cfg.ReturnDirectly}
}
return a
}
-func (a *ReActAgent[M]) WithName(n string) *ReActAgent[M] { a.name = n; return a }
+func (a *ReActAgent[M]) WithName(n string) *ReActAgent[M] { a.name = n; return a }
func (a *ReActAgent[M]) WithDescription(d string) *ReActAgent[M] { a.desc = d; return a }
-func (a *ReActAgent[M]) Name(_ context.Context) string { return a.name }
-func (a *ReActAgent[M]) Description(_ context.Context) string { return a.desc }
-func (a *ReActAgent[M]) GetType() string { return "ReActAgent" }
+func (a *ReActAgent[M]) Name(_ context.Context) string { return a.name }
+func (a *ReActAgent[M]) Description(_ context.Context) string { return a.desc }
+func (a *ReActAgent[M]) GetType() string { return "ReActAgent" }
// ---- Freeze mechanism ----
@@ -127,7 +133,9 @@ func (a *ReActAgent[M]) Run(ctx context.Context, input *TypedAgentInput[M], opts
it, gen := NewAsyncIteratorPair[*TypedAgentEvent[M]]()
go func() {
defer func() {
- if r := recover(); r != nil { gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)}) }
+ if r := recover(); r != nil {
+ gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)})
+ }
gen.Close()
}()
runFunc := a.buildRunFunc(ctx)
@@ -141,14 +149,20 @@ func (a *ReActAgent[M]) Resume(ctx context.Context, info *ResumeInfo, opts ...Ru
it, gen := NewAsyncIteratorPair[*TypedAgentEvent[M]]()
go func() {
defer func() {
- if r := recover(); r != nil { gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)}) }
+ if r := recover(); r != nil {
+ gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)})
+ }
gen.Close()
}()
if info.WasInterrupted {
if s, ok := info.InterruptState.(*TypedReActAgentState[M]); ok {
runFunc := a.buildRunFunc(ctx)
params := &typedRunParams[M]{input: &TypedAgentInput[M]{Messages: s.Messages, EnableStreaming: info.EnableStreaming}, generator: gen, interruptState: s, resumeInfo: info}
- if info.ResumeData != nil { if rd, ok := info.ResumeData.(*ReActAgentResumeData); ok && rd.HistoryModifier != nil { params.historyModifier = rd.HistoryModifier } }
+ if info.ResumeData != nil {
+ if rd, ok := info.ResumeData.(*ReActAgentResumeData); ok && rd.HistoryModifier != nil {
+ params.historyModifier = rd.HistoryModifier
+ }
+ }
runFunc(ctx, params)
a.freeze()
return
@@ -164,38 +178,45 @@ func (a *ReActAgent[M]) Resume(ctx context.Context, info *ResumeInfo, opts ...Ru
type typedRunFunc[M MessageType] func(ctx context.Context, p *typedRunParams[M])
type typedRunParams[M MessageType] struct {
- input *TypedAgentInput[M]
- generator *AsyncGenerator[*TypedAgentEvent[M]]
- interruptState *TypedReActAgentState[M]
- resumeInfo *ResumeInfo
- historyModifier func(context.Context, []Message) []Message
+ input *TypedAgentInput[M]
+ generator *AsyncGenerator[*TypedAgentEvent[M]]
+ interruptState *TypedReActAgentState[M]
+ resumeInfo *ResumeInfo
+ historyModifier func(context.Context, []Message) []Message
afterToolCallsHook func(ctx context.Context) error
}
// reActExecCtx carries per-execution state for event sending, cancellation,
// retry signal propagation, and after-tool-calls hooks.
type reActExecCtx struct {
- generator *AsyncGenerator[*TypedAgentEvent[*schema.Message]]
- cancelCtx *cancelContext
- suppressEventSend bool
- retrySignal *retrySignal
- failoverLastModel Model[*schema.Message]
+ generator *AsyncGenerator[*TypedAgentEvent[*schema.Message]]
+ cancelCtx *cancelContext
+ suppressEventSend bool
+ retrySignal *retrySignal
+ failoverLastModel Model[*schema.Message]
afterToolCallsHook func(ctx context.Context) error
}
func (ec *reActExecCtx) send(ev any) {
if ec != nil && ec.generator != nil {
- if te, ok := ev.(*TypedAgentEvent[*schema.Message]); ok { ec.generator.Send(te) }
+ if te, ok := ev.(*TypedAgentEvent[*schema.Message]); ok {
+ ec.generator.Send(te)
+ }
}
}
type execContext struct {
- instruction string
- returnDirectly map[string]bool
- toolInfos []*schema.ToolInfo
- deferredToolInfos []*schema.ToolInfo
- toolSearchTool *schema.ToolInfo
+ instruction string
+ returnDirectly map[string]bool
+ toolInfos []*schema.ToolInfo // from config.Tools + contributor ToolInfos
+ deferredToolInfos []*schema.ToolInfo
+ toolSearchTool *schema.ToolInfo
emitInternalEvents bool
+
+ // ToolContributor results (collected once in once.Do).
+ contribTools []Tool
+ contribToolInfos []*schema.ToolInfo
+ contribReturnDirectly map[string]bool
}
// ---- Run function builder ----
@@ -204,9 +225,16 @@ func (a *ReActAgent[M]) buildRunFunc(ctx context.Context) typedRunFunc[M] {
var onceRun typedRunFunc[M]
a.once.Do(func() {
ec, err := a.prepareExecContext(ctx)
- if err != nil { onceRun = func(_ context.Context, _ *typedRunParams[M]) {}; a.run = onceRun; return }
+ if err != nil {
+ onceRun = func(_ context.Context, _ *typedRunParams[M]) {}
+ a.run = onceRun
+ return
+ }
a.exeCtx = ec
- hasTools := len(a.config.Tools) > 0 || (a.config.ToolsConfig != nil && len(a.config.ToolsConfig.Tools) > 0)
+ // Check for tools: config.Tools + ToolContributor tools
+ hasTools := len(a.config.Tools) > 0 ||
+ (a.config.ToolsConfig != nil && len(a.config.ToolsConfig.Tools) > 0) ||
+ len(ec.contribTools) > 0
if !hasTools {
onceRun = a.buildNoToolsRunFunc()
} else if a.config.GraphReAct {
@@ -219,45 +247,104 @@ func (a *ReActAgent[M]) buildRunFunc(ctx context.Context) typedRunFunc[M] {
return a.run
}
-func (a *ReActAgent[M]) prepareExecContext(_ context.Context) (*execContext, error) {
+func (a *ReActAgent[M]) prepareExecContext(ctx context.Context) (*execContext, error) {
instruction := a.config.Instruction
- if instruction == "" { instruction = internal.DefaultSystemPrompt }
+ if instruction == "" {
+ instruction = internal.DefaultSystemPrompt
+ }
rd := a.config.ReturnDirectly
- if rd == nil { rd = make(map[string]bool) }
- return &execContext{instruction: instruction, returnDirectly: rd, toolInfos: toolsToInfosTyped[M](a.config.Tools), emitInternalEvents: a.config.EmitInternalEvents}, nil
+ if rd == nil {
+ rd = make(map[string]bool)
+ }
+
+ // Collect from ToolContributor middlewares.
+ contribTools := collectContributorTools(ctx, a.config.Middlewares)
+ contribInfos := collectContributorToolInfos(ctx, a.config.Middlewares)
+ contribRD := collectContributorReturnDirectly(ctx, a.config.Middlewares)
+
+ // Merge return-directly.
+ mergedRD := make(map[string]bool, len(rd)+len(contribRD))
+ for k, v := range rd {
+ mergedRD[k] = v
+ }
+ for k, v := range contribRD {
+ mergedRD[k] = v
+ }
+
+ // Merge tool infos from a single source to avoid duplicates:
+ // when ToolsConfig is nil, NewReActAgent populates ToolsConfig.Tools with a.config.Tools,
+ // so building from both sources would produce duplicate entries.
+ var baseInfos []*schema.ToolInfo
+ if a.config.ToolsConfig != nil && len(a.config.ToolsConfig.Tools) > 0 {
+ baseInfos = toolsToInfosTyped[M](a.config.ToolsConfig.Tools)
+ } else {
+ baseInfos = toolsToInfosTyped[M](a.config.Tools)
+ }
+ allInfos := make([]*schema.ToolInfo, 0, len(baseInfos)+len(contribInfos))
+ allInfos = append(allInfos, baseInfos...)
+ allInfos = append(allInfos, contribInfos...)
+
+ return &execContext{
+ instruction: instruction,
+ returnDirectly: mergedRD,
+ toolInfos: allInfos,
+ contribTools: contribTools,
+ contribToolInfos: contribInfos,
+ contribReturnDirectly: contribRD,
+ emitInternalEvents: a.config.EmitInternalEvents,
+ }, nil
}
// ---- No-tools run function ----
func (a *ReActAgent[M]) buildNoToolsRunFunc() typedRunFunc[M] {
return func(ctx context.Context, p *typedRunParams[M]) {
+ // Build allTools: config.Tools + contribTools
+ allTools := make([]Tool, 0, len(a.config.Tools)+len(a.exeCtx.contribTools))
+ allTools = append(allTools, a.config.Tools...)
+ allTools = append(allTools, a.exeCtx.contribTools...)
+
// BeforeAgent middleware
- rc := &ReActAgentContext{Instruction: a.exeCtx.instruction, Tools: a.config.Tools, ReturnDirectly: a.exeCtx.returnDirectly}
- if err := a.runBeforeAgent(&ctx, rc, p.generator); err != nil { return }
+ rc := &ReActAgentContext{Instruction: a.exeCtx.instruction, Tools: allTools, ReturnDirectly: a.exeCtx.returnDirectly}
+ if err := a.runBeforeAgent(&ctx, rc, p.generator); err != nil {
+ return
+ }
- model := BuildModelWrapperChain(a.config.Model, nil, a.config)
+ model := BuildModelWrapperChain(a.config.Model, nil, a.config, a.exeCtx.toolInfos)
state := NewReActAgentState(p.input.Messages, a.exeCtx.toolInfos, a.config.MaxIterations)
// BeforeModelRewrite middleware
mc := &TypedModelContext[M]{Tools: state.ToolInfos, ModelRetryConfig: a.config.RetryConfig, ModelFailoverConfig: a.config.FailoverConfig}
- if err := a.runBeforeModelRewrite(&ctx, &state, mc, p.generator); err != nil { return }
+ if err := a.runBeforeModelRewrite(&ctx, &state, mc, p.generator); err != nil {
+ return
+ }
if a.config.StateModifier != nil {
var err error
state, err = a.config.StateModifier(ctx, state)
- if err != nil { p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("StateModifier: %w", err)}); return }
+ if err != nil {
+ p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("StateModifier: %w", err)})
+ return
+ }
}
modelMsgs := buildModelInputFromState[M](state.Messages, rc.Instruction)
resp, err := model.Generate(ctx, modelMsgs)
- if err != nil { p.generator.Send(&TypedAgentEvent[M]{Err: err}); return }
+ if err != nil {
+ p.generator.Send(&TypedAgentEvent[M]{Err: err})
+ return
+ }
p.generator.Send(typedModelOutputEvent(resp, nil))
state.Messages = append(state.Messages, resp)
// AfterModelRewrite middleware
- if err := a.runAfterModelRewrite(&ctx, &state, mc, p.generator); err != nil { return }
+ if err := a.runAfterModelRewrite(&ctx, &state, mc, p.generator); err != nil {
+ return
+ }
- if a.config.OutputKey != "" && !isNilMessage(resp) { setOutputToSession(ctx, resp, a.config.OutputKey) }
+ if a.config.OutputKey != "" && !isNilMessage(resp) {
+ setOutputToSession(ctx, resp, a.config.OutputKey)
+ }
// AfterAgent middleware
a.runAfterAgent(&ctx, state, p.generator)
@@ -268,7 +355,9 @@ func (a *ReActAgent[M]) buildNoToolsRunFunc() typedRunFunc[M] {
// Returns a non-nil error if any middleware signals termination.
func (a *ReActAgent[M]) runBeforeAgent(ctx *context.Context, rc *ReActAgentContext, gen *AsyncGenerator[*TypedAgentEvent[M]]) error {
for _, mw := range a.config.Middlewares {
- if mw == nil { continue }
+ if mw == nil {
+ continue
+ }
var err error
*ctx, rc, err = mw.BeforeAgent(*ctx, rc)
if err != nil {
@@ -282,7 +371,9 @@ func (a *ReActAgent[M]) runBeforeAgent(ctx *context.Context, rc *ReActAgentConte
// runBeforeModelRewrite executes the BeforeModelRewrite middleware chain.
func (a *ReActAgent[M]) runBeforeModelRewrite(ctx *context.Context, state **TypedReActAgentState[M], mc *TypedModelContext[M], gen *AsyncGenerator[*TypedAgentEvent[M]]) error {
for _, mw := range a.config.Middlewares {
- if mw == nil { continue }
+ if mw == nil {
+ continue
+ }
var err error
*ctx, *state, err = mw.BeforeModelRewrite(*ctx, *state, mc)
if err != nil {
@@ -296,7 +387,9 @@ func (a *ReActAgent[M]) runBeforeModelRewrite(ctx *context.Context, state **Type
// runAfterModelRewrite executes the AfterModelRewrite middleware chain.
func (a *ReActAgent[M]) runAfterModelRewrite(ctx *context.Context, state **TypedReActAgentState[M], mc *TypedModelContext[M], gen *AsyncGenerator[*TypedAgentEvent[M]]) error {
for _, mw := range a.config.Middlewares {
- if mw == nil { continue }
+ if mw == nil {
+ continue
+ }
var err error
*ctx, *state, err = mw.AfterModelRewrite(*ctx, *state, mc)
if err != nil {
@@ -310,7 +403,9 @@ func (a *ReActAgent[M]) runAfterModelRewrite(ctx *context.Context, state **Typed
// runAfterAgent executes the AfterAgent middleware chain.
func (a *ReActAgent[M]) runAfterAgent(ctx *context.Context, state *TypedReActAgentState[M], gen *AsyncGenerator[*TypedAgentEvent[M]]) {
for _, mw := range a.config.Middlewares {
- if mw == nil { continue }
+ if mw == nil {
+ continue
+ }
var err error
*ctx, err = mw.AfterAgent(*ctx, state)
if err != nil {
@@ -324,15 +419,21 @@ func (a *ReActAgent[M]) runAfterAgent(ctx *context.Context, state *TypedReActAge
func buildModelInputFromState[M MessageType](messages []M, instruction string) []M {
var msgs []M
- if instruction != "" { msgs = append(msgs, any(schema.SystemMessage(instruction)).(M)) }
- for _, m := range messages { msgs = append(msgs, m) }
+ if instruction != "" {
+ msgs = append(msgs, any(schema.SystemMessage(instruction)).(M))
+ }
+ for _, m := range messages {
+ msgs = append(msgs, m)
+ }
return msgs
}
func setOutputToSession[M MessageType](ctx context.Context, msg M, key string) {
if !isNilMessage(msg) {
s := getSession(ctx)
- if s != nil { s.Values[key] = extractTextContent(msg) }
+ if s != nil {
+ s.Values[key] = extractTextContent(msg)
+ }
}
}
@@ -350,19 +451,27 @@ func toolsToInfosTyped[M MessageType](tools []Tool) []*schema.ToolInfo {
func extractTextContent[M MessageType](msg M) string {
switch v := any(msg).(type) {
- case *schema.Message: return v.Content
+ case *schema.Message:
+ return v.Content
case *schema.AgenticMessage:
var texts []string
- for _, b := range v.ContentBlocks { if b.Type == "text" { texts = append(texts, b.Text) } }
+ for _, b := range v.ContentBlocks {
+ if b.Type == "text" {
+ texts = append(texts, b.Text)
+ }
+ }
return strings.Join(texts, "\n")
- default: return ""
+ default:
+ return ""
}
}
// findTool finds a tool by name from a list of tools.
func findTool(tools []Tool, name string) Tool {
for _, t := range tools {
- if t.Name() == name { return t }
+ if t.Name() == name {
+ return t
+ }
}
return nil
}
@@ -372,13 +481,15 @@ func findTool(tools []Tool, name string) Tool {
func extractToolCalls[M MessageType](resp M) []schema.ToolCall {
switch v := any(resp).(type) {
case *schema.Message:
- if len(v.ToolCalls) > 0 { return v.ToolCalls }
+ if len(v.ToolCalls) > 0 {
+ return v.ToolCalls
+ }
case *schema.AgenticMessage:
var tc []schema.ToolCall
for _, b := range v.ContentBlocks {
if b.Type == "tool_use" && b.ToolCall != nil && b.ToolCall.ID != "" && b.ToolCall.Name != "" {
tc = append(tc, schema.ToolCall{
- ID: b.ToolCall.ID,
+ ID: b.ToolCall.ID,
Function: schema.ToolCallFunction{Name: b.ToolCall.Name, Arguments: b.ToolCall.Arguments},
})
}
@@ -390,7 +501,9 @@ func extractToolCalls[M MessageType](resp M) []schema.ToolCall {
// streamWithCancel wraps a streaming model call with cancel detection.
func streamWithCancel[M MessageType](s *schema.StreamReader[M], cc *cancelContext) *schema.StreamReader[M] {
- if cc == nil { return s }
+ if cc == nil {
+ return s
+ }
select {
case <-cc.immediateChan:
s.Close()
@@ -405,7 +518,10 @@ func streamWithCancel[M MessageType](s *schema.StreamReader[M], cc *cancelContex
go func() {
defer r.Close()
defer s.Close()
- ch := make(chan struct{ Data M; Err error }, 64)
+ ch := make(chan struct {
+ Data M
+ Err error
+ }, 64)
go func() {
defer close(ch)
for {
@@ -421,7 +537,10 @@ func streamWithCancel[M MessageType](s *schema.StreamReader[M], cc *cancelContex
default:
}
select {
- case ch <- struct{ Data M; Err error }{d, e}:
+ case ch <- struct {
+ Data M
+ Err error
+ }{d, e}:
case <-cc.immediateChan:
return
}
@@ -450,9 +569,13 @@ func streamWithCancel[M MessageType](s *schema.StreamReader[M], cc *cancelContex
// getChatModelExecCtx retrieves the chat model execution context from context.
func getChatModelExecCtx(ctx context.Context) *reActExecCtx {
rc := getRunCtx(ctx)
- if rc == nil { return nil }
+ if rc == nil {
+ return nil
+ }
// The exec ctx is stored on the run session or passed via context value
- if ec, ok := rc.Session.Values["__exec_ctx"].(*reActExecCtx); ok { return ec }
+ if ec, ok := rc.Session.Values["__exec_ctx"].(*reActExecCtx); ok {
+ return ec
+ }
return nil
}
@@ -524,7 +647,7 @@ func (a *ReActAgent[M]) buildGraphReActRunFunc() typedRunFunc[M] {
return
}
- rg, err := NewReActGraph(msgAgent, graphCfg)
+ rg, err := NewReActGraph(msgAgent, graphCfg, a.exeCtx.toolInfos)
if err != nil {
p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("NewReActGraph: %w", err)})
return
diff --git a/internal/harness/core/react_graph.go b/internal/harness/core/react_graph.go
index 4d48657526..d5cef00f18 100644
--- a/internal/harness/core/react_graph.go
+++ b/internal/harness/core/react_graph.go
@@ -59,6 +59,8 @@ type ReActGraph struct {
compiled *graph.CompiledGraph
config *ReActConfig[*schema.Message]
agent *ReActAgent[*schema.Message]
+ allInfos []*schema.ToolInfo // merged config + contributor tool infos
+ allTools []Tool // merged config + contributor tools
}
// ReActGraphConfig holds options for building a ReActGraph.
@@ -80,11 +82,19 @@ type ReActGraphConfig struct {
// - prepare_input: BeforeAgent
// - model_generate: BeforeModelRewrite → model call → AfterModelRewrite
// - check_done (on exit): AfterAgent
-func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*ReActGraph, error) {
+func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig, allToolInfos []*schema.ToolInfo) (*ReActGraph, error) {
if cfg == nil {
cfg = &ReActGraphConfig{}
}
agentCfg := agent.config
+ // Fallback: when allToolInfos is nil, derive from the agent's tools
+ // so model wrappers always have tool metadata.
+ if allToolInfos == nil {
+ allToolInfos = toolsToInfosTyped[*schema.Message](agentCfg.Tools)
+ if agentCfg.ToolsConfig != nil {
+ allToolInfos = append(allToolInfos, toolsToInfosTyped[*schema.Message](agentCfg.ToolsConfig.Tools)...)
+ }
+ }
sg := graph.NewStateGraph(&ReActGraphState{})
// Register channels for state fields used by the graph engine.
@@ -95,12 +105,26 @@ func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*
// --- Node: prepare_input ---
// Runs once at the start. Applies BeforeAgent middleware.
+ // Build allTools and allRD from config + contributor tools.
+ allTools := make([]Tool, 0, len(agent.config.Tools))
+ allTools = append(allTools, agent.config.Tools...)
+ allRD := make(map[string]bool)
+ for k, v := range agent.config.ReturnDirectly {
+ allRD[k] = v
+ }
+ if ec := agent.exeCtx; ec != nil {
+ allTools = append(allTools, ec.contribTools...)
+ for k, v := range ec.contribReturnDirectly {
+ allRD[k] = v
+ }
+ }
+
sg.AddNode("prepare_input", func(ctx context.Context, state interface{}) (interface{}, error) {
s := state.(*ReActGraphState)
rc := &ReActAgentContext{
Instruction: s.Instruction,
- Tools: agentCfg.Tools,
- ReturnDirectly: agentCfg.ReturnDirectly,
+ Tools: allTools,
+ ReturnDirectly: allRD,
}
for _, mw := range agentCfg.Middlewares {
if mw == nil {
@@ -129,16 +153,16 @@ func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*
// Clear tool cache at start of each iteration.
s.ToolExecutedCache = nil
- model := BuildModelWrapperChain(agentCfg.Model, nil, agentCfg)
+ model := BuildModelWrapperChain(agentCfg.Model, nil, agentCfg, allToolInfos)
agentState := NewReActAgentState(
messageSliceToAny(s.Messages),
- s.ToolInfos,
+ allToolInfos,
s.IterationsLeft+1,
)
typedState := (*TypedReActAgentState[*schema.Message])(agentState)
mc := &TypedModelContext[*schema.Message]{
- Tools: s.ToolInfos,
+ Tools: allToolInfos,
ModelRetryConfig: agentCfg.RetryConfig,
ModelFailoverConfig: agentCfg.FailoverConfig,
}
@@ -247,7 +271,15 @@ func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*
)
typedState := (*TypedReActAgentState[*schema.Message])(agentState)
- tn := NewToolsNode[*schema.Message](agentCfg.ToolsConfig)
+ // Build ToolsNode from config ToolsConfig (for ToolInvokeMiddlewares etc.)
+ // but overlay allTools (config + contributor).
+ tnCfg := &ToolsNodeConfig{}
+ if agentCfg.ToolsConfig != nil {
+ *tnCfg = *agentCfg.ToolsConfig
+ }
+ tnCfg.Tools = allTools
+ tnCfg.ReturnDirectly = allRD
+ tn := NewToolsNode[*schema.Message](tnCfg)
// Execute pending calls one at a time so we can track per-call results.
// Each call uses a single-tool-call message to keep tracking simple.
@@ -256,8 +288,8 @@ func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*
for _, tc := range pendingCalls {
// Build a fresh message containing only this tool call.
singleMsg := &schema.Message{
- Role: schema.RoleAssistant,
- Content: "",
+ Role: schema.RoleAssistant,
+ Content: "",
ToolCalls: []schema.ToolCall{tc},
}
var action *AgentAction
@@ -388,6 +420,8 @@ func NewReActGraph(agent *ReActAgent[*schema.Message], cfg *ReActGraphConfig) (*
compiled: compiled,
config: agentCfg,
agent: agent,
+ allInfos: allToolInfos,
+ allTools: allTools,
}, nil
}
@@ -455,14 +489,9 @@ func (rg *ReActGraph) buildInitialState(input *AgentInput) *ReActGraphState {
AgentName: rg.agent.name,
Instruction: rg.config.Instruction,
}
- state.ToolInfos = make([]*schema.ToolInfo, len(rg.config.Tools))
- for i, t := range rg.config.Tools {
- if p, ok := t.(ToolInfoProvider); ok {
- state.ToolInfos[i] = p.ToolInfo()
- } else {
- state.ToolInfos[i] = &schema.ToolInfo{Name: t.Name(), Description: t.Description()}
- }
- }
+ // Use merged tool infos (config + contributor).
+ state.ToolInfos = make([]*schema.ToolInfo, len(rg.allInfos))
+ copy(state.ToolInfos, rg.allInfos)
return state
}
diff --git a/internal/harness/core/react_graph_test.go b/internal/harness/core/react_graph_test.go
index fe0c9e6159..451b87b070 100644
--- a/internal/harness/core/react_graph_test.go
+++ b/internal/harness/core/react_graph_test.go
@@ -8,8 +8,8 @@ import (
"ragflow/internal/harness/core/schema"
"ragflow/internal/harness/graph/checkpoint"
- "ragflow/internal/harness/graph/graph"
harnesserrors "ragflow/internal/harness/graph/errors"
+ "ragflow/internal/harness/graph/graph"
"ragflow/internal/harness/graph/types"
)
@@ -28,7 +28,7 @@ func TestReActGraph_CheckpointInterruptResume(t *testing.T) {
tool := &mockTool{name: "approve", desc: "approval"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: model, Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 2,
})
agent.name = "interrupt_agent"
@@ -36,7 +36,7 @@ func TestReActGraph_CheckpointInterruptResume(t *testing.T) {
rg, err := NewReActGraph(agent, &ReActGraphConfig{
Checkpointer: checkpoint.NewMemorySaver(),
RecursionLimit: 20,
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -58,7 +58,7 @@ func TestReActGraph_CheckpointInterruptResume(t *testing.T) {
// TestReActGraph_StreamWithInterrupt verifies streaming events include checkpoints.
func TestReActGraph_StreamWithInterrupt(t *testing.T) {
model := &forcedToolModel{
- inner: &mockModel{},
+ inner: &mockModel{},
toolCalls: []schema.ToolCall{{ID: "s1",
Function: schema.ToolCallFunction{Name: "tool_s", Arguments: "{}"},
}},
@@ -68,7 +68,7 @@ func TestReActGraph_StreamWithInterrupt(t *testing.T) {
tool := &mockTool{name: "tool_s", desc: "stream test"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: model, Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 2,
})
agent.name = "stream_agent"
@@ -77,7 +77,7 @@ func TestReActGraph_StreamWithInterrupt(t *testing.T) {
Checkpointer: checkpoint.NewMemorySaver(),
InterruptBefore: []string{},
RecursionLimit: 20,
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -103,10 +103,10 @@ func TestReActGraph_StreamWithInterrupt(t *testing.T) {
// TestReActGraph_FullCheckpointInterruptResume verifies the COMPLETE lifecycle:
//
-// 1. Build graph with checkpoint + interrupt
-// 2. Invoke → reaches tool call → pauses at execute_tools (interrupt)
-// 3. Resume from checkpoint → executes tool → completes
-// 4. Verify final state is correct
+// 1. Build graph with checkpoint + interrupt
+// 2. Invoke → reaches tool call → pauses at execute_tools (interrupt)
+// 3. Resume from checkpoint → executes tool → completes
+// 4. Verify final state is correct
func TestReActGraph_FullCheckpointInterruptResume(t *testing.T) {
t.Skip("requires Pregel engine — run from harness root: go test ./...")
@@ -124,9 +124,9 @@ func TestReActGraph_FullCheckpointInterruptResume(t *testing.T) {
}
tool := &mockTool{name: "calculator", desc: "math tool"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: model,
- Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ Model: model,
+ Tools: []Tool{tool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 3,
})
agent.name = "full_cycle_agent"
@@ -136,7 +136,7 @@ func TestReActGraph_FullCheckpointInterruptResume(t *testing.T) {
Checkpointer: saver,
RecursionLimit: 20,
InterruptBefore: []string{"execute_tools"}, // pause before tool execution
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -191,9 +191,9 @@ func TestReActGraph_SerialCheckpointCycles(t *testing.T) {
tool2 := &mockTool{name: "step2", desc: "second step"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: model,
- Tools: []Tool{tool1, tool2},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool1, tool2}},
+ Model: model,
+ Tools: []Tool{tool1, tool2},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool1, tool2}},
MaxIterations: 5,
})
agent.name = "serial_cycle"
@@ -202,7 +202,7 @@ func TestReActGraph_SerialCheckpointCycles(t *testing.T) {
rg, err := NewReActGraph(agent, &ReActGraphConfig{
Checkpointer: saver,
RecursionLimit: 30,
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -234,9 +234,9 @@ func TestReActGraph_SerialCheckpointCycles(t *testing.T) {
// checkpoint events at each node boundary.
func TestReActGraph_StreamingCheckpointEvents(t *testing.T) {
model := &forcedToolModel{
- inner: &mockModel{},
+ inner: &mockModel{},
toolCalls: []schema.ToolCall{{
- ID: "stream_cp",
+ ID: "stream_cp",
Function: schema.ToolCallFunction{Name: "stream_tool", Arguments: "{}"},
}},
finalResp: "streaming done",
@@ -244,9 +244,9 @@ func TestReActGraph_StreamingCheckpointEvents(t *testing.T) {
}
tool := &mockTool{name: "stream_tool", desc: "stream test"}
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: model,
- Tools: []Tool{tool},
- ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
+ Model: model,
+ Tools: []Tool{tool},
+ ToolsConfig: &ToolsNodeConfig{Tools: []Tool{tool}},
MaxIterations: 2,
})
agent.name = "stream_cp_agent"
@@ -256,7 +256,7 @@ func TestReActGraph_StreamingCheckpointEvents(t *testing.T) {
Checkpointer: saver,
InterruptBefore: []string{},
RecursionLimit: 20,
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -298,7 +298,7 @@ func TestReActGraph_ConcurrentCheckpoints(t *testing.T) {
m := &mockModel{}
m.addResp("concurrent result")
agent := NewReActAgent(&ReActConfig[*schema.Message]{
- Model: m,
+ Model: m,
MaxIterations: 1,
}).WithName("concurrent_cp_agent")
@@ -306,7 +306,7 @@ func TestReActGraph_ConcurrentCheckpoints(t *testing.T) {
Checkpointer: checkpoint.NewMemorySaver(),
InterruptBefore: []string{},
RecursionLimit: 10,
- })
+ }, nil)
if err != nil {
errs <- err
return
diff --git a/internal/harness/core/react_loop.go b/internal/harness/core/react_loop.go
index d0087b7dc2..e528fbe805 100644
--- a/internal/harness/core/react_loop.go
+++ b/internal/harness/core/react_loop.go
@@ -12,16 +12,23 @@ import (
func (a *ReActAgent[M]) buildReActRunFunc() typedRunFunc[M] {
return func(ctx context.Context, p *typedRunParams[M]) {
maxIter := a.config.MaxIterations
- if maxIter <= 0 { maxIter = 10 }
+ if maxIter <= 0 {
+ maxIter = 10
+ }
var state *TypedReActAgentState[M]
- if p.interruptState != nil { state = p.interruptState
- } else { state = NewReActAgentState(p.input.Messages, a.exeCtx.toolInfos, maxIter) }
+ if p.interruptState != nil {
+ state = p.interruptState
+ } else {
+ state = NewReActAgentState(p.input.Messages, a.exeCtx.toolInfos, maxIter)
+ }
// Deep copy input messages to prevent middleware side-effects
if len(state.Messages) > 0 {
copied := make([]M, len(state.Messages))
- for i, m := range state.Messages { copied[i] = copyMessage(m) }
+ for i, m := range state.Messages {
+ copied[i] = copyMessage(m)
+ }
state.Messages = copied
}
@@ -29,39 +36,92 @@ func (a *ReActAgent[M]) buildReActRunFunc() typedRunFunc[M] {
if p.historyModifier != nil && len(state.Messages) > 0 {
switch any(state.Messages[0]).(type) {
case *schema.Message:
- msgs := make([]Message, len(state.Messages))
- for i, m := range state.Messages { msgs[i] = any(m).(Message) }
+ // Collect only successfully asserted messages to avoid zero-value holes.
+ var msgs []Message
+ for _, m := range state.Messages {
+ if msg, ok := any(m).(Message); ok {
+ msgs = append(msgs, msg)
+ }
+ }
modified := p.historyModifier(ctx, msgs)
- state.Messages = make([]M, len(modified))
- for i, m := range modified { state.Messages[i] = any(m).(M) }
+ var stateMsgs []M
+ for _, m := range modified {
+ if msg, ok := any(m).(M); ok {
+ stateMsgs = append(stateMsgs, msg)
+ }
+ }
+ state.Messages = stateMsgs
}
}
+ // Build allTools: config.Tools + ToolsConfig.Tools + contribTools
+ tcTools := 0
+ if a.config.ToolsConfig != nil {
+ tcTools = len(a.config.ToolsConfig.Tools)
+ }
+ allTools := make([]Tool, 0, len(a.config.Tools)+tcTools+len(a.exeCtx.contribTools))
+ allTools = append(allTools, a.config.Tools...)
+ if a.config.ToolsConfig != nil {
+ allTools = append(allTools, a.config.ToolsConfig.Tools...)
+ }
+ allTools = append(allTools, a.exeCtx.contribTools...)
+
+ // Build merged return-directly
+ allRD := make(map[string]bool, len(a.exeCtx.returnDirectly)+len(a.exeCtx.contribReturnDirectly))
+ for k, v := range a.exeCtx.returnDirectly {
+ allRD[k] = v
+ }
+ for k, v := range a.exeCtx.contribReturnDirectly {
+ allRD[k] = v
+ }
+
// BeforeAgent middlewares
- rc := &ReActAgentContext{Instruction: a.exeCtx.instruction, Tools: a.config.Tools, ReturnDirectly: a.exeCtx.returnDirectly, ToolSearchTool: a.exeCtx.toolSearchTool}
- if err := a.runBeforeAgent(&ctx, rc, p.generator); err != nil { return }
+ rc := &ReActAgentContext{Instruction: a.exeCtx.instruction, Tools: allTools, ReturnDirectly: allRD, ToolSearchTool: a.exeCtx.toolSearchTool}
+ if err := a.runBeforeAgent(&ctx, rc, p.generator); err != nil {
+ return
+ }
+ // Capture runtime tool/return-directly mutations made by BeforeAgent middleware.
+ allTools = rc.Tools
+ allRD = rc.ReturnDirectly
- model := BuildModelWrapperChain(a.config.Model, nil, a.config)
+ model := BuildModelWrapperChain(a.config.Model, nil, a.config, a.exeCtx.toolInfos)
+ // Build ToolsNode from merged tools, preserving ToolInvokeMiddlewares from config.
var tn *ToolsNode[M]
- if a.config.ToolsConfig != nil {
- tn = NewToolsNode[M](a.config.ToolsConfig)
- } else if len(a.config.Tools) > 0 {
- // Auto-create ToolsNode from Tools list if ToolsConfig not set.
- tn = NewToolsNode[M](&ToolsNodeConfig{Tools: a.config.Tools})
+ if len(allTools) > 0 {
+ tnCfg := &ToolsNodeConfig{
+ Tools: allTools,
+ ReturnDirectly: allRD,
+ LoopGuard: nil,
+ ArgumentsAliases: nil,
+ }
+ if a.config.ToolsConfig != nil {
+ tnCfg.ToolInvokeMiddlewares = a.config.ToolsConfig.ToolInvokeMiddlewares
+ tnCfg.Registry = a.config.ToolsConfig.Registry
+ tnCfg.EmitInternalEvents = a.config.ToolsConfig.EmitInternalEvents
+ tnCfg.LoopGuard = a.config.ToolsConfig.LoopGuard
+ tnCfg.UnknownToolHandler = a.config.ToolsConfig.UnknownToolHandler
+ tnCfg.ArgumentsAliases = a.config.ToolsConfig.ArgumentsAliases
+ }
+ tn = NewToolsNode[M](tnCfg)
}
for state.RemainingIterations > 0 {
state.RemainingIterations--
mc := &TypedModelContext[M]{Tools: state.ToolInfos, DeferredToolInfos: state.DeferredToolInfos, ModelRetryConfig: a.config.RetryConfig, ModelFailoverConfig: a.config.FailoverConfig}
- if err := a.runBeforeModelRewrite(&ctx, &state, mc, p.generator); err != nil { return }
+ if err := a.runBeforeModelRewrite(&ctx, &state, mc, p.generator); err != nil {
+ return
+ }
var modelMsgs []M
if a.config.StateModifier != nil {
var err error
state, err = a.config.StateModifier(ctx, state)
- if err != nil { p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("StateModifier: %w", err)}); return }
+ if err != nil {
+ p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("StateModifier: %w", err)})
+ return
+ }
}
if a.config.GenModelInput != nil {
@@ -71,24 +131,40 @@ func (a *ReActAgent[M]) buildReActRunFunc() typedRunFunc[M] {
p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("GenModelInput: %w", err)})
return
}
- } else { modelMsgs = buildModelInputFromState(state.Messages, rc.Instruction) }
+ } else {
+ modelMsgs = buildModelInputFromState(state.Messages, rc.Instruction)
+ }
resp, err := model.Generate(ctx, modelMsgs)
- if err != nil { p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("model: %w", err)}); return }
+ if err != nil {
+ p.generator.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("model: %w", err)})
+ return
+ }
p.generator.Send(typedModelOutputEvent(resp, nil))
state.Messages = append(state.Messages, resp)
- if err := a.runAfterModelRewrite(&ctx, &state, mc, p.generator); err != nil { return }
+ if err := a.runAfterModelRewrite(&ctx, &state, mc, p.generator); err != nil {
+ return
+ }
toolCalls := extractToolCalls(resp)
- if len(toolCalls) == 0 || tn == nil { break }
+ if len(toolCalls) == 0 || tn == nil {
+ break
+ }
var action *AgentAction
results, act, err := tn.Execute(ctx, resp, state, nil)
- if err != nil { p.generator.Send(&TypedAgentEvent[M]{Err: err}); return }
- for _, tr := range results { state.Messages = append(state.Messages, tr) }
+ if err != nil {
+ p.generator.Send(&TypedAgentEvent[M]{Err: err})
+ return
+ }
+ for _, tr := range results {
+ state.Messages = append(state.Messages, tr)
+ }
action = act
- if action != nil && action.Exit { break }
+ if action != nil && action.Exit {
+ break
+ }
}
if state.RemainingIterations <= 0 {
diff --git a/internal/harness/core/react_retry_test.go b/internal/harness/core/react_retry_test.go
index 9aca9bd59b..c0037f1e1b 100644
--- a/internal/harness/core/react_retry_test.go
+++ b/internal/harness/core/react_retry_test.go
@@ -397,7 +397,15 @@ func TestRetry_SequentialWorkflow_NonRetryableError_StopsFlow(t *testing.T) {
ctx := context.Background()
iter := wf.Run(ctx, &AgentInput{Messages: []Message{schema.UserMessage("run")}})
var lastErr error
- for { ev, ok := iter.Next(); if !ok { break }; if ev.Err != nil { lastErr = ev.Err } }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ lastErr = ev.Err
+ }
+ }
if lastErr == nil {
t.Log("workflow completed")
} else {
diff --git a/internal/harness/core/retry.go b/internal/harness/core/retry.go
index e4f587d9c6..90adaeddfa 100644
--- a/internal/harness/core/retry.go
+++ b/internal/harness/core/retry.go
@@ -38,8 +38,8 @@ type WillRetryError struct {
err error
}
-func (e *WillRetryError) Error() string { return e.ErrStr }
-func (e *WillRetryError) Unwrap() error { return e.err }
+func (e *WillRetryError) Error() string { return e.ErrStr }
+func (e *WillRetryError) Unwrap() error { return e.err }
func (e *WillRetryError) RejectReason() any { return e.rejectReason }
func init() {
@@ -110,19 +110,31 @@ func (r *typedRetryModelWrapper[M]) Generate(ctx context.Context, input []M, opt
func (r *typedRetryModelWrapper[M]) generateLegacy(ctx context.Context, input []M, opts ...ModelOption) (zero M, _ error) {
isRetryAble := r.config.IsRetryAble
- if isRetryAble == nil { isRetryAble = defaultIsRetryAble }
+ if isRetryAble == nil {
+ isRetryAble = defaultIsRetryAble
+ }
backoff := r.config.BackoffFunc
- if backoff == nil { backoff = defaultBackoff }
+ if backoff == nil {
+ backoff = defaultBackoff
+ }
var lastErr error
for attempt := 0; attempt <= r.config.MaxRetries; attempt++ {
out, err := r.inner.Generate(ctx, input, opts...)
- if err == nil { return out, nil }
- if errors.Is(err, ErrStreamCanceled) { return zero, err }
- if !isRetryAble(ctx, err) { return zero, err }
+ if err == nil {
+ return out, nil
+ }
+ if errors.Is(err, ErrStreamCanceled) {
+ return zero, err
+ }
+ if !isRetryAble(ctx, err) {
+ return zero, err
+ }
lastErr = err
if attempt < r.config.MaxRetries {
- if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil { return zero, err }
+ if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil {
+ return zero, err
+ }
}
}
return zero, &RetryExhaustedError{LastErr: lastErr, TotalRetries: r.config.MaxRetries}
@@ -130,7 +142,9 @@ func (r *typedRetryModelWrapper[M]) generateLegacy(ctx context.Context, input []
func (r *typedRetryModelWrapper[M]) generateWithShouldRetry(ctx context.Context, input []M, opts ...ModelOption) (M, error) {
backoff := r.config.BackoffFunc
- if backoff == nil { backoff = defaultBackoff }
+ if backoff == nil {
+ backoff = defaultBackoff
+ }
execCtx := getReActExecCtx[M](ctx)
currentInput := input
currentOpts := opts
@@ -138,22 +152,34 @@ func (r *typedRetryModelWrapper[M]) generateWithShouldRetry(ctx context.Context,
var zero M
for attempt := 0; attempt <= r.config.MaxRetries; attempt++ {
- if execCtx != nil { execCtx.suppressEventSend = true }
+ if execCtx != nil {
+ execCtx.suppressEventSend = true
+ }
out, err := r.inner.Generate(ctx, currentInput, currentOpts...)
- if execCtx != nil { execCtx.suppressEventSend = false }
+ if execCtx != nil {
+ execCtx.suppressEventSend = false
+ }
- if errors.Is(err, ErrStreamCanceled) { return zero, err }
+ if errors.Is(err, ErrStreamCanceled) {
+ return zero, err
+ }
retryCtx := &TypedRetryContext[M]{
RetryAttempt: attempt + 1, InputMessages: currentInput,
OutputMessage: out, Err: err,
}
decision := r.config.ShouldRetry(ctx, retryCtx)
- if decision == nil { decision = &TypedRetryDecision[M]{} }
+ if decision == nil {
+ decision = &TypedRetryDecision[M]{}
+ }
if !decision.Retry {
- if decision.RewriteError != nil { return zero, decision.RewriteError }
- if err != nil { return zero, err }
+ if decision.RewriteError != nil {
+ return zero, decision.RewriteError
+ }
+ if err != nil {
+ return zero, err
+ }
if execCtx != nil && execCtx.generator != nil && !isNilMessage(out) {
execCtx.send(typedModelOutputEvent(out, nil))
}
@@ -161,8 +187,12 @@ func (r *typedRetryModelWrapper[M]) generateWithShouldRetry(ctx context.Context,
}
lastErr = err
- if lastErr == nil { lastErr = fmt.Errorf("model output rejected by ShouldRetry at attempt %d", attempt+1) }
- if attempt >= r.config.MaxRetries { break }
+ if lastErr == nil {
+ lastErr = fmt.Errorf("model output rejected by ShouldRetry at attempt %d", attempt+1)
+ }
+ if attempt >= r.config.MaxRetries {
+ break
+ }
// Emit WillRetryError event before sleeping
if execCtx != nil && execCtx.generator != nil {
@@ -171,8 +201,12 @@ func (r *typedRetryModelWrapper[M]) generateWithShouldRetry(ctx context.Context,
}
applyRetryDecision(&currentInput, &currentOpts, decision)
delay := decision.Backoff
- if delay == 0 { delay = backoff(ctx, attempt+1) }
- if err := contextAwareSleep(ctx, delay); err != nil { return zero, err }
+ if delay == 0 {
+ delay = backoff(ctx, attempt+1)
+ }
+ if err := contextAwareSleep(ctx, delay); err != nil {
+ return zero, err
+ }
}
return zero, &RetryExhaustedError{LastErr: lastErr, TotalRetries: r.config.MaxRetries}
}
@@ -186,32 +220,47 @@ func (r *typedRetryModelWrapper[M]) Stream(ctx context.Context, input []M, opts
func (r *typedRetryModelWrapper[M]) streamLegacy(ctx context.Context, input []M, opts ...ModelOption) (*schema.StreamReader[M], error) {
isRetryAble := r.config.IsRetryAble
- if isRetryAble == nil { isRetryAble = defaultIsRetryAble }
+ if isRetryAble == nil {
+ isRetryAble = defaultIsRetryAble
+ }
backoff := r.config.BackoffFunc
- if backoff == nil { backoff = defaultBackoff }
+ if backoff == nil {
+ backoff = defaultBackoff
+ }
var lastErr error
for attempt := 0; attempt <= r.config.MaxRetries; attempt++ {
stream, err := r.inner.Stream(ctx, input, opts...)
if err != nil {
- if errors.Is(err, ErrStreamCanceled) { return nil, err }
- if !isRetryAble(ctx, err) { return nil, err }
+ if errors.Is(err, ErrStreamCanceled) {
+ return nil, err
+ }
+ if !isRetryAble(ctx, err) {
+ return nil, err
+ }
lastErr = err
if attempt < r.config.MaxRetries {
- if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil { return nil, err }
+ if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil {
+ return nil, err
+ }
}
continue
}
// Verify the stream is healthy by reading one chunk
chunk, streamErr := stream.Recv()
if streamErr == nil {
- outStream := schema.NewStreamReader[M]()
+ outStream := schema.NewStreamReader[M]()
go func() {
outStream.Send(chunk, nil)
for {
c, e := stream.Recv()
- if e == io.EOF { break }
- if e != nil { outStream.Send(c, e); return }
+ if e == io.EOF {
+ break
+ }
+ if e != nil {
+ outStream.Send(c, e)
+ return
+ }
select {
case <-ctx.Done():
outStream.Send(c, ctx.Err())
@@ -225,11 +274,17 @@ func (r *typedRetryModelWrapper[M]) streamLegacy(ctx context.Context, input []M,
return outStream, nil
}
stream.Close()
- if errors.Is(streamErr, ErrStreamCanceled) { return nil, streamErr }
- if !isRetryAble(ctx, streamErr) { return nil, streamErr }
+ if errors.Is(streamErr, ErrStreamCanceled) {
+ return nil, streamErr
+ }
+ if !isRetryAble(ctx, streamErr) {
+ return nil, streamErr
+ }
lastErr = streamErr
if attempt < r.config.MaxRetries {
- if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil { return nil, err }
+ if err := contextAwareSleep(ctx, backoff(ctx, attempt+1)); err != nil {
+ return nil, err
+ }
}
}
return nil, &RetryExhaustedError{LastErr: lastErr, TotalRetries: r.config.MaxRetries}
@@ -237,7 +292,9 @@ func (r *typedRetryModelWrapper[M]) streamLegacy(ctx context.Context, input []M,
func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, input []M, opts ...ModelOption) (*schema.StreamReader[M], error) {
backoff := r.config.BackoffFunc
- if backoff == nil { backoff = defaultBackoff }
+ if backoff == nil {
+ backoff = defaultBackoff
+ }
execCtx := getReActExecCtx[M](ctx)
currentInput := input
currentOpts := opts
@@ -251,14 +308,20 @@ func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, i
for attempt := 0; attempt <= r.config.MaxRetries; attempt++ {
stream, err := r.inner.Stream(ctx, currentInput, currentOpts...)
if err != nil {
- if errors.Is(err, ErrStreamCanceled) { return nil, err }
+ if errors.Is(err, ErrStreamCanceled) {
+ return nil, err
+ }
retryCtx := &TypedRetryContext[M]{
RetryAttempt: attempt + 1, InputMessages: currentInput, Err: err,
}
decision := r.config.ShouldRetry(ctx, retryCtx)
- if decision == nil { decision = &TypedRetryDecision[M]{} }
+ if decision == nil {
+ decision = &TypedRetryDecision[M]{}
+ }
if !decision.Retry {
- if decision.RewriteError != nil { return nil, decision.RewriteError }
+ if decision.RewriteError != nil {
+ return nil, decision.RewriteError
+ }
return nil, err
}
lastErr = err
@@ -268,8 +331,12 @@ func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, i
}
applyRetryDecision(&currentInput, &currentOpts, decision)
delay := decision.Backoff
- if delay == 0 { delay = backoff(ctx, attempt+1) }
- if err := contextAwareSleep(ctx, delay); err != nil { return nil, err }
+ if delay == 0 {
+ delay = backoff(ctx, attempt+1)
+ }
+ if err := contextAwareSleep(ctx, delay); err != nil {
+ return nil, err
+ }
}
continue
}
@@ -282,21 +349,32 @@ func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, i
RetryAttempt: attempt + 1, InputMessages: currentInput, Err: streamErr,
}
decision := r.config.ShouldRetry(ctx, retryCtx)
- if decision == nil { decision = &TypedRetryDecision[M]{} }
+ if decision == nil {
+ decision = &TypedRetryDecision[M]{}
+ }
if !decision.Retry {
- if decision.RewriteError != nil { return nil, decision.RewriteError }
+ if decision.RewriteError != nil {
+ return nil, decision.RewriteError
+ }
return nil, streamErr
}
lastErr = streamErr
- select { case sig.ch <- streamRetryVerdict{WillRetry: true, Err: streamErr, RejectReason: decision.RejectReason}: default: }
+ select {
+ case sig.ch <- streamRetryVerdict{WillRetry: true, Err: streamErr, RejectReason: decision.RejectReason}:
+ default:
+ }
if attempt < r.config.MaxRetries {
if execCtx != nil && execCtx.generator != nil {
execCtx.send(&TypedAgentEvent[M]{Err: &WillRetryError{ErrStr: lastErr.Error(), RetryAttempt: attempt + 1, rejectReason: decision.RejectReason, err: lastErr}})
}
applyRetryDecision(&currentInput, &currentOpts, decision)
delay := decision.Backoff
- if delay == 0 { delay = backoff(ctx, attempt+1) }
- if err := contextAwareSleep(ctx, delay); err != nil { return nil, err }
+ if delay == 0 {
+ delay = backoff(ctx, attempt+1)
+ }
+ if err := contextAwareSleep(ctx, delay); err != nil {
+ return nil, err
+ }
}
continue
}
@@ -308,11 +386,18 @@ func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, i
}
callerCh := schema.NewStreamReader[M]()
go func() {
- if len(allChunks) > 0 { callerCh.Send(allChunks[0], nil) }
+ if len(allChunks) > 0 {
+ callerCh.Send(allChunks[0], nil)
+ }
for {
c, e := stream.Recv()
- if e == io.EOF { break }
- if e != nil { callerCh.Send(c, e); return }
+ if e == io.EOF {
+ break
+ }
+ if e != nil {
+ callerCh.Send(c, e)
+ return
+ }
allChunks = append(allChunks, c)
callerCh.Send(c, nil)
}
@@ -324,13 +409,18 @@ func (r *typedRetryModelWrapper[M]) streamWithShouldRetry(ctx context.Context, i
}
callerCh.Close()
}()
- select { case sig.ch <- streamRetryVerdict{WillRetry: false}: default: }
+ select {
+ case sig.ch <- streamRetryVerdict{WillRetry: false}:
+ default:
+ }
return callerCh, nil
}
return nil, &RetryExhaustedError{LastErr: lastErr, TotalRetries: r.config.MaxRetries}
}
-func (r *typedRetryModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error { return r.inner.BindTools(tools) }
+func (r *typedRetryModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error {
+ return r.inner.BindTools(tools)
+}
// WithModelRetry wraps a Model with retry logic.
// When cfg.ShouldRetry is set but MaxRetries is 0, the loop runs exactly once
@@ -338,7 +428,9 @@ func (r *typedRetryModelWrapper[M]) BindTools(tools []*schema.ToolInfo) error {
// with RetryExhaustedError{TotalRetries: 0}. Set MaxRetries >= 1 to allow
// ShouldRetry-driven retries to actually retry.
func WithModelRetry[M MessageType](inner Model[M], cfg *TypedModelRetryConfig[M]) Model[M] {
- if cfg == nil || (cfg.MaxRetries <= 0 && cfg.ShouldRetry == nil) { return inner }
+ if cfg == nil || (cfg.MaxRetries <= 0 && cfg.ShouldRetry == nil) {
+ return inner
+ }
return newTypedRetryModelWrapper(inner, cfg)
}
@@ -358,24 +450,34 @@ func applyRetryDecision[M MessageType](input *[]M, opts *[]ModelOption, decision
}
func contextAwareSleep(ctx context.Context, delay time.Duration) error {
- if delay <= 0 { return nil }
+ if delay <= 0 {
+ return nil
+ }
select {
- case <-ctx.Done(): return ctx.Err()
- case <-time.After(delay): return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(delay):
+ return nil
}
}
func mergeChunks[M MessageType](chunks []M) (M, error) {
var zero M
- if len(chunks) == 0 { return zero, nil }
+ if len(chunks) == 0 {
+ return zero, nil
+ }
switch c := any(chunks).(type) {
case []*schema.Message:
merged, err := schema.ConcatMessages(c)
- if err != nil { return zero, err }
+ if err != nil {
+ return zero, err
+ }
return any(merged).(M), nil
case []*schema.AgenticMessage:
merged, err := schema.ConcatAgenticMessages(c)
- if err != nil { return zero, err }
+ if err != nil {
+ return zero, err
+ }
return any(merged).(M), nil
}
return chunks[0], nil
@@ -393,10 +495,14 @@ type retrySignal struct {
}
func (rs *retrySignal) consume() streamRetryVerdict {
- if rs == nil { return streamRetryVerdict{} }
+ if rs == nil {
+ return streamRetryVerdict{}
+ }
select {
- case v := <-rs.ch: return v
- default: return streamRetryVerdict{}
+ case v := <-rs.ch:
+ return v
+ default:
+ return streamRetryVerdict{}
}
}
@@ -404,4 +510,3 @@ func (rs *retrySignal) consume() streamRetryVerdict {
func WithRetry[M MessageType](cfg *TypedModelRetryConfig[M]) ModelOption {
return &typedModelOption[M]{f: func(o *modelOptions[M]) { o.RetryConfig = cfg }}
}
-
diff --git a/internal/harness/core/retry_test.go b/internal/harness/core/retry_test.go
index 8a3288de04..6914ff5dc0 100644
--- a/internal/harness/core/retry_test.go
+++ b/internal/harness/core/retry_test.go
@@ -15,7 +15,9 @@ type countingModel struct {
func (m *countingModel) Generate(ctx context.Context, msgs []Message, opts ...modelOption) (Message, error) {
m.calls++
- if m.err != nil { return nil, m.err }
+ if m.err != nil {
+ return nil, m.err
+ }
return &schema.Message{Role: schema.RoleAssistant, Content: "ok"}, nil
}
func (m *countingModel) Stream(ctx context.Context, msgs []Message, opts ...modelOption) (*schema.StreamReader[Message], error) {
diff --git a/internal/harness/core/runner.go b/internal/harness/core/runner.go
index 3c1c9db19f..93276faa00 100644
--- a/internal/harness/core/runner.go
+++ b/internal/harness/core/runner.go
@@ -39,7 +39,9 @@ func (r *TypedRunner[M]) Run(ctx context.Context, msgs []M, opts ...RunOption) *
func (r *TypedRunner[M]) Query(ctx context.Context, query string, opts ...RunOption) *AsyncIterator[*TypedAgentEvent[M]] {
msgs, err := newUserMsg[M](query)
- if err != nil { return errorIter[M](err) }
+ if err != nil {
+ return errorIter[M](err)
+ }
return r.Run(ctx, []M{msgs}, opts...)
}
@@ -83,7 +85,9 @@ func runImpl[M MessageType](a TypedAgent[M], streaming bool, store CheckPointSto
return errorIter[M](fmt.Errorf("agent does not implement Agent interface"))
}
fa := toFlowAgent(ctx, ca)
- if store != nil { fa.checkPointStore = store }
+ if store != nil {
+ fa.checkPointStore = store
+ }
ci, ok := any(input).(*AgentInput)
if !ok {
return errorIter[M](fmt.Errorf("input type assertion failed: expected *AgentInput, got %T", input))
@@ -93,21 +97,31 @@ func runImpl[M MessageType](a TypedAgent[M], streaming bool, store CheckPointSto
}
tfa := toTypedFlowAgent(a)
- if store != nil { tfa.checkPointStore = store }
+ if store != nil {
+ tfa.checkPointStore = store
+ }
ctx = setupRunContext(ctx, input, o)
return wrapIterForStore(streaming, store, ctx, tfa.Run(ctx, input, opts...), o)
}
func resumeInternal[M MessageType](a TypedAgent[M], store CheckPointStore, ctx context.Context, cid string, data map[string]any, opts ...RunOption) (*AsyncIterator[*TypedAgentEvent[M]], error) {
- if store == nil { return nil, fmt.Errorf("resume requires a checkpoint store") }
+ if store == nil {
+ return nil, fmt.Errorf("resume requires a checkpoint store")
+ }
ctx, rc, info, err := loadCheckpoint(store, ctx, cid)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
streaming := info.EnableStreaming
o := getCommonOptions(nil, opts...)
if o.sharedParentSession {
- if ps := getSession(ctx); ps != nil { rc.Session.Values = ps.Values }
+ if ps := getSession(ctx); ps != nil {
+ rc.Session.Values = ps.Values
+ }
+ }
+ if rc.Session.Values == nil {
+ rc.Session.Values = make(map[string]any)
}
- if rc.Session.Values == nil { rc.Session.Values = make(map[string]any) }
ctx = setRunCtx(ctx, rc)
AddSessionValues(ctx, o.sessionValues)
@@ -116,13 +130,17 @@ func resumeInternal[M MessageType](a TypedAgent[M], store CheckPointStore, ctx c
ca, _ := any(a).(Agent)
fa := toFlowAgent(ctx, ca)
ra, ok := Agent(fa).(ResumableAgent)
- if !ok { return nil, fmt.Errorf("agent %T does not support resume", a) }
+ if !ok {
+ return nil, fmt.Errorf("agent %T does not support resume", a)
+ }
return newIterForStore(streaming, store, ctx, any(ra.Resume(ctx, info, opts...)).(*AsyncIterator[*TypedAgentEvent[M]]), &cid, o.cancelCtx), nil
}
tfa := toTypedFlowAgent(a)
ra, ok := TypedAgent[M](tfa).(TypedResumableAgent[M])
- if !ok { return nil, fmt.Errorf("agent %T does not support resume", a) }
+ if !ok {
+ return nil, fmt.Errorf("agent %T does not support resume", a)
+ }
return newIterForStore(streaming, store, ctx, ra.Resume(ctx, info, opts...), &cid, o.cancelCtx), nil
}
@@ -152,17 +170,23 @@ func newIterForStore[M MessageType](streaming bool, store CheckPointStore, ctx c
func handleIter[M MessageType](streaming bool, store CheckPointStore, ctx context.Context, ai *AsyncIterator[*TypedAgentEvent[M]], gen *AsyncGenerator[*TypedAgentEvent[M]], cid *string, cc *cancelContext) {
defer func() {
- if r := recover(); r != nil { gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)}) }
+ if r := recover(); r != nil {
+ gen.Send(&TypedAgentEvent[M]{Err: fmt.Errorf("panic: %v", r)})
+ }
gen.Close()
}()
var sig *InterruptSignal
for {
ev, ok := ai.Next()
- if !ok { break }
+ if !ok {
+ break
+ }
if ev.Err != nil {
var ce *CancelError
if errors.As(ev.Err, &ce) {
- if cc != nil && cc.isRoot() && cc.shouldCancel() { cc.markHandled() }
+ if cc != nil && cc.isRoot() && cc.shouldCancel() {
+ cc.markHandled()
+ }
if ce.interruptSignal != nil && cid != nil {
ce.InterruptContexts = nil
saveCheckpoint(store, ctx, *cid, streaming, &InterruptInfo{}, ce.interruptSignal)
@@ -172,13 +196,17 @@ func handleIter[M MessageType](streaming bool, store CheckPointStore, ctx contex
}
}
if ev.Action != nil && ev.Action.internalInterrupted != nil {
- if sig != nil { panic("multiple interrupt actions") }
+ if sig != nil {
+ panic("multiple interrupt actions")
+ }
sig = ev.Action.internalInterrupted
ev = &TypedAgentEvent[M]{
AgentName: ev.AgentName, RunPath: ev.RunPath, Output: ev.Output,
- Action: &AgentAction{Interrupted: &InterruptInfo{Data: ev.Action.Interrupted.Data}, internalInterrupted: sig},
- }
- if cid != nil { saveCheckpoint(store, ctx, *cid, streaming, &InterruptInfo{Data: ev.Action.Interrupted.Data}, sig) }
+ Action: &AgentAction{Interrupted: &InterruptInfo{Data: ev.Action.Interrupted.Data}, internalInterrupted: sig},
+ }
+ if cid != nil {
+ saveCheckpoint(store, ctx, *cid, streaming, &InterruptInfo{Data: ev.Action.Interrupted.Data}, sig)
+ }
}
gen.Send(ev)
}
diff --git a/internal/harness/core/schema/types.go b/internal/harness/core/schema/types.go
index 2b0ba1f534..8b2a0b0b21 100644
--- a/internal/harness/core/schema/types.go
+++ b/internal/harness/core/schema/types.go
@@ -41,12 +41,12 @@ type ToolCall struct {
// Message represents a conversation message with typed role and content.
type Message struct {
- Role RoleType `json:"role"`
- Content string `json:"content"`
- Name string `json:"name,omitempty"`
- ToolCalls []ToolCall `json:"tool_calls,omitempty"`
- ToolName string `json:"tool_name,omitempty"`
- Extra map[string]any `json:"extra,omitempty"`
+ Role RoleType `json:"role"`
+ Content string `json:"content"`
+ Name string `json:"name,omitempty"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ ToolName string `json:"tool_name,omitempty"`
+ Extra map[string]any `json:"extra,omitempty"`
}
// ToolCallInfo represents information about a tool call for agentic messages.
@@ -68,8 +68,8 @@ type ToolResult struct {
// ContentBlock represents a structured content element within an AgenticMessage.
type ContentBlock struct {
- Type string `json:"type"`
- Text string `json:"text,omitempty"`
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
ToolCall *ToolCallInfo `json:"tool_call,omitempty"`
ToolResult *ToolResult `json:"tool_result,omitempty"`
}
@@ -95,9 +95,9 @@ const (
// ToolChoiceForbidden instructs the model not to call any tools.
ToolChoiceForbidden ToolChoice = "forbidden"
// ToolChoiceAllowed lets the model decide whether to call tools.
- ToolChoiceAllowed ToolChoice = "allowed"
+ ToolChoiceAllowed ToolChoice = "allowed"
// ToolChoiceForced requires the model to call at least one tool.
- ToolChoiceForced ToolChoice = "forced"
+ ToolChoiceForced ToolChoice = "forced"
)
// AllowedTool specifies a tool that the model is permitted or required to call.
diff --git a/internal/harness/core/session.go b/internal/harness/core/session.go
index 1d967f21db..88147bc3eb 100644
--- a/internal/harness/core/session.go
+++ b/internal/harness/core/session.go
@@ -109,12 +109,12 @@ type branchEvents struct {
// runSession holds per-execution mutable state for an agent run.
type runSession struct {
- mu sync.Mutex
- Values map[string]any
- valuesMx *sync.Mutex
- events []*eventWrapEntry
- BranchEvents *branchEvents
- TypedEvents any // *[]*typedAgentEventWrapper[M] for AgenticMessage path (gob-encodable)
+ mu sync.Mutex
+ Values map[string]any
+ valuesMx *sync.Mutex
+ events []*eventWrapEntry
+ BranchEvents *branchEvents
+ TypedEvents any // *[]*typedAgentEventWrapper[M] for AgenticMessage path (gob-encodable)
}
func newRunSession() *runSession {
@@ -188,7 +188,9 @@ type runContext struct {
// getRunPath safely returns a copy of RunPath under lock.
func (rc *runContext) getRunPath() []RunStep {
- if rc == nil { return nil }
+ if rc == nil {
+ return nil
+ }
rc.mu.Lock()
defer rc.mu.Unlock()
cp := make([]RunStep, len(rc.RunPath))
@@ -198,7 +200,9 @@ func (rc *runContext) getRunPath() []RunStep {
// setRunPath safely replaces RunPath under lock.
func (rc *runContext) setRunPath(v []RunStep) {
- if rc == nil { return }
+ if rc == nil {
+ return
+ }
rc.mu.Lock()
rc.RunPath = v
rc.mu.Unlock()
@@ -206,7 +210,9 @@ func (rc *runContext) setRunPath(v []RunStep) {
// appendRunPath safely appends to RunPath under lock.
func (rc *runContext) appendRunPath(v RunStep) {
- if rc == nil { return }
+ if rc == nil {
+ return
+ }
rc.mu.Lock()
rc.RunPath = append(rc.RunPath, v)
rc.mu.Unlock()
@@ -261,7 +267,7 @@ func forkRunCtx(ctx context.Context) context.Context {
childSession := &runSession{
events: eventsCopy,
- Values: parent.Session.Values, // Share values map
+ Values: parent.Session.Values, // Share values map
valuesMx: parent.Session.valuesMx,
}
diff --git a/internal/harness/core/stability_integration_test.go b/internal/harness/core/stability_integration_test.go
index 76d66b599d..1b470c6a74 100644
--- a/internal/harness/core/stability_integration_test.go
+++ b/internal/harness/core/stability_integration_test.go
@@ -35,7 +35,7 @@ func TestStability_ReActGraph_FullLifecycle(t *testing.T) {
Checkpointer: store,
RecursionLimit: 10,
InterruptBefore: nil, // no interrupts for this test
- })
+ }, nil)
if err != nil {
t.Fatalf("NewReActGraph: %v", err)
}
@@ -280,8 +280,8 @@ func TestStability_NestedAgentCancelPropagation(t *testing.T) {
inner := current
outer := agents[i]
seq, err := NewSequential(ctx, &SequentialConfig{
- Name: fmt.Sprintf("seq_%c", 'a'+i),
- SubAgents: []Agent{outer, inner},
+ Name: fmt.Sprintf("seq_%c", 'a'+i),
+ SubAgents: []Agent{outer, inner},
})
if err != nil {
t.Fatalf("NewSequential depth %d: %v", i, err)
@@ -342,7 +342,13 @@ func TestStability_GoroutineLeak_AllPaths(t *testing.T) {
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model}).WithName("leak_test")
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
iter := runner.Run(context.Background(), []*schema.Message{schema.UserMessage("test")})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
{
@@ -365,42 +371,65 @@ func TestStability_GoroutineLeak_AllPaths(t *testing.T) {
}).WithName("parent")
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: parent})
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("go")})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
{
name: "sequential_workflow",
run: func(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("a")
- m2 := &mockModel{}; m2.addResp("b")
+ m1 := &mockModel{}
+ m1.addResp("a")
+ m2 := &mockModel{}
+ m2.addResp("b")
a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}).WithName("a")
a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}).WithName("b")
ctx := context.Background()
seq, _ := NewSequential(ctx, &SequentialConfig{Name: "seq", SubAgents: []Agent{a1, a2}})
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: seq})
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("go")})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
{
name: "parallel_workflow",
run: func(t *testing.T) {
- m1 := &mockModel{}; m1.addResp("a")
- m2 := &mockModel{}; m2.addResp("b")
+ m1 := &mockModel{}
+ m1.addResp("a")
+ m2 := &mockModel{}
+ m2.addResp("b")
a1 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m1}).WithName("a")
a2 := NewReActAgent(&ReActConfig[*schema.Message]{Model: m2}).WithName("b")
ctx := context.Background()
par, _ := NewParallel(ctx, &ParallelConfig{Name: "par", SubAgents: []Agent{a1, a2}})
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: par})
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("go")})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
{
name: "cancel_immediate",
run: func(t *testing.T) {
m := newCancelTestChatModel(nil)
- m.addResp("slow"); m.setDelay(100 * time.Millisecond)
+ m.addResp("slow")
+ m.setDelay(100 * time.Millisecond)
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: m}).WithName("cancel_leak")
cancelOpt, cancelFunc := WithCancel()
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
@@ -408,7 +437,13 @@ func TestStability_GoroutineLeak_AllPaths(t *testing.T) {
iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("go")}, cancelOpt)
time.Sleep(10 * time.Millisecond)
cancelFunc(WithCancelMode(CancelImmediate))
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
{
@@ -419,7 +454,13 @@ func TestStability_GoroutineLeak_AllPaths(t *testing.T) {
agent := NewReActAgent(&ReActConfig[*schema.Message]{Model: model}).WithName("stream_leak")
runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent, EnableStreaming: true})
iter := runner.Run(context.Background(), []*schema.Message{schema.UserMessage("test")})
- for { ev, ok := iter.Next(); if !ok { break }; _ = ev }
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ _ = ev
+ }
},
},
}
@@ -483,7 +524,7 @@ func TestStability_RetryStorm_CircuitBreaker(t *testing.T) {
agent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: failModel,
RetryConfig: &ModelRetryConfig{
- MaxRetries: 2,
+ MaxRetries: 2,
ShouldRetry: func(ctx context.Context, rc *RetryContext) *RetryDecision {
return &RetryDecision{Retry: true}
},
@@ -520,7 +561,7 @@ func TestStability_RetryStorm_CircuitBreaker(t *testing.T) {
agent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: failModel,
RetryConfig: &ModelRetryConfig{
- MaxRetries: 2,
+ MaxRetries: 2,
ShouldRetry: func(ctx context.Context, rc *RetryContext) *RetryDecision {
return &RetryDecision{Retry: true}
},
diff --git a/internal/harness/core/state_guard.go b/internal/harness/core/state_guard.go
index 6a204926bf..7db3624a0e 100644
--- a/internal/harness/core/state_guard.go
+++ b/internal/harness/core/state_guard.go
@@ -19,8 +19,8 @@ import (
// - Model output event emission
// - BeforeModelRewrite / AfterModelRewrite orchestration (via chatmodel.go loop)
type typedStateModelWrapper[M MessageType] struct {
- inner Model[M]
- cancelCtx *cancelContext
+ inner Model[M]
+ cancelCtx *cancelContext
}
func newTypedStateModelWrapper[M MessageType](inner Model[M], cc *cancelContext) Model[M] {
diff --git a/internal/harness/core/subagent_node.go b/internal/harness/core/subagent_node.go
index 15efeec330..5b091f9351 100644
--- a/internal/harness/core/subagent_node.go
+++ b/internal/harness/core/subagent_node.go
@@ -227,5 +227,3 @@ func subAgentCollectOutput(cfg *SubAgentNodeConfig, ctx context.Context, state i
}
return st, nil
}
-
-
diff --git a/internal/harness/core/tool.go b/internal/harness/core/tool.go
index 1eb4ae2e81..c7b4cb891c 100644
--- a/internal/harness/core/tool.go
+++ b/internal/harness/core/tool.go
@@ -56,9 +56,13 @@ func WithMaxDepth(d int) AgentToolOption {
// - Interrupted actions are propagated via CompositeInterrupt for proper interrupt/resume
func NewAgentTool(ctx context.Context, agent Agent, options ...AgentToolOption) Tool {
opts := &AgentToolOptions{}
- for _, o := range options { o(opts) }
+ for _, o := range options {
+ o(opts)
+ }
name := agent.Name(ctx)
- if name == "" { name = "agent_tool" }
+ if name == "" {
+ name = "agent_tool"
+ }
desc := agent.Description(ctx)
return &agentTool{
name: name, desc: desc, agent: agent,
@@ -75,7 +79,7 @@ type agentTool struct {
}
func (t *agentTool) Name() string { return t.name }
-func (t *agentTool) Description() string { return t.desc }
+func (t *agentTool) Description() string { return t.desc }
func (t *agentTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (result string, err error) {
// Panic recovery: runner.Run or iter.Next may panic; catch and convert to Go error.
@@ -127,8 +131,12 @@ func (t *agentTool) Invoke(ctx context.Context, args string, opts ...ToolOption)
var interrupted bool
for {
ev, ok := iter.Next()
- if !ok { break }
- if ev.Err != nil { return "", fmt.Errorf("agent tool '%s': %w", t.name, ev.Err) }
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ return "", fmt.Errorf("agent tool '%s': %w", t.name, ev.Err)
+ }
// EmitInternalEvents: forward events to parent stream
if parentEC != nil && t.opts.EmitInternalEvents {
@@ -161,6 +169,8 @@ func (t *agentTool) Invoke(ctx context.Context, args string, opts ...ToolOption)
func (t *agentTool) Stream(ctx context.Context, args string, opts ...ToolOption) (*schema.StreamReader[string], error) {
r, err := t.Invoke(ctx, args, opts...)
- if err != nil { return nil, err }
+ if err != nil {
+ return nil, err
+ }
return schema.StreamReaderFromArray([]string{r}), nil
}
diff --git a/internal/harness/core/tool_contributor.go b/internal/harness/core/tool_contributor.go
new file mode 100644
index 0000000000..becb14d3e5
--- /dev/null
+++ b/internal/harness/core/tool_contributor.go
@@ -0,0 +1,88 @@
+package core
+
+import (
+ "context"
+
+ "ragflow/internal/harness/core/schema"
+)
+
+// ToolContributor is an optional interface that middlewares can implement to
+// contribute tools, tool infos, and return-directly entries to the agent.
+//
+// The agent loop collects contributions BEFORE calling BeforeAgent, ensuring
+// that tools are available for both ToolsNode construction and BeforeAgent
+// middleware processing. This replaces the unreliable pattern of modifying
+// rc.Tools in BeforeAgent (which doesn't propagate to ToolsNode) and the
+// timing-coupled BindToConfig pattern.
+//
+// Example:
+//
+// type myMiddleware struct {
+// BaseMiddleware[M]
+// }
+//
+// func (m *myMiddleware) ContributeTools(ctx context.Context) []Tool {
+// return []Tool{NewBaseTool("my_tool", "Does something", myFunc)}
+// }
+type ToolContributor[M MessageType] interface {
+ // ContributeTools returns tools to add to the agent's tool set.
+ // Called once during agent build (before BeforeAgent).
+ ContributeTools(ctx context.Context) []Tool
+
+ // ContributeToolInfos returns structured ToolInfo entries to bind to the
+ // model. These are merged with auto-generated infos from ContributeTools.
+ // Use this for special entries that don't correspond to a Tool (e.g.,
+ // a meta-tool like "search_tools" for dynamic tool search).
+ ContributeToolInfos(ctx context.Context) []*schema.ToolInfo
+
+ // ContributeReturnDirectly returns tool names that should cause the agent
+ // to return immediately after execution. Merged with config-level
+ // ReturnDirectly.
+ ContributeReturnDirectly(ctx context.Context) map[string]bool
+}
+
+// ---- Collection helpers ----
+
+// collectContributorTools returns tools contributed by all ToolContributor middlewares.
+func collectContributorTools[M MessageType](ctx context.Context, middlewares []TypedReActMiddleware[M]) []Tool {
+ var all []Tool
+ for _, mw := range middlewares {
+ if mw == nil {
+ continue
+ }
+ if c, ok := mw.(ToolContributor[M]); ok {
+ all = append(all, c.ContributeTools(ctx)...)
+ }
+ }
+ return all
+}
+
+// collectContributorToolInfos returns tool infos contributed by all ToolContributor middlewares.
+func collectContributorToolInfos[M MessageType](ctx context.Context, middlewares []TypedReActMiddleware[M]) []*schema.ToolInfo {
+ var all []*schema.ToolInfo
+ for _, mw := range middlewares {
+ if mw == nil {
+ continue
+ }
+ if c, ok := mw.(ToolContributor[M]); ok {
+ all = append(all, c.ContributeToolInfos(ctx)...)
+ }
+ }
+ return all
+}
+
+// collectContributorReturnDirectly merges return-directly entries from all ToolContributor middlewares.
+func collectContributorReturnDirectly[M MessageType](ctx context.Context, middlewares []TypedReActMiddleware[M]) map[string]bool {
+ all := make(map[string]bool)
+ for _, mw := range middlewares {
+ if mw == nil {
+ continue
+ }
+ if c, ok := mw.(ToolContributor[M]); ok {
+ for k, v := range c.ContributeReturnDirectly(ctx) {
+ all[k] = v
+ }
+ }
+ }
+ return all
+}
diff --git a/internal/harness/core/tool_contributor_test.go b/internal/harness/core/tool_contributor_test.go
new file mode 100644
index 0000000000..fd4b1f7c5c
--- /dev/null
+++ b/internal/harness/core/tool_contributor_test.go
@@ -0,0 +1,397 @@
+package core
+
+import (
+ "context"
+ "sync"
+ "testing"
+
+ "ragflow/internal/harness/core/schema"
+)
+
+// ========================================================================
+// Local helpers (avoids dependency on subagent/ test internals)
+// ========================================================================
+
+type testScriptedStep struct {
+ Text string
+ ToolCalls []schema.ToolCall
+}
+
+type testScriptedModel struct {
+ mu sync.Mutex
+ steps []testScriptedStep
+ pos int
+}
+
+func newTestScriptedModel(steps ...testScriptedStep) *testScriptedModel {
+ return &testScriptedModel{steps: steps}
+}
+
+func (m *testScriptedModel) Generate(ctx context.Context, msgs []*schema.Message, opts ...ModelOption) (*schema.Message, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.pos >= len(m.steps) {
+ return &schema.Message{Role: schema.RoleAssistant, Content: "done"}, nil
+ }
+ s := m.steps[m.pos]
+ m.pos++
+ msg := &schema.Message{Role: schema.RoleAssistant, Content: s.Text}
+ if len(s.ToolCalls) > 0 {
+ msg.ToolCalls = s.ToolCalls
+ }
+ return msg, nil
+}
+
+func (m *testScriptedModel) Stream(ctx context.Context, msgs []*schema.Message, opts ...ModelOption) (*schema.StreamReader[*schema.Message], error) {
+ msg, _ := m.Generate(ctx, msgs, opts...)
+ return schema.StreamReaderFromArray([]*schema.Message{msg}), nil
+}
+
+func (m *testScriptedModel) BindTools(tools []*schema.ToolInfo) error { return nil }
+
+type testForcedToolModel struct {
+ inner *mockModel
+ toolCalls []schema.ToolCall
+ finalResp string
+ mu sync.Mutex
+ firstCall bool
+}
+
+func newTestForcedToolModel(inner *mockModel, toolCalls []schema.ToolCall, finalResp string) *testForcedToolModel {
+ return &testForcedToolModel{
+ inner: inner,
+ toolCalls: toolCalls,
+ finalResp: finalResp,
+ firstCall: true,
+ }
+}
+
+func (m *testForcedToolModel) Generate(ctx context.Context, msgs []*schema.Message, opts ...ModelOption) (*schema.Message, error) {
+ m.mu.Lock()
+ isFirst := m.firstCall
+ if isFirst {
+ m.firstCall = false
+ }
+ m.mu.Unlock()
+ if isFirst {
+ return &schema.Message{
+ Role: schema.RoleAssistant,
+ Content: "",
+ ToolCalls: m.toolCalls,
+ }, nil
+ }
+ return &schema.Message{Role: schema.RoleAssistant, Content: m.finalResp}, nil
+}
+
+func (m *testForcedToolModel) Stream(ctx context.Context, msgs []*schema.Message, opts ...ModelOption) (*schema.StreamReader[*schema.Message], error) {
+ msg, _ := m.Generate(ctx, msgs, opts...)
+ return schema.StreamReaderFromArray([]*schema.Message{msg}), nil
+}
+
+func (m *testForcedToolModel) BindTools(tools []*schema.ToolInfo) error { return nil }
+
+// ========================================================================
+// Mock ToolContributor Middlewares
+// ========================================================================
+
+// contributorMW is a middleware that contributes tools via ToolContributor.
+type contributorMW struct {
+ BaseMiddleware[*schema.Message]
+ tools []Tool
+ infos []*schema.ToolInfo
+ returnRD map[string]bool
+}
+
+func (m *contributorMW) ContributeTools(ctx context.Context) []Tool {
+ return m.tools
+}
+func (m *contributorMW) ContributeToolInfos(ctx context.Context) []*schema.ToolInfo {
+ return m.infos
+}
+func (m *contributorMW) ContributeReturnDirectly(ctx context.Context) map[string]bool {
+ return m.returnRD
+}
+
+// markerTool records whether it was executed.
+type markerTool struct {
+ name string
+ executed bool
+ mu sync.Mutex
+}
+
+func (t *markerTool) Name() string { return t.name }
+func (t *markerTool) Description() string { return "test tool: " + t.name }
+func (t *markerTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
+ t.mu.Lock()
+ t.executed = true
+ t.mu.Unlock()
+ return "result:" + t.name, nil
+}
+func (t *markerTool) Stream(ctx context.Context, args string, opts ...ToolOption) (*schema.StreamReader[string], error) {
+ return schema.StreamReaderFromArray([]string{"stream:" + t.name}), nil
+}
+
+// ========================================================================
+// Tests
+// ========================================================================
+
+// TestToolContributor_Basic verifies that a ToolContributor middleware's tools
+// are available for tool execution in the ReAct loop.
+func TestToolContributor_Basic(t *testing.T) {
+ myTool := &markerTool{name: "contrib_tool"}
+
+ mw := &contributorMW{tools: []Tool{myTool}}
+ model := newTestForcedToolModel(&mockModel{},
+ []schema.ToolCall{
+ {ID: "c1", Function: schema.ToolCallFunction{Name: "contrib_tool", Arguments: "{}"}},
+ },
+ "final answer",
+ )
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: model,
+ Middlewares: []ReActMiddleware{mw},
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("use tool")})
+
+ drainTestFinal(t, iter)
+ if !myTool.executed {
+ t.Error("contributor tool was NOT executed")
+ }
+ t.Logf("basic: tool_executed=%v", myTool.executed)
+}
+
+// TestToolContributor_MultipleContributors verifies that tools from multiple
+// ToolContributor middlewares are all available.
+func TestToolContributor_MultipleContributors(t *testing.T) {
+ toolA := &markerTool{name: "tool_a"}
+ toolB := &markerTool{name: "tool_b"}
+
+ mwA := &contributorMW{tools: []Tool{toolA}}
+ mwB := &contributorMW{tools: []Tool{toolB}}
+
+ model := newTestScriptedModel(
+ testScriptedStep{ToolCalls: []schema.ToolCall{
+ {ID: "call_a", Function: schema.ToolCallFunction{Name: "tool_a", Arguments: "{}"}},
+ {ID: "call_b", Function: schema.ToolCallFunction{Name: "tool_b", Arguments: "{}"}},
+ }},
+ testScriptedStep{Text: "multi done"},
+ )
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: model,
+ Middlewares: []ReActMiddleware{mwA, mwB},
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("use both")})
+
+ drainTestFinal(t, iter)
+ if !toolA.executed {
+ t.Error("tool_a was NOT executed")
+ }
+ if !toolB.executed {
+ t.Error("tool_b was NOT executed")
+ }
+ t.Logf("multiple: toolA=%v, toolB=%v", toolA.executed, toolB.executed)
+}
+
+// TestToolContributor_WithConfigTools verifies that tools from both config.Tools
+// and ToolContributor middlewares are merged and available.
+func TestToolContributor_WithConfigTools(t *testing.T) {
+ configTool := &markerTool{name: "config_tool"}
+ contribTool := &markerTool{name: "contrib_tool"}
+
+ mw := &contributorMW{tools: []Tool{contribTool}}
+ model := newTestScriptedModel(
+ testScriptedStep{ToolCalls: []schema.ToolCall{
+ {ID: "c1", Function: schema.ToolCallFunction{Name: "config_tool", Arguments: "{}"}},
+ {ID: "c2", Function: schema.ToolCallFunction{Name: "contrib_tool", Arguments: "{}"}},
+ }},
+ testScriptedStep{Text: "merged done"},
+ )
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: model,
+ Tools: []Tool{configTool},
+ Middlewares: []ReActMiddleware{mw},
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("use both types")})
+
+ drainTestFinal(t, iter)
+ if !configTool.executed {
+ t.Error("config tool was NOT executed")
+ }
+ if !contribTool.executed {
+ t.Error("contributor tool was NOT executed")
+ }
+ t.Logf("merged: config=%v, contrib=%v", configTool.executed, contribTool.executed)
+}
+
+// TestToolContributor_ReturnDirectly verifies ContributeReturnDirectly works.
+func TestToolContributor_ReturnDirectly(t *testing.T) {
+ myTool := &markerTool{name: "rd_tool"}
+
+ mw := &contributorMW{
+ tools: []Tool{myTool},
+ returnRD: map[string]bool{"rd_tool": true},
+ }
+ model := newTestForcedToolModel(&mockModel{},
+ []schema.ToolCall{
+ {ID: "rd1", Function: schema.ToolCallFunction{Name: "rd_tool", Arguments: "{}"}},
+ },
+ "should not be reached",
+ )
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: model,
+ Middlewares: []ReActMiddleware{mw},
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("return directly")})
+
+ drainTestFinal(t, iter)
+ if !myTool.executed {
+ t.Error("rd_tool was NOT executed")
+ }
+ t.Logf("return-directly: tool_executed=%v", myTool.executed)
+}
+
+// TestToolContributor_WithSubAgent verifies subagent middleware works
+// via ToolContributor + Init (without BindToConfig).
+func TestToolContributor_WithSubAgent(t *testing.T) {
+ // Use subagent package types — import at top
+ subModel := &mockModel{}
+ subModel.addResp("sub result")
+ subAgent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: subModel,
+ }).WithName("helper").WithDescription("Helper agent")
+
+ parentModel := newTestForcedToolModel(&mockModel{},
+ []schema.ToolCall{
+ {ID: "h1", Function: schema.ToolCallFunction{Name: "helper", Arguments: "{}"}},
+ },
+ "parent done",
+ )
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: parentModel,
+ Tools: []Tool{
+ &agentTool{
+ name: "helper", desc: "Helper agent",
+ agent: subAgent, baseCtx: context.Background(),
+ },
+ },
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("use helper")})
+
+ final := drainTestFinal(t, iter)
+ if final != "parent done" {
+ t.Errorf("expected 'parent done', got %q", final)
+ }
+ t.Logf("subagent tc: final=%q", final)
+}
+
+// TestToolContributor_BeforeAgentStillWorks verifies that BeforeAgent can still
+// modify non-tool fields.
+func TestToolContributor_BeforeAgentStillWorks(t *testing.T) {
+ tracker := &testTrackerMiddleware{}
+
+ model := &mockModel{}
+ model.addResp("before agent works")
+
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: model,
+ Middlewares: []ReActMiddleware{tracker},
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("test")})
+
+ drainTestFinal(t, iter)
+ if !tracker.beforeAgentCalled {
+ t.Error("BeforeAgent was NOT called")
+ }
+ t.Log("BeforeAgent still works with ToolContributor")
+}
+
+// TestToolContributor_NoInitNeeded verifies that subagent tools are auto-collected
+// when Init/BindToConfig is not called.
+func TestToolContributor_NoInitNeeded(t *testing.T) {
+ subModel := &mockModel{}
+ subModel.addResp("auto sub result")
+ subAgent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: subModel,
+ }).WithName("auto_helper").WithDescription("Auto helper")
+
+ agent := NewReActAgent(&ReActConfig[*schema.Message]{
+ Model: newTestForcedToolModel(&mockModel{},
+ []schema.ToolCall{
+ {ID: "a1", Function: schema.ToolCallFunction{Name: "auto_helper", Arguments: "{}"}},
+ },
+ "auto parent done",
+ ),
+ Tools: []Tool{
+ &agentTool{
+ name: "auto_helper", desc: "Auto helper",
+ agent: subAgent, baseCtx: context.Background(),
+ },
+ },
+ })
+
+ ctx := context.Background()
+ runner := NewTypedRunner(RunnerConfig[*schema.Message]{Agent: agent})
+ iter := runner.Run(ctx, []*schema.Message{schema.UserMessage("auto")})
+
+ final := drainTestFinal(t, iter)
+ if final != "auto parent done" {
+ t.Errorf("expected 'auto parent done', got %q", final)
+ }
+ t.Logf("no-init: final=%q", final)
+}
+
+// ========================================================================
+// Helpers
+// ========================================================================
+type testTrackerMiddleware struct {
+ BaseMiddleware[*schema.Message]
+ beforeAgentCalled bool
+ mu sync.Mutex
+}
+
+func (m *testTrackerMiddleware) BeforeAgent(ctx context.Context, rc *ReActAgentContext) (context.Context, *ReActAgentContext, error) {
+ m.mu.Lock()
+ m.beforeAgentCalled = true
+ m.mu.Unlock()
+ return ctx, rc, nil
+}
+
+// drainTestFinal drains the iterator and returns the final output text.
+func drainTestFinal(t *testing.T, iter *AsyncIterator[*TypedAgentEvent[*schema.Message]]) string {
+ t.Helper()
+ var final string
+ for {
+ ev, ok := iter.Next()
+ if !ok {
+ break
+ }
+ if ev.Err != nil {
+ t.Logf("event error: %v", ev.Err)
+ continue
+ }
+ if ev.Output != nil && ev.Output.MessageOutput != nil &&
+ !ev.Output.MessageOutput.IsStreaming &&
+ ev.Output.MessageOutput.Message != nil {
+ final = ev.Output.MessageOutput.Message.Content
+ }
+ }
+ return final
+}
diff --git a/internal/harness/core/tool_invoke.go b/internal/harness/core/tool_invoke.go
index b88d058649..d0c752b6ab 100644
--- a/internal/harness/core/tool_invoke.go
+++ b/internal/harness/core/tool_invoke.go
@@ -275,8 +275,8 @@ func NewCancelToolMiddleware() ToolInvokeMiddleware {
// rateLimiter implements a simple per-tool token bucket.
type rateLimiter struct {
- mu sync.Mutex
- tokens map[string]*tokenBucket
+ mu sync.Mutex
+ tokens map[string]*tokenBucket
}
type tokenBucket struct {
diff --git a/internal/harness/core/tool_invoke_test.go b/internal/harness/core/tool_invoke_test.go
index a4f0b8e89a..394a838019 100644
--- a/internal/harness/core/tool_invoke_test.go
+++ b/internal/harness/core/tool_invoke_test.go
@@ -328,8 +328,8 @@ func TestToolToInvokeFn(t *testing.T) {
invokeFn := ToolToInvokeFn(tool)
ictx := &ToolInvocationContext{
- Name: "echo",
- CallID: "call_1",
+ Name: "echo",
+ CallID: "call_1",
Arguments: &schema.ToolArgument{Arguments: `"hello"`},
}
@@ -347,8 +347,8 @@ func TestEnhancedToolToInvokeFn(t *testing.T) {
invokeFn := EnhancedToolToInvokeFn(et)
ictx := &ToolInvocationContext{
- Name: "enhanced_tool",
- CallID: "call_2",
+ Name: "enhanced_tool",
+ CallID: "call_2",
Arguments: &schema.ToolArgument{
Name: "enhanced_tool", Arguments: `{}`, CallID: "call_2",
},
@@ -394,8 +394,8 @@ type simpleTestTool struct {
}
func newTestTool(name, desc string) *simpleTestTool { return &simpleTestTool{name: name, desc: desc} }
-func (t *simpleTestTool) Name() string { return t.name }
-func (t *simpleTestTool) Description() string { return t.desc }
+func (t *simpleTestTool) Name() string { return t.name }
+func (t *simpleTestTool) Description() string { return t.desc }
func (t *simpleTestTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
return "result: " + args, nil
}
@@ -411,7 +411,7 @@ type simpleEnhancedTestTool struct {
func newTestEnhancedTool(name, desc string) *simpleEnhancedTestTool {
return &simpleEnhancedTestTool{name: name, desc: desc}
}
-func (t *simpleEnhancedTestTool) Name() string { return t.name }
+func (t *simpleEnhancedTestTool) Name() string { return t.name }
func (t *simpleEnhancedTestTool) Description() string { return t.desc }
func (t *simpleEnhancedTestTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
return "plain", nil
diff --git a/internal/harness/core/tool_registry.go b/internal/harness/core/tool_registry.go
index 4ccd276bbd..2e2ddc8d39 100644
--- a/internal/harness/core/tool_registry.go
+++ b/internal/harness/core/tool_registry.go
@@ -11,9 +11,9 @@ import (
// and filtering. It replaces raw []Tool slices for more flexible tool discovery.
type ToolRegistry struct {
mu sync.RWMutex
- tools map[string]Tool // name -> tool
- aliases map[string]string // alias -> canonical name
- category map[string][]string // category -> tool names
+ tools map[string]Tool // name -> tool
+ aliases map[string]string // alias -> canonical name
+ category map[string][]string // category -> tool names
}
// NewToolRegistry creates an empty ToolRegistry.
diff --git a/internal/harness/core/tool_registry_test.go b/internal/harness/core/tool_registry_test.go
index 3e0dfc1930..f481d9e499 100644
--- a/internal/harness/core/tool_registry_test.go
+++ b/internal/harness/core/tool_registry_test.go
@@ -207,9 +207,11 @@ func TestToolRegistry_LookupPanicsForTool(t *testing.T) {
type testPanicTool struct{ name string }
-func (t *testPanicTool) Name() string { return t.name }
+func (t *testPanicTool) Name() string { return t.name }
func (t *testPanicTool) Description() string { return "" }
-func (t *testPanicTool) Invoke(ctx context.Context, s string, opts ...ToolOption) (string, error) { return "", nil }
+func (t *testPanicTool) Invoke(ctx context.Context, s string, opts ...ToolOption) (string, error) {
+ return "", nil
+}
func (t *testPanicTool) Stream(ctx context.Context, s string, opts ...ToolOption) (*schema.StreamReader[string], error) {
return schema.StreamReaderFromArray([]string{""}), nil
}
diff --git a/internal/harness/core/tool_schema.go b/internal/harness/core/tool_schema.go
index 92a35954c9..0294db65bf 100644
--- a/internal/harness/core/tool_schema.go
+++ b/internal/harness/core/tool_schema.go
@@ -212,8 +212,8 @@ type ReflectToolImpl[T any] struct {
info *schema.ToolInfo
}
-func (t *ReflectToolImpl[T]) Name() string { return t.name }
-func (t *ReflectToolImpl[T]) Description() string { return t.desc }
+func (t *ReflectToolImpl[T]) Name() string { return t.name }
+func (t *ReflectToolImpl[T]) Description() string { return t.desc }
func (t *ReflectToolImpl[T]) ToolInfo() *schema.ToolInfo { return t.info }
func (t *ReflectToolImpl[T]) Invoke(ctx context.Context, argsJSON string, opts ...ToolOption) (string, error) {
@@ -272,8 +272,8 @@ type toolWithInfo[T any] struct {
fn func(context.Context, *T) (string, error)
}
-func (t *toolWithInfo[T]) Name() string { return t.info.Name }
-func (t *toolWithInfo[T]) Description() string { return t.info.Description }
+func (t *toolWithInfo[T]) Name() string { return t.info.Name }
+func (t *toolWithInfo[T]) Description() string { return t.info.Description }
func (t *toolWithInfo[T]) ToolInfo() *schema.ToolInfo { return t.info }
func (t *toolWithInfo[T]) Invoke(ctx context.Context, argsJSON string, opts ...ToolOption) (string, error) {
diff --git a/internal/harness/core/tool_schema_test.go b/internal/harness/core/tool_schema_test.go
index bf8bea412c..320045651d 100644
--- a/internal/harness/core/tool_schema_test.go
+++ b/internal/harness/core/tool_schema_test.go
@@ -17,9 +17,9 @@ type weatherArgs struct {
type emptyArgs struct{}
type nestedArgs struct {
- Query string `json:"query" description:"Search query"`
- Page int `json:"page" description:"Page number"`
- Tags []string `json:"tags" description:"Filter tags"`
+ Query string `json:"query" description:"Search query"`
+ Page int `json:"page" description:"Page number"`
+ Tags []string `json:"tags" description:"Filter tags"`
}
// ======================== GenerateToolInfo ========================
diff --git a/internal/harness/core/tools_node.go b/internal/harness/core/tools_node.go
index 9cce2a977d..b0f4d261de 100644
--- a/internal/harness/core/tools_node.go
+++ b/internal/harness/core/tools_node.go
@@ -51,7 +51,7 @@ type ToolsNodeConfig struct {
// collecting results, and applying middleware chains.
type ToolsNode[M MessageType] struct {
config *ToolsNodeConfig
- toolMap map[string]Tool
+ toolMap map[string]Tool
}
// NewToolsNode creates a new ToolsNode with the given configuration.
@@ -325,11 +325,11 @@ func parseToolArgs(argsJSON string, target any) error {
// LoopGuard prevents infinite loops where the model repeatedly calls a tool
// with identical parameters. It tracks consecutive same-args calls per tool.
type LoopGuard struct {
- mu sync.Mutex
- sameArgs map[string]int // key = toolName+"|"+argsHash
- failures map[string]int // key = toolName
- maxSame int
- maxFails int
+ mu sync.Mutex
+ sameArgs map[string]int // key = toolName+"|"+argsHash
+ failures map[string]int // key = toolName
+ maxSame int
+ maxFails int
}
// NewLoopGuard creates a LoopGuard with the given thresholds.
diff --git a/internal/harness/core/tools_node_test.go b/internal/harness/core/tools_node_test.go
index 06870ba07c..03a3fdcabc 100644
--- a/internal/harness/core/tools_node_test.go
+++ b/internal/harness/core/tools_node_test.go
@@ -64,7 +64,7 @@ func TestToolsNode_Execute_ReturnDirectly(t *testing.T) {
exitTool := &mockTool{name: "exit_tool", desc: ""}
tn := NewToolsNode[*schema.Message](&ToolsNodeConfig{
- Tools: []Tool{exitTool},
+ Tools: []Tool{exitTool},
ReturnDirectly: map[string]bool{"exit_tool": true},
})
resp := &schema.Message{
@@ -91,7 +91,9 @@ func TestToolsNode_Execute_ReturnDirectly(t *testing.T) {
}
func TestParseToolArgs_ValidJSON(t *testing.T) {
- var in struct{ Name string `json:"name"` }
+ var in struct {
+ Name string `json:"name"`
+ }
err := parseToolArgs(`{"name":"test"}`, &in)
if err != nil {
t.Fatalf("parseToolArgs: %v", err)
@@ -107,8 +109,8 @@ type failingTool struct {
desc string
}
-func (t *failingTool) Name() string { return t.name }
-func (t *failingTool) Description() string { return t.desc }
+func (t *failingTool) Name() string { return t.name }
+func (t *failingTool) Description() string { return t.desc }
func (t *failingTool) Invoke(ctx context.Context, s string, opts ...toolOption) (string, error) {
return "", errors.New(t.name + " failed")
}
diff --git a/internal/harness/core/utils.go b/internal/harness/core/utils.go
index 205efa20e0..4a3f0606ec 100644
--- a/internal/harness/core/utils.go
+++ b/internal/harness/core/utils.go
@@ -139,7 +139,7 @@ func copyTypedAgentEvent[M MessageType](event *TypedAgentEvent[M]) *TypedAgentEv
cp.Action = &AgentAction{
Exit: event.Action.Exit, Interrupted: event.Action.Interrupted,
TransferToAgent: event.Action.TransferToAgent, BreakLoop: event.Action.BreakLoop,
- CustomizedAction: event.Action.CustomizedAction,
+ CustomizedAction: event.Action.CustomizedAction,
internalInterrupted: event.Action.internalInterrupted,
}
}
@@ -147,7 +147,9 @@ func copyTypedAgentEvent[M MessageType](event *TypedAgentEvent[M]) *TypedAgentEv
}
func setAutomaticClose[M MessageType](event *TypedAgentEvent[M]) {
- if event == nil { return }
+ if event == nil {
+ return
+ }
if event.Output != nil && event.Output.MessageOutput != nil {
if event.Output.MessageOutput.MessageStream != nil {
event.Output.MessageOutput.MessageStream.Close()
@@ -156,7 +158,9 @@ func setAutomaticClose[M MessageType](event *TypedAgentEvent[M]) {
}
func typedSetAutomaticClose[M MessageType](event *TypedAgentEvent[M]) { setAutomaticClose(event) }
func addTypedEvent[M MessageType](s *runSession, event *TypedAgentEvent[M]) {
- if s == nil { return }
+ if s == nil {
+ return
+ }
s.mu.Lock()
defer s.mu.Unlock()
if s.TypedEvents == nil {
diff --git a/internal/harness/core/workflow_complex_test.go b/internal/harness/core/workflow_complex_test.go
index 05c1d0cb15..f9c62d26d6 100644
--- a/internal/harness/core/workflow_complex_test.go
+++ b/internal/harness/core/workflow_complex_test.go
@@ -38,7 +38,7 @@ type workflowNodeToolImpl struct {
}
func (t *workflowNodeToolImpl) Name() string { return t.name }
-func (t *workflowNodeToolImpl) Description() string { return t.desc }
+func (t *workflowNodeToolImpl) Description() string { return t.desc }
func (t *workflowNodeToolImpl) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
t.mu.Lock()
*t.order = append(*t.order, t.name)
@@ -128,9 +128,9 @@ func drainEventsChan(iter *AsyncIterator[*AgentEvent]) <-chan *AgentEvent {
type toolCategory int
const (
- toolCatQuery toolCategory = iota // read-only, fast
- toolCatWrite // write, medium
- toolCatCompute // CPU-intensive, slow
+ toolCatQuery toolCategory = iota // read-only, fast
+ toolCatWrite // write, medium
+ toolCatCompute // CPU-intensive, slow
)
func (c toolCategory) String() string {
@@ -159,8 +159,8 @@ func newTypedTool(nodeID string, cat toolCategory, executed *[]string, mu *sync.
return &typedTool{name: "tool_" + nodeID, desc: fmt.Sprintf("%s tool for %s", cat, nodeID), category: cat, executed: executed, mu: mu}
}
-func (t *typedTool) Name() string { return t.name }
-func (t *typedTool) Description() string { return t.desc }
+func (t *typedTool) Name() string { return t.name }
+func (t *typedTool) Description() string { return t.desc }
func (t *typedTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
result := fmt.Sprintf("%s(%s) executed", t.name, t.category)
t.mu.Lock()
diff --git a/internal/harness/core/workflow_graph.go b/internal/harness/core/workflow_graph.go
index 699e6a4f48..a3289790a1 100644
--- a/internal/harness/core/workflow_graph.go
+++ b/internal/harness/core/workflow_graph.go
@@ -32,10 +32,10 @@ func init() {
// It carries messages between sub-agents and tracks the current position.
type WorkflowGraphState struct {
Messages []*schema.Message
- SubAgentNames []string // names of sub-agents in order
- CurrentStep int // current sub-agent index
- LoopIter int // for loop mode
- MaxLoopIter int // for loop mode
+ SubAgentNames []string // names of sub-agents in order
+ CurrentStep int // current sub-agent index
+ LoopIter int // for loop mode
+ MaxLoopIter int // for loop mode
Done bool
mu sync.Mutex // protects Messages from concurrent access in inline execution
diff --git a/internal/harness/core/workflow_graph_test.go b/internal/harness/core/workflow_graph_test.go
index bcef73881f..1415c6e9d8 100644
--- a/internal/harness/core/workflow_graph_test.go
+++ b/internal/harness/core/workflow_graph_test.go
@@ -1266,7 +1266,7 @@ func TestGraph_50WayFanIn(t *testing.T) {
sg.AddEdge("merge", constants.End)
compiled, err := sg.Compile(
- graph.WithRecursionLimit(branchCount + 10),
+ graph.WithRecursionLimit(branchCount+10),
graph.WithNodeTriggerMode(types.NodeTriggerAllPredecessor),
)
if err != nil {
diff --git a/internal/harness/core/workflow_integration_test.go b/internal/harness/core/workflow_integration_test.go
index e1537d1961..df44d4fed1 100644
--- a/internal/harness/core/workflow_integration_test.go
+++ b/internal/harness/core/workflow_integration_test.go
@@ -82,12 +82,12 @@ func TestWorkflow_StreamCheckpointCancelResume(t *testing.T) {
// ============================================================
type panickingTool struct {
- name string
+ name string
panicOn int32
callNum int32
}
-func (t *panickingTool) Name() string { return t.name }
+func (t *panickingTool) Name() string { return t.name }
func (t *panickingTool) Description() string { return "tool that may panic" }
func (t *panickingTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
@@ -305,7 +305,7 @@ func TestWorkflow_ModelFailover_TimeoutChain(t *testing.T) {
agent := NewReActAgent(&ReActConfig[*schema.Message]{
Model: slowModel,
RetryConfig: &ModelRetryConfig{
- MaxRetries: 3,
+ MaxRetries: 3,
ShouldRetry: func(ctx context.Context, rc *RetryContext) *RetryDecision {
return &RetryDecision{Retry: true}
},
diff --git a/internal/harness/core/workflow_stress_test.go b/internal/harness/core/workflow_stress_test.go
index ef0dc56f12..6b26cb8d5e 100644
--- a/internal/harness/core/workflow_stress_test.go
+++ b/internal/harness/core/workflow_stress_test.go
@@ -101,9 +101,9 @@ func newErrorAgent(name string) Agent {
return &errorAgent{name: name}
}
-func (a *errorAgent) Name(_ context.Context) string { return a.name }
-func (a *errorAgent) Description(_ context.Context) string { return a.name + " error" }
-func (a *errorAgent) GetType() string { return "ErrorAgent" }
+func (a *errorAgent) Name(_ context.Context) string { return a.name }
+func (a *errorAgent) Description(_ context.Context) string { return a.name + " error" }
+func (a *errorAgent) GetType() string { return "ErrorAgent" }
func (a *errorAgent) Run(_ context.Context, _ *AgentInput, _ ...RunOption) *AsyncIterator[*AgentEvent] {
it, gen := NewAsyncIteratorPair[*AgentEvent]()
gen.Send(&AgentEvent{Err: errors.New("intentional agent failure")})
@@ -172,9 +172,9 @@ func TestWorkflow_SequentialCancel_ShouldNotTriggerInterruptCheckpoint(t *testin
// This assertion exposes the bug: if found == true, the cancel was incorrectly
// treated as an interrupt, saving an unnecessary checkpoint.
if found {
- t.Errorf("BUG: cancel in sequential workflow saved a checkpoint. "+
- "cancelTransition uses Interrupted action instead of CancelError, "+
- "so the upper AgentLoop treats cancel as a business interrupt and saves checkpoint. "+
+ t.Errorf("BUG: cancel in sequential workflow saved a checkpoint. " +
+ "cancelTransition uses Interrupted action instead of CancelError, " +
+ "so the upper AgentLoop treats cancel as a business interrupt and saves checkpoint. " +
"Cancel should NOT produce an interrupt checkpoint.")
}
t.Logf("Cancel checkpoint found=%v (expected false if cancel is clean)", found)
@@ -257,7 +257,7 @@ func TestFlow_TransferLoop_ContextCancel(t *testing.T) {
case <-done:
// Agent terminated cleanly
case <-time.After(time.Second * 5):
- t.Errorf("BUG: agent did not terminate within 5s after context cancel. "+
+ t.Errorf("BUG: agent did not terminate within 5s after context cancel. " +
"flow.go runLoop may not check context cancellation, causing goroutine leak")
}
}
@@ -449,8 +449,8 @@ func TestReAct_MaxIterationExceeded_SkipsAfterAgent(t *testing.T) {
}
if !afterAgentCalled.Load() {
- t.Errorf("BUG: AfterAgent middleware not called after max iteration exceeded. "+
- "buildReActRunFunc returns early on line 94, skipping runAfterAgent. "+
+ t.Errorf("BUG: AfterAgent middleware not called after max iteration exceeded. " +
+ "buildReActRunFunc returns early on line 94, skipping runAfterAgent. " +
"Middleware cleanup/hooks are missed.")
} else {
t.Log("AfterAgent middleware was called (pass)")
@@ -600,8 +600,8 @@ func TestWorkflow_Sequential_LastEventWithoutActionIsDropped(t *testing.T) {
}
if len(events) == 0 {
- t.Errorf("BUG: no events received from sequential workflow. "+
- "drainEvents in runSeq returns nil when the last event has no Action, "+
+ t.Errorf("BUG: no events received from sequential workflow. " +
+ "drainEvents in runSeq returns nil when the last event has no Action, " +
"so the final message output is dropped by runSeq (it's not forwarded to gen).")
} else {
t.Logf("Received %d events (first is probably the dropped one)", len(events))
@@ -797,9 +797,9 @@ func TestFlow_SetSubAgents_DoesNotPopulateSubAgents(t *testing.T) {
if len(fa.subAgents) > 0 {
t.Logf("subAgents populated: %d (unexpected but OK)", len(fa.subAgents))
} else {
- t.Errorf("BUG: SetSubAgents does not populate flowAgent.subAgents. "+
- "The sub-agents are set on the returned ResumableAgent but not on "+
- "the original flowAgent. This causes inconsistency when flowAgent.Run() "+
+ t.Errorf("BUG: SetSubAgents does not populate flowAgent.subAgents. " +
+ "The sub-agents are set on the returned ResumableAgent but not on " +
+ "the original flowAgent. This causes inconsistency when flowAgent.Run() " +
"tries to find sub-agents via getAgent().")
}
}
@@ -875,7 +875,7 @@ type delayedTool struct {
mu *sync.Mutex
}
-func (t *delayedTool) Name() string { return t.inner.Name() }
+func (t *delayedTool) Name() string { return t.inner.Name() }
func (t *delayedTool) Description() string { return t.inner.Description() }
func (t *delayedTool) Invoke(ctx context.Context, args string, opts ...ToolOption) (string, error) {
time.Sleep(t.delay)
diff --git a/internal/harness/graph/channels/barrier.go b/internal/harness/graph/channels/barrier.go
index 0b87120514..f67cb584fc 100644
--- a/internal/harness/graph/channels/barrier.go
+++ b/internal/harness/graph/channels/barrier.go
@@ -215,7 +215,7 @@ func NewNamedBarrierValueAfterFinish(typ interface{}, waitFor []string) *NamedBa
BaseChannel: BaseChannel{Typ: typ},
names: names,
seen: make(map[string]bool),
- finished: false,
+ finished: false,
}
}
@@ -395,14 +395,14 @@ type LastValueAfterFinish struct {
BaseChannel
value interface{}
finished bool
- mu sync.RWMutex
+ mu sync.RWMutex
}
// NewLastValueAfterFinish creates a new LastValueAfterFinish channel.
func NewLastValueAfterFinish(typ interface{}) *LastValueAfterFinish {
return &LastValueAfterFinish{
BaseChannel: BaseChannel{Typ: typ},
- value: Missing,
+ value: Missing,
finished: false,
}
}
diff --git a/internal/harness/graph/channels/base.go b/internal/harness/graph/channels/base.go
index e602e2db5a..294de7a080 100644
--- a/internal/harness/graph/channels/base.go
+++ b/internal/harness/graph/channels/base.go
@@ -19,11 +19,11 @@ func (m *missingSentinel) String() string {
}
// IsMissing checks if a value is the Missing sentinel.
-func IsMissing(v interface{}) bool {
- if v == nil {
+func IsMissing(val any) bool {
+ if val == nil {
return false
}
- _, ok := v.(*missingSentinel)
+ _, ok := val.(*missingSentinel)
return ok
}
diff --git a/internal/harness/graph/channels/binop.go b/internal/harness/graph/channels/binop.go
index 2e4960391b..dd3707ae8e 100644
--- a/internal/harness/graph/channels/binop.go
+++ b/internal/harness/graph/channels/binop.go
@@ -24,10 +24,10 @@ func NewBinaryOperatorAggregate(typ interface{}, operator BinaryOperator) *Binar
BaseChannel: BaseChannel{Typ: typ},
operator: operator,
}
-
+
// Try to initialize with zero value
c.value = createZeroValue(typ)
-
+
return c
}
@@ -37,9 +37,9 @@ func createZeroValue(typ interface{}) (result interface{}) {
if typ == nil {
return
}
-
+
rt := reflect.TypeOf(typ)
-
+
// Handle special collection types
switch rt.String() {
case "[]interface {}":
@@ -47,27 +47,27 @@ func createZeroValue(typ interface{}) (result interface{}) {
case "map[string]interface {}":
return make(map[string]interface{})
}
-
+
// Try to create instance
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
-
+
if rt.Kind() == reflect.Slice {
return reflect.MakeSlice(rt, 0, 0).Interface()
}
-
+
if rt.Kind() == reflect.Map {
return reflect.MakeMap(rt).Interface()
}
-
+
// Use named return so the deferred recovery can return Missing.
defer func() {
if r := recover(); r != nil {
result = Missing
}
}()
-
+
// Create a zero value using reflect.Zero
zero := reflect.Zero(rt)
result = zero.Interface()
@@ -92,7 +92,7 @@ func isOverwrite(value interface{}) (bool, interface{}) {
if value == nil {
return false, nil
}
-
+
// Check for Overwrite type
type overwriter interface {
GetValue() interface{}
@@ -100,7 +100,7 @@ func isOverwrite(value interface{}) (bool, interface{}) {
if ow, ok := value.(overwriter); ok {
return true, ow.GetValue()
}
-
+
// Check for map with __overwrite__ key
if m, ok := value.(map[string]interface{}); ok {
if len(m) == 1 {
@@ -109,7 +109,7 @@ func isOverwrite(value interface{}) (bool, interface{}) {
}
}
}
-
+
return false, nil
}
@@ -118,13 +118,13 @@ func (c *BinaryOperatorAggregate) Update(values []interface{}) (bool, error) {
if len(values) == 0 {
return false, nil
}
-
+
// Initialize with first value if empty
if IsMissing(c.value) {
c.value = values[0]
values = values[1:]
}
-
+
seenOverwrite := false
for _, value := range values {
isOver, overwriteValue := isOverwrite(value)
@@ -138,12 +138,12 @@ func (c *BinaryOperatorAggregate) Update(values []interface{}) (bool, error) {
seenOverwrite = true
continue
}
-
+
if !seenOverwrite {
c.value = c.operator(c.value, value)
}
}
-
+
return true, nil
}
diff --git a/internal/harness/graph/channels/channels_test.go b/internal/harness/graph/channels/channels_test.go
index 0347fa8e20..4d266a3693 100644
--- a/internal/harness/graph/channels/channels_test.go
+++ b/internal/harness/graph/channels/channels_test.go
@@ -280,10 +280,14 @@ func TestBaseChannelGetVersion(t *testing.T) {
// Concurrent read/write should not race (atomic).
done := make(chan struct{})
go func() {
- for i := 0; i < 100; i++ { ch.SetVersion(i) }
+ for i := 0; i < 100; i++ {
+ ch.SetVersion(i)
+ }
close(done)
}()
- for i := 0; i < 100; i++ { _ = ch.GetVersion() }
+ for i := 0; i < 100; i++ {
+ _ = ch.GetVersion()
+ }
<-done
}
diff --git a/internal/harness/graph/channels/reducer.go b/internal/harness/graph/channels/reducer.go
index 19b2173826..3d1bad8d27 100644
--- a/internal/harness/graph/channels/reducer.go
+++ b/internal/harness/graph/channels/reducer.go
@@ -165,4 +165,4 @@ var (
}
return update
}
-)
\ No newline at end of file
+)
diff --git a/internal/harness/graph/channels/topic.go b/internal/harness/graph/channels/topic.go
index d0d6f8ff87..027fd3993b 100644
--- a/internal/harness/graph/channels/topic.go
+++ b/internal/harness/graph/channels/topic.go
@@ -7,7 +7,7 @@ import (
// Topic is a configurable PubSub Topic.
type Topic struct {
BaseChannel
- values []interface{}
+ values []interface{}
accumulate bool
}
diff --git a/internal/harness/graph/checkpoint/checkpoint.go b/internal/harness/graph/checkpoint/checkpoint.go
index 4e466df877..13476ad662 100644
--- a/internal/harness/graph/checkpoint/checkpoint.go
+++ b/internal/harness/graph/checkpoint/checkpoint.go
@@ -45,11 +45,11 @@ type CheckpointMetadata struct {
type CheckpointSource string
const (
- SourceNode CheckpointSource = "node" // Created after node execution
- SourceEdge CheckpointSource = "edge" // Created after edge traversal
+ SourceNode CheckpointSource = "node" // Created after node execution
+ SourceEdge CheckpointSource = "edge" // Created after edge traversal
SourceInterrupt CheckpointSource = "interrupt" // Created on interrupt
- SourceManual CheckpointSource = "manual" // Manually created
- SourceResume CheckpointSource = "resume" // Created on resume
+ SourceManual CheckpointSource = "manual" // Manually created
+ SourceResume CheckpointSource = "resume" // Created on resume
)
// PendingWrite represents a write that hasn't been applied yet.
@@ -106,7 +106,7 @@ func NewCheckpoint(threadID string, step int) *Checkpoint {
return &Checkpoint{
ID: id,
Version: 0,
- ChannelVersions: make(map[string]int),
+ ChannelVersions: make(map[string]int),
VersionsSeen: make(map[string]map[string]int),
State: make(map[string]interface{}),
PendingWrites: make([]PendingWrite, 0),
@@ -142,12 +142,12 @@ func (c *Checkpoint) Clone() *Checkpoint {
Metadata: make(map[string]interface{}),
},
}
-
+
// Copy channel versions
for k, v := range c.ChannelVersions {
clone.ChannelVersions[k] = v
}
-
+
// Copy versions seen
for node, versions := range c.VersionsSeen {
clone.VersionsSeen[node] = make(map[string]int)
@@ -155,25 +155,25 @@ func (c *Checkpoint) Clone() *Checkpoint {
clone.VersionsSeen[node][k] = v
}
}
-
+
// Copy state
for k, v := range c.State {
clone.State[k] = deepCopy(v)
}
-
-// Deep-copy pending writes — each Value must be independently copied so that
-// mutating the clone's Value never affects the original.
-clone.PendingWrites = make([]PendingWrite, len(c.PendingWrites))
-for i, pw := range c.PendingWrites {
- clone.PendingWrites[i] = pw
- clone.PendingWrites[i].Value = deepCopy(pw.Value)
-}
-
- // Copy metadata
+
+ // Deep-copy pending writes — each Value must be independently copied so that
+ // mutating the clone's Value never affects the original.
+ clone.PendingWrites = make([]PendingWrite, len(c.PendingWrites))
+ for i, pw := range c.PendingWrites {
+ clone.PendingWrites[i] = pw
+ clone.PendingWrites[i].Value = deepCopy(pw.Value)
+ }
+
+ // Copy metadata — deep copy to avoid shared maps/slices.
for k, v := range c.Metadata.Metadata {
- clone.Metadata.Metadata[k] = v
+ clone.Metadata.Metadata[k] = deepCopy(v)
}
-
+
return clone
}
@@ -218,17 +218,17 @@ func (c *Checkpoint) ClearPendingWrites() {
// ToMap converts the checkpoint to a map for storage.
func (c *Checkpoint) ToMap() map[string]interface{} {
result := make(map[string]interface{})
-
+
result["id"] = c.ID
result["version"] = c.Version
result["parent_id"] = c.ParentID
-
+
channelVersions := make(map[string]int)
for k, v := range c.ChannelVersions {
channelVersions[k] = v
}
result["channel_versions"] = channelVersions
-
+
versionsSeen := make(map[string]map[string]int)
for node, versions := range c.VersionsSeen {
versionsSeen[node] = make(map[string]int)
@@ -237,13 +237,13 @@ func (c *Checkpoint) ToMap() map[string]interface{} {
}
}
result["versions_seen"] = versionsSeen
-
+
state := make(map[string]interface{})
for k, v := range c.State {
state[k] = deepCopy(v)
}
result["state"] = state
-
+
pendingWrites := make([]map[string]interface{}, len(c.PendingWrites))
for i, pw := range c.PendingWrites {
pendingWrites[i] = map[string]interface{}{
@@ -254,7 +254,7 @@ func (c *Checkpoint) ToMap() map[string]interface{} {
}
}
result["pending_writes"] = pendingWrites
-
+
metadata := map[string]interface{}{
"id": c.Metadata.ID,
"parent_id": c.Metadata.ParentID,
@@ -267,7 +267,7 @@ func (c *Checkpoint) ToMap() map[string]interface{} {
metadata[k] = v
}
result["metadata"] = metadata
-
+
return result
}
@@ -277,12 +277,12 @@ func FromMap(data map[string]interface{}) (*Checkpoint, error) {
ID: getString(data, "id"),
ParentID: getString(data, "parent_id"),
Version: getInt(data, "version", 0),
- ChannelVersions: make(map[string]int),
+ ChannelVersions: make(map[string]int),
VersionsSeen: make(map[string]map[string]int),
State: make(map[string]interface{}),
PendingWrites: make([]PendingWrite, 0),
}
-
+
// Parse channel versions
if cv, ok := data["channel_versions"].(map[string]interface{}); ok {
for k, v := range cv {
@@ -291,7 +291,7 @@ func FromMap(data map[string]interface{}) (*Checkpoint, error) {
}
}
}
-
+
// Parse versions seen
if vs, ok := data["versions_seen"].(map[string]interface{}); ok {
for node, versions := range vs {
@@ -305,14 +305,14 @@ func FromMap(data map[string]interface{}) (*Checkpoint, error) {
}
}
}
-
+
// Parse state
if state, ok := data["state"].(map[string]interface{}); ok {
for k, v := range state {
c.State[k] = deepCopy(v)
}
}
-
+
// Parse pending writes
if pws, ok := data["pending_writes"].([]interface{}); ok {
for _, pw := range pws {
@@ -326,24 +326,24 @@ func FromMap(data map[string]interface{}) (*Checkpoint, error) {
}
}
}
-
+
// Parse metadata
if md, ok := data["metadata"].(map[string]interface{}); ok {
c.Metadata = CheckpointMetadata{
- ID: getString(md, "id"),
- ParentID: getString(md, "parent_id"),
- ThreadID: getString(md, "thread_id"),
- Step: getInt(md, "step", 0),
- Source: CheckpointSource(getString(md, "source")),
- Metadata: make(map[string]interface{}),
+ ID: getString(md, "id"),
+ ParentID: getString(md, "parent_id"),
+ ThreadID: getString(md, "thread_id"),
+ Step: getInt(md, "step", 0),
+ Source: CheckpointSource(getString(md, "source")),
+ Metadata: make(map[string]interface{}),
}
-
+
if createdAtStr := getString(md, "created_at"); createdAtStr != "" {
if t, err := time.Parse(time.RFC3339Nano, createdAtStr); err == nil {
c.Metadata.CreatedAt = t
}
}
-
+
// Copy custom metadata
for k, v := range md {
if k != "id" && k != "parent_id" && k != "thread_id" && k != "step" && k != "created_at" && k != "source" {
@@ -351,28 +351,28 @@ func FromMap(data map[string]interface{}) (*Checkpoint, error) {
}
}
}
-
+
return c, nil
}
// Helper functions
-func getString(m map[string]interface{}, key string) string {
- if v, ok := m[key].(string); ok {
- return v
+func getString(data map[string]any, key string) string {
+ if val, ok := data[key].(string); ok {
+ return val
}
return ""
}
-func getInt(m map[string]interface{}, key string, defaultVal int) int {
- if v, ok := m[key].(float64); ok {
- return int(v)
+func getInt(data map[string]any, key string, defaultVal int) int {
+ if val, ok := data[key].(float64); ok {
+ return int(val)
}
return defaultVal
}
-func getBool(m map[string]interface{}, key string, defaultVal bool) bool {
- if v, ok := m[key].(bool); ok {
- return v
+func getBool(data map[string]any, key string, defaultVal bool) bool {
+ if val, ok := data[key].(bool); ok {
+ return val
}
return defaultVal
}
@@ -394,7 +394,7 @@ func NewCheckpointTuple(config *types.RunnableConfig, checkpoint *Checkpoint, pa
if config == nil {
config = types.NewRunnableConfig()
}
-
+
metadata := make(map[string]interface{})
if checkpoint != nil {
metadata["id"] = checkpoint.ID
@@ -404,12 +404,12 @@ func NewCheckpointTuple(config *types.RunnableConfig, checkpoint *Checkpoint, pa
metadata["source"] = string(checkpoint.Metadata.Source)
metadata["created_at"] = checkpoint.Metadata.CreatedAt
}
-
+
return &CheckpointTuple{
Config: config,
Checkpoint: checkpoint,
ParentConfig: parentConfig,
- Metadata: metadata,
+ Metadata: metadata,
}
}
@@ -440,11 +440,11 @@ type CheckpointListFilter struct {
// CheckpointListResponse represents a checkpoint in list results.
type CheckpointListResponse struct {
- ID string
- ThreadID string
- Version int
- CreatedAt time.Time
- Metadata map[string]interface{}
+ ID string
+ ThreadID string
+ Version int
+ CreatedAt time.Time
+ Metadata map[string]interface{}
}
// LineageEntry represents an entry in a checkpoint lineage.
@@ -455,7 +455,7 @@ type LineageEntry struct {
// VersionConflictError is raised when there is a version conflict.
type VersionConflictError struct {
- CurrentVersion int
+ CurrentVersion int
ExpectedVersion int
CheckpointID string
ThreadID string
@@ -475,7 +475,7 @@ func (e *VersionConflictError) Error() string {
type CheckpointManager struct {
mu sync.RWMutex
checkpoints map[string][]*Checkpoint // threadID -> checkpoints
- maxVersions int // Maximum versions to keep per thread
+ maxVersions int // Maximum versions to keep per thread
}
// NewCheckpointManager creates a new checkpoint manager.
@@ -614,12 +614,12 @@ func (cm *CheckpointManager) PutWrites(ctx context.Context, config *types.Runnab
func (cm *CheckpointManager) Load(ctx context.Context, threadID string) (*Checkpoint, error) {
cm.mu.RLock()
defer cm.mu.RUnlock()
-
+
checkpoints := cm.checkpoints[threadID]
if len(checkpoints) == 0 {
return nil, nil
}
-
+
return checkpoints[len(checkpoints)-1].Clone(), nil
}
@@ -627,7 +627,7 @@ func (cm *CheckpointManager) Load(ctx context.Context, threadID string) (*Checkp
func (cm *CheckpointManager) LoadByCheckpointID(ctx context.Context, checkpointID string) (*Checkpoint, error) {
cm.mu.RLock()
defer cm.mu.RUnlock()
-
+
for _, checkpoints := range cm.checkpoints {
for _, cp := range checkpoints {
if cp.ID == checkpointID {
@@ -635,7 +635,7 @@ func (cm *CheckpointManager) LoadByCheckpointID(ctx context.Context, checkpointI
}
}
}
-
+
return nil, fmt.Errorf("checkpoint not found: %s", checkpointID)
}
@@ -643,23 +643,23 @@ func (cm *CheckpointManager) LoadByCheckpointID(ctx context.Context, checkpointI
func (cm *CheckpointManager) List(ctx context.Context, threadID string, limit int) ([]*Checkpoint, error) {
cm.mu.RLock()
defer cm.mu.RUnlock()
-
+
checkpoints := cm.checkpoints[threadID]
if len(checkpoints) == 0 {
return nil, nil
}
-
+
if limit <= 0 || limit > len(checkpoints) {
limit = len(checkpoints)
}
-
+
// Return most recent checkpoints first
result := make([]*Checkpoint, limit)
start := len(checkpoints) - limit
for i := 0; i < limit; i++ {
result[i] = checkpoints[start+i].Clone()
}
-
+
return result, nil
}
@@ -788,7 +788,7 @@ func (cm *CheckpointManager) GetVersion(ctx context.Context, threadID string, ve
func (cm *CheckpointManager) Delete(ctx context.Context, checkpointID string) error {
cm.mu.Lock()
defer cm.mu.Unlock()
-
+
for threadID, checkpoints := range cm.checkpoints {
for i, cp := range checkpoints {
if cp.ID == checkpointID {
@@ -798,7 +798,7 @@ func (cm *CheckpointManager) Delete(ctx context.Context, checkpointID string) er
}
}
}
-
+
return fmt.Errorf("checkpoint not found: %s", checkpointID)
}
@@ -806,7 +806,7 @@ func (cm *CheckpointManager) Delete(ctx context.Context, checkpointID string) er
func (cm *CheckpointManager) ClearThread(ctx context.Context, threadID string) error {
cm.mu.Lock()
defer cm.mu.Unlock()
-
+
delete(cm.checkpoints, threadID)
return nil
}
@@ -815,7 +815,7 @@ func (cm *CheckpointManager) ClearThread(ctx context.Context, threadID string) e
func (cm *CheckpointManager) ClearAll(ctx context.Context) error {
cm.mu.Lock()
defer cm.mu.Unlock()
-
+
cm.checkpoints = make(map[string][]*Checkpoint)
return nil
}
@@ -827,25 +827,25 @@ func (cm *CheckpointManager) ClearAll(ctx context.Context) error {
// On serialization failure (channels, functions, circular references),
// returns nil rather than a shared reference that would silently
// propagate mutations between checkpoint and its clone.
-func deepCopy(v interface{}) interface{} {
- if v == nil {
+func deepCopy(val any) any {
+ if val == nil {
return nil
}
-
+
// Handle common collection types with dedicated helpers
- if m, ok := v.(map[string]interface{}); ok {
+ if m, ok := val.(map[string]any); ok {
return deepCopyMap(m)
}
- if s, ok := v.([]interface{}); ok {
- return deepCopySlice(s)
+ if slice, ok := val.([]any); ok {
+ return deepCopySlice(slice)
}
-
+
// For all other types, JSON round-trip provides reliable deep copy.
- data, err := json.Marshal(v)
+ data, err := json.Marshal(val)
if err != nil {
return nil
}
- var result interface{}
+ var result any
if err := json.Unmarshal(data, &result); err != nil {
return nil
}
@@ -853,19 +853,19 @@ func deepCopy(v interface{}) interface{} {
}
// deepCopyMap creates a deep copy of a map.
-func deepCopyMap(m map[string]interface{}) map[string]interface{} {
- result := make(map[string]interface{}, len(m))
- for k, v := range m {
- result[k] = deepCopy(v)
+func deepCopyMap(src map[string]any) map[string]any {
+ result := make(map[string]any, len(src))
+ for key, val := range src {
+ result[key] = deepCopy(val)
}
return result
}
// deepCopySlice creates a deep copy of a slice.
-func deepCopySlice(s []interface{}) []interface{} {
- result := make([]interface{}, len(s))
- for i, v := range s {
- result[i] = deepCopy(v)
+func deepCopySlice(slice []any) []any {
+ result := make([]any, len(slice))
+ for i, val := range slice {
+ result[i] = deepCopy(val)
}
return result
}
diff --git a/internal/harness/graph/checkpoint/checkpoint_test.go b/internal/harness/graph/checkpoint/checkpoint_test.go
index ba2c67d753..05fb6baebc 100644
--- a/internal/harness/graph/checkpoint/checkpoint_test.go
+++ b/internal/harness/graph/checkpoint/checkpoint_test.go
@@ -218,7 +218,7 @@ func TestMemorySaverCheckpointID(t *testing.T) {
"step": 1,
}
config := map[string]interface{}{
- "thread_id": threadID,
+ "thread_id": threadID,
"checkpoint_id": checkpointID,
}
diff --git a/internal/harness/graph/checkpoint/memory.go b/internal/harness/graph/checkpoint/memory.go
index 2c46db862a..523b151f87 100644
--- a/internal/harness/graph/checkpoint/memory.go
+++ b/internal/harness/graph/checkpoint/memory.go
@@ -121,9 +121,9 @@ func (s *MemorySaver) List(ctx context.Context, config map[string]interface{}, l
result = append(result, map[string]interface{}{
constants.ConfigKeyCheckpointID: entry.ID,
constants.ConfigKeyThreadID: entry.ThreadID,
- "metadata": deepCopyMap(entry.Metadata),
- "created_at": entry.CreatedAt,
- "parent_id": entry.ParentID,
+ "metadata": deepCopyMap(entry.Metadata),
+ "created_at": entry.CreatedAt,
+ "parent_id": entry.ParentID,
})
}
@@ -171,5 +171,3 @@ type CheckpointState struct {
Checkpoint map[string]interface{}
Metadata map[string]interface{}
}
-
-
diff --git a/internal/harness/graph/errors/errors.go b/internal/harness/graph/errors/errors.go
index a452438fef..aa57e74e5c 100644
--- a/internal/harness/graph/errors/errors.go
+++ b/internal/harness/graph/errors/errors.go
@@ -73,27 +73,27 @@ func NewErrorContext(code ErrorCode, message string, cause error) *ErrorContext
// Error returns the error message with context.
func (ec *ErrorContext) Error() string {
var sb strings.Builder
-
+
sb.WriteString(fmt.Sprintf("[%s] %s", ec.ErrorCode, ec.Message))
-
+
if ec.Cause != nil {
sb.WriteString(fmt.Sprintf("\nCaused by: %s", ec.Cause.Error()))
}
-
+
if len(ec.StackTrace) > 0 {
sb.WriteString("\nStack trace:")
for _, frame := range ec.StackTrace {
sb.WriteString(fmt.Sprintf("\n %s", frame))
}
}
-
+
if len(ec.Metadata) > 0 {
sb.WriteString("\nMetadata:")
for k, v := range ec.Metadata {
sb.WriteString(fmt.Sprintf("\n %s: %v", k, v))
}
}
-
+
return sb.String()
}
@@ -145,7 +145,7 @@ func WrapError(err error, code ErrorCode, message string) error {
if err == nil {
return nil
}
-
+
// If it's already an ErrorContext, just add to it
if ec, ok := err.(*ErrorContext); ok {
return &ErrorContext{
@@ -156,7 +156,7 @@ func WrapError(err error, code ErrorCode, message string) error {
Metadata: make(map[string]interface{}),
}
}
-
+
return NewErrorContext(code, message, err)
}
@@ -165,12 +165,12 @@ func GetErrorCode(err error) ErrorCode {
if err == nil {
return ""
}
-
+
// Check for ErrorContext
if ec, ok := err.(*ErrorContext); ok {
return ec.ErrorCode
}
-
+
// Check for specific error types
if IsGraphRecursionError(err) {
return ErrorCodeGraphRecursionLimit
@@ -181,7 +181,7 @@ func GetErrorCode(err error) ErrorCode {
if IsParentCommand(err) {
return ErrorCodeInvalidConcurrentGraphUpdate
}
-
+
return ""
}
@@ -190,11 +190,11 @@ func GetErrorStack(err error) []string {
if err == nil {
return nil
}
-
+
if ec, ok := err.(*ErrorContext); ok {
return ec.StackTrace
}
-
+
return nil
}
@@ -203,25 +203,25 @@ func FormatError(err error) string {
if err == nil {
return ""
}
-
+
var sb strings.Builder
-
+
current := err
depth := 0
for current != nil && depth < 10 { // Prevent infinite loops
prefix := strings.Repeat(" ", depth)
sb.WriteString(fmt.Sprintf("%s%s\n", prefix, current.Error()))
-
+
// Check for wrapped error
if unwrapped := fmt.Sprintf("%v", err); unwrapped != current.Error() {
current = fmt.Errorf("%s", unwrapped)
} else {
current = nil
}
-
+
depth++
}
-
+
return sb.String()
}
@@ -230,11 +230,11 @@ func ChainError(base error, newErr error) error {
if newErr == nil {
return base
}
-
+
if base == nil {
return newErr
}
-
+
return fmt.Errorf("%s: %w", newErr, base)
}
diff --git a/internal/harness/graph/errors/errors_test.go b/internal/harness/graph/errors/errors_test.go
index 13e1f96754..338e8cdb9e 100644
--- a/internal/harness/graph/errors/errors_test.go
+++ b/internal/harness/graph/errors/errors_test.go
@@ -8,9 +8,9 @@ import (
func TestErrorCodeConstants(t *testing.T) {
// Test that all error codes are defined
tests := []struct {
- name string
- code ErrorCode
- expected string
+ name string
+ code ErrorCode
+ expected string
}{
{"GraphRecursionLimit", ErrorCodeGraphRecursionLimit, "GRAPH_RECURSION_LIMIT"},
{"InvalidConcurrentGraphUpdate", ErrorCodeInvalidConcurrentGraphUpdate, "INVALID_CONCURRENT_GRAPH_UPDATE"},
diff --git a/internal/harness/graph/graph/checkpoint_recovery_test.go b/internal/harness/graph/graph/checkpoint_recovery_test.go
index 4d17a29747..b95f363acc 100644
--- a/internal/harness/graph/graph/checkpoint_recovery_test.go
+++ b/internal/harness/graph/graph/checkpoint_recovery_test.go
@@ -150,7 +150,7 @@ func TestCheckpoint_ConcurrentSaves(t *testing.T) {
for i := 0; i < threads; i++ {
go func(id int) {
config := map[string]interface{}{
- "thread_id": "concurrent-save",
+ "thread_id": "concurrent-save",
"checkpoint_id": "cp-" + string(rune('A'+id)),
}
cp := map[string]interface{}{
diff --git a/internal/harness/graph/graph/compiled.go b/internal/harness/graph/graph/compiled.go
index 97e89763f1..da0f21d0b1 100644
--- a/internal/harness/graph/graph/compiled.go
+++ b/internal/harness/graph/graph/compiled.go
@@ -15,30 +15,30 @@ import (
// This corresponds to Python's CompiledStateGraph in graph/state.py
type CompiledStateGraph struct {
*CompiledGraph
-
+
// subgraphs maps subgraph names to their compiled graphs
subgraphs map[string]*CompiledStateGraph
-
+
// parent is the parent graph (nil for root graph)
parent *CompiledStateGraph
-
+
// namespace is the checkpoint namespace for this graph
namespace string
-
+
// checkpointMap maps parent checkpoint IDs to child checkpoint IDs
checkpointMap map[string]string
-
+
mu sync.RWMutex
}
// NewCompiledStateGraph creates a new compiled state graph.
func NewCompiledStateGraph(base *CompiledGraph) *CompiledStateGraph {
return &CompiledStateGraph{
- CompiledGraph: base,
- subgraphs: make(map[string]*CompiledStateGraph),
- parent: nil,
- namespace: "",
- checkpointMap: make(map[string]string),
+ CompiledGraph: base,
+ subgraphs: make(map[string]*CompiledStateGraph),
+ parent: nil,
+ namespace: "",
+ checkpointMap: make(map[string]string),
}
}
@@ -141,13 +141,13 @@ func (c *CompiledStateGraph) MigrateCheckpoint(
if c.parent == nil {
return "", fmt.Errorf("no parent graph to migrate to")
}
-
+
// Get parent checkpoint ID from map
parentCheckpointID, exists := c.checkpointMap[checkpointID]
if !exists {
return "", fmt.Errorf("no parent checkpoint mapping found for %s", checkpointID)
}
-
+
return parentCheckpointID, nil
}
@@ -159,7 +159,7 @@ func (c *CompiledStateGraph) MigrateCheckpoint(
// Create new checkpoint ID for subgraph
newCheckpointID := generateCheckpointID()
-
+
// Store mapping
subgraph.checkpointMap[newCheckpointID] = checkpointID
c.checkpointMap[checkpointID] = newCheckpointID
diff --git a/internal/harness/graph/graph/graph.go b/internal/harness/graph/graph/graph.go
index 5b9b4a95e0..847ae9af39 100644
--- a/internal/harness/graph/graph/graph.go
+++ b/internal/harness/graph/graph/graph.go
@@ -26,7 +26,7 @@ type Node struct {
// Triggers lists channel names this node reads from.
Triggers []string
// Writes lists channel names this node writes to.
- Writes []string
+ Writes []string
// RetryPolicy configures automatic retry for this node.
RetryPolicy *types.RetryPolicy
// Tags are opaque labels for filtering and debugging.
@@ -267,9 +267,9 @@ type NodeOptions struct {
Metadata map[string]interface{}
Triggers []string
Writes []string
- FieldMapping []FieldMapping // field-level routing for this node's output
- StatePre types.NodeFunc // transforms state BEFORE node execution
- StatePost types.NodeFunc // transforms state AFTER node execution
+ FieldMapping []FieldMapping // field-level routing for this node's output
+ StatePre types.NodeFunc // transforms state BEFORE node execution
+ StatePost types.NodeFunc // transforms state AFTER node execution
}
// WithStatePreHandler wraps the node with a pre-execution state transform.
@@ -307,14 +307,14 @@ func (g *StateGraph) AddEdge(from, to string) error {
if _, ok := g.nodes[to]; !ok && to != constants.End {
return &errors.NodeNotFoundError{NodeName: to}
}
-
+
g.edges = append(g.edges, &Edge{From: from, To: to})
-
+
// If this is an edge from Start, set entry point to the target node
if from == constants.Start {
g.entryPoint = to
}
-
+
// If this is an edge to End, set the source as a finish point
if to == constants.End {
found := false
@@ -328,7 +328,7 @@ func (g *StateGraph) AddEdge(from, to string) error {
g.finishPoints = append(g.finishPoints, from)
}
}
-
+
return nil
}
@@ -337,14 +337,14 @@ func (g *StateGraph) AddConditionalEdges(from string, condition types.EdgeFunc,
if _, ok := g.nodes[from]; !ok {
return &errors.NodeNotFoundError{NodeName: from}
}
-
+
// Validate all targets exist
for _, target := range mapping {
if _, ok := g.nodes[target]; !ok && target != constants.End {
return &errors.NodeNotFoundError{NodeName: target}
}
}
-
+
g.conditionalEdges = append(g.conditionalEdges, &ConditionalEdge{
From: from,
Condition: condition,
@@ -358,7 +358,7 @@ func (g *StateGraph) AddBranch(from string, condition types.EdgeFunc, then func(
if _, ok := g.nodes[from]; !ok {
return &errors.NodeNotFoundError{NodeName: from}
}
-
+
g.branches = append(g.branches, &Branch{
From: from,
Condition: condition,
@@ -472,11 +472,11 @@ func (g *StateGraph) Validate() error {
if g.entryPoint == "" {
return fmt.Errorf("no entry point set")
}
-
+
if len(g.finishPoints) == 0 {
return fmt.Errorf("no finish points set")
}
-
+
// Check that all nodes are reachable
reachable := g.computeReachable()
for name := range g.nodes {
@@ -484,12 +484,12 @@ func (g *StateGraph) Validate() error {
return fmt.Errorf("node %s is not reachable from entry point", name)
}
}
-
+
// Validate state schema
if err := g.ValidateStateSchema(); err != nil {
return fmt.Errorf("state schema validation failed: %w", err)
}
-
+
return nil
}
@@ -499,14 +499,14 @@ func (g *StateGraph) computeReachable() map[string]bool {
if g.entryPoint == "" {
return reachable
}
-
+
queue := []string{g.entryPoint}
reachable[g.entryPoint] = true
-
+
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
-
+
// Follow regular edges
for _, edge := range g.edges {
if edge.From == current && !reachable[edge.To] && edge.To != constants.End {
@@ -514,7 +514,7 @@ func (g *StateGraph) computeReachable() map[string]bool {
queue = append(queue, edge.To)
}
}
-
+
// Follow conditional edges - all targets are potentially reachable
for _, condEdge := range g.conditionalEdges {
if condEdge.From == current {
@@ -526,10 +526,10 @@ func (g *StateGraph) computeReachable() map[string]bool {
}
}
}
-
+
// Note: branches are truly dynamic and can't be statically verified
}
-
+
return reachable
}
@@ -578,25 +578,26 @@ func (g *StateGraph) Compile(opts ...CompileOption) (*CompiledGraph, error) {
if err := g.Validate(); err != nil {
return nil, fmt.Errorf("graph validation failed: %w", err)
}
-
+
// Configure channels and reducers from schema annotations
if err := g.configureChannelsFromSchema(); err != nil {
return nil, fmt.Errorf("failed to configure channels from schema: %w", err)
}
-
+
cg := &CompiledGraph{
graph: g,
checkpointer: nil,
interrupts: make(map[string]bool),
+ interruptsAfter: make(map[string]bool),
recursionLimit: constants.DefaultRecursionLimit,
debug: false,
nodeTriggerMode: types.NodeTriggerAnyPredecessor,
}
-
+
for _, opt := range opts {
opt(cg)
}
-
+
// Propagate node trigger mode to the graph for the engine to access.
g.NodeTriggerMode = cg.nodeTriggerMode
@@ -626,6 +627,18 @@ func WithInterrupts(nodes ...string) CompileOption {
}
}
+// WithInterruptsAfter marks one or more nodes as interrupt-after points.
+// Execution pauses AFTER the named node completes, saving a checkpoint with
+// the node's output, then returns GraphInterrupt for resume.
+// Use "*" to interrupt after every node.
+func WithInterruptsAfter(nodes ...string) CompileOption {
+ return func(cg *CompiledGraph) {
+ for _, node := range nodes {
+ cg.interruptsAfter[node] = true
+ }
+ }
+}
+
// WithRecursionLimit sets the maximum number of Pregel iterations before the
// graph aborts with GraphRecursionError. The default is 25. Increase for deeply
// nested or iterative graphs, decrease to catch runaway loops early.
@@ -690,12 +703,13 @@ func SetPregelRunFunc(fn func(ctx context.Context, cg *CompiledGraph, input inte
// cg, err := sg.Compile(graph.WithCheckpointer(memSaver))
// result, err := cg.Invoke(ctx, MyState{Messages: []string{"hello"}})
type CompiledGraph struct {
- graph *StateGraph
- checkpointer Checkpointer
- interrupts map[string]bool
- recursionLimit int
- debug bool
- nodeTriggerMode types.NodeTriggerMode
+ graph *StateGraph
+ checkpointer Checkpointer
+ interrupts map[string]bool // nodes to interrupt BEFORE execution
+ interruptsAfter map[string]bool // nodes to interrupt AFTER execution
+ recursionLimit int
+ debug bool
+ nodeTriggerMode types.NodeTriggerMode
}
// Invoke executes the graph synchronously. It applies input to the state
@@ -710,12 +724,12 @@ func (cg *CompiledGraph) Invoke(ctx context.Context, input interface{}, config .
if len(config) > 0 && config[0] != nil {
rc = config[0]
}
-
+
result, err := cg.run(ctx, input, rc, types.StreamModeValues)
if err != nil {
return nil, err
}
-
+
return result, nil
}
@@ -837,6 +851,12 @@ func (cg *CompiledGraph) inlineRun(ctx context.Context, input interface{}, confi
for _, result := range results {
if result.err != nil {
+ // Pass GraphInterrupt through unwrapped so the caller
+ // (e.g. runLoop in loop.go) can detect it via direct
+ // type assertion. Wrapping it would prevent detection.
+ if errors.IsGraphInterrupt(result.err) {
+ return nil, result.err
+ }
return nil, fmt.Errorf("node %s failed: %w", result.nodeName, result.err)
}
completedTasks[result.nodeName] = true
@@ -852,9 +872,17 @@ func (cg *CompiledGraph) inlineRun(ctx context.Context, input interface{}, confi
cp := channelRegistry.CreateCheckpoint()
_ = cg.checkpointer.Put(ctx, map[string]interface{}{
constants.ConfigKeyThreadID: getThreadID(config),
- "step": step,
+ "step": step,
}, cp)
}
+
+ // Check for after-node interrupts. The checkpoint above already
+ // captures this step's output, so a resume starts with the node's
+ // data in place.
+ if inlineShouldInterruptAfter(results, cg.interruptsAfter) {
+ return nil, &errors.GraphInterrupt{}
+ }
+
step++
}
@@ -876,11 +904,17 @@ func (cg *CompiledGraph) GetCheckpointer() Checkpointer {
}
// GetInterrupts returns the set of node names that are configured to interrupt
-// execution (human-in-the-loop breakpoints).
+// execution (human-in-the-loop breakpoints) BEFORE node execution.
func (cg *CompiledGraph) GetInterrupts() map[string]bool {
return cg.interrupts
}
+// GetInterruptsAfter returns the set of node names that are configured to
+// interrupt execution AFTER node execution.
+func (cg *CompiledGraph) GetInterruptsAfter() map[string]bool {
+ return cg.interruptsAfter
+}
+
// GetRecursionLimit returns the maximum number of Pregel steps before the
// graph aborts with a GraphRecursionError.
func (cg *CompiledGraph) GetRecursionLimit() int {
@@ -945,26 +979,26 @@ func inlineGetNextTasks(ctx context.Context, registry *channels.Registry, comple
}
if lastCompletedNode != "" {
nextNodes := make(map[string]bool)
+ hasConditional := false
for _, condEdge := range g.conditionalEdges {
if condEdge.From == lastCompletedNode {
+ hasConditional = true
conditionResult, err := condEdge.Condition(ctx, currentState)
if err != nil {
- return nil, fmt.Errorf("condition evaluation failed for node %s: %w", lastCompletedNode, err)
+ return nil, fmt.Errorf("conditional edge condition from '%s' failed: %w", lastCompletedNode, err)
}
conditionKey := fmt.Sprintf("%v", conditionResult)
targetNode, ok := condEdge.Mapping[conditionKey]
if !ok {
- return nil, fmt.Errorf("no mapping for condition result %s from node %s", conditionKey, lastCompletedNode)
+ return nil, fmt.Errorf("conditional edge from '%s': condition key '%v' not mapped", lastCompletedNode, conditionResult)
}
if targetNode == constants.End {
return tasks, nil
}
- // BSP mode: always schedule conditional edge targets, even if previously completed.
- // The conditional router can dynamically route to different nodes each time.
nextNodes[targetNode] = true
}
}
- if len(nextNodes) == 0 {
+ if !hasConditional && len(nextNodes) == 0 {
for _, edge := range g.edges {
if edge.From == lastCompletedNode {
if edge.To == constants.End {
@@ -977,6 +1011,36 @@ func inlineGetNextTasks(ctx context.Context, registry *channels.Registry, comple
}
}
}
+ // Resume fallback: when lastCompletedNode has no outgoing edges
+ // but currentState contains _next (persisted from Switch/Categorize),
+ // route directly from _next. This handles checkpoint resume where
+ // the conditional edge is on a different node.
+ if len(nextNodes) == 0 {
+ if st, ok := currentState.(map[string]any); ok {
+ if raw, has := st["_next"]; has && raw != nil {
+ switch tv := raw.(type) {
+ case string:
+ if _, exists := g.GetNode(tv); exists {
+ nextNodes[tv] = true
+ }
+ case []any:
+ for _, item := range tv {
+ if str, ok := item.(string); ok {
+ if _, exists := g.GetNode(str); exists {
+ nextNodes[str] = true
+ }
+ }
+ }
+ case []string:
+ for _, str := range tv {
+ if _, exists := g.GetNode(str); exists {
+ nextNodes[str] = true
+ }
+ }
+ }
+ }
+ }
+ }
for nodeName := range nextNodes {
node, ok := g.GetNode(nodeName)
if ok {
@@ -1000,6 +1064,25 @@ func inlineShouldInterrupt(tasks []*inlineTask, interrupts map[string]bool) bool
return false
}
+// inlineShouldInterruptAfter checks if any SUCCESSFULLY completed task's node
+// name is in interruptsAfter. This is called AFTER execution and checkpoint
+// save, so the checkpoint captures the node's output.
+func inlineShouldInterruptAfter(results []*inlineTaskResult, interruptsAfter map[string]bool) bool {
+ if len(interruptsAfter) == 0 {
+ return false
+ }
+ interruptAll := interruptsAfter[types.All]
+ for _, r := range results {
+ if r.err != nil {
+ continue
+ }
+ if interruptAll || interruptsAfter[r.nodeName] {
+ return true
+ }
+ }
+ return false
+}
+
func inlineExecuteTasks(ctx context.Context, tasks []*inlineTask, g *StateGraph) ([]*inlineTaskResult, error) {
results := make([]*inlineTaskResult, 0, len(tasks))
for _, t := range tasks {
@@ -1055,43 +1138,43 @@ func inlineBuildOutput(registry *channels.Registry, lastState interface{}) (inte
return lastState, nil
}
-func inlineMergeStates(existing, new interface{}) interface{} {
+func inlineMergeStates(existing, next any) any {
if existing == nil {
- return new
+ return next
}
- if new == nil {
+ if next == nil {
return existing
}
- existingMap, ok1 := existing.(map[string]interface{})
- newMap, ok2 := new.(map[string]interface{})
+ existingMap, ok1 := existing.(map[string]any)
+ nextMap, ok2 := next.(map[string]any)
if ok1 && ok2 {
- result := make(map[string]interface{})
- for k, v := range existingMap {
- result[k] = v
+ result := make(map[string]any)
+ for key, val := range existingMap {
+ result[key] = val
}
- for k, v := range newMap {
- result[k] = v
+ for key, val := range nextMap {
+ result[key] = val
}
return result
}
- return new
+ return next
}
-func inlineToMap(v interface{}) (map[string]interface{}, error) {
- if v == nil {
+func inlineToMap(val any) (map[string]any, error) {
+ if val == nil {
return nil, fmt.Errorf("nil value")
}
- if m, ok := v.(map[string]interface{}); ok {
+ if m, ok := val.(map[string]any); ok {
return m, nil
}
- rv := reflect.ValueOf(v)
+ rv := reflect.ValueOf(val)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map {
- return map[string]interface{}{"__root__": v}, nil
+ return map[string]any{"__root__": val}, nil
}
- result := make(map[string]interface{})
+ result := make(map[string]any)
if rv.Kind() == reflect.Map {
for _, key := range rv.MapKeys() {
result[fmt.Sprintf("%v", key.Interface())] = rv.MapIndex(key).Interface()
diff --git a/internal/harness/graph/graph/graph_channel_test.go b/internal/harness/graph/graph/graph_channel_test.go
index cfa9f3dabf..2a53d2ee20 100644
--- a/internal/harness/graph/graph/graph_channel_test.go
+++ b/internal/harness/graph/graph/graph_channel_test.go
@@ -555,57 +555,77 @@ func TestGraphChannel_CheckpointRoundTrip(t *testing.T) {
cases := []testCase{
{
- name: "LastValue",
+ name: "LastValue",
makeCh: func() channels.Channel { ch := channels.NewLastValue(""); ch.SetKey("lv"); return ch },
- setup: func(ch channels.Channel) { ch.Update([]interface{}{"stored"}) },
+ setup: func(ch channels.Channel) { ch.Update([]interface{}{"stored"}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
- if v != "stored" { t.Errorf("expected 'stored', got %v", v) }
+ if v != "stored" {
+ t.Errorf("expected 'stored', got %v", v)
+ }
},
},
{
name: "BinaryOperatorAggregate",
- makeCh: func() channels.Channel { ch := channels.NewBinaryOperatorAggregate(int(0), channels.IntAdd); ch.SetKey("bo"); return ch },
+ makeCh: func() channels.Channel {
+ ch := channels.NewBinaryOperatorAggregate(int(0), channels.IntAdd)
+ ch.SetKey("bo")
+ return ch
+ },
setup: func(ch channels.Channel) { ch.Update([]interface{}{7, 3}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
- if v != 10 { t.Errorf("expected 10, got %v", v) }
+ if v != 10 {
+ t.Errorf("expected 10, got %v", v)
+ }
},
},
{
name: "NamedBarrierValue",
- makeCh: func() channels.Channel { ch := channels.NewNamedBarrierValue(nil, []string{"x", "y"}); ch.SetKey("nb"); return ch },
+ makeCh: func() channels.Channel {
+ ch := channels.NewNamedBarrierValue(nil, []string{"x", "y"})
+ ch.SetKey("nb")
+ return ch
+ },
setup: func(ch channels.Channel) { ch.Update([]interface{}{"x", "y"}) },
verify: func(ch channels.Channel, t *testing.T) {
- if !ch.IsAvailable() { t.Error("barrier should be available") }
+ if !ch.IsAvailable() {
+ t.Error("barrier should be available")
+ }
},
},
{
- name: "Topic",
+ name: "Topic",
makeCh: func() channels.Channel { ch := channels.NewTopic("", true); ch.SetKey("tp"); return ch },
- setup: func(ch channels.Channel) { ch.Update([]interface{}{"a", "b"}) },
+ setup: func(ch channels.Channel) { ch.Update([]interface{}{"a", "b"}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
items := v.([]interface{})
- if len(items) != 2 { t.Errorf("expected 2 items, got %d", len(items)) }
+ if len(items) != 2 {
+ t.Errorf("expected 2 items, got %d", len(items))
+ }
},
},
{
- name: "EphemeralValue",
+ name: "EphemeralValue",
makeCh: func() channels.Channel { ch := channels.NewEphemeralValue("", true); ch.SetKey("ev"); return ch },
- setup: func(ch channels.Channel) { ch.Update([]interface{}{"temp"}) },
+ setup: func(ch channels.Channel) { ch.Update([]interface{}{"temp"}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
- if v != "temp" { t.Errorf("expected 'temp', got %v", v) }
+ if v != "temp" {
+ t.Errorf("expected 'temp', got %v", v)
+ }
},
},
{
- name: "AnyValue",
+ name: "AnyValue",
makeCh: func() channels.Channel { ch := channels.NewAnyValue(""); ch.SetKey("av"); return ch },
- setup: func(ch channels.Channel) { ch.Update([]interface{}{"stored"}) },
+ setup: func(ch channels.Channel) { ch.Update([]interface{}{"stored"}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
- if v != "stored" { t.Errorf("expected 'stored', got %v", v) }
+ if v != "stored" {
+ t.Errorf("expected 'stored', got %v", v)
+ }
},
},
{
@@ -619,7 +639,9 @@ func TestGraphChannel_CheckpointRoundTrip(t *testing.T) {
setup: func(ch channels.Channel) { ch.Update([]interface{}{5, 3}) },
verify: func(ch channels.Channel, t *testing.T) {
v, _ := ch.Get()
- if v != 8 { t.Errorf("expected 8, got %v", v) }
+ if v != 8 {
+ t.Errorf("expected 8, got %v", v)
+ }
},
},
}
diff --git a/internal/harness/graph/graph/loop.go b/internal/harness/graph/graph/loop.go
new file mode 100644
index 0000000000..d7c8057d12
--- /dev/null
+++ b/internal/harness/graph/graph/loop.go
@@ -0,0 +1,279 @@
+// Package graph — Loop macro support.
+//
+// NewLoopNodeFunc wraps a compiled sub-graph in a NodeFunc closure that
+// repeatedly invokes the sub-graph until a LoopCondition returns true.
+// The loop lives entirely inside the closure — the outer StateGraph sees
+// a single node.
+//
+// Design (independent sub-graph pattern):
+//
+// - Fresh run: iterate from iteration 1 using the outer input.
+// - Sub-graph interrupt: the closure captures its own state
+// (iteration, current input, sub-checkpoint ID), serialises it to
+// JSON, and re-throws via interrupt.Interrupt(ctx, encodedState).
+// The outer Pregel engine saves a checkpoint and surfaces the
+// GraphInterrupt error.
+// - Resume: the closure is re-invoked. It reads the encoded state
+// from interrupt.GetResumeValues(ctx), decodes iteration/input/
+// sub-checkpoint ID, and continues from where it left off.
+// The sub-graph is invoked with a RunnableConfig whose ThreadID
+// incorporates the sub-checkpoint namespace, so the sub-graph's
+// own checkpointer can resume the interrupted sub-iteration.
+// - Termination: when shouldQuit returns true or max iterations is
+// reached, the last iteration's output is returned as the node's
+// output.
+package graph
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "go.uber.org/zap"
+
+ "ragflow/internal/common"
+ "ragflow/internal/harness/graph/interrupt"
+ "ragflow/internal/harness/graph/types"
+)
+
+// LoopCondition is the per-iteration exit predicate invoked AFTER each
+// completed iteration. Return (true, nil) to terminate the loop; the
+// `next` value becomes the loop's final output.
+// Return (false, nil) to continue to the next iteration.
+type LoopCondition func(ctx context.Context, iteration int, prev, next interface{}) (bool, error)
+
+// LoopOption configures NewLoopNodeFunc.
+type LoopOption func(*loopOptions)
+
+type loopOptions struct {
+ maxIterations int
+ checkpointIDPrefix string
+}
+
+// WithLoopMaxIterations caps the loop at n iterations. Default 1024.
+func WithLoopMaxIterations(maxIterations int) LoopOption {
+ return func(o *loopOptions) {
+ if maxIterations >= 0 {
+ o.maxIterations = maxIterations
+ }
+ }
+}
+
+// WithLoopCheckpointIDPrefix sets a stable prefix for per-iteration
+// sub-graph checkpoint IDs. Defaults to the node key.
+func WithLoopCheckpointIDPrefix(prefix string) LoopOption {
+ return func(o *loopOptions) {
+ if prefix != "" {
+ o.checkpointIDPrefix = prefix
+ }
+ }
+}
+
+func getLoopOptions(opts []LoopOption) *loopOptions {
+ o := &loopOptions{
+ maxIterations: 1024,
+ checkpointIDPrefix: "",
+ }
+ for _, opt := range opts {
+ opt(o)
+ }
+ return o
+}
+
+// Sentinel errors.
+var (
+ ErrLoopMaxIterationsExceeded = errors.New("graph: loop max iterations exceeded")
+ ErrLoopSubgraphInterrupted = errors.New("graph: sub-graph interrupted")
+ ErrLoopResumeStateInvalid = errors.New("graph: loop resume state invalid")
+)
+
+// loopStateCtxKey is the context key for storing loop sub-graph state
+// during checkpoint restore. It is separate from the interrupt resume
+// values so that UserFillUp's consumeNextResumeValue doesn't accidentally
+// consume the loop state instead of the user's follow-up input.
+type loopStateCtxKeyType struct{}
+
+var loopStateCtxKey = loopStateCtxKeyType{}
+
+// loopInterruptState is the JSON-serialised loop state saved when the
+// sub-graph emits an interrupt.
+type loopInterruptState struct {
+ Iteration int `json:"iteration"`
+ CurrentInput json.RawMessage `json:"current_input,omitempty"`
+ UserFillUpValue json.RawMessage `json:"user_fill_up_value,omitempty"`
+}
+
+// NewLoopNodeFunc wraps a compiled sub-graph into a NodeFunc that loops.
+//
+// The returned NodeFunc can be added directly to a StateGraph via
+// sg.AddNode(key, nodeFunc). The outer graph sees one node; the loop
+// lives entirely inside the closure.
+//
+// key is the node name (used for deterministic sub-checkpoint IDs).
+// sub is the already-compiled sub-graph to invoke each iteration.
+// shouldQuit is the termination predicate (called after each iteration).
+func NewLoopNodeFunc(
+ key string,
+ sub *CompiledGraph,
+ shouldQuit LoopCondition,
+ opts ...LoopOption,
+) (types.NodeFunc, error) {
+ if key == "" {
+ return nil, fmt.Errorf("graph: loop key is empty")
+ }
+ if sub == nil {
+ return nil, fmt.Errorf("graph: loop sub-graph is nil")
+ }
+ if shouldQuit == nil {
+ return nil, fmt.Errorf("graph: loop shouldQuit is nil")
+ }
+ options := getLoopOptions(opts)
+ if options.checkpointIDPrefix == "" {
+ options.checkpointIDPrefix = key
+ }
+
+ nodeFunc := func(ctx context.Context, state interface{}) (interface{}, error) {
+ return runLoop(ctx, key, sub, state, shouldQuit, options)
+ }
+ return nodeFunc, nil
+}
+
+// runLoop implements the loop node body.
+func runLoop(
+ ctx context.Context,
+ key string,
+ sub *CompiledGraph,
+ input interface{},
+ shouldQuit LoopCondition,
+ options *loopOptions,
+) (interface{}, error) {
+ // Check for resume values (set by interrupt.Interrupt on a previous run).
+ snap, isResume := loadLoopSnapshot(ctx)
+
+ var current interface{}
+ startIteration := 1
+
+ if isResume {
+ startIteration = snap.Iteration
+ if snap.CurrentInput != nil {
+ var decoded interface{}
+ if err := json.Unmarshal(snap.CurrentInput, &decoded); err != nil {
+ return nil, fmt.Errorf("%w: decode current input: %v", ErrLoopResumeStateInvalid, err)
+ }
+ current = decoded
+ } else {
+ current = input
+ }
+ } else {
+ current = input
+ }
+ // Guard against nil input. The sub-graph's inlineApplyInput
+ // (inlineToMap) fails on nil with "nil value". An empty map
+ // is safe and harmless for the first iteration.
+ if current == nil {
+ current = make(map[string]any)
+ }
+
+ iteration := startIteration
+
+ for {
+ // Build sub-checkpoint thread ID for this iteration.
+ subCheckpointID := fmt.Sprintf("%s:loop:%s:iter:%d", options.checkpointIDPrefix, key, iteration)
+
+ // Set up config for sub-graph invocation with per-iteration checkpoint.
+ subCfg := &types.RunnableConfig{Configurable: make(map[string]interface{})}
+ subCfg.Configurable["thread_id"] = subCheckpointID
+
+ // Invoke sub-graph.
+ next, invokeErr := sub.Invoke(ctx, current, subCfg)
+ if invokeErr != nil {
+ // Check if it's an interrupt from the sub-graph.
+ if interrupt.IsInterrupt(invokeErr) {
+ // Encode loop state and re-throw via interrupt.Interrupt
+ // so the outer engine receives a GraphInterrupt with a
+ // non-nil Interrupts list (required for the engine's
+ // IsGraphInterrupt→interrupt detection chain). Preserve
+ // the original UserFillUp value inside the state so
+ // MustExtractInterruptContexts can extract tips/cpn_id.
+ currentJSON, mErr := json.Marshal(current)
+ if mErr != nil {
+ return nil, fmt.Errorf("graph: loop marshal state: %w", mErr)
+ }
+ originalVal, _ := interrupt.GetInterruptValue(invokeErr)
+ var fillUpJSON json.RawMessage
+ if originalVal != nil {
+ if b, e := json.Marshal(originalVal); e == nil {
+ fillUpJSON = b
+ }
+ }
+ loopState := loopInterruptState{
+ Iteration: iteration,
+ CurrentInput: currentJSON,
+ UserFillUpValue: fillUpJSON,
+ }
+ // Pass loopState directly — the checkpoint engine serializes
+ // interrupt values when persisting __sub_state__. Avoid
+ // double-serialization by not marshalling here.
+ _, interruptErr := interrupt.Interrupt(ctx, loopState)
+ common.Debug("runLoop interruptErr",
+ zap.String("type", fmt.Sprintf("%T", interruptErr)),
+ zap.Any("error", interruptErr))
+ return nil, interruptErr
+ }
+ return nil, fmt.Errorf("graph: loop iteration %d: %w", iteration, invokeErr)
+ }
+
+ // Evaluate the quit predicate.
+ quit, qErr := shouldQuit(ctx, iteration, current, next)
+ if qErr != nil {
+ return nil, fmt.Errorf("graph: loop condition iteration %d: %w", iteration, qErr)
+ }
+ if quit {
+ return next, nil
+ }
+
+ if iteration >= options.maxIterations {
+ return nil, fmt.Errorf("%w: %d", ErrLoopMaxIterationsExceeded, options.maxIterations)
+ }
+
+ iteration++
+ current = next
+ }
+}
+
+// loadLoopSnapshot reads the loop state from context (set by the engine
+// during checkpoint restore). Falls back to interrupt resume values for
+// backward compatibility.
+func loadLoopSnapshot(ctx context.Context) (loopInterruptState, bool) {
+ // Check context key first (set by engine's checkpoint restore).
+ if ctx != nil {
+ if v := ctx.Value(interrupt.SubGraphStateCtxKey); v != nil {
+ switch tv := v.(type) {
+ case []byte:
+ var st loopInterruptState
+ if err := json.Unmarshal(tv, &st); err == nil && st.Iteration > 0 {
+ return st, true
+ }
+ }
+ }
+ }
+ // Fallback: interrupt resume values (deprecated, remove when
+ // engine.go and graph.go are migrated to loopStateCtxKey).
+ values := interrupt.GetResumeValues(ctx)
+ for _, v := range values {
+ switch tv := v.(type) {
+ case []byte:
+ var st loopInterruptState
+ if err := json.Unmarshal(tv, &st); err == nil && st.Iteration > 0 {
+ return st, true
+ }
+ case string:
+ var st loopInterruptState
+ if err := json.Unmarshal([]byte(tv), &st); err == nil && st.Iteration > 0 {
+ return st, true
+ }
+ }
+ }
+ return loopInterruptState{}, false
+}
diff --git a/internal/harness/graph/graph/message.go b/internal/harness/graph/graph/message.go
index ab64701b8d..2f19296fab 100644
--- a/internal/harness/graph/graph/message.go
+++ b/internal/harness/graph/graph/message.go
@@ -106,7 +106,7 @@ func AddMessagesReducer(existing interface{}, updates interface{}) (interface{},
result := make([]*Message, 0, len(existingMsgs)+len(msgs))
// Keep track of which IDs have been processed
processedIDs := make(map[string]bool)
-
+
// First, add all existing messages, updating those that have updates
for _, msg := range existingMsgs {
if msg.ID == "" {
@@ -129,7 +129,7 @@ func AddMessagesReducer(existing interface{}, updates interface{}) (interface{},
result = append(result, msg)
}
}
-
+
// Then, append new messages that don't have matching IDs in existing
for _, msg := range msgs {
if msg.ID == "" {
@@ -147,8 +147,8 @@ func AddMessagesReducer(existing interface{}, updates interface{}) (interface{},
// MessageGraph is a graph specialized for message-based workflows.
// It automatically manages a messages channel with the AddMessages reducer.
type MessageGraph struct {
- graph *StateGraph
- messagesChannel string
+ graph *StateGraph
+ messagesChannel string
}
// NewMessageGraph creates a new message-based graph.
@@ -349,10 +349,10 @@ func FilterMessagesByRole(msgs []*Message, roles ...string) []*Message {
// MessagesFilter provides message filtering capabilities.
type MessagesFilter struct {
- roles []string
- limit int
- offset int
- reverse bool
+ roles []string
+ limit int
+ offset int
+ reverse bool
predicate func(*Message) bool
}
diff --git a/internal/harness/graph/graph/parallel.go b/internal/harness/graph/graph/parallel.go
new file mode 100644
index 0000000000..7327549e0c
--- /dev/null
+++ b/internal/harness/graph/graph/parallel.go
@@ -0,0 +1,382 @@
+// Package graph — Parallel macro support.
+//
+// NewParallelNodeFunc wraps a compiled sub-graph in a NodeFunc closure
+// that invokes the sub-graph once per item in the input slice, with
+// bounded concurrency. The outer StateGraph sees a single node; the
+// fan-out lives entirely inside the closure.
+//
+// Design (independent sub-graph pattern):
+//
+// - Input: the node receives a []any (list of items to process).
+// - Output: the node returns []any (ordered results, one per input item).
+// - Concurrency: maxConcurrency ≤ 1 → sequential; > 1 → bounded fan-out
+// using a semaphore. The first item runs on the calling goroutine.
+// - Interrupt: if any per-item sub-graph invocation is interrupted, the
+// results for completed items are saved alongside the interrupted indices
+// and per-item checkpoint IDs, then re-thrown via interrupt.Interrupt.
+// On resume, only the interrupted items are re-processed.
+// - Error: the first non-interrupt error terminates the loop (items are
+// drained to prevent goroutine leaks, but the error is returned).
+package graph
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sync"
+
+ "ragflow/internal/harness/graph/interrupt"
+ "ragflow/internal/harness/graph/types"
+)
+
+// ParallelOption configures NewParallelNodeFunc.
+type ParallelOption func(*parallelOptions)
+
+type parallelOptions struct {
+ maxConcurrency int
+}
+
+// WithParallelMaxConcurrency caps the number of concurrent sub-graph
+// invocations. ≤ 1 = sequential (no goroutines). Default 0 (sequential).
+func WithParallelMaxConcurrency(maxConcurrency int) ParallelOption {
+ return func(o *parallelOptions) {
+ if maxConcurrency >= 0 {
+ o.maxConcurrency = maxConcurrency
+ }
+ }
+}
+
+func getParallelOptions(opts []ParallelOption) *parallelOptions {
+ o := &parallelOptions{}
+ for _, opt := range opts {
+ opt(o)
+ }
+ return o
+}
+
+// Sentinel errors.
+var (
+ ErrParallelResumeStateInvalid = errors.New("graph: parallel resume state invalid")
+ ErrParallelItemFailed = errors.New("graph: parallel item failed")
+)
+
+// parallelInterruptState is persisted when a parallel node is interrupted.
+type parallelInterruptState struct {
+ OriginalInputsJSON []byte `json:"original_inputs_json"`
+ CompletedResults map[int]any `json:"completed_results"`
+ InterruptedIndices []int `json:"interrupted_indices"`
+ TotalCount int `json:"total_count"`
+ ItemCheckpoints map[string][]byte `json:"item_checkpoints,omitempty"`
+}
+
+// parallelItemResult is the per-item outcome from the fan-out goroutines.
+type parallelItemResult struct {
+ index int
+ output interface{}
+ err error
+}
+
+// NewParallelNodeFunc wraps a compiled sub-graph into a NodeFunc that
+// parallel-fanouts over its input slice.
+//
+// The returned NodeFunc expects input of type []any and returns []any.
+// It can be added directly via sg.AddNode(key, nodeFunc).
+//
+// key is the node name.
+// sub is the already-compiled sub-graph to invoke per item.
+func NewParallelNodeFunc(
+ key string,
+ sub *CompiledGraph,
+ opts ...ParallelOption,
+) (types.NodeFunc, error) {
+ if key == "" {
+ return nil, fmt.Errorf("graph: parallel key is empty")
+ }
+ if sub == nil {
+ return nil, fmt.Errorf("graph: parallel sub-graph is nil")
+ }
+ options := getParallelOptions(opts)
+
+ nodeFunc := func(ctx context.Context, state interface{}) (interface{}, error) {
+ items, ok := state.([]interface{})
+ if !ok {
+ // If the state is a map with the relevant key, try to extract.
+ m, mapOk := state.(map[string]interface{})
+ if !mapOk {
+ return nil, fmt.Errorf("graph: parallel node expects []interface{} input, got %T", state)
+ }
+ // Try '__input__' or 'items' key.
+ if raw, found := m["__input__"]; found {
+ items, ok = raw.([]interface{})
+ if !ok {
+ items, ok = raw.([]interface{})
+ }
+ }
+ if raw, found := m["items"]; found && !ok {
+ items, _ = raw.([]interface{})
+ }
+ if items == nil {
+ return nil, fmt.Errorf("graph: parallel node cannot extract []interface{} from %T", state)
+ }
+ }
+ return runParallel(ctx, key, sub, items, options)
+ }
+ return nodeFunc, nil
+}
+
+// runParallel implements the parallel fan-out body.
+func runParallel(
+ ctx context.Context,
+ key string,
+ sub *CompiledGraph,
+ items []interface{},
+ options *parallelOptions,
+) (interface{}, error) {
+ // Check for resume.
+ prev, isResume := loadParallelSnapshot(ctx)
+
+ effectiveItems := items
+ totalCount := len(effectiveItems)
+ outputs := make([]interface{}, totalCount)
+ indicesToProcess := make([]int, totalCount)
+ for i := range effectiveItems {
+ indicesToProcess[i] = i
+ }
+ bridgeState := newItemCheckpointStore(nil)
+
+ if isResume && prev != nil {
+ totalCount = prev.TotalCount
+ outputs = make([]interface{}, totalCount)
+ // Replay completed results.
+ for idx, v := range prev.CompletedResults {
+ if idx >= 0 && idx < totalCount {
+ outputs[idx] = v
+ }
+ }
+ // Only re-process interrupted indices.
+ indicesToProcess = append([]int(nil), prev.InterruptedIndices...)
+ bridgeState = newItemCheckpointStore(prev.ItemCheckpoints)
+ }
+
+ if len(indicesToProcess) == 0 {
+ return outputs, nil
+ }
+
+ // Fan-out.
+ results := fanOutItems(ctx, key, sub, effectiveItems, indicesToProcess, options, bridgeState)
+
+ // Collect results.
+ var normalErr error
+ hasInterrupt := false
+ completedResults := make(map[int]any)
+ for r := range results {
+ if r.err == nil {
+ if r.index >= 0 && r.index < len(outputs) {
+ outputs[r.index] = r.output
+ }
+ completedResults[r.index] = r.output
+ continue
+ }
+ if interrupt.IsInterrupt(r.err) {
+ hasInterrupt = true
+ continue
+ }
+ if normalErr == nil {
+ normalErr = fmt.Errorf("%w: item %d: %v", ErrParallelItemFailed, r.index, r.err)
+ }
+ }
+
+ if normalErr != nil {
+ return nil, normalErr
+ }
+
+ if hasInterrupt {
+ inputsJSON, jErr := json.Marshal(effectiveItems)
+ if jErr != nil {
+ return nil, fmt.Errorf("graph: parallel marshal inputs: %w", jErr)
+ }
+ pending := make([]int, 0, totalCount)
+ for idx := 0; idx < totalCount; idx++ {
+ if _, done := completedResults[idx]; !done {
+ pending = append(pending, idx)
+ }
+ }
+ state := parallelInterruptState{
+ OriginalInputsJSON: inputsJSON,
+ CompletedResults: completedResults,
+ InterruptedIndices: pending,
+ TotalCount: totalCount,
+ ItemCheckpoints: bridgeState.snapshot(),
+ }
+ // Pass state directly — the checkpoint engine serializes
+ // interrupt values when persisting. Avoid double-serialization
+ // by not marshalling here.
+ _, interruptErr := interrupt.Interrupt(ctx, state)
+ return nil, interruptErr
+ }
+
+ return outputs, nil
+}
+
+// fanOutItems fans out sub-graph invocations across items.
+func fanOutItems(
+ ctx context.Context,
+ key string,
+ sub *CompiledGraph,
+ items []interface{},
+ indices []int,
+ options *parallelOptions,
+ bridgeState *itemCheckpointStore,
+) <-chan parallelItemResult {
+ resultCh := make(chan parallelItemResult, len(indices))
+ if len(indices) == 0 {
+ close(resultCh)
+ return resultCh
+ }
+
+ runOne := func(idx int) {
+ itemCheckpointID := fmt.Sprintf("parallel:%s:item:%d", key, idx)
+ cfg := &types.RunnableConfig{Configurable: make(map[string]interface{})}
+ cfg.Configurable["thread_id"] = itemCheckpointID
+
+ // Attach bridge state so the sub-graph's checkpointer can find it.
+ itemCtx := withItemCheckpointCtx(ctx, bridgeState)
+
+ var out interface{}
+ var err error
+ if idx < 0 || idx >= len(items) {
+ err = fmt.Errorf("parallel item index %d out of bounds (len(items)=%d)", idx, len(items))
+ resultCh <- parallelItemResult{index: idx, output: out, err: err}
+ return
+ }
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("parallel item %d panic: %v", idx, r)
+ }
+ }()
+ out, err = sub.Invoke(itemCtx, items[idx], cfg)
+ }()
+ resultCh <- parallelItemResult{index: idx, output: out, err: err}
+ }
+
+ // Sequential path.
+ if options.maxConcurrency <= 1 {
+ for _, idx := range indices {
+ runOne(idx)
+ }
+ close(resultCh)
+ return resultCh
+ }
+
+ // Concurrent path: semaphore-bounded fan-out.
+ sem := make(chan struct{}, options.maxConcurrency)
+ var wg sync.WaitGroup
+ for i, idx := range indices {
+ wg.Add(1)
+ idx := idx
+ if i == 0 {
+ // First item runs on main goroutine.
+ runOne(idx)
+ wg.Done()
+ continue
+ }
+ go func() {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ runOne(idx)
+ }()
+ }
+ go func() {
+ wg.Wait()
+ close(resultCh)
+ }()
+ return resultCh
+}
+
+// loadParallelSnapshot reads the parallel state from interrupt resume values.
+func loadParallelSnapshot(ctx context.Context) (*parallelInterruptState, bool) {
+ values := interrupt.GetResumeValues(ctx)
+ for _, v := range values {
+ var data []byte
+ switch tv := v.(type) {
+ case []byte:
+ data = tv
+ case string:
+ data = []byte(tv)
+ default:
+ continue
+ }
+ var st parallelInterruptState
+ if err := json.Unmarshal(data, &st); err == nil && st.TotalCount > 0 {
+ return &st, true
+ }
+ }
+ return nil, false
+}
+
+// itemCheckpointStore provides per-item checkpoint storage for sub-graphs.
+type itemCheckpointStore struct {
+ mu sync.Mutex
+ data map[string][]byte
+}
+
+func newItemCheckpointStore(data map[string][]byte) *itemCheckpointStore {
+ cloned := make(map[string][]byte)
+ for k, v := range data {
+ buf := make([]byte, len(v))
+ copy(buf, v)
+ cloned[k] = buf
+ }
+ if cloned == nil {
+ cloned = make(map[string][]byte)
+ }
+ return &itemCheckpointStore{data: cloned}
+}
+
+func (s *itemCheckpointStore) get(id string) ([]byte, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ v, ok := s.data[id]
+ if !ok {
+ return nil, false
+ }
+ buf := make([]byte, len(v))
+ copy(buf, v)
+ return buf, true
+}
+
+func (s *itemCheckpointStore) set(id string, payload []byte) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ buf := make([]byte, len(payload))
+ copy(buf, payload)
+ s.data[id] = buf
+}
+
+func (s *itemCheckpointStore) snapshot() map[string][]byte {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ result := make(map[string][]byte, len(s.data))
+ for k, v := range s.data {
+ buf := make([]byte, len(v))
+ copy(buf, v)
+ result[k] = buf
+ }
+ return result
+}
+
+type itemCheckpointCtxKey struct{}
+
+func withItemCheckpointCtx(ctx context.Context, store *itemCheckpointStore) context.Context {
+ return context.WithValue(ctx, itemCheckpointCtxKey{}, store)
+}
+
+func getItemCheckpointStore(ctx context.Context) *itemCheckpointStore {
+ if s, ok := ctx.Value(itemCheckpointCtxKey{}).(*itemCheckpointStore); ok {
+ return s
+ }
+ return nil
+}
diff --git a/internal/harness/graph/graph/state.go b/internal/harness/graph/graph/state.go
index 54a75b1aa0..4d077c7359 100644
--- a/internal/harness/graph/graph/state.go
+++ b/internal/harness/graph/graph/state.go
@@ -210,4 +210,4 @@ func (g *StateGraph) ValidateStateSchema() error {
// Useful for debugging and tooling.
func (g *StateGraph) GetStateSchemaInfo() (map[string]*fieldInfo, error) {
return validateStateSchema(g.stateSchema)
-}
\ No newline at end of file
+}
diff --git a/internal/harness/graph/interrupt/interrupt.go b/internal/harness/graph/interrupt/interrupt.go
index 0ebbc60fed..b0fbde8dbc 100644
--- a/internal/harness/graph/interrupt/interrupt.go
+++ b/internal/harness/graph/interrupt/interrupt.go
@@ -15,6 +15,14 @@ import (
// contextKey is the key for interrupt context in context.Context.
type contextKey struct{}
+// SubGraphStateCtxKey is the context key for sub-graph checkpoint state
+// (e.g. Loop iteration, currentInput). Defined here so that both the
+// engine (pregel) and the sub-graph node (graph/loop.go) can access it
+// without import cycles.
+type SubGraphStateCtxKeyType struct{}
+
+var SubGraphStateCtxKey = SubGraphStateCtxKeyType{}
+
// WithInterruptContext creates a new context with interrupt support.
func WithInterruptContext(ctx context.Context) context.Context {
return context.WithValue(ctx, contextKey{}, &interruptContext{
@@ -213,7 +221,7 @@ func GetInterruptIndex(ctx context.Context) int {
}
// AppendResumeValue appends a resume value to the context.
-func AppendResumeValue(ctx context.Context, v interface{}) {
+func AppendResumeValue(ctx context.Context, value interface{}) {
var ic *interruptContext
if ctx != nil {
ic = GetInterruptContext(ctx)
@@ -221,7 +229,7 @@ func AppendResumeValue(ctx context.Context, v interface{}) {
if ic == nil {
ic = globalContext
}
- ic.appendResumeValue(v)
+ ic.appendResumeValue(value)
}
// GetNullResume gets the null resume value from context.
diff --git a/internal/harness/graph/managed/managed.go b/internal/harness/graph/managed/managed.go
index 73e5212955..c4ed8fe8f4 100644
--- a/internal/harness/graph/managed/managed.go
+++ b/internal/harness/graph/managed/managed.go
@@ -346,16 +346,16 @@ func GetManagedValueName(val interface{}) string {
// ExtractManagedValues extracts managed values from a struct.
func ExtractManagedValues(obj interface{}) []ManagedValue {
result := []ManagedValue{}
-
+
v := reflect.ValueOf(obj)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
-
+
if v.Kind() != reflect.Struct {
return result
}
-
+
for i := 0; i < v.NumField(); i++ {
if !v.Type().Field(i).IsExported() {
continue
@@ -367,23 +367,23 @@ func ExtractManagedValues(obj interface{}) []ManagedValue {
}
}
}
-
+
return result
}
// ExtractManagedValueSpecs extracts managed value specs from a struct.
func ExtractManagedValueSpecs(obj interface{}) []*ManagedValueSpec {
result := []*ManagedValueSpec{}
-
+
v := reflect.ValueOf(obj)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
-
+
if v.Kind() != reflect.Struct {
return result
}
-
+
for i := 0; i < v.NumField(); i++ {
if !v.Type().Field(i).IsExported() {
continue
@@ -395,7 +395,7 @@ func ExtractManagedValueSpecs(obj interface{}) []*ManagedValueSpec {
}
}
}
-
+
return result
}
@@ -485,13 +485,13 @@ func (p PregelScratchpad) Clone() PregelScratchpad {
// ConfigKey represents keys used in runtime configuration.
const (
- ManagedConfigKeyTaskID = "__task_id__"
- ManagedConfigKeyRuntime = "__runtime__"
- ManagedConfigKeyRead = "__read__"
- ManagedConfigKeySend = "__send__"
- ManagedConfigKeyWriter = "__writer__"
- ManagedConfigKeyStore = "__store__"
- ManagedConfigKeyPrevious = "__previous__"
+ ManagedConfigKeyTaskID = "__task_id__"
+ ManagedConfigKeyRuntime = "__runtime__"
+ ManagedConfigKeyRead = "__read__"
+ ManagedConfigKeySend = "__send__"
+ ManagedConfigKeyWriter = "__writer__"
+ ManagedConfigKeyStore = "__store__"
+ ManagedConfigKeyPrevious = "__previous__"
ManagedConfigKeyCheckpointNS = "__checkpoint_ns__"
ManagedConfigKeyConfigurable = "__configurable__"
)
@@ -651,13 +651,13 @@ func (r *Runtime) Override(overrides map[string]interface{}) *Runtime {
return newRuntime
}
-func cloneMap(m map[string]interface{}) map[string]interface{} {
- if m == nil {
+func cloneMap(src map[string]any) map[string]any {
+ if src == nil {
return nil
}
- clone := make(map[string]interface{}, len(m))
- for k, v := range m {
- clone[k] = v
+ clone := make(map[string]any, len(src))
+ for key, val := range src {
+ clone[key] = val
}
return clone
}
@@ -774,10 +774,6 @@ func SetWriter(config map[string]interface{}, writer interface{}) {
config[ManagedConfigKeyWriter] = writer
}
-
-
-
-
// PatchConfig patches a config with new values.
func PatchConfig(base map[string]interface{}, updates map[string]interface{}) map[string]interface{} {
if base == nil {
@@ -786,7 +782,7 @@ func PatchConfig(base map[string]interface{}, updates map[string]interface{}) ma
if updates == nil {
return base
}
-
+
result := make(map[string]interface{}, len(base))
for k, v := range base {
result[k] = v
@@ -805,7 +801,7 @@ func PatchConfigurable(base map[string]interface{}, updates map[string]interface
if updates == nil {
return base
}
-
+
// Get or create configurable section — deep copy to avoid mutating the original.
configurable := make(map[string]interface{})
if cfg, ok := base[ManagedConfigKeyConfigurable]; ok {
@@ -815,19 +811,19 @@ func PatchConfigurable(base map[string]interface{}, updates map[string]interface
}
}
}
-
+
// Merge updates
for k, v := range updates {
configurable[k] = v
}
-
+
// Update base config
result := make(map[string]interface{}, len(base)+1)
for k, v := range base {
result[k] = v
}
result[ManagedConfigKeyConfigurable] = configurable
-
+
return result
}
@@ -877,13 +873,13 @@ func RecastCheckpointNS(ns string) string {
if len(parts) == 0 {
return ""
}
-
+
// Remove task ID if present (usually the last part)
lastPart := parts[len(parts)-1]
if isTaskID(lastPart) {
return joinCheckpointNS(parts[:len(parts)-1])
}
-
+
return ns
}
@@ -928,7 +924,7 @@ func FormatCheckpoint(checkpoint map[string]interface{}) string {
if checkpoint == nil {
return "{}"
}
-
+
result := "{"
first := true
for k, v := range checkpoint {
diff --git a/internal/harness/graph/managed/managed_test.go b/internal/harness/graph/managed/managed_test.go
index bb1f3dd707..b364e16044 100644
--- a/internal/harness/graph/managed/managed_test.go
+++ b/internal/harness/graph/managed/managed_test.go
@@ -268,10 +268,10 @@ func TestManagedValueGetValue(t *testing.T) {
}
type TestStruct struct {
- ManagedField ManagedValue
- SpecField *ManagedValueSpec
- NormalField string
- NilField interface{}
+ ManagedField ManagedValue
+ SpecField *ManagedValueSpec
+ NormalField string
+ NilField interface{}
}
func TestExtractManagedValues(t *testing.T) {
diff --git a/internal/harness/graph/pregel/async.go b/internal/harness/graph/pregel/async.go
index 25252ebb9c..2754169476 100644
--- a/internal/harness/graph/pregel/async.go
+++ b/internal/harness/graph/pregel/async.go
@@ -24,7 +24,7 @@ type AsyncExecutor struct {
type asyncTask struct {
ID string
Name string
- Func func(context.Context) (interface{}, error)
+ Func func(context.Context) (any, error)
Context context.Context
Cancel context.CancelFunc
Priority int
@@ -34,7 +34,7 @@ type asyncTask struct {
type asyncTaskResult struct {
TaskID string
Name string
- Output interface{}
+ Output any
Err error
Duration time.Duration
}
@@ -44,26 +44,26 @@ func NewAsyncExecutor(maxConcurrency int) *AsyncExecutor {
if maxConcurrency <= 0 {
maxConcurrency = 10 // Default concurrency
}
-
+
exec := &AsyncExecutor{
maxConcurrency: maxConcurrency,
workerPool: make(chan struct{}, maxConcurrency),
results: make(chan *asyncTaskResult, 100),
activeTasks: make(map[string]*asyncTask),
}
-
+
// Pre-fill worker pool
for i := 0; i < maxConcurrency; i++ {
exec.workerPool <- struct{}{}
}
-
+
return exec
}
// Execute executes a single task asynchronously.
-func (e *AsyncExecutor) Execute(ctx context.Context, name string, fn func(context.Context) (interface{}, error)) <-chan *asyncTaskResult {
+func (e *AsyncExecutor) Execute(ctx context.Context, name string, fn func(context.Context) (any, error)) <-chan *asyncTaskResult {
resultCh := make(chan *asyncTaskResult, 1)
-
+
// Create cancellable context so Cancel() can stop running tasks.
taskCtx, cancel := context.WithCancel(ctx)
task := &asyncTask{
@@ -73,16 +73,22 @@ func (e *AsyncExecutor) Execute(ctx context.Context, name string, fn func(contex
Context: taskCtx,
Cancel: cancel,
}
-
+
e.mu.Lock()
e.activeTasks[task.ID] = task
e.mu.Unlock()
-
+
go func() {
defer close(resultCh)
-
+ // Remove from activeTasks on ALL exit paths (success, ctx cancelled, etc.).
+ defer func() {
+ e.mu.Lock()
+ delete(e.activeTasks, task.ID)
+ e.mu.Unlock()
+ }()
+
startTime := time.Now()
-
+
// Acquire worker slot
select {
case <-e.workerPool:
@@ -95,10 +101,10 @@ func (e *AsyncExecutor) Execute(ctx context.Context, name string, fn func(contex
}
return
}
-
+
// Execute task
output, err := task.Func(task.Context)
-
+
result := &asyncTaskResult{
TaskID: task.ID,
Name: task.Name,
@@ -106,36 +112,38 @@ func (e *AsyncExecutor) Execute(ctx context.Context, name string, fn func(contex
Err: err,
Duration: time.Since(startTime),
}
-
- e.mu.Lock()
- delete(e.activeTasks, task.ID)
- e.mu.Unlock()
-
+
resultCh <- result
}()
-
+
return resultCh
}
// ExecuteBatch executes multiple tasks concurrently with controlled concurrency.
func (e *AsyncExecutor) ExecuteBatch(ctx context.Context, tasks []asyncTask) <-chan *asyncTaskResult {
resultCh := make(chan *asyncTaskResult, len(tasks))
-
+
+ // Register all tasks in activeTasks before any goroutine starts.
for i := range tasks {
tasks[i].ID = uuid.New().String()
e.mu.Lock()
e.activeTasks[tasks[i].ID] = &tasks[i]
e.mu.Unlock()
}
-
+
var wg sync.WaitGroup
for i := range tasks {
wg.Add(1)
go func(task *asyncTask) {
defer wg.Done()
-
+ defer func() {
+ e.mu.Lock()
+ delete(e.activeTasks, task.ID)
+ e.mu.Unlock()
+ }()
+
startTime := time.Now()
-
+
// Acquire worker slot
select {
case <-e.workerPool:
@@ -148,10 +156,10 @@ func (e *AsyncExecutor) ExecuteBatch(ctx context.Context, tasks []asyncTask) <-c
}
return
}
-
+
// Execute task
output, err := task.Func(task.Context)
-
+
resultCh <- &asyncTaskResult{
TaskID: task.ID,
Name: task.Name,
@@ -159,25 +167,21 @@ func (e *AsyncExecutor) ExecuteBatch(ctx context.Context, tasks []asyncTask) <-c
Err: err,
Duration: time.Since(startTime),
}
-
- e.mu.Lock()
- delete(e.activeTasks, task.ID)
- e.mu.Unlock()
}(&tasks[i])
}
-
+
go func() {
wg.Wait()
close(resultCh)
}()
-
+
return resultCh
}
// ExecuteWithRetry executes a task with retry logic.
-func (e *AsyncExecutor) ExecuteWithRetry(ctx context.Context, name string, fn func(context.Context) (interface{}, error), retryConfig *RetryConfig) <-chan *asyncTaskResult {
+func (e *AsyncExecutor) ExecuteWithRetry(ctx context.Context, name string, fn func(context.Context) (any, error), retryConfig *RetryConfig) <-chan *asyncTaskResult {
resultCh := make(chan *asyncTaskResult, 1)
-
+
taskCtx, cancel := context.WithCancel(ctx)
task := &asyncTask{
ID: uuid.New().String(),
@@ -185,19 +189,19 @@ func (e *AsyncExecutor) ExecuteWithRetry(ctx context.Context, name string, fn fu
Context: taskCtx,
Cancel: cancel,
}
-
+
e.mu.Lock()
e.activeTasks[task.ID] = task
e.mu.Unlock()
-
+
go func() {
defer close(resultCh)
-
+
executor := NewRetryExecutor(retryConfig.Policy)
-
+
startTime := time.Now()
- output, err := executor.Execute(ctx, name, fn)
-
+ output, err := executor.Execute(task.Context, name, fn)
+
result := &asyncTaskResult{
TaskID: task.ID,
Name: name,
@@ -205,14 +209,14 @@ func (e *AsyncExecutor) ExecuteWithRetry(ctx context.Context, name string, fn fu
Err: err,
Duration: time.Since(startTime),
}
-
+
e.mu.Lock()
delete(e.activeTasks, task.ID)
e.mu.Unlock()
-
+
resultCh <- result
}()
-
+
return resultCh
}
@@ -220,7 +224,7 @@ func (e *AsyncExecutor) ExecuteWithRetry(ctx context.Context, name string, fn fu
func (e *AsyncExecutor) Cancel() {
e.mu.Lock()
defer e.mu.Unlock()
-
+
for id, task := range e.activeTasks {
if task.Cancel != nil {
task.Cancel()
@@ -240,7 +244,7 @@ func (e *AsyncExecutor) GetActiveTaskCount() int {
func (e *AsyncExecutor) Wait(ctx context.Context) error {
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
-
+
for {
select {
case <-ctx.Done():
@@ -257,15 +261,15 @@ func (e *AsyncExecutor) Wait(ctx context.Context) error {
type AsyncPipeline struct {
executor *AsyncExecutor
retryer *RetryExecutor
-
+
// Stream channels
- events chan interface{}
- errors chan error
-
+ events chan any
+ errors chan error
+
// Control
- mu sync.RWMutex
- cancel context.CancelFunc
- running bool
+ mu sync.RWMutex
+ cancel context.CancelFunc
+ running bool
}
// NewAsyncPipeline creates a new async pipeline.
@@ -273,7 +277,7 @@ func NewAsyncPipeline(maxConcurrency int, retryPolicy *types.RetryPolicy) *Async
return &AsyncPipeline{
executor: NewAsyncExecutor(maxConcurrency),
retryer: NewRetryExecutor(retryPolicy),
- events: make(chan interface{}, 100),
+ events: make(chan any, 100),
errors: make(chan error, 10),
running: false,
}
@@ -283,14 +287,18 @@ func NewAsyncPipeline(maxConcurrency int, retryPolicy *types.RetryPolicy) *Async
func (p *AsyncPipeline) Start(ctx context.Context) context.Context {
p.mu.Lock()
defer p.mu.Unlock()
-
+
if p.running {
return ctx
}
-
+
+ // Reinitialize channels that were closed by Stop().
+ p.events = make(chan any, 100)
+ p.errors = make(chan error, 10)
+
ctx, p.cancel = context.WithCancel(ctx)
p.running = true
-
+
return ctx
}
@@ -298,15 +306,15 @@ func (p *AsyncPipeline) Start(ctx context.Context) context.Context {
func (p *AsyncPipeline) Stop() {
p.mu.Lock()
defer p.mu.Unlock()
-
+
if !p.running {
return
}
-
+
if p.cancel != nil {
p.cancel()
}
-
+
p.executor.Cancel()
close(p.events)
close(p.errors)
@@ -314,7 +322,7 @@ func (p *AsyncPipeline) Stop() {
}
// ExecuteNode executes a node in the pipeline.
-func (p *AsyncPipeline) ExecuteNode(ctx context.Context, name string, fn func(context.Context) (interface{}, error), retryConfig *RetryConfig) <-chan *asyncTaskResult {
+func (p *AsyncPipeline) ExecuteNode(ctx context.Context, name string, fn func(context.Context) (any, error), retryConfig *RetryConfig) <-chan *asyncTaskResult {
if retryConfig != nil {
return p.executor.ExecuteWithRetry(ctx, name, fn, retryConfig)
}
@@ -322,7 +330,7 @@ func (p *AsyncPipeline) ExecuteNode(ctx context.Context, name string, fn func(co
}
// Events returns the event channel.
-func (p *AsyncPipeline) Events() <-chan interface{} {
+func (p *AsyncPipeline) Events() <-chan any {
return p.events
}
@@ -332,10 +340,10 @@ func (p *AsyncPipeline) Errors() <-chan error {
}
// EmitEvent emits an event to the pipeline.
-func (p *AsyncPipeline) EmitEvent(event interface{}) {
+func (p *AsyncPipeline) EmitEvent(event any) {
p.mu.RLock()
defer p.mu.RUnlock()
-
+
if p.running {
select {
case p.events <- event:
@@ -349,7 +357,7 @@ func (p *AsyncPipeline) EmitEvent(event interface{}) {
func (p *AsyncPipeline) EmitError(err error) {
p.mu.RLock()
defer p.mu.RUnlock()
-
+
if p.running {
select {
case p.errors <- err:
@@ -383,7 +391,7 @@ func NewConcurrencyLimiter() *ConcurrencyLimiter {
func (l *ConcurrencyLimiter) SetLimit(node string, limit int) {
l.mu.Lock()
defer l.mu.Unlock()
-
+
ch := make(chan struct{}, limit)
for i := 0; i < limit; i++ {
ch <- struct{}{}
@@ -396,12 +404,12 @@ func (l *ConcurrencyLimiter) Acquire(ctx context.Context, node string) error {
l.mu.RLock()
ch, ok := l.limits[node]
l.mu.RUnlock()
-
+
if !ok {
// No limit set
return nil
}
-
+
select {
case <-ch:
return nil
@@ -415,11 +423,11 @@ func (l *ConcurrencyLimiter) Release(node string) {
l.mu.RLock()
ch, ok := l.limits[node]
l.mu.RUnlock()
-
+
if !ok {
return
}
-
+
select {
case ch <- struct{}{}:
default:
@@ -429,7 +437,7 @@ func (l *ConcurrencyLimiter) Release(node string) {
// PriorityTask represents a prioritized task.
type PriorityTask struct {
- Func func(context.Context) (interface{}, error)
+ Func func(context.Context) (any, error)
Priority int
}
@@ -457,14 +465,14 @@ func (e *PriorityExecutor) Submit(task PriorityTask) error {
}
// Execute executes tasks in priority order.
-func (e *PriorityExecutor) Execute(ctx context.Context, maxConcurrency int) <-chan interface{} {
- resultCh := make(chan interface{}, maxConcurrency)
-
+func (e *PriorityExecutor) Execute(ctx context.Context, maxConcurrency int) <-chan any {
+ resultCh := make(chan any, maxConcurrency)
+
// Simple priority scheduling using multiple channels
// In a real implementation, you'd use a priority queue
go func() {
defer close(resultCh)
-
+
// This is a simplified implementation
// A full implementation would use a heap-based priority queue
for {
@@ -473,7 +481,7 @@ func (e *PriorityExecutor) Execute(ctx context.Context, maxConcurrency int) <-ch
return
case task := <-e.tasks:
output, err := task.Func(ctx)
- resultCh <- map[string]interface{}{
+ resultCh <- map[string]any{
"output": output,
"error": err,
"priority": task.Priority,
@@ -481,6 +489,6 @@ func (e *PriorityExecutor) Execute(ctx context.Context, maxConcurrency int) <-ch
}
}
}()
-
+
return resultCh
}
diff --git a/internal/harness/graph/pregel/background.go b/internal/harness/graph/pregel/background.go
index e07715b185..d9d3ac2ae3 100644
--- a/internal/harness/graph/pregel/background.go
+++ b/internal/harness/graph/pregel/background.go
@@ -14,7 +14,7 @@ import (
type BackgroundTask struct {
ID string
Name string
- Func func(context.Context) (interface{}, error)
+ Func func(context.Context) (any, error)
Context context.Context
Result chan *BackgroundTaskResult
Cancel context.CancelFunc
@@ -26,30 +26,30 @@ type BackgroundTask struct {
type BackgroundTaskResult struct {
TaskID string
Name string
- Output interface{}
+ Output any
Err error
Duration time.Duration
}
// BackgroundExecutor executes tasks in a background worker pool.
type BackgroundExecutor struct {
- maxWorkers int
- taskQueue chan *BackgroundTask
- results chan *BackgroundTaskResult
- workers []*backgroundWorker
- mu sync.RWMutex
- running bool
- stopCh chan struct{}
- wg sync.WaitGroup
- activeTasks map[string]*BackgroundTask
+ maxWorkers int
+ taskQueue chan *BackgroundTask
+ results chan *BackgroundTaskResult
+ workers []*backgroundWorker
+ mu sync.RWMutex
+ running bool
+ stopCh chan struct{}
+ wg sync.WaitGroup
+ activeTasks map[string]*BackgroundTask
shutdownTimeout time.Duration
}
// backgroundWorker represents a worker goroutine.
type backgroundWorker struct {
- id int
+ id int
executor *BackgroundExecutor
- stopCh chan struct{}
+ stopCh chan struct{}
}
// NewBackgroundExecutor creates a new background executor.
@@ -87,9 +87,9 @@ func (e *BackgroundExecutor) Start(ctx context.Context) {
// Start workers
for i := 0; i < e.maxWorkers; i++ {
worker := &backgroundWorker{
- id: i,
+ id: i,
executor: e,
- stopCh: make(chan struct{}),
+ stopCh: make(chan struct{}),
}
e.workers = append(e.workers, worker)
e.wg.Add(1)
@@ -127,7 +127,7 @@ func (e *BackgroundExecutor) Stop() {
}
// Submit submits a task for background execution.
-func (e *BackgroundExecutor) Submit(ctx context.Context, name string, fn func(context.Context) (interface{}, error), priority int) (*BackgroundTask, error) {
+func (e *BackgroundExecutor) Submit(ctx context.Context, name string, fn func(context.Context) (any, error), priority int) (*BackgroundTask, error) {
e.mu.RLock()
if !e.running {
e.mu.RUnlock()
diff --git a/internal/harness/graph/pregel/cache.go b/internal/harness/graph/pregel/cache.go
index 2d242bcb77..f623990cb8 100644
--- a/internal/harness/graph/pregel/cache.go
+++ b/internal/harness/graph/pregel/cache.go
@@ -16,9 +16,9 @@ import (
// Cache is the interface for caching node outputs.
type Cache interface {
// Get retrieves a value from the cache.
- Get(ctx context.Context, key string) (interface{}, bool)
+ Get(ctx context.Context, key string) (any, bool)
// Set stores a value in the cache.
- Set(ctx context.Context, key string, value interface{}, ttl time.Duration)
+ Set(ctx context.Context, key string, value any, ttl time.Duration)
// Delete removes a value from the cache.
Delete(ctx context.Context, key string)
// Clear clears all values from the cache.
@@ -34,10 +34,10 @@ type MemoryCache struct {
}
type cacheEntry struct {
- value interface{}
- expiration time.Time
- lastAccess time.Time
- hits int64
+ value any
+ expiration time.Time
+ lastAccess time.Time
+ hits int64
}
// EvictionPolicy determines how entries are evicted when cache is full.
@@ -62,7 +62,7 @@ func NewMemoryCache(maxSize int, eviction EvictionPolicy) *MemoryCache {
}
// Get retrieves a value from the cache.
-func (c *MemoryCache) Get(ctx context.Context, key string) (interface{}, bool) {
+func (c *MemoryCache) Get(ctx context.Context, key string) (any, bool) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -82,7 +82,7 @@ func (c *MemoryCache) Get(ctx context.Context, key string) (interface{}, bool) {
}
// Set stores a value in the cache.
-func (c *MemoryCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) {
+func (c *MemoryCache) Set(ctx context.Context, key string, value any, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -97,10 +97,10 @@ func (c *MemoryCache) Set(ctx context.Context, key string, value interface{}, tt
}
c.data[key] = &cacheEntry{
- value: value,
- expiration: expiration,
- lastAccess: time.Now(),
- hits: 0,
+ value: value,
+ expiration: expiration,
+ lastAccess: time.Now(),
+ hits: 0,
}
}
@@ -159,8 +159,12 @@ func (c *MemoryCache) evict() {
}
// GenerateCacheKey generates a cache key from the given input.
-func GenerateCacheKey(nodeName string, input interface{}) string {
- data, _ := json.Marshal(input)
+func GenerateCacheKey(nodeName string, input any) string {
+ data, err := json.Marshal(input)
+ if err != nil {
+ // Fall back to the type name so different inputs still produce different keys.
+ return fmt.Sprintf("%s:%T", nodeName, input)
+ }
hash := sha256.Sum256(data)
return fmt.Sprintf("%s:%s", nodeName, hex.EncodeToString(hash[:]))
}
@@ -180,7 +184,7 @@ func NewCachedExecutor(cache Cache, policy *types.CachePolicy) *CachedExecutor {
}
// Execute executes a function with caching.
-func (e *CachedExecutor) Execute(ctx context.Context, nodeName string, input interface{}, fn func(context.Context, interface{}) (interface{}, error)) (interface{}, error) {
+func (e *CachedExecutor) Execute(ctx context.Context, nodeName string, input any, fn func(context.Context, any) (any, error)) (any, error) {
// Generate cache key
var key string
if e.cachePolicy != nil && e.cachePolicy.KeyFunc != nil {
@@ -214,12 +218,12 @@ func (e *CachedExecutor) Execute(ctx context.Context, nodeName string, input int
type NoopCache struct{}
// Get always returns false.
-func (n *NoopCache) Get(ctx context.Context, key string) (interface{}, bool) {
+func (n *NoopCache) Get(ctx context.Context, key string) (any, bool) {
return nil, false
}
// Set is a no-op.
-func (n *NoopCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) {}
+func (n *NoopCache) Set(ctx context.Context, key string, value any, ttl time.Duration) {}
// Delete is a no-op.
func (n *NoopCache) Delete(ctx context.Context, key string) {}
diff --git a/internal/harness/graph/pregel/cache_async.go b/internal/harness/graph/pregel/cache_async.go
index f7e0d426de..6fdf30e3c3 100644
--- a/internal/harness/graph/pregel/cache_async.go
+++ b/internal/harness/graph/pregel/cache_async.go
@@ -9,15 +9,15 @@ import (
// AsyncCache extends the Cache interface with asynchronous operations.
type AsyncCache interface {
Cache
-
+
// AGet asynchronously retrieves a value from the cache.
// Returns a channel that will receive the result.
AGet(ctx context.Context, key string) <-chan CacheResult
-
+
// ASet asynchronously stores a value in the cache.
// Returns a channel that will be closed when the operation completes.
- ASet(ctx context.Context, key string, value interface{}, ttl time.Duration) <-chan error
-
+ ASet(ctx context.Context, key string, value any, ttl time.Duration) <-chan error
+
// ADelete asynchronously removes a value from the cache.
// Returns a channel that will be closed when the operation completes.
ADelete(ctx context.Context, key string) <-chan error
@@ -25,7 +25,7 @@ type AsyncCache interface {
// CacheResult represents the result of an asynchronous cache get operation.
type CacheResult struct {
- Value interface{}
+ Value any
Found bool
Error error
}
@@ -42,7 +42,7 @@ type asyncCacheOp struct {
ctx context.Context
opType string // "get", "set", "delete"
key string
- value interface{}
+ value any
ttl time.Duration
result chan<- CacheResult
done chan<- error
@@ -53,18 +53,18 @@ func NewAsyncMemoryCache(maxSize int, eviction EvictionPolicy, numWorkers int) *
if numWorkers <= 0 {
numWorkers = 4
}
-
+
cache := &AsyncMemoryCache{
MemoryCache: NewMemoryCache(maxSize, eviction),
workerCh: make(chan asyncCacheOp, 1000),
stopCh: make(chan struct{}),
}
-
+
// Start worker goroutines
for i := 0; i < numWorkers; i++ {
go cache.worker()
}
-
+
return cache
}
@@ -104,7 +104,7 @@ func (c *AsyncMemoryCache) processOp(op asyncCacheOp) {
// AGet asynchronously retrieves a value from the cache.
func (c *AsyncMemoryCache) AGet(ctx context.Context, key string) <-chan CacheResult {
resultCh := make(chan CacheResult, 1)
-
+
select {
case c.workerCh <- asyncCacheOp{
ctx: ctx,
@@ -116,14 +116,14 @@ func (c *AsyncMemoryCache) AGet(ctx context.Context, key string) <-chan CacheRes
resultCh <- CacheResult{Error: ctx.Err()}
close(resultCh)
}
-
+
return resultCh
}
// ASet asynchronously stores a value in the cache.
-func (c *AsyncMemoryCache) ASet(ctx context.Context, key string, value interface{}, ttl time.Duration) <-chan error {
+func (c *AsyncMemoryCache) ASet(ctx context.Context, key string, value any, ttl time.Duration) <-chan error {
doneCh := make(chan error, 1)
-
+
select {
case c.workerCh <- asyncCacheOp{
ctx: ctx,
@@ -137,14 +137,14 @@ func (c *AsyncMemoryCache) ASet(ctx context.Context, key string, value interface
doneCh <- ctx.Err()
close(doneCh)
}
-
+
return doneCh
}
// ADelete asynchronously removes a value from the cache.
func (c *AsyncMemoryCache) ADelete(ctx context.Context, key string) <-chan error {
doneCh := make(chan error, 1)
-
+
select {
case c.workerCh <- asyncCacheOp{
ctx: ctx,
@@ -156,7 +156,7 @@ func (c *AsyncMemoryCache) ADelete(ctx context.Context, key string) <-chan error
doneCh <- ctx.Err()
close(doneCh)
}
-
+
return doneCh
}
@@ -168,11 +168,11 @@ func (c *AsyncMemoryCache) Stop() {
// AsyncCachePolicy configures async cache behavior.
type AsyncCachePolicy struct {
// KeyFunc generates the cache key.
- KeyFunc func(context.Context, interface{}) string
-
+ KeyFunc func(context.Context, any) string
+
// TTL is the time-to-live for cached values.
TTL *time.Duration
-
+
// Async determines if operations should be async.
Async bool
}
@@ -195,9 +195,9 @@ func NewAsyncCachedExecutor(cache AsyncCache, policy *AsyncCachePolicy) *AsyncCa
func (e *AsyncCachedExecutor) Execute(
ctx context.Context,
nodeName string,
- input interface{},
- fn func(context.Context, interface{}) (interface{}, error),
-) (interface{}, error) {
+ input any,
+ fn func(context.Context, any) (any, error),
+) (any, error) {
// Generate cache key
var key string
if e.cachePolicy != nil && e.cachePolicy.KeyFunc != nil {
@@ -205,11 +205,11 @@ func (e *AsyncCachedExecutor) Execute(
} else {
key = GenerateCacheKey(nodeName, input)
}
-
+
// Check cache asynchronously
if e.cachePolicy != nil && e.cachePolicy.Async {
resultCh := e.cache.AGet(ctx, key)
-
+
select {
case result := <-resultCh:
if result.Error != nil {
@@ -227,26 +227,26 @@ func (e *AsyncCachedExecutor) Execute(
return cached, nil
}
}
-
+
// Execute function
result, err := fn(ctx, input)
if err != nil {
return nil, err
}
-
+
// Cache result asynchronously
var ttl time.Duration
if e.cachePolicy != nil && e.cachePolicy.TTL != nil {
ttl = *e.cachePolicy.TTL
}
-
+
if e.cachePolicy != nil && e.cachePolicy.Async {
// Fire and forget async set
e.cache.ASet(context.Background(), key, result, ttl)
} else {
e.cache.Set(ctx, key, result, ttl)
}
-
+
return result, nil
}
diff --git a/internal/harness/graph/pregel/cache_test.go b/internal/harness/graph/pregel/cache_test.go
index 9dbf15a4cc..dc5ae88a1e 100644
--- a/internal/harness/graph/pregel/cache_test.go
+++ b/internal/harness/graph/pregel/cache_test.go
@@ -81,9 +81,9 @@ func TestMemoryCacheEviction(t *testing.T) {
}
func TestGenerateCacheKey(t *testing.T) {
- key1 := GenerateCacheKey("node1", map[string]interface{}{"input": "test"})
- key2 := GenerateCacheKey("node1", map[string]interface{}{"input": "test"})
- key3 := GenerateCacheKey("node2", map[string]interface{}{"input": "test"})
+ key1 := GenerateCacheKey("node1", map[string]any{"input": "test"})
+ key2 := GenerateCacheKey("node1", map[string]any{"input": "test"})
+ key3 := GenerateCacheKey("node2", map[string]any{"input": "test"})
if key1 != key2 {
t.Error("expected same input to generate same key")
@@ -98,7 +98,7 @@ func TestCachedExecutor(t *testing.T) {
cache := NewMemoryCache(100, EvictLRU)
callCount := 0
- fn := func(ctx context.Context, input interface{}) (interface{}, error) {
+ fn := func(ctx context.Context, input any) (any, error) {
callCount++
return input.(int) * 2, nil
}
diff --git a/internal/harness/graph/pregel/engine.go b/internal/harness/graph/pregel/engine.go
index b3a3674589..2d559f2029 100644
--- a/internal/harness/graph/pregel/engine.go
+++ b/internal/harness/graph/pregel/engine.go
@@ -3,6 +3,7 @@ package pregel
import (
"context"
+ "encoding/json"
"fmt"
"reflect"
"sort"
@@ -18,6 +19,7 @@ import (
"ragflow/internal/harness/graph/constants"
"ragflow/internal/harness/graph/errors"
"ragflow/internal/harness/graph/graph"
+ "ragflow/internal/harness/graph/interrupt"
"ragflow/internal/harness/graph/types"
)
@@ -36,6 +38,7 @@ type Engine struct {
graph *graph.StateGraph
checkpointer graph.Checkpointer
interrupts map[string]bool
+ interruptsAfter map[string]bool
recursionLimit int
debug bool
config *types.RunnableConfig
@@ -54,7 +57,7 @@ type deferredCheckpoint struct {
ThreadID string
CheckpointID string
Step int
- Checkpoint map[string]interface{}
+ Checkpoint map[string]any
}
// NewEngine creates a new Pregel engine bound to a StateGraph.
@@ -66,6 +69,7 @@ func NewEngine(g *graph.StateGraph, opts ...EngineOption) *Engine {
eng := &Engine{
graph: g,
interrupts: make(map[string]bool),
+ interruptsAfter: make(map[string]bool),
recursionLimit: 25,
debug: false,
config: types.NewRunnableConfig(),
@@ -110,6 +114,15 @@ func WithInterrupts(nodes ...string) EngineOption {
}
}
+// WithInterruptsAfter sets the after-execution interrupt nodes.
+func WithInterruptsAfter(nodes ...string) EngineOption {
+ return func(e *Engine) {
+ for _, node := range nodes {
+ e.interruptsAfter[node] = true
+ }
+ }
+}
+
// WithRecursionLimit sets the recursion limit.
func WithRecursionLimit(limit int) EngineOption {
return func(e *Engine) {
@@ -164,11 +177,11 @@ func WithBackgroundExecutor(exec *BackgroundExecutor) EngineOption {
// ExecuteResult represents the result of graph execution.
type ExecuteResult struct {
// Final state of the graph.
- State interface{}
+ State any
// Checkpoint ID for this execution.
CheckpointID string
// Metadata about the execution.
- Metadata map[string]interface{}
+ Metadata map[string]any
}
// Run executes the graph using the Pregel algorithm and returns streaming events.
@@ -178,8 +191,8 @@ type ExecuteResult struct {
//
// The caller MUST read from outputCh until it is closed to prevent goroutine leaks.
// For synchronous execution, use RunSync instead.
-func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMode) (<-chan interface{}, <-chan error) {
- outputCh := make(chan interface{}, 100)
+func (e *Engine) Run(ctx context.Context, input any, mode types.StreamMode) (<-chan any, <-chan error) {
+ outputCh := make(chan any, 100)
errCh := make(chan error, 1)
go func() {
@@ -248,24 +261,78 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
// Get thread ID for checkpointing
threadID := e.getThreadID()
- // Load checkpoint only when resuming (input == nil).
- // New executions (input != nil) start from scratch — checkpoint is not loaded,
- // preventing state from bleeding across independent runs on the same Engine.
- if input == nil && e.checkpointer != nil {
- cpData, err := e.checkpointer.Get(ctx, map[string]interface{}{
+ // Load checkpoint when one exists for this thread_id, even when
+ // input is non-nil (resume from a previous run). The canvas
+ // always passes a non-nil input ({"query": ...}) on resume, so
+ // a strict input==nil guard would prevent checkpoint recovery.
+ // We only skip checkpoint loading if the checkpointer reports
+ // no data (fresh start).
+ // When a checkpoint IS loaded, do NOT apply input — the
+ // channel values from the checkpoint already contain the
+ // state at the point of interruption.
+ var (
+ didLoadCheckpoint bool
+ cpCompletedTasks map[string]bool
+ cpLastCompletedNode string
+ cpData map[string]any
+ )
+ if e.checkpointer != nil {
+ var cpErr error
+ cpData, cpErr = e.checkpointer.Get(ctx, map[string]any{
constants.ConfigKeyThreadID: threadID,
})
- if err == nil && cpData != nil {
- if err := channelRegistry.RestoreFromCheckpoint(cpData); err != nil {
- errCh <- fmt.Errorf("failed to restore from checkpoint: %w", err)
- return
+ if cpErr == nil && cpData != nil {
+ didLoadCheckpoint = true
+ common.Debug("LOOP_CHECK: loaded checkpoint",
+ zap.String("thread", threadID),
+ zap.Bool("has_sub", cpData["__sub_state__"] != nil))
+ // Restore sub-state (e.g. Loop iteration, currentInput)
+ // and inject into interrupt context so Loop node can
+ // read it via loadLoopSnapshot on resume.
+ if raw, ok := cpData["__sub_state__"]; ok {
+ switch v := raw.(type) {
+ case []byte:
+ pipelineCtx = context.WithValue(pipelineCtx, interrupt.SubGraphStateCtxKey, v)
+ case string:
+ pipelineCtx = context.WithValue(pipelineCtx, interrupt.SubGraphStateCtxKey, []byte(v))
+ }
+ }
+ // Restore completed task tracking.
+ if raw, ok := cpData["__completed_tasks__"]; ok {
+ if str, ok := raw.(string); ok {
+ cpCompletedTasks = deserializeStringSet(str)
+ }
+ }
+ if raw, ok := cpData["__last_completed_node__"]; ok {
+ if str, ok := raw.(string); ok {
+ cpLastCompletedNode = str
+ }
+ }
+ // Only restore keys that correspond to registered channels.
+ filtered := make(map[string]any)
+ for key, val := range cpData {
+ if _, ok := channelRegistry.Get(key); ok {
+ filtered[key] = val
+ }
+ }
+ if len(filtered) > 0 {
+ if err := channelRegistry.RestoreFromCheckpoint(filtered); err != nil {
+ errCh <- fmt.Errorf("failed to restore from checkpoint: %w", err)
+ return
+ }
}
- // Load checkpoint object
if cp, err := checkpoint.FromMap(cpData); err == nil {
e.currentCheckpoint = cp
}
}
}
+ // Apply input only when no checkpoint was loaded.
+ if !didLoadCheckpoint {
+ if err := e.applyInput(channelRegistry, input); err != nil {
+ errCh <- fmt.Errorf("failed to apply input: %w", err)
+ return
+ }
+ }
// Initialize new checkpoint if none exists
if e.currentCheckpoint == nil {
@@ -281,9 +348,33 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
// Execute Pregel loop
step := 0
- completedTasks := make(map[string]bool)
- lastCompletedNode := ""
- lastState := input
+ var completedTasks map[string]bool
+ lastCompletedNode := cpLastCompletedNode
+ if didLoadCheckpoint && cpCompletedTasks != nil {
+ completedTasks = cpCompletedTasks
+ } else {
+ completedTasks = make(map[string]bool)
+ }
+ var lastState any
+ if didLoadCheckpoint {
+ if raw, ok := cpData["__last_state__"]; ok {
+ var jsonBytes []byte
+ switch val := raw.(type) {
+ case string:
+ jsonBytes = []byte(val)
+ case []byte:
+ jsonBytes = val
+ }
+ if jsonBytes != nil {
+ var decoded map[string]any
+ if json.Unmarshal(jsonBytes, &decoded) == nil {
+ lastState = decoded
+ }
+ }
+ }
+ } else {
+ lastState = input
+ }
for {
// Check context cancellation at each superstep.
@@ -304,7 +395,7 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
streamManager.EmitCheckpoint(step, channelRegistry.CreateCheckpoint())
// Determine next tasks
- tasks, triggers, err := e.prepareNextTasks(channelRegistry, completedTasks, lastCompletedNode, lastState)
+ tasks, triggers, err := e.prepareNextTasks(ctx, channelRegistry, completedTasks, lastCompletedNode, lastState)
if err != nil {
errCh <- fmt.Errorf("failed to prepare next tasks: %w", err)
return
@@ -326,7 +417,7 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
// Save checkpoint
if e.checkpointer != nil {
checkpoint := channelRegistry.CreateCheckpoint()
- if err := e.checkpointer.Put(ctx, map[string]interface{}{
+ if err := e.checkpointer.Put(ctx, map[string]any{
constants.ConfigKeyThreadID: threadID,
}, checkpoint); err != nil {
errCh <- fmt.Errorf("failed to save checkpoint: %w", err)
@@ -354,7 +445,12 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
// Mark tasks as completed and track last state
allFailed := len(results) > 0
+ var interruptTaskNames []string
for _, result := range results {
+ if errors.IsGraphInterrupt(result.Err) {
+ interruptTaskNames = append(interruptTaskNames, result.Name)
+ continue
+ }
if result.Err == nil {
allFailed = false
completedTasks[result.Name] = true
@@ -363,10 +459,73 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
lastState = e.mergeStates(lastState, result.Output)
}
}
+ // If any task was interrupted, handle the interrupt.
+ if len(interruptTaskNames) > 0 {
+ common.Debug("engine interrupt path",
+ zap.Int("step", step),
+ zap.Strings("tasks", interruptTaskNames),
+ zap.Bool("allFailed", allFailed))
+ // Save checkpoint with completed_tasks and sub_state.
+ if e.checkpointer != nil {
+ checkpointData := channelRegistry.CreateCheckpoint()
+ cpPayload := make(map[string]any, len(checkpointData)+4)
+ for key, val := range checkpointData {
+ cpPayload[key] = val
+ }
+ cpPayload["__completed_tasks__"] = serializeStringSet(completedTasks)
+ cpPayload["__last_completed_node__"] = lastCompletedNode
+ cpPayload["__step__"] = float64(step)
+ // Persist lastState as string (not []byte) to avoid
+ // JSON double-base64-encoding when the checkpointer
+ // adapter serializes the whole payload.
+ if lastState != nil {
+ if ls, err := json.Marshal(lastState); err == nil {
+ cpPayload["__last_state__"] = string(ls)
+ }
+ }
+ // Extract sub-state from GraphInterrupt value.
+ for _, r := range results {
+ if gi, ok := r.Err.(*errors.GraphInterrupt); ok && len(gi.Interrupts) > 0 {
+ if intr, ok := gi.Interrupts[0].(*types.Interrupt); ok && intr.Value != nil {
+ if b, e := json.Marshal(intr.Value); e == nil {
+ cpPayload["__sub_state__"] = b
+ }
+ }
+ break
+ }
+ }
+ if err := e.checkpointer.Put(ctx, map[string]any{
+ constants.ConfigKeyThreadID: threadID,
+ }, cpPayload); err != nil {
+ errCh <- fmt.Errorf("failed to save checkpoint on interrupt: %w", err)
+ return
+ }
+ }
+ streamManager.EmitInterrupt(step, interruptTaskNames)
+ // Preserve the first interrupted task's GraphInterrupt value
+ // (with Interrupts populated) instead of creating a bare one,
+ // so MustExtractInterruptContexts can extract the original
+ // UserFillUp spec / tips / cpn_id from it.
+ for _, r := range results {
+ if gi, ok := r.Err.(*errors.GraphInterrupt); ok && len(gi.Interrupts) > 0 {
+ errCh <- gi
+ return
+ }
+ }
+ errCh <- &errors.GraphInterrupt{}
+ return
+ }
// If every task in this step failed, the graph cannot make progress.
// Terminate immediately rather than infinitely re-scheduling the
// same failing nodes (e.g. a panicking node caught by recover()).
if allFailed {
+ var why string
+ for _, r := range results {
+ why += fmt.Sprintf(" %s=%T(%v)", r.Name, r.Err, r.Err)
+ }
+ common.Debug("allFailed",
+ zap.Int("step", step),
+ zap.String("results", why))
errCh <- fmt.Errorf("all %d tasks failed in step %d", len(results), step)
return
}
@@ -397,7 +556,7 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
}
case types.DurabilityAsync:
// Asynchronous save - don't block next step
- go func(cp map[string]interface{}, cpID string, s int) {
+ go func(cp map[string]any, cpID string, s int) {
if err := e.saveCheckpoint(context.Background(), threadID, cpID, s, cp); err != nil {
// Log async error but don't fail execution
common.Error("async checkpoint save failed", err, zap.String("thread_id", threadID), zap.String("checkpoint_id", cpID), zap.Int("step", s))
@@ -416,6 +575,13 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
}
}
+ // Check for after-node interrupts. The checkpoint above already
+ // captures this step's output.
+ if e.shouldInterruptAfter(results) {
+ errCh <- &errors.GraphInterrupt{}
+ return
+ }
+
step++
}
@@ -444,12 +610,13 @@ func (e *Engine) Run(ctx context.Context, input interface{}, mode types.StreamMo
// prepareNextTasks determines which tasks to execute next.
// This is the standard version that prepares tasks for execution.
func (e *Engine) prepareNextTasks(
+ ctx context.Context,
registry *channels.Registry,
completedTasks map[string]bool,
lastCompletedNode string,
- currentState interface{},
+ currentState any,
) ([]*Task, map[string]struct{}, error) {
- return e.prepareNextTasksWithMode(registry, completedTasks, lastCompletedNode, currentState, true)
+ return e.prepareNextTasksWithMode(ctx, registry, completedTasks, lastCompletedNode, currentState, true)
}
// prepareNextTasksWithMode determines which tasks to execute next with for_execution mode.
@@ -460,10 +627,11 @@ func (e *Engine) prepareNextTasks(
// source nodes have completed. In AnyPredecessor (Pregel/BSP) mode (default), a node is
// triggered when any predecessor completes. AllPredecessor does not support cycles.
func (e *Engine) prepareNextTasksWithMode(
+ ctx context.Context,
registry *channels.Registry,
completedTasks map[string]bool,
lastCompletedNode string,
- currentState interface{},
+ currentState any,
forExecution bool,
) ([]*Task, map[string]struct{}, error) {
tasks := make([]*Task, 0)
@@ -488,7 +656,15 @@ func (e *Engine) prepareNextTasksWithMode(
// Pass node Triggers as task Channels so the first task reads from
// registered channels rather than receiving a nil state.
+ // When the entry point has no explicit triggers, use all registered
+ // channel names so it can read the initial input values. This is
+ // needed by systems (e.g. canvas) that route data via context
+ // rather than channels but still register input channels for
+ // the engine's input validation.
triggers := e.getTriggers(node)
+ if len(triggers) == 0 {
+ triggers = registry.Names()
+ }
task := e.createTask(node, currentState, triggers, []string{})
tasks = append(tasks, task)
triggerToNodes["__start__"] = struct{}{}
@@ -503,7 +679,7 @@ func (e *Engine) prepareNextTasksWithMode(
// AnyPredecessor (Pregel/BSP) mode: determine next nodes from the
// last completed node's outgoing edges.
- nextNodes := e.getNextNodes(lastCompletedNode, currentState)
+ nextNodes := e.getNextNodes(ctx, lastCompletedNode, currentState)
for nodeName := range nextNodes {
node := e.getNode(nodeName)
@@ -537,7 +713,7 @@ func (e *Engine) prepareNextTasksWithMode(
// have all completed. This is O(n) per call but correct for fan-in patterns.
func (e *Engine) prepareNextTasksDAG(
completedTasks map[string]bool,
- currentState interface{},
+ currentState any,
forExecution bool,
) ([]*Task, map[string]struct{}, error) {
tasks := make([]*Task, 0)
@@ -642,6 +818,25 @@ func (e *Engine) shouldInterrupt(
return interrupted
}
+// shouldInterruptAfter checks if any SUCCESSFULLY completed task's node name
+// is in interruptsAfter. Called AFTER execution and checkpoint save so the
+// checkpoint already captures the node's output.
+func (e *Engine) shouldInterruptAfter(results []*TaskResult) bool {
+ if len(e.interruptsAfter) == 0 {
+ return false
+ }
+ interruptAll := e.interruptsAfter[types.All]
+ for _, r := range results {
+ if r.Err != nil {
+ continue
+ }
+ if interruptAll || e.interruptsAfter[r.Name] {
+ return true
+ }
+ }
+ return false
+}
+
// applyWrites applies task outputs to channels with version management and write merging.
func (e *Engine) applyWrites(
registry *channels.Registry,
@@ -656,7 +851,7 @@ func (e *Engine) applyWrites(
})
// Group writes by channel with write merging
- writesByChannel := make(map[string][]interface{})
+ writesByChannel := make(map[string][]any)
pendingWrites := make(map[string]*checkpoint.PendingWrite)
for _, result := range results {
@@ -709,10 +904,10 @@ func (e *Engine) applyWrites(
for channelName, values := range writesByChannel {
if ch, ok := registry.Get(channelName); ok {
// Filter out nil values
- filtered := make([]interface{}, 0, len(values))
- for _, v := range values {
- if v != nil {
- filtered = append(filtered, v)
+ filtered := make([]any, 0, len(values))
+ for _, val := range values {
+ if val != nil {
+ filtered = append(filtered, val)
}
}
@@ -841,7 +1036,7 @@ func (e *Engine) executeTasksAsync(
}
// Define the function to execute
- executeFn := func(ctx context.Context) (interface{}, error) {
+ executeFn := func(ctx context.Context) (any, error) {
return t.Func(ctx, input)
}
@@ -929,7 +1124,7 @@ func (e *Engine) executeTask(
retryExecutor := NewRetryExecutor(retryPolicy)
// Define the function to execute
- executeFn := func(ctx context.Context) (interface{}, error) {
+ executeFn := func(ctx context.Context) (any, error) {
return task.Func(ctx, input)
}
@@ -966,13 +1161,13 @@ func (e *Engine) executeTask(
}
// readTaskInput reads the input for a task from channels.
-func (e *Engine) readTaskInput(registry *channels.Registry, task *Task) (interface{}, error) {
+func (e *Engine) readTaskInput(registry *channels.Registry, task *Task) (any, error) {
if len(task.Channels) == 0 {
return nil, nil
}
// Read values from specified channels
- values := make(map[string]interface{})
+ values := make(map[string]any)
for _, channelName := range task.Channels {
if ch, ok := registry.Get(channelName); ok {
value, err := ch.Get()
@@ -1004,7 +1199,7 @@ type Task struct {
// TaskResult represents the result of executing a task.
type TaskResult struct {
Name string
- Output interface{}
+ Output any
Err error
Path []string // Task path for deterministic ordering (like Python's task_path)
}
@@ -1029,21 +1224,21 @@ func ParseTaskPath(pathStr string) []string {
// BuildTaskPath builds a task path from components.
// Supports nested paths like Python's tuple-based paths.
-func BuildTaskPath(components ...interface{}) []string {
+func BuildTaskPath(components ...any) []string {
path := make([]string, 0, len(components))
for _, comp := range components {
- switch v := comp.(type) {
+ switch val := comp.(type) {
case string:
- path = append(path, v)
+ path = append(path, val)
case int:
- path = append(path, fmt.Sprintf("%d", v))
+ path = append(path, fmt.Sprintf("%d", val))
case []string:
- path = append(path, v...)
+ path = append(path, val...)
default:
- if s, ok := v.(fmt.Stringer); ok {
- path = append(path, s.String())
+ if stringer, ok := val.(fmt.Stringer); ok {
+ path = append(path, stringer.String())
} else {
- path = append(path, fmt.Sprintf("%v", v))
+ path = append(path, fmt.Sprintf("%v", val))
}
}
}
@@ -1060,34 +1255,43 @@ func (e *Engine) getEntryPoint() string {
}
func (e *Engine) getNode(name string) *graph.Node {
- n, _ := e.graph.GetNode(name)
- return n
+ node, _ := e.graph.GetNode(name)
+ return node
}
-func (e *Engine) getNextNodes(node string, state interface{}) map[string]bool {
+func (e *Engine) getNextNodes(ctx context.Context, node string, state any) map[string]bool {
+ common.Debug("getNextNodes",
+ zap.String("node", node),
+ zap.Any("state", state))
nextNodes := make(map[string]bool)
- // Check conditional edges
+ // (1) Check conditional edges. When a node has conditional edges,
+ // ONLY the matched target(s) are scheduled — the regular-edge
+ // fallback is skipped entirely so branchable nodes (Switch,
+ // Categorize) route exclusively via the _next value.
+ hasConditional := false
for _, condEdge := range e.graph.GetConditionalEdges() {
- if condEdge.From == node {
- conditionResult, err := condEdge.Condition(nil, state)
- if err != nil {
- continue
- }
- conditionKey := fmt.Sprintf("%v", conditionResult)
- targetNode, ok := condEdge.Mapping[conditionKey]
- if !ok {
- continue
- }
- if targetNode == constants.End {
- return nextNodes // Return empty to signal end
- }
- nextNodes[targetNode] = true
+ if condEdge.From != node {
+ continue
}
+ hasConditional = true
+ conditionResult, err := condEdge.Condition(ctx, state)
+ if err != nil {
+ continue
+ }
+ conditionKey := fmt.Sprintf("%v", conditionResult)
+ targetNode, ok := condEdge.Mapping[conditionKey]
+ if !ok {
+ continue
+ }
+ if targetNode == constants.End {
+ return nextNodes
+ }
+ nextNodes[targetNode] = true
}
- // Check regular edges if no conditional edge was found
- if len(nextNodes) == 0 {
+ // (2) Regular edges: ONLY when this node has no conditional edges.
+ if !hasConditional && len(nextNodes) == 0 {
for _, edge := range e.graph.GetEdges() {
if edge.From == node {
if edge.To == constants.End {
@@ -1098,10 +1302,36 @@ func (e *Engine) getNextNodes(node string, state interface{}) map[string]bool {
}
}
- // Check branches
+ // (3) Resume fallback: when the last completed node has no outgoing
+ // edges but the graph state contains _next (persisted from a
+ // Switch/Categorize branch), route directly from _next. This
+ // happens on checkpoint resume because the conditional edge is
+ // registered on the Switch node, not on __loop_init__.
+ if len(nextNodes) == 0 {
+ if st, ok := state.(map[string]any); ok {
+ if raw, has := st["_next"]; has && raw != nil {
+ switch tv := raw.(type) {
+ case string:
+ if _, exists := e.graph.GetNode(tv); exists {
+ nextNodes[tv] = true
+ }
+ case []any:
+ if len(tv) > 0 {
+ if str, ok := tv[0].(string); ok {
+ if _, exists := e.graph.GetNode(str); exists {
+ nextNodes[str] = true
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // (4) Branches: always included on top of whatever was scheduled.
for _, branch := range e.graph.GetBranches() {
if branch.From == node {
- branchResult, err := branch.Condition(nil, state)
+ branchResult, err := branch.Condition(ctx, state)
if err != nil {
continue
}
@@ -1125,7 +1355,7 @@ func (e *Engine) getTriggers(node *graph.Node) []string {
return node.Triggers
}
-func (e *Engine) createTask(node *graph.Node, state interface{}, channels []string, triggers []string) *Task {
+func (e *Engine) createTask(node *graph.Node, state any, channels []string, triggers []string) *Task {
task := &Task{
ID: uuid.New().String(),
Name: node.Name,
@@ -1143,7 +1373,7 @@ func (e *Engine) createTask(node *graph.Node, state interface{}, channels []stri
// createTaskInfo creates a task info object for inspection/planning (for_execution=false mode).
// This is similar to Python's prepare_next_tasks with for_execution=False.
-func (e *Engine) createTaskInfo(node *graph.Node, state interface{}, channels []string, triggers []string) *Task {
+func (e *Engine) createTaskInfo(node *graph.Node, state any, channels []string, triggers []string) *Task {
task := &Task{
ID: uuid.New().String(),
Name: node.Name,
@@ -1160,15 +1390,16 @@ func (e *Engine) createTaskInfo(node *graph.Node, state interface{}, channels []
// PrepareNextTasksForInspection prepares tasks for inspection/planning only (for_execution=false).
// This corresponds to Python's prepare_next_tasks with for_execution=False.
func (e *Engine) PrepareNextTasksForInspection(
+ ctx context.Context,
registry *channels.Registry,
completedTasks map[string]bool,
lastCompletedNode string,
- currentState interface{},
+ currentState any,
) ([]*Task, map[string]struct{}, error) {
- return e.prepareNextTasksWithMode(registry, completedTasks, lastCompletedNode, currentState, false)
+ return e.prepareNextTasksWithMode(ctx, registry, completedTasks, lastCompletedNode, currentState, false)
}
-func (e *Engine) applyInput(registry *channels.Registry, input interface{}) error {
+func (e *Engine) applyInput(registry *channels.Registry, input any) error {
// Convert input to map
inputMap, err := toMap(input)
if err != nil {
@@ -1176,9 +1407,9 @@ func (e *Engine) applyInput(registry *channels.Registry, input interface{}) erro
}
// Apply each key to corresponding channel
- writes := make(map[string][]interface{})
+ writes := make(map[string][]any)
for key, value := range inputMap {
- writes[key] = []interface{}{value}
+ writes[key] = []any{value}
}
return registry.UpdateChannels(writes)
@@ -1193,7 +1424,7 @@ func (e *Engine) getThreadID() string {
return uuid.New().String()
}
-func (e *Engine) buildOutput(registry *channels.Registry, lastState interface{}) (interface{}, error) {
+func (e *Engine) buildOutput(registry *channels.Registry, lastState any) (any, error) {
values, err := registry.GetValues()
if err != nil {
return lastState, nil
@@ -1206,55 +1437,55 @@ func (e *Engine) buildOutput(registry *channels.Registry, lastState interface{})
return lastState, nil
}
-func (e *Engine) mergeStates(existing, new interface{}) interface{} {
+func (e *Engine) mergeStates(existing, next any) any {
if existing == nil {
- return new
+ return next
}
- if new == nil {
+ if next == nil {
return existing
}
// Try to merge maps
- existingMap, ok1 := existing.(map[string]interface{})
- newMap, ok2 := new.(map[string]interface{})
+ existingMap, ok1 := existing.(map[string]any)
+ nextMap, ok2 := next.(map[string]any)
if ok1 && ok2 {
- result := make(map[string]interface{})
- for k, v := range existingMap {
- result[k] = v
+ result := make(map[string]any)
+ for key, val := range existingMap {
+ result[key] = val
}
- for k, v := range newMap {
- result[k] = v
+ for key, val := range nextMap {
+ result[key] = val
}
return result
}
- return new
+ return next
}
-// toMap converts a struct or map to a map[string]interface{}.
-func toMap(v interface{}) (map[string]interface{}, error) {
- if v == nil {
+// toMap converts a struct or map to a map[string]any.
+func toMap(val any) (map[string]any, error) {
+ if val == nil {
return nil, fmt.Errorf("nil value")
}
// If it's already a map
- if m, ok := v.(map[string]interface{}); ok {
+ if m, ok := val.(map[string]any); ok {
return m, nil
}
// Use reflection to convert struct to map
- rv := reflect.ValueOf(v)
+ rv := reflect.ValueOf(val)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map {
- return map[string]interface{}{"__root__": v}, nil
+ return map[string]any{"__root__": val}, nil
}
- result := make(map[string]interface{})
+ result := make(map[string]any)
if rv.Kind() == reflect.Map {
for _, key := range rv.MapKeys() {
@@ -1271,20 +1502,20 @@ func toMap(v interface{}) (map[string]interface{}, error) {
if field.PkgPath != "" {
continue
}
- value := rv.Field(i).Interface()
+ val := rv.Field(i).Interface()
// Convert field name to snake_case for consistency
fieldName := toSnakeCase(field.Name)
- result[fieldName] = value
+ result[fieldName] = val
}
return result, nil
}
// toSnakeCase converts CamelCase to snake_case.
-func toSnakeCase(s string) string {
+func toSnakeCase(name string) string {
var result []rune
- for i, r := range s {
+ for i, r := range name {
if i > 0 && r >= 'A' && r <= 'Z' {
result = append(result, '_')
}
@@ -1294,11 +1525,11 @@ func toSnakeCase(s string) string {
}
// saveCheckpoint saves a checkpoint to the checkpointer.
-func (e *Engine) saveCheckpoint(ctx context.Context, threadID, checkpointID string, step int, checkpoint map[string]interface{}) error {
+func (e *Engine) saveCheckpoint(ctx context.Context, threadID, checkpointID string, step int, checkpoint map[string]any) error {
if e.checkpointer == nil {
return nil
}
- return e.checkpointer.Put(ctx, map[string]interface{}{
+ return e.checkpointer.Put(ctx, map[string]any{
constants.ConfigKeyThreadID: threadID,
constants.ConfigKeyCheckpointID: checkpointID,
"step": step,
@@ -1306,7 +1537,7 @@ func (e *Engine) saveCheckpoint(ctx context.Context, threadID, checkpointID stri
}
// deferCheckpoint defers a checkpoint save for DurabilityExit mode.
-func (e *Engine) deferCheckpoint(threadID, checkpointID string, step int, checkpoint map[string]interface{}) {
+func (e *Engine) deferCheckpoint(threadID, checkpointID string, step int, checkpoint map[string]any) {
e.deferredCheckpoints = append(e.deferredCheckpoints, deferredCheckpoint{
ThreadID: threadID,
CheckpointID: checkpointID,
@@ -1336,60 +1567,65 @@ func (e *Engine) saveDeferredCheckpoints(ctx context.Context) error {
// RunSync executes the graph synchronously and returns the final state.
// This is a convenience wrapper around Run() for callers that want a blocking API.
-func (e *Engine) RunSync(ctx context.Context, input interface{}) (interface{}, error) {
+//
+// RunSync first drains all events from outputCh (reading until it is closed),
+// then checks errCh for any execution error. This ordering avoids a race
+// between the EventTypeFinal arriving on outputCh and errCh being closed
+// (the defer calling close(errCh) runs AFTER close(outputCh)).
+func (e *Engine) RunSync(ctx context.Context, input any) (any, error) {
outputCh, errCh := e.Run(ctx, input, types.StreamModeValues)
- var finalState interface{}
- for {
- select {
- case result, ok := <-outputCh:
- if !ok {
- return finalState, nil
- }
- // Extract final state from StreamEvent wrapping
- if se, ok := result.(*StreamEvent); ok && se.Type == EventTypeFinal {
- if data, ok := se.Data.(map[string]interface{}); ok {
- if state, ok := data["state"]; ok {
- finalState = state
- }
+ var finalState any
+
+ // Drain outputCh to capture the final state event.
+ // Must read until closed to avoid leaking the forward goroutine.
+ for result := range outputCh {
+ if se, ok := result.(*StreamEvent); ok && se.Type == EventTypeFinal {
+ if data, ok := se.Data.(map[string]any); ok {
+ if state, ok := data["state"]; ok {
+ finalState = state
}
}
- case err := <-errCh:
- if err != nil {
- return nil, err
- }
- return finalState, nil
- case <-ctx.Done():
- return nil, ctx.Err()
}
}
+
+ // Check for execution errors (non-blocking; errCh is closed after outputCh).
+ select {
+ case err := <-errCh:
+ if err != nil {
+ return nil, err
+ }
+ default:
+ }
+
+ return finalState, nil
}
// applyFieldMapping filters and remaps an output map according to FieldMapping rules.
// If no mappings are specified, the entire output map is passed through unchanged.
// Each mapping specifies a source field path (From) and a target field path (To).
-func applyFieldMapping(output map[string]interface{}, mappings []graph.FieldMapping) map[string]interface{} {
+func applyFieldMapping(output map[string]any, mappings []graph.FieldMapping) map[string]any {
if len(mappings) == 0 {
return output
}
- result := make(map[string]interface{}, len(mappings))
- for _, m := range mappings {
- val := getNestedField(output, m.From)
+ result := make(map[string]any, len(mappings))
+ for _, mapping := range mappings {
+ val := getNestedField(output, mapping.From)
if val != nil {
- setNestedField(result, m.To, val)
+ setNestedField(result, mapping.To, val)
}
}
return result
}
// getNestedField retrieves a value from a nested map using a dot-separated path.
-func getNestedField(m map[string]interface{}, path string) interface{} {
+func getNestedField(m map[string]any, path string) any {
if path == "" {
return m // return entire map
}
parts := strings.Split(path, ".")
- var cur interface{} = m
+ var cur any = m
for _, part := range parts {
- cm, ok := cur.(map[string]interface{})
+ cm, ok := cur.(map[string]any)
if !ok {
return nil
}
@@ -1402,9 +1638,9 @@ func getNestedField(m map[string]interface{}, path string) interface{} {
}
// setNestedField sets a value in a nested map using a dot-separated path.
-func setNestedField(m map[string]interface{}, path string, val interface{}) {
+func setNestedField(m map[string]any, path string, val any) {
if path == "" {
- for k, v := range val.(map[string]interface{}) {
+ for k, v := range val.(map[string]any) {
m[k] = v
}
return
@@ -1413,16 +1649,51 @@ func setNestedField(m map[string]interface{}, path string, val interface{}) {
for i := 0; i < len(parts)-1; i++ {
sub, ok := m[parts[i]]
if !ok {
- sub = make(map[string]interface{})
+ sub = make(map[string]any)
m[parts[i]] = sub
}
var ok2 bool
- m, ok2 = sub.(map[string]interface{})
+ m, ok2 = sub.(map[string]any)
if !ok2 {
- nm := make(map[string]interface{})
+ nm := make(map[string]any)
m[parts[i]] = nm
m = nm
}
}
m[parts[len(parts)-1]] = val
}
+
+// serializeStringSet encodes a map[string]bool to a NUL-separated string
+// for storage in the checkpoint payload.
+func serializeStringSet(set map[string]bool) string {
+ if len(set) == 0 {
+ return ""
+ }
+ keys := make([]string, 0, len(set))
+ for key := range set {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ out := make([]byte, 0, 256)
+ for i, key := range keys {
+ if i > 0 {
+ out = append(out, 0)
+ }
+ out = append(out, key...)
+ }
+ return string(out)
+}
+
+// deserializeStringSet decodes a NUL-separated string back to a
+// map[string]bool.
+func deserializeStringSet(encoded string) map[string]bool {
+ if encoded == "" {
+ return nil
+ }
+ parts := strings.Split(encoded, "\x00")
+ out := make(map[string]bool, len(parts))
+ for _, part := range parts {
+ out[part] = true
+ }
+ return out
+}
diff --git a/internal/harness/graph/pregel/engine_test.go b/internal/harness/graph/pregel/engine_test.go
index 625c38f6e2..e34e6c043a 100644
--- a/internal/harness/graph/pregel/engine_test.go
+++ b/internal/harness/graph/pregel/engine_test.go
@@ -17,22 +17,22 @@ func newTestGraph(t *testing.T) *graph.StateGraph {
func newSimpleGraph(t *testing.T) *graph.StateGraph {
t.Helper()
- sg := graph.NewStateGraph(map[string]interface{}{"value": ""})
+ sg := graph.NewStateGraph(map[string]any{"value": ""})
// Register a channel so the engine can write output
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("node_a", func(ctx context.Context, state interface{}) (interface{}, error) {
- m, _ := state.(map[string]interface{})
+ sg.AddNode("node_a", func(ctx context.Context, state any) (any, error) {
+ m, _ := state.(map[string]any)
if m == nil {
- m = map[string]interface{}{}
+ m = map[string]any{}
}
m["value"] = "a"
return m, nil
})
- sg.AddNode("node_b", func(ctx context.Context, state interface{}) (interface{}, error) {
- m, _ := state.(map[string]interface{})
+ sg.AddNode("node_b", func(ctx context.Context, state any) (any, error) {
+ m, _ := state.(map[string]any)
if m == nil {
- m = map[string]interface{}{}
+ m = map[string]any{}
}
m["value"] = "b"
return m, nil
@@ -67,16 +67,14 @@ func TestEngine_RunSync(t *testing.T) {
sg := newSimpleGraph(t)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{"value": "start"})
+ result, err := engine.RunSync(context.Background(), map[string]any{"value": "start"})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
- // result may be nil if the engine's goroutine closes the output channel
- // before sending the final state event (channel timing). The graph still
- // executed correctly — the state is consumed by the engine's channel system.
if result == nil {
- t.Log("RunSync returned nil result (channel closed before EventTypeFinal)")
- } else if m, ok := result.(map[string]interface{}); ok {
+ t.Fatal("expected non-nil result")
+ }
+ if m, ok := result.(map[string]any); ok {
if m["value"] != "b" {
t.Errorf("expected value='b', got %v", m["value"])
}
@@ -84,13 +82,13 @@ func TestEngine_RunSync(t *testing.T) {
}
func TestEngine_RunSyncWithChannelRead(t *testing.T) {
- sg := graph.NewStateGraph(map[string]interface{}{"name": ""})
+ sg := graph.NewStateGraph(map[string]any{"name": ""})
sg.AddChannel("name", channels.NewLastValue(""))
- sg.AddNode("echo", func(ctx context.Context, state interface{}) (interface{}, error) {
- m, ok := state.(map[string]interface{})
+ sg.AddNode("echo", func(ctx context.Context, state any) (any, error) {
+ m, ok := state.(map[string]any)
if !ok || m == nil {
- m = map[string]interface{}{}
+ m = map[string]any{}
}
m["name"] = "echoed"
return m, nil
@@ -103,7 +101,7 @@ func TestEngine_RunSyncWithChannelRead(t *testing.T) {
}
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{"name": "world"})
+ result, err := engine.RunSync(context.Background(), map[string]any{"name": "world"})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -118,7 +116,7 @@ func TestEngine_RecursionLimit(t *testing.T) {
sg.AddEdge("node_a", constants.End)
engine := NewEngine(sg, WithRecursionLimit(3))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{"value": "x"})
+ _, err := engine.RunSync(context.Background(), map[string]any{"value": "x"})
if err != nil {
// Engine runs successfully: node_a -> node_b -> node_a loops via self-edge
t.Logf("got error (expected from recursion limit): %v", err)
@@ -147,10 +145,10 @@ func TestEngine_ConfigPropagation(t *testing.T) {
}
func TestEngine_EmptyGraph(t *testing.T) {
- sg := graph.NewStateGraph(map[string]interface{}{"x": ""})
+ sg := graph.NewStateGraph(map[string]any{"x": ""})
sg.AddChannel("x", channels.NewLastValue(""))
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{"x": "1"})
+ _, err := engine.RunSync(context.Background(), map[string]any{"x": "1"})
if err == nil {
t.Fatal("expected error for graph with no entry point")
}
diff --git a/internal/harness/graph/pregel/messages.go b/internal/harness/graph/pregel/messages.go
index f3f1143f34..f16120d4a0 100644
--- a/internal/harness/graph/pregel/messages.go
+++ b/internal/harness/graph/pregel/messages.go
@@ -29,19 +29,19 @@ type MessageStream struct {
// MessageChunk represents a chunk of a message.
type MessageChunk struct {
- Index int
- Content string
- Metadata map[string]interface{}
- IsComplete bool
- Role string
- ToolCalls []*ToolCall
+ Index int
+ Content string
+ Metadata map[string]any
+ IsComplete bool
+ Role string
+ ToolCalls []*ToolCall
}
// ToolCall represents a tool call within a message.
type ToolCall struct {
- ID string
- Name string
- Arguments map[string]interface{}
+ ID string
+ Name string
+ Arguments map[string]any
}
// FlushTrigger determines when to flush aggregated messages.
@@ -104,7 +104,7 @@ func (h *StreamMessagesHandler) OnChunk(ctx context.Context, node string, chunk
if ms.current == nil || ms.current.IsComplete {
ms.current = &MessageChunk{
Index: len(ms.chunks),
- Metadata: make(map[string]interface{}),
+ Metadata: make(map[string]any),
}
}
@@ -114,7 +114,7 @@ func (h *StreamMessagesHandler) OnChunk(ctx context.Context, node string, chunk
// Update metadata
if chunk.Metadata != nil {
if ms.current.Metadata == nil {
- ms.current.Metadata = make(map[string]interface{})
+ ms.current.Metadata = make(map[string]any)
}
for k, v := range chunk.Metadata {
ms.current.Metadata[k] = v
@@ -297,12 +297,12 @@ func (a *MessageAggregator) AddEmitter(emitter MessageEmitter) {
// StreamToChannel emits messages to a stream channel.
func StreamToChannel(ch *types.ChannelStream) MessageEmitter {
return func(ctx context.Context, node string, chunk *MessageChunk) error {
- chunkData := map[string]interface{}{
- "node": node,
- "role": chunk.Role,
- "content": chunk.Content,
- "index": chunk.Index,
- "complete": chunk.IsComplete,
+ chunkData := map[string]any{
+ "node": node,
+ "role": chunk.Role,
+ "content": chunk.Content,
+ "index": chunk.Index,
+ "complete": chunk.IsComplete,
}
if len(chunk.ToolCalls) > 0 {
chunkData["tool_calls"] = chunk.ToolCalls
@@ -351,7 +351,7 @@ func StreamModeMessages(opts ...StreamMessagesOption) *StreamMessagesHandler {
}
// ExtractMessagesFromOutput extracts messages from node output.
-func ExtractMessagesFromOutput(output interface{}) ([]*MessageChunk, error) {
+func ExtractMessagesFromOutput(output any) ([]*MessageChunk, error) {
// Check if output is already a MessageChunk
if chunk, ok := output.(*MessageChunk); ok {
return []*MessageChunk{chunk}, nil
@@ -363,16 +363,16 @@ func ExtractMessagesFromOutput(output interface{}) ([]*MessageChunk, error) {
}
// Try to extract from map
- if m, ok := output.(map[string]interface{}); ok {
+ if m, ok := output.(map[string]any); ok {
if content, ok := m["content"].(string); ok {
role := "assistant"
if r, ok := m["role"].(string); ok {
role = r
}
chunk := &MessageChunk{
- Content: content,
- Role: role,
- Metadata: make(map[string]interface{}),
+ Content: content,
+ Role: role,
+ Metadata: make(map[string]any),
}
return []*MessageChunk{chunk}, nil
}
@@ -393,9 +393,9 @@ func ConvertToTaskResult(node string, chunks []*MessageChunk) *TaskResult {
// Merge chunks
merged := &MessageChunk{
- Content: "",
- Metadata: make(map[string]interface{}),
- ToolCalls: make([]*ToolCall, 0),
+ Content: "",
+ Metadata: make(map[string]any),
+ ToolCalls: make([]*ToolCall, 0),
}
for _, chunk := range chunks {
@@ -412,7 +412,7 @@ func ConvertToTaskResult(node string, chunks []*MessageChunk) *TaskResult {
}
// Convert to map for output
- output := map[string]interface{}{
+ output := map[string]any{
"messages": []*MessageChunk{merged},
"content": merged.Content,
"role": merged.Role,
diff --git a/internal/harness/graph/pregel/optimized.go b/internal/harness/graph/pregel/optimized.go
index a68e32ce2c..0b2658f3e0 100644
--- a/internal/harness/graph/pregel/optimized.go
+++ b/internal/harness/graph/pregel/optimized.go
@@ -13,16 +13,16 @@ import (
// OptimizedEngineConfig configures the optimized Pregel engine.
type OptimizedEngineConfig struct {
- BumpStep bool
+ BumpStep bool
FinishNotification bool
- TaskPriority bool
+ TaskPriority bool
}
// PregelOptimizedEngine extends Engine with Python-style Pregel algorithm optimizations.
type PregelOptimizedEngine struct {
*Engine
config *OptimizedEngineConfig
- taskPriorityQueue []*TaskWithPriority
+ taskPriorityQueue []*TaskWithPriority
stepQueue map[int][]string
seenChannels map[string]map[string]bool
readyChannels map[string]bool
@@ -44,16 +44,16 @@ type TaskWithPriority struct {
func NewPregelOptimizedEngine(baseEngine *Engine, config *OptimizedEngineConfig) *PregelOptimizedEngine {
if config == nil {
config = &OptimizedEngineConfig{
- BumpStep: true,
+ BumpStep: true,
FinishNotification: true,
- TaskPriority: true,
+ TaskPriority: true,
}
}
-
+
return &PregelOptimizedEngine{
- Engine: baseEngine,
+ Engine: baseEngine,
config: config,
- taskPriorityQueue: make([]*TaskWithPriority, 0, 100),
+ taskPriorityQueue: make([]*TaskWithPriority, 0, 100),
stepQueue: make(map[int][]string),
seenChannels: make(map[string]map[string]bool),
readyChannels: make(map[string]bool),
@@ -74,22 +74,22 @@ func (e *PregelOptimizedEngine) BumpStep(
) error {
e.mu.Lock()
defer e.mu.Unlock()
-
+
// Mark task as finished
e.finishedTasks[taskName] = true
-
+
// Find dependent tasks
dependencies, exists := e.taskDependencies[taskName]
if !exists || len(dependencies) == 0 {
// No dependent tasks, nothing to bump
return nil
}
-
+
for _, depTask := range dependencies {
// Check if dependent task has seen all updated channels
ready := true
seenChannels := e.seenChannels[depTask]
-
+
for channel := range updatedChannels {
if seenChannels != nil && !seenChannels[channel] {
// This dependent task needs to be bumped
@@ -97,11 +97,11 @@ func (e *PregelOptimizedEngine) BumpStep(
break
}
}
-
+
if ready {
// Bump task to current step
e.stepQueue[completedStep+1] = append(e.stepQueue[completedStep+1], depTask)
-
+
// Mark channels as seen for this task
if e.seenChannels[depTask] == nil {
e.seenChannels[depTask] = make(map[string]bool)
@@ -111,7 +111,7 @@ func (e *PregelOptimizedEngine) BumpStep(
}
}
}
-
+
return nil
}
@@ -120,24 +120,24 @@ func (e *PregelOptimizedEngine) BumpStep(
func (e *PregelOptimizedEngine) FinishNotification(
ctx context.Context,
taskName string,
- result interface{},
+ result any,
err error,
completedStep int,
) {
if !e.config.FinishNotification {
return
}
-
+
// Build finish notification
notification := &FinishNotification{
- TaskName: taskName,
- Output: result,
- Error: err,
- Step: completedStep,
- Timestamp: time.Now(),
- Namespace: e.getNamespace(ctx),
- }
-
+ TaskName: taskName,
+ Output: result,
+ Error: err,
+ Step: completedStep,
+ Timestamp: time.Now(),
+ Namespace: e.getNamespace(ctx),
+ }
+
// Send to stream manager if available
// Note: This requires the Engine to have access to streamManager
// For now, we'll just log it
@@ -146,7 +146,7 @@ func (e *PregelOptimizedEngine) FinishNotification(
} else {
fmt.Printf("[FinishNotification] Task %s completed at step %d\n", taskName, completedStep)
}
-
+
_ = notification // Mark as used to avoid unused variable error
}
@@ -205,7 +205,7 @@ func (e *PregelOptimizedEngine) OptimizedApplyWrites(
})
// Group and apply writes
- writesByChannel := make(map[string][]interface{})
+ writesByChannel := make(map[string][]any)
for _, result := range results {
if result.Err != nil {
@@ -233,7 +233,7 @@ func (e *PregelOptimizedEngine) OptimizedApplyWrites(
continue
}
- filtered := make([]interface{}, 0, len(values))
+ filtered := make([]any, 0, len(values))
for _, v := range values {
if v != nil {
filtered = append(filtered, v)
@@ -290,11 +290,11 @@ func (e *PregelOptimizedEngine) OptimizedApplyWrites(
func (e *PregelOptimizedEngine) AddTaskDependency(fromTask, toTask string) {
e.mu.Lock()
defer e.mu.Unlock()
-
+
if e.taskDependencies[toTask] == nil {
e.taskDependencies[toTask] = make([]string, 0)
}
-
+
// Add dependency (fromTask depends on toTask)
e.taskDependencies[toTask] = append(e.taskDependencies[toTask], fromTask)
}
@@ -303,7 +303,7 @@ func (e *PregelOptimizedEngine) AddTaskDependency(fromTask, toTask string) {
func (e *PregelOptimizedEngine) GetTaskDependencies(taskName string) []string {
e.mu.RLock()
defer e.mu.RUnlock()
-
+
if deps, exists := e.taskDependencies[taskName]; exists {
return append([]string{}, deps...)
}
@@ -314,20 +314,20 @@ func (e *PregelOptimizedEngine) GetTaskDependencies(taskName string) []string {
func (e *PregelOptimizedEngine) IsTaskReady(taskName string) bool {
e.mu.RLock()
defer e.mu.RUnlock()
-
+
// Check if task has been seen all required channels
// This is a simplified check - in practice you'd check specific channels
if len(e.taskDependencies[taskName]) == 0 {
return true
}
-
+
// Check if any dependencies are still unfinished
for _, dep := range e.taskDependencies[taskName] {
if !e.finishedTasks[dep] {
return false
}
}
-
+
return true
}
@@ -340,12 +340,12 @@ func (e *PregelOptimizedEngine) getNamespace(ctx context.Context) string {
// FinishNotification represents a task completion notification.
type FinishNotification struct {
- TaskName string `json:"task_name"`
- Output interface{} `json:"output"`
- Error error `json:"error,omitempty"`
- Step int `json:"step"`
- Timestamp time.Time `json:"timestamp"`
- Namespace string `json:"namespace,omitempty"`
+ TaskName string `json:"task_name"`
+ Output any `json:"output"`
+ Error error `json:"error,omitempty"`
+ Step int `json:"step"`
+ Timestamp time.Time `json:"timestamp"`
+ Namespace string `json:"namespace,omitempty"`
}
// TaskPriority represents task execution priority.
@@ -370,12 +370,12 @@ func (tp *TaskPriority) Compare(other *TaskPriority) int {
if tp.Priority != other.Priority {
return tp.Priority - other.Priority
}
-
+
// Then by path length
if len(tp.Path) != len(other.Path) {
return len(tp.Path) - len(other.Path)
}
-
+
// Finally by path lexicographically
for i := 0; i < len(tp.Path); i++ {
if tp.Path[i] != other.Path[i] {
@@ -385,7 +385,7 @@ func (tp *TaskPriority) Compare(other *TaskPriority) int {
return 1
}
}
-
+
return 0
}
@@ -396,8 +396,8 @@ func (tp *TaskPriority) Compare(other *TaskPriority) int {
// callers to integrate into custom execution flows.
func (e *PregelOptimizedEngine) OptimizedRun(
ctx context.Context,
- input interface{},
-) (interface{}, error) {
+ input any,
+) (any, error) {
return e.RunSync(ctx, input)
}
@@ -411,17 +411,17 @@ func (e *PregelOptimizedEngine) ExecuteTaskWithPriority(
// Mark task as executing
e.mu.Lock()
taskWithPriority := &TaskWithPriority{
- Task: task,
+ Task: task,
Priority: priority,
Namespace: namespace,
Path: []string{namespace, task.Name},
}
e.taskPriorityQueue = append(e.taskPriorityQueue, taskWithPriority)
e.mu.Unlock()
-
- // Execute task
- output, err := task.Func(ctx, nil)
-
+
+ // Execute task
+ output, err := task.Func(ctx, nil)
+
return &TaskResult{
Name: task.Name,
Output: output,
@@ -433,12 +433,12 @@ func (e *PregelOptimizedEngine) ExecuteTaskWithPriority(
func (e *PregelOptimizedEngine) GetNextPriorityTask() *TaskWithPriority {
e.mu.Lock()
defer e.mu.Unlock()
-
+
if len(e.taskPriorityQueue) == 0 {
return nil
}
-
- // Sort by priority (could use heap for better performance)
+
+ // Sort by priority (could use heap for better performance)
sort.Slice(e.taskPriorityQueue, func(i, j int) bool {
tp1 := &TaskPriority{
Name: e.taskPriorityQueue[i].Name,
@@ -452,15 +452,15 @@ func (e *PregelOptimizedEngine) GetNextPriorityTask() *TaskWithPriority {
}
return tp1.Compare(tp2) < 0
})
-
+
// Get first task
if len(e.taskPriorityQueue) == 0 {
return nil
}
-
+
task := e.taskPriorityQueue[0]
e.taskPriorityQueue = e.taskPriorityQueue[1:]
-
+
return task
}
@@ -468,7 +468,7 @@ func (e *PregelOptimizedEngine) GetNextPriorityTask() *TaskWithPriority {
func (e *PregelOptimizedEngine) ClearFinishedTasks() {
e.mu.Lock()
defer e.mu.Unlock()
-
+
e.finishedTasks = make(map[string]bool)
}
@@ -476,12 +476,12 @@ func (e *PregelOptimizedEngine) ClearFinishedTasks() {
func (e *PregelOptimizedEngine) GetFinishedTasks() []string {
e.mu.RLock()
defer e.mu.RUnlock()
-
+
tasks := make([]string, 0, len(e.finishedTasks))
for name := range e.finishedTasks {
tasks = append(tasks, name)
}
-
+
return tasks
}
@@ -489,7 +489,7 @@ func (e *PregelOptimizedEngine) GetFinishedTasks() []string {
func (e *PregelOptimizedEngine) Reset() {
e.mu.Lock()
defer e.mu.Unlock()
-
+
e.taskPriorityQueue = make([]*TaskWithPriority, 0, 100)
e.stepQueue = make(map[int][]string)
e.seenChannels = make(map[string]map[string]bool)
@@ -552,7 +552,7 @@ func (e *PregelOptimizedEngine) getDependencies(taskName string) []string {
func (e *PregelOptimizedEngine) hasSeenChannel(taskName, channel string) bool {
e.mu.RLock()
defer e.mu.RUnlock()
-
+
if channels, exists := e.seenChannels[taskName]; exists {
return channels[channel]
}
@@ -581,7 +581,7 @@ func (e *PregelOptimizedEngine) getTriggersForNode(nodeName string) map[string]s
func (e *PregelOptimizedEngine) getCurrentNamespace() string {
e.mu.RLock()
defer e.mu.RUnlock()
-
+
// Simplified - check config for namespace
if e.Engine != nil && e.Engine.config != nil {
if ns, ok := e.Engine.config.Get("namespace"); ok {
@@ -598,10 +598,10 @@ func (e *PregelOptimizedEngine) getCurrentNamespace() string {
// which handles entry points, conditional edges, regular edges, and branches.
func (e *PregelOptimizedEngine) PrepareNextTasksOptimized(
ctx context.Context,
- registry interface{},
+ registry any,
visited map[string]bool,
trigger string,
- currentState interface{},
+ currentState any,
) ([]*Task, map[string]struct{}, error) {
if e.Engine == nil || e.Engine.graph == nil {
return nil, nil, fmt.Errorf("PrepareNextTasksOptimized: engine not initialized")
@@ -610,5 +610,5 @@ func (e *PregelOptimizedEngine) PrepareNextTasksOptimized(
if !ok {
return nil, nil, fmt.Errorf("PrepareNextTasksOptimized: invalid registry type %T", registry)
}
- return e.prepareNextTasks(reg, visited, trigger, currentState)
+ return e.prepareNextTasks(ctx, reg, visited, trigger, currentState)
}
diff --git a/internal/harness/graph/pregel/optimized_test.go b/internal/harness/graph/pregel/optimized_test.go
index 181abcfc9c..d04b3a78ce 100644
--- a/internal/harness/graph/pregel/optimized_test.go
+++ b/internal/harness/graph/pregel/optimized_test.go
@@ -11,31 +11,31 @@ import (
func TestPriorityTaskQueue(t *testing.T) {
pq := NewPriorityTaskQueue()
-
+
// Test push and pop
task1 := &Task{Name: "task1", Path: []string{"a"}}
task2 := &Task{Name: "task2", Path: []string{"b"}}
task3 := &Task{Name: "task3", Path: []string{"a", "b"}}
-
+
pq.Push(task1)
pq.Push(task2)
pq.Push(task3)
-
+
if pq.Len() != 3 {
t.Errorf("Expected 3 tasks, got %d", pq.Len())
}
-
+
// Test pop - should return shortest path first
popped := pq.Pop()
if popped == nil {
t.Fatal("Expected non-nil popped task")
}
-
+
// task1 has path ["a"] which is shorter than task3's ["a","b"]
if popped.Name != "task1" && popped.Name != "task2" {
t.Errorf("Expected task1 or task2, got %s", popped.Name)
}
-
+
// Check queue size
if pq.Len() != 2 {
t.Errorf("Expected 2 tasks remaining, got %d", pq.Len())
@@ -44,7 +44,7 @@ func TestPriorityTaskQueue(t *testing.T) {
func TestPriorityTaskQueueOrdering(t *testing.T) {
pq := NewPriorityTaskQueue()
-
+
// Add tasks with different path lengths
tasks := []*Task{
{Name: "deep1", Path: []string{"a", "b", "c"}},
@@ -52,11 +52,11 @@ func TestPriorityTaskQueueOrdering(t *testing.T) {
{Name: "deep2", Path: []string{"a", "b"}},
{Name: "shallow2", Path: []string{"b"}},
}
-
+
for _, task := range tasks {
pq.Push(task)
}
-
+
// Pop in priority order
// Shallow paths should come first
order := make([]string, 0, 4)
@@ -66,7 +66,7 @@ func TestPriorityTaskQueueOrdering(t *testing.T) {
order = append(order, task.Name)
}
}
-
+
// Verify shallow tasks come first
if order[0] != "shallow1" && order[0] != "shallow2" {
t.Errorf("Expected shallow task first, got %s", order[0])
@@ -75,10 +75,10 @@ func TestPriorityTaskQueueOrdering(t *testing.T) {
func TestTaskPriorityComparison(t *testing.T) {
tests := []struct {
- name string
- tp1 *TaskPriority
- tp2 *TaskPriority
- expected int
+ name string
+ tp1 *TaskPriority
+ tp2 *TaskPriority
+ expected int
}{
{
name: "different priorities",
@@ -99,7 +99,7 @@ func TestTaskPriorityComparison(t *testing.T) {
expected: -1, // t1 comes first alphabetically
},
}
-
+
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.tp1.Compare(tt.tp2)
@@ -114,25 +114,25 @@ func TestPregelOptimizedEngineCreation(t *testing.T) {
baseEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
optimized := NewPregelOptimizedEngine(baseEngine, nil)
-
+
if optimized == nil {
t.Fatal("Expected non-nil optimized engine")
}
-
+
if optimized.Engine != baseEngine {
t.Error("Expected base engine to match")
}
-
+
if !optimized.config.BumpStep {
t.Error("Expected bump_step to be enabled")
}
-
+
if !optimized.config.FinishNotification {
t.Error("Expected finish notification to be enabled")
}
-
+
if optimized.taskPriorityQueue == nil {
t.Error("Expected task queue to be initialized")
}
@@ -144,19 +144,19 @@ func TestFinishNotification(t *testing.T) {
// For now, just verify the structure
notification := &FinishNotification{
TaskName: "test_node",
- Output: map[string]interface{}{"result": "success"},
- Step: 1,
- Namespace: "test_namespace",
+ Output: map[string]any{"result": "success"},
+ Step: 1,
+ Namespace: "test_namespace",
}
-
+
if notification.TaskName != "test_node" {
t.Errorf("Expected task name 'test_node', got %s", notification.TaskName)
}
-
+
if notification.Step != 1 {
t.Errorf("Expected step 1, got %d", notification.Step)
}
-
+
if notification.Namespace != "test_namespace" {
t.Errorf("Expected namespace 'test_namespace', got %s", notification.Namespace)
}
@@ -167,23 +167,23 @@ func TestBumpStep(t *testing.T) {
baseEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
optimized := NewPregelOptimizedEngine(baseEngine, nil)
-
+
t.Run("bump step for dependent tasks", func(t *testing.T) {
ctx := context.Background()
-
+
// Simulate task completion
updatedChannels := map[string]struct{}{
"channel1": {},
"channel2": {},
}
-
+
err := optimized.BumpStep(ctx, "task1", 1, updatedChannels)
if err != nil {
t.Errorf("BumpStep failed: %v", err)
}
-
+
// Verify task is marked as finished
if !optimized.finishedTasks["task1"] {
t.Error("Expected task1 to be marked as finished")
@@ -193,7 +193,7 @@ func TestBumpStep(t *testing.T) {
func TestCompareTaskPriority(t *testing.T) {
optimized := NewPregelOptimizedEngine(&Engine{}, nil)
-
+
tests := []struct {
name string
t1 *Task
@@ -201,19 +201,19 @@ func TestCompareTaskPriority(t *testing.T) {
expected int
}{
{
- name: "different path lengths",
- t1: &Task{Name: "a", Path: []string{"a"}},
- t2: &Task{Name: "b", Path: []string{"a", "b"}},
+ name: "different path lengths",
+ t1: &Task{Name: "a", Path: []string{"a"}},
+ t2: &Task{Name: "b", Path: []string{"a", "b"}},
expected: -1, // Shorter path first
},
{
- name: "same path length, lexicographic",
- t1: &Task{Name: "a", Path: []string{"a"}},
- t2: &Task{Name: "b", Path: []string{"a"}},
+ name: "same path length, lexicographic",
+ t1: &Task{Name: "a", Path: []string{"a"}},
+ t2: &Task{Name: "b", Path: []string{"a"}},
expected: -1, // Alphabetical first
},
}
-
+
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := optimized.compareTaskPriority(tt.t1, tt.t2)
@@ -226,7 +226,7 @@ func TestCompareTaskPriority(t *testing.T) {
func TestIsNodeReady(t *testing.T) {
optimized := NewPregelOptimizedEngine(&Engine{}, nil)
-
+
t.Run("node with no dependencies", func(t *testing.T) {
// Nodes with no required channels are always ready
ready := optimized.isNodeReady("node1")
@@ -234,12 +234,12 @@ func TestIsNodeReady(t *testing.T) {
t.Error("Expected node to be ready with no dependencies")
}
})
-
+
t.Run("node with seen channels", func(t *testing.T) {
// Mark channels as ready
optimized.readyChannels["channel1"] = true
optimized.readyChannels["channel2"] = true
-
+
// This would need to be set up with proper dependencies
// For now, just test the mechanism
_ = optimized.isNodeReady("node1")
@@ -248,7 +248,7 @@ func TestIsNodeReady(t *testing.T) {
func TestGetDependencies(t *testing.T) {
optimized := NewPregelOptimizedEngine(&Engine{}, nil)
-
+
t.Run("get dependencies", func(t *testing.T) {
// This would require proper graph setup
// For now, test that the function exists
@@ -261,20 +261,20 @@ func TestGetDependencies(t *testing.T) {
func TestHasSeenChannel(t *testing.T) {
optimized := NewPregelOptimizedEngine(&Engine{}, nil)
-
+
t.Run("channel not seen", func(t *testing.T) {
seen := optimized.hasSeenChannel("task1", "channel1")
if seen {
t.Error("Expected channel to not be seen")
}
})
-
+
t.Run("channel seen", func(t *testing.T) {
// Initialize seen channels for task
optimized.seenChannels["task1"] = map[string]bool{
"channel1": true,
}
-
+
seen := optimized.hasSeenChannel("task1", "channel1")
if !seen {
t.Error("Expected channel to be seen")
@@ -284,7 +284,7 @@ func TestHasSeenChannel(t *testing.T) {
func TestGetTriggersForNode(t *testing.T) {
optimized := NewPregelOptimizedEngine(&Engine{}, nil)
-
+
t.Run("get triggers", func(t *testing.T) {
// This would require proper graph setup
// For now, test that the function exists
@@ -297,19 +297,19 @@ func TestGetTriggersForNode(t *testing.T) {
func TestNewTaskPriority(t *testing.T) {
tp := NewTaskPriority("test_task", []string{"a", "b"}, 1)
-
+
if tp == nil {
t.Fatal("Expected non-nil task priority")
}
-
+
if tp.Name != "test_task" {
t.Errorf("Expected name 'test_task', got %s", tp.Name)
}
-
+
if len(tp.Path) != 2 {
t.Errorf("Expected path length 2, got %d", len(tp.Path))
}
-
+
if tp.Priority != 1 {
t.Errorf("Expected priority 1, got %d", tp.Priority)
}
@@ -317,7 +317,7 @@ func TestNewTaskPriority(t *testing.T) {
func TestPriorityQueueHeap(t *testing.T) {
pq := NewPriorityTaskQueue()
-
+
// Test heap property maintenance
tasks := []*Task{
{Name: "z", Path: []string{"z"}},
@@ -325,12 +325,12 @@ func TestPriorityQueueHeap(t *testing.T) {
{Name: "a", Path: []string{"a"}},
{Name: "n", Path: []string{"n"}},
}
-
+
// Add in random order
for _, task := range tasks {
pq.Push(task)
}
-
+
// Verify heap property: each parent should have higher priority than children
// This is a simplified check - in practice we'd verify the full heap property
if pq.Len() != 4 {
@@ -342,21 +342,21 @@ func TestOptimizedApplyWrites(t *testing.T) {
baseEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
optimized := NewPregelOptimizedEngine(baseEngine, nil)
-
+
t.Run("apply writes with bump_step", func(t *testing.T) {
ctx := context.Background()
-
+
// Create a registry with a channel
registry := channels.NewRegistry()
ch := channels.NewAnyValue(nil)
registry.Register("key", ch)
-
+
results := []*TaskResult{
- {Name: "task1", Output: map[string]interface{}{"key": "value"}},
+ {Name: "task1", Output: map[string]any{"key": "value"}},
}
-
+
updatedChannels, err := optimized.OptimizedApplyWrites(
ctx,
registry,
@@ -364,11 +364,11 @@ func TestOptimizedApplyWrites(t *testing.T) {
1,
map[string]struct{}{"trigger": {}},
)
-
+
if err != nil {
t.Logf("OptimizedApplyWrites error: %v", err)
}
-
+
if updatedChannels == nil {
t.Error("Expected non-nil updated channels")
}
@@ -380,11 +380,11 @@ func TestGetCurrentNamespace(t *testing.T) {
config: types.NewRunnableConfig(),
}
baseEngine.config.Set("namespace", "test_ns")
-
+
optimized := NewPregelOptimizedEngine(baseEngine, nil)
-
+
ns := optimized.getCurrentNamespace()
-
+
if ns == "" {
t.Log("getCurrentNamespace returns empty (config may not have namespace)")
}
@@ -394,12 +394,12 @@ func TestPrepareNextTasksOptimized(t *testing.T) {
baseEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
optimized := NewPregelOptimizedEngine(baseEngine, nil)
-
+
t.Run("prepare next tasks with optimization", func(t *testing.T) {
ctx := context.Background()
-
+
tasks, triggers, err := optimized.PrepareNextTasksOptimized(
ctx,
nil, // registry
@@ -407,19 +407,19 @@ func TestPrepareNextTasksOptimized(t *testing.T) {
"",
nil, // current state
)
-
+
if err != nil {
t.Logf("PrepareNextTasksOptimized error: %v", err)
}
-
+
if tasks == nil {
tasks = []*Task{}
}
-
+
if triggers == nil {
triggers = map[string]struct{}{}
}
-
+
t.Logf("Prepared %d tasks with %d triggers", len(tasks), len(triggers))
})
}
diff --git a/internal/harness/graph/pregel/pregel_pressure_test.go b/internal/harness/graph/pregel/pregel_pressure_test.go
index 944a85fa0f..8ff7d08211 100644
--- a/internal/harness/graph/pregel/pregel_pressure_test.go
+++ b/internal/harness/graph/pregel/pregel_pressure_test.go
@@ -16,13 +16,13 @@ import (
)
// safeMap extracts a map from state, initializing if nil.
-func safeMap(state interface{}) map[string]interface{} {
+func safeMap(state any) map[string]any {
if state == nil {
- return map[string]interface{}{}
+ return map[string]any{}
}
- m, ok := state.(map[string]interface{})
+ m, ok := state.(map[string]any)
if !ok {
- return map[string]interface{}{}
+ return map[string]any{}
}
return m
}
@@ -33,20 +33,20 @@ func safeMap(state interface{}) map[string]interface{} {
func newLoopGraph(t *testing.T, maxIter int) *graph.StateGraph {
t.Helper()
- sg := graph.NewStateGraph(map[string]interface{}{
+ sg := graph.NewStateGraph(map[string]any{
"counter": 0,
"value": "",
})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("entry", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("entry", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["counter"] = 0
m["value"] = "start"
return m, nil
})
- sg.AddNode("loop", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("loop", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -57,7 +57,7 @@ func newLoopGraph(t *testing.T, maxIter int) *graph.StateGraph {
if n, ok := sg.GetNode("loop"); ok {
n.Triggers = []string{"counter", "value"}
}
- sg.AddNode("done", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("done", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["value"] = "done"
return m, nil
@@ -66,7 +66,7 @@ func newLoopGraph(t *testing.T, maxIter int) *graph.StateGraph {
sg.AddEdge(constants.Start, "entry")
sg.AddEdge("entry", "loop")
sg.AddConditionalEdges("loop",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
if c >= maxIter {
@@ -83,7 +83,7 @@ func newLoopGraph(t *testing.T, maxIter int) *graph.StateGraph {
func TestEngine_Loop10Iterations(t *testing.T) {
sg := newLoopGraph(t, 10)
engine := NewEngine(sg, WithRecursionLimit(50))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -91,7 +91,7 @@ func TestEngine_Loop10Iterations(t *testing.T) {
t.Skip("result nil (channel timing)")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["value"].(string)
if v != "done" {
t.Errorf("expected done, got %s", v)
@@ -106,7 +106,7 @@ func TestEngine_Loop10Iterations(t *testing.T) {
func TestEngine_Loop100Iterations(t *testing.T) {
sg := newLoopGraph(t, 100)
engine := NewEngine(sg, WithRecursionLimit(200))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -118,12 +118,12 @@ func TestEngine_Loop100Iterations(t *testing.T) {
func newChainGraph(t *testing.T, n int) *graph.StateGraph {
t.Helper()
- sg := graph.NewStateGraph(map[string]interface{}{"idx": 0})
+ sg := graph.NewStateGraph(map[string]any{"idx": 0})
sg.AddChannel("idx", channels.NewLastValue(0))
for i := 0; i < n; i++ {
name := fmt.Sprintf("n%d", i)
j := i
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["idx"] = j + 1
return m, nil
@@ -140,7 +140,7 @@ func newChainGraph(t *testing.T, n int) *graph.StateGraph {
func TestEngine_Chain50Nodes(t *testing.T) {
sg := newChainGraph(t, 50)
engine := NewEngine(sg, WithRecursionLimit(100))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -148,7 +148,7 @@ func TestEngine_Chain50Nodes(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
idx, _ := m["idx"].(int)
if idx != 50 {
t.Errorf("expected idx=50, got %d", idx)
@@ -160,28 +160,28 @@ func TestEngine_Chain50Nodes(t *testing.T) {
// ============================================================
func TestEngine_FanOut10_FanInDAG(t *testing.T) {
- sg := graph.NewStateGraph(map[string]interface{}{"count": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"count": 0, "value": ""})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("split", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 0}, nil
+ sg.AddNode("split", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 0}, nil
})
triggerChannels := []string{"count"}
for i := 0; i < 10; i++ {
name := fmt.Sprintf("work%d", i)
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 1}, nil
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 1}, nil
})
if n, ok := sg.GetNode(name); ok {
n.Triggers = triggerChannels
}
}
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"value": "joined"}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"value": "joined"}, nil
})
if n, ok := sg.GetNode("join"); ok {
n.Triggers = []string{"count", "value"}
@@ -194,7 +194,7 @@ func TestEngine_FanOut10_FanInDAG(t *testing.T) {
sg.AddEdge("join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(30))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -202,7 +202,7 @@ func TestEngine_FanOut10_FanInDAG(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["value"].(string)
if v != "joined" {
t.Errorf("expected joined, got %s", m)
@@ -219,9 +219,9 @@ func TestEngine_FanOut10_FanInDAG(t *testing.T) {
func TestEngine_Concurrent50SameGraph(t *testing.T) {
// Create the graph once, then a new Engine per goroutine (Engine is not designed for concurrent RunSync).
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("a", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("a", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["val"] = "ok"
return m, nil
@@ -236,7 +236,7 @@ func TestEngine_Concurrent50SameGraph(t *testing.T) {
go func(id int) {
defer wg.Done()
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
errs <- fmt.Errorf("goroutine %d: %w", id, err)
}
@@ -260,9 +260,9 @@ func TestEngine_MultiTenant50Engines(t *testing.T) {
wg.Add(1)
go func(id int) {
defer wg.Done()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("worker", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("worker", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["val"] = fmt.Sprintf("worker_%d", id)
return m, nil
@@ -270,7 +270,7 @@ func TestEngine_MultiTenant50Engines(t *testing.T) {
sg.AddEdge(constants.Start, "worker")
sg.AddEdge("worker", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
errs <- fmt.Errorf("engine %d: %w", id, err)
}
@@ -288,19 +288,19 @@ func TestEngine_MultiTenant50Engines(t *testing.T) {
// ============================================================
func TestEngine_BinaryOperatorAggregate(t *testing.T) {
- sg := graph.NewStateGraph(map[string]interface{}{"total": 0})
+ sg := graph.NewStateGraph(map[string]any{"total": 0})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("total", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("total", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
- sg.AddNode("add5", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"total": 5}, nil
+ sg.AddNode("add5", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"total": 5}, nil
})
- sg.AddNode("add10", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"total": 10}, nil
+ sg.AddNode("add10", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"total": 10}, nil
})
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
if n, ok := sg.GetNode("join"); ok {
n.Triggers = []string{"total"}
@@ -312,7 +312,7 @@ func TestEngine_BinaryOperatorAggregate(t *testing.T) {
sg.AddEdge("join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -320,7 +320,7 @@ func TestEngine_BinaryOperatorAggregate(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
total, _ := m["total"].(int)
if total != 15 {
t.Errorf("expected total=15, got %d", total)
@@ -332,11 +332,11 @@ func TestEngine_BinaryOperatorAggregate(t *testing.T) {
// ============================================================
func TestEngine_TimeoutCancel(t *testing.T) {
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("slow", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("slow", func(ctx context.Context, state any) (any, error) {
time.Sleep(5 * time.Second)
- return map[string]interface{}{"val": "done"}, nil
+ return map[string]any{"val": "done"}, nil
})
sg.AddEdge(constants.Start, "slow")
sg.AddEdge("slow", constants.End)
@@ -345,7 +345,7 @@ func TestEngine_TimeoutCancel(t *testing.T) {
defer cancel()
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(ctx, map[string]interface{}{})
+ _, err := engine.RunSync(ctx, map[string]any{})
if err == nil {
t.Fatal("expected timeout error, got nil")
}
@@ -359,7 +359,7 @@ func TestEngine_TimeoutCancel(t *testing.T) {
func TestEngine_RecursionLimitExceeded(t *testing.T) {
sg := newLoopGraph(t, 50)
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err == nil {
t.Fatal("expected recursion limit error, got nil")
}
@@ -376,13 +376,13 @@ func TestEngine_RecursionLimitExceeded(t *testing.T) {
func TestEngine_NodePanicRecovery(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("normal", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "ok"}, nil
+ sg.AddNode("normal", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "ok"}, nil
})
- sg.AddNode("panicker", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("panicker", func(ctx context.Context, state any) (any, error) {
panic("simulated panic in node")
})
sg.AddEdge(constants.Start, "normal")
@@ -390,7 +390,7 @@ func TestEngine_NodePanicRecovery(t *testing.T) {
sg.AddEdge("panicker", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err == nil {
t.Fatal("expected panic error, got nil")
}
@@ -403,17 +403,17 @@ func TestEngine_NodePanicRecovery(t *testing.T) {
func TestEngine_NodeErrorPropagation(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("good", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "good"}, nil
+ sg.AddNode("good", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "good"}, nil
})
- sg.AddNode("failing", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("failing", func(ctx context.Context, state any) (any, error) {
return nil, fmt.Errorf("node failure")
})
- sg.AddNode("never_reached", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "should_not_happen"}, nil
+ sg.AddNode("never_reached", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "should_not_happen"}, nil
})
sg.AddEdge(constants.Start, "good")
sg.AddEdge("good", "failing")
@@ -421,7 +421,7 @@ func TestEngine_NodeErrorPropagation(t *testing.T) {
sg.AddEdge("never_reached", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err == nil {
t.Fatal("expected error from failing node, got nil")
}
@@ -434,27 +434,27 @@ func TestEngine_NodeErrorPropagation(t *testing.T) {
func TestEngine_PartialNodeFailureInFanOut(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"count": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"count": 0, "value": ""})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("split", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 0}, nil
+ sg.AddNode("split", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 0}, nil
})
for i := 0; i < 5; i++ {
name := fmt.Sprintf("good%d", i)
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 1}, nil
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 1}, nil
})
}
- sg.AddNode("bad", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("bad", func(ctx context.Context, state any) (any, error) {
return nil, fmt.Errorf("intentional task failure")
})
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"value": "joined"}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"value": "joined"}, nil
})
if n, ok := sg.GetNode("join"); ok {
n.Triggers = []string{"count", "value"}
@@ -475,7 +475,7 @@ func TestEngine_PartialNodeFailureInFanOut(t *testing.T) {
sg.AddEdge("join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(30))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
// Error behavior depends on how the engine handles partial failure.
// The key thing is that the engine should not hang or crash.
if err != nil {
@@ -493,20 +493,20 @@ func TestEngine_PartialNodeFailureInFanOut(t *testing.T) {
func TestEngine_ContextCancellationMidExecution(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("slow_start", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("slow_start", func(ctx context.Context, state any) (any, error) {
// Start work then check context
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(50 * time.Millisecond):
}
- return map[string]interface{}{"val": "slow_done"}, nil
+ return map[string]any{"val": "slow_done"}, nil
})
- sg.AddNode("never_run", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "should_not_reach"}, nil
+ sg.AddNode("never_run", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "should_not_reach"}, nil
})
sg.AddEdge(constants.Start, "slow_start")
sg.AddEdge("slow_start", "never_run")
@@ -516,7 +516,7 @@ func TestEngine_ContextCancellationMidExecution(t *testing.T) {
defer cancel()
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(ctx, map[string]interface{}{})
+ _, err := engine.RunSync(ctx, map[string]any{})
if err == nil {
t.Log("engine completed before cancellation (timing-dependent)")
} else {
@@ -534,7 +534,7 @@ func TestEngine_ContextCancellationMidExecution(t *testing.T) {
func TestEngine_MixedBSPAndDAG(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0, "merged": ""})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0, "merged": ""})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("merged", channels.NewLastValue(""))
@@ -542,12 +542,12 @@ func TestEngine_MixedBSPAndDAG(t *testing.T) {
// Uses Pregel mode (default AnyPredecessor). The DAG fan-in (fork_a→dag_join,
// fork_b→dag_join) works in Pregel mode because both forks run in the same
// superstep and the last one alphabetically triggers dag_join.
- sg.AddNode("entry", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("entry", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["counter"] = 0
return m, nil
})
- sg.AddNode("loop_body", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("loop_body", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -556,23 +556,23 @@ func TestEngine_MixedBSPAndDAG(t *testing.T) {
if n, ok := sg.GetNode("loop_body"); ok {
n.Triggers = []string{"counter"}
}
- sg.AddNode("exit_loop", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("exit_loop", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
- sg.AddNode("fork_a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("fork_a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
- sg.AddNode("fork_b", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("fork_b", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
- sg.AddNode("dag_join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"merged": "all_done"}, nil
+ sg.AddNode("dag_join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"merged": "all_done"}, nil
})
sg.AddEdge(constants.Start, "entry")
sg.AddEdge("entry", "loop_body")
sg.AddConditionalEdges("loop_body",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
if c >= 3 {
@@ -589,7 +589,7 @@ func TestEngine_MixedBSPAndDAG(t *testing.T) {
sg.AddEdge("dag_join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(20))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -597,7 +597,7 @@ func TestEngine_MixedBSPAndDAG(t *testing.T) {
t.Skip("result nil (channel timing)")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["merged"].(string)
if v != "all_done" {
t.Errorf("expected merged=all_done, got %v", m)
@@ -615,30 +615,30 @@ func TestEngine_MixedBSPAndDAG(t *testing.T) {
func TestEngine_ConditionalEdgesWithDAG(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"route": "", "result": ""})
+ sg := graph.NewStateGraph(map[string]any{"route": "", "result": ""})
sg.AddChannel("route", channels.NewLastValue(""))
sg.AddChannel("result", channels.NewLastValue(""))
- sg.AddNode("router", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"route": "alpha"}, nil
+ sg.AddNode("router", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"route": "alpha"}, nil
})
- sg.AddNode("alpha", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"result": "alpha_done"}, nil
+ sg.AddNode("alpha", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"result": "alpha_done"}, nil
})
- sg.AddNode("beta", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"result": "beta_done"}, nil
+ sg.AddNode("beta", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"result": "beta_done"}, nil
})
- sg.AddNode("merge", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"result": "merged"}, nil
+ sg.AddNode("merge", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"result": "merged"}, nil
})
- sg.AddNode("final", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("final", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
// Edges
sg.AddEdge(constants.Start, "router")
sg.AddConditionalEdges("router",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
return m["route"], nil
},
@@ -650,7 +650,7 @@ func TestEngine_ConditionalEdgesWithDAG(t *testing.T) {
sg.AddEdge("final", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -658,7 +658,7 @@ func TestEngine_ConditionalEdgesWithDAG(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
r, _ := m["result"].(string)
if r != "merged" {
t.Errorf("expected merged result, got %v", m)
@@ -673,24 +673,24 @@ func TestEngine_ConditionalEdgesWithDAG(t *testing.T) {
func TestEngine_LargeFanIn100(t *testing.T) {
t.Parallel()
const n = 100
- sg := graph.NewStateGraph(map[string]interface{}{"count": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"count": 0, "value": ""})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("count", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("split", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 0}, nil
+ sg.AddNode("split", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 0}, nil
})
for i := 0; i < n; i++ {
name := fmt.Sprintf("w%d", i)
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"count": 1}, nil
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"count": 1}, nil
})
}
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"value": "joined"}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"value": "joined"}, nil
})
if node, ok := sg.GetNode("join"); ok {
node.Triggers = []string{"count", "value"}
@@ -703,7 +703,7 @@ func TestEngine_LargeFanIn100(t *testing.T) {
sg.AddEdge("join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(n+10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -711,7 +711,7 @@ func TestEngine_LargeFanIn100(t *testing.T) {
t.Skip("result nil (channel timing)")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
c, _ := m["count"].(int)
if c != n {
t.Errorf("expected count=%d, got %d", n, c)
@@ -729,24 +729,24 @@ func TestEngine_LargeFanIn100(t *testing.T) {
func TestEngine_LargeFanOut100(t *testing.T) {
t.Parallel()
const n = 100
- sg := graph.NewStateGraph(map[string]interface{}{"aggregated": 0, "done": ""})
+ sg := graph.NewStateGraph(map[string]any{"aggregated": 0, "done": ""})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("aggregated", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("aggregated", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
sg.AddChannel("done", channels.NewLastValue(""))
- sg.AddNode("source", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"aggregated": 0}, nil
+ sg.AddNode("source", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"aggregated": 0}, nil
})
for i := 0; i < n; i++ {
name := fmt.Sprintf("leaf%d", i)
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"aggregated": 1}, nil
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"aggregated": 1}, nil
})
}
- sg.AddNode("collector", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"done": "collected"}, nil
+ sg.AddNode("collector", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"done": "collected"}, nil
})
if node, ok := sg.GetNode("collector"); ok {
node.Triggers = []string{"aggregated", "done"}
@@ -759,7 +759,7 @@ func TestEngine_LargeFanOut100(t *testing.T) {
sg.AddEdge("collector", constants.End)
engine := NewEngine(sg, WithRecursionLimit(n+10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -767,7 +767,7 @@ func TestEngine_LargeFanOut100(t *testing.T) {
t.Skip("result nil (channel timing)")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
c, _ := m["aggregated"].(int)
if c != n {
t.Errorf("expected aggregated=%d, got %d", n, c)
@@ -781,22 +781,22 @@ func TestEngine_LargeFanOut100(t *testing.T) {
func TestEngine_InterruptAndLoop(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0, "value": ""})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("entry", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("entry", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["counter"] = 0
m["value"] = "start"
return m, nil
})
- sg.AddNode("checkpoint", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("checkpoint", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
// Halt on counter == 2 to test interrupt
if c == 2 {
- return nil, &errors.GraphInterrupt{Interrupts: []interface{}{"stopped at checkpoint node"}}
+ return nil, &errors.GraphInterrupt{Interrupts: []any{"stopped at checkpoint node"}}
}
m["counter"] = c
m["value"] = fmt.Sprintf("check_%d", c)
@@ -805,14 +805,14 @@ func TestEngine_InterruptAndLoop(t *testing.T) {
if n, ok := sg.GetNode("checkpoint"); ok {
n.Triggers = []string{"counter", "value"}
}
- sg.AddNode("increment", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("increment", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
m["value"] = fmt.Sprintf("inc_%d", c+1)
return m, nil
})
- sg.AddNode("done", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("done", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["value"] = "done"
return m, nil
@@ -822,7 +822,7 @@ func TestEngine_InterruptAndLoop(t *testing.T) {
sg.AddEdge("entry", "increment")
sg.AddEdge("increment", "checkpoint")
sg.AddConditionalEdges("checkpoint",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
// If interrupted, return "done" (shouldn't reach here)
return "done", nil
},
@@ -834,7 +834,7 @@ func TestEngine_InterruptAndLoop(t *testing.T) {
engine := NewEngine(sg, WithInterrupts("checkpoint"), WithRecursionLimit(20))
// First run: should stop at checkpoint
- result1, err1 := engine.RunSync(context.Background(), map[string]interface{}{})
+ result1, err1 := engine.RunSync(context.Background(), map[string]any{})
if err1 != nil {
// GraphInterrupt is expected — that means the engine correctly interrupted
t.Logf("first run interrupted as expected: %v", err1)
@@ -849,16 +849,16 @@ func TestEngine_InterruptAndLoop(t *testing.T) {
func TestEngine_EmptyNodeExecution(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("start", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "initial"}, nil
+ sg.AddNode("start", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "initial"}, nil
})
- sg.AddNode("empty", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("empty", func(ctx context.Context, state any) (any, error) {
return nil, nil // engine must handle nil output gracefully
})
- sg.AddNode("end", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("end", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["val"] = "final"
return m, nil
@@ -869,7 +869,7 @@ func TestEngine_EmptyNodeExecution(t *testing.T) {
sg.AddEdge("end", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -877,7 +877,7 @@ func TestEngine_EmptyNodeExecution(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["val"].(string)
if v != "final" {
t.Errorf("expected final, got %v", m)
@@ -891,7 +891,7 @@ func TestEngine_EmptyNodeExecution(t *testing.T) {
func TestEngine_NodeReuseConcurrentRun(t *testing.T) {
t.Parallel()
// Build a reusable node function
- nodeFunc := func(ctx context.Context, state interface{}) (interface{}, error) {
+ nodeFunc := func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["val"] = "ok"
return m, nil
@@ -905,14 +905,14 @@ func TestEngine_NodeReuseConcurrentRun(t *testing.T) {
wg.Add(1)
go func(id int) {
defer wg.Done()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
sg.AddNode("worker", nodeFunc)
sg.AddEdge(constants.Start, "worker")
sg.AddEdge("worker", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{"val": "start"})
+ _, err := engine.RunSync(context.Background(), map[string]any{"val": "start"})
if err != nil {
errs <- fmt.Errorf("engine %d: %w", id, err)
}
@@ -952,10 +952,10 @@ func TestEngine_DurabilityModes(t *testing.T) {
mode := mode // capture
t.Run(string(mode), func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "done"}, nil
+ sg.AddNode("a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "done"}, nil
})
sg.AddEdge(constants.Start, "a")
sg.AddEdge("a", constants.End)
@@ -963,12 +963,12 @@ func TestEngine_DurabilityModes(t *testing.T) {
cfg := types.NewRunnableConfig()
cfg.Durability = mode
engine := NewEngine(sg, WithRecursionLimit(5), WithConfig(cfg))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("mode=%s failed: %v", mode, err)
}
if result != nil {
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["val"].(string)
t.Logf("mode=%s: val=%s", mode, v)
}
@@ -985,21 +985,21 @@ func TestEngine_ChannelWriteConflict(t *testing.T) {
t.Run("last_value_conflict_errors", func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "from_a"}, nil
+ sg.AddNode("a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "from_a"}, nil
})
- sg.AddNode("b", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "from_b"}, nil
+ sg.AddNode("b", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "from_b"}, nil
})
sg.AddEdge(constants.Start, "a")
sg.AddEdge(constants.Start, "b")
sg.AddEdge("a", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
// Start→a and Start→b execute in consecutive steps (Pregel mode follows
// lastCompletedNode), so no conflict. When they happen in the same step,
// LastValue rejects the second write.
@@ -1012,23 +1012,23 @@ func TestEngine_ChannelWriteConflict(t *testing.T) {
t.Run("binop_multiple_writes_merged", func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"sum": 0})
+ sg := graph.NewStateGraph(map[string]any{"sum": 0})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("sum", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("sum", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
- sg.AddNode("split", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"sum": 0}, nil
+ sg.AddNode("split", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"sum": 0}, nil
})
for i := 0; i < 5; i++ {
name := fmt.Sprintf("w%d", i)
- sg.AddNode(name, func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"sum": 1}, nil
+ sg.AddNode(name, func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"sum": 1}, nil
})
}
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
if n, ok := sg.GetNode("join"); ok {
n.Triggers = []string{"sum"}
@@ -1041,7 +1041,7 @@ func TestEngine_ChannelWriteConflict(t *testing.T) {
sg.AddEdge("join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(20))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1049,7 +1049,7 @@ func TestEngine_ChannelWriteConflict(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
sum, _ := m["sum"].(int)
if sum != 5 {
t.Errorf("expected sum=5 from 5×1 writes, got %d", sum)
@@ -1072,24 +1072,24 @@ func TestEngine_StateConcurrentHighPressure(t *testing.T) {
wg.Add(1)
go func(id int) {
defer wg.Done()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0, "path": ""})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0, "path": ""})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("path", channels.NewLastValue(""))
- sg.AddNode("a", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("a", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
m["counter"] = 1
m["path"] = "a"
return m, nil
})
- sg.AddNode("b", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("b", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
m["path"] = "b"
return m, nil
})
- sg.AddNode("c", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("c", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -1102,7 +1102,7 @@ func TestEngine_StateConcurrentHighPressure(t *testing.T) {
sg.AddEdge("c", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
errCh <- fmt.Errorf("engine %d: %w", id, err)
}
@@ -1130,10 +1130,10 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
t.Run("condition_unstable_hits_limit", func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0})
sg.AddChannel("counter", channels.NewLastValue(0))
- sg.AddNode("inc", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("inc", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -1144,14 +1144,14 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
}
sg.AddEdge(constants.Start, "inc")
sg.AddConditionalEdges("inc",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
return "inc", nil // always loops
},
map[string]string{"inc": "inc"},
)
engine := NewEngine(sg, WithRecursionLimit(5))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err == nil {
t.Skip("engine completed without limit enforcement (timing)")
} else {
@@ -1161,10 +1161,10 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
t.Run("condition_stable_terminates_normally", func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0})
sg.AddChannel("counter", channels.NewLastValue(0))
- sg.AddNode("inc", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("inc", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -1173,12 +1173,12 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
if n, ok := sg.GetNode("inc"); ok {
n.Triggers = []string{"counter"}
}
- sg.AddNode("done", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("done", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
sg.AddEdge(constants.Start, "inc")
sg.AddConditionalEdges("inc",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
if c >= 3 {
@@ -1191,7 +1191,7 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
sg.AddEdge("done", constants.End)
engine := NewEngine(sg, WithRecursionLimit(20))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("stable loop should terminate: %v", err)
}
@@ -1199,7 +1199,7 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
c, _ := m["counter"].(int)
if c != 3 {
t.Errorf("expected counter=3 after stable loop, got %d", c)
@@ -1214,24 +1214,24 @@ func TestEngine_MaxIterationsVsConditionStable(t *testing.T) {
func TestEngine_ChannelTypeCombinations(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": "", "total": 0})
+ sg := graph.NewStateGraph(map[string]any{"val": "", "total": 0})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddChannel("total", channels.NewBinaryOperatorAggregate(0, func(a, b interface{}) interface{} {
+ sg.AddChannel("total", channels.NewBinaryOperatorAggregate(0, func(a, b any) any {
return a.(int) + b.(int)
}))
- sg.AddNode("init", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "init", "total": 0}, nil
+ sg.AddNode("init", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "init", "total": 0}, nil
})
- sg.AddNode("writer", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "written", "total": 1}, nil
+ sg.AddNode("writer", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "written", "total": 1}, nil
})
- sg.AddNode("adder", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"total": 2}, nil
+ sg.AddNode("adder", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"total": 2}, nil
})
- sg.AddNode("collect", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("collect", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
// collect reads from both channels — this works in DAG mode after all predecessors
if n, ok := sg.GetNode("collect"); ok {
@@ -1245,7 +1245,7 @@ func TestEngine_ChannelTypeCombinations(t *testing.T) {
sg.AddEdge("collect", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1253,7 +1253,7 @@ func TestEngine_ChannelTypeCombinations(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
// LastValue: "written" (last write wins)
val, _ := m["val"].(string)
if val != "written" {
@@ -1273,11 +1273,11 @@ func TestEngine_ChannelTypeCombinations(t *testing.T) {
func TestEngine_DynamicConditionalRouting(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0, "history": ""})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0, "history": ""})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("history", channels.NewLastValue(""))
- sg.AddNode("router", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("router", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -1288,19 +1288,19 @@ func TestEngine_DynamicConditionalRouting(t *testing.T) {
if n, ok := sg.GetNode("router"); ok {
n.Triggers = []string{"counter"}
}
- sg.AddNode("left", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("left", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
h, _ := m["history"].(string)
m["history"] = h + "_left"
return m, nil
})
- sg.AddNode("right", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("right", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
h, _ := m["history"].(string)
m["history"] = h + "_right"
return m, nil
})
- sg.AddNode("final", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("final", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
h, _ := m["history"].(string)
m["history"] = h + "_end"
@@ -1310,7 +1310,7 @@ func TestEngine_DynamicConditionalRouting(t *testing.T) {
sg.AddEdge(constants.Start, "router")
// Dynamic edge: routing decision changes based on counter value at each step
sg.AddConditionalEdges("router",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
if c >= 5 {
@@ -1328,7 +1328,7 @@ func TestEngine_DynamicConditionalRouting(t *testing.T) {
sg.AddEdge("final", constants.End)
engine := NewEngine(sg, WithRecursionLimit(15))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1336,7 +1336,7 @@ func TestEngine_DynamicConditionalRouting(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
c, _ := m["counter"].(int)
hist, _ := m["history"].(string)
if c < 1 {
@@ -1354,10 +1354,10 @@ func TestEngine_CheckpointWithBSPLoop(t *testing.T) {
cp := checkpoint.NewMemorySaver()
sg := newLoopGraph(t, 5)
cfg := types.NewRunnableConfig()
- cfg.Configurable = map[string]interface{}{constants.ConfigKeyThreadID: "test-cp-bsp"}
+ cfg.Configurable = map[string]any{constants.ConfigKeyThreadID: "test-cp-bsp"}
engine := NewEngine(sg, WithRecursionLimit(20), WithCheckpointer(cp), WithConfig(cfg))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1366,7 +1366,7 @@ func TestEngine_CheckpointWithBSPLoop(t *testing.T) {
return
}
ctx := context.Background()
- checkpoints, err := cp.List(ctx, map[string]interface{}{
+ checkpoints, err := cp.List(ctx, map[string]any{
constants.ConfigKeyThreadID: "test-cp-bsp",
}, 100)
if err != nil {
@@ -1377,7 +1377,7 @@ func TestEngine_CheckpointWithBSPLoop(t *testing.T) {
} else {
t.Logf("checkpoints saved: %d entries for %d-step loop", len(checkpoints), 5)
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["value"].(string)
if v != "done" {
t.Errorf("expected done, got %s", v)
@@ -1390,22 +1390,22 @@ func TestEngine_CheckpointWithBSPLoop(t *testing.T) {
func TestEngine_DuplicateNodeID(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
// Add a node
- sg.AddNode("dup", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "first"}, nil
+ sg.AddNode("dup", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "first"}, nil
})
// Overwrite with same name (graph.AddNode overwrites silently)
- sg.AddNode("dup", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "second"}, nil
+ sg.AddNode("dup", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "second"}, nil
})
sg.AddEdge(constants.Start, "dup")
sg.AddEdge("dup", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1413,7 +1413,7 @@ func TestEngine_DuplicateNodeID(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["val"].(string)
// The second AddNode overwrites the first, so val should be "second"
if v != "second" {
@@ -1431,22 +1431,22 @@ func TestEngine_ExtremeConfigValues(t *testing.T) {
t.Run("recursion_limit_zero", func(t *testing.T) {
// With recursion limit = 0, the engine should error immediately on loop
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "x"}, nil
+ sg.AddNode("a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "x"}, nil
})
// Create a self-loop via conditional edge
sg.AddEdge(constants.Start, "a")
sg.AddConditionalEdges("a",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
return "a", nil
},
map[string]string{"a": "a"},
)
engine := NewEngine(sg, WithRecursionLimit(0))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ _, err := engine.RunSync(context.Background(), map[string]any{})
if err == nil {
t.Skip("engine didn't enforce recursion limit 0 (allowed step 0)")
} else {
@@ -1457,7 +1457,7 @@ func TestEngine_ExtremeConfigValues(t *testing.T) {
t.Run("recursion_limit_one", func(t *testing.T) {
sg := newSimpleGraph(t)
engine := NewEngine(sg, WithRecursionLimit(1))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{"value": "x"})
+ _, err := engine.RunSync(context.Background(), map[string]any{"value": "x"})
// With limit=1 and 2 nodes (entry + node_a), may or may not complete
t.Logf("recursion limit 1 result: %v", err)
})
@@ -1465,7 +1465,7 @@ func TestEngine_ExtremeConfigValues(t *testing.T) {
t.Run("max_concurrency_zero", func(t *testing.T) {
sg := newSimpleGraph(t)
engine := NewEngine(sg, WithRecursionLimit(10), WithMaxConcurrency(0))
- _, err := engine.RunSync(context.Background(), map[string]interface{}{"value": "x"})
+ _, err := engine.RunSync(context.Background(), map[string]any{"value": "x"})
if err != nil {
t.Fatalf("max concurrency 0 should use default: %v", err)
}
@@ -1479,18 +1479,18 @@ func TestEngine_ExtremeConfigValues(t *testing.T) {
func TestEngine_MultipleEntryPoints(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val_a": "", "val_b": ""})
+ sg := graph.NewStateGraph(map[string]any{"val_a": "", "val_b": ""})
sg.AddChannel("val_a", channels.NewLastValue(""))
sg.AddChannel("val_b", channels.NewLastValue(""))
- sg.AddNode("entry_a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val_a": "from_a"}, nil
+ sg.AddNode("entry_a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val_a": "from_a"}, nil
})
- sg.AddNode("entry_b", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val_b": "from_b"}, nil
+ sg.AddNode("entry_b", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val_b": "from_b"}, nil
})
- sg.AddNode("join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val_a": "joined"}, nil
+ sg.AddNode("join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val_a": "joined"}, nil
})
// Multiple start nodes — both entry_a and entry_b run concurrently
@@ -1500,7 +1500,7 @@ func TestEngine_MultipleEntryPoints(t *testing.T) {
sg.AddEdge("entry_b", constants.End)
engine := NewEngine(sg, WithRecursionLimit(10))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1508,7 +1508,7 @@ func TestEngine_MultipleEntryPoints(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
// Both entry nodes should have executed
t.Logf("multi-entry result: %v", m)
}
@@ -1519,14 +1519,14 @@ func TestEngine_MultipleEntryPoints(t *testing.T) {
func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"counter": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"counter": 0, "value": ""})
sg.AddChannel("counter", channels.NewLastValue(0))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("start", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"counter": 0, "value": "start"}, nil
+ sg.AddNode("start", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"counter": 0, "value": "start"}, nil
})
- sg.AddNode("router", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("router", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
m["counter"] = c + 1
@@ -1536,8 +1536,8 @@ func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
if n, ok := sg.GetNode("router"); ok {
n.Triggers = []string{"counter"}
}
- sg.AddNode("done", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"value": "done"}, nil
+ sg.AddNode("done", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"value": "done"}, nil
})
sg.AddEdge(constants.Start, "start")
@@ -1545,7 +1545,7 @@ func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
// router has both a regular edge (to done) and a conditional edge (to itself for loop)
sg.AddEdge("router", "done")
sg.AddConditionalEdges("router",
- func(ctx context.Context, state interface{}) (interface{}, error) {
+ func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
c, _ := m["counter"].(int)
if c < 3 {
@@ -1558,7 +1558,7 @@ func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
sg.AddEdge("done", constants.End)
engine := NewEngine(sg, WithRecursionLimit(20))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1566,7 +1566,7 @@ func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
t.Logf("node with both edges: %v", m)
}
@@ -1576,15 +1576,15 @@ func TestEngine_NodeWithBothEdgeAndConditionalEdge(t *testing.T) {
func TestEngine_NodeTimeout(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("quick", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "quick"}, nil
+ sg.AddNode("quick", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "quick"}, nil
})
- sg.AddNode("slow", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("slow", func(ctx context.Context, state any) (any, error) {
time.Sleep(200 * time.Millisecond)
- return map[string]interface{}{"val": "slow_done"}, nil
+ return map[string]any{"val": "slow_done"}, nil
})
sg.AddEdge(constants.Start, "quick")
sg.AddEdge("quick", "slow")
@@ -1595,7 +1595,7 @@ func TestEngine_NodeTimeout(t *testing.T) {
defer cancel()
engine := NewEngine(sg, WithRecursionLimit(10))
- _, err := engine.RunSync(ctx, map[string]interface{}{})
+ _, err := engine.RunSync(ctx, map[string]any{})
if err != nil {
t.Logf("node timeout correctly triggered: %v", err)
} else {
@@ -1609,45 +1609,45 @@ func TestEngine_NodeTimeout(t *testing.T) {
func TestEngine_MultipleFanInNodes(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"a": 0, "b": 0, "result": ""})
+ sg := graph.NewStateGraph(map[string]any{"a": 0, "b": 0, "result": ""})
sg.NodeTriggerMode = types.NodeTriggerAllPredecessor
- sg.AddChannel("a", channels.NewBinaryOperatorAggregate(0, func(x, y interface{}) interface{} {
+ sg.AddChannel("a", channels.NewBinaryOperatorAggregate(0, func(x, y any) any {
return x.(int) + y.(int)
}))
- sg.AddChannel("b", channels.NewBinaryOperatorAggregate(0, func(x, y interface{}) interface{} {
+ sg.AddChannel("b", channels.NewBinaryOperatorAggregate(0, func(x, y any) any {
return x.(int) + y.(int)
}))
sg.AddChannel("result", channels.NewLastValue(""))
- sg.AddNode("split", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"a": 0, "b": 0}, nil
+ sg.AddNode("split", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"a": 0, "b": 0}, nil
})
- sg.AddNode("x1", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"a": 1}, nil
+ sg.AddNode("x1", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"a": 1}, nil
})
- sg.AddNode("x2", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"a": 2}, nil
+ sg.AddNode("x2", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"a": 2}, nil
})
- sg.AddNode("y1", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"b": 10}, nil
+ sg.AddNode("y1", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"b": 10}, nil
})
- sg.AddNode("y2", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"b": 20}, nil
+ sg.AddNode("y2", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"b": 20}, nil
})
- sg.AddNode("join_a", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("join_a", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
if n, ok := sg.GetNode("join_a"); ok {
n.Triggers = []string{"a"}
}
- sg.AddNode("join_b", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{}, nil
+ sg.AddNode("join_b", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{}, nil
})
if n, ok := sg.GetNode("join_b"); ok {
n.Triggers = []string{"b"}
}
- sg.AddNode("final_join", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"result": "all_done"}, nil
+ sg.AddNode("final_join", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"result": "all_done"}, nil
})
if n, ok := sg.GetNode("final_join"); ok {
n.Triggers = []string{"a", "b", "result"}
@@ -1667,7 +1667,7 @@ func TestEngine_MultipleFanInNodes(t *testing.T) {
sg.AddEdge("final_join", constants.End)
engine := NewEngine(sg, WithRecursionLimit(30))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1675,7 +1675,7 @@ func TestEngine_MultipleFanInNodes(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
r, _ := m["result"].(string)
a, _ := m["a"].(int)
b, _ := m["b"].(int)
@@ -1697,17 +1697,17 @@ func TestEngine_MultipleFanInNodes(t *testing.T) {
func TestEngine_OverwriteValue(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"value": ""})
+ sg := graph.NewStateGraph(map[string]any{"value": ""})
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("writer", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"value": types.NewOverwrite("overwritten")}, nil
+ sg.AddNode("writer", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"value": types.NewOverwrite("overwritten")}, nil
})
sg.AddEdge(constants.Start, "writer")
sg.AddEdge("writer", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1715,7 +1715,7 @@ func TestEngine_OverwriteValue(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["value"].(string)
if v != "overwritten" {
t.Errorf("expected overwritten, got %v", m["value"])
@@ -1729,13 +1729,13 @@ func TestEngine_OverwriteValue(t *testing.T) {
func TestEngine_TrivialEmptyGraph(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"x": ""})
+ sg := graph.NewStateGraph(map[string]any{"x": ""})
sg.AddChannel("x", channels.NewLastValue(""))
// No nodes at all — only Start and End
sg.AddEdge(constants.Start, constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{"x": "hello"})
+ result, err := engine.RunSync(context.Background(), map[string]any{"x": "hello"})
if err != nil {
t.Fatalf("trivial graph failed: %v", err)
}
@@ -1748,11 +1748,11 @@ func TestEngine_TrivialEmptyGraph(t *testing.T) {
func TestEngine_PregelWithCustomChannels(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"total": 0, "value": ""})
+ sg := graph.NewStateGraph(map[string]any{"total": 0, "value": ""})
sg.AddChannel("total", channels.NewLastValue(0))
sg.AddChannel("value", channels.NewLastValue(""))
- sg.AddNode("adder", func(ctx context.Context, state interface{}) (interface{}, error) {
+ sg.AddNode("adder", func(ctx context.Context, state any) (any, error) {
m := safeMap(state)
t, _ := m["total"].(int)
m["total"] = t + 5
@@ -1765,7 +1765,7 @@ func TestEngine_PregelWithCustomChannels(t *testing.T) {
sg.AddEdge("adder", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{"total": 10, "value": "init"})
+ result, err := engine.RunSync(context.Background(), map[string]any{"total": 10, "value": "init"})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1773,7 +1773,7 @@ func TestEngine_PregelWithCustomChannels(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
// Entry point now passes Triggers, so node reads total=10 from channel, adds 5 → 15.
total, _ := m["total"].(int)
if total != 15 {
@@ -1791,7 +1791,7 @@ func TestEngine_LargeLoopBSP(t *testing.T) {
const iterations = 50
sg := newLoopGraph(t, iterations)
engine := NewEngine(sg, WithRecursionLimit(iterations*2))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("RunSync failed: %v", err)
}
@@ -1799,7 +1799,7 @@ func TestEngine_LargeLoopBSP(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
c, _ := m["counter"].(int)
if c < iterations {
t.Errorf("expected counter >= %d, got %d", iterations, c)
@@ -1824,17 +1824,17 @@ func TestEngine_SingleNodeGraph(t *testing.T) {
mode := mode
t.Run(string(mode), func(t *testing.T) {
t.Parallel()
- sg := graph.NewStateGraph(map[string]interface{}{"val": ""})
+ sg := graph.NewStateGraph(map[string]any{"val": ""})
sg.NodeTriggerMode = mode
sg.AddChannel("val", channels.NewLastValue(""))
- sg.AddNode("only", func(ctx context.Context, state interface{}) (interface{}, error) {
- return map[string]interface{}{"val": "single"}, nil
+ sg.AddNode("only", func(ctx context.Context, state any) (any, error) {
+ return map[string]any{"val": "single"}, nil
})
sg.AddEdge(constants.Start, "only")
sg.AddEdge("only", constants.End)
engine := NewEngine(sg, WithRecursionLimit(5))
- result, err := engine.RunSync(context.Background(), map[string]interface{}{})
+ result, err := engine.RunSync(context.Background(), map[string]any{})
if err != nil {
t.Fatalf("mode=%s failed: %v", mode, err)
}
@@ -1842,7 +1842,7 @@ func TestEngine_SingleNodeGraph(t *testing.T) {
t.Skip("result nil")
return
}
- m := result.(map[string]interface{})
+ m := result.(map[string]any)
v, _ := m["val"].(string)
if v != "single" {
t.Errorf("expected single, got %s", v)
@@ -1856,4 +1856,3 @@ func TestEngine_SingleNodeGraph(t *testing.T) {
// ============================================================
// #2: Channel 写入冲突 — LastValue 多写入报错 vs BinaryOperator 合并
// ============================================================
-
diff --git a/internal/harness/graph/pregel/read.go b/internal/harness/graph/pregel/read.go
index ccac6e4d88..24a6cd0a35 100644
--- a/internal/harness/graph/pregel/read.go
+++ b/internal/harness/graph/pregel/read.go
@@ -24,7 +24,7 @@ type ChannelSelector interface {
// ChannelTransformer transforms the raw channel values.
type ChannelTransformer interface {
- Transform(values map[string]interface{}) (map[string]interface{}, error)
+ Transform(values map[string]any) (map[string]any, error)
}
// NewChannelRead creates a new channel read operation.
@@ -60,7 +60,7 @@ func WithTransformer(transformer ChannelTransformer) ChannelReadOption {
}
// Read performs the read operation.
-func (cr *ChannelRead) Read(ctx context.Context) (map[string]interface{}, error) {
+func (cr *ChannelRead) Read(ctx context.Context) (map[string]any, error) {
cr.mu.RLock()
defer cr.mu.RUnlock()
@@ -71,7 +71,7 @@ func (cr *ChannelRead) Read(ctx context.Context) (map[string]interface{}, error)
}
// Read values from channels
- values := make(map[string]interface{})
+ values := make(map[string]any)
for _, name := range channelNames {
if ch, ok := cr.registry.Get(name); ok {
val, err := ch.Get()
@@ -94,7 +94,7 @@ func (cr *ChannelRead) Read(ctx context.Context) (map[string]interface{}, error)
}
// ReadChannel reads a single channel by name.
-func (cr *ChannelRead) ReadChannel(ctx context.Context, name string) (interface{}, error) {
+func (cr *ChannelRead) ReadChannel(ctx context.Context, name string) (any, error) {
cr.mu.RLock()
defer cr.mu.RUnlock()
@@ -189,7 +189,7 @@ func (s *AvailableChannelsSelector) Select(registry *channels.Registry) ([]strin
// IdentityTransformer returns values as-is.
type IdentityTransformer struct{}
-func (t *IdentityTransformer) Transform(values map[string]interface{}) (map[string]interface{}, error) {
+func (t *IdentityTransformer) Transform(values map[string]any) (map[string]any, error) {
return values, nil
}
@@ -203,8 +203,8 @@ func NewMappingTransformer(mappings map[string]string) *MappingTransformer {
return &MappingTransformer{mappings: mappings}
}
-func (t *MappingTransformer) Transform(values map[string]interface{}) (map[string]interface{}, error) {
- result := make(map[string]interface{})
+func (t *MappingTransformer) Transform(values map[string]any) (map[string]any, error) {
+ result := make(map[string]any)
for oldName, value := range values {
newName := oldName
if mapped, ok := t.mappings[oldName]; ok {
@@ -229,8 +229,8 @@ func NewFilterTransformer(keep ...string) *FilterTransformer {
return &FilterTransformer{filter: filter}
}
-func (t *FilterTransformer) Transform(values map[string]interface{}) (map[string]interface{}, error) {
- result := make(map[string]interface{})
+func (t *FilterTransformer) Transform(values map[string]any) (map[string]any, error) {
+ result := make(map[string]any)
for name, value := range values {
if t.filter[name] {
result[name] = value
@@ -241,16 +241,16 @@ func (t *FilterTransformer) Transform(values map[string]interface{}) (map[string
// DefaultTransformer provides default values for missing channels.
type DefaultTransformer struct {
- defaults map[string]interface{}
+ defaults map[string]any
}
// NewDefaultTransformer creates a transformer with default values.
-func NewDefaultTransformer(defaults map[string]interface{}) *DefaultTransformer {
+func NewDefaultTransformer(defaults map[string]any) *DefaultTransformer {
return &DefaultTransformer{defaults: defaults}
}
-func (t *DefaultTransformer) Transform(values map[string]interface{}) (map[string]interface{}, error) {
- result := make(map[string]interface{})
+func (t *DefaultTransformer) Transform(values map[string]any) (map[string]any, error) {
+ result := make(map[string]any)
for name, defValue := range t.defaults {
if value, ok := values[name]; ok {
result[name] = value
@@ -270,20 +270,20 @@ func (t *DefaultTransformer) Transform(values map[string]interface{}) (map[strin
// MergingTransformer merges channels into a single value.
type MergingTransformer struct {
target string
- merger func([]interface{}) (interface{}, error)
+ merger func([]any) (any, error)
}
// NewMergingTransformer creates a transformer that merges channels.
-func NewMergingTransformer(target string, merger func([]interface{}) (interface{}, error)) *MergingTransformer {
+func NewMergingTransformer(target string, merger func([]any) (any, error)) *MergingTransformer {
return &MergingTransformer{
target: target,
merger: merger,
}
}
-func (t *MergingTransformer) Transform(values map[string]interface{}) (map[string]interface{}, error) {
+func (t *MergingTransformer) Transform(values map[string]any) (map[string]any, error) {
// Collect all values
- items := make([]interface{}, 0, len(values))
+ items := make([]any, 0, len(values))
for _, value := range values {
items = append(items, value)
}
@@ -295,7 +295,7 @@ func (t *MergingTransformer) Transform(values map[string]interface{}) (map[strin
}
// Return merged value under target key
- return map[string]interface{}{t.target: merged}, nil
+ return map[string]any{t.target: merged}, nil
}
// ==================== Triggers ====================
@@ -384,10 +384,10 @@ func (t *ChannelChangedTrigger) ShouldTrigger(registry *channels.Registry) bool
// ReadContext represents the context of a channel read operation.
type ReadContext struct {
- Node string
- Step int
- Triggers []Trigger
- Readers map[string]*ChannelRead
+ Node string
+ Step int
+ Triggers []Trigger
+ Readers map[string]*ChannelRead
}
// NewReadContext creates a new read context.
@@ -426,8 +426,8 @@ func (rc *ReadContext) ShouldExecute(registry *channels.Registry) bool {
}
// ReadAll executes all readers and combines their results.
-func (rc *ReadContext) ReadAll(ctx context.Context) (map[string]interface{}, error) {
- combined := make(map[string]interface{})
+func (rc *ReadContext) ReadAll(ctx context.Context) (map[string]any, error) {
+ combined := make(map[string]any)
for name, reader := range rc.Readers {
values, err := reader.Read(ctx)
if err != nil {
diff --git a/internal/harness/graph/pregel/read_test.go b/internal/harness/graph/pregel/read_test.go
index eae4a10306..b39cd68c2a 100644
--- a/internal/harness/graph/pregel/read_test.go
+++ b/internal/harness/graph/pregel/read_test.go
@@ -45,7 +45,7 @@ func TestChannelRead_Read(t *testing.T) {
reg := channels.NewRegistry()
ch := channels.NewLastValue("")
ch.SetKey("greeting")
- ch.Update([]interface{}{"hello"})
+ ch.Update([]any{"hello"})
reg.Register("greeting", ch)
cr := NewChannelRead(reg)
@@ -78,10 +78,10 @@ func TestAllChannelsSelector(t *testing.T) {
reg := channels.NewRegistry()
ch1 := channels.NewLastValue("")
ch1.SetKey("a")
- ch1.Update([]interface{}{1})
+ ch1.Update([]any{1})
ch2 := channels.NewLastValue("")
ch2.SetKey("b")
- ch2.Update([]interface{}{2})
+ ch2.Update([]any{2})
reg.Register("a", ch1)
reg.Register("b", ch2)
@@ -101,7 +101,7 @@ func TestSpecificChannelsSelector(t *testing.T) {
reg := channels.NewRegistry()
ch1 := channels.NewLastValue("")
ch1.SetKey("target")
- ch1.Update([]interface{}{"data"})
+ ch1.Update([]any{"data"})
ch2 := channels.NewLastValue("")
ch2.SetKey("other")
@@ -123,7 +123,7 @@ func TestAvailableChannelsSelector(t *testing.T) {
reg := channels.NewRegistry()
ch := channels.NewLastValue("")
ch.SetKey("active")
- ch.Update([]interface{}{"data"})
+ ch.Update([]any{"data"})
reg.Register("active", ch)
@@ -142,7 +142,7 @@ func TestPrefixChannelsSelector(t *testing.T) {
reg := channels.NewRegistry()
ch := channels.NewLastValue("")
ch.SetKey("pre_alpha")
- ch.Update([]interface{}{1})
+ ch.Update([]any{1})
reg.Register("pre_alpha", ch)
@@ -161,7 +161,7 @@ func TestPrefixChannelsSelector(t *testing.T) {
// TestIdentityTransformer verifies passthrough behavior.
func TestIdentityTransformer(t *testing.T) {
tf := &IdentityTransformer{}
- input := map[string]interface{}{"key": "value"}
+ input := map[string]any{"key": "value"}
result, err := tf.Transform(input)
if err != nil {
t.Fatalf("Transform: %v", err)
@@ -174,7 +174,7 @@ func TestIdentityTransformer(t *testing.T) {
// TestMappingTransformer verifies key mapping.
func TestMappingTransformer(t *testing.T) {
tf := NewMappingTransformer(map[string]string{"old": "new"})
- input := map[string]interface{}{"old": "data"}
+ input := map[string]any{"old": "data"}
result, err := tf.Transform(input)
if err != nil {
t.Fatalf("Transform: %v", err)
@@ -187,7 +187,7 @@ func TestMappingTransformer(t *testing.T) {
// TestFilterTransformer verifies filtering.
func TestFilterTransformer(t *testing.T) {
tf := NewFilterTransformer("keep")
- input := map[string]interface{}{"keep": "val", "remove": "ignored"}
+ input := map[string]any{"keep": "val", "remove": "ignored"}
result, err := tf.Transform(input)
if err != nil {
t.Fatalf("Transform: %v", err)
diff --git a/internal/harness/graph/pregel/remote.go b/internal/harness/graph/pregel/remote.go
index adb0b74737..80ca767f07 100644
--- a/internal/harness/graph/pregel/remote.go
+++ b/internal/harness/graph/pregel/remote.go
@@ -59,7 +59,7 @@ func NewRemoteRunnable(config *RemoteConfig) *RemoteRunnable {
}
// Execute sends a request to the remote server to execute a node.
-func (r *RemoteRunnable) Execute(ctx context.Context, nodeName string, input interface{}, config *types.RunnableConfig) (interface{}, error) {
+func (r *RemoteRunnable) Execute(ctx context.Context, nodeName string, input any, config *types.RunnableConfig) (any, error) {
// Build request
reqBody := &RemoteExecuteRequest{
Node: nodeName,
@@ -114,15 +114,15 @@ func (r *RemoteRunnable) Execute(ctx context.Context, nodeName string, input int
// RemoteExecuteRequest represents a request to execute a node remotely.
type RemoteExecuteRequest struct {
- Node string `json:"node"`
- Input interface{} `json:"input"`
- Config *types.RunnableConfig `json:"config,omitempty"`
+ Node string `json:"node"`
+ Input any `json:"input"`
+ Config *types.RunnableConfig `json:"config,omitempty"`
}
// RemoteExecuteResponse represents the response from a remote execution.
type RemoteExecuteResponse struct {
- Output interface{} `json:"output,omitempty"`
- Error string `json:"error,omitempty"`
+ Output any `json:"output,omitempty"`
+ Error string `json:"error,omitempty"`
}
// PregelProtocol defines the protocol for remote Pregel execution.
@@ -137,14 +137,14 @@ type PregelProtocol interface {
// PregelMessage represents a message in the Pregel protocol.
type PregelMessage struct {
- Type MessageType `json:"type"`
- ID string `json:"id"`
- NodeName string `json:"node_name,omitempty"`
- Input interface{} `json:"input,omitempty"`
- Output interface{} `json:"output,omitempty"`
- Error string `json:"error,omitempty"`
- Metadata map[string]interface{} `json:"metadata,omitempty"`
- Timestamp time.Time `json:"timestamp"`
+ Type MessageType `json:"type"`
+ ID string `json:"id"`
+ NodeName string `json:"node_name,omitempty"`
+ Input any `json:"input,omitempty"`
+ Output any `json:"output,omitempty"`
+ Error string `json:"error,omitempty"`
+ Metadata map[string]any `json:"metadata,omitempty"`
+ Timestamp time.Time `json:"timestamp"`
}
// MessageType represents the type of a Pregel message.
@@ -270,7 +270,7 @@ func NewRemoteNode(runnable *RemoteRunnable, nodeName string) *RemoteNode {
}
// Execute executes the remote node.
-func (n *RemoteNode) Execute(ctx context.Context, input interface{}) (interface{}, error) {
+func (n *RemoteNode) Execute(ctx context.Context, input any) (any, error) {
return n.runnable.Execute(ctx, n.nodeName, input, nil)
}
diff --git a/internal/harness/graph/pregel/retry.go b/internal/harness/graph/pregel/retry.go
index be68d809ed..7b8e07a4dd 100644
--- a/internal/harness/graph/pregel/retry.go
+++ b/internal/harness/graph/pregel/retry.go
@@ -6,6 +6,7 @@ import (
"fmt"
"time"
+ "ragflow/internal/harness/graph/errors"
"ragflow/internal/harness/graph/types"
)
@@ -24,40 +25,43 @@ func NewRetryExecutor(policy *types.RetryPolicy) *RetryExecutor {
}
// Execute executes a function with retry logic.
-func (e *RetryExecutor) Execute(ctx context.Context, name string, fn func(context.Context) (interface{}, error)) (output interface{}, err error) {
+func (e *RetryExecutor) Execute(ctx context.Context, name string, fn func(context.Context) (any, error)) (output any, err error) {
defer func() {
if r := recover(); r != nil {
output = nil
err = fmt.Errorf("node %s panicked: %v", name, r)
}
}()
-
+
var lastErr error
- var lastOutput interface{}
-
+ var lastOutput any
+
for attempt := 1; attempt <= e.policy.MaxAttempts; attempt++ {
// Execute the function
output, err = fn(ctx)
if err == nil {
return output, nil
}
-
+
// Check if this is a non-retryable error
+ if errors.IsGraphInterrupt(err) {
+ return nil, err // propagate GraphInterrupt immediately without wrapping
+ }
if e.policy.RetryOn != nil && !e.policy.RetryOn(err) {
return nil, fmt.Errorf("node %s failed with non-retryable error: %w", name, err)
}
-
+
lastErr = err
lastOutput = output
-
+
// If we've exhausted attempts, break
if attempt >= e.policy.MaxAttempts {
break
}
-
+
// Calculate backoff with jitter
backoff := e.calculateBackoff(attempt)
-
+
// Wait before retry
select {
case <-ctx.Done():
@@ -66,11 +70,11 @@ func (e *RetryExecutor) Execute(ctx context.Context, name string, fn func(contex
// Continue to next attempt
}
}
-
+
return nil, &RetryExhaustedError{
- NodeName: name,
- Attempts: e.policy.MaxAttempts,
- LastErr: lastErr,
+ NodeName: name,
+ Attempts: e.policy.MaxAttempts,
+ LastErr: lastErr,
LastOutput: lastOutput,
}
}
@@ -90,7 +94,7 @@ type RetryExhaustedError struct {
NodeName string
Attempts int
LastErr error
- LastOutput interface{}
+ LastOutput any
}
// Error implements the error interface.
@@ -172,11 +176,11 @@ var RetryPredicates = struct {
// contains checks if a string contains a substring (case-insensitive).
func contains(s, substr string) bool {
- return len(s) >= len(substr) &&
- (s == substr ||
- len(s) > len(substr) &&
- (s[0:len(substr)] == substr ||
- containsIgnoreCase(s, substr)))
+ return len(s) >= len(substr) &&
+ (s == substr ||
+ len(s) > len(substr) &&
+ (s[0:len(substr)] == substr ||
+ containsIgnoreCase(s, substr)))
}
// containsIgnoreCase performs case-insensitive substring check.
diff --git a/internal/harness/graph/pregel/retry_multi.go b/internal/harness/graph/pregel/retry_multi.go
index 88feaef632..060b73ea97 100644
--- a/internal/harness/graph/pregel/retry_multi.go
+++ b/internal/harness/graph/pregel/retry_multi.go
@@ -28,14 +28,14 @@ func NewMultiPolicyRetryExecutor(policies ...types.RetryPolicy) *MultiPolicyRetr
func (e *MultiPolicyRetryExecutor) Execute(
ctx context.Context,
name string,
- fn func(context.Context) (interface{}, error),
-) (interface{}, error) {
+ fn func(context.Context) (any, error),
+) (any, error) {
if len(e.policies) == 0 {
return fn(ctx)
}
var lastErr error
- var lastOutput interface{}
+ var lastOutput any
attempt := 0
for {
@@ -96,9 +96,9 @@ func (e *MultiPolicyRetryExecutor) findMatchingPolicy(err error) *types.RetryPol
// MultiRetryConfig provides configuration for multi-policy retry behavior.
type MultiRetryConfig struct {
- Policies []types.RetryPolicy
- OnRetry func(attempt int, policyIndex int, err error)
- OnSuccess func(attempt int)
+ Policies []types.RetryPolicy
+ OnRetry func(attempt int, policyIndex int, err error)
+ OnSuccess func(attempt int)
OnPolicyMatch func(attempt int, policyIndex int)
}
@@ -167,10 +167,14 @@ var RetryPolicyPresets = struct {
BackoffFactor: 1.5,
Jitter: true,
RetryOn: func(err error) bool {
- if err == nil { return false }
+ if err == nil {
+ return false
+ }
errMsg := err.Error()
for _, kw := range []string{"resource exhausted", "too many requests", "rate limit", "quota exceeded", "429", "503"} {
- if contains(errMsg, kw) { return true }
+ if contains(errMsg, kw) {
+ return true
+ }
}
return false
},
@@ -182,10 +186,14 @@ var RetryPolicyPresets = struct {
BackoffFactor: 2.0,
Jitter: false,
RetryOn: func(err error) bool {
- if err == nil { return false }
+ if err == nil {
+ return false
+ }
errMsg := err.Error()
for _, kw := range []string{"timeout", "deadline exceeded", "context deadline", "408", "504"} {
- if contains(errMsg, kw) { return true }
+ if contains(errMsg, kw) {
+ return true
+ }
}
return false
},
diff --git a/internal/harness/graph/pregel/stream.go b/internal/harness/graph/pregel/stream.go
index d2cc4710f8..626b7cbd7d 100644
--- a/internal/harness/graph/pregel/stream.go
+++ b/internal/harness/graph/pregel/stream.go
@@ -48,7 +48,7 @@ type StreamEvent struct {
// TaskID is the task ID (for task events)
TaskID string
// Data is the event-specific data
- Data interface{}
+ Data any
// Error is the error (for error events)
Error error
}
@@ -59,7 +59,7 @@ func NewStreamEvent(eventType StreamEventType, step int) *StreamEvent {
Type: eventType,
Timestamp: time.Now(),
Step: step,
- Data: make(map[string]interface{}),
+ Data: make(map[string]any),
}
}
@@ -86,18 +86,18 @@ func NewStreamManager(mode types.StreamMode, bufferSize int) *StreamManager {
if bufferSize <= 0 {
bufferSize = 100
}
-
+
sm := &StreamManager{
- mode: mode,
- eventCh: make(chan *StreamEvent, bufferSize),
- errorCh: make(chan error, 10),
- bufferSize: bufferSize,
+ mode: mode,
+ eventCh: make(chan *StreamEvent, bufferSize),
+ errorCh: make(chan error, 10),
+ bufferSize: bufferSize,
includeFilter: make(map[StreamEventType]bool),
}
-
+
// Set up include filter based on stream mode
sm.setupIncludeFilter()
-
+
return sm
}
@@ -107,21 +107,21 @@ func (sm *StreamManager) setupIncludeFilter() {
case types.StreamModeValues:
sm.includeFilter[EventTypeValues] = true
sm.includeFilter[EventTypeFinal] = true
-
+
case types.StreamModeUpdates:
sm.includeFilter[EventTypeUpdate] = true
sm.includeFilter[EventTypeFinal] = true
-
+
case types.StreamModeTasks:
sm.includeFilter[EventTypeTaskStart] = true
sm.includeFilter[EventTypeTaskEnd] = true
sm.includeFilter[EventTypeError] = true
sm.includeFilter[EventTypeFinal] = true
-
+
case types.StreamModeCheckpoints:
sm.includeFilter[EventTypeCheckpoint] = true
sm.includeFilter[EventTypeFinal] = true
-
+
case types.StreamModeDebug:
// Include all events in debug mode
sm.includeFilter[EventTypeCheckpoint] = true
@@ -133,7 +133,7 @@ func (sm *StreamManager) setupIncludeFilter() {
sm.includeFilter[EventTypeError] = true
sm.includeFilter[EventTypeDebug] = true
sm.includeFilter[EventTypeFinal] = true
-
+
default:
// Default to values mode
sm.includeFilter[EventTypeValues] = true
@@ -149,16 +149,16 @@ func (sm *StreamManager) shouldEmit(eventType StreamEventType) bool {
}
// EmitCheckpoint emits a checkpoint event.
-func (sm *StreamManager) EmitCheckpoint(step int, checkpoint map[string]interface{}) {
+func (sm *StreamManager) EmitCheckpoint(step int, checkpoint map[string]any) {
if !sm.shouldEmit(EventTypeCheckpoint) {
return
}
-
+
event := NewStreamEvent(EventTypeCheckpoint, step)
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"checkpoint": checkpoint,
}
-
+
sm.emit(event)
}
@@ -167,65 +167,65 @@ func (sm *StreamManager) EmitTaskStart(step int, node string, taskID string) {
if !sm.shouldEmit(EventTypeTaskStart) {
return
}
-
+
event := NewStreamEvent(EventTypeTaskStart, step)
event.Node = node
event.TaskID = taskID
- event.Data = map[string]interface{}{
- "node": node,
+ event.Data = map[string]any{
+ "node": node,
"task_id": taskID,
}
-
+
sm.emit(event)
}
// EmitTaskEnd emits a task end event.
-func (sm *StreamManager) EmitTaskEnd(step int, node string, taskID string, output interface{}, duration time.Duration, err error) {
+func (sm *StreamManager) EmitTaskEnd(step int, node string, taskID string, output any, duration time.Duration, err error) {
if !sm.shouldEmit(EventTypeTaskEnd) {
return
}
-
+
event := NewStreamEvent(EventTypeTaskEnd, step)
event.Node = node
event.TaskID = taskID
event.Error = err
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"node": node,
"task_id": taskID,
"output": output,
"duration": duration.String(),
}
-
+
sm.emit(event)
}
// EmitUpdate emits a state update event.
-func (sm *StreamManager) EmitUpdate(step int, node string, output interface{}) {
+func (sm *StreamManager) EmitUpdate(step int, node string, output any) {
if !sm.shouldEmit(EventTypeUpdate) {
return
}
-
+
event := NewStreamEvent(EventTypeUpdate, step)
event.Node = node
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"node": node,
"output": output,
}
-
+
sm.emit(event)
}
// EmitValues emits state values event.
-func (sm *StreamManager) EmitValues(step int, values map[string]interface{}) {
+func (sm *StreamManager) EmitValues(step int, values map[string]any) {
if !sm.shouldEmit(EventTypeValues) {
return
}
-
+
event := NewStreamEvent(EventTypeValues, step)
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"values": values,
}
-
+
sm.emit(event)
}
@@ -234,12 +234,12 @@ func (sm *StreamManager) EmitInterrupt(step int, interrupts []string) {
if !sm.shouldEmit(EventTypeInterrupt) {
return
}
-
+
event := NewStreamEvent(EventTypeInterrupt, step)
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"interrupts": interrupts,
}
-
+
sm.emit(event)
}
@@ -248,44 +248,44 @@ func (sm *StreamManager) EmitError(step int, err error, node string) {
if !sm.shouldEmit(EventTypeError) {
return
}
-
+
event := NewStreamEvent(EventTypeError, step)
event.Node = node
event.Error = err
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"node": node,
"error": err.Error(),
}
-
+
sm.emit(event)
}
// EmitDebug emits a debug event.
-func (sm *StreamManager) EmitDebug(step int, message string, data interface{}) {
+func (sm *StreamManager) EmitDebug(step int, message string, data any) {
if !sm.shouldEmit(EventTypeDebug) {
return
}
-
+
event := NewStreamEvent(EventTypeDebug, step)
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"message": message,
"data": data,
}
-
+
sm.emit(event)
}
// EmitFinal emits final event with complete state.
-func (sm *StreamManager) EmitFinal(step int, state interface{}) {
+func (sm *StreamManager) EmitFinal(step int, state any) {
if !sm.shouldEmit(EventTypeFinal) {
return
}
-
+
event := NewStreamEvent(EventTypeFinal, step)
- event.Data = map[string]interface{}{
+ event.Data = map[string]any{
"state": state,
}
-
+
sm.emit(event)
}
@@ -293,11 +293,11 @@ func (sm *StreamManager) EmitFinal(step int, state interface{}) {
func (sm *StreamManager) emit(event *StreamEvent) {
sm.mu.RLock()
defer sm.mu.RUnlock()
-
+
if sm.mu.closed {
return
}
-
+
select {
case sm.eventCh <- event:
// Event sent
@@ -320,7 +320,7 @@ func (sm *StreamManager) Errors() <-chan error {
func (sm *StreamManager) Close() {
sm.mu.Lock()
defer sm.mu.Unlock()
-
+
if !sm.mu.closed {
sm.mu.closed = true
close(sm.eventCh)
@@ -345,13 +345,13 @@ func NewStreamWriter(sm *StreamManager, step int, node string) *StreamWriter {
}
// Write writes data to the stream.
-func (w *StreamWriter) Write(data interface{}) error {
+func (w *StreamWriter) Write(data any) error {
w.streamManager.EmitDebug(w.step, fmt.Sprintf("custom output from node %s", w.node), data)
return nil
}
// WriteJSON writes JSON data to the stream.
-func (w *StreamWriter) WriteJSON(data interface{}) error {
+func (w *StreamWriter) WriteJSON(data any) error {
jsonData, err := json.Marshal(data)
if err != nil {
return err
@@ -413,17 +413,17 @@ func (es *EventStream) Stream() (<-chan *StreamEvent, <-chan error) {
// StreamProcessor processes stream events.
type StreamProcessor struct {
- filter func(*StreamEvent) bool
+ filter func(*StreamEvent) bool
transform func(*StreamEvent) (*StreamEvent, error)
- handler func(*StreamEvent)
+ handler func(*StreamEvent)
}
// NewStreamProcessor creates a new stream processor.
func NewStreamProcessor() *StreamProcessor {
return &StreamProcessor{
- filter: func(e *StreamEvent) bool { return true },
+ filter: func(e *StreamEvent) bool { return true },
transform: func(e *StreamEvent) (*StreamEvent, error) { return e, nil },
- handler: func(e *StreamEvent) {},
+ handler: func(e *StreamEvent) {},
}
}
@@ -450,12 +450,12 @@ func (sp *StreamProcessor) Process(event *StreamEvent) error {
if !sp.filter(event) {
return nil
}
-
+
transformed, err := sp.transform(event)
if err != nil {
return err
}
-
+
sp.handler(transformed)
return nil
}
diff --git a/internal/harness/graph/pregel/subgraph.go b/internal/harness/graph/pregel/subgraph.go
index 7b9dd28a4f..70df2084f5 100644
--- a/internal/harness/graph/pregel/subgraph.go
+++ b/internal/harness/graph/pregel/subgraph.go
@@ -19,7 +19,7 @@ type SubgraphManager struct {
parentEngine *Engine
subgraphs map[string]*Engine
namespaceStack []string
- mu sync.RWMutex
+ mu sync.RWMutex
checkpointNS map[string]string // maps thread_id to checkpoint namespace
}
@@ -27,10 +27,10 @@ type SubgraphManager struct {
type SubgraphConfig struct {
Name string
ParentEngine *Engine
- Graph interface{} // Use interface{} to accept any graph type
- Configurable interface{}
- Store interface{}
- Writer interface{}
+ Graph any // Use any to accept any graph type
+ Configurable any
+ Store any
+ Writer any
}
// NewSubgraphManager creates a new subgraph manager.
@@ -80,7 +80,7 @@ func (m *SubgraphManager) CreateSubgraph(config *SubgraphConfig) (*Engine, error
func (m *SubgraphManager) GetSubgraph(name string) (*Engine, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
-
+
subgraph, exists := m.subgraphs[name]
return subgraph, exists
}
@@ -90,8 +90,8 @@ func (m *SubgraphManager) ExecuteInSubgraph(
ctx context.Context,
subgraphName string,
nodeName string,
- input interface{},
-) (interface{}, error) {
+ input any,
+) (any, error) {
subgraph, exists := m.GetSubgraph(subgraphName)
if !exists {
return nil, fmt.Errorf("subgraph '%s' not found", subgraphName)
@@ -122,7 +122,7 @@ func (m *SubgraphManager) ExecuteInSubgraph(
func (m *SubgraphManager) PushNamespace(ns string) {
m.mu.Lock()
defer m.mu.Unlock()
-
+
m.namespaceStack = append(m.namespaceStack, ns)
}
@@ -130,7 +130,7 @@ func (m *SubgraphManager) PushNamespace(ns string) {
func (m *SubgraphManager) PopNamespace() {
m.mu.Lock()
defer m.mu.Unlock()
-
+
if len(m.namespaceStack) > 0 {
m.namespaceStack = m.namespaceStack[:len(m.namespaceStack)-1]
}
@@ -140,7 +140,7 @@ func (m *SubgraphManager) PopNamespace() {
func (m *SubgraphManager) CurrentNamespace() string {
m.mu.RLock()
defer m.mu.RUnlock()
-
+
if len(m.namespaceStack) > 0 {
return m.namespaceStack[len(m.namespaceStack)-1]
}
@@ -151,18 +151,18 @@ func (m *SubgraphManager) CurrentNamespace() string {
func (m *SubgraphManager) BuildNamespacePath() string {
m.mu.RLock()
defer m.mu.RUnlock()
-
+
if len(m.namespaceStack) == 0 {
return ""
}
-
+
return strings.Join(m.namespaceStack, string(constants.NSSep))
}
// withCheckpointNamespace adds the checkpoint namespace to the context.
func (m *SubgraphManager) withCheckpointNamespace(ctx context.Context, ns string) context.Context {
path := m.BuildNamespacePath()
-
+
// Create a new config and add namespace
// Note: Simplified implementation for compilation
_ = path // Mark as used for now
@@ -172,12 +172,12 @@ func (m *SubgraphManager) withCheckpointNamespace(ctx context.Context, ns string
// CheckpointMigration handles checkpoint migration between parent and subgraphs.
type CheckpointMigration struct {
manager *SubgraphManager
- checkpointer interface{} // Changed from checkpoint.CheckpointSaver to avoid type issues
+ checkpointer any // Changed from checkpoint.CheckpointSaver to avoid type issues
mu sync.Mutex
}
// NewCheckpointMigration creates a new checkpoint migration handler.
-func NewCheckpointMigration(manager *SubgraphManager, checkpointer interface{}) *CheckpointMigration {
+func NewCheckpointMigration(manager *SubgraphManager, checkpointer any) *CheckpointMigration {
return &CheckpointMigration{
manager: manager,
checkpointer: checkpointer,
@@ -196,9 +196,9 @@ func (cm *CheckpointMigration) MigrateToSubgraph(
// Build subgraph namespace
subgraphNS := cm.manager.BuildNamespacePath() + string(constants.NSSep) + subgraphName
-
+
// Build subgraph config
- subgraphConfig := make(map[string]interface{})
+ subgraphConfig := make(map[string]any)
subgraphConfig[constants.ConfigKeyCheckpointNS] = subgraphNS
subgraphConfig[constants.ConfigKeyCheckpointID] = uuid.New().String()
subgraphConfig["task_path"] = parentCheckpointID + string(constants.NSEnd) + subgraphName
@@ -261,9 +261,9 @@ func (m *SubgraphManager) ResolveParentCommand(
// NamespaceIsolatedRegistry creates a channel registry with namespace isolation.
type NamespaceIsolatedRegistry struct {
- registry *channels.Registry
+ registry *channels.Registry
namespace string
- prefix string
+ prefix string
}
// NewNamespaceIsolatedRegistry creates a new namespace-isolated registry.
@@ -272,22 +272,22 @@ func NewNamespaceIsolatedRegistry(baseRegistry *channels.Registry, namespace str
if prefix != "" {
prefix += string(constants.NSSep)
}
-
+
return &NamespaceIsolatedRegistry{
- registry: baseRegistry,
+ registry: baseRegistry,
namespace: namespace,
- prefix: prefix,
+ prefix: prefix,
}
}
// Get retrieves a channel with namespace prefix.
-func (r *NamespaceIsolatedRegistry) Get(name string) (interface{}, bool) {
+func (r *NamespaceIsolatedRegistry) Get(name string) (any, bool) {
fullName := r.prefix + name
return r.registry.Get(fullName)
}
// Register registers a channel with namespace prefix.
-func (r *NamespaceIsolatedRegistry) Register(name string, channel interface{}) error {
+func (r *NamespaceIsolatedRegistry) Register(name string, channel any) error {
fullName := r.prefix + name
// Check if channel implements channels.Channel
if ch, ok := channel.(channels.Channel); ok {
@@ -299,39 +299,39 @@ func (r *NamespaceIsolatedRegistry) Register(name string, channel interface{}) e
}
// CreateCheckpoint creates a checkpoint with namespace isolation.
-func (r *NamespaceIsolatedRegistry) CreateCheckpoint() map[string]interface{} {
+func (r *NamespaceIsolatedRegistry) CreateCheckpoint() map[string]any {
baseCheckpoint := r.registry.CreateCheckpoint()
-
+
// Add namespace metadata
baseCheckpoint["namespace"] = r.namespace
baseCheckpoint["prefix"] = r.prefix
-
+
return baseCheckpoint
}
// GetValues retrieves all channel values with namespace isolation.
-func (r *NamespaceIsolatedRegistry) GetValues() (map[string]interface{}, error) {
+func (r *NamespaceIsolatedRegistry) GetValues() (map[string]any, error) {
allValues, err := r.registry.GetValues()
if err != nil {
return nil, err
}
-
+
// Filter to namespace-prefixed channels
- filtered := make(map[string]interface{})
+ filtered := make(map[string]any)
for key, value := range allValues {
if strings.HasPrefix(key, r.prefix) {
relKey := strings.TrimPrefix(key, r.prefix)
filtered[relKey] = value
}
}
-
+
return filtered, nil
}
// RecursiveSubgraphExecutor handles recursive execution within subgraphs.
type RecursiveSubgraphExecutor struct {
- manager *SubgraphManager
- maxDepth int
+ manager *SubgraphManager
+ maxDepth int
}
// NewRecursiveSubgraphExecutor creates a new recursive subgraph executor.
@@ -347,13 +347,13 @@ func (e *RecursiveSubgraphExecutor) ExecuteRecursive(
ctx context.Context,
subgraphName string,
nodeName string,
- input interface{},
+ input any,
depth int,
-) (interface{}, error) {
+) (any, error) {
if depth > e.maxDepth {
return nil, fmt.Errorf("recursion depth limit exceeded: %d > %d", depth, e.maxDepth)
}
-
+
// Execute in subgraph
return e.manager.ExecuteInSubgraph(ctx, subgraphName, nodeName, input)
}
@@ -362,9 +362,9 @@ func (e *RecursiveSubgraphExecutor) ExecuteRecursive(
func (e *RecursiveSubgraphExecutor) executeRecursive(
ctx context.Context,
subgraphName string,
- input interface{},
+ input any,
depth int,
-) (interface{}, error) {
+) (any, error) {
// Simplified version for testing
if depth > e.maxDepth {
return nil, fmt.Errorf("recursion depth limit exceeded: %d > %d", depth, e.maxDepth)
diff --git a/internal/harness/graph/pregel/subgraph_test.go b/internal/harness/graph/pregel/subgraph_test.go
index ea638db2d0..9aa3e0b8cd 100644
--- a/internal/harness/graph/pregel/subgraph_test.go
+++ b/internal/harness/graph/pregel/subgraph_test.go
@@ -16,17 +16,17 @@ func TestSubgraphManagerCreation(t *testing.T) {
parentEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
manager := NewSubgraphManager(parentEngine)
-
+
if manager == nil {
t.Fatal("Expected non-nil manager")
}
-
+
if manager.parentEngine != parentEngine {
t.Error("Expected parent engine to match")
}
-
+
if len(manager.subgraphs) != 0 {
t.Errorf("Expected empty subgraphs, got %d", len(manager.subgraphs))
}
@@ -36,7 +36,7 @@ func TestNamespaceStack(t *testing.T) {
manager := &SubgraphManager{
namespaceStack: make([]string, 0),
}
-
+
// Test pushing namespaces
manager.PushNamespace("subgraph1")
if len(manager.namespaceStack) != 1 {
@@ -45,7 +45,7 @@ func TestNamespaceStack(t *testing.T) {
if manager.CurrentNamespace() != "subgraph1" {
t.Errorf("Expected current namespace 'subgraph1', got %s", manager.CurrentNamespace())
}
-
+
manager.PushNamespace("subgraph2")
if len(manager.namespaceStack) != 2 {
t.Errorf("Expected stack size 2, got %d", len(manager.namespaceStack))
@@ -53,7 +53,7 @@ func TestNamespaceStack(t *testing.T) {
if manager.CurrentNamespace() != "subgraph2" {
t.Errorf("Expected current namespace 'subgraph2', got %s", manager.CurrentNamespace())
}
-
+
// Test popping namespaces
manager.PopNamespace()
if len(manager.namespaceStack) != 1 {
@@ -62,7 +62,7 @@ func TestNamespaceStack(t *testing.T) {
if manager.CurrentNamespace() != "subgraph1" {
t.Errorf("Expected current namespace 'subgraph1', got %s", manager.CurrentNamespace())
}
-
+
manager.PopNamespace()
if len(manager.namespaceStack) != 0 {
t.Errorf("Expected empty stack, got %d", len(manager.namespaceStack))
@@ -74,33 +74,33 @@ func TestNamespaceStack(t *testing.T) {
func TestBuildNamespacePath(t *testing.T) {
tests := []struct {
- name string
- stack []string
- expectedPath string
+ name string
+ stack []string
+ expectedPath string
}{
{
- name: "empty stack",
- stack: []string{},
- expectedPath: "",
+ name: "empty stack",
+ stack: []string{},
+ expectedPath: "",
},
{
- name: "single namespace",
- stack: []string{"subgraph1"},
- expectedPath: "subgraph1",
+ name: "single namespace",
+ stack: []string{"subgraph1"},
+ expectedPath: "subgraph1",
},
{
- name: "multiple namespaces",
- stack: []string{"subgraph1", "subgraph2", "subgraph3"},
- expectedPath: "subgraph1|subgraph2|subgraph3",
+ name: "multiple namespaces",
+ stack: []string{"subgraph1", "subgraph2", "subgraph3"},
+ expectedPath: "subgraph1|subgraph2|subgraph3",
},
}
-
+
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
manager := &SubgraphManager{
namespaceStack: tt.stack,
}
-
+
path := manager.BuildNamespacePath()
if path != tt.expectedPath {
t.Errorf("Expected path '%s', got '%s'", tt.expectedPath, path)
@@ -111,26 +111,26 @@ func TestBuildNamespacePath(t *testing.T) {
func TestNamespaceIsolatedRegistry(t *testing.T) {
baseRegistry := channels.NewRegistry()
-
+
// Register some channels in base registry
ch1 := channels.NewAnyValue(nil)
baseRegistry.Register("base_channel1", ch1)
-
+
// Create isolated registry
isolated := NewNamespaceIsolatedRegistry(baseRegistry, "subgraph1")
-
+
// Test get with namespace prefix
_, exists := isolated.Get("channel1")
if exists {
t.Error("Expected non-existent channel")
}
-
+
// Register in isolated registry
ch2 := channels.NewAnyValue(nil)
if err := isolated.Register("isolated_channel1", ch2); err != nil {
t.Fatalf("Failed to register isolated channel: %v", err)
}
-
+
// Get should work with full namespace prefix
_, exists = isolated.Get("isolated_channel1")
if !exists {
@@ -142,10 +142,10 @@ func TestRecursiveSubgraphExecutor(t *testing.T) {
parentEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
manager := NewSubgraphManager(parentEngine)
executor := NewRecursiveSubgraphExecutor(manager, 5)
-
+
t.Run("depth limit enforcement", func(t *testing.T) {
// Try to exceed max depth
_, err := executor.executeRecursive(context.Background(), "test", "input", 10)
@@ -153,7 +153,7 @@ func TestRecursiveSubgraphExecutor(t *testing.T) {
t.Error("Expected depth limit error")
}
})
-
+
t.Run("normal execution", func(t *testing.T) {
// This would need proper graph setup for full test
_, err := executor.executeRecursive(context.Background(), "test", "input", 0)
@@ -166,40 +166,40 @@ func TestRecursiveSubgraphExecutor(t *testing.T) {
func TestCheckpointMigration(t *testing.T) {
mockCheckpointer := &MockCheckpointSaver{
- checkpoints: make(map[string]map[string]interface{}),
- tuples: make(map[string]*checkpoint.CheckpointTuple),
- mu: sync.RWMutex{},
+ checkpoints: make(map[string]map[string]any),
+ tuples: make(map[string]*checkpoint.CheckpointTuple),
+ mu: sync.RWMutex{},
}
-
+
parentEngine := &Engine{
checkpointer: mockCheckpointer,
}
-
+
manager := NewSubgraphManager(parentEngine)
migration := NewCheckpointMigration(manager, mockCheckpointer)
-
+
t.Run("migrate to subgraph", func(t *testing.T) {
manager.PushNamespace("subgraph1")
ctx := context.Background()
-
+
// Create parent checkpoint
- parentCP := map[string]interface{}{
+ parentCP := map[string]any{
"channel1": "value1",
"channel2": "value2",
}
-
+
mockCheckpointer.tuples["parent"] = &checkpoint.CheckpointTuple{
Checkpoint: &checkpoint.Checkpoint{
State: parentCP,
},
}
-
+
// Migrate to subgraph
_, err := migration.MigrateToSubgraph(ctx, "thread1", "parent", "subgraph1")
if err != nil {
t.Errorf("MigrateToSubgraph failed: %v", err)
}
-
+
// Check namespace tracking
ns, exists := manager.checkpointNS["thread1"]
if !exists {
@@ -209,34 +209,34 @@ func TestCheckpointMigration(t *testing.T) {
if ns != expectedNS {
t.Errorf("Expected namespace '%s', got '%s'", expectedNS, ns)
}
-
+
manager.PopNamespace()
})
-
+
t.Run("migrate from subgraph", func(t *testing.T) {
ctx := context.Background()
-
+
// Create subgraph checkpoint
- subgraphCP := map[string]interface{}{
+ subgraphCP := map[string]any{
"channel1": "updated_value1",
"channel2": "updated_value2",
}
-
+
mockCheckpointer.tuples["subgraph"] = &checkpoint.CheckpointTuple{
Checkpoint: &checkpoint.Checkpoint{
State: subgraphCP,
},
}
-
+
// Set checkpoint namespace
manager.checkpointNS["thread1"] = "subgraph1"
-
+
// Migrate from subgraph
err := migration.MigrateFromSubgraph(ctx, "thread1", "subgraph")
if err != nil {
t.Errorf("MigrateFromSubgraph failed: %v", err)
}
-
+
// Check namespace removed
_, exists := manager.checkpointNS["thread1"]
if exists {
@@ -247,31 +247,31 @@ func TestCheckpointMigration(t *testing.T) {
func TestResolveParentCommand(t *testing.T) {
manager := NewSubgraphManager(&Engine{})
-
+
t.Run("resolve with namespace", func(t *testing.T) {
manager.PushNamespace("subgraph1")
-
+
cmd := &types.Command{
Goto: types.Parent,
}
-
+
resolved, err := manager.ResolveParentCommand(context.Background(), cmd)
if err != nil {
t.Errorf("ResolveParentCommand failed: %v", err)
}
-
+
if resolved.Goto != types.Parent {
t.Error("Expected Parent goto")
}
-
+
manager.PopNamespace()
})
-
+
t.Run("resolve at root", func(t *testing.T) {
cmd := &types.Command{
Goto: types.Parent,
}
-
+
_, err := manager.ResolveParentCommand(context.Background(), cmd)
if err == nil {
t.Error("Expected error at root namespace")
@@ -283,44 +283,44 @@ func TestCreateSubgraph(t *testing.T) {
parentEngine := &Engine{
config: types.NewRunnableConfig(),
}
-
+
manager := NewSubgraphManager(parentEngine)
-
+
// Create a simple graph for subgraph
graph := NewMockGraph()
graph.AddNode("node1", &MockNode{name: "node1"})
graph.SetEntryPoint("node1")
-
+
t.Run("create subgraph", func(t *testing.T) {
config := &SubgraphConfig{
Name: "subgraph1",
ParentEngine: parentEngine,
Graph: graph,
}
-
+
subgraph, err := manager.CreateSubgraph(config)
if err != nil {
t.Fatalf("CreateSubgraph failed: %v", err)
}
-
+
if subgraph == nil {
t.Fatal("Expected non-nil subgraph")
}
-
+
// Check that subgraph is registered in manager
_, exists := manager.GetSubgraph("subgraph1")
if !exists {
t.Error("Expected subgraph to be registered in manager")
}
})
-
+
t.Run("duplicate subgraph", func(t *testing.T) {
config := &SubgraphConfig{
Name: "subgraph1",
ParentEngine: parentEngine,
Graph: graph,
}
-
+
_, err := manager.CreateSubgraph(config)
if err == nil {
t.Error("Expected error for duplicate subgraph")
@@ -331,23 +331,23 @@ func TestCreateSubgraph(t *testing.T) {
func TestGetSubgraph(t *testing.T) {
parentEngine := &Engine{}
manager := NewSubgraphManager(parentEngine)
-
+
// Create a subgraph
graph := NewMockGraph()
graph.AddNode("node1", &MockNode{name: "node1"})
graph.SetEntryPoint("node1")
-
+
config := &SubgraphConfig{
Name: "test_subgraph",
ParentEngine: parentEngine,
Graph: graph,
}
-
+
subgraph, err := manager.CreateSubgraph(config)
if err != nil {
t.Fatalf("Failed to create subgraph: %v", err)
}
-
+
t.Run("get existing subgraph", func(t *testing.T) {
retrieved, exists := manager.GetSubgraph("test_subgraph")
if !exists {
@@ -357,7 +357,7 @@ func TestGetSubgraph(t *testing.T) {
t.Error("Retrieved subgraph doesn't match")
}
})
-
+
t.Run("get non-existent subgraph", func(t *testing.T) {
_, exists := manager.GetSubgraph("non_existent")
if exists {
@@ -369,19 +369,19 @@ func TestGetSubgraph(t *testing.T) {
func TestNamespaceSeparator(t *testing.T) {
// Verify constants.NSSep is set correctly
expectedSep := "|"
-
+
if string(constants.NSSep) != expectedSep {
t.Errorf("Expected NSSep '%s', got '%s'", expectedSep, string(constants.NSSep))
}
-
+
// Test path building with NSSep
manager := &SubgraphManager{}
manager.PushNamespace("ns1")
manager.PushNamespace("ns2")
-
+
path := manager.BuildNamespacePath()
expectedPath := "ns1|ns2"
-
+
if path != expectedPath {
t.Errorf("Expected path '%s', got '%s'", expectedPath, path)
}
@@ -389,24 +389,24 @@ func TestNamespaceSeparator(t *testing.T) {
// MockCheckpointSaver is a mock implementation of CheckpointSaver for testing.
type MockCheckpointSaver struct {
- checkpoints map[string]map[string]interface{}
- tuples map[string]*checkpoint.CheckpointTuple
- mu sync.RWMutex
+ checkpoints map[string]map[string]any
+ tuples map[string]*checkpoint.CheckpointTuple
+ mu sync.RWMutex
}
-func (m *MockCheckpointSaver) Put(ctx context.Context, config map[string]interface{}, checkpoint map[string]interface{}) error {
+func (m *MockCheckpointSaver) Put(ctx context.Context, config map[string]any, checkpoint map[string]any) error {
m.mu.Lock()
defer m.mu.Unlock()
-
+
id, _ := config["checkpoint_id"].(string)
m.checkpoints[id] = checkpoint
return nil
}
-func (m *MockCheckpointSaver) Get(ctx context.Context, config map[string]interface{}) (map[string]interface{}, error) {
+func (m *MockCheckpointSaver) Get(ctx context.Context, config map[string]any) (map[string]any, error) {
m.mu.RLock()
defer m.mu.RUnlock()
-
+
id, _ := config["checkpoint_id"].(string)
cp, exists := m.checkpoints[id]
if !exists {
@@ -415,18 +415,18 @@ func (m *MockCheckpointSaver) Get(ctx context.Context, config map[string]interfa
return cp, nil
}
-func (m *MockCheckpointSaver) List(ctx context.Context, config map[string]interface{}, limit int) ([]map[string]interface{}, error) {
+func (m *MockCheckpointSaver) List(ctx context.Context, config map[string]any, limit int) ([]map[string]any, error) {
return nil, nil
}
-func (m *MockCheckpointSaver) PutWrites(ctx context.Context, config map[string]interface{}, writes []*checkpoint.PendingWrite) error {
+func (m *MockCheckpointSaver) PutWrites(ctx context.Context, config map[string]any, writes []*checkpoint.PendingWrite) error {
return nil
}
-func (m *MockCheckpointSaver) GetTuple(ctx context.Context, config map[string]interface{}) (*checkpoint.CheckpointTuple, error) {
+func (m *MockCheckpointSaver) GetTuple(ctx context.Context, config map[string]any) (*checkpoint.CheckpointTuple, error) {
m.mu.RLock()
defer m.mu.RUnlock()
-
+
id, _ := config["checkpoint_id"].(string)
tuple, exists := m.tuples[id]
if !exists {
@@ -448,8 +448,8 @@ type MockNode struct {
name string
}
-func (n *MockNode) Invoke(ctx context.Context, input interface{}) (interface{}, error) {
- return map[string]interface{}{
+func (n *MockNode) Invoke(ctx context.Context, input any) (any, error) {
+ return map[string]any{
"output": n.name + "_result",
}, nil
}
@@ -457,7 +457,7 @@ func (n *MockNode) Invoke(ctx context.Context, input interface{}) (interface{},
// MockGraph is a mock implementation of a graph for testing.
type MockGraph struct{}
-func (g *MockGraph) AddNode(name string, node interface{}) {
+func (g *MockGraph) AddNode(name string, node any) {
// Mock implementation
}
diff --git a/internal/harness/graph/pregel/write.go b/internal/harness/graph/pregel/write.go
index 6ab484585c..cb278b5ca7 100644
--- a/internal/harness/graph/pregel/write.go
+++ b/internal/harness/graph/pregel/write.go
@@ -12,20 +12,20 @@ import (
// ChannelWrite represents a write operation to channels.
// It encapsulates the logic for writing state updates to multiple channels.
type ChannelWrite struct {
- registry *channels.Registry
- entries []*ChannelWriteEntry
+ registry *channels.Registry
+ entries []*ChannelWriteEntry
transformer WriteTransformer
- validator WriteValidator
- mu sync.RWMutex
+ validator WriteValidator
+ mu sync.RWMutex
}
// ChannelWriteEntry represents a single write operation.
type ChannelWriteEntry struct {
Channel string
- Value interface{}
+ Value any
Overwrite bool
Node string
- Metadata map[string]interface{}
+ Metadata map[string]any
}
// WriteTransformer transforms write values before applying them.
@@ -41,10 +41,10 @@ type WriteValidator interface {
// NewChannelWrite creates a new channel write operation.
func NewChannelWrite(registry *channels.Registry, opts ...ChannelWriteOption) *ChannelWrite {
cw := &ChannelWrite{
- registry: registry,
- entries: make([]*ChannelWriteEntry, 0),
+ registry: registry,
+ entries: make([]*ChannelWriteEntry, 0),
transformer: &IdentityWriteTransformer{},
- validator: &NoOpValidator{},
+ validator: &NoOpValidator{},
}
for _, opt := range opts {
@@ -86,7 +86,7 @@ func (cw *ChannelWrite) AddEntries(entries ...*ChannelWriteEntry) {
}
// WriteTo adds a simple write to a channel.
-func (cw *ChannelWrite) WriteTo(channel string, value interface{}) {
+func (cw *ChannelWrite) WriteTo(channel string, value any) {
cw.AddEntry(&ChannelWriteEntry{
Channel: channel,
Value: value,
@@ -95,7 +95,7 @@ func (cw *ChannelWrite) WriteTo(channel string, value interface{}) {
}
// Overwrite overwrites a channel with a value.
-func (cw *ChannelWrite) Overwrite(channel string, value interface{}) {
+func (cw *ChannelWrite) Overwrite(channel string, value any) {
cw.AddEntry(&ChannelWriteEntry{
Channel: channel,
Value: value,
@@ -104,7 +104,7 @@ func (cw *ChannelWrite) Overwrite(channel string, value interface{}) {
}
// WriteNode writes from a specific node.
-func (cw *ChannelWrite) WriteNode(node string, channel string, value interface{}) {
+func (cw *ChannelWrite) WriteNode(node string, channel string, value any) {
cw.AddEntry(&ChannelWriteEntry{
Channel: channel,
Value: value,
@@ -146,7 +146,7 @@ func (cw *ChannelWrite) Write(ctx context.Context) (map[string]bool, error) {
value = &types.Overwrite{Value: value}
}
- wasUpdated, err := ch.Update([]interface{}{value})
+ wasUpdated, err := ch.Update([]any{value})
if err != nil {
return nil, fmt.Errorf("failed to update channel %s: %w", transformed.Channel, err)
}
@@ -234,18 +234,18 @@ func (t *PrefixWriteTransformer) Transform(entry *ChannelWriteEntry) (*ChannelWr
// MetadataWriteTransformer adds metadata to entries.
type MetadataWriteTransformer struct {
- metadata map[string]interface{}
+ metadata map[string]any
}
// NewMetadataWriteTransformer creates a transformer that adds metadata.
-func NewMetadataWriteTransformer(metadata map[string]interface{}) *MetadataWriteTransformer {
+func NewMetadataWriteTransformer(metadata map[string]any) *MetadataWriteTransformer {
return &MetadataWriteTransformer{metadata: metadata}
}
func (t *MetadataWriteTransformer) Transform(entry *ChannelWriteEntry) (*ChannelWriteEntry, error) {
transformed := *entry
if transformed.Metadata == nil {
- transformed.Metadata = make(map[string]interface{})
+ transformed.Metadata = make(map[string]any)
}
for k, v := range t.metadata {
transformed.Metadata[k] = v
@@ -300,11 +300,11 @@ func (v *NoOpValidator) Validate(entry *ChannelWriteEntry) error {
// TypeWriteValidator validates value types.
type TypeWriteValidator struct {
- types map[string]interface{}
+ types map[string]any
}
// NewTypeWriteValidator creates a validator for value types.
-func NewTypeWriteValidator(types map[string]interface{}) *TypeWriteValidator {
+func NewTypeWriteValidator(types map[string]any) *TypeWriteValidator {
return &TypeWriteValidator{types: types}
}
@@ -364,11 +364,11 @@ func (v *LengthWriteValidator) Validate(entry *ChannelWriteEntry) error {
var length int
switch val := entry.Value.(type) {
- case []interface{}:
+ case []any:
length = len(val)
case string:
length = len(val)
- case map[string]interface{}:
+ case map[string]any:
length = len(val)
default:
return nil
@@ -411,7 +411,7 @@ func (b *WriteBatch) Add(entry *ChannelWriteEntry) {
}
// WriteTo adds a simple write to the batch.
-func (b *WriteBatch) WriteTo(channel string, value interface{}) {
+func (b *WriteBatch) WriteTo(channel string, value any) {
b.Add(&ChannelWriteEntry{
Channel: channel,
Value: value,
@@ -420,7 +420,7 @@ func (b *WriteBatch) WriteTo(channel string, value interface{}) {
}
// Overwrite adds an overwrite to the batch.
-func (b *WriteBatch) Overwrite(channel string, value interface{}) {
+func (b *WriteBatch) Overwrite(channel string, value any) {
b.Add(&ChannelWriteEntry{
Channel: channel,
Value: value,
diff --git a/internal/harness/graph/pregel/write_test.go b/internal/harness/graph/pregel/write_test.go
index e379bb1813..2a9fede8d8 100644
--- a/internal/harness/graph/pregel/write_test.go
+++ b/internal/harness/graph/pregel/write_test.go
@@ -155,7 +155,7 @@ func TestPrefixWriteTransformer(t *testing.T) {
}
func TestMetadataWriteTransformer(t *testing.T) {
- tf := NewMetadataWriteTransformer(map[string]interface{}{"ctx": "test"})
+ tf := NewMetadataWriteTransformer(map[string]any{"ctx": "test"})
entry := &ChannelWriteEntry{Channel: "c", Value: "v"}
result, err := tf.Transform(entry)
if err != nil {
diff --git a/internal/harness/graph/runnable/inject.go b/internal/harness/graph/runnable/inject.go
index c55a2089ef..b42ae5bf93 100644
--- a/internal/harness/graph/runnable/inject.go
+++ b/internal/harness/graph/runnable/inject.go
@@ -76,11 +76,11 @@ type Injectable interface {
// InjectableRunnable is a Runnable that supports dependency injection.
type InjectableRunnable struct {
- name string
- fn interface{}
- injectionCtx *InjectionContext
- paramInjector *ParamInjector
- schema *RunnableSchema
+ name string
+ fn interface{}
+ injectionCtx *InjectionContext
+ paramInjector *ParamInjector
+ schema *RunnableSchema
}
// NewInjectableRunnable creates a new runnable with dependency injection support.
@@ -389,8 +389,8 @@ func (t *Tracer) Clear() {
// - Functions: wrapped with NewInjectableRunnable
// - Runnable: wrapped to support injection
// - InjectableRunnable: returned as-is
-func CoerceToInjectableRunnable(v interface{}, name string) (*InjectableRunnable, error) {
- switch r := v.(type) {
+func CoerceToInjectableRunnable(target interface{}, name string) (*InjectableRunnable, error) {
+ switch r := target.(type) {
case *InjectableRunnable:
return r, nil
case Runnable[any, any]:
@@ -400,10 +400,14 @@ func CoerceToInjectableRunnable(v interface{}, name string) (*InjectableRunnable
}), nil
default:
// Check if it's a function
- if reflect.TypeOf(v).Kind() == reflect.Func {
- return NewInjectableRunnable(name, v), nil
+ targetType := reflect.TypeOf(target)
+ if targetType == nil {
+ return nil, fmt.Errorf("cannot coerce nil to InjectableRunnable")
}
- return nil, fmt.Errorf("cannot coerce %T to InjectableRunnable", v)
+ if targetType.Kind() == reflect.Func {
+ return NewInjectableRunnable(name, target), nil
+ }
+ return nil, fmt.Errorf("cannot coerce %T to InjectableRunnable", target)
}
}
diff --git a/internal/harness/graph/runnable/runnable.go b/internal/harness/graph/runnable/runnable.go
index e3c1a6ae34..d72f00686c 100644
--- a/internal/harness/graph/runnable/runnable.go
+++ b/internal/harness/graph/runnable/runnable.go
@@ -24,9 +24,9 @@ type Runnable[Input, Output any] interface {
// RunnableSchema describes the schema of a runnable.
type RunnableSchema struct {
- InputType string
- OutputType string
- Name string
+ InputType string
+ OutputType string
+ Name string
Description string
}
@@ -240,9 +240,9 @@ func NewRunnableParallel(runnables map[string]Runnable[any, any]) *RunnableParal
// Invoke executes all runnables in parallel with the same input.
func (p *RunnableParallel) Invoke(ctx context.Context, input interface{}) (interface{}, error) {
type result struct {
- name string
- value interface{}
- err error
+ name string
+ value interface{}
+ err error
}
resultCh := make(chan result, len(p.runnables))
@@ -395,12 +395,12 @@ func CoerceToRunnable(value interface{}) (Runnable[any, any], error) {
Message: "cannot coerce nil to Runnable",
}
}
-
+
if valType.Kind() == reflect.Func {
// Try to wrap it as a RunnableFunc
return coerceFuncToRunnable(value, valType)
}
-
+
return nil, &RunnableError{
Message: fmt.Sprintf("cannot coerce %T to Runnable", value),
}
@@ -412,31 +412,31 @@ func coerceFuncToRunnable(fn interface{}, fnType reflect.Type) (Runnable[any, an
// Check function signature
numIn := fnType.NumIn()
numOut := fnType.NumOut()
-
+
// Supported signatures:
// 1. func(context.Context, T) (U, error)
// 2. func(T) U
// 3. func(T) (U, error)
// 4. func() U
// 5. func() (U, error)
-
+
// We'll create a wrapper that adapts the function to Runnable[any, any]
wrapper := func(ctx context.Context, input interface{}) (interface{}, error) {
// Prepare arguments
args := make([]reflect.Value, 0, numIn)
-
+
argIndex := 0
// Check if first argument is context.Context
if numIn > 0 && fnType.In(0).AssignableTo(reflect.TypeOf((*context.Context)(nil)).Elem()) {
args = append(args, reflect.ValueOf(ctx))
argIndex++
}
-
+
// Add input argument if needed
if argIndex < numIn {
inputVal := reflect.ValueOf(input)
paramType := fnType.In(argIndex)
-
+
// Try to convert input to expected type
if input != nil && inputVal.Type().AssignableTo(paramType) {
args = append(args, inputVal)
@@ -448,15 +448,15 @@ func coerceFuncToRunnable(fn interface{}, fnType reflect.Type) (Runnable[any, an
}
argIndex++
}
-
+
// Fill remaining parameters with zero values
for ; argIndex < numIn; argIndex++ {
args = append(args, reflect.Zero(fnType.In(argIndex)))
}
-
+
// Call function
results := reflect.ValueOf(fn).Call(args)
-
+
// Process results
if numOut == 0 {
return nil, nil
@@ -480,12 +480,12 @@ func coerceFuncToRunnable(fn interface{}, fnType reflect.Type) (Runnable[any, an
}
return result, nil
}
-
+
return nil, &RunnableError{
Message: fmt.Sprintf("unsupported number of return values: %d", numOut),
}
}
-
+
return NewRunnableFunc(wrapper), nil
}
diff --git a/internal/harness/graph/store/base.go b/internal/harness/graph/store/base.go
index 4cd66572f3..1a377ac846 100644
--- a/internal/harness/graph/store/base.go
+++ b/internal/harness/graph/store/base.go
@@ -111,9 +111,9 @@ type MatchCondition struct {
// TTLConfig configures TTL behavior.
type TTLConfig struct {
- RefreshOnRead bool
- DefaultTTL *time.Duration
- SweepInterval *time.Duration
+ RefreshOnRead bool
+ DefaultTTL *time.Duration
+ SweepInterval *time.Duration
}
// IndexConfig configures semantic search indexing.
diff --git a/internal/harness/graph/store/memory.go b/internal/harness/graph/store/memory.go
index b8bd0d728d..25354abb75 100644
--- a/internal/harness/graph/store/memory.go
+++ b/internal/harness/graph/store/memory.go
@@ -13,12 +13,12 @@ import (
// InMemoryStore is an in-memory implementation of BaseStore.
// It is not thread-safe by default, use NewInMemoryStore() for a thread-safe version.
type InMemoryStore struct {
- mu sync.RWMutex
- data map[string]map[string]map[string]interface{}
- ttl map[string]time.Time
- indexes map[string]map[string][]float64 // namespaceKey -> key -> embedding vector
- indexConfigs map[string]IndexConfig // namespaceKey -> index config
- closed bool
+ mu sync.RWMutex
+ data map[string]map[string]map[string]interface{}
+ ttl map[string]time.Time
+ indexes map[string]map[string][]float64 // namespaceKey -> key -> embedding vector
+ indexConfigs map[string]IndexConfig // namespaceKey -> index config
+ closed bool
cleanupTicker *time.Ticker
stopCleanup chan struct{}
}
@@ -336,12 +336,12 @@ func (s *InMemoryStore) PutItem(ctx context.Context, namespace []string, key str
s.data[nsKey] = make(map[string]map[string]interface{})
}
s.data[nsKey][key] = s.copyValue(value)
-
+
if ttl != nil {
fullKey := s.fullKey(nsKey, key)
s.ttl[fullKey] = time.Now().Add(*ttl)
}
-
+
// Handle indexing
if index != nil {
switch idx := index.(type) {
@@ -473,7 +473,7 @@ func (s *InMemoryStore) ListNamespaces(ctx context.Context, conditions []MatchCo
}
}
}
-
+
// Apply conditions
filtered := make([][]string, 0)
for _, nsParts := range namespaceSet {
@@ -483,7 +483,7 @@ func (s *InMemoryStore) ListNamespaces(ctx context.Context, conditions []MatchCo
}
}
}
-
+
// Apply maxDepth
if maxDepth != nil {
filtered2 := make([][]string, 0)
@@ -494,15 +494,15 @@ func (s *InMemoryStore) ListNamespaces(ctx context.Context, conditions []MatchCo
}
filtered = filtered2
}
-
+
// Apply offset and limit
- if offset > 0 && offset < len(filtered) {
+ if offset > 0 {
filtered = filtered[offset:]
}
if limit > 0 && limit < len(filtered) {
filtered = filtered[:limit]
}
-
+
return filtered, nil
}
@@ -611,7 +611,7 @@ func (s *InMemoryStore) matchFilter(value map[string]interface{}, filter map[str
if !exists {
return false
}
-
+
// Handle nested operators
if condMap, ok := condition.(map[string]interface{}); ok {
for op, opValue := range condMap {
diff --git a/internal/harness/graph/task/decorator.go b/internal/harness/graph/task/decorator.go
index 8b8773c762..4ecb049131 100644
--- a/internal/harness/graph/task/decorator.go
+++ b/internal/harness/graph/task/decorator.go
@@ -232,16 +232,16 @@ func Task(fn types.NodeFunc, opts ...DecoratorOption) types.NodeFunc {
// Entrypoint marks a function as a graph entrypoint.
type Entrypoint struct {
- name string
- fn types.NodeFunc
- metadata map[string]interface{}
- checkpointer interface{}
- store interface{}
- configurable map[string]interface{}
- graph *graph.StateGraph
- compiledGraph *graph.CompiledGraph
- compileOnce sync.Once
- compileErr error
+ name string
+ fn types.NodeFunc
+ metadata map[string]interface{}
+ checkpointer interface{}
+ store interface{}
+ configurable map[string]interface{}
+ graph *graph.StateGraph
+ compiledGraph *graph.CompiledGraph
+ compileOnce sync.Once
+ compileErr error
}
// NewEntrypoint creates a new entrypoint.
@@ -450,7 +450,7 @@ func (e *Entrypoint) AStream(ctx context.Context, input interface{}, config *typ
// Batch invokes the graph with multiple inputs.
func (e *Entrypoint) Batch(ctx context.Context, inputs []interface{}, config *types.RunnableConfig) ([]interface{}, error) {
results := make([]interface{}, len(inputs))
-
+
for i, input := range inputs {
output, err := e.Invoke(ctx, input, config)
if err != nil {
@@ -458,7 +458,7 @@ func (e *Entrypoint) Batch(ctx context.Context, inputs []interface{}, config *ty
}
results[i] = output
}
-
+
return results, nil
}
@@ -554,8 +554,8 @@ func Final(value interface{}, save ...bool) *EntrypointFinal {
}
// IsFinal checks if a value is an EntrypointFinal.
-func IsFinal(v interface{}) (*EntrypointFinal, bool) {
- if f, ok := v.(*EntrypointFinal); ok {
+func IsFinal(val any) (*EntrypointFinal, bool) {
+ if f, ok := val.(*EntrypointFinal); ok {
return f, true
}
return nil, false
diff --git a/internal/harness/graph/types/config.go b/internal/harness/graph/types/config.go
index 61088e5ebf..d23f8bc7e6 100644
--- a/internal/harness/graph/types/config.go
+++ b/internal/harness/graph/types/config.go
@@ -6,22 +6,22 @@ import "ragflow/internal/harness/graph/constants"
type RunnableConfig struct {
// Configurable values that can be used by nodes and checkpointers
Configurable map[string]interface{}
-
+
// RecursionLimit is the maximum number of steps before raising GraphRecursionError
RecursionLimit int
-
+
// Tags for the execution
Tags []string
-
+
// Metadata for the execution
Metadata map[string]interface{}
-
+
// RunID is a unique identifier for this run
RunID string
-
+
// ThreadID is the thread identifier for checkpointing
ThreadID string
-
+
// Durability controls when checkpoint writes are persisted
Durability Durability
}
@@ -59,40 +59,40 @@ func (c *RunnableConfig) Merge(other *RunnableConfig) *RunnableConfig {
if other == nil {
return c
}
-
+
// Merge configurable
for k, v := range other.Configurable {
c.Set(k, v)
}
-
+
// Use other's recursion limit if set
if other.RecursionLimit > 0 {
c.RecursionLimit = other.RecursionLimit
}
-
+
// Merge tags
c.Tags = append(c.Tags, other.Tags...)
-
+
// Merge metadata
for k, v := range other.Metadata {
c.Metadata[k] = v
}
-
+
// Use other's RunID if set
if other.RunID != "" {
c.RunID = other.RunID
}
-
+
// Use other's ThreadID if set
if other.ThreadID != "" {
c.ThreadID = other.ThreadID
}
-
+
// Use other's Durability if set (not default)
if other.Durability != "" && other.Durability != DurabilitySync {
c.Durability = other.Durability
}
-
+
return c
}
@@ -160,13 +160,13 @@ func PatchConfig(config *RunnableConfig, patchers ...ConfigPatcher) *RunnableCon
if config == nil {
config = NewRunnableConfig()
}
-
+
for _, patcher := range patchers {
if patcher != nil {
config = patcher(config)
}
}
-
+
return config
}
@@ -181,10 +181,10 @@ func EnsureConfig(config *RunnableConfig) *RunnableConfig {
// MergeConfigs merges multiple configs into one.
func MergeConfigs(configs ...*RunnableConfig) *RunnableConfig {
result := NewRunnableConfig()
-
+
for _, config := range configs {
result.Merge(config)
}
-
+
return result
}
diff --git a/internal/harness/graph/types/scratchpad.go b/internal/harness/graph/types/scratchpad.go
index c074a49e27..a55da273fd 100644
--- a/internal/harness/graph/types/scratchpad.go
+++ b/internal/harness/graph/types/scratchpad.go
@@ -14,12 +14,12 @@ type PregelScratchpad struct {
metadata map[string]interface{}
createdAt time.Time
lastAccess time.Time
- step int64 // current step number
- stop bool // stop flag
- callCounter int64 // number of calls
- interruptCounter int64 // number of interrupts
- resume bool // resume flag
- subgraphCounter int64 // subgraph invocation count
+ step int64 // current step number
+ stop bool // stop flag
+ callCounter int64 // number of calls
+ interruptCounter int64 // number of interrupts
+ resume bool // resume flag
+ subgraphCounter int64 // subgraph invocation count
}
// NewPregelScratchpad creates a new scratchpad.
@@ -434,19 +434,19 @@ func (p *PregelScratchpad) Stats() ScratchpadStats {
defer p.mu.RUnlock()
return ScratchpadStats{
- DataSize: len(p.data),
+ DataSize: len(p.data),
CountersCount: len(p.counters),
- MetadataSize: len(p.metadata),
- CreatedAt: p.createdAt,
- LastAccess: p.lastAccess,
+ MetadataSize: len(p.metadata),
+ CreatedAt: p.createdAt,
+ LastAccess: p.lastAccess,
}
}
// ScratchpadStats represents statistics about a scratchpad.
type ScratchpadStats struct {
- DataSize int
- CountersCount int
- MetadataSize int
- CreatedAt time.Time
- LastAccess time.Time
+ DataSize int
+ CountersCount int
+ MetadataSize int
+ CreatedAt time.Time
+ LastAccess time.Time
}
diff --git a/internal/harness/graph/types/stream.go b/internal/harness/graph/types/stream.go
index 1202328073..976a11ced4 100644
--- a/internal/harness/graph/types/stream.go
+++ b/internal/harness/graph/types/stream.go
@@ -9,13 +9,13 @@ import (
// StreamChunk represents a single chunk of data from a stream.
type StreamChunk struct {
- Mode StreamMode
- Data interface{}
- Step int
- Node string
- Metadata map[string]interface{}
- Timestamp int64
- Index int
+ Mode StreamMode
+ Data interface{}
+ Step int
+ Node string
+ Metadata map[string]interface{}
+ Timestamp int64
+ Index int
}
// StreamProtocol defines the interface for streaming output from graph execution.
@@ -50,11 +50,11 @@ type StreamIterator interface {
// ChannelStream implements StreamProtocol using Go channels.
type ChannelStream struct {
- mode StreamMode
- ch chan *StreamChunk
- closed bool
- closer chan struct{}
- mu sync.RWMutex
+ mode StreamMode
+ ch chan *StreamChunk
+ closed bool
+ closer chan struct{}
+ mu sync.RWMutex
}
// NewChannelStream creates a new channel-based stream.
diff --git a/internal/harness/graph/types/types.go b/internal/harness/graph/types/types.go
index f9325fb6ae..0b34e06c83 100644
--- a/internal/harness/graph/types/types.go
+++ b/internal/harness/graph/types/types.go
@@ -156,9 +156,9 @@ func NewInterrupt(value interface{}, id string) *Interrupt {
// StateUpdate represents an update to the graph state.
type StateUpdate struct {
- Values map[string]interface{}
- AsNode string
- TaskID string
+ Values map[string]interface{}
+ AsNode string
+ TaskID string
}
// PregelTask represents a Pregel task.
@@ -184,18 +184,18 @@ type CacheKey struct {
// PregelExecutableTask represents an executable task in Pregel.
type PregelExecutableTask struct {
- Name string
- Input interface{}
- Proc interface{} // Runnable
- Writes [][2]interface{}
- Config map[string]interface{}
- Triggers []string
+ Name string
+ Input interface{}
+ Proc interface{} // Runnable
+ Writes [][2]interface{}
+ Config map[string]interface{}
+ Triggers []string
RetryPolicy []RetryPolicy
- CacheKey *CacheKey
- ID string
- Path []interface{}
- Writers []interface{}
- Subgraphs []interface{} // PregelProtocol
+ CacheKey *CacheKey
+ ID string
+ Path []interface{}
+ Writers []interface{}
+ Subgraphs []interface{} // PregelProtocol
}
// StateSnapshot is a snapshot of the state of the graph at the beginning of a step.
@@ -290,7 +290,7 @@ func (c *Command) UpdateAsTuples() [][2]interface{} {
if c.Update == nil {
return nil
}
-
+
switch v := c.Update.(type) {
case map[string]interface{}:
result := make([][2]interface{}, 0, len(v))
diff --git a/internal/harness/harness.go b/internal/harness/harness.go
index 70f064c641..0443439a18 100644
--- a/internal/harness/harness.go
+++ b/internal/harness/harness.go
@@ -64,34 +64,34 @@ import (
"ragflow/internal/harness/graph/errors"
"ragflow/internal/harness/graph/graph"
"ragflow/internal/harness/graph/interrupt"
- "ragflow/internal/harness/prebuilt"
"ragflow/internal/harness/graph/pregel"
"ragflow/internal/harness/graph/types"
+ "ragflow/internal/harness/prebuilt"
)
// Re-export main types for convenience.
type (
// StateGraph is a graph whose nodes communicate by reading and writing to a shared state.
StateGraph = graph.StateGraph
-
+
// CompiledGraph is a compiled, executable graph.
CompiledGraph = graph.CompiledGraph
-
+
// Node represents a node in the graph.
Node = graph.Node
-
+
// Edge represents an edge in the graph.
Edge = graph.Edge
-
+
// Send represents a dynamic node invocation.
Send = graph.Send
-
+
// Checkpointer is the interface for checkpoint savers.
Checkpointer = graph.Checkpointer
-
+
// MemorySaver is an in-memory checkpoint saver.
MemorySaver = checkpoint.MemorySaver
-
+
// NATSSaver is a NATS JetStream-based checkpoint saver.
NATSSaver = checkpoint.NATSSaver
// NATSConfig holds configuration for the NATS checkpoint saver.
@@ -99,52 +99,52 @@ type (
// Channel is the base interface for all channels.
Channel = channels.Channel
-
+
// BaseChannel provides a base implementation of Channel.
BaseChannel = channels.BaseChannel
-
+
// LastValue stores the last value received.
LastValue = channels.LastValue
-
+
// Topic is a configurable PubSub Topic.
Topic = channels.Topic
-
+
// BinaryOperatorAggregate stores the result of applying a binary operator.
BinaryOperatorAggregate = channels.BinaryOperatorAggregate
-
+
// BinaryOperator is a function that combines two values into one.
BinaryOperator = channels.BinaryOperator
-
+
// EphemeralValue stores a value that is cleared after being read once.
EphemeralValue = channels.EphemeralValue
-
+
// NamedBarrierValue waits until all named nodes have written a value.
NamedBarrierValue = channels.NamedBarrierValue
-
+
// NamedBarrierValueAfterFinish waits for all named nodes, available only after finish.
NamedBarrierValueAfterFinish = channels.NamedBarrierValueAfterFinish
-
+
// LastValueAfterFinish stores last value, available only after finish.
LastValueAfterFinish = channels.LastValueAfterFinish
-
+
// UntrackedValue stores a value but does not track it for checkpointing.
UntrackedValue = channels.UntrackedValue
-
+
// AnyValue stores any value received.
AnyValue = channels.AnyValue
-
+
// RunnableConfig is the configuration for a runnable.
RunnableConfig = types.RunnableConfig
-
+
// StreamMode defines how the stream method should emit outputs.
StreamMode = types.StreamMode
-
+
// RetryPolicy configures retrying nodes.
RetryPolicy = types.RetryPolicy
-
+
// CachePolicy configures caching nodes.
CachePolicy = types.CachePolicy
-
+
// Command is used to update the graph's state and send messages to nodes.
Command = types.Command
@@ -246,8 +246,8 @@ var (
WithCancel = core.WithCancel
// Run option constructors
- WithSessionValues = core.WithSessionValues
- WithCheckPointID = core.WithCheckPointID
+ WithSessionValues = core.WithSessionValues
+ WithCheckPointID = core.WithCheckPointID
WithSkipTransferMessages = core.WithSkipTransferMessages
WithCallbacks = core.WithCallbacks
WithAgentNames = core.WithAgentNames
@@ -269,15 +269,14 @@ var (
DeleteRunLocalValue = core.DeleteRunLocalValue
// Transfer and middleware
- AgentWithOptions = core.AgentWithOptions
+ AgentWithOptions = core.AgentWithOptions
AgentWithDeterministicTransfer = core.AgentWithDeterministicTransfer
- SetLanguage = core.SetLanguage
+ SetLanguage = core.SetLanguage
// Errors
ErrCancelTimeout = core.ErrCancelTimeout
ErrExecutionEnded = core.ErrExecutionEnded
ErrStreamCanceled = core.ErrStreamCanceled
-
)
// Prebuilt component functions.
@@ -298,13 +297,13 @@ var (
const (
// Start is the first (virtual) node in the graph.
Start = constants.Start
-
+
// End is the last (virtual) node in the graph.
End = constants.End
-
+
// TagNoStream is a tag to disable streaming.
TagNoStream = constants.TagNoStream
-
+
// TagHidden is a tag to hide a node/edge from tracing.
TagHidden = constants.TagHidden
)
@@ -322,15 +321,15 @@ const (
// Re-export error types.
type (
- GraphRecursionError = errors.GraphRecursionError
- InvalidUpdateError = errors.InvalidUpdateError
- GraphInterrupt = errors.GraphInterrupt
- EmptyChannelError = errors.EmptyChannelError
- EmptyInputError = errors.EmptyInputError
- NodeNotFoundError = errors.NodeNotFoundError
- InvalidNodeError = errors.InvalidNodeError
- InvalidEdgeError = errors.InvalidEdgeError
- ChannelNotFoundError = errors.ChannelNotFoundError
+ GraphRecursionError = errors.GraphRecursionError
+ InvalidUpdateError = errors.InvalidUpdateError
+ GraphInterrupt = errors.GraphInterrupt
+ EmptyChannelError = errors.EmptyChannelError
+ EmptyInputError = errors.EmptyInputError
+ NodeNotFoundError = errors.NodeNotFoundError
+ InvalidNodeError = errors.InvalidNodeError
+ InvalidEdgeError = errors.InvalidEdgeError
+ ChannelNotFoundError = errors.ChannelNotFoundError
)
// NewStateGraph creates a new StateGraph with the given state schema.
@@ -347,25 +346,52 @@ func NewMemorySaver() *MemorySaver {
var (
// WithCheckpointer sets the checkpointer for the compiled graph.
WithCheckpointer = graph.WithCheckpointer
-
+
// WithInterrupts sets the nodes that should trigger interrupts.
WithInterrupts = graph.WithInterrupts
-
+
+ // WithInterruptsAfter sets the nodes that should trigger interrupts AFTER execution.
+ WithInterruptsAfter = graph.WithInterruptsAfter
+
// WithRecursionLimit sets the recursion limit.
WithRecursionLimit = graph.WithRecursionLimit
-
+
// WithDebug enables debug mode.
WithDebug = graph.WithDebug
+
+ // WithNodeTriggerMode sets the node trigger mode (AnyPredecessor / AllPredecessor).
+ WithNodeTriggerMode = graph.WithNodeTriggerMode
)
+// Loop / Parallel option constructors.
+var (
+ // WithLoopMaxIterations sets the maximum number of iterations for a Loop node.
+ WithLoopMaxIterations = graph.WithLoopMaxIterations
+ // WithLoopCheckpointIDPrefix sets a stable checkpoint prefix for loop iterations.
+ WithLoopCheckpointIDPrefix = graph.WithLoopCheckpointIDPrefix
+ // WithParallelMaxConcurrency sets the maximum concurrency for a Parallel node.
+ WithParallelMaxConcurrency = graph.WithParallelMaxConcurrency
+)
+
+// Loop / Parallel node constructor functions.
+var (
+ // NewLoopNodeFunc creates a NodeFunc that repeatedly executes a sub-graph.
+ NewLoopNodeFunc = graph.NewLoopNodeFunc
+ // NewParallelNodeFunc creates a NodeFunc that fans out items to a sub-graph.
+ NewParallelNodeFunc = graph.NewParallelNodeFunc
+)
+
+// LoopCondition is the per-iteration exit predicate for loop nodes.
+type LoopCondition = graph.LoopCondition
+
// Interrupt functions.
var (
// InterruptFunc interrupts the graph with a resumable exception.
InterruptFunc = interrupt.Interrupt
-
+
// IsInterrupt checks if an error is a GraphInterrupt.
IsInterrupt = interrupt.IsInterrupt
-
+
// GetInterruptValue extracts the interrupt value from a GraphInterrupt error.
GetInterruptValue = interrupt.GetInterruptValue
)
@@ -374,28 +400,28 @@ var (
var (
// NewLastValue creates a new LastValue channel.
NewLastValue = channels.NewLastValue
-
+
// NewTopic creates a new Topic channel.
NewTopic = channels.NewTopic
-
+
// NewBinaryOperatorAggregate creates a new BinaryOperatorAggregate channel.
NewBinaryOperatorAggregate = channels.NewBinaryOperatorAggregate
-
+
// NewEphemeralValue creates a new EphemeralValue channel.
NewEphemeralValue = channels.NewEphemeralValue
-
+
// NewNamedBarrierValue creates a new NamedBarrierValue channel.
NewNamedBarrierValue = channels.NewNamedBarrierValue
-
+
// NewNamedBarrierValueAfterFinish creates a new NamedBarrierValueAfterFinish channel.
NewNamedBarrierValueAfterFinish = channels.NewNamedBarrierValueAfterFinish
-
+
// NewLastValueAfterFinish creates a new LastValueAfterFinish channel.
NewLastValueAfterFinish = channels.NewLastValueAfterFinish
-
+
// NewUntrackedValue creates a new UntrackedValue channel.
NewUntrackedValue = channels.NewUntrackedValue
-
+
// NewAnyValue creates a new AnyValue channel.
NewAnyValue = channels.NewAnyValue
)
@@ -404,10 +430,10 @@ var (
var (
// ListAppend appends two lists.
ListAppend = channels.ListAppend
-
+
// IntAdd adds two integers.
IntAdd = channels.IntAdd
-
+
// StringConcat concatenates two strings.
StringConcat = channels.StringConcat
)
@@ -455,10 +481,16 @@ func pregelRunCompiledGraph(
for k := range cg.GetInterrupts() {
interruptKeys = append(interruptKeys, k)
}
+ // Extract after-interrupt node names
+ interruptAfterKeys := make([]string, 0, len(cg.GetInterruptsAfter()))
+ for k := range cg.GetInterruptsAfter() {
+ interruptAfterKeys = append(interruptAfterKeys, k)
+ }
engine := pregel.NewEngine(cg.GetGraph(),
pregel.WithCheckpointer(cg.GetCheckpointer()),
pregel.WithInterrupts(interruptKeys...),
+ pregel.WithInterruptsAfter(interruptAfterKeys...),
pregel.WithRecursionLimit(cg.GetRecursionLimit()),
pregel.WithDebug(cg.IsDebug()),
pregel.WithConfig(config),
diff --git a/internal/harness/prebuilt/prebuilt.go b/internal/harness/prebuilt/prebuilt.go
index 7a7b817cba..728a02a0c4 100644
--- a/internal/harness/prebuilt/prebuilt.go
+++ b/internal/harness/prebuilt/prebuilt.go
@@ -280,4 +280,4 @@ func executeTool(ctx context.Context, action string, input map[string]interface{
}
}
return nil, fmt.Errorf("tool not found: %s", action)
-}
\ No newline at end of file
+}
diff --git a/internal/harness/prebuilt/prebuilt_edge_test.go b/internal/harness/prebuilt/prebuilt_edge_test.go
index aee95af2af..0296371cfe 100644
--- a/internal/harness/prebuilt/prebuilt_edge_test.go
+++ b/internal/harness/prebuilt/prebuilt_edge_test.go
@@ -152,8 +152,8 @@ func TestPrebuiltAgent_MaxIterations(t *testing.T) {
return "result", nil
}},
},
- Model: mock,
- SystemPrompt: "test",
+ Model: mock,
+ SystemPrompt: "test",
MaxIterations: 3,
}
diff --git a/internal/harness/prebuilt/prebuilt_test.go b/internal/harness/prebuilt/prebuilt_test.go
index 186da018ab..cf859ca9e3 100644
--- a/internal/harness/prebuilt/prebuilt_test.go
+++ b/internal/harness/prebuilt/prebuilt_test.go
@@ -10,13 +10,13 @@ import (
func TestToolNode(t *testing.T) {
ctx := context.Background()
-
+
tool := Tool{
Name: "test_tool",
Description: "A test tool",
Function: func(ctx context.Context, input map[string]interface{}) (interface{}, error) {
return map[string]interface{}{
- "result": input["value"],
+ "result": input["value"],
"processed": true,
}, nil
},
@@ -24,14 +24,14 @@ func TestToolNode(t *testing.T) {
"type": "object",
},
}
-
+
node := ToolNode(tool)
-
+
input := map[string]interface{}{
"value": "test",
"extra": "data",
}
-
+
output, err := node.Invoke(ctx, input)
if err != nil {
t.Fatalf("ToolNode failed: %v", err)
@@ -48,7 +48,7 @@ func TestToolNode(t *testing.T) {
func TestValidationNode(t *testing.T) {
ctx := context.Background()
-
+
validationNode := ValidationNode(
func(input map[string]interface{}) error {
if input["required"] == nil {
@@ -58,7 +58,7 @@ func TestValidationNode(t *testing.T) {
},
"validation failed",
)
-
+
// Test valid input
validInput := map[string]interface{}{
"required": "present",
@@ -83,7 +83,7 @@ func TestValidationNode(t *testing.T) {
func TestTransformNode(t *testing.T) {
ctx := context.Background()
-
+
transformNode := TransformNode(
func(input map[string]interface{}) (map[string]interface{}, error) {
transformed := make(map[string]interface{})
@@ -93,12 +93,12 @@ func TestTransformNode(t *testing.T) {
return transformed, nil
},
)
-
+
input := map[string]interface{}{
"key1": "value1",
"key2": 123,
}
-
+
output, err := transformNode.Invoke(ctx, input)
if err != nil {
t.Fatalf("TransformNode failed: %v", err)
@@ -111,7 +111,7 @@ func TestTransformNode(t *testing.T) {
func TestConditionalNode(t *testing.T) {
ctx := context.Background()
-
+
// Create branch runnables
branchA := runnable.NewRunnableFunc(
func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
@@ -122,7 +122,7 @@ func TestConditionalNode(t *testing.T) {
},
runnable.WithName[map[string]interface{}, map[string]interface{}]("branch_a"),
)
-
+
branchB := runnable.NewRunnableFunc(
func(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error) {
return map[string]interface{}{
@@ -132,7 +132,7 @@ func TestConditionalNode(t *testing.T) {
},
runnable.WithName[map[string]interface{}, map[string]interface{}]("branch_b"),
)
-
+
conditionalNode := ConditionalNode(
func(input map[string]interface{}) string {
if input["route"] == "a" {
@@ -146,13 +146,13 @@ func TestConditionalNode(t *testing.T) {
},
"B", // default branch
)
-
+
// Test branch A
inputA := map[string]interface{}{
"route": "a",
"data": "test",
}
-
+
outputA, err := conditionalNode.Invoke(ctx, inputA)
if err != nil {
t.Fatalf("ConditionalNode failed for branch A: %v", err)
@@ -161,13 +161,13 @@ func TestConditionalNode(t *testing.T) {
if outputA["branch"] != "A" {
t.Errorf("Expected branch A, got %v", outputA["branch"])
}
-
+
// Test branch B
inputB := map[string]interface{}{
"route": "b",
"data": "test",
}
-
+
outputB, err := conditionalNode.Invoke(ctx, inputB)
if err != nil {
t.Fatalf("ConditionalNode failed for branch B: %v", err)
@@ -185,7 +185,7 @@ func TestNewReactAgent(t *testing.T) {
}
ctx := context.Background()
-
+
// Create mock tools
tools := []Tool{
{
@@ -199,7 +199,7 @@ func TestNewReactAgent(t *testing.T) {
},
},
}
-
+
// Create mock LLM
mockLLM := &mockLLM{
responses: []string{
@@ -207,20 +207,20 @@ func TestNewReactAgent(t *testing.T) {
"ANSWER: The answer is 42",
},
}
-
+
config := ReactAgentConfig{
- Tools: tools,
- Model: mockLLM,
- SystemPrompt: "You are a helpful assistant",
- MaxIterations: 3,
- StopCondition: nil,
+ Tools: tools,
+ Model: mockLLM,
+ SystemPrompt: "You are a helpful assistant",
+ MaxIterations: 3,
+ StopCondition: nil,
}
-
+
agent, err := NewReactAgent(config)
if err != nil {
t.Fatalf("Failed to create ReactAgent: %v", err)
}
-
+
input := map[string]interface{}{
"input": "What is the meaning of life?",
}
@@ -261,4 +261,4 @@ func (m *mockLLM) GenerateStream(ctx context.Context, messages []map[string]inte
ch <- response
close(ch)
return ch, nil
-}
\ No newline at end of file
+}