| 1 |
package clnkr |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
) |
| 8 |
|
| 9 |
type RunOptions struct { |
| 10 |
ContextLengthBackstop func(context.Context, error) error |
| 11 |
} |
| 12 |
|
| 13 |
type runPolicyState struct { |
| 14 |
policy RunPolicy |
| 15 |
commandsUsed, modelTurns int |
| 16 |
protocolErrors, completionRejects int |
| 17 |
completionGate CompletionGate |
| 18 |
gateCompletions bool |
| 19 |
guidancePressure resourcePressure |
| 20 |
contextLengthBackstop func(context.Context, error) error |
| 21 |
contextLengthBackstopOriginal error |
| 22 |
} |
| 23 |
|
| 24 |
func newRunPolicyStateOptions(policy RunPolicy, opts RunOptions) runPolicyState { |
| 25 |
if policy == nil { |
| 26 |
policy = FullSendPolicy{} |
| 27 |
} |
| 28 |
return runPolicyState{ |
| 29 |
policy: policy, |
| 30 |
gateCompletions: policyUsesCompletionGate(policy), |
| 31 |
contextLengthBackstop: opts.ContextLengthBackstop, |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
func (s *runPolicyState) step(ctx context.Context, a *Agent) (bool, error) { |
| 36 |
a.appendStateMessageIfNeeded() |
| 37 |
a.appendResourceStateMessage(s.commandsUsed, s.modelTurns, s.resourcePressureGuidanceDue(a)) |
| 38 |
result, err := a.Step(ctx) |
| 39 |
s.modelTurns++ |
| 40 |
if err != nil { |
| 41 |
return false, s.handleStepError(ctx, a, err) |
| 42 |
} |
| 43 |
s.contextLengthBackstopOriginal = nil |
| 44 |
if result.ParseErr != nil { |
| 45 |
return s.handleProtocolFailure(a) |
| 46 |
} |
| 47 |
s.protocolErrors = 0 |
| 48 |
|
| 49 |
switch turn := result.Turn.(type) { |
| 50 |
case *DoneTurn: |
| 51 |
return s.handleDone(a, turn) |
| 52 |
case *ClarifyTurn: |
| 53 |
return false, s.handleClarify(ctx, a, turn) |
| 54 |
case *ActTurn: |
| 55 |
return s.handleAct(ctx, a, turn) |
| 56 |
default: |
| 57 |
return false, s.runError(a, fmt.Errorf("unhandled turn type %T", turn)) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
func (s *runPolicyState) handleStepError(ctx context.Context, a *Agent, err error) error { |
| 62 |
if s.contextLengthBackstopOriginal != nil { |
| 63 |
retryErr := fmt.Errorf("context_length_backstop: retry failed: %w", err) |
| 64 |
return s.runError(a, errors.Join(s.contextLengthBackstopOriginal, retryErr)) |
| 65 |
} |
| 66 |
if !errors.Is(err, ErrContextLengthExceeded) || s.contextLengthBackstop == nil { |
| 67 |
return s.runError(a, err) |
| 68 |
} |
| 69 |
|
| 70 |
backstop := s.contextLengthBackstop |
| 71 |
s.contextLengthBackstop = nil |
| 72 |
s.contextLengthBackstopOriginal = err |
| 73 |
a.notify(EventDebug{Message: ContextLengthBackstopCompactingDebug}) |
| 74 |
if compactErr := backstop(ctx, err); compactErr != nil { |
| 75 |
compactErr = fmt.Errorf("context_length_backstop: compaction failed: %w", compactErr) |
| 76 |
return s.runError(a, errors.Join(err, compactErr)) |
| 77 |
} |
| 78 |
a.notify(EventDebug{Message: ContextLengthBackstopRetryingDebug}) |
| 79 |
return nil |
| 80 |
} |
| 81 |
|
| 82 |
func (s *runPolicyState) handleProtocolFailure(a *Agent) (bool, error) { |
| 83 |
s.protocolErrors++ |
| 84 |
a.notify(EventDebug{Message: fmt.Sprintf("consecutive protocol errors: %d", s.protocolErrors)}) |
| 85 |
if s.protocolErrors >= 3 { |
| 86 |
return false, s.runError(a, fmt.Errorf("consecutive protocol failures, exiting")) |
| 87 |
} |
| 88 |
return false, nil |
| 89 |
} |
| 90 |
|
| 91 |
func (s *runPolicyState) handleDone(a *Agent, turn *DoneTurn) (bool, error) { |
| 92 |
if !s.gateCompletions { |
| 93 |
return true, nil |
| 94 |
} |
| 95 |
|
| 96 |
decision, reasons, guidance := s.completionGate.Decide(turn, s.commandsUsed, a.MaxSteps) |
| 97 |
a.notify( |
| 98 |
EventCompletionGate{ |
| 99 |
Decision: decision, |
| 100 |
Reasons: cloneStrings(reasons), |
| 101 |
Summary: turn.Summary, |
| 102 |
}, |
| 103 |
) |
| 104 |
switch decision { |
| 105 |
case CompletionAccept: |
| 106 |
return true, nil |
| 107 |
case CompletionReject: |
| 108 |
s.completionRejects++ |
| 109 |
if s.completionRejects >= 3 { |
| 110 |
return false, s.runError( |
| 111 |
a, |
| 112 |
fmt.Errorf("consecutive completion gate rejections, exiting"), |
| 113 |
) |
| 114 |
} |
| 115 |
case CompletionChallenge: |
| 116 |
s.completionRejects = 0 |
| 117 |
} |
| 118 |
a.AppendUserMessage(guidance) |
| 119 |
return false, nil |
| 120 |
} |
| 121 |
|
| 122 |
func (s *runPolicyState) handleClarify(ctx context.Context, a *Agent, turn *ClarifyTurn) error { |
| 123 |
reply, err := s.policy.Clarify(ctx, turn.Question) |
| 124 |
if err != nil { |
| 125 |
return s.runError(a, fmt.Errorf("clarify: %w", err)) |
| 126 |
} |
| 127 |
s.completionRejects = 0 |
| 128 |
a.AppendUserMessage(reply) |
| 129 |
return nil |
| 130 |
} |
| 131 |
|
| 132 |
func (s *runPolicyState) handleAct(ctx context.Context, a *Agent, turn *ActTurn) (bool, error) { |
| 133 |
limited, skipped := s.limitActTurn(a, turn) |
| 134 |
commands := cloneBashActions(limited.Bash.Commands) |
| 135 |
decision, err := s.policy.DecideAct(ctx, ActProposal{ |
| 136 |
Turn: &ActTurn{ |
| 137 |
Bash: BashBatch{Commands: cloneBashActions(commands)}, |
| 138 |
Reasoning: limited.Reasoning, |
| 139 |
}, |
| 140 |
Skipped: cloneBashActions(skipped), |
| 141 |
Commands: commands, |
| 142 |
Prompt: formatActProposal(commands), |
| 143 |
}) |
| 144 |
if err != nil { |
| 145 |
return false, s.runError(a, fmt.Errorf("decide act: %w", err)) |
| 146 |
} |
| 147 |
switch decision.Kind { |
| 148 |
case ActDecisionReject: |
| 149 |
allCommands := append(cloneBashActions(limited.Bash.Commands), skipped...) |
| 150 |
a.RejectTurn( |
| 151 |
&ActTurn{Bash: BashBatch{Commands: allCommands}, Reasoning: limited.Reasoning}, |
| 152 |
decision.Guidance, |
| 153 |
) |
| 154 |
return false, nil |
| 155 |
case ActDecisionApprove: |
| 156 |
default: |
| 157 |
return false, s.runError(a, fmt.Errorf("decide act: unknown decision %q", decision.Kind)) |
| 158 |
} |
| 159 |
|
| 160 |
execResult, err := a.ExecuteTurnWithSkipped(ctx, limited, skipped) |
| 161 |
if err != nil { |
| 162 |
return false, s.runError(a, err) |
| 163 |
} |
| 164 |
s.completionRejects = 0 |
| 165 |
s.commandsUsed += execResult.ExecCount |
| 166 |
a.notify(EventDebug{Message: fmt.Sprintf("step %d/%d", s.commandsUsed, a.MaxSteps)}) |
| 167 |
if a.MaxSteps > 0 && s.commandsUsed >= a.MaxSteps { |
| 168 |
return s.requestStepLimitSummary(ctx, a) |
| 169 |
} |
| 170 |
return false, nil |
| 171 |
} |
| 172 |
|
| 173 |
func (s *runPolicyState) limitActTurn(a *Agent, turn *ActTurn) (*ActTurn, []BashAction) { |
| 174 |
if remaining := a.MaxSteps - s.commandsUsed; a.MaxSteps > 0 && |
| 175 |
len(turn.Bash.Commands) > remaining { |
| 176 |
skipped := append([]BashAction(nil), turn.Bash.Commands[remaining:]...) |
| 177 |
limited := &ActTurn{ |
| 178 |
Bash: BashBatch{Commands: turn.Bash.Commands[:remaining]}, |
| 179 |
Reasoning: turn.Reasoning, |
| 180 |
} |
| 181 |
return limited, skipped |
| 182 |
} |
| 183 |
return turn, nil |
| 184 |
} |
| 185 |
|
| 186 |
func (s *runPolicyState) requestStepLimitSummary(ctx context.Context, a *Agent) (bool, error) { |
| 187 |
a.appendResourceStateMessage(s.commandsUsed, s.modelTurns, s.resourcePressureGuidanceDue(a)) |
| 188 |
summarize := a.RequestStepLimitSummary |
| 189 |
for { |
| 190 |
err := summarize(ctx) |
| 191 |
s.modelTurns++ |
| 192 |
if err == nil { |
| 193 |
s.contextLengthBackstopOriginal = nil |
| 194 |
return true, nil |
| 195 |
} |
| 196 |
if handleErr := s.handleStepError(ctx, a, err); handleErr != nil { |
| 197 |
return false, handleErr |
| 198 |
} |
| 199 |
summarize = a.retryStepLimitSummary |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
func (s *runPolicyState) resourcePressureGuidanceDue(a *Agent) bool { |
| 204 |
pressure := commandBudgetPressure(s.commandsUsed, a.MaxSteps) |
| 205 |
if pressure == resourcePressureNormal || pressure == s.guidancePressure { |
| 206 |
return false |
| 207 |
} |
| 208 |
s.guidancePressure = pressure |
| 209 |
return true |
| 210 |
} |
| 211 |
|
| 212 |
func (s *runPolicyState) runError(a *Agent, err error) error { |
| 213 |
return a.notifyRunError(err, s.commandsUsed, s.modelTurns) |
| 214 |
} |
| 215 |
|
| 216 |
func policyUsesCompletionGate(policy RunPolicy) bool { |
| 217 |
switch policy.(type) { |
| 218 |
case FullSendPolicy, *FullSendPolicy: |
| 219 |
return true |
| 220 |
} |
| 221 |
return false |
| 222 |
} |