Debian Codegraph @

agent.go

raw
1 package clnkr
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "strings"
8
9 "github.com/clnkr-ai/clnkr/internal/core/transcript"
10 )
11
12 const DefaultMaxSteps = 100
13
14 type resourcePressure string
15
16 const (
17 resourcePressureNormal resourcePressure = "normal"
18 resourcePressureLow resourcePressure = "low"
19 resourcePressureCritical resourcePressure = "critical"
20 )
21
22 var ErrClarificationNeeded = errors.New("clarification needed")
23
24 // Agent coordinates model turns and command execution.
25 type Agent struct {
26 model Model
27 executor Executor
28 messages []Message
29 cwd string
30 env map[string]string
31 started bool
32 Notify func(Event)
33 MaxSteps int
34 ActProtocol ActProtocol
35 }
36
37 func NewAgent(model Model, executor Executor, cwd string) *Agent {
38 return &Agent{model: model, executor: executor, cwd: cwd, MaxSteps: DefaultMaxSteps}
39 }
40
41 // SetEnv replaces the shell environment snapshot used for future commands.
42 func (a *Agent) SetEnv(env map[string]string) {
43 if env == nil {
44 a.env = nil
45 return
46 }
47 a.env = make(map[string]string, len(env))
48 for k, v := range env {
49 a.env[k] = v
50 }
51 }
52
53 func cloneProviderReplay(items []ProviderReplayItem) []ProviderReplayItem {
54 if len(items) == 0 {
55 return nil
56 }
57 return transcript.CloneMessage(Message{ProviderReplay: items}).ProviderReplay
58 }
59
60 func (a *Agent) notify(e Event) {
61 if a.Notify != nil {
62 a.Notify(e)
63 }
64 }
65
66 func (a *Agent) Messages() []Message {
67 return transcript.CloneMessages(a.messages)
68 }
69
70 func (a *Agent) Cwd() string { return a.cwd }
71
72 // AddMessages prepends msgs before the first Step/Run call.
73 func (a *Agent) AddMessages(msgs []Message) error {
74 if a.started {
75 return fmt.Errorf("add messages: agent already started")
76 }
77 if len(msgs) == 0 {
78 return nil
79 }
80 combined := make([]Message, len(msgs)+len(a.messages))
81 copy(combined, transcript.CloneMessages(msgs))
82 copy(combined[len(msgs):], transcript.CloneMessages(a.messages))
83 a.messages = combined
84 a.restoreExecutionStateFromMessages()
85 return nil
86 }
87
88 // AppendUserMessage appends a user message after the agent has started or for
89 // frontends that drive the loop manually.
90 func (a *Agent) AppendUserMessage(text string) {
91 a.started = true
92 a.messages = append(a.messages, Message{Role: "user", Content: text})
93 }
94
95 func (a *Agent) restoreExecutionStateFromMessages() {
96 if cwd, ok := transcript.ExtractLatestCwd(a.messages); ok {
97 a.cwd = cwd
98 }
99 }
100
101 func (a *Agent) appendStateMessageIfNeeded() {
102 if cwd, ok := transcript.ExtractLatestCwd(a.messages); ok && cwd == a.cwd {
103 return
104 }
105 a.messages = append(
106 a.messages,
107 Message{Role: "user", Content: transcript.FormatStateMessage(a.cwd)},
108 )
109 }
110
111 func commandBudgetPressure(commandsUsed, maxCommands int) resourcePressure {
112 if maxCommands <= 0 {
113 return resourcePressureNormal
114 }
115 remaining := max(maxCommands-commandsUsed, 0)
116 if remaining <= 1 {
117 return resourcePressureCritical
118 }
119 lowThreshold := (maxCommands + 3) / 4
120 if remaining <= lowThreshold {
121 return resourcePressureLow
122 }
123 return resourcePressureNormal
124 }
125
126 func resourcePressureGuidance(pressure resourcePressure) string {
127 switch pressure {
128 case resourcePressureLow:
129 return "Command budget pressure is low. Prefer targeted checks and edits over broad exploration."
130 case resourcePressureCritical:
131 return "Command budget pressure is critical. Stop broad exploration, produce the smallest viable result, run one cheap check, then finish."
132 default:
133 return ""
134 }
135 }
136
137 func (a *Agent) appendResourceStateMessage(
138 commandsUsed,
139 modelTurnsUsed int,
140 includeGuidance bool,
141 ) {
142 content := fmt.Sprintf(
143 `{"type":"resource_state","source":"clnkr","commands_used":%d,"model_turns_used":%d}`,
144 commandsUsed,
145 modelTurnsUsed,
146 )
147 if a.MaxSteps > 0 {
148 pressure := commandBudgetPressure(commandsUsed, a.MaxSteps)
149 content = fmt.Sprintf(
150 `{"type":"resource_state","source":"clnkr","commands_used":%d,"commands_remaining":%d,"max_commands":%d,"model_turns_used":%d,"pressure":%q}`,
151 commandsUsed,
152 max(a.MaxSteps-commandsUsed, 0),
153 a.MaxSteps,
154 modelTurnsUsed,
155 string(pressure),
156 )
157 if guidance := resourcePressureGuidance(pressure); includeGuidance && guidance != "" {
158 content = fmt.Sprintf(
159 `{"type":"resource_state","source":"clnkr","commands_used":%d,"commands_remaining":%d,"max_commands":%d,"model_turns_used":%d,"pressure":%q,"guidance":%q}`,
160 commandsUsed,
161 max(a.MaxSteps-commandsUsed, 0),
162 a.MaxSteps,
163 modelTurnsUsed,
164 string(pressure),
165 guidance,
166 )
167 }
168 }
169 if len(a.messages) > 0 && a.messages[len(a.messages)-1].Role == "user" &&
170 a.messages[len(a.messages)-1].Content == content {
171 return
172 }
173 a.messages = append(a.messages, Message{Role: "user", Content: content})
174 }
175
176 func (a *Agent) notifyRunError(err error, commandsUsed, modelTurns int) error {
177 a.notify(EventDebug{Message: fmt.Sprintf(
178 "run error: model_turns=%d commands=%d messages=%d cwd=%s last_error=%v",
179 modelTurns, commandsUsed, len(a.messages), a.cwd, err,
180 )})
181 return err
182 }
183
184 func (a *Agent) appendSuccessfulResponse(resp *Response) error {
185 resp.Turn = turnPointer(resp.Turn)
186 if resp.Turn == nil {
187 return fmt.Errorf("query model: missing turn")
188 }
189 canonicalText, err := CanonicalTurnJSON(resp.Turn)
190 if err != nil {
191 return fmt.Errorf("canonicalize model turn: %w", err)
192 }
193 a.messages = append(a.messages, Message{Role: "assistant", Content: canonicalText})
194 if len(resp.BashToolCalls) > 0 || len(resp.ProviderReplay) > 0 {
195 msg := &a.messages[len(a.messages)-1]
196 msg.BashToolCalls = append([]BashToolCall(nil), resp.BashToolCalls...)
197 msg.ProviderReplay = cloneProviderReplay(resp.ProviderReplay)
198 }
199 a.notify(EventResponse{Turn: resp.Turn, Usage: resp.Usage, Raw: resp.Raw})
200 return nil
201 }
202
203 func (a *Agent) appendProtocolFailure(resp Response, appendCorrection bool) {
204 a.messages = append(a.messages, Message{Role: "assistant", Content: resp.Raw})
205 a.notify(EventProtocolFailure{Reason: errorToReason(resp.ProtocolErr), Raw: resp.Raw})
206 if appendCorrection {
207 a.messages = append(
208 a.messages,
209 Message{
210 Role: "user",
211 Content: protocolCorrectionMessageFor(resp.ProtocolErr, a.ActProtocol),
212 },
213 )
214 }
215 }
216
217 // Compact rewrites the transcript by summarizing an older prefix and keeping a
218 // recent tail of user-authored turns intact.
219 func (a *Agent) Compact(
220 ctx context.Context,
221 compactor Compactor,
222 opts CompactOptions,
223 ) (CompactStats, error) {
224 if compactor == nil {
225 return CompactStats{}, fmt.Errorf("compact transcript: no compactor configured")
226 }
227
228 keepRecentTurns := opts.KeepRecentTurns
229 if keepRecentTurns < 0 {
230 return CompactStats{}, fmt.Errorf(
231 "compact transcript: invalid keep recent turns: %d",
232 keepRecentTurns,
233 )
234 }
235 if keepRecentTurns == 0 {
236 keepRecentTurns = 2
237 }
238
239 transcriptMessages := transcript.CloneMessages(a.messages)
240 boundary, ok := transcript.FindCompactBoundary(transcriptMessages, keepRecentTurns)
241 if !ok {
242 return CompactStats{}, fmt.Errorf("compact transcript: not enough history to compact")
243 }
244
245 prefix := transcript.CloneMessages(a.messages[:boundary])
246 summary, err := compactor.Summarize(ctx, prefix)
247 if err != nil {
248 return CompactStats{}, fmt.Errorf("compact transcript: summarize prefix: %w", err)
249 }
250 summary = strings.TrimSpace(summary)
251 if summary == "" {
252 return CompactStats{}, fmt.Errorf("compact transcript: empty summary")
253 }
254
255 rewritten, stats, err := transcript.RewriteForCompaction(
256 transcriptMessages,
257 summary,
258 keepRecentTurns,
259 )
260 if err != nil {
261 return CompactStats{}, fmt.Errorf("compact transcript: %w", err)
262 }
263
264 a.messages = rewritten
265 a.restoreExecutionStateFromMessages()
266 return CompactStats(stats), nil
267 }
268
269 // ExecutorStateSetter is optional. Executors that skip it must populate
270 // PostCwd/PostEnv themselves for cross-turn state.
271 type ExecutorStateSetter interface {
272 SetEnv(map[string]string)
273 }
274
275 // Step runs one query-parse cycle. Policy lives in Run.
276 func (a *Agent) Step(ctx context.Context) (StepResult, error) {
277 a.started = true
278 a.appendStateMessageIfNeeded()
279 a.notify(EventDebug{Message: "querying model..."})
280 resp, err := a.model.Query(ctx, transcript.CloneMessages(a.messages))
281 if err != nil {
282 return StepResult{}, fmt.Errorf("query model: %w", err)
283 }
284 a.notify(
285 EventDebug{
286 Message: fmt.Sprintf(
287 "usage: %d input, %d output tokens",
288 resp.Usage.InputTokens,
289 resp.Usage.OutputTokens,
290 ),
291 },
292 )
293
294 if resp.ProtocolErr != nil {
295 a.appendProtocolFailure(resp, true)
296 return StepResult{Response: resp, ParseErr: resp.ProtocolErr}, nil
297 }
298
299 if err := a.appendSuccessfulResponse(&resp); err != nil {
300 return StepResult{}, err
301 }
302 a.notify(EventDebug{Message: fmt.Sprintf("parsed turn: %T", resp.Turn)})
303 return StepResult{Response: resp, Turn: resp.Turn}, nil
304 }
305
306 // ExecuteTurn runs an act turn and appends the command result payload.
307 func (a *Agent) ExecuteTurn(ctx context.Context, act *ActTurn) (StepResult, error) {
308 return a.executeTurn(ctx, act, nil)
309 }
310
311 // ExecuteTurnWithSkipped runs an act turn and records bash tool calls that
312 // were skipped before execution, for example by MaxSteps truncation.
313 func (a *Agent) ExecuteTurnWithSkipped(
314 ctx context.Context,
315 act *ActTurn,
316 skipped []BashAction,
317 ) (StepResult, error) {
318 return a.executeTurn(ctx, act, skipped)
319 }
320
321 func (a *Agent) executeTurn(
322 ctx context.Context,
323 act *ActTurn,
324 skipped []BashAction,
325 ) (StepResult, error) {
326 return actTurnExecutor{agent: a}.Execute(ctx, act, skipped)
327 }
328
329 // RejectTurn records that an approval-mode act turn was not executed.
330 func (a *Agent) RejectTurn(act *ActTurn, reply string) {
331 if act == nil || len(act.Bash.Commands) == 0 {
332 a.AppendUserMessage(reply)
333 return
334 }
335 toolCallResults := 0
336 for _, action := range act.Bash.Commands {
337 if action.ID == "" {
338 continue
339 }
340 content := transcript.FormatDeniedCommandResult(reply)
341 a.messages = append(a.messages, Message{
342 Role: "user",
343 Content: content,
344 BashToolResult: &BashToolResult{ID: action.ID, Content: content, IsError: true},
345 })
346 toolCallResults++
347 }
348 if toolCallResults == 0 {
349 a.AppendUserMessage(reply)
350 }
351 }
352
353 func (a *Agent) appendSkippedToolResult(action BashAction, reason string) (string, bool) {
354 if action.ID == "" {
355 return "", false
356 }
357 content := transcript.FormatSkippedCommandResult(reason)
358 a.messages = append(a.messages, Message{
359 Role: "user",
360 Content: content,
361 BashToolResult: &BashToolResult{ID: action.ID, Content: content, IsError: true},
362 })
363 return content, true
364 }
365
366 func commandResultIsError(result CommandResult) bool {
367 if result.Outcome.Type == "" ||
368 result.Outcome.Type == CommandOutcomeExit && result.Outcome.ExitCode == nil {
369 return result.ExitCode != 0
370 }
371 if result.Outcome.Type != CommandOutcomeExit {
372 return true
373 }
374 return *result.Outcome.ExitCode != 0
375 }
376
377 // RequestStepLimitSummary asks the model for a final done summary after the
378 // caller decides the step budget is exhausted.
379 func (a *Agent) RequestStepLimitSummary(ctx context.Context) error {
380 a.notify(EventDebug{Message: "step limit reached, requesting summary"})
381 a.AppendUserMessage(
382 "Step limit reached. Respond with " + protocolDoneExample + " summarizing your progress.",
383 )
384
385 return a.retryStepLimitSummary(ctx)
386 }
387
388 func (a *Agent) retryStepLimitSummary(ctx context.Context) error {
389 query := a.model.Query
390 if finalModel, ok := a.model.(FinalSummaryModel); ok {
391 query = finalModel.QueryFinal
392 }
393 resp, err := query(ctx, transcript.CloneMessages(a.messages))
394 if err != nil {
395 return fmt.Errorf("query model (final): %w", err)
396 }
397 if resp.ProtocolErr != nil {
398 a.appendProtocolFailure(resp, false)
399 a.notify(
400 EventDebug{
401 Message: fmt.Sprintf("final response not a valid turn: %v", resp.ProtocolErr),
402 },
403 )
404 return fmt.Errorf("query model (final): %w", resp.ProtocolErr)
405 }
406 resp.Turn = turnPointer(resp.Turn)
407 if _, ok := resp.Turn.(*DoneTurn); !ok {
408 return fmt.Errorf("query model (final): expected done turn, got %T", resp.Turn)
409 }
410 if err := a.appendSuccessfulResponse(&resp); err != nil {
411 return fmt.Errorf("query model (final): %w", err)
412 }
413 a.notify(EventDebug{Message: fmt.Sprintf("final response turn: %T", resp.Turn)})
414 return nil
415 }
416
417 func (a *Agent) Run(ctx context.Context, task string) error {
418 return a.RunWithPolicy(ctx, task, FullSendPolicy{})
419 }
420
421 // RunWithPolicy loops Step until done, clarify, or step limit. The policy
422 // decides whether act turns execute and supplies clarification replies.
423 func (a *Agent) RunWithPolicy(ctx context.Context, task string, policy RunPolicy) error {
424 return a.RunWithPolicyOptions(ctx, task, policy, RunOptions{})
425 }
426
427 func (a *Agent) RunWithPolicyOptions(
428 ctx context.Context,
429 task string,
430 policy RunPolicy,
431 opts RunOptions,
432 ) error {
433 run := newRunPolicyStateOptions(policy, opts)
434 a.AppendUserMessage(task)
435
436 for ctx.Err() == nil {
437 done, err := run.step(ctx, a)
438 if err != nil {
439 return err
440 }
441 if done {
442 return nil
443 }
444 }
445 return run.runError(a, ctx.Err())
446 }
447
448 func cloneBashActions(actions []BashAction) []BashAction {
449 if len(actions) == 0 {
450 return nil
451 }
452 return append([]BashAction(nil), actions...)
453 }
454
455 func formatActProposal(commands []BashAction) string {
456 var b strings.Builder
457 for i, action := range commands {
458 if i > 0 {
459 b.WriteByte('\n')
460 }
461 command := action.Command
462 if workdir := strings.TrimSpace(action.Workdir); workdir != "" {
463 command = fmt.Sprintf("%s in %s", command, workdir)
464 }
465 fmt.Fprintf(&b, "%d. %s", i+1, command)
466 }
467 return b.String()
468 }