From 52b9dad5b8489e095de2812ae71ea5164472ab36 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 4 Oct 2026 01:33:00 +1000 Subject: [PATCH] refactor(agentrun): agent stage contract moves to the domain layer internal/domain/workflow imported internal/agentexec for its protocol types, pulling the AI runtime into every binary that touches workflow types. The request, result and runner contract now live in internal/domain/agentrun; agentexec keeps the runtime. The model catalog cache moves from servicekit into modelcatalog and WaitForPeer into staterpc, so archie-state-store and archie-messaging no longer link the AI runtime. --- internal/agentexec/capture_mcp.go | 12 ++-- internal/agentexec/doc.go | 4 ++ internal/agentexec/harness_adapters.go | 12 ++-- internal/agentexec/harness_output_claude.go | 24 ++++--- internal/agentexec/harness_output_codex.go | 18 ++--- internal/agentexec/harness_output_copilot.go | 14 ++-- internal/agentexec/harness_output_pi.go | 12 ++-- internal/agentexec/harness_runner.go | 52 +++++++------- internal/agentexec/loop_runner.go | 54 +++++++-------- internal/agentexec/providers.go | 11 +-- internal/agentexec/runtime.go | 7 +- internal/agentexec/toolset.go | 20 ++---- internal/app/agentworker/persistent_runner.go | 11 +-- internal/app/agentworker/task_execution.go | 12 ++-- internal/app/archied/bootstrap.go | 10 +-- internal/app/archied/control_plane.go | 5 +- internal/app/archiegateway/chat_runtime.go | 4 +- internal/app/archiegateway/server.go | 12 ++-- internal/app/archiemessaging/run.go | 3 +- internal/app/prbench/live.go | 4 +- internal/app/servicekit/statestore.go | 8 +-- .../controlplane/v1/controlplane.pb.go | 7 +- .../controlplane/v1/controlplane_grpc.pb.go | 1 + internal/contracts/gateway/v1/chat.pb.go | 7 +- internal/contracts/gateway/v1/chat_grpc.pb.go | 1 + .../secretengine/v1/secretengine.pb.go | 5 +- .../secretengine/v1/secretengine_grpc.pb.go | 1 + internal/contracts/state/v1/state.pb.go | 7 +- internal/contracts/state/v1/state_grpc.pb.go | 1 + internal/daemon/daemon.go | 4 +- .../agentrun}/protocol.go | 7 +- internal/domain/agentrun/runner.go | 23 +++++++ ...hie-core-internal-domain-eda-module-log.go | 3 +- internal/domain/workflow/agent.go | 69 ++++++++++--------- internal/domain/workflow/agent_run.go | 6 +- internal/domain/workflow/command_run.go | 14 ++-- internal/domain/workflow/feasibility.go | 10 +-- internal/domain/workflow/implement.go | 23 ++++--- internal/domain/workflow/outputs.go | 11 +-- internal/domain/workflow/prreview_stages.go | 51 +++++++------- .../domain/workflow/prreview_stages_verify.go | 27 ++++---- internal/domain/workflow/remediate.go | 8 +-- internal/domain/workflow/tdd.go | 21 +++--- internal/domain/workflow/triage.go | 8 +-- internal/domain/workflow/workflow.go | 19 ++--- internal/infrastructure/kit/launch.go | 7 +- internal/infrastructure/kitrun/launcher.go | 4 +- .../modelcatalog/cache.go} | 21 +++--- .../infrastructure/secretengine/engine.go | 2 +- internal/infrastructure/staterpc/dial.go | 5 ++ ...amcharles93-archie-core-internal-plugin.go | 3 +- internal/taskrun/taskrun.go | 13 ++-- 52 files changed, 380 insertions(+), 318 deletions(-) create mode 100644 internal/agentexec/doc.go rename internal/{agentexec => domain/agentrun}/protocol.go (97%) create mode 100644 internal/domain/agentrun/runner.go rename internal/{app/servicekit/catalog.go => infrastructure/modelcatalog/cache.go} (78%) diff --git a/internal/agentexec/capture_mcp.go b/internal/agentexec/capture_mcp.go index 3a0077356..3372b4f58 100644 --- a/internal/agentexec/capture_mcp.go +++ b/internal/agentexec/capture_mcp.go @@ -11,6 +11,8 @@ import ( "os" "sync" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -26,7 +28,7 @@ type captureRecord struct { // 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 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 } @@ -42,7 +44,7 @@ func acceptCapture(spec CaptureTool, accepted int, value json.RawMessage) (strin // ServeCaptureMCP serves a stage's capture tools over MCP and appends each // accepted call to sink as one JSON line. A rejected call is answered with // its rejection, so the agent can correct it, and is not recorded. -func ServeCaptureMCP(ctx context.Context, specs []CaptureTool, sink io.Writer, t mcp.Transport) error { +func ServeCaptureMCP(ctx context.Context, specs []agentrun.CaptureTool, sink io.Writer, t mcp.Transport) error { server := mcp.NewServer(&mcp.Implementation{Name: "archie", Version: "1"}, nil) var mu sync.Mutex accepted := map[string]int{} @@ -77,7 +79,7 @@ func ServeCaptureMCP(ctx context.Context, specs []CaptureTool, sink io.Writer, t // is writable by the harness user, so nothing in it is trusted: every record // is checked again, and anything that is not an accepted call of a declared // tool is dropped. -func readCaptures(path string, specs []CaptureTool) (map[string][]json.RawMessage, error) { +func readCaptures(path string, specs []agentrun.CaptureTool) (map[string][]json.RawMessage, error) { raw, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, nil @@ -85,7 +87,7 @@ func readCaptures(path string, specs []CaptureTool) (map[string][]json.RawMessag if err != nil { return nil, err } - byName := make(map[string]CaptureTool, len(specs)) + byName := make(map[string]agentrun.CaptureTool, len(specs)) for _, s := range specs { byName[s.Name] = s } @@ -119,7 +121,7 @@ func ServeCaptureFiles(ctx context.Context, specPath, capturesPath string, t mcp if err != nil { return err } - var specs []CaptureTool + var specs []agentrun.CaptureTool if err := json.Unmarshal(raw, &specs); err != nil { return fmt.Errorf("capture tool spec: %w", err) } diff --git a/internal/agentexec/doc.go b/internal/agentexec/doc.go new file mode 100644 index 000000000..3dd0c4047 --- /dev/null +++ b/internal/agentexec/doc.go @@ -0,0 +1,4 @@ +// Package agentexec defines worker-local workflow-stage execution. archie-agent +// owns workflow orchestration; authority-bearing forge, store, and push effects +// remain daemon-owned behind scoped RPC boundaries. +package agentexec diff --git a/internal/agentexec/harness_adapters.go b/internal/agentexec/harness_adapters.go index c989aab37..b44f2b840 100644 --- a/internal/agentexec/harness_adapters.go +++ b/internal/agentexec/harness_adapters.go @@ -1,6 +1,10 @@ package agentexec -import "context" +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" +) // AdapterClaudeCode names the Claude Code stream-json output adapter. const AdapterClaudeCode = "claude-code" @@ -47,11 +51,11 @@ func LookupHarnessAdapter(name string) (HarnessAdapter, bool) { // HarnessStages runs every stage of a task on one harness: a Kit task's // container is built from its harness, so no stage in it runs anywhere else. type HarnessStages struct { - Runner Runner - Spec HarnessSpec + Runner agentrun.Runner + Spec agentrun.HarnessSpec } -func (r HarnessStages) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { +func (r HarnessStages) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) { spec := r.Spec req.Harness = &spec return r.Runner.Run(ctx, workspace, req, report) diff --git a/internal/agentexec/harness_output_claude.go b/internal/agentexec/harness_output_claude.go index ac99313ba..e52de18ed 100644 --- a/internal/agentexec/harness_output_claude.go +++ b/internal/agentexec/harness_output_claude.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/json" "strings" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // claudeCodeHarnessOutput reads Claude Code's newline-delimited stream-json @@ -13,10 +15,10 @@ type claudeCodeHarnessOutput struct { sessionID string pending map[string]string - messageUsage Usage + messageUsage agentrun.Usage seenMessages map[string]struct{} hasResult bool - resultUsage Usage + resultUsage agentrun.Usage } func newClaudeCodeHarnessOutput() *claudeCodeHarnessOutput { @@ -26,7 +28,7 @@ func newClaudeCodeHarnessOutput() *claudeCodeHarnessOutput { } } -func (o *claudeCodeHarnessOutput) Line(line []byte, report ToolCallReporter) { +func (o *claudeCodeHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) { var event struct { Type string `json:"type"` SessionID string `json:"session_id"` @@ -53,7 +55,7 @@ func (o *claudeCodeHarnessOutput) Line(line []byte, report ToolCallReporter) { } } -func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ ToolCallReporter) { +func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ agentrun.ToolCallReporter) { var message struct { ID string `json:"id"` Usage json.RawMessage `json:"usage"` @@ -77,7 +79,7 @@ func (o *claudeCodeHarnessOutput) assistant(raw json.RawMessage, _ ToolCallRepor } } -func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report ToolCallReporter) { +func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report agentrun.ToolCallReporter) { var message struct { Content []struct { Type string `json:"type"` @@ -99,7 +101,7 @@ func (o *claudeCodeHarnessOutput) user(raw json.RawMessage, report ToolCallRepor } delete(o.pending, block.ToolUseID) if report != nil { - report(ToolCallReport{ + report(agentrun.ToolCallReport{ Tool: tool, Detail: clipToolCallDetail(claudeResultContent(block.Content)), Failed: block.IsError, }) @@ -117,14 +119,14 @@ func (o *claudeCodeHarnessOutput) markMessage(id string) bool { func (o *claudeCodeHarnessOutput) SessionID() string { return o.sessionID } -func (o *claudeCodeHarnessOutput) Usage() Usage { +func (o *claudeCodeHarnessOutput) Usage() agentrun.Usage { if o.hasResult { return o.resultUsage } return o.messageUsage } -func decodeClaudeUsage(raw json.RawMessage) (Usage, bool) { +func decodeClaudeUsage(raw json.RawMessage) (agentrun.Usage, bool) { var fields struct { InputTokens int `json:"input_tokens"` OutputTokens int `json:"output_tokens"` @@ -132,7 +134,7 @@ func decodeClaudeUsage(raw json.RawMessage) (Usage, bool) { CacheCreationInputTokens int `json:"cache_creation_input_tokens"` } if len(raw) == 0 || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) || json.Unmarshal(raw, &fields) != nil { - return Usage{}, false + return agentrun.Usage{}, false } return usageFromFields(fields.InputTokens, fields.OutputTokens, fields.CacheReadInputTokens, fields.CacheCreationInputTokens), true } @@ -141,9 +143,9 @@ func decodeClaudeUsage(raw json.RawMessage) (Usage, bool) { // built-in loop's Anthropic provider does: Claude's input_tokens excludes // them, and budgets must count a harness run the way they count a built-in // one. -func usageFromFields(input, output, cacheRead, cacheCreation int) Usage { +func usageFromFields(input, output, cacheRead, cacheCreation int) agentrun.Usage { prompt := input + cacheRead + cacheCreation - return Usage{ + return agentrun.Usage{ PromptTokens: prompt, CompletionTokens: output, TotalTokens: prompt + output, CachedTokens: cacheRead, CacheCreationTokens: cacheCreation, } diff --git a/internal/agentexec/harness_output_codex.go b/internal/agentexec/harness_output_codex.go index 797032443..332b90ccd 100644 --- a/internal/agentexec/harness_output_codex.go +++ b/internal/agentexec/harness_output_codex.go @@ -3,6 +3,8 @@ package agentexec import ( "encoding/json" "strings" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // codexHarnessOutput reads `codex exec --json`. Each tool item is reported @@ -10,10 +12,10 @@ import ( // a run killed mid-turn reports none. type codexHarnessOutput struct { threadID string - usage Usage + usage agentrun.Usage } -func (o *codexHarnessOutput) Line(line []byte, report ToolCallReporter) { +func (o *codexHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) { var event struct { Type string `json:"type"` ThreadID string `json:"thread_id"` @@ -34,7 +36,7 @@ func (o *codexHarnessOutput) Line(line []byte, report ToolCallReporter) { case "turn.completed": if u := event.Usage; u != nil { // Codex follows OpenAI: input_tokens already includes cached input. - o.usage = addUsage(o.usage, Usage{ + o.usage = addUsage(o.usage, agentrun.Usage{ PromptTokens: u.InputTokens, CompletionTokens: u.OutputTokens, TotalTokens: u.InputTokens + u.OutputTokens, CachedTokens: u.CachedInputTokens, CacheCreationTokens: u.CacheWriteTokens, @@ -67,8 +69,8 @@ type codexItem struct { Query string `json:"query"` } -func (item codexItem) report() (ToolCallReport, bool) { - call := ToolCallReport{Tool: item.Type, Failed: item.Status == "failed"} +func (item codexItem) report() (agentrun.ToolCallReport, bool) { + call := agentrun.ToolCallReport{Tool: item.Type, Failed: item.Status == "failed"} switch item.Type { case "command_execution": call.Detail = item.AggregatedOutput @@ -95,11 +97,11 @@ func (item codexItem) report() (ToolCallReport, bool) { case "web_search": call.Detail = item.Query default: - return ToolCallReport{}, false + return agentrun.ToolCallReport{}, false } call.Detail = clipToolCallDetail(call.Detail) return call, true } -func (o *codexHarnessOutput) SessionID() string { return o.threadID } -func (o *codexHarnessOutput) Usage() Usage { return o.usage } +func (o *codexHarnessOutput) SessionID() string { return o.threadID } +func (o *codexHarnessOutput) Usage() agentrun.Usage { return o.usage } diff --git a/internal/agentexec/harness_output_copilot.go b/internal/agentexec/harness_output_copilot.go index ff82f36ec..92128a055 100644 --- a/internal/agentexec/harness_output_copilot.go +++ b/internal/agentexec/harness_output_copilot.go @@ -1,6 +1,10 @@ package agentexec -import "encoding/json" +import ( + "encoding/json" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" +) // copilotHarnessOutput reads GitHub Copilot CLI's `--output-format json`. // The stream carries no token counts, so a Copilot run reports no usage and @@ -14,7 +18,7 @@ func newCopilotHarnessOutput() *copilotHarnessOutput { return &copilotHarnessOutput{pending: make(map[string]string)} } -func (o *copilotHarnessOutput) Line(line []byte, report ToolCallReporter) { +func (o *copilotHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) { var event struct { Type string `json:"type"` SessionID string `json:"sessionId"` @@ -49,10 +53,10 @@ func (o *copilotHarnessOutput) Line(line []byte, report ToolCallReporter) { } delete(o.pending, event.Data.ToolCallID) if report != nil { - report(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}) } } } -func (o *copilotHarnessOutput) SessionID() string { return o.sessionID } -func (o *copilotHarnessOutput) Usage() Usage { return Usage{} } +func (o *copilotHarnessOutput) SessionID() string { return o.sessionID } +func (o *copilotHarnessOutput) Usage() agentrun.Usage { return agentrun.Usage{} } diff --git a/internal/agentexec/harness_output_pi.go b/internal/agentexec/harness_output_pi.go index b8394025b..a82a803a1 100644 --- a/internal/agentexec/harness_output_pi.go +++ b/internal/agentexec/harness_output_pi.go @@ -3,6 +3,8 @@ package agentexec import ( "encoding/json" "strings" + + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // piHarnessOutput reads `--mode json` from Pi and OMP, which share the @@ -10,10 +12,10 @@ import ( // interrupted run still reports what it spent. type piHarnessOutput struct { sessionID string - usage Usage + usage agentrun.Usage } -func (o *piHarnessOutput) Line(line []byte, report ToolCallReporter) { +func (o *piHarnessOutput) Line(line []byte, report agentrun.ToolCallReporter) { var event struct { Type string `json:"type"` ID string `json:"id"` @@ -56,9 +58,9 @@ func (o *piHarnessOutput) Line(line []byte, report ToolCallReporter) { texts = append(texts, block.Text) } } - report(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}) } } -func (o *piHarnessOutput) SessionID() string { return o.sessionID } -func (o *piHarnessOutput) Usage() Usage { return o.usage } +func (o *piHarnessOutput) SessionID() string { return o.sessionID } +func (o *piHarnessOutput) Usage() agentrun.Usage { return o.usage } diff --git a/internal/agentexec/harness_runner.go b/internal/agentexec/harness_runner.go index 444eb8f48..2422d59d8 100644 --- a/internal/agentexec/harness_runner.go +++ b/internal/agentexec/harness_runner.go @@ -18,6 +18,8 @@ import ( "strings" "time" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + git "github.com/go-git/go-git/v6" "github.com/go-git/go-git/v6/plumbing" ) @@ -43,9 +45,9 @@ const ( // knows its CLI's stream format; it reports tool calls as they complete and // the session to resume. type HarnessOutput interface { - Line(line []byte, report ToolCallReporter) + Line(line []byte, report agentrun.ToolCallReporter) SessionID() string - Usage() Usage + Usage() agentrun.Usage } // HarnessRunner runs a stage on an external coding-agent CLI. Archie's @@ -65,16 +67,16 @@ func NewHarnessRunner(newOutput func() HarnessOutput) *HarnessRunner { return &HarnessRunner{newOutput: newOutput} } -func (r *HarnessRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { +func (r *HarnessRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) { if err := validateHarness(req); err != nil { - return Result{}, err + return agentrun.Result{}, err } if err := ownTreeForHarness(req.Harness.User, workspace); err != nil { - return Result{}, fmt.Errorf("give the worktree to the harness user: %w", err) + return agentrun.Result{}, fmt.Errorf("give the worktree to the harness user: %w", err) } mcpConfig, capturesPath, cleanup, err := r.prepareCaptures(req) if err != nil { - return Result{}, err + return agentrun.Result{}, err } defer cleanup() res, err := r.run(ctx, workspace, req, mcpConfig, report) @@ -88,11 +90,11 @@ func (r *HarnessRunner) Run(ctx context.Context, workspace string, req Request, return res, err } -func (r *HarnessRunner) run(ctx context.Context, workspace string, req Request, mcpConfig string, report ToolCallReporter) (Result, error) { - res := Result{Version: ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage} +func (r *HarnessRunner) run(ctx context.Context, workspace string, req agentrun.Request, mcpConfig string, report agentrun.ToolCallReporter) (agentrun.Result, error) { + res := agentrun.Result{Version: agentrun.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage} before, err := snapshotRepo(workspace) if err != nil { - return Result{}, fmt.Errorf("snapshot workspace before harness: %w", err) + return agentrun.Result{}, fmt.Errorf("snapshot workspace before harness: %w", err) } runCtx := ctx if req.Budget.WallClock > 0 { @@ -128,7 +130,7 @@ func (r *HarnessRunner) run(ctx context.Context, workspace string, req Request, gateOutput, gateErr := runHarnessGate(runCtx, req.Gate.Commands, workspace) if gateErr == nil { - res.Status = StatusPassed + res.Status = agentrun.StatusPassed return res, nil } if runCtx.Err() != nil { @@ -144,7 +146,7 @@ func (r *HarnessRunner) run(ctx context.Context, workspace string, req Request, // settle checks one finished invocation. Guarantees come first: a policy // violation parks the step even when the invocation also timed out or // failed, because what the harness did matters more than how it ended. -func settle(runCtx context.Context, workspace string, before repoState, req Request, res Result, exitErr error) (Result, bool, error) { +func settle(runCtx context.Context, workspace string, before repoState, req agentrun.Request, res agentrun.Result, exitErr error) (agentrun.Result, bool, error) { after, err := snapshotRepo(workspace) if err != nil { return res, true, fmt.Errorf("snapshot workspace after harness: %w", err) @@ -173,7 +175,7 @@ func (r *HarnessRunner) output(adapter string) HarnessOutput { return silentOutput{} } -func validateHarness(req Request) error { +func validateHarness(req agentrun.Request) error { if err := req.Validate(); err != nil { return err } @@ -202,7 +204,7 @@ func validateHarness(req Request) error { // harnessArgv is the launch command, then the verb, then the prompt verb // when the verb is a resume or continue, with placeholders substituted as // raw values rather than shell text. -func harnessArgv(h *HarnessSpec, verb []string, prompt, session, mcpConfig string) []string { +func harnessArgv(h *agentrun.HarnessSpec, verb []string, prompt, session, mcpConfig string) []string { argv := slices.Clone(h.Launch) tails := [][]string{verb} if !slices.Equal(verb, h.Prompt) { @@ -224,7 +226,7 @@ func harnessArgv(h *HarnessSpec, verb []string, prompt, session, mcpConfig strin // resumeVerb continues the session the last invocation reported, falling // back to the most recent session when the CLI reported none. -func resumeVerb(h *HarnessSpec, sessionID string) []string { +func resumeVerb(h *agentrun.HarnessSpec, sessionID string) []string { if len(h.Resume) > 0 && sessionID != "" { return slices.Clone(h.Resume) } @@ -237,7 +239,7 @@ func resumeVerb(h *HarnessSpec, sessionID string) []string { // invoke runs one harness invocation in its own process group, feeding // stdout to out line by line. Cancelling ctx kills the whole group, so a // CLI's children cannot outlive the step. -func invoke(ctx context.Context, workspace string, h *HarnessSpec, argv []string, out HarnessOutput, report ToolCallReporter) error { +func invoke(ctx context.Context, workspace string, h *agentrun.HarnessSpec, argv []string, out HarnessOutput, report agentrun.ToolCallReporter) error { cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) cmd.Dir = workspace cmd.WaitDelay = killGrace @@ -271,7 +273,7 @@ func invoke(ctx context.Context, workspace string, h *HarnessSpec, argv []string return nil } -func harnessPrompt(workspace string, req Request) string { +func harnessPrompt(workspace string, req agentrun.Request) string { var b strings.Builder b.WriteString(req.Mission) b.WriteString("\n\n## Rules\n\n") @@ -295,7 +297,7 @@ func harnessPrompt(workspace string, req Request) string { return b.String() } -func runHarnessGate(ctx context.Context, commands []Command, workspace string) (string, error) { +func runHarnessGate(ctx context.Context, commands []agentrun.Command, workspace string) (string, error) { for _, c := range commands { if len(c.Argv) == 0 { continue @@ -323,13 +325,13 @@ func clipGate(out []byte) string { return s[:limit/2] + "\n...[truncated]...\n" + s[len(s)-limit/2:] } -func park(res Result, stop, detail string) Result { +func park(res agentrun.Result, stop, detail string) agentrun.Result { res.Status, res.StopReason, res.Detail = StatusParked, stop, detail return res } -func addUsage(a, b Usage) Usage { - return Usage{ +func addUsage(a, b agentrun.Usage) agentrun.Usage { + return agentrun.Usage{ PromptTokens: a.PromptTokens + b.PromptTokens, CompletionTokens: a.CompletionTokens + b.CompletionTokens, TotalTokens: a.TotalTokens + b.TotalTokens, @@ -425,7 +427,7 @@ func mergeKeys(a, b map[string]string) map[string]struct{} { return keys } -func policyViolation(before, after repoState, changes []string, req Request) string { +func policyViolation(before, after repoState, changes []string, req agentrun.Request) string { if !maps.Equal(before.refs, after.refs) { var moved []string for name := range mergeKeys(before.refs, after.refs) { @@ -458,9 +460,9 @@ func policyViolation(before, after repoState, changes []string, req Request) str type silentOutput struct{} -func (silentOutput) Line([]byte, ToolCallReporter) {} -func (silentOutput) SessionID() string { return "" } -func (silentOutput) Usage() Usage { return Usage{} } +func (silentOutput) Line([]byte, agentrun.ToolCallReporter) {} +func (silentOutput) SessionID() string { return "" } +func (silentOutput) Usage() agentrun.Usage { return agentrun.Usage{} } // tailBuffer keeps the last stderrTailBytes written to it. type tailBuffer struct{ buf bytes.Buffer } @@ -479,7 +481,7 @@ func (t *tailBuffer) String() string { return t.buf.String() } // the CLI at archie's MCP server, and creates the captures file the server // appends to. The directory belongs to the harness user, whose MCP server // writes into it. -func (r *HarnessRunner) prepareCaptures(req Request) (config, captures string, cleanup func(), err error) { +func (r *HarnessRunner) prepareCaptures(req agentrun.Request) (config, captures string, cleanup func(), err error) { cleanup = func() {} if len(req.CaptureTools) == 0 { return "", "", cleanup, nil diff --git a/internal/agentexec/loop_runner.go b/internal/agentexec/loop_runner.go index e1cee345f..058b1a773 100644 --- a/internal/agentexec/loop_runner.go +++ b/internal/agentexec/loop_runner.go @@ -10,6 +10,8 @@ import ( "slices" "strings" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/ai-sdk/agentloop" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/ai-sdk/runtime" @@ -20,12 +22,6 @@ import ( "github.com/samcharles93/archie-core/internal/tools" ) -// Runner executes one autonomous stage against an already prepared workspace. -type Runner interface { - // report, when non-nil, is notified once per completed tool call. - Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) -} - type loopFunc func(context.Context, agentloop.Config) (agentloop.Result, error) // LoopRunner executes one workflow stage through ai-sdk's agent loop. It is @@ -62,15 +58,15 @@ func NewLoopRunner( // work on the chat workspace and bypass ReadOnly and ProtectPaths. const workspaceToolset = "workspace" -func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { +func (r *LoopRunner) Run(ctx context.Context, workspace string, req agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) { if err := req.Validate(); err != nil { - return Result{}, err + return agentrun.Result{}, err } if r.runtime == nil { - return Result{}, fmt.Errorf("agent runtime is not configured") + return agentrun.Result{}, fmt.Errorf("agent runtime is not configured") } if r.run == nil { - return Result{}, fmt.Errorf("agent loop is not configured") + return agentrun.Result{}, fmt.Errorf("agent loop is not configured") } notes := &memoryNotes{initial: req.Notes} @@ -79,13 +75,13 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep toolOpts.OnToolCall = report centralTools, err := BuildToolSet(r.tools, toolOpts) if err != nil { - return Result{}, fmt.Errorf("build central tool set: %w", err) + return agentrun.Result{}, fmt.Errorf("build central tool set: %w", err) } captureTools := captureToolSet(req.CaptureTools, captures) scriptTools := scriptToolSet(workspace) pluginTools, err := pluginToolSet(req, workspace, centralTools, captureTools, scriptTools) if err != nil { - return Result{}, err + return agentrun.Result{}, err } res, err := r.run(ctx, agentloop.Config{ Runtime: r.runtime, @@ -124,9 +120,9 @@ func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, rep return result, err } -func resultFromRun(req Request, res agentloop.Result, appended []string, captures map[string][]json.RawMessage) Result { - result := Result{ - Version: ProtocolVersion, +func resultFromRun(req agentrun.Request, res agentloop.Result, appended []string, captures map[string][]json.RawMessage) agentrun.Result { + result := agentrun.Result{ + Version: agentrun.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage, @@ -135,7 +131,7 @@ func resultFromRun(req Request, res agentloop.Result, appended []string, capture Changes: res.Changes, Iterations: res.Iterations, TokensUsed: res.TokensUsed, - Usage: Usage{ + Usage: agentrun.Usage{ PromptTokens: res.Usage.PromptTokens, CompletionTokens: res.Usage.CompletionTokens, TotalTokens: res.Usage.TotalTokens, @@ -165,7 +161,7 @@ func projectScopedRules(workspace, extra string) string { return rule + "\n" + extra } -func pluginToolSet(req Request, workspace string, occupied ...core.ToolSet) (core.ToolSet, error) { +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 } @@ -202,21 +198,21 @@ func pluginToolSet(req Request, workspace string, occupied ...core.ToolSet) (cor return set, nil } -func (r *LoopRunner) logger(req Request) *slog.Logger { +func (r *LoopRunner) logger(req agentrun.Request) *slog.Logger { if r.log == nil { return slog.New(slog.DiscardHandler) } return r.log.With("task", req.TaskID, "attempt", req.Attempt, "stage", req.Stage, "model", req.Model) } -func toAgentGate(g Gate) agentloop.GateConfig { +func toAgentGate(g agentrun.Gate) agentloop.GateConfig { return agentloop.GateConfig{ Commands: toAgentCommands(g.Commands), MaxConsecutiveFailures: g.MaxConsecutiveFailures, } } -func toAgentCommands(commands []Command) []agentloop.GateCommand { +func toAgentCommands(commands []agentrun.Command) []agentloop.GateCommand { out := make([]agentloop.GateCommand, 0, len(commands)) for _, command := range commands { out = append(out, agentloop.GateCommand{ @@ -226,7 +222,7 @@ func toAgentCommands(commands []Command) []agentloop.GateCommand { return out } -func protectionMatcher(p Protection, readOnly bool) func(string) bool { +func protectionMatcher(p agentrun.Protection, readOnly bool) func(string) bool { if readOnly || len(p.Suffixes)+len(p.Globs) == 0 { return nil } @@ -249,7 +245,7 @@ func protectionMatcher(p Protection, readOnly bool) func(string) bool { } } -func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage) core.ToolSet { +func captureToolSet(specs []agentrun.CaptureTool, captures map[string][]json.RawMessage) core.ToolSet { tools := make(core.ToolSet, len(specs)) for _, spec := range specs { tools[spec.Name] = core.NewTool(spec.Name, spec.Description, spec.Parameters, @@ -260,7 +256,7 @@ func captureToolSet(specs []CaptureTool, captures map[string][]json.RawMessage) // makeCaptureHandler builds a tool handler that validates and records // capture-tool invocations. -func makeCaptureHandler(spec CaptureTool, captures map[string][]json.RawMessage) func(context.Context, string) (string, error) { +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) @@ -275,12 +271,12 @@ func makeCaptureHandler(spec CaptureTool, captures map[string][]json.RawMessage) // 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 CaptureTool, value json.RawMessage) (string, bool) { +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(CaptureTool, map[string]json.RawMessage) (string, bool){ + for _, check := range []func(agentrun.CaptureTool, map[string]json.RawMessage) (string, bool){ checkRequiredFields, checkNonEmptyStrings, checkBooleanFields, @@ -293,7 +289,7 @@ func validateCaptureArgs(spec CaptureTool, value json.RawMessage) (string, bool) return "", true } -func checkRequiredFields(spec CaptureTool, object map[string]json.RawMessage) (string, bool) { +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 @@ -302,7 +298,7 @@ func checkRequiredFields(spec CaptureTool, object map[string]json.RawMessage) (s return "", true } -func checkNonEmptyStrings(spec CaptureTool, object map[string]json.RawMessage) (string, bool) { +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 @@ -311,7 +307,7 @@ func checkNonEmptyStrings(spec CaptureTool, object map[string]json.RawMessage) ( return "", true } -func checkBooleanFields(spec CaptureTool, object map[string]json.RawMessage) (string, bool) { +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 { @@ -324,7 +320,7 @@ func checkBooleanFields(spec CaptureTool, object map[string]json.RawMessage) (st // 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 CaptureTool, object map[string]json.RawMessage) (string, bool) { +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 { diff --git a/internal/agentexec/providers.go b/internal/agentexec/providers.go index 8964fbbca..a21bbec4a 100644 --- a/internal/agentexec/providers.go +++ b/internal/agentexec/providers.go @@ -1,14 +1,17 @@ package agentexec -import "github.com/samcharles93/archie-core/internal/config" +import ( + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/agentrun" +) // ProvidersFromConfig converts the daemon's configured LLM providers into // the wire-safe Provider map sent to an agent runner. It carries only // class/env-var-name/base-URL -- never the resolved API key. -func ProvidersFromConfig(providers map[string]config.Provider) map[string]Provider { - out := make(map[string]Provider, len(providers)) +func ProvidersFromConfig(providers map[string]config.Provider) map[string]agentrun.Provider { + out := make(map[string]agentrun.Provider, len(providers)) for name, p := range providers { - out[name] = Provider{Class: p.Class, APIKeyEnv: p.APIKeyEnv, BaseURL: p.BaseURL} + out[name] = agentrun.Provider{Class: p.Class, APIKeyEnv: p.APIKeyEnv, BaseURL: p.BaseURL} } return out } diff --git a/internal/agentexec/runtime.go b/internal/agentexec/runtime.go index c337d7286..847b40f37 100644 --- a/internal/agentexec/runtime.go +++ b/internal/agentexec/runtime.go @@ -1,10 +1,13 @@ package agentexec -import "github.com/samcharles93/ai-sdk/runtime" +import ( + "github.com/samcharles93/ai-sdk/runtime" + "github.com/samcharles93/archie-core/internal/domain/agentrun" +) // NewRuntime builds a provider runtime for interactive chat or a worker-local // workflow stage. Nil means no providers were configured. -func NewRuntime(providers map[string]Provider) *runtime.Runtime { +func NewRuntime(providers map[string]agentrun.Provider) *runtime.Runtime { if len(providers) == 0 { return nil } diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index 076ff54ba..d235107a8 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -8,6 +8,8 @@ import ( "os" "slices" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + aicore "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/internal/tools" @@ -71,23 +73,9 @@ type ToolSetOptions struct { // OnToolCall, when non-nil, is notified once per completed tool call. // LoopRunner populates it so a workflow stage can surface tool activity on // the task timeline. Nil means no one is listening. - OnToolCall ToolCallReporter + OnToolCall agentrun.ToolCallReporter } -// ToolCallReport is one completed tool invocation, reported through a -// ToolCallReporter. -type ToolCallReport struct { - Tool string - // Detail is a clipped one-line summary: the tool's result, or - // "error: " if it failed. - Detail string - Failed bool -} - -// ToolCallReporter receives one ToolCallReport per completed tool call. A nil -// reporter is valid and reports nothing. -type ToolCallReporter func(ToolCallReport) - // 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 @@ -112,7 +100,7 @@ func reportToolCallCompletion(opts ToolSetOptions, entry tools.ToolEntry, result if err != nil { outcome = "error: " + err.Error() } - opts.OnToolCall(ToolCallReport{Tool: entry.Name, Detail: clipToolCallDetail(outcome), Failed: err != nil}) + opts.OnToolCall(agentrun.ToolCallReport{Tool: entry.Name, Detail: clipToolCallDetail(outcome), Failed: err != nil}) } // resultLimit returns the cap that applies to one entry. diff --git a/internal/app/agentworker/persistent_runner.go b/internal/app/agentworker/persistent_runner.go index 1d76eac94..bc886e01b 100644 --- a/internal/app/agentworker/persistent_runner.go +++ b/internal/app/agentworker/persistent_runner.go @@ -6,12 +6,13 @@ import ( "os" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/storage" ) type persistentRunner struct { - agentexec.Runner + agentrun.Runner enabled bool sessionPath string memoryPath string @@ -46,7 +47,7 @@ func readProjectMemory(path string) (string, error) { return "Project memory from earlier sessions:\n" + strings.Join(entries, "\n"), nil } -func (r persistentRunner) Run(ctx context.Context, workspace string, request agentexec.Request, report agentexec.ToolCallReporter) (agentexec.Result, error) { +func (r persistentRunner) Run(ctx context.Context, workspace string, request agentrun.Request, report agentrun.ToolCallReporter) (agentrun.Result, error) { if !r.enabled { return r.Runner.Run(ctx, workspace, request, report) } @@ -64,11 +65,11 @@ func (r persistentRunner) Run(ctx context.Context, workspace string, request age plugin := &request.Plugins[i] filename := plugin.Name + ".go" if err := storage.StagePlugin(pluginsDir, filename, []byte(plugin.Src)); err != nil { - return agentexec.Result{}, fmt.Errorf("stage plugin %s: %w", plugin.Name, err) + return agentrun.Result{}, fmt.Errorf("stage plugin %s: %w", plugin.Name, err) } source, err := os.ReadFile(pluginsDir + "/" + filename) if err != nil { - return agentexec.Result{}, fmt.Errorf("read staged plugin %s: %w", plugin.Name, err) + return agentrun.Result{}, fmt.Errorf("read staged plugin %s: %w", plugin.Name, err) } plugin.Src = string(source) } diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 89519a34b..d9858f39e 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -10,6 +10,8 @@ import ( "path/filepath" "strconv" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/archie-core/internal/agentexec" @@ -152,15 +154,15 @@ type taskDependencies struct { guardrails *tools.GuardrailEngine } -type runnerFactory func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner +type runnerFactory func(map[string]agentrun.Provider, *slog.Logger) agentrun.Runner -func newTaskRunner(providers map[string]agentexec.Provider, log *slog.Logger) agentexec.Runner { +func newTaskRunner(providers map[string]agentrun.Provider, log *slog.Logger) agentrun.Runner { return agentexec.NewLoopRunner(agentexec.NewRuntime(providers), log) } // applyToolLimits sets the task's tool policy and allowlist on a // *LoopRunner. Other runners are untouched. -func applyToolLimits(agent agentexec.Runner, policy config.ToolPolicy, allow []string) { +func applyToolLimits(agent agentrun.Runner, policy config.ToolPolicy, allow []string) { runner, ok := agent.(*agentexec.LoopRunner) if !ok { return @@ -175,12 +177,12 @@ func applyToolLimits(agent agentexec.Runner, policy config.ToolPolicy, allow []s // stageRunners builds the runner every agent stage uses. llm is the task's // shared model runtime (the one its MCP providers answer sampling from); the // registry path reuses it rather than building a second one. -func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerFactory, llm *runtime.Runtime, log *slog.Logger) (agentexec.Runner, error) { +func stageRunners(req taskrun.Request, mcpSet *mcpProviderSet, newRunner runnerFactory, llm *runtime.Runtime, log *slog.Logger) (agentrun.Runner, error) { if req.Harness != nil { // The built-in loop has no route to a model from a Kit container. return agentexec.HarnessStages{Runner: agentexec.NewHarnessRunner(nil), Spec: *req.Harness}, nil } - var agent agentexec.Runner + var agent agentrun.Runner if mcpSet != nil && mcpSet.registry != nil { agent = agentexec.NewLoopRunner(llm, log, mcpSet.registry) } else { diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 8e7295e28..4aba4d29c 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -67,7 +67,7 @@ import ( // reverse at shutdown, matching the LIFO ordering of the deferred calls // they replace. type boot struct { - catalog *servicekit.Catalog + catalog *modelcatalog.Catalog cfg config.Config log *slog.Logger @@ -235,7 +235,7 @@ func (b *boot) loadConfig(_ context.Context, cfgPath, overlayPath string) error return err } b.loader, b.doc = loader, doc - b.catalog = servicekit.NewCatalog(cfgPath) + b.catalog = modelcatalog.NewCatalog(cfgPath) b.cfg = b.doc.Config b.cfgHolder = config.NewHolder(b.cfg) b.currentProvenance.Store(&b.doc.Provenance) @@ -981,7 +981,7 @@ func (b *boot) loadCatalog(ctx context.Context) { b.log.Warn("model catalog unavailable; using configured providers and models", "err", err) return } - models := servicekit.ApplyModelCatalog(&b.cfg, snapshot) + models := modelcatalog.Apply(&b.cfg, snapshot) b.cfgHolder.Set(b.cfg.Clone()) b.catalog.Set(snapshot, models) b.log.Info("model catalog loaded", "providers", len(snapshot.Providers), "models", len(models)) @@ -993,7 +993,7 @@ func (b *boot) refreshModelCatalog(ctx context.Context) error { return err } base := b.cfgHolder.Get().Clone() - models := servicekit.ApplyModelCatalog(&base, snapshot) + models := modelcatalog.Apply(&base, snapshot) cfg, _, err := b.runtimeConfig(ctx, base) if err != nil { return err @@ -1005,7 +1005,7 @@ func (b *boot) refreshModelCatalog(ctx context.Context) error { } func (b *boot) startModelCatalogRefresh(ctx context.Context) { - servicekit.Every(ctx, servicekit.CatalogRefreshInterval, func() { + modelcatalog.Every(ctx, modelcatalog.RefreshInterval, func() { if err := b.refreshModelCatalog(ctx); err != nil { b.log.Warn("model catalog refresh failed; keeping the loaded catalog", "err", err) } diff --git a/internal/app/archied/control_plane.go b/internal/app/archied/control_plane.go index f35670323..1b90179da 100644 --- a/internal/app/archied/control_plane.go +++ b/internal/app/archied/control_plane.go @@ -12,6 +12,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/applystatus" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" ) // runtimeConfig layers every database-owned setting over a file config and @@ -53,7 +54,7 @@ func (b *boot) reloadConfig(ctx context.Context, doc *configuration.Document) er // unchanged. Re-apply the same merge (idempotent: a catalog that // failed to load merges to identity). catalog, _ := b.catalogState() - servicekit.ApplyModelCatalog(&doc.Config, catalog) + modelcatalog.Apply(&doc.Config, catalog) // Bounded: this runs on the signal loop, which handles nothing else // while it waits, and a State Store that has stopped answering must // surface as a failed reload rather than a SIGHUP that never returns. @@ -329,7 +330,7 @@ func (b *boot) applyRuntimeResourceUpdate(ctx context.Context, kind string, upda // providers. The merge is idempotent, and reloadConfig re-applies it // before layering for the same reason. catalog, _ := b.catalogState() - servicekit.ApplyModelCatalog(&base, catalog) + modelcatalog.Apply(&base, catalog) cfg, _, err := b.runtimeConfig(ctx, base) if err != nil { // runtimeConfig reported the refusal through apply status for every diff --git a/internal/app/archiegateway/chat_runtime.go b/internal/app/archiegateway/chat_runtime.go index b27a84b2f..583ea77bf 100644 --- a/internal/app/archiegateway/chat_runtime.go +++ b/internal/app/archiegateway/chat_runtime.go @@ -6,6 +6,8 @@ import ( "log/slog" "time" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/ai-sdk/chat" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/internal/agentexec" @@ -99,7 +101,7 @@ func (b *server) rebuildChatModelRuntime(cfg config.Config) { // sessionKey builds a deterministic session identifier from a gateway // message's routing fields. Platform + channel + thread uniquely identify // a conversation for session persistence and history retrieval. -func executionProviders(cfg config.Config) map[string]agentexec.Provider { +func executionProviders(cfg config.Config) map[string]agentrun.Provider { return agentexec.ProvidersFromConfig(cfg.Providers) } diff --git a/internal/app/archiegateway/server.go b/internal/app/archiegateway/server.go index 4aa02902a..52ef4de8c 100644 --- a/internal/app/archiegateway/server.go +++ b/internal/app/archiegateway/server.go @@ -64,7 +64,7 @@ type server struct { controlPlane *controlplane.Client applyStatus *applystatus.Reporter runtimeVersions map[string]int64 - catalog *servicekit.Catalog + catalog *modelcatalog.Catalog chatPool *pgxpool.Pool chatSessionStore gateway.SessionStore taskActionsConn *natsio.Conn @@ -151,7 +151,7 @@ func (b *server) loadConfig(cfgPath, overlayPath string) error { return err } b.cfg = doc.Config - b.catalog = servicekit.NewCatalog(cfgPath) + b.catalog = modelcatalog.NewCatalog(cfgPath) b.cfgHolder = config.NewHolder(b.cfg) logs := servicekit.Logging(b.cfg, "gateway") b.log, b.taskLogs = logs.Log, logs.TaskLogs @@ -245,20 +245,20 @@ func (b *server) loadCatalog(ctx context.Context) { b.log.Warn("model catalog unavailable; using configured providers and models", "err", err) return } - models := servicekit.ApplyModelCatalog(&b.cfg, snapshot) + models := modelcatalog.Apply(&b.cfg, snapshot) b.cfgHolder.Set(b.cfg.Clone()) b.catalog.Set(snapshot, models) } func (b *server) startModelCatalogRefresh(ctx context.Context) { - servicekit.Every(ctx, servicekit.CatalogRefreshInterval, func() { + modelcatalog.Every(ctx, modelcatalog.RefreshInterval, func() { snapshot, err := b.catalog.Fetch(ctx, b.secrets.Getenv, b.cfgHolder.Get().Providers) if err != nil { b.log.Warn("model catalog refresh failed; keeping the loaded catalog", "err", err) return } base := b.cfgHolder.Get().Clone() - models := servicekit.ApplyModelCatalog(&base, snapshot) + models := modelcatalog.Apply(&base, snapshot) b.catalog.Set(snapshot, models) b.relayer(ctx, base, "") }) @@ -291,7 +291,7 @@ func (b *server) startRuntimeWatches(ctx context.Context) error { } base := b.cfgHolder.Get() catalog, _ := b.catalogState() - servicekit.ApplyModelCatalog(&base, catalog) + modelcatalog.Apply(&base, catalog) b.relayer(ctx, base, kind) }) } diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index d00381237..46ab13fb8 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -5,7 +5,6 @@ import ( "fmt" "log/slog" - "github.com/samcharles93/archie-core/internal/app/servicekit" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/applystatus" "github.com/samcharles93/archie-core/internal/domain/messaging" @@ -47,7 +46,7 @@ func Run(ctx context.Context, o Options) error { var applyReporter *applystatus.Reporter var appliedVersion int64 if cfg.Options.StateStore.Target != "" { - stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, cfg.Options.StateStore.Token, servicekit.WaitForPeer) + stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, cfg.Options.StateStore.Token, staterpc.WaitForPeer) if dialErr != nil { return fmt.Errorf("dial state store control plane (%s): %w", cfg.Options.StateStore.Target, dialErr) } diff --git a/internal/app/prbench/live.go b/internal/app/prbench/live.go index d953e28f8..bfe925bba 100644 --- a/internal/app/prbench/live.go +++ b/internal/app/prbench/live.go @@ -9,6 +9,8 @@ import ( "strings" "sync/atomic" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/archie-core/internal/agentexec" @@ -48,7 +50,7 @@ func newBenchmarkReviewer(opts Options, cfg config.Config, rt *runtime.Runtime) type liveReviewer struct { cfg config.Config - agent agentexec.Runner + agent agentrun.Runner source workflow.PRSource nextID atomic.Int64 } diff --git a/internal/app/servicekit/statestore.go b/internal/app/servicekit/statestore.go index ab23f2fc8..b663f2c21 100644 --- a/internal/app/servicekit/statestore.go +++ b/internal/app/servicekit/statestore.go @@ -4,7 +4,6 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/secret" - "google.golang.org/grpc" ) // StateStoreClient dials the State Store gRPC service the daemon's own @@ -18,10 +17,5 @@ func StateStoreClient(services config.Services, secrets *secret.Registry) (*stat if err != nil { return nil, nil, err } - return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv), WaitForPeer) + return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv), staterpc.WaitForPeer) } - -// WaitForPeer makes a service's calls to another service wait for it to come -// up instead of failing while it is down or restarting. A call that must not -// wait carries its own deadline. -var WaitForPeer = grpc.WithDefaultCallOptions(grpc.WaitForReady(true)) diff --git a/internal/contracts/controlplane/v1/controlplane.pb.go b/internal/contracts/controlplane/v1/controlplane.pb.go index 852f666fb..71945ada6 100644 --- a/internal/contracts/controlplane/v1/controlplane.pb.go +++ b/internal/contracts/controlplane/v1/controlplane.pb.go @@ -7,12 +7,13 @@ package controlplanev1 import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) const ( diff --git a/internal/contracts/controlplane/v1/controlplane_grpc.pb.go b/internal/contracts/controlplane/v1/controlplane_grpc.pb.go index 09513fa51..fc9032637 100644 --- a/internal/contracts/controlplane/v1/controlplane_grpc.pb.go +++ b/internal/contracts/controlplane/v1/controlplane_grpc.pb.go @@ -8,6 +8,7 @@ package controlplanev1 import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" diff --git a/internal/contracts/gateway/v1/chat.pb.go b/internal/contracts/gateway/v1/chat.pb.go index 34b91de27..6366915c2 100644 --- a/internal/contracts/gateway/v1/chat.pb.go +++ b/internal/contracts/gateway/v1/chat.pb.go @@ -7,12 +7,13 @@ package gatewayv1 import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) const ( diff --git a/internal/contracts/gateway/v1/chat_grpc.pb.go b/internal/contracts/gateway/v1/chat_grpc.pb.go index d15a671f8..a7ce951f4 100644 --- a/internal/contracts/gateway/v1/chat_grpc.pb.go +++ b/internal/contracts/gateway/v1/chat_grpc.pb.go @@ -8,6 +8,7 @@ package gatewayv1 import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" diff --git a/internal/contracts/secretengine/v1/secretengine.pb.go b/internal/contracts/secretengine/v1/secretengine.pb.go index d9c2647f5..5159f5ec1 100644 --- a/internal/contracts/secretengine/v1/secretengine.pb.go +++ b/internal/contracts/secretengine/v1/secretengine.pb.go @@ -7,11 +7,12 @@ package secretenginev1 import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( diff --git a/internal/contracts/secretengine/v1/secretengine_grpc.pb.go b/internal/contracts/secretengine/v1/secretengine_grpc.pb.go index 18961e554..6bf9310c5 100644 --- a/internal/contracts/secretengine/v1/secretengine_grpc.pb.go +++ b/internal/contracts/secretengine/v1/secretengine_grpc.pb.go @@ -8,6 +8,7 @@ package secretenginev1 import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 9fae3ecd6..628769be4 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -7,12 +7,13 @@ package statev1 import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) const ( diff --git a/internal/contracts/state/v1/state_grpc.pb.go b/internal/contracts/state/v1/state_grpc.pb.go index ec010ca56..ead374bbc 100644 --- a/internal/contracts/state/v1/state_grpc.pb.go +++ b/internal/contracts/state/v1/state_grpc.pb.go @@ -8,6 +8,7 @@ package statev1 import ( context "context" + grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 71d160e7d..24f66a58a 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -17,6 +17,8 @@ import ( "sync/atomic" "time" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" @@ -1642,7 +1644,7 @@ func (d *Daemon) recordPark(ctx context.Context, taskID int64, reason string) { // runViaAgent hands a task to archie-agent and waits for its result. It parks // the task only when the agent never answered or failed before recording an // outcome. -func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo config.Repo, profile config.AgentProfile, harness *agentexec.HarnessSpec) { +func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo config.Repo, profile config.AgentProfile, harness *agentrun.HarnessSpec) { grant, revoke, ok := d.publicationGrant(ctx, task) if !ok { return diff --git a/internal/agentexec/protocol.go b/internal/domain/agentrun/protocol.go similarity index 97% rename from internal/agentexec/protocol.go rename to internal/domain/agentrun/protocol.go index d16b4468e..5d9052d46 100644 --- a/internal/agentexec/protocol.go +++ b/internal/domain/agentrun/protocol.go @@ -1,7 +1,6 @@ -// Package agentexec defines worker-local workflow-stage execution. archie-agent -// owns workflow orchestration; authority-bearing forge, store, and push effects -// remain daemon-owned behind scoped RPC boundaries. -package agentexec +// Package agentrun is the contract between the daemon and an agent stage: the +// request a stage runs, the result it returns, and the runner that executes it. +package agentrun import ( "encoding/json" diff --git a/internal/domain/agentrun/runner.go b/internal/domain/agentrun/runner.go new file mode 100644 index 000000000..39df40658 --- /dev/null +++ b/internal/domain/agentrun/runner.go @@ -0,0 +1,23 @@ +package agentrun + +import "context" + +// Runner executes one autonomous stage against an already prepared workspace. +type Runner interface { + // report, when non-nil, is notified once per completed tool call. + Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) +} + +// ToolCallReport is one completed tool invocation, reported through a +// ToolCallReporter. +type ToolCallReport struct { + Tool string + // Detail is a clipped one-line summary: the tool's result, or + // "error: " if it failed. + Detail string + Failed bool +} + +// ToolCallReporter receives one ToolCallReport per completed tool call. A nil +// reporter is valid and reports nothing. +type ToolCallReporter func(ToolCallReport) diff --git a/internal/domain/eda/module/log/logextract/github_com-samcharles93-archie-core-internal-domain-eda-module-log.go b/internal/domain/eda/module/log/logextract/github_com-samcharles93-archie-core-internal-domain-eda-module-log.go index 5ca61b70e..4d490d124 100644 --- a/internal/domain/eda/module/log/logextract/github_com-samcharles93-archie-core-internal-domain-eda-module-log.go +++ b/internal/domain/eda/module/log/logextract/github_com-samcharles93-archie-core-internal-domain-eda-module-log.go @@ -3,10 +3,11 @@ package logextract import ( - "github.com/samcharles93/archie-core/internal/domain/eda/module/log" "go/constant" "go/token" "reflect" + + "github.com/samcharles93/archie-core/internal/domain/eda/module/log" ) func init() { diff --git a/internal/domain/workflow/agent.go b/internal/domain/workflow/agent.go index 80b5123c8..3e2619986 100644 --- a/internal/domain/workflow/agent.go +++ b/internal/domain/workflow/agent.go @@ -7,7 +7,8 @@ import ( "path/filepath" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/skill" @@ -25,7 +26,7 @@ type AgentStage struct { Mission func(*TaskContext) string // Gate returns the stage's quality gate; nil means ungated (e.g. // read-only analysis stages). - Gate func(*TaskContext) agentexec.Gate + Gate func(*TaskContext) agentrun.Gate // ExtraRules is appended to the system prompt. ExtraRules string // MaxSteps overrides the configured step budget when > 0 (planner @@ -36,15 +37,15 @@ type AgentStage struct { ProtectGlobs func(*TaskContext) []string // CaptureTools adds structured-output tools whose calls are returned // as data rather than receiving callbacks into daemon state. - CaptureTools func(*TaskContext) []agentexec.CaptureTool + CaptureTools func(*TaskContext) []agentrun.CaptureTool // OnResult consumes a successful (passed) result. Parked and idle // results park the workflow before OnResult is called. - OnResult func(*TaskContext, agentexec.Result) error + OnResult func(*TaskContext, agentrun.Result) error // ReviewResult gates agent output before OnResult forwards it to human // channels. The daemon calls this hook to review stage output (issue // comments, PR bodies) before human delivery. Return an error to block the // stage. Nil means pass-through -- no review. - ReviewResult func(*TaskContext, agentexec.Result) error + ReviewResult func(*TaskContext, agentrun.Result) error } // Stage adapts the AgentStage to the engine. @@ -69,7 +70,7 @@ func (a AgentStage) Stage() Stage { } // The agent call is a child of the stage's recorded step: the store // says what the stage's runtime did, not just what the stage did. - res, runErr := tc.RunAgentChild(ctx, a.Name, func() (agentexec.Result, error) { + res, runErr := tc.RunAgentChild(ctx, a.Name, func() (agentrun.Result, error) { return tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter(a.Name)) }) return a.handleResult(ctx, tc, req, res, runErr, modelRef) @@ -89,9 +90,9 @@ func (a AgentStage) resolveModel(tc *TaskContext) (string, error) { return modelRef, nil } -// buildRequest assembles the agentexec.Request for this stage's run. -func (a AgentStage) buildRequest(tc *TaskContext, modelRef string) (agentexec.Request, error) { - budget := agentexec.Budget{ +// buildRequest assembles the agentrun.Request for this stage's run. +func (a AgentStage) buildRequest(tc *TaskContext, modelRef string) (agentrun.Request, error) { + budget := agentrun.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std(), } @@ -99,37 +100,37 @@ func (a AgentStage) buildRequest(tc *TaskContext, modelRef string) (agentexec.Re budget.MaxSteps = a.MaxSteps } - var gate agentexec.Gate + var gate agentrun.Gate if a.Gate != nil { gate = a.Gate(tc) } - var captureTools []agentexec.CaptureTool + var captureTools []agentrun.CaptureTool if a.CaptureTools != nil { captureTools = a.CaptureTools(tc) } captureTools, err := tc.appendOutputTools(captureTools) if err != nil { - return agentexec.Request{}, err + return agentrun.Request{}, err } - protection := agentexec.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)} + protection := agentrun.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)} if a.ProtectGlobs != nil { protection.Globs = a.ProtectGlobs(tc) } if a.ReadOnly { - protection = agentexec.Protection{} + protection = agentrun.Protection{} } - var preflight []agentexec.Command + var preflight []agentrun.Command for _, argv := range tc.Repo.ResolvedPreflight() { if len(argv) == 0 { continue } - preflight = append(preflight, agentexec.Command{Name: argv[0], Argv: argv}) + preflight = append(preflight, agentrun.Command{Name: argv[0], Argv: argv}) } - return agentexec.Request{ - Version: agentexec.ProtocolVersion, + return agentrun.Request{ + Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, Stage: a.Name, @@ -168,7 +169,7 @@ func (a AgentStage) buildExtraRules(tc *TaskContext) string { // handleResult records guardrail state, validates and persists the agent // result, then dispatches to ReviewResult/OnResult on success. func (a AgentStage) handleResult( - ctx context.Context, tc *TaskContext, req agentexec.Request, res agentexec.Result, runErr error, modelRef string, + ctx context.Context, tc *TaskContext, req agentrun.Request, res agentrun.Result, runErr error, modelRef string, ) error { a.recordGuardrails(tc, res, runErr) @@ -196,11 +197,11 @@ func (a AgentStage) handleResult( // recordGuardrails feeds this run's outcome to the guardrail engine: on // success it checks no-progress thresholds, on failure it records the // error pattern. -func (a AgentStage) recordGuardrails(tc *TaskContext, res agentexec.Result, runErr error) { +func (a AgentStage) recordGuardrails(tc *TaskContext, res agentrun.Result, runErr error) { if tc.Guardrails == nil { return } - if runErr == nil && res.Status == agentexec.StatusPassed { + if runErr == nil && res.Status == agentrun.StatusPassed { tc.Guardrails.RecordSuccess("agent:" + a.Name) } else if runErr != nil { tc.Guardrails.RecordFailure("agent:"+a.Name, runErr) @@ -208,7 +209,7 @@ func (a AgentStage) recordGuardrails(tc *TaskContext, res agentexec.Result, runE } // persistAppendedNotes saves any notes the agent appended during the run. -func persistAppendedNotes(ctx context.Context, tc *TaskContext, res agentexec.Result) error { +func persistAppendedNotes(ctx context.Context, tc *TaskContext, res agentrun.Result) error { if len(res.AppendedNotes) == 0 { return nil } @@ -222,8 +223,8 @@ func persistAppendedNotes(ctx context.Context, tc *TaskContext, res agentexec.Re } // deliverResult checks the run passed, then runs ReviewResult and OnResult. -func (a AgentStage) deliverResult(tc *TaskContext, res agentexec.Result) error { - if res.Status != agentexec.StatusPassed { +func (a AgentStage) deliverResult(tc *TaskContext, res agentrun.Result) error { + if res.Status != agentrun.StatusPassed { detail := res.Detail if detail == "" { detail = res.Summary @@ -256,7 +257,7 @@ func modelContextBudget(cfg config.Config, modelRef string) int { // accumulateUsage adds a single agent run's token breakdown onto a // workflow-run running total. Extracted so every accumulation site (agent.go // and implement.go's baseline-fix repair loop) stays in sync. -func accumulateUsage(total *agentexec.Usage, delta agentexec.Usage) { +func accumulateUsage(total *agentrun.Usage, delta agentrun.Usage) { total.PromptTokens += delta.PromptTokens total.CompletionTokens += delta.CompletionTokens total.TotalTokens += delta.TotalTokens @@ -264,7 +265,7 @@ func accumulateUsage(total *agentexec.Usage, delta agentexec.Usage) { total.CacheCreationTokens += delta.CacheCreationTokens } -func agentFinishData(res agentexec.Result, modelRef string) map[string]any { +func agentFinishData(res agentrun.Result, modelRef string) map[string]any { return map[string]any{ "status": res.Status, "stop_reason": res.StopReason, "tokens": res.TokensUsed, "iterations": res.Iterations, "model": modelRef, @@ -275,25 +276,25 @@ func agentFinishData(res agentexec.Result, modelRef string) map[string]any { // GateFromRepo converts the repo's configured command lists into an // agent execution gate. -func GateFromRepo(repo config.Repo, budgets config.Budgets) agentexec.Gate { - cmds := make([]agentexec.Command, 0, len(repo.Gate)) +func GateFromRepo(repo config.Repo, budgets config.Budgets) agentrun.Gate { + cmds := make([]agentrun.Command, 0, len(repo.Gate)) for _, argv := range repo.Gate { if len(argv) == 0 { continue } - cmds = append(cmds, agentexec.Command{Name: argv[0], Argv: argv}) + cmds = append(cmds, agentrun.Command{Name: argv[0], Argv: argv}) } - return agentexec.Gate{Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures} + return agentrun.Gate{Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures} } -// pluginSpecs converts skill.Plugin to agentexec.PluginSpec for transport. -func pluginSpecs(plugins []skill.Plugin) []agentexec.PluginSpec { +// pluginSpecs converts skill.Plugin to agentrun.PluginSpec for transport. +func pluginSpecs(plugins []skill.Plugin) []agentrun.PluginSpec { if len(plugins) == 0 { return nil } - out := make([]agentexec.PluginSpec, len(plugins)) + out := make([]agentrun.PluginSpec, len(plugins)) for i, p := range plugins { - out[i] = agentexec.PluginSpec{Name: p.Name, Src: p.Src} + out[i] = agentrun.PluginSpec{Name: p.Name, Src: p.Src} } return out } diff --git a/internal/domain/workflow/agent_run.go b/internal/domain/workflow/agent_run.go index bd9310cd3..fbc98a63d 100644 --- a/internal/domain/workflow/agent_run.go +++ b/internal/domain/workflow/agent_run.go @@ -6,9 +6,9 @@ import ( "fmt" "strings" - "gopkg.in/yaml.v3" + "github.com/samcharles93/archie-core/internal/domain/agentrun" - "github.com/samcharles93/archie-core/internal/agentexec" + "gopkg.in/yaml.v3" ) // AgentRunStepName is the step type that runs one agent mission and finishes @@ -52,7 +52,7 @@ func newAgentRunStage(settings yaml.Node) (Stage, error) { Role: role, ReadOnly: s.ReadOnly, Mission: func(*TaskContext) string { return s.Mission }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.Outcome = Outcome{Status: StatusCompleted, Detail: res.Summary} return nil }, diff --git a/internal/domain/workflow/command_run.go b/internal/domain/workflow/command_run.go index f6b3d0eb0..a90a622b8 100644 --- a/internal/domain/workflow/command_run.go +++ b/internal/domain/workflow/command_run.go @@ -6,9 +6,9 @@ import ( "os/exec" "strings" - "gopkg.in/yaml.v3" + "github.com/samcharles93/archie-core/internal/domain/agentrun" - "github.com/samcharles93/archie-core/internal/agentexec" + "gopkg.in/yaml.v3" ) // CommandRunStepName is the step type that runs operator-authored argv in the @@ -31,7 +31,7 @@ type commandRunSettings struct { } // commandRunCommand is one command in a command.run step's settings. It is -// the YAML shape of agentexec.Command. +// the YAML shape of agentrun.Command. type commandRunCommand struct { Name string `yaml:"name"` Argv []string `yaml:"argv"` @@ -40,8 +40,8 @@ type commandRunCommand struct { // command converts the settings shape into the type the execution path takes, // so command.run and the repository gate share one command meaning. -func (c commandRunCommand) command() agentexec.Command { - return agentexec.Command{Name: c.Name, Argv: c.Argv, ExpectFailure: c.ExpectFailure} +func (c commandRunCommand) command() agentrun.Command { + return agentrun.Command{Name: c.Name, Argv: c.Argv, ExpectFailure: c.ExpectFailure} } // CommandRunStepType contributes the command.run step type. @@ -65,7 +65,7 @@ func newCommandRunStage(settings yaml.Node) (Stage, error) { if len(s.Run) == 0 { return Stage{}, fmt.Errorf("%s: settings.run needs at least one command", CommandRunStepName) } - commands := make([]agentexec.Command, 0, len(s.Run)) + commands := make([]agentrun.Command, 0, len(s.Run)) for i := range s.Run { if len(s.Run[i].Argv) == 0 { return Stage{}, fmt.Errorf("%s: settings.run[%d].argv is required", CommandRunStepName, i) @@ -110,7 +110,7 @@ func newCommandRunStage(settings yaml.Node) (Stage, error) { // runCommands executes argv commands in dir, in order, without a shell, and // returns the first failure's clipped output. ExpectFailure inverts a // command's result. -func runCommands(ctx context.Context, commands []agentexec.Command, dir string) (string, error) { +func runCommands(ctx context.Context, commands []agentrun.Command, dir string) (string, error) { for _, c := range commands { cmd := exec.CommandContext(ctx, c.Argv[0], c.Argv[1:]...) cmd.Dir = dir diff --git a/internal/domain/workflow/feasibility.go b/internal/domain/workflow/feasibility.go index 35c4d75fc..9300c2f9c 100644 --- a/internal/domain/workflow/feasibility.go +++ b/internal/domain/workflow/feasibility.go @@ -8,7 +8,7 @@ import ( "net/http" "time" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // The operator answers in chat or on the dashboard -- the decision surfaces -- @@ -36,7 +36,7 @@ func Feasibility() Workflow { tc.Repo.FullName(), taskPromptBlock(tc.Task), ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { calls := res.Captures["decide"] if len(calls) != 1 { return fmt.Errorf("assess stage called the decide tool %d times (want exactly once)", len(calls)) @@ -82,7 +82,7 @@ func Feasibility() Workflow { tc.Repo.FullName(), taskPromptBlock(tc.Task), tc.decision.Reasons, ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.Task.Plan = res.Summary return nil }, @@ -111,7 +111,7 @@ type decision struct { // decideCaptureTools gives the assess agent a structured verdict tool. Its // arguments cross the execution boundary as data and are applied by OnResult. -func decideCaptureTools(*TaskContext) []agentexec.CaptureTool { +func decideCaptureTools(*TaskContext) []agentrun.CaptureTool { params := json.RawMessage(`{ "type": "object", "properties": { @@ -120,7 +120,7 @@ func decideCaptureTools(*TaskContext) []agentexec.CaptureTool { }, "required": ["fit", "reasons"] }`) - return []agentexec.CaptureTool{{ + return []agentrun.CaptureTool{{ Name: "decide", Description: "Record the feasibility verdict. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"fit", "reasons"}, NonEmptyStrings: []string{"reasons"}, BooleanFields: []string{"fit"}, MaxCalls: 1, diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index 936244f61..fd8377606 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -6,7 +6,8 @@ import ( "os/exec" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/events" ) @@ -74,8 +75,8 @@ func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []b ) modelRef := tc.Cfg.Models["builder"] - req := agentexec.Request{ - Version: agentexec.ProtocolVersion, + req := agentrun.Request{ + Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, Stage: "baseline-fix", @@ -83,15 +84,15 @@ func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []b Model: modelRef, ContextWindow: modelContextBudget(tc.Cfg, modelRef), Mission: mission, - Budget: agentexec.Budget{ + Budget: agentrun.Budget{ MaxSteps: tc.Cfg.Budgets.MaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std(), }, Gate: GateFromRepo(tc.Repo, tc.Cfg.Budgets), - Protection: agentexec.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)}, + Protection: agentrun.Protection{Suffixes: append([]string(nil), tc.Repo.Protect...)}, } - res, agentErr := tc.RunAgentChild(ctx, "baseline-fix", func() (agentexec.Result, error) { + res, agentErr := tc.RunAgentChild(ctx, "baseline-fix", func() (agentrun.Result, error) { return tc.Agent.Run(ctx, tc.Dir, req, tc.toolCallReporter("baseline-fix")) }) if agentErr != nil && res.Version == 0 { @@ -106,7 +107,7 @@ func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []b if agentErr != nil { return baselineFixFailedError(argv, string(out), fmt.Sprintf("the builder could not run: %v", agentErr)) } - if res.Status != agentexec.StatusPassed { + if res.Status != agentrun.StatusPassed { return baselineFixFailedError(argv, string(out), "builder status "+res.Status) } @@ -154,7 +155,7 @@ func Implement() Workflow { taskKind(tc.Task), tc.Repo.FullName(), taskPromptBlock(tc.Task), ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.Task.Plan = res.Summary return nil }, @@ -163,7 +164,7 @@ func Implement() Workflow { AgentStage{ Name: "build", Role: "builder", - Gate: func(tc *TaskContext) agentexec.Gate { + Gate: func(tc *TaskContext) agentrun.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, ExtraRules: "Files matching the repository's protected suffixes (e.g. generated code) are " + @@ -179,9 +180,9 @@ func Implement() Workflow { taskKind(tc.Task), tc.Repo.FullName(), taskPromptBlock(tc.Task), tc.Task.Plan, ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.BuildSummary = res.Summary - if res.Status == agentexec.StatusPassed && len(res.Changes) == 0 && !tc.BaselineFixed { + if res.Status == agentrun.StatusPassed && len(res.Changes) == 0 && !tc.BaselineFixed { tc.BuildNoChanges = true } return nil diff --git a/internal/domain/workflow/outputs.go b/internal/domain/workflow/outputs.go index ece035f0f..2711c50db 100644 --- a/internal/domain/workflow/outputs.go +++ b/internal/domain/workflow/outputs.go @@ -7,7 +7,8 @@ import ( "slices" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) @@ -64,7 +65,7 @@ func (tc *TaskContext) WriteOutput(name string, value any) error { // as: named after the output, whose arguments are {"value": ...}, with the // declared type as the value's schema. The schema guides the agent; the // run-time re-check is what enforces. -func outputCaptureTool(name string, spec task.OutputSpec) agentexec.CaptureTool { +func outputCaptureTool(name string, spec task.OutputSpec) agentrun.CaptureTool { value := map[string]any{"description": fmt.Sprintf("The value of the %q output.", name)} if typ := jsonSchemaType(spec.Type); typ != "" { value["type"] = typ @@ -79,7 +80,7 @@ func outputCaptureTool(name string, spec task.OutputSpec) agentexec.CaptureTool // through RequiredFields alone if it ever did. params = []byte(`{"type":"object"}`) } - return agentexec.CaptureTool{ + return agentrun.CaptureTool{ Name: name, Description: fmt.Sprintf("Write the workflow output %q. Call exactly once, with the value as the value argument.", name), Parameters: params, @@ -107,7 +108,7 @@ func jsonSchemaType(vocab string) string { // appendOutputTools offers the declared outputs the run has not written yet // to this stage as capture tools, refusing a stage capture tool that shares a // declared output's name: the value would otherwise be ambiguous. -func (tc *TaskContext) appendOutputTools(tools []agentexec.CaptureTool) ([]agentexec.CaptureTool, error) { +func (tc *TaskContext) appendOutputTools(tools []agentrun.CaptureTool) ([]agentrun.CaptureTool, error) { iface := tc.workflowInterface() for _, tool := range tools { if _, clash := iface.Outputs[tool.Name]; clash { @@ -128,7 +129,7 @@ func (tc *TaskContext) appendOutputTools(tools []agentexec.CaptureTool) ([]agent // agent result carries: the accepted call's value member is the output's // value, re-validated against the declared type the way readCaptures // re-checks every record, before it enters the run's set. -func (tc *TaskContext) applyOutputCaptures(res agentexec.Result) error { +func (tc *TaskContext) applyOutputCaptures(res agentrun.Result) error { iface := tc.workflowInterface() for name, calls := range res.Captures { spec, ok := iface.Outputs[name] diff --git a/internal/domain/workflow/prreview_stages.go b/internal/domain/workflow/prreview_stages.go index 3bbd1c13a..77def9917 100644 --- a/internal/domain/workflow/prreview_stages.go +++ b/internal/domain/workflow/prreview_stages.go @@ -11,7 +11,8 @@ import ( "sync/atomic" "time" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/taskstate" @@ -242,7 +243,7 @@ func scoreAIGenerated(ctx context.Context, tc *TaskContext, meta PRMetadata) (fl "with status \"passed\".", meta.Title, meta.Body, strings.Join(meta.Commits, "\n"), ) - res, err := runPRReviewAgent(ctx, tc, scratch, "intake-ai-score", "classification", mission, 6, []agentexec.CaptureTool{{ + res, err := runPRReviewAgent(ctx, tc, scratch, "intake-ai-score", "classification", mission, 6, []agentrun.CaptureTool{{ Name: "score_ai_generated", Description: "Record the machine-written confidence. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"confidence"}, MaxCalls: 1, }}) @@ -411,7 +412,7 @@ func runLens(ctx context.Context, tc *TaskContext, name, angle string) ([]prrevi name, angle, tc.prReview.metadata.Title, tc.prReview.metadata.Body, clip(tc.prReview.diff, 60000), operatorInstructionsBlock(tc), ) - res, err := runPRReviewAgent(ctx, tc, tc.prReview.snapshotDir, "lens-"+name, "review", mission, 15, []agentexec.CaptureTool{{ + res, err := runPRReviewAgent(ctx, tc, tc.prReview.snapshotDir, "lens-"+name, "review", mission, 15, []agentrun.CaptureTool{{ Name: "propose_dimensions", Description: "Record this lens's proposed review dimensions. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"dimensions"}, MaxCalls: 1, }}) @@ -480,8 +481,8 @@ func runReviewer(ctx context.Context, tc *TaskContext, dim prreview.Dimension) [ dim.Prompt, strings.Join(dim.TargetFiles, ", "), operatorInstructionsBlock(tc), ) name := "reviewer-" + dim.Name - res, runErr := runReviewerAgent(ctx, tc, name, mission, []agentexec.CaptureTool{reportFindingsTool}) - if runErr != nil || res.Status != agentexec.StatusPassed { + res, runErr := runReviewerAgent(ctx, tc, name, mission, []agentrun.CaptureTool{reportFindingsTool}) + if runErr != nil || res.Status != agentrun.StatusPassed { tc.prReview.reviewerFailures.Add(1) return nil } @@ -521,7 +522,7 @@ var reportFindingsSchema = json.RawMessage(`{ // reportFindingsTool is the capture tool every findings-reporting call // registers, at the shape reportFindingsSchema names. -var reportFindingsTool = agentexec.CaptureTool{ +var reportFindingsTool = agentrun.CaptureTool{ Name: "report_findings", Description: "Record findings. Call exactly once, before finish.", Parameters: reportFindingsSchema, RequiredFields: []string{"findings"}, MaxCalls: 1, } @@ -573,23 +574,23 @@ const prReviewMaxSteps = 25 // runReviewerAgent runs one reviewer call and records its step as failed when // it stopped before its terminal tool call, succeeded otherwise. func runReviewerAgent( - ctx context.Context, tc *TaskContext, name, mission string, captureTools []agentexec.CaptureTool, -) (agentexec.Result, error) { + ctx context.Context, tc *TaskContext, name, mission string, captureTools []agentrun.CaptureTool, +) (agentrun.Result, error) { modelRef := tc.Cfg.Models["review"] if modelRef == "" { - return agentexec.Result{}, fmt.Errorf("no model configured for role %q (set [models] in config)", "review") + return agentrun.Result{}, fmt.Errorf("no model configured for role %q (set [models] in config)", "review") } - req := agentexec.Request{ - Version: agentexec.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, + req := agentrun.Request{ + Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, Stage: name, Workflow: tc.Task.Workflow, Model: modelRef, ContextWindow: modelContextBudget(tc.Cfg, modelRef), Mission: mission, ReadOnly: true, - Budget: agentexec.Budget{MaxSteps: prReviewMaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()}, + Budget: agentrun.Budget{MaxSteps: prReviewMaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()}, CaptureTools: captureTools, } stepID, _, err := tc.startChildStep(ctx, task.StepKindAgent, name) if err != nil { - return agentexec.Result{}, err + return agentrun.Result{}, err } res, runErr := tc.Agent.Run(ctx, tc.prReview.snapshotDir, req, tc.toolCallReporter(name)) tc.prReview.tokensSpent.Add(int64(res.TokensUsed)) @@ -597,7 +598,7 @@ func runReviewerAgent( switch { case runErr != nil: to, detail = taskstate.StepFailed, runErr.Error() - case res.Status != agentexec.StatusPassed: + case res.Status != agentrun.StatusPassed: to, detail = taskstate.StepFailed, fmt.Sprintf("reviewer did not complete (%s: %s)", res.Status, res.StopReason) } if ferr := tc.finishChildStep(ctx, stepID, to, detail, int64(res.TokensUsed)); ferr != nil { @@ -674,7 +675,7 @@ func polishFinding(ctx context.Context, tc *TaskContext, f prreview.ScoredFindin "call finish with status \"passed\".", f.Title, f.Body, ) - res, err := runPRReviewAgent(ctx, tc, tc.prReview.snapshotDir, "polish", "classification", mission, 4, []agentexec.CaptureTool{{ + res, err := runPRReviewAgent(ctx, tc, tc.prReview.snapshotDir, "polish", "classification", mission, 4, []agentrun.CaptureTool{{ Name: "polish", Description: "Record the tightened comment body. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"body"}, MaxCalls: 1, }}) @@ -740,13 +741,13 @@ func postPRReview(ctx context.Context, tc *TaskContext) error { // runPRReviewAgent runs one read-only agent call in workspace and returns an // error for any result that did not pass. func runPRReviewAgent( - ctx context.Context, tc *TaskContext, workspace, name, role, mission string, maxSteps int, captureTools []agentexec.CaptureTool, -) (agentexec.Result, error) { + ctx context.Context, tc *TaskContext, workspace, name, role, mission string, maxSteps int, captureTools []agentrun.CaptureTool, +) (agentrun.Result, error) { res, err := runPRReviewAgentRecorded(ctx, tc, workspace, name, role, mission, maxSteps, captureTools) if err != nil { return res, err } - if res.Status != agentexec.StatusPassed { + if res.Status != agentrun.StatusPassed { detail := res.Detail if detail == "" { detail = res.Summary @@ -759,21 +760,21 @@ func runPRReviewAgent( // runPRReviewAgentRecorded builds the request for a pr-review agent call, // records its step, and returns the runtime's result unchanged. func runPRReviewAgentRecorded( - ctx context.Context, tc *TaskContext, workspace, name, role, mission string, maxSteps int, captureTools []agentexec.CaptureTool, -) (agentexec.Result, error) { + ctx context.Context, tc *TaskContext, workspace, name, role, mission string, maxSteps int, captureTools []agentrun.CaptureTool, +) (agentrun.Result, error) { modelRef := tc.Cfg.Models[role] if modelRef == "" { - return agentexec.Result{}, fmt.Errorf("no model configured for role %q (set [models] in config)", role) + return agentrun.Result{}, fmt.Errorf("no model configured for role %q (set [models] in config)", role) } - req := agentexec.Request{ - Version: agentexec.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, + req := agentrun.Request{ + Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt, Stage: name, Workflow: tc.Task.Workflow, Model: modelRef, ContextWindow: modelContextBudget(tc.Cfg, modelRef), Mission: mission, ReadOnly: true, - Budget: agentexec.Budget{MaxSteps: maxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()}, + Budget: agentrun.Budget{MaxSteps: maxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()}, CaptureTools: captureTools, } - res, err := tc.RunAgentChild(ctx, name, func() (agentexec.Result, error) { + res, err := tc.RunAgentChild(ctx, name, func() (agentrun.Result, error) { return tc.Agent.Run(ctx, workspace, req, tc.toolCallReporter(name)) }) tc.prReview.tokensSpent.Add(int64(res.TokensUsed)) diff --git a/internal/domain/workflow/prreview_stages_verify.go b/internal/domain/workflow/prreview_stages_verify.go index 475c40d27..20ddce5fd 100644 --- a/internal/domain/workflow/prreview_stages_verify.go +++ b/internal/domain/workflow/prreview_stages_verify.go @@ -8,7 +8,8 @@ import ( "strings" "sync" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/domain/workflow/prreview" "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) @@ -94,11 +95,11 @@ func runPrecisionGate(ctx context.Context, tc *TaskContext, findings []prreview. "finish with status \"passed\".", listing.String(), ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "precision-gate", "classification", mission, 15, []agentexec.CaptureTool{{ + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "precision-gate", "classification", mission, 15, []agentrun.CaptureTool{{ Name: "precision_gate", Description: "Record each finding's keep/drop verdict. Call exactly once, before finish.", Parameters: precisionGateSchema, RequiredFields: []string{"verdicts"}, MaxCalls: 1, }}) - if err != nil || res.Status != agentexec.StatusPassed { + if err != nil || res.Status != agentrun.StatusPassed { return findings //nolint:nilerr // recall-first: a gate that could not run is not evidence any finding should drop } calls := res.Captures["precision_gate"] @@ -240,11 +241,11 @@ func runEvidenceVerifier(ctx context.Context, tc *TaskContext, findings []prrevi "call finish with status \"passed\".", evidenceListing(tc, candidates), ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "evidence-verifier", "review", mission, 15, []agentexec.CaptureTool{{ + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "evidence-verifier", "review", mission, 15, []agentrun.CaptureTool{{ Name: "verify_findings", Description: "Record each finding's evidence verdict. Call exactly once, before finish.", Parameters: verifyFindingsSchema, RequiredFields: []string{"verdicts"}, MaxCalls: 1, }}) - if err != nil || res.Status != agentexec.StatusPassed { + if err != nil || res.Status != agentrun.StatusPassed { return findings, nil //nolint:nilerr // recall-first: a verifier that could not run is not evidence any finding is wrong, so nothing is filtered } calls := res.Captures["verify_findings"] @@ -366,14 +367,14 @@ func runAdversary(ctx context.Context, tc *TaskContext, findings []prreview.Find "nothing new). Then call finish with status \"passed\".", adversarySkepticism(tc.prReview.aiGenerated), findingsListing(findings), ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "adversary", "review", mission, 25, []agentexec.CaptureTool{ + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "adversary", "review", mission, 25, []agentrun.CaptureTool{ { Name: "adversary_verdicts", Description: "Record each finding's adversary verdict. Call exactly once, before finish.", Parameters: adversaryVerdictsSchema, RequiredFields: []string{"verdicts"}, MaxCalls: 1, }, reportFindingsTool, }) - if err != nil || res.Status != agentexec.StatusPassed { + if err != nil || res.Status != agentrun.StatusPassed { return findings, nil //nolint:nilerr // a call that could not run reached no verdict, which the pipeline treats as neutral, not as a stage failure } @@ -450,11 +451,11 @@ func runCompoundClusterCheck(ctx context.Context, tc *TaskContext, clusterID str "once with the indices of the findings that compound (an empty array if none "+ "do). Then call finish with status \"passed\".\n\n%s", listing.String(), ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "compound-"+clusterID, "review", mission, 15, []agentexec.CaptureTool{{ + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "compound-"+clusterID, "review", mission, 15, []agentrun.CaptureTool{{ Name: "compound_findings", Description: "Record which findings compound. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"indices"}, MaxCalls: 1, }}) - if err != nil || res.Status != agentexec.StatusPassed { + if err != nil || res.Status != agentrun.StatusPassed { return nil //nolint:nilerr // a cluster call that could not run flags nothing rather than failing the whole compound-check stage } calls := res.Captures["compound_findings"] @@ -555,8 +556,8 @@ func runConsistencyVerification(ctx context.Context, tc *TaskContext) error { "held), then call finish with status \"passed\".", clip(tc.prReview.diff, 60000), ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "consistency", "review", mission, 25, []agentexec.CaptureTool{reportFindingsTool}) - if err != nil || res.Status != agentexec.StatusPassed { + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "consistency", "review", mission, 25, []agentrun.CaptureTool{reportFindingsTool}) + if err != nil || res.Status != agentrun.StatusPassed { return nil //nolint:nilerr // a consistency call that could not run reports no broken obligations rather than failing the stage } found, err := decodeReportedFindings(res.Captures["report_findings"], "consistency") @@ -613,11 +614,11 @@ func runMergeGateCall(ctx context.Context, tc *TaskContext, f prreview.ScoredFin "Call classify_blocking exactly once, then call finish with status \"passed\".", f.Severity, f.Title, f.File, f.LineStart, f.Body, ) - res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "merge-gate", "classification", mission, 6, []agentexec.CaptureTool{{ + res, err := runPRReviewAgentRecorded(ctx, tc, tc.prReview.snapshotDir, "merge-gate", "classification", mission, 6, []agentrun.CaptureTool{{ Name: "classify_blocking", Description: "Record the blocking verdict. Call exactly once, before finish.", Parameters: mergeGateSchema, RequiredFields: []string{"blocking"}, MaxCalls: 1, }}) - if err != nil || res.Status != agentexec.StatusPassed { + if err != nil || res.Status != agentrun.StatusPassed { return false //nolint:nilerr // a merge-gate call that could not run leaves the finding advisory } calls := res.Captures["classify_blocking"] diff --git a/internal/domain/workflow/remediate.go b/internal/domain/workflow/remediate.go index 1cb2c04a7..05f3ab793 100644 --- a/internal/domain/workflow/remediate.go +++ b/internal/domain/workflow/remediate.go @@ -7,7 +7,7 @@ import ( "fmt" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // ErrNoReviewPayload is returned when a remediate run starts on a task that @@ -170,13 +170,13 @@ func remediateBuildStage() Stage { return AgentStage{ Name: "remediate-build", Role: "builder", - Gate: func(tc *TaskContext) agentexec.Gate { + Gate: func(tc *TaskContext) agentrun.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, Mission: remediateMission, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.BuildSummary = res.Summary - if res.Status == agentexec.StatusPassed && len(res.Changes) == 0 { + if res.Status == agentrun.StatusPassed && len(res.Changes) == 0 { tc.BuildNoChanges = true } return nil diff --git a/internal/domain/workflow/tdd.go b/internal/domain/workflow/tdd.go index 17b8b699b..a643f8591 100644 --- a/internal/domain/workflow/tdd.go +++ b/internal/domain/workflow/tdd.go @@ -7,7 +7,8 @@ import ( "slices" "strings" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/config" ) @@ -57,7 +58,7 @@ func tddAnalyseStage() Stage { taskKind(tc.Task), tc.Repo.FullName(), taskPromptBlock(tc.Task), ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.Task.Plan = res.Summary return nil }, @@ -71,7 +72,7 @@ func tddReproTestsStage() Stage { return AgentStage{ Name: "repro-tests", Role: "builder", - Gate: func(tc *TaskContext) agentexec.Gate { + Gate: func(tc *TaskContext) agentrun.Gate { return tddReproGate(tc.Repo, tc.Cfg.Budgets) }, Mission: func(tc *TaskContext) string { @@ -114,7 +115,7 @@ func tddFixStage() Stage { return AgentStage{ Name: "fix", Role: "builder", - Gate: func(tc *TaskContext) agentexec.Gate { + Gate: func(tc *TaskContext) agentrun.Gate { return GateFromRepo(tc.Repo, tc.Cfg.Budgets) }, ProtectGlobs: func(tc *TaskContext) []string { @@ -136,7 +137,7 @@ func tddFixStage() Stage { tc.Repo.FullName(), taskPromptBlock(tc.Task), tc.Task.Plan, ) }, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { tc.BuildSummary = res.Summary return nil }, @@ -157,22 +158,22 @@ func tddOpenPRStage() Stage { // every command from repo.Gate runs normally except the last one (the // test runner, by convention), which gets ExpectFailure -- the repro // must fail the tests to prove the bug exists. -func tddReproGate(repo config.Repo, budgets config.Budgets) agentexec.Gate { +func tddReproGate(repo config.Repo, budgets config.Budgets) agentrun.Gate { if len(repo.Gate) == 0 { - return agentexec.Gate{} + return agentrun.Gate{} } - cmds := make([]agentexec.Command, 0, len(repo.Gate)) + cmds := make([]agentrun.Command, 0, len(repo.Gate)) for _, argv := range repo.Gate { if len(argv) == 0 { continue } - gc := agentexec.Command{Name: argv[0], Argv: argv} + gc := agentrun.Command{Name: argv[0], Argv: argv} cmds = append(cmds, gc) } if len(cmds) > 0 { cmds[len(cmds)-1].ExpectFailure = true } - return agentexec.Gate{ + return agentrun.Gate{ Commands: cmds, MaxConsecutiveFailures: budgets.GateMaxFailures, } diff --git a/internal/domain/workflow/triage.go b/internal/domain/workflow/triage.go index 148e483ca..f200fc9e9 100644 --- a/internal/domain/workflow/triage.go +++ b/internal/domain/workflow/triage.go @@ -5,7 +5,7 @@ import ( "encoding/json" "fmt" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" ) // triageWorkflowNames is the set of workflows triage may hand a task to. @@ -30,7 +30,7 @@ func Triage() Workflow { ReadOnly: true, CaptureTools: triageDecideCaptureTools, Mission: triageMission, - OnResult: func(tc *TaskContext, res agentexec.Result) error { + OnResult: func(tc *TaskContext, res agentrun.Result) error { calls := res.Captures["decide"] if len(calls) != 1 { return fmt.Errorf("triage classify stage called the decide tool %d times (want exactly once)", len(calls)) @@ -78,7 +78,7 @@ func Triage() Workflow { // triageDecideCaptureTools gives the classify agent a structured verdict // tool, mirroring feasibility.go's decideCaptureTools. -func triageDecideCaptureTools(*TaskContext) []agentexec.CaptureTool { +func triageDecideCaptureTools(*TaskContext) []agentrun.CaptureTool { params := json.RawMessage(`{ "type": "object", "properties": { @@ -88,7 +88,7 @@ func triageDecideCaptureTools(*TaskContext) []agentexec.CaptureTool { }, "required": ["needs_code_change", "reasons"] }`) - return []agentexec.CaptureTool{{ + return []agentrun.CaptureTool{{ Name: "decide", Description: "Record the triage verdict. Call exactly once, before finish.", Parameters: params, RequiredFields: []string{"needs_code_change", "reasons"}, NonEmptyStrings: []string{"reasons"}, BooleanFields: []string{"needs_code_change"}, diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 420b038f0..f59600b3c 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -10,7 +10,8 @@ import ( "time" "unicode/utf8" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" @@ -81,7 +82,7 @@ type TaskContext struct { Forge Forger Store Store Trees Trees - Agent agentexec.Runner + Agent agentrun.Runner // Calls starts workflow.call callees and reads them back while a // wait:true caller waits. Nil is only safe for a workflow with no // workflow.call step: such a step in a runner with no capability @@ -157,7 +158,7 @@ type TaskContext struct { // RunUsage accumulates this run's token breakdown for PR bodies. Not // persisted; Task.TokensUsed is the total. - RunUsage agentexec.Usage + RunUsage agentrun.Usage } // Emit publishes an observability event stamped with the task and its @@ -203,11 +204,11 @@ func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail stri return nil } -// toolCallReporter builds the agentexec.ToolCallReporter an agent stage passes +// toolCallReporter builds the agentrun.ToolCallReporter an agent stage passes // to tc.Agent.Run, so every completed tool call during that run surfaces as a // tool_call event on the task timeline. Safe to call on a nil Bus: Emit no-ops. -func (tc *TaskContext) toolCallReporter(stage string) agentexec.ToolCallReporter { - return func(report agentexec.ToolCallReport) { +func (tc *TaskContext) toolCallReporter(stage string) agentrun.ToolCallReporter { + return func(report agentrun.ToolCallReport) { tc.Emit(events.KindToolCall, stage, report.Detail, map[string]any{ "tool": report.Tool, "failed": report.Failed, @@ -450,7 +451,7 @@ func clipTail(s string, n int) string { // formatTokenUsage renders a token total split into cached and fresh tokens, // or the plain total when no breakdown exists. -func formatTokenUsage(total int, usage agentexec.Usage) string { +func formatTokenUsage(total int, usage agentrun.Usage) string { if usage.PromptTokens == 0 && usage.CompletionTokens == 0 && usage.CachedTokens == 0 { return fmt.Sprintf("%d tokens", total) } @@ -486,10 +487,10 @@ var goTestOKLine = regexp.MustCompile(`^ok\s+\S+`) // RunAgentChild records one agent call as a child step of the current stage. // A failed write parks the execution. Outside a recorded run it just runs. -func (tc *TaskContext) RunAgentChild(ctx context.Context, name string, run func() (agentexec.Result, error)) (agentexec.Result, error) { +func (tc *TaskContext) RunAgentChild(ctx context.Context, name string, run func() (agentrun.Result, error)) (agentrun.Result, error) { stepID, _, err := tc.startChildStep(ctx, task.StepKindAgent, name) if err != nil { - return agentexec.Result{}, err + return agentrun.Result{}, err } res, runErr := run() to, detail := taskstate.StepSucceeded, res.Summary diff --git a/internal/infrastructure/kit/launch.go b/internal/infrastructure/kit/launch.go index 128b45fed..a904ff4d2 100644 --- a/internal/infrastructure/kit/launch.go +++ b/internal/infrastructure/kit/launch.go @@ -10,9 +10,10 @@ import ( "strings" "time" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/docker/sandbox-kit-spec/v3/spec" - "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/infrastructure/egress" ) @@ -85,7 +86,7 @@ type Volume struct { // Launch is everything archie needs to run a composed Kit for one run. type Launch struct { - Harness agentexec.HarnessSpec + Harness agentrun.HarnessSpec Install []Hook Startup []Hook Files []spec.File @@ -119,7 +120,7 @@ func Assemble(p *Plan, img ImageConfig, params LaunchParams) (Launch, error) { runtimeVars[credentialModeVar(c.Service)] = credentialMode(params.Bound[c.Service]) } - l := Launch{Harness: agentexec.HarnessSpec{ + l := Launch{Harness: agentrun.HarnessSpec{ User: harnessUser(img.User), Launch: slices.Concat(img.Entrypoint, img.Cmd), Env: slices.Concat(img.Env, []string{"WORKSPACE_DIR=" + WorkspaceDir}, proxyEnv, egress.SentinelEnv(creds)), diff --git a/internal/infrastructure/kitrun/launcher.go b/internal/infrastructure/kitrun/launcher.go index 3b3e6a58e..15b5e6276 100644 --- a/internal/infrastructure/kitrun/launcher.go +++ b/internal/infrastructure/kitrun/launcher.go @@ -11,6 +11,8 @@ import ( "slices" "sync" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/docker/sandbox-kit-spec/v3/fetch" "github.com/docker/sandbox-kit-spec/v3/spec" @@ -100,7 +102,7 @@ type Request struct { // Run is a started Kit task. type Run struct { Container *container.Container - Harness agentexec.HarnessSpec + Harness agentrun.HarnessSpec // Volumes outlive the run; remove them with RemoveVolumes once the // execution has ended. Volumes []kit.Volume diff --git a/internal/app/servicekit/catalog.go b/internal/infrastructure/modelcatalog/cache.go similarity index 78% rename from internal/app/servicekit/catalog.go rename to internal/infrastructure/modelcatalog/cache.go index 228fce94d..7b1b2c9de 100644 --- a/internal/app/servicekit/catalog.go +++ b/internal/infrastructure/modelcatalog/cache.go @@ -1,4 +1,4 @@ -package servicekit +package modelcatalog import ( "context" @@ -9,19 +9,18 @@ import ( "time" "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" "github.com/samcharles93/archie-core/internal/secret" ) -// CatalogRefreshInterval is how often a running service re-reads the catalog. -const CatalogRefreshInterval = time.Hour +// RefreshInterval is how often a running service re-reads the catalog. +const RefreshInterval = time.Hour // Catalog holds the last model catalog a service loaded. type Catalog struct { cachePath string mu sync.RWMutex - snapshot modelcatalog.Snapshot + snapshot Snapshot models []string } @@ -31,22 +30,22 @@ func NewCatalog(cfgPath string) *Catalog { } // State returns the loaded snapshot and its model references. -func (c *Catalog) State() (modelcatalog.Snapshot, []string) { +func (c *Catalog) State() (Snapshot, []string) { c.mu.RLock() defer c.mu.RUnlock() return c.snapshot, c.models } // Set records a loaded snapshot and its model references. -func (c *Catalog) Set(snapshot modelcatalog.Snapshot, models []string) { +func (c *Catalog) Set(snapshot Snapshot, models []string) { c.mu.Lock() defer c.mu.Unlock() c.snapshot, c.models = snapshot, models } // Fetch reads the catalog, resolving provider keys through getenv. -func (c *Catalog) Fetch(ctx context.Context, getenv func(string) string, configured map[string]config.Provider) (modelcatalog.Snapshot, error) { - return modelcatalog.Load(ctx, modelcatalog.Options{CachePath: c.cachePath, Getenv: getenv, Configured: configured}) +func (c *Catalog) Fetch(ctx context.Context, getenv func(string) string, configured map[string]config.Provider) (Snapshot, error) { + return Load(ctx, Options{CachePath: c.cachePath, Getenv: getenv, Configured: configured}) } // Every runs fn every interval until ctx ends. @@ -65,9 +64,9 @@ func Every(ctx context.Context, interval time.Duration, fn func()) { }() } -// ApplyModelCatalog layers the catalog's providers and model limits under cfg's +// Apply layers the catalog's providers and model limits under cfg's // own and returns the catalog's model references, sorted. -func ApplyModelCatalog(cfg *config.Config, snapshot modelcatalog.Snapshot) []string { +func Apply(cfg *config.Config, snapshot Snapshot) []string { discovered := make(map[string]config.Provider, len(snapshot.Providers)) limits := make(map[string]config.ModelLimits) var models []string diff --git a/internal/infrastructure/secretengine/engine.go b/internal/infrastructure/secretengine/engine.go index d3771c9dd..2ffd46a99 100644 --- a/internal/infrastructure/secretengine/engine.go +++ b/internal/infrastructure/secretengine/engine.go @@ -12,7 +12,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "github.com/samcharles93/archie-core/internal/contracts/secretengine/v1" + secretenginev1 "github.com/samcharles93/archie-core/internal/contracts/secretengine/v1" "github.com/samcharles93/archie-core/internal/infrastructure/extension" ) diff --git a/internal/infrastructure/staterpc/dial.go b/internal/infrastructure/staterpc/dial.go index 03edc800a..a0be8e7ff 100644 --- a/internal/infrastructure/staterpc/dial.go +++ b/internal/infrastructure/staterpc/dial.go @@ -103,3 +103,8 @@ func TargetIsLoopback(addr string) (bool, error) { } return ip.IsLoopback(), nil } + +// WaitForPeer makes calls to the State Store wait for it to come up +// instead of failing while it is down or restarting. A call that must not +// wait carries its own deadline. +var WaitForPeer = grpc.WithDefaultCallOptions(grpc.WaitForReady(true)) diff --git a/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go b/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go index 2987d2770..fa2611406 100644 --- a/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go +++ b/internal/plugin/pluginextract/github_com-samcharles93-archie-core-internal-plugin.go @@ -4,10 +4,11 @@ package pluginextract import ( "context" - "github.com/samcharles93/archie-core/internal/plugin" "go/constant" "go/token" "reflect" + + "github.com/samcharles93/archie-core/internal/plugin" ) func init() { diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go index d688b390d..aae580632 100644 --- a/internal/taskrun/taskrun.go +++ b/internal/taskrun/taskrun.go @@ -6,7 +6,8 @@ import ( "errors" "fmt" - "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/domain/agentrun" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/workflow" ) @@ -14,10 +15,10 @@ import ( // Request is everything archie-agent needs to run a task's workflow. API // keys reach the container as environment variables, not here. type Request struct { - Task *workflow.Task `json:"task"` - Repo config.Repo `json:"repo"` - Cfg config.TaskConfig `json:"cfg"` - Providers map[string]agentexec.Provider `json:"providers"` + Task *workflow.Task `json:"task"` + Repo config.Repo `json:"repo"` + Cfg config.TaskConfig `json:"cfg"` + Providers map[string]agentrun.Provider `json:"providers"` // MCPServers carries MCP server definitions so the agent can construct // transports, discover tools, and register them locally. Absent/empty // means no MCP servers (backward compatible). @@ -36,7 +37,7 @@ type Request struct { Tools []string `json:"tools,omitempty"` // Harness, set for a Kit profile, runs every agent stage on the Kit's // CLI instead of the built-in loop. - Harness *agentexec.HarnessSpec `json:"harness,omitempty"` + Harness *agentrun.HarnessSpec `json:"harness,omitempty"` } // Validate rejects a full-task request that cannot be correlated to a real