refactor(staterpc,releaseupdate,agentexec,storecontract,worktree): cut comments down to what the code does
This commit is contained in:
1 parent
ee5f59e189
commit
2fc11b60e1
22 files changed
+175
-822
No files matched your search
@@ -40,13 +40,9 @@ type LoopRunner struct {
|
||||
// Limits bounds the size of tool results fed back into the stage. The
|
||||
// zero value applies no limits.
|
||||
Limits ToolLimits
|
||||
// AllowTools is the agent profile's allowlist over the tools archie adds
|
||||
// (central/MCP, repository scripts and skill plugins). Empty allows them
|
||||
// all. A stage's capture tools are how it returns structured results, so
|
||||
// they are never filtered. The agent loop's built-in file tools are not
|
||||
// covered either: ai-sdk agentloop registers them itself with no filter
|
||||
// hook, so they are always present (read-only when the stage asks), and
|
||||
// restricting them needs an ai-sdk change.
|
||||
// AllowTools is the profile's allowlist over archie-added tools. Empty allows
|
||||
// all. Capture tools and agentloop's built-in file tools are never
|
||||
// filtered.
|
||||
AllowTools []string
|
||||
}
|
||||
|
||||
@@ -62,16 +58,8 @@ func NewLoopRunner(
|
||||
return runner
|
||||
}
|
||||
|
||||
// workspaceToolset names the central-registry toolset a task agent must not
|
||||
// inherit. Those tools are rooted at the chat workspace, not the task's
|
||||
// worktree, and they reach the filesystem through their own handlers -- so
|
||||
// agentloop's ReadOnly and ProtectPaths, which gate only the tools agentloop
|
||||
// registers itself, do not apply to them. A feasibility stage running
|
||||
// ReadOnly could otherwise write, and a TDD fix stage could edit the very
|
||||
// tests it is being graded against.
|
||||
//
|
||||
// This is an invariant of task execution rather than a deployment choice, so
|
||||
// it is not configurable.
|
||||
// workspaceToolset is the central toolset a task agent never gets: its tools
|
||||
// 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) {
|
||||
@@ -357,12 +345,8 @@ func isNonEmptyString(object map[string]json.RawMessage, field string) bool {
|
||||
return ok && json.Unmarshal(raw, &text) == nil && strings.TrimSpace(text) != ""
|
||||
}
|
||||
|
||||
// scriptToolSet exposes run_go_script: interpreting a Yaegi Go script
|
||||
// bundled with a skill or living
|
||||
// anywhere else in the workspace, and returning what it printed. This is
|
||||
// how an agent following a skill's instructions ("run scripts/gitleaks.go
|
||||
// to scan for secrets") actually executes a .go helper without a Go
|
||||
// toolchain in the sandbox.
|
||||
// scriptToolSet exposes run_go_script, which runs a Yaegi Go script from the
|
||||
// workspace and returns its output.
|
||||
func scriptToolSet(workspace string) core.ToolSet {
|
||||
return core.ToolSet{
|
||||
"run_go_script": core.NewTypedTool(
|
||||
|
||||
@@ -52,13 +52,8 @@ type CaptureTool struct {
|
||||
RequiredFields []string `json:"required_fields,omitempty"`
|
||||
NonEmptyStrings []string `json:"non_empty_strings,omitempty"`
|
||||
BooleanFields []string `json:"boolean_fields,omitempty"`
|
||||
// RequiredWhenTrue makes fields required only when a boolean field in
|
||||
// the same call is true, keyed by that boolean's name. It exists because
|
||||
// a flat RequiredFields entry cannot express "name a workflow, but only
|
||||
// when you have said one is needed": the alternatives were forcing a
|
||||
// meaningless answer on the other branch, or accepting the omission and
|
||||
// defaulting it, which lets the model skip the decision entirely.
|
||||
// A named field must also be a non-empty string when the trigger is true.
|
||||
// RequiredWhenTrue lists fields that must be non-empty strings when the named
|
||||
// boolean field is true.
|
||||
RequiredWhenTrue map[string][]string `json:"required_when_true,omitempty"`
|
||||
MaxCalls int `json:"max_calls,omitempty"`
|
||||
}
|
||||
|
||||
@@ -15,12 +15,8 @@ import (
|
||||
// turn-sized output allowance on a single request.
|
||||
const DefaultSamplingMaxTokens = 4096
|
||||
|
||||
// SamplingMessages maps a server's sampling messages onto chat messages. Both
|
||||
// MCP sampling host paths use it -- the daemon's chat handler and the agent
|
||||
// worker's task handler -- so the same server is answered the same way
|
||||
// wherever the client runs. A non-text content block or an unknown role is
|
||||
// rejected rather than silently dropped: answering from a partial prompt would
|
||||
// be a wrong answer, not a degraded one.
|
||||
// SamplingMessages converts sampling messages to chat messages. Non-text
|
||||
// content and unknown roles are errors.
|
||||
func SamplingMessages(req protocol.SamplingRequest) ([]chat.Message, error) {
|
||||
if len(req.Messages) == 0 {
|
||||
return nil, errors.New("mcp sampling: the request has no messages")
|
||||
@@ -44,13 +40,8 @@ func SamplingMessages(req protocol.SamplingRequest) ([]chat.Message, error) {
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// SamplingMaxTokens bounds a delegated completion to the request's own
|
||||
// maxTokens, falling back to DefaultSamplingMaxTokens, and never past the
|
||||
// model's own output ceiling (zero when the ceiling is unknown). A
|
||||
// reasoning-class model gets no bound at all: its provider rejects the
|
||||
// `max_tokens` parameter the chat-completions provider emits for a non-zero
|
||||
// bound. Both the daemon's chat path and the agent worker answer sampling
|
||||
// with this, so the same server gets the same bound on either path.
|
||||
// SamplingMaxTokens returns the request's maxTokens or the default, capped at
|
||||
// the model's ceiling. Reasoning models get no bound.
|
||||
func SamplingMaxTokens(requested, modelCeiling int, reasoning bool) int {
|
||||
maxTokens := requested
|
||||
if maxTokens <= 0 {
|
||||
|
||||
@@ -6,10 +6,6 @@ import (
|
||||
)
|
||||
|
||||
// Agent observability subjects.
|
||||
//
|
||||
// These belong to this package because it defines what an agent request and
|
||||
// response mean. They previously sat in the NATS package, which made the
|
||||
// transport the owner of Archie's agent protocol.
|
||||
const (
|
||||
// SubjectSystemWildcard matches every task's system subject, for a
|
||||
// daemon subscribing to all of them at once with a single core NATS
|
||||
@@ -46,11 +42,8 @@ func subjectForTask(taskID int64, kind string) string {
|
||||
return subjectAgentPrefix + strconv.FormatInt(taskID, 10) + "." + kind
|
||||
}
|
||||
|
||||
// TaskIDFromSystemSubject extracts the task ID from a subject produced by
|
||||
// SubjectForSystem, for a daemon demuxing a SubjectSystemWildcard
|
||||
// subscription. Rejects (0, false) for anything that isn't exactly that
|
||||
// shape, rather than parsing a partial or wrong-kind subject into a
|
||||
// misleading task ID.
|
||||
// TaskIDFromSystemSubject extracts the task ID from a SubjectForSystem
|
||||
// subject.
|
||||
func TaskIDFromSystemSubject(subject string) (int64, bool) {
|
||||
if !strings.HasPrefix(subject, subjectAgentPrefix) || !strings.HasSuffix(subject, subjectSystemSuffix) {
|
||||
return 0, false
|
||||
@@ -63,11 +56,8 @@ func TaskIDFromSystemSubject(subject string) (int64, bool) {
|
||||
return id, true
|
||||
}
|
||||
|
||||
// TaskIDFromEventsSubject extracts the task ID from a subject produced by
|
||||
// SubjectForEvents, for a daemon demuxing a SubjectEventsWildcard
|
||||
// subscription. Rejects (0, false) for anything that isn't exactly that
|
||||
// shape, rather than parsing a partial or wrong-kind subject into a
|
||||
// misleading task ID.
|
||||
// TaskIDFromEventsSubject extracts the task ID from a SubjectForEvents
|
||||
// subject.
|
||||
func TaskIDFromEventsSubject(subject string) (int64, bool) {
|
||||
if !strings.HasPrefix(subject, subjectAgentPrefix) || !strings.HasSuffix(subject, subjectEventsSuffix) {
|
||||
return 0, false
|
||||
|
||||
@@ -10,41 +10,14 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// LogPublisher is the minimal capability SystemLogHandler needs: fire a
|
||||
// message at a subject without waiting for a reply. Declared here rather
|
||||
// than taking *nats.go's Conn or eventbus.Bus so the handler can be tested
|
||||
// with a fake and never gains capabilities (subscribe, request/reply) it has
|
||||
// no use for. *nats.Conn already satisfies this with no adapter needed.
|
||||
// LogPublisher publishes a message to a subject without waiting.
|
||||
type LogPublisher interface {
|
||||
Publish(subject string, data []byte) error
|
||||
}
|
||||
|
||||
// SystemLogHandler tees slog records to a wrapped handler -- normally the
|
||||
// agent's own stderr, kept for an operator attached to a live container --
|
||||
// and additionally publishes each one, JSON-encoded as a logging.Entry, to
|
||||
// SubjectForSystem(taskID): the return channel documented in subjects.go for
|
||||
// "log dumps, health... observability" that previously had no publisher.
|
||||
//
|
||||
// The wire payload is a marshaled logging.Entry -- {"time","level","msg",
|
||||
// "fields":{...}} -- meant to be round-tripped with json.Unmarshal straight
|
||||
// back into a logging.Entry. This is deliberately NOT the same shape
|
||||
// logging.decode() parses: decode() reads raw slog JSON *log lines* off
|
||||
// disk, where every non-{time,level,msg} key sits at the top level and
|
||||
// decode() moves it into Fields itself. Handing decode() this payload
|
||||
// instead of json.Unmarshal would nest everything one level too deep, under
|
||||
// a literal "fields" key, and silently lose every real field name. A future
|
||||
// consumer of this subject must unmarshal directly
|
||||
// into logging.Entry, not call decode() on these bytes.
|
||||
//
|
||||
// Publishing is fire-and-forget. A core NATS Publish call is already
|
||||
// non-blocking -- it queues to the connection's outbound buffer and returns,
|
||||
// and the client itself drops writes rather than blocking once its
|
||||
// reconnect buffer is full -- so this handler does not duplicate that
|
||||
// behaviour with a second, home-grown bounded queue. A publish or marshal
|
||||
// failure is reported once via the wrapped handler and then swallowed: log
|
||||
// shipping must never block or fail the run it is reporting on, and a dead
|
||||
// NATS connection is already visible through every stage subsequently
|
||||
// failing to report its own result.
|
||||
// SystemLogHandler writes slog records to a wrapped handler and publishes
|
||||
// each as a JSON logging.Entry to SubjectForSystem(taskID). Publish failures
|
||||
// are reported once and never block.
|
||||
type SystemLogHandler struct {
|
||||
next slog.Handler
|
||||
pub LogPublisher
|
||||
@@ -86,12 +59,7 @@ func (h *SystemLogHandler) Handle(ctx context.Context, record slog.Record) error
|
||||
return h.next.Handle(ctx, record)
|
||||
}
|
||||
|
||||
// warnAtMostOnce reports the first system-log delivery failure (marshal or
|
||||
// publish, either way this record's own history is now missing on the
|
||||
// daemon side) via the wrapped handler, then goes quiet -- a dead
|
||||
// connection would otherwise turn every subsequent line into a second
|
||||
// failure notice on stderr, drowning out the output an operator is trying
|
||||
// to read.
|
||||
// warnAtMostOnce reports the first publish failure only.
|
||||
func (h *SystemLogHandler) warnAtMostOnce(ctx context.Context, at time.Time, cause error) {
|
||||
h.warnOnce.Do(func() {
|
||||
warning := slog.NewRecord(at, slog.LevelWarn,
|
||||
|
||||
@@ -7,27 +7,13 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// EventPublisher is the minimal capability needed to ship a task's
|
||||
// observability events to the daemon over NATS: fire a message at a subject
|
||||
// without waiting for a reply. Declared here rather than taking *nats.go's
|
||||
// Conn so ForwardTaskEvents can be tested with a fake. *nats.Conn already
|
||||
// satisfies this with no adapter needed.
|
||||
// EventPublisher publishes a message to a subject without waiting.
|
||||
type EventPublisher interface {
|
||||
Publish(subject string, data []byte) error
|
||||
}
|
||||
|
||||
// ForwardTaskEvents relays every event published on sub to pub, JSON-encoded,
|
||||
// on SubjectForEvents(taskID), until sub is closed.
|
||||
//
|
||||
// A workflow.TaskContext built inside an archie-agent worker publishes to an
|
||||
// in-process *events.Bus the daemon cannot see -- the worker and the daemon
|
||||
// are separate processes connected only by NATS. This is the bridge that
|
||||
// makes those Emit calls (stage progress, outcome, parking) reach the
|
||||
// daemon's events table and dashboard timeline.
|
||||
//
|
||||
// A marshal or publish failure is logged and the loop continues: one missing
|
||||
// event must never abort the ones after it, and event shipping must never
|
||||
// block or fail the workflow run it is reporting on.
|
||||
// ForwardTaskEvents publishes every event from sub to SubjectForEvents(taskID)
|
||||
// until sub closes. Failures are logged.
|
||||
func ForwardTaskEvents(sub *events.Sub, pub EventPublisher, taskID int64, log *slog.Logger) {
|
||||
subject := SubjectForEvents(taskID)
|
||||
for e := range sub.C {
|
||||
|
||||
@@ -13,23 +13,14 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
|
||||
// ToolLimits are the configured result limits for one chat turn or agent
|
||||
// stage. It holds only settings, never accumulated state, so it is safe to
|
||||
// store on a long-lived runner and share across tasks.
|
||||
//
|
||||
// A negative limit means no limit; see config.ToolPolicy for why zero cannot
|
||||
// carry that meaning.
|
||||
// ToolLimits are the tool result limits for one turn or stage. A negative
|
||||
// limit means none.
|
||||
type ToolLimits struct {
|
||||
MaxResultChars int
|
||||
SpillDir string
|
||||
}
|
||||
|
||||
// EnsureSpillDir creates the spill directory if one is configured.
|
||||
//
|
||||
// Call it once at startup. Without it the directory never exists, and a
|
||||
// failed spill write falls back to inline truncation -- spilling looks
|
||||
// configured and does nothing. An empty SpillDir is not an error: it
|
||||
// selects inline truncation deliberately.
|
||||
// EnsureSpillDir creates the spill directory if one is set.
|
||||
func (l ToolLimits) EnsureSpillDir() error {
|
||||
if l.SpillDir == "" {
|
||||
return nil
|
||||
@@ -137,21 +128,9 @@ func (o ToolSetOptions) excludes(entry tools.ToolEntry) bool {
|
||||
return slices.Contains(o.ExcludeToolsets, entry.Toolset)
|
||||
}
|
||||
|
||||
// BuildToolSet converts every currently-available entry in reg into an
|
||||
// ai-sdk core.ToolSet, ready to pass as core.GenerateOptions.Tools for a
|
||||
// multi-step chat turn. A nil registry (memory/tools disabled) returns
|
||||
// an empty set. Invalid availability callbacks and dynamic schemas return
|
||||
// errors instead of panicking or silently hiding an advertised tool.
|
||||
//
|
||||
// core.Tool.Execute exchanges JSON-encoded strings with the model;
|
||||
// tools.Handler exchanges a decoded map. The returned Execute functions
|
||||
// do the JSON <-> map translation and surface decode failures as errors
|
||||
// rather than silently dropping malformed model input.
|
||||
//
|
||||
// This is the only path from a registered tools.ToolEntry to a model, so it is
|
||||
// also where result limits are enforced. The model runtime owns the tool loop
|
||||
// and decides what to invoke, so archie cannot gate a batch -- but it builds
|
||||
// every Execute closure here, which makes per-call accounting reachable.
|
||||
// BuildToolSet converts reg's available entries into an ai-sdk ToolSet,
|
||||
// translating JSON input and enforcing result limits. A nil registry returns
|
||||
// an empty set.
|
||||
func BuildToolSet(reg *tools.Registry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
if reg == nil {
|
||||
return aicore.ToolSet{}, nil
|
||||
@@ -159,13 +138,7 @@ func BuildToolSet(reg *tools.Registry, opts ToolSetOptions) (aicore.ToolSet, err
|
||||
return BuildToolSetFrom(reg.All(), opts)
|
||||
}
|
||||
|
||||
// BuildToolSetFrom converts a loose slice of entries under the same rules as
|
||||
// [BuildToolSet].
|
||||
//
|
||||
// It exists for tools that are bound per turn rather than registered globally
|
||||
// -- the task tools carry the calling gateway's identity, so there is one set
|
||||
// of them per gateway and they cannot live in the process-wide registry. Pass
|
||||
// the same ToolSetOptions to both calls so a single turn shares one budget.
|
||||
// BuildToolSetFrom is BuildToolSet over a slice of entries.
|
||||
func BuildToolSetFrom(entries []tools.ToolEntry, opts ToolSetOptions) (aicore.ToolSet, error) {
|
||||
set := aicore.ToolSet{}
|
||||
for _, entry := range entries {
|
||||
@@ -223,14 +196,8 @@ func safeResolvedSchema(entry tools.ToolEntry) (schema tools.JSONSchema, err err
|
||||
return entry.ResolvedSchema(), nil
|
||||
}
|
||||
|
||||
// toolExecute adapts a tools.ToolEntry's Handler to core.Tool's
|
||||
// Execute(ctx, jsonInput string) (jsonOutput string, err error) shape, and
|
||||
// applies the turn's result accounting.
|
||||
//
|
||||
// The cap is applied to the marshalled payload rather than to the handler's
|
||||
// return value, because the marshalled form is what actually reaches the
|
||||
// model: JSON escaping can change the length materially, so capping the Go
|
||||
// value would bound the wrong string.
|
||||
// toolExecute adapts a ToolEntry's handler to an ai-sdk Execute and caps the
|
||||
// marshalled result.
|
||||
func toolExecute(entry tools.ToolEntry, opts ToolSetOptions) func(context.Context, string) (string, error) {
|
||||
limit := opts.resultLimit(entry)
|
||||
return func(ctx context.Context, input string) (result string, err error) {
|
||||
@@ -275,11 +242,8 @@ func requireApproval(ctx context.Context, entry tools.ToolEntry, opts ToolSetOpt
|
||||
}
|
||||
decision, err := opts.Approval.RequestApproval(approveCtx, entry.Name, desc)
|
||||
if err != nil {
|
||||
// Distinguish a tool-level timeout (our own deadline) from a
|
||||
// turn-level cancellation (/stop). A turn cancellation must
|
||||
// propagate as a context error; a tool timeout must surface as
|
||||
// a plain error so the model can report it instead of the turn
|
||||
// aborting.
|
||||
// A tool timeout is a plain error; a turn cancellation stays a context
|
||||
// error.
|
||||
if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && ctx.Err() == nil {
|
||||
return fmt.Errorf("tool %s: approval timed out after %v", entry.Name, tools.ToolApprovalTimeout)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user