diff --git a/internal/agentexec/capture_mcp.go b/internal/agentexec/capture_mcp.go index 3372b4f58..8e90d5896 100644 --- a/internal/agentexec/capture_mcp.go +++ b/internal/agentexec/capture_mcp.go @@ -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) } } diff --git a/internal/agentexec/harness_output_claude.go b/internal/agentexec/harness_output_claude.go index e52de18ed..a05d4a207 100644 --- a/internal/agentexec/harness_output_claude.go +++ b/internal/agentexec/harness_output_claude.go @@ -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, }) } diff --git a/internal/agentexec/harness_output_codex.go b/internal/agentexec/harness_output_codex.go index 332b90ccd..f21cf7b4c 100644 --- a/internal/agentexec/harness_output_codex.go +++ b/internal/agentexec/harness_output_codex.go @@ -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 } diff --git a/internal/agentexec/harness_output_copilot.go b/internal/agentexec/harness_output_copilot.go index 92128a055..2488ee861 100644 --- a/internal/agentexec/harness_output_copilot.go +++ b/internal/agentexec/harness_output_copilot.go @@ -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}) } } } diff --git a/internal/agentexec/harness_output_pi.go b/internal/agentexec/harness_output_pi.go index a82a803a1..a853c7816 100644 --- a/internal/agentexec/harness_output_pi.go +++ b/internal/agentexec/harness_output_pi.go @@ -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}) } } diff --git a/internal/agentexec/harness_runner.go b/internal/agentexec/harness_runner.go index 2422d59d8..62d633f63 100644 --- a/internal/agentexec/harness_runner.go +++ b/internal/agentexec/harness_runner.go @@ -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) { diff --git a/internal/agentexec/helpers.go b/internal/agentexec/helpers.go new file mode 100644 index 000000000..91cb52f3c --- /dev/null +++ b/internal/agentexec/helpers.go @@ -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) != "" +} diff --git a/internal/agentexec/loop_runner.go b/internal/agentexec/modelloop/loop_runner.go similarity index 71% rename from internal/agentexec/loop_runner.go rename to internal/agentexec/modelloop/loop_runner.go index 058b1a773..fc4fd6837 100644 --- a/internal/agentexec/loop_runner.go +++ b/internal/agentexec/modelloop/loop_runner.go @@ -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 { diff --git a/internal/agentexec/runtime.go b/internal/agentexec/modelloop/runtime.go similarity index 97% rename from internal/agentexec/runtime.go rename to internal/agentexec/modelloop/runtime.go index 847b40f37..db1930b3a 100644 --- a/internal/agentexec/runtime.go +++ b/internal/agentexec/modelloop/runtime.go @@ -1,4 +1,4 @@ -package agentexec +package modelloop import ( "github.com/samcharles93/ai-sdk/runtime" diff --git a/internal/agentexec/sampling.go b/internal/agentexec/modelloop/sampling.go similarity index 99% rename from internal/agentexec/sampling.go rename to internal/agentexec/modelloop/sampling.go index 698cb79d5..2b68d24c6 100644 --- a/internal/agentexec/sampling.go +++ b/internal/agentexec/modelloop/sampling.go @@ -1,4 +1,4 @@ -package agentexec +package modelloop import ( "errors" diff --git a/internal/agentexec/toolset.go b/internal/agentexec/modelloop/toolset.go similarity index 94% rename from internal/agentexec/toolset.go rename to internal/agentexec/modelloop/toolset.go index d235107a8..90cfea72e 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/modelloop/toolset.go @@ -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. diff --git a/internal/app/agentworker/mcp_sampling.go b/internal/app/agentworker/mcp_sampling.go index 246b34615..1e0af5d37 100644 --- a/internal/app/agentworker/mcp_sampling.go +++ b/internal/app/agentworker/mcp_sampling.go @@ -9,7 +9,7 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/tools/mcp" ) @@ -30,7 +30,7 @@ func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig) mcp.Sampli if model == "" { return mcp.SamplingResult{}, errors.New("mcp sampling: no builder model is configured") } - messages, err := agentexec.SamplingMessages(req) + messages, err := modelloop.SamplingMessages(req) if err != nil { return mcp.SamplingResult{}, err } @@ -39,7 +39,7 @@ func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig) mcp.Sampli Messages: messages, System: req.SystemPrompt, MaxSteps: 1, - MaxTokens: agentexec.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens, limits.Reasoning), + MaxTokens: modelloop.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens, limits.Reasoning), } if req.Temperature != nil { options.Temperature = float32(*req.Temperature) diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index d9858f39e..d22c866f7 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -10,6 +10,7 @@ import ( "path/filepath" "strconv" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/domain/agentrun" "github.com/samcharles93/ai-sdk/runtime" @@ -157,17 +158,17 @@ type taskDependencies struct { type runnerFactory func(map[string]agentrun.Provider, *slog.Logger) agentrun.Runner func newTaskRunner(providers map[string]agentrun.Provider, log *slog.Logger) agentrun.Runner { - return agentexec.NewLoopRunner(agentexec.NewRuntime(providers), log) + return modelloop.NewLoopRunner(modelloop.NewRuntime(providers), log) } // applyToolLimits sets the task's tool policy and allowlist on a // *LoopRunner. Other runners are untouched. func applyToolLimits(agent agentrun.Runner, policy config.ToolPolicy, allow []string) { - runner, ok := agent.(*agentexec.LoopRunner) + runner, ok := agent.(*modelloop.LoopRunner) if !ok { return } - runner.Limits = agentexec.ToolLimits{ + runner.Limits = modelloop.ToolLimits{ MaxResultChars: policy.MaxResultChars, SpillDir: policy.SpillDir, } @@ -184,7 +185,7 @@ func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerF } var agent agentrun.Runner if mcpSet != nil && mcpSet.registry != nil { - agent = agentexec.NewLoopRunner(llm, log, mcpSet.registry) + agent = modelloop.NewLoopRunner(llm, log, mcpSet.registry) } else { agent = newRunner(req.Providers, log) } @@ -231,7 +232,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // the task's own model rather than a second provider client. var llm *runtime.Runtime if len(req.MCPServers) > 0 { - llm = agentexec.NewRuntime(req.Providers) + llm = modelloop.NewRuntime(req.Providers) } mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, taskSamplingHandler(llm, req.Cfg), log) if mcpSet != nil { diff --git a/internal/app/archiegateway/chat_runtime.go b/internal/app/archiegateway/chat_runtime.go index 583ea77bf..f774dbe89 100644 --- a/internal/app/archiegateway/chat_runtime.go +++ b/internal/app/archiegateway/chat_runtime.go @@ -6,6 +6,7 @@ import ( "log/slog" "time" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/domain/agentrun" "github.com/samcharles93/ai-sdk/chat" @@ -91,7 +92,7 @@ func (b *server) rebuildChatModelRuntime(cfg config.Config) { if b.chatModels == nil { return // this process serves no chat turns } - b.setLLM(agentexec.NewRuntime(executionProviders(cfg))) + b.setLLM(modelloop.NewRuntime(executionProviders(cfg))) b.chatModels.SetConfigured(cfg.Models) catalog, models := b.catalogState() b.chatModels.SetModelCatalog(catalog, models) @@ -111,7 +112,7 @@ func chatGenerateOptions( messages []chat.Message, registry *tools.Registry, maxSteps int, - limits agentexec.ToolLimits, + limits modelloop.ToolLimits, extra []tools.ToolEntry, contextWindow int, ) (core.GenerateOptions, error) { @@ -132,7 +133,7 @@ func chatGenerateOptions( } gate := tools.NewContextPressureGate(contextWindow) gate.Evaluate(composed.All()) - toolSet, err := agentexec.BuildToolSetFrom(gate.FilterTools(composed), toolOpts) + toolSet, err := modelloop.BuildToolSetFrom(gate.FilterTools(composed), toolOpts) if err != nil { return core.GenerateOptions{}, err } diff --git a/internal/app/archiegateway/chat_setup.go b/internal/app/archiegateway/chat_setup.go index 7f27dd180..9cf00bdca 100644 --- a/internal/app/archiegateway/chat_setup.go +++ b/internal/app/archiegateway/chat_setup.go @@ -12,7 +12,7 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/events" @@ -33,7 +33,7 @@ type chatSetup struct { // ToolLimits resolves the tool-output policy at each turn, so a live // tool-settings update reaches the next chat turn's tool options rather // than the value captured when the runner was built. - ToolLimits func() agentexec.ToolLimits + ToolLimits func() modelloop.ToolLimits // LLM resolves the provider runtime at each use: a live provider-settings // or model-role-assignments update swaps the runtime wholesale (ai-sdk's // Runtime caches the provider instances it built), so the pointer cannot diff --git a/internal/app/archiegateway/chat_turn_model.go b/internal/app/archiegateway/chat_turn_model.go index 907c42ab8..5aa210ef5 100644 --- a/internal/app/archiegateway/chat_turn_model.go +++ b/internal/app/archiegateway/chat_turn_model.go @@ -9,7 +9,7 @@ import ( "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/tools" ) @@ -26,7 +26,7 @@ type chatTurnModel struct { // limits resolves the tool-output policy at each turn, so a live // tool-settings update is the policy the next turn builds its tool options // with; a snapshot taken at construction would keep the boot limits. - limits func() agentexec.ToolLimits + limits func() modelloop.ToolLimits // outcomes records each call's result for /status (see sendChatTurn). outcomes *providerOutcomeRecorder } @@ -35,7 +35,7 @@ func newChatTurnModel( llm func() *runtime.Runtime, registry *tools.Registry, maxSteps int, - limits func() agentexec.ToolLimits, + limits func() modelloop.ToolLimits, outcomes *providerOutcomeRecorder, ) gateway.TurnModel { return &chatTurnModel{ @@ -51,7 +51,7 @@ func (m *chatTurnModel) Prepare( ctx context.Context, req gateway.TurnPrepareContext, ) (gateway.PreparedTurnModel, error) { - limits := agentexec.ToolLimits{} + limits := modelloop.ToolLimits{} if m.limits != nil { limits = m.limits() } diff --git a/internal/app/archiegateway/curators.go b/internal/app/archiegateway/curators.go index d121b8861..02eddc3ff 100644 --- a/internal/app/archiegateway/curators.go +++ b/internal/app/archiegateway/curators.go @@ -9,7 +9,7 @@ import ( "github.com/samcharles93/ai-sdk/chat" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/events" infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory" @@ -131,7 +131,7 @@ type curatorLLMRunner struct { } func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) { - // agentexec.NewRuntime returns nil when no provider is configured, and a + // modelloop.NewRuntime returns nil when no provider is configured, and a // nil *runtime.Runtime panics on the first method call. A curator asking // for a completion on a daemon with no providers is a misconfiguration, // not a reason to take the process down. @@ -146,7 +146,7 @@ func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (cu for _, m := range req.Messages { msgs = append(msgs, chat.Message{Role: chat.Role(m.Role), Content: m.Content}) } - toolSet, err := agentexec.BuildToolSetFrom(req.Tools, agentexec.ToolSetOptions{}) + toolSet, err := modelloop.BuildToolSetFrom(req.Tools, modelloop.ToolSetOptions{}) if err != nil { r.outcomes.record(req.Model, err) return curator.ChatResult{}, err diff --git a/internal/app/archiegateway/gateway_runtime.go b/internal/app/archiegateway/gateway_runtime.go index 3759b3705..82910c22e 100644 --- a/internal/app/archiegateway/gateway_runtime.go +++ b/internal/app/archiegateway/gateway_runtime.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/app/chattask" "github.com/samcharles93/archie-core/internal/app/controlplane" "github.com/samcharles93/archie-core/internal/app/servicekit" @@ -26,7 +26,7 @@ func (b *server) setupChatRuntime(ctx context.Context, cfg config.Config, actor // Created before the router so the LLMResponder can be wired in for // non-command message processing. providers := executionProviders(cfg) - b.setLLM(agentexec.NewRuntime(providers)) + b.setLLM(modelloop.NewRuntime(providers)) // Transcription is a model-role capability, like the chat models it sits // beside: it is built here, on the model-owning side, from this process's // own [models]/[providers]. The Messaging Service carries a voice note's @@ -141,7 +141,7 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct // applies to the next turn in the process that serves this runner. setup := chatSetup{ Cfg: config.NewHolder(cfg), - ToolLimits: func() agentexec.ToolLimits { return toolLimits(b.cfgHolder.Get()) }, + ToolLimits: func() modelloop.ToolLimits { return toolLimits(b.cfgHolder.Get()) }, LLM: b.chatLLM, ChatModels: b.chatModels, ToolReg: b.toolReg, Personas: b.personas, ChatTasks: b.chatTasks, ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks}, diff --git a/internal/app/archiegateway/mcp_sampling.go b/internal/app/archiegateway/mcp_sampling.go index 19ba19842..18071b8ab 100644 --- a/internal/app/archiegateway/mcp_sampling.go +++ b/internal/app/archiegateway/mcp_sampling.go @@ -7,7 +7,7 @@ import ( "github.com/samcharles93/ai-sdk/core" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/tools/mcp" ) @@ -30,7 +30,7 @@ func (b *server) mcpSamplingHandler() mcp.SamplingHandler { if model == "" { return mcp.SamplingResult{}, errors.New("mcp sampling: no chat model is configured") } - messages, err := agentexec.SamplingMessages(req) + messages, err := modelloop.SamplingMessages(req) if err != nil { return mcp.SamplingResult{}, err } @@ -63,9 +63,9 @@ func (b *server) mcpSamplingHandler() mcp.SamplingHandler { // samplingMaxTokens bounds the completion to the request's own maxTokens, // falling back to a conservative default, and never past the model's own // output ceiling. The bound itself is shared with the agent worker's sampling -// path (agentexec.SamplingMaxTokens) so the same server sees the same bound on +// path (modelloop.SamplingMaxTokens) so the same server sees the same bound on // either path. func samplingMaxTokens(req mcp.SamplingRequest, models *chatModelManager, model string) int { details, ok := models.ModelDetails(model) - return agentexec.SamplingMaxTokens(req.MaxTokens, details.MaxOutputTokens, ok && details.Reasoning) + return modelloop.SamplingMaxTokens(req.MaxTokens, details.MaxOutputTokens, ok && details.Reasoning) } diff --git a/internal/app/archiegateway/tools.go b/internal/app/archiegateway/tools.go index 23f98f62a..c66a92c9d 100644 --- a/internal/app/archiegateway/tools.go +++ b/internal/app/archiegateway/tools.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/skill" @@ -146,8 +146,8 @@ func (b *server) registerMinimaxTool(cfg config.Config, log *slog.Logger) { } // toolLimits reads the configured per-turn result limits. -func toolLimits(cfg config.Config) agentexec.ToolLimits { - return agentexec.ToolLimits{ +func toolLimits(cfg config.Config) modelloop.ToolLimits { + return modelloop.ToolLimits{ MaxResultChars: cfg.Tools.Policy.MaxResultChars, SpillDir: cfg.Tools.Policy.SpillDir, } diff --git a/internal/app/prbench/live.go b/internal/app/prbench/live.go index bfe925bba..d98f4fa5d 100644 --- a/internal/app/prbench/live.go +++ b/internal/app/prbench/live.go @@ -9,11 +9,11 @@ import ( "strings" "sync/atomic" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/domain/agentrun" "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" @@ -43,7 +43,7 @@ func newBenchmarkReviewer(opts Options, cfg config.Config, rt *runtime.Runtime) cfg.Review.ApproveBeforePost = false cfg.Review.PrecisionGate = false return &liveReviewer{ - cfg: cfg, agent: agentexec.NewLoopRunner(rt, slog.Default()), + cfg: cfg, agent: modelloop.NewLoopRunner(rt, slog.Default()), source: prsource.New(forgeSource{PullRequestReader: prReader, PullRequestDiffReader: diffReader, RepoArchiveReader: archiveReader}), }, nil } diff --git a/internal/app/prbench/prbench.go b/internal/app/prbench/prbench.go index f28e0e590..8cee96961 100644 --- a/internal/app/prbench/prbench.go +++ b/internal/app/prbench/prbench.go @@ -16,6 +16,7 @@ import ( "sync" "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/agentexec/modelloop" "github.com/samcharles93/archie-core/internal/app/servicekit" "github.com/samcharles93/archie-core/internal/domain/workflow/prreview/bench" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" @@ -75,7 +76,7 @@ func Run(ctx context.Context, opts Options, w io.Writer) (bench.Summary, error) if err := servicekit.ResolveProviders(&doc.Config, slog.Default()); err != nil { return bench.Summary{}, err } - rt := agentexec.NewRuntime(agentexec.ProvidersFromConfig(doc.Config.Providers)) + rt := modelloop.NewRuntime(agentexec.ProvidersFromConfig(doc.Config.Providers)) if rt == nil { return bench.Summary{}, fmt.Errorf("%s configures no providers for the judge", opts.Config) }