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

+130
View File
@@ -0,0 +1,130 @@
// Package coordinator implements coordinator mode: a top-level agent that
// decomposes work and delegates each unit to isolated "worker" subagents
// instead of doing the work itself. It offers two paths:
// an LLM-driven one (expose AgentTool + SystemSegment so the model spawns
// workers via the Agent tool) and a programmatic one (RunParallel fans tasks
// out to workers concurrently and returns their results).
package coordinator
import (
"context"
"strings"
"sync"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/subagent"
"github.com/Autumn-27/norma/tool"
)
// DefaultWorkerPrompt is the default system prompt for worker subagents.
const DefaultWorkerPrompt = `You are a worker agent spawned by a coordinator. Complete the task described in the prompt thoroughly and report back a concise summary of what you did and found.
Guidelines:
- Complete the task fully — don't leave it half-done, but don't gold-plate either.
- Use tools proactively: read files, search code, run commands, edit files.
- Be thorough in research: check multiple locations and naming conventions.
- For implementation: make targeted changes and run tests to verify.
- Report back with actionable findings — the coordinator will synthesize your results.
- If you hit errors, investigate and try to fix them before reporting failure.`
// Config configures coordinator mode.
type Config struct {
Provider llm.Provider
WorkerTools *tool.Registry // tools available to workers (e.g. the core toolset)
WorkerPrompt []string // worker system prompt (default DefaultWorkerPrompt)
PermissionMode permission.Mode // workers' permission mode (default acceptEdits)
WorkingDir string
MaxTurns int // per-worker turn cap
MaxDepth int // subagent recursion cap (default 3)
MaxParallel int // bounded concurrency for RunParallel (default 4)
CanUseTool permission.CanUseTool
Hooks harness.HookRunner
}
func (c *Config) workerPrompt() []string {
if len(c.WorkerPrompt) > 0 {
return c.WorkerPrompt
}
return []string{DefaultWorkerPrompt}
}
func (c *Config) mode() permission.Mode {
if c.PermissionMode != "" {
return c.PermissionMode
}
return permission.ModeAcceptEdits
}
// subagentConfig wires a subagent.Config with a single "worker" definition.
func (c *Config) subagentConfig() subagent.Config {
return subagent.Config{
Provider: c.Provider,
ParentTools: c.WorkerTools,
MaxDepth: c.MaxDepth,
CanUseTool: c.CanUseTool,
Hooks: c.Hooks,
Agents: map[string]subagent.Definition{
"worker": {
Description: "Executes a research, implementation, or verification task autonomously and reports back.",
Prompt: c.workerPrompt(),
PermissionMode: c.mode(),
MaxTurns: c.MaxTurns,
},
},
}
}
// AgentTool returns the Agent tool the coordinator LLM uses to spawn workers.
// Add it (and nothing else mutating) to the coordinator session's tools.
func (c *Config) AgentTool() tool.CoreTool {
return subagent.NewTool(c.subagentConfig())
}
// SystemSegment returns coordinator guidance to append to the system prompt.
func (c *Config) SystemSegment() string {
var names []string
if c.WorkerTools != nil {
for _, t := range c.WorkerTools.List() {
names = append(names, t.Name())
}
}
return "# Coordinator mode\n" +
"You orchestrate work by delegating to worker subagents — you do NOT implement directly. " +
"Break the request into independent units and spawn a worker for each via the Agent tool " +
"(agent_type \"worker\"), then synthesize their reports into a final answer. " +
"Prefer parallel, independent units. Workers have these tools: " + strings.Join(names, ", ") + "."
}
// Result is the outcome of one programmatic worker run.
type Result struct {
Task string
Output string
Err error
}
// RunParallel fans tasks out to workers concurrently (bounded by MaxParallel)
// and returns results in task order.
func (c *Config) RunParallel(ctx context.Context, tasks []string) []Result {
cfg := c.subagentConfig()
results := make([]Result, len(tasks))
limit := c.MaxParallel
if limit <= 0 {
limit = 4
}
sem := make(chan struct{}, limit)
var wg sync.WaitGroup
for i, task := range tasks {
wg.Add(1)
sem <- struct{}{}
go func(i int, task string) {
defer wg.Done()
defer func() { <-sem }()
out, err := subagent.Run(ctx, cfg, "worker", task, c.WorkingDir)
results[i] = Result{Task: task, Output: out, Err: err}
}(i, task)
}
wg.Wait()
return results
}
+92
View File
@@ -0,0 +1,92 @@
package coordinator
import (
"context"
"iter"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
"github.com/Autumn-27/norma/tool"
)
// echoProvider answers each worker with text derived from the task's last user
// message, so we can verify distinct workers ran.
type echoProvider struct{ count int32 }
func (p *echoProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
atomic.AddInt32(&p.count, 1)
last := ""
if n := len(req.Messages); n > 0 {
last = req.Messages[n-1].Text()
}
return func(yield func(llm.StreamEvent, error) bool) {
yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "did: " + last}, nil)
yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil)
yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil)
}
}
func (p *echoProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
return accumulateStream(ctx, p, req)
}
// accumulateStream drains a provider's own Stream to satisfy the non-streaming
// Complete method for test mocks.
func accumulateStream(ctx context.Context, p llm.Provider, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
acc := llm.NewAccumulator()
for ev, err := range p.Stream(ctx, req) {
if err != nil {
return llm.Message{}, "", llm.Usage{}, err
}
acc.Add(ev)
}
return acc.Message(), acc.StopReason, acc.Usage, nil
}
func TestRunParallelFansOut(t *testing.T) {
prov := &echoProvider{}
c := &Config{
Provider: prov,
WorkerTools: tool.NewRegistry(tool.DefaultTools()...),
PermissionMode: permission.ModeBypass,
}
tasks := []string{"task A", "task B", "task C"}
results := c.RunParallel(context.Background(), tasks)
if len(results) != 3 {
t.Fatalf("results=%d", len(results))
}
for i, r := range results {
if r.Err != nil {
t.Fatalf("task %d err: %v", i, r.Err)
}
if !strings.Contains(r.Output, tasks[i]) {
t.Fatalf("result %d mismatched: task=%q output=%q", i, tasks[i], r.Output)
}
}
if atomic.LoadInt32(&prov.count) != 3 {
t.Fatalf("expected 3 worker runs, got %d", prov.count)
}
}
func TestAgentToolAndSystemSegment(t *testing.T) {
c := &Config{
Provider: &echoProvider{},
WorkerTools: tool.NewRegistry(tool.NewRead(), tool.NewBash()),
}
at := c.AgentTool()
if at.Name() != "Agent" {
t.Fatalf("agent tool name=%q", at.Name())
}
seg := c.SystemSegment()
if !strings.Contains(seg, "Coordinator mode") || !strings.Contains(seg, "Read") || !strings.Contains(seg, "Bash") {
t.Fatalf("system segment missing pieces:\n%s", seg)
}
// The Agent tool actually dispatches a worker.
res, _ := at.Call(context.Background(), []byte(`{"agent_type":"worker","prompt":"find bugs"}`), &tool.ToolContext{})
if !strings.Contains(res.Flatten(), "find bugs") {
t.Fatalf("worker dispatch: %q", res.Flatten())
}
}