build: 内置 norma 模块,构建不再依赖上游仓库

把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到
third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或
改写 tag 都不再影响本仓库构建。

- 已验证 GOPROXY=off 下可完整编译并打出发行包
- go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希)
- 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
wangdefa committed 2026-10-20 21:10:41 -07:00
1 parent a819fa3230
commit f782b612ec
213 files changed
+37401 -2

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
package harness
import (
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/tool"
)
// The global post-tool net caps an oversized text block regardless of the tool.
func TestCapOutputCapsOversizedTextBlock(t *testing.T) {
tc := &tool.ToolContext{MaxOutputChars: 100} // no OutputDir → head+tail truncation
long := strings.Repeat("z", 5000)
res := tool.Result{Content: []llm.ContentBlock{llm.TextBlock(long)}}
out := capOutput(tc, res)
got := out.Content[0].Text
if len(got) >= 5000 || !strings.Contains(got, "characters truncated]") {
t.Fatalf("capOutput did not cap oversized block: len=%d", len(got))
}
}
// Output already within budget is passed through untouched.
func TestCapOutputLeavesSmallOutputIntact(t *testing.T) {
tc := &tool.ToolContext{MaxOutputChars: 100}
res := tool.Result{Content: []llm.ContentBlock{llm.TextBlock("fine")}}
if out := capOutput(tc, res); out.Content[0].Text != "fine" {
t.Fatalf("small output changed: %q", out.Content[0].Text)
}
}
// Output a tool already captured (carries the spill marker) is not re-processed,
// so the net never double-truncates.
func TestCapOutputIdempotentOnAlreadyCaptured(t *testing.T) {
tc := &tool.ToolContext{MaxOutputChars: 100}
pre := strings.Repeat("a", 100) + "\n\n... <persisted-output>[Output too large: full 9999 bytes ... saved to x.txt </persisted-output>"
res := tool.Result{Content: []llm.ContentBlock{llm.TextBlock(pre)}}
if out := capOutput(tc, res); out.Content[0].Text != pre {
t.Fatalf("capOutput re-processed already-captured output")
}
}
@@ -0,0 +1,72 @@
package harness
import (
"context"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// recordingCompactor captures the lastInputTokens the loop passes to each Pre.
type recordingCompactor struct{ seen []int }
func (c *recordingCompactor) Pre(_ context.Context, msgs []llm.Message, last int) []llm.Message {
c.seen = append(c.seen, last)
return msgs
}
func (c *recordingCompactor) Reactive(_ context.Context, msgs []llm.Message) ([]llm.Message, bool) {
return msgs, false
}
func (c *recordingCompactor) IsOverflow(error) bool { return false }
func usageToolTurn(id, name, input string, in, out int) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: in}},
{Type: llm.SEToolUseStart, ToolID: id, ToolName: name},
{Type: llm.SEToolInputJSON, Text: input},
{Type: llm.SEMessageDelta, StopReason: "tool_use", Usage: llm.Usage{OutputTokens: out}},
{Type: llm.SEMessageStop},
}
}
func usageTextTurn(s string, in, out int) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEMessageStart, Usage: llm.Usage{InputTokens: in}},
{Type: llm.SETextDelta, Text: s},
{Type: llm.SEMessageDelta, StopReason: "end_turn", Usage: llm.Usage{OutputTokens: out}},
{Type: llm.SEMessageStop},
}
}
// The loop must pass the previous response's total token size to the compactor's
// Pre: 0 on the first turn (no prior response), then input+output of the turn
// that just completed.
func TestCompactorReceivesLastInputTokens(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
usageToolTurn("c1", "Bash", `{"command":"echo hi"}`, 100, 20),
usageTextTurn("done", 500, 30),
}}
rc := &recordingCompactor{}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
Compactor: rc,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted {
t.Fatalf("reason=%v", term.Reason)
}
if len(rc.seen) != 2 {
t.Fatalf("want 2 Pre calls, got %d: %v", len(rc.seen), rc.seen)
}
if rc.seen[0] != 0 {
t.Fatalf("first Pre should see 0 (no prior response), got %d", rc.seen[0])
}
if rc.seen[1] != 120 {
t.Fatalf("second Pre should see turn-1 tokens (100+20), got %d", rc.seen[1])
}
}
+105
View File
@@ -0,0 +1,105 @@
package harness
import (
"context"
"testing"
"github.com/Autumn-27/norma/llm"
)
// noopCompactor implements Compactor but NOT ContextView: the loop must fall
// back to llm.MessagesForAPI, i.e. behaviour is unchanged.
type noopCompactor struct{}
func (noopCompactor) Pre(_ context.Context, msgs []llm.Message, _ int) []llm.Message { return msgs }
func (noopCompactor) Reactive(_ context.Context, msgs []llm.Message) ([]llm.Message, bool) {
return msgs, false
}
func (noopCompactor) IsOverflow(error) bool { return false }
// viewCompactor implements both Compactor and ContextView. It records what it
// was handed and returns a projection, so the test can assert that the loop
// uses the returned slice and never writes it back.
type viewCompactor struct {
noopCompactor
sawLen int
calls int
project func([]llm.Message) []llm.Message
}
func (v *viewCompactor) View(_ context.Context, msgs []llm.Message) []llm.Message {
v.calls++
v.sawLen = len(msgs)
return v.project(msgs)
}
func TestRequestMessagesFallsBackWithoutContextView(t *testing.T) {
msgs := []llm.Message{
llm.UserText("a"),
llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto"}),
llm.UserText("b"),
}
l := &loop{ctx: context.Background(), messages: msgs, in: QueryInput{Compactor: noopCompactor{}}}
got := l.requestMessages()
want := llm.MessagesForAPI(msgs)
if len(got) != len(want) {
t.Fatalf("requestMessages() len = %d, want %d (MessagesForAPI fallback)", len(got), len(want))
}
for i := range got {
if got[i].Text() != want[i].Text() {
t.Fatalf("requestMessages()[%d] = %q, want %q", i, got[i].Text(), want[i].Text())
}
}
}
func TestRequestMessagesUsesContextView(t *testing.T) {
msgs := []llm.Message{llm.UserText("a"), llm.UserText("b"), llm.UserText("c")}
v := &viewCompactor{project: func(in []llm.Message) []llm.Message {
return []llm.Message{llm.UserText("projected")}
}}
l := &loop{ctx: context.Background(), messages: msgs, in: QueryInput{Compactor: v}}
got := l.requestMessages()
if v.calls != 1 {
t.Fatalf("View called %d times, want 1", v.calls)
}
if v.sawLen != 3 {
t.Fatalf("View saw %d messages, want the full history (3)", v.sawLen)
}
if len(got) != 1 || got[0].Text() != "projected" {
t.Fatalf("requestMessages() = %+v, want the View projection", got)
}
// The projection must not be written back: l.messages is the durable history
// and message identity (content hashing) depends on it staying byte-stable.
if len(l.messages) != 3 {
t.Fatalf("l.messages len = %d after View, want 3 (View must not write back)", len(l.messages))
}
}
// A ContextView bypasses the boundary slice entirely — it owns the projection.
func TestContextViewBypassesBoundarySlicing(t *testing.T) {
msgs := []llm.Message{
llm.UserText("pre-boundary"),
llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto"}),
llm.UserText("post-boundary"),
}
v := &viewCompactor{project: func(in []llm.Message) []llm.Message { return in }}
l := &loop{ctx: context.Background(), messages: msgs, in: QueryInput{Compactor: v}}
got := l.requestMessages()
if len(got) != 3 {
t.Fatalf("requestMessages() len = %d, want 3 — a ContextView receives the raw history, not the post-boundary slice", len(got))
}
if got[0].Text() != "pre-boundary" {
t.Fatalf("requestMessages()[0] = %q, want the pre-boundary message to be visible to View", got[0].Text())
}
}
func TestRequestMessagesWithNilCompactor(t *testing.T) {
msgs := []llm.Message{llm.UserText("a")}
l := &loop{ctx: context.Background(), messages: msgs, in: QueryInput{}}
if got := l.requestMessages(); len(got) != 1 || got[0].Text() != "a" {
t.Fatalf("requestMessages() with nil Compactor = %+v, want the MessagesForAPI fallback", got)
}
}
+73
View File
@@ -0,0 +1,73 @@
// Package harness implements the agent's core loop as a state machine:
// stream a completion, recover from max-output-tokens / prompt-too-long,
// surface text/thinking/tool events, execute tool calls through a streaming
// executor (FIFO + exclusive scheduling), gate the Stop transition with hooks
// and a token budget, and repeat. It is exposed as a range-over-func iterator
// of Events and threads context cancellation throughout.
package harness
import "github.com/Autumn-27/norma/llm"
// EventKind classifies a loop Event.
type EventKind string
const (
KindText EventKind = "text" // assistant text delta
KindThinking EventKind = "thinking" // reasoning delta
KindToolUse EventKind = "tool_use" // a tool is about to run
KindToolResult EventKind = "tool_result" // a tool finished
KindProgress EventKind = "progress" // mid-tool progress
KindUsage EventKind = "usage" // cumulative token usage so far (per model turn)
KindResult EventKind = "result" // terminal event (loop finished)
)
// Event is one item in the loop's output stream.
type Event struct {
Kind EventKind
Text string // KindText / KindThinking / KindProgress
ToolUse *llm.ContentBlock // KindToolUse
ToolResult *llm.ContentBlock // KindToolResult
Terminal *Terminal // KindResult
Usage *llm.Usage // KindUsage: cumulative usage after the latest model turn
}
// TerminalReason explains why the loop stopped.
type TerminalReason string
const (
ReasonCompleted TerminalReason = "completed" // model ended its turn
ReasonBlockingLimit TerminalReason = "blocking_limit" // hard context limit hit pre-request
ReasonImageError TerminalReason = "image_error" // unsupported media (multimodal)
ReasonModelError TerminalReason = "model_error" // provider/API failure
ReasonAbortedStreaming TerminalReason = "aborted_streaming" // canceled during streaming
ReasonAbortedTools TerminalReason = "aborted_tools" // canceled during tool execution
ReasonPromptTooLong TerminalReason = "prompt_too_long" // overflow recovery exhausted
ReasonStopHookPrevented TerminalReason = "stop_hook_prevented" // a Stop hook blocked continuation
ReasonHookStopped TerminalReason = "hook_stopped" // a tool/hook stopped continuation
ReasonMaxTurns TerminalReason = "max_turns" // hit MaxTurns
ReasonTimeout TerminalReason = "timeout" // hit a wall-clock run budget (host-imposed)
)
// ContinueReason names why the loop took another turn. These drive control
// flow; they are recorded on the loop for telemetry.
type ContinueReason string
const (
ContinueNextTurn ContinueReason = "next_turn"
ContinueReactiveCompactRetry ContinueReason = "reactive_compact_retry"
ContinueMaxOutputTokensEscalate ContinueReason = "max_output_tokens_escalate"
ContinueMaxOutputTokensRecovery ContinueReason = "max_output_tokens_recovery"
ContinueStopHookBlocking ContinueReason = "stop_hook_blocking"
ContinueTokenBudget ContinueReason = "token_budget_continuation"
ContinueTaskNotification ContinueReason = "task_notification"
)
// Terminal is the final state of a Query, delivered as the KindResult event.
type Terminal struct {
Reason TerminalReason
Err error
Usage llm.Usage
Turns int
Messages []llm.Message // full conversation snapshot (non-destructive: retains history)
Text string // the assistant's final text, for convenience
}
+194
View File
@@ -0,0 +1,194 @@
package harness
import (
"context"
"iter"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
func maxTokensTurn(text string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SETextDelta, Text: text},
{Type: llm.SEMessageDelta, StopReason: "max_tokens"},
{Type: llm.SEMessageStop},
}
}
// alwaysModel returns the same turn forever (with a hard cap via MaxTurns).
func alwaysModel(turn []llm.StreamEvent) func(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
for _, e := range turn {
if !yield(e, nil) {
return
}
}
}
}
}
func TestMaxOutputTokensRecovery(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
maxTokensTurn("partial output"), // truncated
textTurn("finished"), // resumes and completes
}}
in := QueryInput{Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(), PermissionMode: permission.ModeBypass}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted || term.Text != "finished" {
t.Fatalf("terminal=%+v", term)
}
// user, asst(partial), user(resume), asst(finished)
if len(term.Messages) != 4 || !strings.Contains(term.Messages[2].Text(), "Resume directly") {
t.Fatalf("resume message not injected: %+v", term.Messages)
}
}
func TestMaxOutputTokensRecoveryLimit(t *testing.T) {
// Always truncates → must stop after 3 recoveries (no infinite loop).
in := QueryInput{Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(), PermissionMode: permission.ModeBypass, MaxTurns: 20}
term := drain(t, in, QueryDeps{CallModel: alwaysModel(maxTokensTurn("x"))})
if term.Reason != ReasonCompleted {
t.Fatalf("should complete after recovery limit, got %v", term.Reason)
}
resumes := 0
for _, msg := range term.Messages {
if strings.Contains(msg.Text(), "Resume directly") {
resumes++
}
}
if resumes != 3 {
t.Fatalf("expected 3 recovery injections, got %d", resumes)
}
}
func TestTokenBudgetContinuation(t *testing.T) {
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(),
PermissionMode: permission.ModeBypass, TokenBudget: 100000, MaxTurns: 20,
}
term := drain(t, in, QueryDeps{CallModel: alwaysModel(textTurn("done"))})
if term.Reason != ReasonCompleted {
t.Fatalf("reason=%v", term.Reason)
}
nudges := 0
for _, msg := range term.Messages {
if strings.Contains(msg.Text(), "token budget") {
nudges++
}
}
// continuationCount reaches 3 (with zero-delta diminishing) then stops.
if nudges != 3 {
t.Fatalf("expected 3 budget nudges then diminishing-returns stop, got %d", nudges)
}
}
func TestRecoveriesDoNotCountTowardMaxTurns(t *testing.T) {
// Two max_tokens recoveries then completion, with MaxTurns=1. Since recoveries
// are retries of the same turn (not tool-turns), they must NOT trip max_turns.
m := &scriptedModel{turns: [][]llm.StreamEvent{
maxTokensTurn("partial 1"),
maxTokensTurn("partial 2"),
textTurn("done"),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(),
PermissionMode: permission.ModeBypass, MaxTurns: 1,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted || term.Text != "done" {
t.Fatalf("recoveries should not count as turns; terminal=%+v", term)
}
if term.Turns != 1 {
t.Fatalf("turnCount should stay 1 (no tool-turns), got %d", term.Turns)
}
}
func TestToolTurnsCountTowardMaxTurns(t *testing.T) {
// Each tool-turn advances turnCount; MaxTurns bounds them.
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("a", "Bash", `{"command":"echo 1"}`),
toolTurn("b", "Bash", `{"command":"echo 2"}`),
toolTurn("c", "Bash", `{"command":"echo 3"}`),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass, WorkingDir: t.TempDir(), MaxTurns: 2,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonMaxTurns {
t.Fatalf("reason=%v, want max_turns", term.Reason)
}
}
type fakeHooks struct {
stop func(calls int) (bool, []string, string)
n int
}
func (h *fakeHooks) PreToolUse(context.Context, string, []byte) (bool, string, []byte) {
return false, "", nil
}
func (h *fakeHooks) PostToolUse(context.Context, string, []byte, []byte, bool) {}
func (h *fakeHooks) Stop(context.Context, []llm.Message) (bool, []string, string) {
h.n++
return h.stop(h.n)
}
func TestStopHookPreventTerminates(t *testing.T) {
hooks := &fakeHooks{stop: func(int) (bool, []string, string) { return true, nil, "halt" }}
in := QueryInput{Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(), Hooks: hooks}
term := drain(t, in, QueryDeps{CallModel: alwaysModel(textTurn("done"))})
if term.Reason != ReasonStopHookPrevented || term.Text != "halt" {
t.Fatalf("terminal=%+v", term)
}
}
func TestStopHookBlockingContinues(t *testing.T) {
hooks := &fakeHooks{stop: func(n int) (bool, []string, string) {
if n == 1 {
return false, []string{"keep going"}, ""
}
return false, nil, ""
}}
m := &scriptedModel{turns: [][]llm.StreamEvent{textTurn("first"), textTurn("really done")}}
in := QueryInput{Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(), Hooks: hooks}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted || term.Text != "really done" {
t.Fatalf("terminal=%+v", term)
}
found := false
for _, msg := range term.Messages {
if strings.Contains(msg.Text(), "keep going") {
found = true
}
}
if !found {
t.Fatal("blocking error not injected")
}
}
func TestMessagesForAPIExcludesPreBoundary(t *testing.T) {
seeded := []llm.Message{
llm.UserText("ancient question"),
{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("ancient answer")}},
llm.BoundaryMessage(llm.BoundaryMeta{PreTokens: 1234}),
llm.UserText("[summary] earlier work digest"),
llm.UserText("recent question"),
}
var captured []llm.Message
capture := func(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
captured = append([]llm.Message(nil), req.Messages...)
return alwaysModel(textTurn("ok"))(context.Background(), req)
}
in := QueryInput{Messages: seeded, Tools: tool.NewRegistry(), PermissionMode: permission.ModeBypass}
drain(t, in, QueryDeps{CallModel: capture})
// API view = summary + recent (boundary stripped, pre-boundary excluded).
if len(captured) != 2 || captured[0].Text() != "[summary] earlier work digest" || captured[1].Text() != "recent question" {
t.Fatalf("API view wrong: %+v", captured)
}
}
+226
View File
@@ -0,0 +1,226 @@
package harness
import (
"context"
"iter"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// scriptedModel returns one preset event sequence per call, driving the loop
// offline through QueryDeps.CallModel.
type scriptedModel struct {
turns [][]llm.StreamEvent
calls int
}
func (m *scriptedModel) call(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
evs := m.turns[m.calls]
m.calls++
return func(yield func(llm.StreamEvent, error) bool) {
for _, ev := range evs {
if !yield(ev, nil) {
return
}
}
}
}
func textTurn(s string) []llm.StreamEvent {
return []llm.StreamEvent{{Type: llm.SETextDelta, Text: s}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}, {Type: llm.SEMessageStop}}
}
func toolTurn(id, name, input string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEToolUseStart, ToolID: id, ToolName: name},
{Type: llm.SEToolInputJSON, Text: input},
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
{Type: llm.SEMessageStop},
}
}
func drain(t *testing.T, in QueryInput, deps QueryDeps) *Terminal {
t.Helper()
var term *Terminal
for ev, err := range Query(context.Background(), in, deps) {
if err != nil {
t.Fatalf("event err: %v", err)
}
if ev.Kind == KindResult {
term = ev.Terminal
}
}
if term == nil {
t.Fatal("no terminal event")
}
return term
}
func TestLoopRunsToolThenCompletes(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("c1", "Bash", `{"command":"echo hi"}`),
textTurn("done"),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted || term.Text != "done" {
t.Fatalf("terminal=%+v", term)
}
// user, assistant(tool_use), user(tool_result), assistant(text)
if len(term.Messages) != 4 {
t.Fatalf("messages=%d", len(term.Messages))
}
res := term.Messages[2].Content[0]
if res.ToolUseID != "c1" || !strings.Contains(res.Content[0].Text, "hi") {
t.Fatalf("tool_result wrong: %+v", res)
}
if m.calls != 2 {
t.Fatalf("model calls=%d", m.calls)
}
}
func TestPermissionDenyPairsSyntheticResult(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("c1", "Write", `{"file_path":"x","content":"y"}`),
textTurn("ok"),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewWrite()),
PermissionMode: permission.ModePlan, // denies writes
WorkingDir: t.TempDir(),
}
term := drain(t, in, QueryDeps{CallModel: m.call})
res := term.Messages[2].Content[0]
if !res.IsError || !strings.Contains(res.Content[0].Text, "not permitted") {
t.Fatalf("expected permission-denied result, got %+v", res)
}
}
func TestMaxTurns(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("a", "Bash", `{"command":"echo 1"}`),
toolTurn("b", "Bash", `{"command":"echo 2"}`),
toolTurn("c", "Bash", `{"command":"echo 3"}`),
}}
in := QueryInput{
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
MaxTurns: 2,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonMaxTurns {
t.Fatalf("reason=%v", term.Reason)
}
}
func TestParallelReadOnlyExecution(t *testing.T) {
// Two concurrent-safe reads in one turn must both run and pair results.
dir := t.TempDir()
in := QueryInput{Messages: []llm.Message{llm.UserText("go")}, Tools: tool.NewRegistry(tool.NewGlob()), PermissionMode: permission.ModeDefault, WorkingDir: dir}
m := &scriptedModel{turns: [][]llm.StreamEvent{
{
{Type: llm.SEToolUseStart, ToolID: "g1", ToolName: "Glob"},
{Type: llm.SEToolInputJSON, Text: `{"pattern":"*.go"}`},
{Type: llm.SEToolUseStart, ToolID: "g2", ToolName: "Glob"},
{Type: llm.SEToolInputJSON, Text: `{"pattern":"*.txt"}`},
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
{Type: llm.SEMessageStop},
},
textTurn("done"),
}}
term := drain(t, in, QueryDeps{CallModel: m.call})
results := term.Messages[2].Content
if len(results) != 2 || results[0].ToolUseID != "g1" || results[1].ToolUseID != "g2" {
t.Fatalf("parallel results mis-ordered: %+v", results)
}
}
// fakeCompactor simulates autoCompact once: it inserts a boundary + summary just
// before the last message (the kept tail), so the post-boundary working set is
// [boundary, summary, tail] — the shape recordNewBoundary must persist.
type fakeCompactor struct{ done bool }
func (f *fakeCompactor) Pre(_ context.Context, msgs []llm.Message, _ int) []llm.Message {
if f.done || len(msgs) < 2 {
return msgs
}
f.done = true
tailStart := len(msgs) - 1
boundary := llm.BoundaryMessage(llm.BoundaryMeta{Trigger: "auto", PreTokens: 999, MessagesSummarized: tailStart})
summary := llm.Message{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.TextBlock("[summary] DIGEST")}}
out := append([]llm.Message{}, msgs[:tailStart]...)
out = append(out, boundary, summary)
return append(out, msgs[tailStart:]...)
}
func (f *fakeCompactor) Reactive(_ context.Context, msgs []llm.Message) ([]llm.Message, bool) {
return msgs, false
}
func (f *fakeCompactor) IsOverflow(error) bool { return false }
// capRecorder captures everything the harness persists.
type capRecorder struct {
msgs []llm.Message
boundaries int
}
func (r *capRecorder) RecordMessage(m llm.Message, _ llm.Usage) { r.msgs = append(r.msgs, m) }
func (r *capRecorder) RecordBoundary(_ llm.BoundaryMeta) { r.boundaries++ }
// TestCompactionWorkingSetIsPersisted verifies that when compaction inserts a
// boundary, recordNewBoundary persists the WHOLE post-boundary working set
// (boundary marker + summary + kept tail) as durable messages — so a cold-start
// resume can restore the compacted view instead of re-summarizing.
func TestCompactionWorkingSetIsPersisted(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{textTurn("done")}}
rec := &capRecorder{}
in := QueryInput{
Messages: []llm.Message{llm.UserText("m1"), llm.UserText("m2"), llm.UserText("TAILMSG")},
Tools: tool.NewRegistry(),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
Compactor: &fakeCompactor{},
Recorder: rec,
}
drain(t, in, QueryDeps{CallModel: m.call})
if rec.boundaries != 1 {
t.Fatalf("RecordBoundary calls=%d, want 1 (observability marker)", rec.boundaries)
}
// Find the persisted boundary marker; the summary and the tail must follow it.
bi := -1
for i, msg := range rec.msgs {
if llm.IsBoundaryMarker(msg) {
bi = i
break
}
}
if bi < 0 {
t.Fatal("boundary marker was not persisted as a message")
}
post := rec.msgs[bi:]
if len(post) < 3 {
t.Fatalf("post-boundary persisted = %d msgs, want >=3 (boundary+summary+tail)", len(post))
}
if !strings.Contains(post[1].Text(), "DIGEST") {
t.Fatalf("message after boundary should be the summary, got %q", post[1].Text())
}
if post[2].Text() != "TAILMSG" {
t.Fatalf("kept tail not re-recorded after the boundary, got %q", post[2].Text())
}
// The persisted boundary reconstructs to the compacted API view: it opens with
// [summary, tail] (the assistant's reply, recorded after, trails it).
if api := llm.MessagesForAPI(post); len(api) < 2 || !strings.Contains(api[0].Text(), "DIGEST") || api[1].Text() != "TAILMSG" {
t.Fatalf("MessagesForAPI(persisted working set) = %+v, want to open with [summary, TAILMSG]", api)
}
}
+107
View File
@@ -0,0 +1,107 @@
package harness
import (
"context"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// scriptedSyncModel drives the loop's non-streaming path (QueryInput.NonStreaming
// + QueryDeps.CallModelSync): one preset whole-message reply per call.
type scriptedSyncModel struct {
turns []syncTurn
calls int
}
type syncTurn struct {
msg llm.Message
stop string
usage llm.Usage
}
func (m *scriptedSyncModel) call(_ context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
t := m.turns[m.calls]
m.calls++
return t.msg, t.stop, t.usage, nil
}
func syncToolTurn(id, name, input string) syncTurn {
return syncTurn{
msg: llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{{Type: llm.BlockToolUse, ID: id, Name: name, Input: []byte(input)}}},
stop: "tool_use",
}
}
func syncTextTurn(s string) syncTurn {
return syncTurn{
msg: llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(s)}},
stop: "end_turn",
usage: llm.Usage{InputTokens: 5, OutputTokens: 2},
}
}
// TestNonStreamingRunsToolThenCompletes mirrors TestLoopRunsToolThenCompletes but
// over the non-streaming path: the loop must still execute the tool, feed back
// the result, and complete — producing the same conversation shape and events.
func TestNonStreamingRunsToolThenCompletes(t *testing.T) {
m := &scriptedSyncModel{turns: []syncTurn{
syncToolTurn("c1", "Bash", `{"command":"echo hi"}`),
syncTextTurn("done"),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
NonStreaming: true,
}
var sawText, sawToolUse, sawToolResult bool
var term *Terminal
for ev, err := range Query(context.Background(), in, QueryDeps{CallModelSync: m.call}) {
if err != nil {
t.Fatalf("event err: %v", err)
}
switch ev.Kind {
case KindText:
if ev.Text == "done" {
sawText = true
}
case KindToolUse:
sawToolUse = true
case KindToolResult:
sawToolResult = true
case KindResult:
term = ev.Terminal
}
}
if term == nil {
t.Fatal("no terminal event")
}
if term.Reason != ReasonCompleted || term.Text != "done" {
t.Fatalf("terminal=%+v", term)
}
if !sawText || !sawToolUse || !sawToolResult {
t.Fatalf("missing host events: text=%v toolUse=%v toolResult=%v", sawText, sawToolUse, sawToolResult)
}
// Same conversation shape as the streaming test: user, assistant(tool_use),
// user(tool_result), assistant(text).
if len(term.Messages) != 4 {
t.Fatalf("messages=%d", len(term.Messages))
}
res := term.Messages[2].Content[0]
if res.ToolUseID != "c1" || !strings.Contains(res.Content[0].Text, "hi") {
t.Fatalf("tool_result wrong: %+v", res)
}
if m.calls != 2 {
t.Fatalf("model calls=%d", m.calls)
}
// Usage must accumulate across turns exactly like the streaming accumulator.
if term.Usage.InputTokens != 5 || term.Usage.OutputTokens != 2 {
t.Fatalf("usage=%+v", term.Usage)
}
}
+941
View File
@@ -0,0 +1,941 @@
package harness
import (
"context"
"fmt"
"iter"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// QueryInput is a fully-resolved request to run the loop.
type QueryInput struct {
Provider llm.Provider
System []string
DynamicBoundary int
Messages []llm.Message // conversation including the latest user turn
// SystemReminder, when non-empty, is prepended as the first message on each
// model call. It is not stored in conversation history — the host builds it
// fresh per Prompt call so it never accumulates across turns.
SystemReminder string
Tools *tool.Registry
// DeferredTools names tools whose schemas are withheld from the model's tool
// list (they stay in Tools and are invoked via ExecuteExtraTool). Empty = all
// tool schemas sent as usual.
DeferredTools []string
MaxTokens int
Temperature *float64
// MaxTurns bounds tool-turns (0 = off). MaxDuration bounds wall-clock time,
// checked at the turn boundary so a turn is never aborted mid-stream — unlike
// cancelling ctx, which cuts an in-flight stream/tool (0 = off).
MaxTurns int
MaxDuration time.Duration
MaxConcurrency int
// NonStreaming makes each model call a single non-streaming request (via
// QueryDeps.CallModelSync / Provider.Complete) instead of a token stream. The
// loop still emits the same KindText/KindThinking/KindToolUse/KindUsage events
// to the host — they are surfaced once, when the full response arrives, rather
// than incrementally. Zero value = streaming (unchanged default).
NonStreaming bool
WorkingDir string
AgentID string
// ToolOutputDir, when set, makes oversized tool output spill to a file there
// (full content kept) instead of being discarded; MaxToolOutputChars sets the
// per-tool output budget (head size; 0 = default 30000). See tool.Capture.
ToolOutputDir string
MaxToolOutputChars int
// Tasks, when non-nil, is the background-task manager shared with the tools.
// The loop drains its completion notifications into the conversation between
// tool turns so the model learns when background work finishes.
Tasks *tool.Manager
// Todos, when non-nil, enables todo system-reminders: when the model hasn't
// used TodoWrite for TodoReminderTurnsSinceWrite turns (and it's been at least
// TodoReminderTurnsBetweenReminder turns since the last reminder), the current
// list is re-surfaced as a <system-reminder> user message. Throttle turns are
// derived by scanning the API-visible history, so it survives compaction and
// resume. 0 thresholds default to 10/10 (mirrors claude-code).
Todos *tool.TodoStore
TodoReminderTurnsSinceWrite int
TodoReminderTurnsBetweenReminder int
// BashEnv holds extra "KEY=VALUE" entries injected into Bash subprocess
// environments (foreground + background). Empty = inherit unchanged.
BashEnv []string
// Permission policy.
PermissionMode permission.Mode
PermissionModeFunc func() permission.Mode
Allowed []string
Disallowed []string
CanUseTool permission.CanUseTool
// Hooks is optional lifecycle instrumentation. Nil disables it.
Hooks HookRunner
// Compactor is optional context-window management. Nil disables it.
Compactor Compactor
// Recorder, when non-nil, is notified as the conversation grows so a host can
// persist a transcript. It fires for genuinely new messages (births) in
// order, and for compaction boundaries; it is never called for compaction's
// ephemeral working-set edits (MicroCompact tool-result clearing), so the
// recorded transcript is the raw, full-fidelity history.
Recorder Recorder
// TokenBudget, when > 0, enables budget-driven continuation: after a turn
// with no tool calls, the agent is nudged to keep working until ~90% of the
// budget (output tokens), stopping early on diminishing returns.
TokenBudget int
// EscalateMaxTokens, when true, first retries a max_tokens truncation with a
// raised output cap (64k) before falling back to resume-recovery.
EscalateMaxTokens bool
// Settlement, when non-nil with a Prompt, runs a bounded wrap-up phase the
// moment a budget (MaxTurns/MaxDuration) is hit: it injects Prompt as a user
// turn and hides DisabledTools, so a budget-terminated run can checkpoint its
// findings instead of ending abruptly. The run still finishes with the budget's
// reason (ReasonMaxTurns/ReasonTimeout), never ReasonCompleted. Nil = off.
Settlement *Settlement
}
// Settlement configures the wrap-up phase that runs when a budget is hit.
type Settlement struct {
Prompt string // wrap-up instruction injected as a user turn (empty = settlement off)
MaxTurns int // turn budget for the wrap-up phase itself (0 = default 2)
DisabledTools []string // tool names hidden from the model during wrap-up (e.g. ["Bash"])
// PromptByReason optionally overrides Prompt based on WHY the run settled
// (keyed by the terminal reason, e.g. ReasonTimeout / ReasonMaxTurns). When the
// settling reason has a non-empty entry here it is used; otherwise Prompt is used.
// Lets a caller inject a different wrap-up depending on whether a run was cut by
// its time budget vs its step budget, without knowing which at build time.
PromptByReason map[TerminalReason]string
}
// promptFor returns the wrap-up prompt to inject for a settling reason: the
// PromptByReason override when present and non-empty, else the base Prompt.
func (s *Settlement) promptFor(reason TerminalReason) string {
if s.PromptByReason != nil {
if p := s.PromptByReason[reason]; p != "" {
return p
}
}
return s.Prompt
}
// Compactor is the harness's view of the compaction system (implemented in
// package compaction). Compaction is non-destructive; the harness sends only
// llm.MessagesForAPI(messages) to the model.
type Compactor interface {
// Pre conditions the history before a model request. lastInputTokens is the
// total token size the previous model response reported (0 if none yet), used
// as the initial gate count in preference to local estimation.
Pre(ctx context.Context, msgs []llm.Message, lastInputTokens int) []llm.Message
Reactive(ctx context.Context, msgs []llm.Message) ([]llm.Message, bool)
IsOverflow(err error) bool
}
// ContextView is optionally implemented by a Compactor that builds the request
// message array itself, replacing llm.MessagesForAPI. Hosts with their own
// context manager (e.g. model-driven compression) implement it to project the
// history per request without mutating it.
//
// View MUST be pure: the returned slice is used for this request only and is
// never written back to the loop's history. Implementations that depend on
// stable message identity (content hashing, per-message refs) rely on this —
// writing back would change message bytes and invalidate that identity.
type ContextView interface {
View(ctx context.Context, msgs []llm.Message) []llm.Message
}
// Recorder receives conversation events for durable transcript persistence
// (implemented in package transcript). RecordMessage fires once per new message
// in birth order; usage carries the token delta attributed to that turn
// (assistant messages only; zero otherwise). RecordBoundary fires when
// compaction inserts a boundary, for observability — boundaries are not part of
// the raw reconstructable history.
type Recorder interface {
RecordMessage(m llm.Message, usage llm.Usage)
RecordBoundary(meta llm.BoundaryMeta)
}
// HookRunner is the harness's view of the hook system (implemented in package
// hook). Stop returns two distinct outcomes: preventContinuation (hard
// terminate) and/or blockingErrors (inject + continue).
type HookRunner interface {
PreToolUse(ctx context.Context, name string, input []byte) (block bool, message string, updated []byte)
PostToolUse(ctx context.Context, name string, input, result []byte, isErr bool)
Stop(ctx context.Context, messages []llm.Message) (prevent bool, blockingErrors []string, message string)
}
// QueryDeps are injectable side-effect boundaries for testing (FR-01.6).
type QueryDeps struct {
CallModel func(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error]
// CallModelSync is the non-streaming counterpart of CallModel, used when
// QueryInput.NonStreaming is set. It performs a single request and returns the
// fully assembled assistant message, the stop reason, and cumulative usage.
CallModelSync func(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error)
NewID func() string
}
func (d *QueryDeps) withDefaults(in QueryInput) {
if d.CallModel == nil && in.Provider != nil {
d.CallModel = in.Provider.Stream
}
if d.CallModelSync == nil && in.Provider != nil {
d.CallModelSync = in.Provider.Complete
}
if d.NewID == nil {
var n int64
d.NewID = func() string { return "id_" + strconv.FormatInt(atomic.AddInt64(&n, 1), 10) }
}
}
// Query runs the agent loop and returns its event stream. The final event is
// always KindResult carrying a Terminal (unless the consumer stops early).
func Query(ctx context.Context, in QueryInput, deps QueryDeps) iter.Seq2[Event, error] {
deps.withDefaults(in)
conc := in.MaxConcurrency
if conc <= 0 {
conc = 10
}
return func(yield func(Event, error) bool) {
l := &loop{ctx: ctx, in: in, deps: deps, yield: yield, sem: make(chan struct{}, conc)}
l.messages = append([]llm.Message(nil), in.Messages...)
l.run()
}
}
// budgetTracker tracks token-budget continuation state.
type budgetTracker struct {
continuationCount int
lastGlobalTurnTokens int
lastDeltaTokens int
}
type loop struct {
ctx context.Context
// toolCtx bounds tool execution with the run's MaxDuration deadline, so a tool
// that overruns the wall-clock budget is interrupted mid-flight (the model call
// stays on ctx — streams are never cut mid-flight). Derived from ctx, so a parent
// cancellation (pause/kill/shutdown) still cancels it. Swapped to ctx once the
// wrap-up phase begins, so settlement tools run live, bounded only by settleMaxTurns.
toolCtx context.Context
in QueryInput
deps QueryDeps
yield func(Event, error) bool
sem chan struct{} // bounds concurrent tool execution
messages []llm.Message
usage llm.Usage
lastInputTokens int // total token size the previous model response reported (compaction gate)
turnCount int
boundaryCount int // boundary markers already seen, so Recorder fires once each
startTime time.Time // loop start, for MaxDuration (wall-clock budget)
// settlement (wrap-up) phase state, entered when a budget is hit
settling bool
settleReason TerminalReason // the budget reason to finish with after wrap-up
settleTurn int
// recovery / continuation state
maxOutputTokensOverride int
maxOutputTokensRecoveryCount int
hasAttemptedReactiveCompact bool
stopHookActive bool
budget budgetTracker
lastContinue ContinueReason
}
const (
budgetCompletionThresholdNum = 9 // 0.9
budgetCompletionThresholdDen = 10
budgetDiminishingThreshold = 500
escalatedMaxTokens = 64000
maxOutputTokensRecoveryLimit = 3
// maxLoopIterations is a defensive backstop; turnCount counts only tool-turns,
// so this only guards against a pathological recovery/continuation loop.
maxLoopIterations = 10000
)
func (l *loop) emit(ev Event) bool { return l.yield(ev, nil) }
// record forwards a newly appended message to the transcript Recorder, if any.
func (l *loop) record(m llm.Message, u llm.Usage) {
if l.in.Recorder != nil {
l.in.Recorder.RecordMessage(m, u)
}
}
// injectTaskNotifications drains completion notifications from the background-task
// manager and appends them to the conversation as a user message, so the model is
// told when background work finishes. Returns true if any were injected.
func (l *loop) injectTaskNotifications() bool {
if l.in.Tasks == nil {
return false
}
notes := l.in.Tasks.DrainNotifications()
if len(notes) == 0 {
return false
}
var b strings.Builder
for i, n := range notes {
if i > 0 {
b.WriteString("\n")
}
b.WriteString(n.String())
}
msg := llm.UserText(b.String())
l.messages = append(l.messages, msg)
l.record(msg, llm.Usage{})
return true
}
// recordNewBoundary persists a boundary that compaction just inserted (detected
// by a rise in the boundary-marker count). It writes the post-boundary working
// set — the boundary marker, the summary, and the kept recent tail — as durable
// messages, so a COLD-START Resume restores the compacted view via MessagesForAPI
// instead of replaying raw history and re-summarizing. The tail is re-recorded
// after the boundary (it also exists earlier as births); only the post-boundary
// copy is sent to the model. RecordBoundary keeps the observability-only marker
// (a Type:"boundary" record, skipped during reconstruction).
func (l *loop) recordNewBoundary() {
if l.in.Recorder == nil {
return
}
c := countBoundaries(l.messages)
if c <= l.boundaryCount {
return
}
if i := llm.LastBoundaryIndex(l.messages); i >= 0 {
if meta, ok := llm.ParseBoundaryMeta(l.messages[i]); ok {
l.in.Recorder.RecordBoundary(meta)
}
for _, m := range l.messages[i:] { // boundary marker + summary + kept tail
l.in.Recorder.RecordMessage(m, llm.Usage{})
}
}
l.boundaryCount = c
}
func usageDelta(before, after llm.Usage) llm.Usage {
return llm.Usage{
InputTokens: after.InputTokens - before.InputTokens,
OutputTokens: after.OutputTokens - before.OutputTokens,
CacheReadTokens: after.CacheReadTokens - before.CacheReadTokens,
CacheWriteTokens: after.CacheWriteTokens - before.CacheWriteTokens,
}
}
func countBoundaries(msgs []llm.Message) int {
n := 0
for _, m := range msgs {
if llm.IsBoundaryMarker(m) {
n++
}
}
return n
}
func (l *loop) finish(reason TerminalReason, err error, text string) {
l.yield(Event{Kind: KindResult, Terminal: &Terminal{
Reason: reason,
Err: err,
Usage: l.usage,
Turns: l.turnCount,
Messages: l.messages,
Text: text,
}}, nil)
}
func (l *loop) maxTokens() int {
if l.maxOutputTokensOverride > 0 {
return l.maxOutputTokensOverride
}
if l.in.MaxTokens > 0 {
return l.in.MaxTokens
}
return 32768
}
func (l *loop) run() {
var schemas []llm.ToolSchema
if l.in.Tools != nil {
schemas = l.in.Tools.Schemas()
// Deferred tools stay in the registry (callable via ExecuteExtraTool) but
// their schemas are withheld from the model to save context tokens.
if len(l.in.DeferredTools) > 0 {
schemas = filterToolSchemas(schemas, l.in.DeferredTools)
}
}
l.turnCount = 1 // the first model call is turn 1
l.boundaryCount = countBoundaries(l.messages)
l.startTime = time.Now() // wall-clock baseline for MaxDuration
// toolCtx carries the MaxDuration deadline so a tool that overruns the wall-clock
// budget is interrupted mid-flight (rather than the run only noticing at the next
// turn boundary, which a hung tool never reaches). On interrupt the loop enters the
// wrap-up phase on the live parent ctx instead of aborting — see the tools branch.
l.toolCtx = l.ctx
if l.in.MaxDuration > 0 {
var stopTool context.CancelFunc
l.toolCtx, stopTool = context.WithDeadline(l.ctx, l.startTime.Add(l.in.MaxDuration))
defer stopTool()
}
iterations := 0
for {
if l.ctx.Err() != nil {
l.finish(ReasonAbortedStreaming, l.ctx.Err(), "")
return
}
// Defensive backstop against a pathological recovery/continuation loop.
// turnCount itself only counts tool-turns (below); every continuation path
// is individually bounded, so this guard should never fire in practice.
iterations++
if iterations > maxLoopIterations {
l.finish(ReasonMaxTurns, nil, "")
return
}
// Non-destructive proactive compaction (MicroCompact → AutoCompact).
if l.in.Compactor != nil {
l.messages = l.in.Compactor.Pre(l.ctx, l.messages, l.lastInputTokens)
l.recordNewBoundary()
}
usageBefore := l.usage
asst, exec, stopReason, streamErr, consumerStopped, aborted := l.streamAndExecute(schemas)
if consumerStopped {
return
}
if streamErr != nil {
if l.ctx.Err() != nil {
l.finish(ReasonAbortedStreaming, l.ctx.Err(), "")
return
}
// Reactive recovery from prompt-too-long: one forced AutoCompact, then retry.
if l.in.Compactor != nil && l.in.Compactor.IsOverflow(streamErr) && !l.hasAttemptedReactiveCompact {
l.hasAttemptedReactiveCompact = true
if msgs, ok := l.in.Compactor.Reactive(l.ctx, l.messages); ok {
l.messages = msgs
l.recordNewBoundary()
l.lastContinue = ContinueReactiveCompactRetry
continue
}
l.finish(ReasonPromptTooLong, streamErr, "")
return
}
l.finish(ReasonModelError, streamErr, "")
return
}
l.hasAttemptedReactiveCompact = false
l.messages = append(l.messages, asst)
turnUsage := usageDelta(usageBefore, l.usage)
// The size the model just reported for its input, preferred by the
// compactor over local estimation on the next turn's gate check.
l.lastInputTokens = turnUsage.InputTokens + turnUsage.OutputTokens
l.record(asst, turnUsage)
// surface cumulative usage after each model turn so hosts can show live token
// counts during a run (not just at the terminal event).
if u := l.usage; u != (llm.Usage{}) {
if !l.emit(Event{Kind: KindUsage, Usage: &u}) {
return
}
}
toolUses := asst.ToolUses()
// max_tokens truncation with no tool calls → escalate / resume-recovery.
// These continuations are retries of the same turn (they do not advance
// turnCount).
if stopReason == "max_tokens" && len(toolUses) == 0 {
if l.handleMaxOutputTokens() {
continue
}
// recovery exhausted: surface the truncated turn as completion.
} else {
l.maxOutputTokensOverride = 0
}
if len(toolUses) == 0 {
// During the wrap-up phase, a natural stop ends the run with the ORIGINAL
// budget reason (not "completed") — the run was budget-terminated; the
// settlement is just a checkpoint. Skip the keep-working nudges below.
if l.settling {
l.finish(l.settleReason, nil, asst.Text())
return
}
// Stop hooks: hard terminate, or force continue with injected errors.
// stopHookActive prevents an always-blocking hook from looping forever
// without an intervening tool-turn.
if l.in.Hooks != nil && !l.stopHookActive {
prevent, blocking, msg := l.in.Hooks.Stop(l.ctx, l.messages)
if prevent {
l.finish(ReasonStopHookPrevented, nil, msg)
return
}
if len(blocking) > 0 {
for _, b := range blocking {
bm := llm.UserText(b)
l.messages = append(l.messages, bm)
l.record(bm, llm.Usage{})
}
l.stopHookActive = true
l.lastContinue = ContinueStopHookBlocking
continue
}
}
l.stopHookActive = false
// Surface any background-task completions before ending the turn; if any
// landed, take another turn so the model can react to them.
if l.injectTaskNotifications() {
l.lastContinue = ContinueTaskNotification
continue
}
// Token budget: nudge to keep working until ~90% / diminishing returns.
if l.in.TokenBudget > 0 && l.checkBudgetContinue() {
l.lastContinue = ContinueTokenBudget
continue
}
l.finish(ReasonCompleted, nil, asst.Text())
return
}
// Tools were executed during streaming; record their results.
results := exec.results()
resultMsg := llm.Message{Role: llm.RoleUser, Content: results}
l.messages = append(l.messages, resultMsg)
l.record(resultMsg, llm.Usage{})
// Extra messages a tool injected after its result (e.g. the Skill tool's
// instructions as an independent user message) are appended next so the
// next model round sees them as standing guidance.
for _, em := range exec.extraMessages() {
l.messages = append(l.messages, em)
l.record(em, llm.Usage{})
}
// Surface any background-task completions that landed during this turn so
// the next model round sees them alongside the tool results.
l.injectTaskNotifications()
// Parent-ctx cancellation (pause / planner kill / shutdown) → real abort, no wrap-up.
if l.ctx.Err() != nil {
l.finish(ReasonAbortedTools, l.ctx.Err(), "")
return
}
// aborted with the parent still alive ⇒ the run's own MaxDuration deadline (on
// toolCtx) interrupted an in-flight tool. Enter the wrap-up phase on the live
// parent ctx instead of dying, so a run whose tool overran the wall-clock budget
// still checkpoints its findings. Mid-tool interrupts are always time-driven
// (MaxTurns is only ever checked at the turn boundary), hence ReasonTimeout.
if aborted {
if l.settling {
l.finish(l.settleReason, nil, "")
return
}
if l.beginSettlement(ReasonTimeout, &schemas) {
l.toolCtx = l.ctx // wrap-up tools run live, bounded only by settleMaxTurns
l.lastContinue = ContinueNextTurn
continue
}
l.finish(ReasonTimeout, nil, "")
return
}
// next_turn: only tool-turns advance turnCount.
l.stopHookActive = false // a real turn happened; stop hooks may fire fresh
if l.settling {
// wrap-up phase: bounded by its own small turn budget. When spent, finish
// with the original budget reason (not "completed").
l.settleTurn++
if l.settleTurn >= l.settleMaxTurns() {
l.finish(l.settleReason, nil, "")
return
}
l.lastContinue = ContinueNextTurn
continue
}
// Primary budgets are checked HERE, at the turn boundary — never mid-stream —
// so a turn is not aborted in flight (that would surface as an abort/error).
// On hit, optionally run the wrap-up phase before finishing.
nextTurn := l.turnCount + 1
hitTurns := l.in.MaxTurns > 0 && nextTurn > l.in.MaxTurns
hitTime := l.in.MaxDuration > 0 && time.Since(l.startTime) >= l.in.MaxDuration
if hitTurns || hitTime {
reason := ReasonMaxTurns
if hitTime && !hitTurns {
reason = ReasonTimeout
}
if l.beginSettlement(reason, &schemas) {
l.lastContinue = ContinueNextTurn
continue
}
l.finish(reason, nil, "")
return
}
l.turnCount = nextTurn
l.lastContinue = ContinueNextTurn
}
}
// settleMaxTurns is the wrap-up phase's own turn budget (default 2).
func (l *loop) settleMaxTurns() int {
if l.in.Settlement != nil && l.in.Settlement.MaxTurns > 0 {
return l.in.Settlement.MaxTurns
}
return 2
}
// beginSettlement enters the wrap-up phase when configured: injects the caller's
// prompt as a user turn and hides DisabledTools, so a budget-terminated run can
// checkpoint its findings. Returns false when no settlement is configured (caller
// then finishes immediately).
func (l *loop) beginSettlement(reason TerminalReason, schemas *[]llm.ToolSchema) bool {
s := l.in.Settlement
if s == nil {
return false
}
prompt := s.promptFor(reason)
if prompt == "" {
return false
}
msg := llm.UserText(prompt)
l.messages = append(l.messages, msg)
l.record(msg, llm.Usage{})
l.settling = true
l.settleReason = reason
l.settleTurn = 0
if len(s.DisabledTools) > 0 {
*schemas = filterToolSchemas(*schemas, s.DisabledTools)
}
return true
}
// filterToolSchemas returns schemas with the named tools removed.
func filterToolSchemas(schemas []llm.ToolSchema, disabled []string) []llm.ToolSchema {
block := make(map[string]bool, len(disabled))
for _, d := range disabled {
block[d] = true
}
out := make([]llm.ToolSchema, 0, len(schemas))
for _, s := range schemas {
if !block[s.Name] {
out = append(out, s)
}
}
return out
}
// handleMaxOutputTokens implements the escalate→recover(3×) flow. Returns true
// if it injected a recovery and the loop should continue.
func (l *loop) handleMaxOutputTokens() bool {
if l.in.EscalateMaxTokens && l.maxOutputTokensOverride == 0 {
l.maxOutputTokensOverride = escalatedMaxTokens
l.lastContinue = ContinueMaxOutputTokensEscalate
return true
}
if l.maxOutputTokensRecoveryCount < maxOutputTokensRecoveryLimit {
nudge := llm.UserText(
"Output token limit hit. Resume directly — no apology, no recap of what you already wrote. Continue exactly where you left off.")
l.messages = append(l.messages, nudge)
l.record(nudge, llm.Usage{})
l.maxOutputTokensRecoveryCount++
l.maxOutputTokensOverride = 0
l.lastContinue = ContinueMaxOutputTokensRecovery
return true
}
return false
}
// checkBudgetContinue continues with a nudge while under 90% of budget and not
// in diminishing returns; otherwise stops.
func (l *loop) checkBudgetContinue() bool {
budget := l.in.TokenBudget
if budget <= 0 || l.in.AgentID != "" { // subagents have no budget
return false
}
turnTokens := l.usage.OutputTokens
delta := turnTokens - l.budget.lastGlobalTurnTokens
diminishing := l.budget.continuationCount >= 3 && delta < budgetDiminishingThreshold && l.budget.lastDeltaTokens < budgetDiminishingThreshold
if !diminishing && turnTokens < budget*budgetCompletionThresholdNum/budgetCompletionThresholdDen {
l.budget.continuationCount++
l.budget.lastDeltaTokens = delta
l.budget.lastGlobalTurnTokens = turnTokens
pct := 0
if budget > 0 {
pct = turnTokens * 100 / budget
}
nudge := llm.UserText(fmt.Sprintf(
"You have used %d%% of your token budget for this task (%d/%d output tokens). Keep going and finish the task; wrap up before the budget is exhausted.",
pct, turnTokens, budget))
l.messages = append(l.messages, nudge)
l.record(nudge, llm.Usage{})
return true
}
return false
}
// Todo system-reminder throttle defaults (mirror claude-code's TODO_REMINDER_CONFIG).
const (
defaultTodoTurnsSinceWrite = 10
defaultTodoTurnsBetween = 10
)
func (l *loop) todoTurnsSinceWrite() int {
if l.in.TodoReminderTurnsSinceWrite > 0 {
return l.in.TodoReminderTurnsSinceWrite
}
return defaultTodoTurnsSinceWrite
}
func (l *loop) todoTurnsBetween() int {
if l.in.TodoReminderTurnsBetweenReminder > 0 {
return l.in.TodoReminderTurnsBetweenReminder
}
return defaultTodoTurnsBetween
}
// maybeInjectTodoReminder appends a todo <system-reminder> user message to the
// history when the model has gone long enough without touching TodoWrite and
// without a recent reminder. Throttle turns are derived from the API-visible
// window (post-boundary) so a reminder re-appears after compaction drops the
// prior one. No-op when todos are disabled or the list is empty.
func (l *loop) maybeInjectTodoReminder() {
if l.in.Todos == nil {
return
}
todos := l.in.Todos.List()
if len(todos) == 0 {
return
}
sinceWrite, sinceReminder := todoReminderTurnCounts(llm.MessagesForAPI(l.messages))
if sinceWrite < l.todoTurnsSinceWrite() || sinceReminder < l.todoTurnsBetween() {
return
}
body := tool.RenderTodoReminder(todos)
if body == "" {
return
}
msg := llm.TodoReminderMessage(body)
l.messages = append(l.messages, msg)
l.record(msg, llm.Usage{})
}
// todoReminderTurnCounts scans messages (most-recent first) and returns the
// number of assistant turns since the last TodoWrite tool_use and since the last
// todo reminder. The turn that contains the TodoWrite is not itself counted (so
// the call turn reads as 0). A never-seen event yields the total assistant-turn
// count (effectively "long ago").
func todoReminderTurnCounts(msgs []llm.Message) (sinceWrite, sinceReminder int) {
foundWrite, foundReminder := false, false
for i := len(msgs) - 1; i >= 0; i-- {
m := msgs[i]
if !foundReminder && llm.IsTodoReminder(m) {
foundReminder = true
continue
}
if m.Role != llm.RoleAssistant {
continue
}
if !foundWrite {
if messageHasToolUse(m, "TodoWrite") {
foundWrite = true
} else {
sinceWrite++
}
}
if !foundReminder {
sinceReminder++
}
}
return
}
func messageHasToolUse(m llm.Message, name string) bool {
for _, b := range m.Content {
if b.Type == llm.BlockToolUse && b.Name == name {
return true
}
}
return false
}
// streamAndExecute runs one model completion, surfacing text/thinking, and feeds
// tool_use blocks to the streaming executor as they finish — so tools begin
// running while the rest of the message is still arriving. It returns the
// assembled assistant message, the executor, the stop reason, and flags.
// requestMessages builds the message array for one model request. A Compactor
// that implements ContextView takes over the projection entirely; otherwise the
// default working set (post-boundary, unpaired tool blocks dropped) is used.
// Either way l.messages is left untouched.
func (l *loop) requestMessages() []llm.Message {
if v, ok := l.in.Compactor.(ContextView); ok {
return v.View(l.ctx, l.messages)
}
return llm.MessagesForAPI(l.messages)
}
func (l *loop) streamAndExecute(schemas []llm.ToolSchema) (asst llm.Message, exec *streamExec, stopReason string, err error, consumerStopped, aborted bool) {
l.maybeInjectTodoReminder()
msgs := l.requestMessages()
if l.in.SystemReminder != "" {
msgs = append([]llm.Message{llm.UserText(l.in.SystemReminder)}, msgs...)
}
req := llm.CompletionRequest{
System: l.in.System,
DynamicBoundary: l.in.DynamicBoundary,
Messages: msgs,
Tools: schemas,
MaxTokens: l.maxTokens(),
Temperature: l.in.Temperature,
}
if l.in.NonStreaming {
return l.completeAndExecute(req)
}
exec = newStreamExec(l)
acc := llm.NewAccumulator()
var building bool
var curID, curName string
var curInput strings.Builder
finalizeTool := func() bool { // false = consumer stopped
if !building {
return true
}
building = false
raw := strings.TrimSpace(curInput.String())
curInput.Reset()
if raw == "" || !jsonValid(raw) {
raw = "{}"
}
block := llm.ContentBlock{Type: llm.BlockToolUse, ID: curID, Name: curName, Input: []byte(raw)}
if !l.emit(Event{Kind: KindToolUse, ToolUse: &block}) {
return false
}
exec.add(block)
return exec.drain()
}
for ev, e := range l.deps.CallModel(l.ctx, req) {
if e != nil {
err = e
break
}
if ev.Type == llm.SEToolInputJSON {
if building {
curInput.WriteString(ev.Text)
}
acc.Add(ev)
continue
}
if !finalizeTool() {
return asst, exec, "", nil, true, false
}
switch ev.Type {
case llm.SETextDelta:
if ev.Text != "" && !l.emit(Event{Kind: KindText, Text: ev.Text}) {
return asst, exec, "", nil, true, false
}
case llm.SEThinkingDelta:
if ev.Text != "" && !l.emit(Event{Kind: KindThinking, Text: ev.Text}) {
return asst, exec, "", nil, true, false
}
case llm.SEToolUseStart:
curID, curName, building = ev.ToolID, ev.ToolName, true
}
acc.Add(ev)
}
if !finalizeTool() {
return asst, exec, "", nil, true, false
}
l.usage.Add(acc.Usage)
asst = acc.Message()
stopReason = acc.StopReason
if err != nil {
return asst, exec, stopReason, err, false, false
}
// Drain tools to completion (or synthesize on abort).
cs, ab := exec.finish()
if cs {
return asst, exec, stopReason, nil, true, false
}
return asst, exec, stopReason, nil, false, ab
}
// completeAndExecute is the non-streaming counterpart of streamAndExecute's body.
// It performs a single non-streaming model call, then replays the assembled
// message as host events (thinking → text → each tool_use) and runs the same
// tool executor. The returned tuple matches streamAndExecute so the turn loop is
// oblivious to which path produced it. Usage is folded into l.usage exactly as
// the streaming accumulator does, so the loop's per-turn usage delta, KindUsage
// emission, and recorder all see identical numbers.
func (l *loop) completeAndExecute(req llm.CompletionRequest) (asst llm.Message, exec *streamExec, stopReason string, err error, consumerStopped, aborted bool) {
exec = newStreamExec(l)
msg, sr, usage, cerr := l.deps.CallModelSync(l.ctx, req)
if cerr != nil {
return asst, exec, "", cerr, false, false
}
l.usage.Add(usage)
asst = msg
stopReason = sr
for _, b := range msg.Content {
switch b.Type {
case llm.BlockThinking:
if b.Thinking != "" && !l.emit(Event{Kind: KindThinking, Text: b.Thinking}) {
return asst, exec, stopReason, nil, true, false
}
case llm.BlockText:
if b.Text != "" && !l.emit(Event{Kind: KindText, Text: b.Text}) {
return asst, exec, stopReason, nil, true, false
}
case llm.BlockToolUse:
block := b
if !l.emit(Event{Kind: KindToolUse, ToolUse: &block}) {
return asst, exec, stopReason, nil, true, false
}
exec.add(block)
if !exec.drain() { // surface any results ready so far (FIFO)
return asst, exec, stopReason, nil, true, false
}
}
}
// Drain tools to completion (or synthesize on abort).
cs, ab := exec.finish()
if cs {
return asst, exec, stopReason, nil, true, false
}
return asst, exec, stopReason, nil, false, ab
}
func jsonValid(s string) bool {
// minimal check used only to guard tool input assembly
s = strings.TrimSpace(s)
if s == "" {
return false
}
depth := 0
inStr := false
esc := false
for _, r := range s {
if inStr {
if esc {
esc = false
} else if r == '\\' {
esc = true
} else if r == '"' {
inStr = false
}
continue
}
switch r {
case '"':
inStr = true
case '{', '[':
depth++
case '}', ']':
depth--
}
}
return depth == 0 && !inStr
}
+131
View File
@@ -0,0 +1,131 @@
package harness
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// A tool's InputSchema does two unrelated jobs: it tells the model what to send,
// and it decides what gets through. Most tools want both. A tool that repairs
// malformed arguments itself wants only the first — the gate would reject the
// very calls it exists to repair, because a truncated or fence-wrapped call is
// not valid JSON.
//
// These tests cover both sides of the opt-out.
// recordingSpec builds a tool that remembers the bytes it was handed.
func recordingSpec(name string, raw bool, got *json.RawMessage) tool.CoreTool {
return tool.Build(tool.Spec{
Name: name,
Schema: map[string]any{"type": "object", "required": []any{"content"}},
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Decision{Behavior: permission.Allow}
},
RawInput: raw,
Run: func(_ context.Context, in json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
*got = in
return tool.Result{Content: []llm.ContentBlock{llm.TextBlock("ran")}}, nil
},
})
}
func execWith(t *testing.T, ct tool.CoreTool, input string) llm.ContentBlock {
t.Helper()
l := &loop{ctx: context.Background(), in: QueryInput{
Tools: tool.NewRegistry(ct),
PermissionMode: permission.ModeBypass,
}}
res, _ := l.execOne(llm.ContentBlock{
Type: llm.BlockToolUse, ID: "toolu_1", Name: ct.Name(), Input: json.RawMessage(input),
}, nil)
return res
}
// The default: invalid JSON is answered with a validation error and Run is never
// reached. This is the behaviour every other tool relies on.
func TestSchemaGateStillRejectsForOrdinaryTools(t *testing.T) {
var got json.RawMessage
res := execWith(t, recordingSpec("Ordinary", false, &got), `{"content":[{"a`)
if !res.IsError {
t.Fatal("malformed input produced a success result for a tool that did not opt out")
}
if !strings.Contains(res.Content[0].Text, "invalid tool input") {
t.Fatalf("result = %q, want the schema validation error", res.Content[0].Text)
}
if got != nil {
t.Fatalf("Run was reached with %q despite failing validation", got)
}
}
// The opt-out: the same bytes reach Run untouched, so the tool can repair them.
func TestRawInputToolReceivesMalformedArgumentsVerbatim(t *testing.T) {
cases := map[string]string{
"truncated mid-object": `{"content":[{"startId":"m00001","end`,
"fenced in markdown": "```json\n{\"content\":[]}\n```",
"trailing comma": `{"content":[{"a":1,},],}`,
"not an object": `"just a string"`,
"missing required": `{"topic":"t"}`,
"empty": ``,
}
for name, input := range cases {
t.Run(name, func(t *testing.T) {
var got json.RawMessage
res := execWith(t, recordingSpec("Lenient", true, &got), input)
if res.IsError {
t.Fatalf("the harness rejected input the tool opted in to handle: %q", res.Content[0].Text)
}
if string(got) != input {
t.Fatalf("Run received %q, want the bytes the model sent, %q", got, input)
}
})
}
}
// Opting out of validation must not opt out of anything else. Permission is the
// one that matters: a tool that skips the schema check still answers to the same
// permission decision.
func TestRawInputToolStillHonoursPermissions(t *testing.T) {
var got json.RawMessage
denied := tool.Build(tool.Spec{
Name: "Denied",
Schema: map[string]any{"type": "object"},
RawInput: true,
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Decision{Behavior: permission.Deny, Message: "nope"}
},
Run: func(_ context.Context, in json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
got = in
return tool.Result{}, nil
},
})
res := execWith(t, denied, `{"garbage`)
if !res.IsError {
t.Fatal("a denied raw-input tool produced a success result")
}
if got != nil {
t.Fatal("a denied raw-input tool was executed anyway")
}
}
// A tool that does not implement the optional interface at all — the shape every
// host-supplied CoreTool has — must keep being validated.
type bareTool struct{ tool.CoreTool }
func TestToolsWithoutTheOptionalInterfaceAreValidated(t *testing.T) {
var got json.RawMessage
res := execWith(t, bareTool{recordingSpec("Bare", true, &got)}, `{"content":[{"a`)
if !res.IsError {
t.Fatal("a CoreTool that does not implement AcceptsRawInput skipped validation; " +
"the assertion is matching something it should not")
}
}
+89
View File
@@ -0,0 +1,89 @@
package harness
import (
"context"
"encoding/json"
"sync"
"testing"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// concurrencyProbe records the peak number of simultaneous executions.
type concurrencyProbe struct {
mu sync.Mutex
active int
maxSeen int
}
func (p *concurrencyProbe) enter() {
p.mu.Lock()
p.active++
if p.active > p.maxSeen {
p.maxSeen = p.active
}
p.mu.Unlock()
}
func (p *concurrencyProbe) leave() {
p.mu.Lock()
p.active--
p.mu.Unlock()
}
func probeTool(name string, safe bool, p *concurrencyProbe) tool.CoreTool {
return tool.Build(tool.Spec{
Name: name,
Schema: map[string]any{"type": "object"},
ReadOnly: func(json.RawMessage) bool { return safe },
Concurrent: func(json.RawMessage) bool { return safe },
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(_ context.Context, _ json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
p.enter()
time.Sleep(25 * time.Millisecond) // widen the overlap window
p.leave()
return tool.Text("ok"), nil
},
})
}
func twoToolTurn(name string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEToolUseStart, ToolID: "t1", ToolName: name},
{Type: llm.SEToolInputJSON, Text: `{}`},
{Type: llm.SEToolUseStart, ToolID: "t2", ToolName: name},
{Type: llm.SEToolInputJSON, Text: `{}`},
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
{Type: llm.SEMessageStop},
}
}
func TestSafeToolsRunConcurrently(t *testing.T) {
p := &concurrencyProbe{}
m := &scriptedModel{turns: [][]llm.StreamEvent{twoToolTurn("safe"), textTurn("done")}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")}, PermissionMode: permission.ModeBypass,
Tools: tool.NewRegistry(probeTool("safe", true, p)),
}
drain(t, in, QueryDeps{CallModel: m.call})
if p.maxSeen != 2 {
t.Fatalf("concurrency-safe tools should overlap (maxSeen=%d, want 2)", p.maxSeen)
}
}
func TestNonSafeToolsRunExclusively(t *testing.T) {
p := &concurrencyProbe{}
m := &scriptedModel{turns: [][]llm.StreamEvent{twoToolTurn("excl"), textTurn("done")}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")}, PermissionMode: permission.ModeBypass,
Tools: tool.NewRegistry(probeTool("excl", false, p)),
}
drain(t, in, QueryDeps{CallModel: m.call})
if p.maxSeen != 1 {
t.Fatalf("non-concurrency-safe tools must run exclusively (maxSeen=%d, want 1)", p.maxSeen)
}
}
+102
View File
@@ -0,0 +1,102 @@
package harness
import (
"context"
"iter"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// On hitting MaxTurns with a Settlement configured, the loop injects the wrap-up
// prompt, hides DisabledTools during wrap-up, and finishes with the ORIGINAL
// budget reason (not ReasonCompleted).
func TestSettlementOnBudgetHit(t *testing.T) {
var toolsSeen [][]string
turns := [][]llm.StreamEvent{
toolTurn("a", "Bash", `{"command":"echo 1"}`), // turn 1 → hits MaxTurns=1
textTurn("已写回事实并总结"), // settlement turn → natural stop
}
call := func(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
names := make([]string, 0, len(req.Tools))
for _, ts := range req.Tools {
names = append(names, ts.Name)
}
i := len(toolsSeen)
toolsSeen = append(toolsSeen, names)
evs := turns[i]
return func(yield func(llm.StreamEvent, error) bool) {
for _, ev := range evs {
if !yield(ev, nil) {
return
}
}
}
}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
MaxTurns: 1,
Settlement: &Settlement{Prompt: "SETTLE_NOW 请写回事实", DisabledTools: []string{"Bash"}},
}
term := drain(t, in, QueryDeps{CallModel: call})
if term.Reason != ReasonMaxTurns {
t.Fatalf("reason=%v, want ReasonMaxTurns(收尾后仍报原预算 reason)", term.Reason)
}
found := false
for _, m := range term.Messages {
for _, c := range m.Content {
if strings.Contains(c.Text, "SETTLE_NOW") {
found = true
}
}
}
if !found {
t.Fatalf("收尾提示未被注入到对话")
}
if len(toolsSeen) < 2 {
t.Fatalf("应至少 2 次模型调用(主+收尾),得 %d", len(toolsSeen))
}
if !contains(toolsSeen[0], "Bash") {
t.Fatalf("主阶段应能看到 Bash: %v", toolsSeen[0])
}
if contains(toolsSeen[1], "Bash") {
t.Fatalf("收尾阶段应屏蔽 Bash: %v", toolsSeen[1])
}
}
// With no Settlement, hitting the budget finishes immediately (unchanged behavior).
func TestNoSettlementFinishesImmediately(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("a", "Bash", `{"command":"echo 1"}`),
toolTurn("b", "Bash", `{"command":"echo 2"}`),
}}
in := QueryInput{
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
MaxTurns: 1,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonMaxTurns {
t.Fatalf("reason=%v", term.Reason)
}
if m.calls != 1 {
t.Fatalf("无收尾应只调用 1 次模型,得 %d", m.calls)
}
}
func contains(xs []string, s string) bool {
for _, x := range xs {
if x == s {
return true
}
}
return false
}
+250
View File
@@ -0,0 +1,250 @@
package harness
import (
"sync"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/tool"
)
// streamExec is the streaming tool executor: tool_use blocks are registered as
// they finish streaming and begin executing immediately, subject to a FIFO +
// exclusivity rule — a concurrency-safe tool may run alongside other safe tools,
// but a non-safe tool requires exclusive access (no other tool executing) and
// blocks every tool queued behind it until it finishes. Results are yielded in
// arrival order; progress is yielded as soon as it arrives.
type streamExec struct {
l *loop
mu sync.Mutex
tools []*tracked
notify chan struct{} // pinged when a tool completes or emits progress
}
type toolStatus int
const (
stQueued toolStatus = iota
stExecuting
stCompleted
stYielded
)
type tracked struct {
block llm.ContentBlock
safe bool
status toolStatus
result llm.ContentBlock
extra []llm.Message // messages the tool injects after its result (Result.Extra)
prog []string
}
func newStreamExec(l *loop) *streamExec {
return &streamExec{l: l, notify: make(chan struct{}, 1)}
}
func (e *streamExec) ping() {
select {
case e.notify <- struct{}{}:
default:
}
}
// add registers a completed tool_use block and tries to start it.
func (e *streamExec) add(block llm.ContentBlock) {
e.mu.Lock()
safe := false
if t, ok := e.l.in.Tools.Get(block.Name); ok {
safe = t.IsConcurrencySafe(block.Input)
}
e.tools = append(e.tools, &tracked{block: block, safe: safe})
e.mu.Unlock()
e.processQueue()
}
// canStartLocked reports whether a tool with the given safety may start now.
func (e *streamExec) canStartLocked(safe bool) bool {
for _, t := range e.tools {
if t.status == stExecuting && (!safe || !t.safe) {
return false
}
}
return true
}
// processQueue starts every queued tool that may run, honoring FIFO: a non-safe
// tool that cannot start blocks the tools behind it.
func (e *streamExec) processQueue() {
e.mu.Lock()
var start []*tracked
for _, t := range e.tools {
if t.status != stQueued {
continue
}
if e.canStartLocked(t.safe) {
t.status = stExecuting
start = append(start, t)
} else if !t.safe {
break
}
}
e.mu.Unlock()
for _, t := range start {
go e.run(t)
}
}
func (e *streamExec) run(t *tracked) {
e.l.sem <- struct{}{} // bound concurrent tool execution
defer func() { <-e.l.sem }()
res, extra := e.l.execOne(t.block, func(p tool.ProgressInfo) {
e.mu.Lock()
t.prog = append(t.prog, p.Message)
e.mu.Unlock()
e.ping()
})
e.mu.Lock()
t.result = res
t.extra = extra
t.status = stCompleted
e.mu.Unlock()
e.ping()
e.processQueue() // a slot freed
}
// drain yields all ready progress and completed results in FIFO order. Stops at
// the first not-yet-finished non-safe tool. Returns false if the consumer broke.
func (e *streamExec) drain() bool {
e.mu.Lock()
var evs []Event
for _, t := range e.tools {
for _, p := range t.prog {
evs = append(evs, Event{Kind: KindProgress, Text: p})
}
t.prog = nil
if t.status == stYielded {
continue
}
if t.status == stCompleted {
t.status = stYielded
r := t.result
evs = append(evs, Event{Kind: KindToolResult, ToolResult: &r})
continue
}
// status is queued/executing: a non-safe one preserves FIFO ordering.
if !t.safe {
break
}
}
e.mu.Unlock()
for _, ev := range evs {
if !e.l.emit(ev) {
return false
}
}
return true
}
// pending reports whether any tool is still queued or executing.
func (e *streamExec) pending() bool {
e.mu.Lock()
defer e.mu.Unlock()
for _, t := range e.tools {
if t.status == stQueued || t.status == stExecuting {
return true
}
}
return false
}
// finish drains to completion. It returns (consumerStopped, aborted): on context
// cancellation it synthesizes interrupted results for unfinished tools.
func (e *streamExec) finish() (consumerStopped, aborted bool) {
for {
if !e.drain() {
return true, false
}
// toolCtx cancellation is either a parent cancel (pause/kill/shutdown) or the
// run's own MaxDuration deadline firing on an in-flight tool. Either way we
// synthesize interrupted results and report aborted; the turn loop then decides
// (parent-cancel → abort, budget-only → wrap-up) via ctx vs toolCtx.
if e.l.toolCtx.Err() != nil {
return !e.drainSynthetic("tool execution interrupted"), true
}
if !e.pending() {
if !e.drain() {
return true, false
}
return false, false
}
select {
case <-e.notify:
case <-e.l.toolCtx.Done():
}
}
}
// drainSynthetic marks every not-yet-yielded tool with a synthetic error result
// and emits it. Returns consumer-not-stopped.
func (e *streamExec) drainSynthetic(msg string) bool {
e.mu.Lock()
var evs []Event
for _, t := range e.tools {
if t.status == stYielded {
continue
}
if t.status == stCompleted {
t.status = stYielded
r := t.result
evs = append(evs, Event{Kind: KindToolResult, ToolResult: &r})
continue
}
t.status = stYielded
t.result = llm.ToolResultText(t.block.ID, msg, true)
r := t.result
evs = append(evs, Event{Kind: KindToolResult, ToolResult: &r})
}
e.mu.Unlock()
for _, ev := range evs {
if !e.l.emit(ev) {
return false
}
}
return true
}
// results returns one tool_result per tool in arrival order (synthesizing for
// any that never finished).
func (e *streamExec) results() []llm.ContentBlock {
e.mu.Lock()
defer e.mu.Unlock()
out := make([]llm.ContentBlock, len(e.tools))
for i, t := range e.tools {
if t.status == stCompleted || t.status == stYielded {
out[i] = t.result
} else {
out[i] = llm.ToolResultText(t.block.ID, "tool execution interrupted", true)
}
}
return out
}
// extraMessages returns, in tool arrival order, the extra messages tools chose
// to inject after their tool_result (Result.Extra). Empty for the common case
// where no tool injects anything.
func (e *streamExec) extraMessages() []llm.Message {
e.mu.Lock()
defer e.mu.Unlock()
var out []llm.Message
for _, t := range e.tools {
if (t.status == stCompleted || t.status == stYielded) && len(t.extra) > 0 {
out = append(out, t.extra...)
}
}
return out
}
func (e *streamExec) count() int {
e.mu.Lock()
defer e.mu.Unlock()
return len(e.tools)
}
+107
View File
@@ -0,0 +1,107 @@
package harness
import (
"context"
"encoding/json"
"iter"
"sync/atomic"
"testing"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// TestStreamingToolExecutionOverlapsStream proves FR-01.4: a read-only,
// concurrency-safe tool begins executing as soon as its tool_use block finishes
// streaming, while the rest of the assistant message is still being produced.
//
// The scripted model emits tool A, then tool B (whose start finalizes A and
// dispatches it), then BLOCKS — refusing to finish the message until A has
// actually run. If tools only ran after the stream completed, this would
// deadlock; the test's timeout would then fire.
func TestStreamingToolExecutionOverlapsStream(t *testing.T) {
ran := make(chan string, 4)
probe := tool.Build(tool.Spec{
Name: "probe",
Schema: map[string]any{
"type": "object",
"properties": map[string]any{"id": map[string]any{"type": "string"}},
},
ReadOnly: func(json.RawMessage) bool { return true },
Concurrent: func(json.RawMessage) bool { return true },
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.Allowed()
},
Run: func(_ context.Context, in json.RawMessage, _ *tool.ToolContext) (tool.Result, error) {
var v struct {
ID string `json:"id"`
}
json.Unmarshal(in, &v)
ran <- v.ID
return tool.Text("ok"), nil
},
})
var turn int32
callModel := func(_ context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
n := atomic.AddInt32(&turn, 1)
return func(yield func(llm.StreamEvent, error) bool) {
if n > 1 { // second turn: finish.
yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "done"}, nil)
yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil)
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
return
}
yield(llm.StreamEvent{Type: llm.SEToolUseStart, ToolID: "a", ToolName: "probe"}, nil)
yield(llm.StreamEvent{Type: llm.SEToolInputJSON, Text: `{"id":"a"}`}, nil)
// Starting B finalizes A, so A is dispatched and runs concurrently.
yield(llm.StreamEvent{Type: llm.SEToolUseStart, ToolID: "b", ToolName: "probe"}, nil)
yield(llm.StreamEvent{Type: llm.SEToolInputJSON, Text: `{"id":"b"}`}, nil)
// Refuse to finish the message until A has actually executed.
for v := range ran {
if v == "a" {
break
}
}
yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "tool_use"}, nil)
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(probe),
PermissionMode: permission.ModeBypass,
}
done := make(chan *Terminal, 1)
go func() {
var term *Terminal
for ev, err := range Query(context.Background(), in, QueryDeps{CallModel: callModel}) {
if err != nil {
t.Errorf("event err: %v", err)
break
}
if ev.Kind == KindResult {
term = ev.Terminal
}
}
done <- term
}()
select {
case term := <-done:
if term == nil || term.Reason != ReasonCompleted {
t.Fatalf("terminal=%+v", term)
}
// Both probes produced tool_results, paired in order.
results := term.Messages[2].Content
if len(results) != 2 || results[0].ToolUseID != "a" || results[1].ToolUseID != "b" {
t.Fatalf("results=%+v", results)
}
case <-time.After(3 * time.Second):
t.Fatal("deadlock: tool did not execute during streaming (FR-01.4 regression)")
}
}
+70
View File
@@ -0,0 +1,70 @@
package harness
import (
"strings"
"testing"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// A pending background-task completion is drained into the conversation and the
// loop takes one extra turn so the model can react to it.
func TestTaskNotificationInjected(t *testing.T) {
mgr, err := tool.NewManager("harness-notify-test")
if err != nil {
t.Fatalf("NewManager: %v", err)
}
defer mgr.Cleanup()
task, err := mgr.Spawn(tool.SpawnSpec{Command: "echo hi"})
if err != nil {
t.Fatalf("Spawn: %v", err)
}
mgr.Background(task.ID)
// Wait until the task finishes and its notification is queued.
deadline := time.Now().Add(5 * time.Second)
for {
if info, ok := mgr.Get(task.ID); ok && info.Status.Terminal() {
break
}
if time.Now().After(deadline) {
t.Fatal("task did not finish")
}
time.Sleep(10 * time.Millisecond)
}
// Model: first turn produces no tools (loop should inject the notification and
// continue); second turn completes.
m := &scriptedModel{turns: [][]llm.StreamEvent{
textTurn("first"),
textTurn("done"),
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewBash()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
Tasks: mgr,
}
term := drain(t, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonCompleted || term.Text != "done" {
t.Fatalf("terminal=%+v", term)
}
if m.calls != 2 {
t.Fatalf("expected the loop to take an extra turn for the notification, calls=%d", m.calls)
}
var found bool
for _, msg := range term.Messages {
if strings.Contains(msg.Text(), "<task-notification>") && strings.Contains(msg.Text(), task.OutputPath) {
found = true
}
}
if !found {
t.Fatal("no task-notification injected into the conversation")
}
}
+105
View File
@@ -0,0 +1,105 @@
package harness
import (
"context"
"strings"
"testing"
"time"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// drainWithCtx is drain() over a caller-supplied ctx, so a test can cancel the
// parent (pause/kill/shutdown) independently of the run's own MaxDuration budget.
func drainWithCtx(t *testing.T, ctx context.Context, in QueryInput, deps QueryDeps) *Terminal {
t.Helper()
var term *Terminal
for ev, err := range Query(ctx, in, deps) {
if err != nil {
t.Fatalf("event err: %v", err)
}
if ev.Kind == KindResult {
term = ev.Terminal
}
}
if term == nil {
t.Fatal("no terminal event")
}
return term
}
// When a tool overruns the MaxDuration wall-clock budget, the tool is interrupted
// at the deadline and the run enters the WRAP-UP phase (settlement) on the live
// ctx — finishing with ReasonTimeout and the wrap-up prompt injected — instead of
// dying with ReasonAbortedTools. This is the hung/slow-tool case that the old
// turn-boundary-only budget check could never settle.
func TestSettlementOnToolOverrunsBudget(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("s1", "sleep", `{"seconds":3600}`), // hangs far past MaxDuration
textTurn("已写回事实并总结"), // settlement turn → natural stop
}}
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewSleep()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
MaxDuration: 100 * time.Millisecond, // budget the run so the sleep overruns it
Settlement: &Settlement{Prompt: "SETTLE_ON_TIMEOUT 请写回事实"},
}
term := drainWithCtx(t, context.Background(), in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonTimeout {
t.Fatalf("reason=%v, want ReasonTimeout(工具超墙→就地收尾,非 aborted_tools)", term.Reason)
}
found := false
for _, msg := range term.Messages {
for _, c := range msg.Content {
if strings.Contains(c.Text, "SETTLE_ON_TIMEOUT") {
found = true
}
}
}
if !found {
t.Fatalf("超墙收尾提示未被注入到对话")
}
if m.calls != 2 {
t.Fatalf("应有 2 次模型调用(主+收尾),得 %d", m.calls)
}
}
// Regression guard: a PARENT-ctx cancellation (pause / planner kill / shutdown) —
// as opposed to the run's own budget — still aborts with ReasonAbortedTools and
// does NOT enter the wrap-up phase.
func TestParentCancelStillAbortsNoSettlement(t *testing.T) {
m := &scriptedModel{turns: [][]llm.StreamEvent{
toolTurn("s1", "sleep", `{"seconds":3600}`),
textTurn("would-be settlement"), // must NOT be reached
}}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
in := QueryInput{
Messages: []llm.Message{llm.UserText("go")},
Tools: tool.NewRegistry(tool.NewSleep()),
PermissionMode: permission.ModeBypass,
WorkingDir: t.TempDir(),
// no MaxDuration: the only deadline is the parent ctx above
Settlement: &Settlement{Prompt: "SHOULD_NOT_APPEAR"},
}
term := drainWithCtx(t, ctx, in, QueryDeps{CallModel: m.call})
if term.Reason != ReasonAbortedTools {
t.Fatalf("reason=%v, want ReasonAbortedTools(父 ctx 取消=真中断,不收尾)", term.Reason)
}
for _, msg := range term.Messages {
for _, c := range msg.Content {
if strings.Contains(c.Text, "SHOULD_NOT_APPEAR") {
t.Fatalf("父 ctx 取消时不应进入收尾,却注入了收尾提示")
}
}
}
if m.calls != 1 {
t.Fatalf("父取消后不应再调用模型收尾,模型调用数=%d,want 1", m.calls)
}
}
+96
View File
@@ -0,0 +1,96 @@
package harness
import (
"context"
"strings"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/tool"
)
func asst(text string) llm.Message {
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock(text)}}
}
func todoWriteAsst() llm.Message {
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{
{Type: llm.BlockToolUse, ID: "t1", Name: "TodoWrite", Input: []byte(`{}`)},
}}
}
func TestTodoReminderTurnCounts(t *testing.T) {
msgs := []llm.Message{
llm.UserText("go"),
todoWriteAsst(), // the write turn — not counted
{Role: llm.RoleUser, Content: []llm.ContentBlock{llm.ToolResultText("t1", "ok", false)}},
asst("thinking about it"), // +1 since write
llm.UserText("more"),
asst("still working"), // +1 since write
}
sinceWrite, sinceReminder := todoReminderTurnCounts(msgs)
if sinceWrite != 2 {
t.Fatalf("sinceWrite=%d, want 2", sinceWrite)
}
// No reminder in history → counts every assistant turn (3: two text + the write turn).
if sinceReminder != 3 {
t.Fatalf("sinceReminder=%d, want 3", sinceReminder)
}
// Insert a reminder; sinceReminder should count only assistant turns after it.
withReminder := append([]llm.Message{}, msgs...)
withReminder = append(withReminder, llm.TodoReminderMessage("1. [pending] x"), asst("after reminder"))
_, sinceReminder = todoReminderTurnCounts(withReminder)
if sinceReminder != 1 {
t.Fatalf("sinceReminder after a reminder=%d, want 1", sinceReminder)
}
}
func TestMaybeInjectTodoReminder(t *testing.T) {
store := tool.NewTodoStore()
// Disabled / empty list → never injects.
l := &loop{in: QueryInput{}}
l.maybeInjectTodoReminder()
if len(l.messages) != 0 {
t.Fatal("no injection when Todos is nil")
}
l = &loop{in: QueryInput{Todos: store}}
l.maybeInjectTodoReminder()
if len(l.messages) != 0 {
t.Fatal("no injection for an empty todo list")
}
// Seed a list; 10 assistant turns with no TodoWrite → injects.
store.Tool().Call(context.Background(), []byte(`{"todos":[{"content":"build","status":"in_progress"}]}`), &tool.ToolContext{})
l = &loop{in: QueryInput{Todos: store}}
for i := 0; i < 10; i++ {
l.messages = append(l.messages, asst("work"))
}
l.maybeInjectTodoReminder()
if len(l.messages) != 11 || !llm.IsTodoReminder(l.messages[10]) {
t.Fatalf("expected a todo reminder appended, got %d msgs", len(l.messages))
}
if !strings.Contains(l.messages[10].Text(), "build") {
t.Fatalf("reminder should carry the current list: %q", l.messages[10].Text())
}
// Immediately calling again → sinceReminder=0 < gap → no second injection.
l.maybeInjectTodoReminder()
if len(l.messages) != 11 {
t.Fatal("should not inject a second reminder within the throttle gap")
}
}
func TestMaybeInjectTodoReminderSkipsAfterRecentWrite(t *testing.T) {
store := tool.NewTodoStore()
store.Tool().Call(context.Background(), []byte(`{"todos":[{"content":"x","status":"pending"}]}`), &tool.ToolContext{})
l := &loop{in: QueryInput{Todos: store}}
// Recent TodoWrite (only 2 turns ago) → sinceWrite < 10 → no injection.
l.messages = []llm.Message{todoWriteAsst(), asst("a"), asst("b")}
l.maybeInjectTodoReminder()
if len(l.messages) != 3 {
t.Fatalf("should not inject shortly after a TodoWrite, got %d msgs", len(l.messages))
}
}
+133
View File
@@ -0,0 +1,133 @@
package harness
import (
"encoding/json"
"fmt"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// rawInputTool is the optional opt-out from schema validation. Discovered by
// assertion rather than declared on tool.CoreTool, so hosts implementing that
// interface are unaffected.
type rawInputTool interface{ AcceptsRawInput() bool }
func acceptsRawInput(t tool.CoreTool) bool {
r, ok := t.(rawInputTool)
return ok && r.AcceptsRawInput()
}
// execOne resolves, permission-checks, and runs a single tool call, returning a
// tool_result block and any extra messages the tool injects after its result
// (Result.Extra — e.g. the Skill tool's instructions message). It never panics;
// failures become error results. It is safe to call from the streaming
// executor's goroutines (read-only access to loop config; permission/hook
// callbacks are the host's responsibility to make safe).
func (l *loop) execOne(use llm.ContentBlock, emitProgress func(tool.ProgressInfo)) (llm.ContentBlock, []llm.Message) {
t, ok := l.in.Tools.Get(use.Name)
if !ok {
return llm.ToolResultText(use.ID, fmt.Sprintf("Error: unknown tool %q", use.Name), true), nil
}
input := use.Input
// Schema validation (FR-04.5).
//
// A tool may opt out by reporting AcceptsRawInput: it parses its own
// arguments and would rather repair a malformed call than have it rejected
// here, where the only possible answer is a generic error. The schema is
// still advertised to the model either way — see tool.Spec.RawInput.
if !acceptsRawInput(t) {
if err := tool.ValidateInput(t.InputSchema(), input); err != nil {
return llm.ToolResultText(use.ID, "Error: invalid tool input: "+err.Error(), true), nil
}
}
mode := l.in.PermissionMode
if l.in.PermissionModeFunc != nil {
mode = l.in.PermissionModeFunc()
}
pc := permission.Context{
Mode: mode,
WorkingDir: l.in.WorkingDir,
Allowed: l.in.Allowed,
Disallowed: l.in.Disallowed,
}
dec := permission.Evaluate(l.ctx, permission.Request{
ToolName: use.Name,
Input: input,
IsReadOnly: t.IsReadOnly(input),
ToolDecision: t.CheckPermissions(l.ctx, input, pc),
Ctx: pc,
Ask: l.in.CanUseTool,
})
if dec.Behavior != permission.Allow {
msg := dec.Message
if msg == "" {
msg = "denied"
}
return llm.ToolResultText(use.ID, "Tool call was not permitted: "+msg, true), nil
}
if len(dec.UpdatedInput) > 0 {
input = dec.UpdatedInput
}
// Pre-tool hook.
if l.in.Hooks != nil {
if block, msg, updated := l.in.Hooks.PreToolUse(l.ctx, use.Name, input); block {
return llm.ToolResultText(use.ID, "Blocked by hook: "+msg, true), nil
} else if len(updated) > 0 {
input = updated
}
}
tc := &tool.ToolContext{
WorkingDir: l.in.WorkingDir,
AgentID: l.in.AgentID,
ToolUseID: use.ID,
Emit: emitProgress,
OutputDir: l.in.ToolOutputDir,
MaxOutputChars: l.in.MaxToolOutputChars,
Tasks: l.in.Tasks,
Env: l.in.BashEnv,
}
// toolCtx carries the run's MaxDuration deadline, so a tool that overruns the
// wall-clock budget is interrupted here (the turn loop then enters wrap-up). During
// the wrap-up phase toolCtx is the live parent ctx, so settlement tools run freely.
res, err := t.Call(l.toolCtx, input, tc)
if err != nil {
res = tool.Errorf("Error: " + err.Error())
}
// Global output cap at the single post-tool choke point: EVERY tool —
// built-in, MCP, custom, host — is bounded here regardless of whether it
// remembered to Capture itself, so no tool can overflow the context window
// (the failure mode that motivated this net). CaptureOnce is idempotent:
// output a tool already spilled/truncated carries a marker and is left
// untouched, so this never double-truncates or double-spills.
res = capOutput(tc, res)
if l.in.Hooks != nil {
raw, _ := json.Marshal(res.Flatten())
l.in.Hooks.PostToolUse(l.ctx, use.Name, input, raw, res.IsError)
}
content := res.Content
if len(content) == 0 {
content = []llm.ContentBlock{llm.TextBlock("(no output)")}
}
return llm.ContentBlock{Type: llm.BlockToolResult, ToolUseID: use.ID, Content: content, IsError: res.IsError}, res.Extra
}
// capOutput runs every text block of a tool result through the idempotent
// output cap (tool.CaptureOnce). Non-text blocks pass through untouched. It is
// the one place that guarantees no tool's output — however constructed — can
// blow past the context budget.
func capOutput(tc *tool.ToolContext, res tool.Result) tool.Result {
for i, b := range res.Content {
if b.Type == llm.BlockText {
res.Content[i].Text = tool.CaptureOnce(tc, b.Text)
}
}
return res
}