refactor(agentexec): model loop moves to agentexec/modelloop
agentexec's wire contract, harness adapters and log forwarding no longer import the AI SDK; the in-process model loop, runtime, tool set and sampling helpers that do now live in agentexec/modelloop, used by the Gateway and archie-agent only.
This commit is contained in:
22 files changed
+187
-170
No files matched your search
@@ -25,17 +25,17 @@ type captureRecord struct {
|
||||
Args json.RawMessage `json:"args"`
|
||||
}
|
||||
|
||||
// acceptCapture decides whether one capture call is kept. Both the built-in
|
||||
// AcceptCapture decides whether one capture call is kept. Both the built-in
|
||||
// loop and the harness path use it, and the harness path applies it twice:
|
||||
// in the MCP server, and again when the worker reads the captures back.
|
||||
func acceptCapture(spec agentrun.CaptureTool, accepted int, value json.RawMessage) (string, bool) {
|
||||
func AcceptCapture(spec agentrun.CaptureTool, accepted int, value json.RawMessage) (string, bool) {
|
||||
if spec.MaxCalls > 0 && accepted >= spec.MaxCalls {
|
||||
return fmt.Sprintf("%s rejected: maximum call count is %d", spec.Name, spec.MaxCalls), false
|
||||
}
|
||||
if !json.Valid(value) {
|
||||
return spec.Name + " rejected: arguments are not valid JSON", false
|
||||
}
|
||||
if rejection, ok := validateCaptureArgs(spec, value); !ok {
|
||||
if rejection, ok := ValidateCaptureArgs(spec, value); !ok {
|
||||
return rejection, false
|
||||
}
|
||||
return spec.Name + " recorded", true
|
||||
@@ -58,7 +58,7 @@ func ServeCaptureMCP(ctx context.Context, specs []agentrun.CaptureTool, sink io.
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
args := append(json.RawMessage(nil), req.Params.Arguments...)
|
||||
reply, ok := acceptCapture(spec, accepted[spec.Name], args)
|
||||
reply, ok := AcceptCapture(spec, accepted[spec.Name], args)
|
||||
if ok {
|
||||
line, err := json.Marshal(captureRecord{Tool: spec.Name, Args: args})
|
||||
if err != nil {
|
||||
@@ -103,7 +103,7 @@ func readCaptures(path string, specs []agentrun.CaptureTool) (map[string][]json.
|
||||
if !declared {
|
||||
continue
|
||||
}
|
||||
if _, ok := acceptCapture(spec, len(captures[rec.Tool]), rec.Args); ok {
|
||||
if _, ok := AcceptCapture(spec, len(captures[rec.Tool]), rec.Args); ok {
|
||||
captures[rec.Tool] = append(captures[rec.Tool], rec.Args)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.Tool
|
||||
delete(o.pending, block.ToolUseID)
|
||||
if report != nil {
|
||||
report(agentrun.ToolCallReport{
|
||||
Tool: tool, Detail: clipToolCallDetail(claudeResultContent(block.Content)),
|
||||
Tool: tool, Detail: ClipToolCallDetail(claudeResultContent(block.Content)),
|
||||
Failed: block.IsError,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ func (item codexItem) report() (agentrun.ToolCallReport, bool) {
|
||||
default:
|
||||
return agentrun.ToolCallReport{}, false
|
||||
}
|
||||
call.Detail = clipToolCallDetail(call.Detail)
|
||||
call.Detail = ClipToolCallDetail(call.Detail)
|
||||
return call, true
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporte
|
||||
}
|
||||
delete(o.pending, event.Data.ToolCallID)
|
||||
if report != nil {
|
||||
report(agentrun.ToolCallReport{Tool: tool, Detail: clipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
|
||||
report(agentrun.ToolCallReport{Tool: tool, Detail: ClipToolCallDetail(event.Data.Result.Content), Failed: !event.Data.Success})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) {
|
||||
texts = append(texts, block.Text)
|
||||
}
|
||||
}
|
||||
report(agentrun.ToolCallReport{Tool: event.ToolName, Detail: clipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
|
||||
report(agentrun.ToolCallReport{Tool: event.ToolName, Detail: ClipToolCallDetail(strings.Join(texts, "\n")), Failed: event.IsError})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -277,7 +277,7 @@ func harnessPrompt(workspace string, req agentrun.Request) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(req.Mission)
|
||||
b.WriteString("\n\n## Rules\n\n")
|
||||
b.WriteString(projectScopedRules(workspace, req.ExtraRules))
|
||||
b.WriteString(ProjectScopedRules(workspace, req.ExtraRules))
|
||||
b.WriteString("\nDo not run git commands that change history, refs or configuration. Archie commits your changes.")
|
||||
if req.ReadOnly {
|
||||
b.WriteString("\nThis stage is read-only. Do not create, modify or delete any file.")
|
||||
@@ -444,7 +444,7 @@ func policyViolation(before, after repoState, changes []string, req agentrun.Req
|
||||
if req.ReadOnly && len(changes) > 0 {
|
||||
return "the harness wrote in a read-only stage: " + strings.Join(changes, ", ")
|
||||
}
|
||||
if protected := protectionMatcher(req.Protection, false); protected != nil {
|
||||
if protected := ProtectionMatcher(req.Protection, false); protected != nil {
|
||||
var hit []string
|
||||
for _, path := range changes {
|
||||
if protected(path) {
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package agentexec
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
)
|
||||
|
||||
// toolCallDetailBytes caps the summary ToolCallReport.Detail carries. This
|
||||
// rides on every task's observability event stream, so one large file read
|
||||
// must not dominate it the way baselineMissionBytes-sized content is allowed
|
||||
// to dominate a builder's own context.
|
||||
const toolCallDetailBytes = 300
|
||||
|
||||
func ClipToolCallDetail(s string) string {
|
||||
if len(s) <= toolCallDetailBytes {
|
||||
return s
|
||||
}
|
||||
return s[:toolCallDetailBytes] + "…"
|
||||
}
|
||||
|
||||
func ProjectScopedRules(workspace, extra string) string {
|
||||
rule := "Confine discovery to " + workspace + ". Do not inspect home directories, dependency/module caches, or unrelated projects unless the mission explicitly requests that external path."
|
||||
if strings.TrimSpace(extra) == "" {
|
||||
return rule
|
||||
}
|
||||
return rule + "\n" + extra
|
||||
}
|
||||
|
||||
func ProtectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool {
|
||||
if readOnly || len(p.Suffixes)+len(p.Globs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func(path string) bool {
|
||||
for _, suffix := range p.Suffixes {
|
||||
if strings.HasSuffix(path, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, glob := range p.Globs {
|
||||
matchPath := path
|
||||
if !strings.ContainsAny(glob, `/\`) {
|
||||
matchPath = filepath.Base(path)
|
||||
}
|
||||
if matched, err := filepath.Match(glob, matchPath); err == nil && matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateCaptureArgs checks that the capture tool arguments satisfy all
|
||||
// constraints. Returns a rejection message and false on failure, or "" and
|
||||
// true on success. Each constraint is its own check so adding one does not
|
||||
// grow a single branching function.
|
||||
func ValidateCaptureArgs(spec agentrun.CaptureTool, value json.RawMessage) (string, bool) {
|
||||
var object map[string]json.RawMessage
|
||||
if err := json.Unmarshal(value, &object); err != nil {
|
||||
return spec.Name + " rejected: arguments must be a JSON object", false //nolint:nilerr // the agent loop must see malformed tool arguments as feedback it can correct, not as a failed tool call
|
||||
}
|
||||
for _, check := range []func(agentrun.CaptureTool, map[string]json.RawMessage) (string, bool){
|
||||
checkRequiredFields,
|
||||
checkNonEmptyStrings,
|
||||
checkBooleanFields,
|
||||
checkRequiredWhenTrue,
|
||||
} {
|
||||
if rejection, ok := check(spec, object); !ok {
|
||||
return rejection, false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkRequiredFields(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.RequiredFields {
|
||||
if _, ok := object[field]; !ok {
|
||||
return fmt.Sprintf("%s rejected: %s is required", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkNonEmptyStrings(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.NonEmptyStrings {
|
||||
if !isNonEmptyString(object, field) {
|
||||
return fmt.Sprintf("%s rejected: %s must be a non-empty string", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkBooleanFields(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.BooleanFields {
|
||||
var val bool
|
||||
if raw, ok := object[field]; !ok || json.Unmarshal(raw, &val) != nil {
|
||||
return fmt.Sprintf("%s rejected: %s must be a boolean", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// checkRequiredWhenTrue enforces the conditional requirements. Triggers are
|
||||
// visited in sorted order so a call violating two of them names the same one
|
||||
// every run, rather than a different one on each retry.
|
||||
func checkRequiredWhenTrue(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, trigger := range slices.Sorted(maps.Keys(spec.RequiredWhenTrue)) {
|
||||
var on bool
|
||||
if raw, ok := object[trigger]; !ok || json.Unmarshal(raw, &on) != nil || !on {
|
||||
continue
|
||||
}
|
||||
for _, field := range spec.RequiredWhenTrue[trigger] {
|
||||
if !isNonEmptyString(object, field) {
|
||||
return fmt.Sprintf("%s rejected: %s is required when %s is true", spec.Name, field, trigger), false
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func isNonEmptyString(object map[string]json.RawMessage, field string) bool {
|
||||
var text string
|
||||
raw, ok := object[field]
|
||||
return ok && json.Unmarshal(raw, &text) == nil && strings.TrimSpace(text) != ""
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package agentexec
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/agentloop"
|
||||
@@ -88,7 +89,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
|
||||
ModelRef: req.Model,
|
||||
WorkDir: workspace,
|
||||
Mission: req.Mission,
|
||||
ExtraRules: projectScopedRules(workspace, req.ExtraRules),
|
||||
ExtraRules: agentexec.ProjectScopedRules(workspace, req.ExtraRules),
|
||||
Notes: notes,
|
||||
Gate: toAgentGate(req.Gate),
|
||||
Preflight: toAgentCommands(req.Preflight),
|
||||
@@ -104,7 +105,7 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Req
|
||||
},
|
||||
Completion: agentloop.CompletionForceFinish,
|
||||
ReadOnly: req.ReadOnly,
|
||||
ProtectPaths: protectionMatcher(req.Protection, req.ReadOnly),
|
||||
ProtectPaths: agentexec.ProtectionMatcher(req.Protection, req.ReadOnly),
|
||||
Extra: mergeToolSets(
|
||||
allowedTools(centralTools, r.AllowTools),
|
||||
captureTools,
|
||||
@@ -153,14 +154,6 @@ func resultFromRun(req agentrun.Request, res agentloop.Result, appended []string
|
||||
return result
|
||||
}
|
||||
|
||||
func projectScopedRules(workspace, extra string) string {
|
||||
rule := "Confine discovery to " + workspace + ". Do not inspect home directories, dependency/module caches, or unrelated projects unless the mission explicitly requests that external path."
|
||||
if strings.TrimSpace(extra) == "" {
|
||||
return rule
|
||||
}
|
||||
return rule + "\n" + extra
|
||||
}
|
||||
|
||||
func pluginToolSet(req agentrun.Request, workspace string, occupied ...core.ToolSet) (core.ToolSet, error) {
|
||||
if req.ReadOnly || len(req.Protection.Suffixes)+len(req.Protection.Globs) > 0 || len(req.Gate.Commands) > 0 {
|
||||
return nil, nil
|
||||
@@ -222,29 +215,6 @@ func toAgentCommands(commands []agentrun.Command) []agentloop.GateCommand {
|
||||
return out
|
||||
}
|
||||
|
||||
func protectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool {
|
||||
if readOnly || len(p.Suffixes)+len(p.Globs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func(path string) bool {
|
||||
for _, suffix := range p.Suffixes {
|
||||
if strings.HasSuffix(path, suffix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, glob := range p.Globs {
|
||||
matchPath := path
|
||||
if !strings.ContainsAny(glob, `/\`) {
|
||||
matchPath = filepath.Base(path)
|
||||
}
|
||||
if matched, err := filepath.Match(glob, matchPath); err == nil && matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func captureToolSet(specs []agentrun.CaptureTool, captures map[string][]json.RawMessage) core.ToolSet {
|
||||
tools := make(core.ToolSet, len(specs))
|
||||
for _, spec := range specs {
|
||||
@@ -259,7 +229,7 @@ func captureToolSet(specs []agentrun.CaptureTool, captures map[string][]json.Raw
|
||||
func makeCaptureHandler(spec agentrun.CaptureTool, captures map[string][]json.RawMessage) func(context.Context, string) (string, error) {
|
||||
return func(_ context.Context, input string) (string, error) {
|
||||
value := json.RawMessage(input)
|
||||
reply, ok := acceptCapture(spec, len(captures[spec.Name]), value)
|
||||
reply, ok := agentexec.AcceptCapture(spec, len(captures[spec.Name]), value)
|
||||
if ok {
|
||||
captures[spec.Name] = append(captures[spec.Name], append(json.RawMessage(nil), value...))
|
||||
}
|
||||
@@ -267,80 +237,6 @@ func makeCaptureHandler(spec agentrun.CaptureTool, captures map[string][]json.Ra
|
||||
}
|
||||
}
|
||||
|
||||
// validateCaptureArgs checks that the capture tool arguments satisfy all
|
||||
// constraints. Returns a rejection message and false on failure, or "" and
|
||||
// true on success. Each constraint is its own check so adding one does not
|
||||
// grow a single branching function.
|
||||
func validateCaptureArgs(spec agentrun.CaptureTool, value json.RawMessage) (string, bool) {
|
||||
var object map[string]json.RawMessage
|
||||
if err := json.Unmarshal(value, &object); err != nil {
|
||||
return spec.Name + " rejected: arguments must be a JSON object", false //nolint:nilerr // the agent loop must see malformed tool arguments as feedback it can correct, not as a failed tool call
|
||||
}
|
||||
for _, check := range []func(agentrun.CaptureTool, map[string]json.RawMessage) (string, bool){
|
||||
checkRequiredFields,
|
||||
checkNonEmptyStrings,
|
||||
checkBooleanFields,
|
||||
checkRequiredWhenTrue,
|
||||
} {
|
||||
if rejection, ok := check(spec, object); !ok {
|
||||
return rejection, false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkRequiredFields(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.RequiredFields {
|
||||
if _, ok := object[field]; !ok {
|
||||
return fmt.Sprintf("%s rejected: %s is required", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkNonEmptyStrings(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.NonEmptyStrings {
|
||||
if !isNonEmptyString(object, field) {
|
||||
return fmt.Sprintf("%s rejected: %s must be a non-empty string", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func checkBooleanFields(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, field := range spec.BooleanFields {
|
||||
var val bool
|
||||
if raw, ok := object[field]; !ok || json.Unmarshal(raw, &val) != nil {
|
||||
return fmt.Sprintf("%s rejected: %s must be a boolean", spec.Name, field), false
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// checkRequiredWhenTrue enforces the conditional requirements. Triggers are
|
||||
// visited in sorted order so a call violating two of them names the same one
|
||||
// every run, rather than a different one on each retry.
|
||||
func checkRequiredWhenTrue(spec agentrun.CaptureTool, object map[string]json.RawMessage) (string, bool) {
|
||||
for _, trigger := range slices.Sorted(maps.Keys(spec.RequiredWhenTrue)) {
|
||||
var on bool
|
||||
if raw, ok := object[trigger]; !ok || json.Unmarshal(raw, &on) != nil || !on {
|
||||
continue
|
||||
}
|
||||
for _, field := range spec.RequiredWhenTrue[trigger] {
|
||||
if !isNonEmptyString(object, field) {
|
||||
return fmt.Sprintf("%s rejected: %s is required when %s is true", spec.Name, field, trigger), false
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
func isNonEmptyString(object map[string]json.RawMessage, field string) bool {
|
||||
var text string
|
||||
raw, ok := object[field]
|
||||
return ok && json.Unmarshal(raw, &text) == nil && strings.TrimSpace(text) != ""
|
||||
}
|
||||
|
||||
// scriptToolSet exposes run_go_script, which runs a Yaegi Go script from the
|
||||
// workspace and returns its output.
|
||||
func scriptToolSet(workspace string) core.ToolSet {
|
||||
@@ -1,4 +1,4 @@
|
||||
package agentexec
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
@@ -1,4 +1,4 @@
|
||||
package agentexec
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -1,4 +1,4 @@
|
||||
package agentexec
|
||||
package modelloop
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
|
||||
aicore "github.com/samcharles93/ai-sdk/core"
|
||||
@@ -76,19 +77,6 @@ type ToolSetOptions struct {
|
||||
OnToolCall agentrun.ToolCallReporter
|
||||
}
|
||||
|
||||
// toolCallDetailBytes caps the summary ToolCallReport.Detail carries. This
|
||||
// rides on every task's observability event stream, so one large file read
|
||||
// must not dominate it the way baselineMissionBytes-sized content is allowed
|
||||
// to dominate a builder's own context.
|
||||
const toolCallDetailBytes = 300
|
||||
|
||||
func clipToolCallDetail(s string) string {
|
||||
if len(s) <= toolCallDetailBytes {
|
||||
return s
|
||||
}
|
||||
return s[:toolCallDetailBytes] + "…"
|
||||
}
|
||||
|
||||
// reportToolCallCompletion notifies opts.OnToolCall, if set, of one
|
||||
// completed call. Factored out of toolExecute's closure so the branching
|
||||
// here doesn't add to that function's own cognitive-complexity budget.
|
||||
@@ -100,7 +88,7 @@ func reportToolCallCompletion(opts ToolSetOptions, entry tools.ToolEntry, result
|
||||
if err != nil {
|
||||
outcome = "error: " + err.Error()
|
||||
}
|
||||
opts.OnToolCall(agentrun.ToolCallReport{Tool: entry.Name, Detail: clipToolCallDetail(outcome), Failed: err != nil})
|
||||
opts.OnToolCall(agentrun.ToolCallReport{Tool: entry.Name, Detail: agentexec.ClipToolCallDetail(outcome), Failed: err != nil})
|
||||
}
|
||||
|
||||
// resultLimit returns the cap that applies to one entry.
|
||||
Reference in new issue
Block a user