magi-code 0.96.1

Repository-aware CLI coding agent for terminal work
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use super::*;

impl AgentSession {
    pub(crate) fn run_turn_untracked<P: Provider + ?Sized>(
        &self,
        provider: &P,
        request: AgentRunRequest<'_, '_>,
        steering: Option<AgentSteering>,
        defer_final_steering: bool,
        request_sequence: Arc<AtomicU64>,
    ) -> anyhow::Result<AgentRunOutput> {
        self.run_turn(
            provider,
            request,
            steering,
            defer_final_steering,
            request_sequence,
            None,
        )
    }

    pub(super) fn run_turn<P: Provider + ?Sized>(
        &self,
        provider: &P,
        run: AgentRunRequest<'_, '_>,
        steering: Option<AgentSteering>,
        defer_final_steering: bool,
        request_sequence: Arc<AtomicU64>,
        preflight_projection: Option<PreflightRequestProjection>,
    ) -> anyhow::Result<AgentRunOutput> {
        let cancellation = run.cancellation.clone();
        cancellation.check()?;
        // Reuse validated durable replay before prompt expansion or any tool invocation.
        let scoped_tools = self.tools_for_task_scope(run.session, run.tools)?;
        let mut run = AgentRunRequest {
            tools: scoped_tools.as_ref().or(run.tools),
            ..run
        };

        let request_tools = tool_request_configuration(run.tools);
        let mut prepared = self.prepare_initial_run(&run, request_tools, preflight_projection)?;
        self.record_initial_user_input(&mut prepared, &mut run)?;
        let mut tool_execution_expectation = ToolExecutionExpectation::from_request(
            run.prompt,
            run.tools.is_some(),
            &prepared.tool_request_configuration.advertised_tool_names,
        );
        if matches!(run.prompt_origin, crate::output::UserPromptOrigin::Steering) {
            tool_execution_expectation.invalidate();
            if let Some(steering) = steering.as_ref()
                && let Some(prompts) = steering.acknowledge_reserved_prompt(run.prompt)
                && let Some(sink) = run.output_sink.as_deref_mut()
            {
                sink.steering_prompts_acknowledged(&prompts);
            }
        }
        let title_guard = self.start_title_generation_guard(&mut run, cancellation.clone());
        let replay_diagnostics = std::mem::take(&mut prepared.session_read_diagnostics);
        let replay_warnings = std::mem::take(&mut prepared.replay_warnings);
        let provider_prompt = std::mem::take(&mut prepared.provider_prompt);
        let mut state = self.start_print_turn_state(prepared, &run, title_guard, request_sequence);
        let mut auto_continue_used = false;
        let mut staged_dangling_tool_recovery = false;
        let steering_tools = run.tools;
        let steering_cwd = run.cwd;
        let steering_mode = run.invocation_mode;
        let expand_steering_prompt = |text: &str| {
            Self::expand_effective_prompt(
                text,
                steering_tools,
                steering_mode,
                steering_cwd,
                &cancellation,
            )
            .unwrap_or_else(|| text.to_string())
        };
        let turn_steering = TurnSteering {
            steering: steering.as_ref(),
            defer_final: defer_final_steering,
            expand: &expand_steering_prompt,
        };
        macro_rules! terminal_try {
            ($expression:expr) => {
                match $expression {
                    Ok(value) => value,
                    Err(error) => {
                        let _ = self.record_terminal_failure(&mut state, &mut run, &error);
                        return Err(error);
                    }
                }
            };
        }
        terminal_try!(self.update_tool_checkpoint_context(&run));
        terminal_try!(self.emit_initial_user_prompt_and_replay_diagnostics(
            &mut run,
            provider_prompt,
            &replay_diagnostics,
            &replay_warnings,
        ));
        terminal_try!(self.apply_skill_suggestion(&mut state, &mut run, &cancellation));
        loop {
            terminal_try!(cancellation.check());
            if staged_dangling_tool_recovery {
                // Resolve staged recovery immediately before the continuation request is built;
                // steering queued after this observation is not promised to preempt that request.
                let boundary_steering =
                    steering.as_ref().and_then(AgentSteering::observe_collapsed);
                if let Some(batch) = boundary_steering {
                    staged_dangling_tool_recovery = false;
                    if defer_final_steering {
                        if let Err(error) = state.assistant_chunk_batch.flush() {
                            state
                                .session_persistence
                                .warn_once(&mut run.output_sink, &error)?;
                        }
                        break;
                    }
                    terminal_try!(self.complete_assistant_turn_without_tools(
                        &mut state,
                        &mut run,
                        &cancellation,
                    ));
                    terminal_try!(cancellation.check());
                    state.turn_state.finish_text_action_for_continuation();
                    terminal_try!(inject_steering_update_at_continuation_boundary(
                        steering.as_ref(),
                        Some(batch),
                        &mut state.turn_state,
                        &state.session_persistence,
                        &mut run.output_sink,
                        expand_steering_prompt,
                    ));
                    tool_execution_expectation.invalidate();
                    continue;
                }

                staged_dangling_tool_recovery = false;
                terminal_try!(self.auto_continue_after_dangling_tool_intent(&mut state, &mut run));
                state.output.auto_compaction_blocked_by_recovery = true;
                auto_continue_used = true;
                terminal_try!(cancellation.check());
            }
            let (request, request_sequence, request_input_tokens, estimated_input_tokens) =
                match self.build_turn_request_and_emit_context_usage(&mut state, &mut run) {
                    Ok(request) => request,
                    Err(error) => {
                        return Err(self.fail_turn_request_build(error, &mut state, &mut run));
                    }
                };

            let stream_result = match self.collect_provider_turn(
                provider,
                request,
                &mut state,
                &mut run,
                &cancellation,
                request_sequence,
                request_input_tokens,
            ) {
                Ok(stream_result) => stream_result,
                Err(failure)
                    if !failure.cancelled
                        && !state.output.auto_compaction_blocked_by_recovery
                        && !state.session_persistence.is_degraded()
                        && run.continuation_auto_compaction_policy.is_some()
                        && failure
                            .error
                            .downcast_ref::<crate::providers::error::ProviderError>()
                            .is_some_and(
                                crate::providers::error::ProviderError::is_prompt_too_long,
                            ) =>
                {
                    terminal_try!(cancellation.check());
                    // Input is already durable, including any settled tool work.
                    // Reuse continuation compaction rather than resending it.
                    let error = ContextBudgetError {
                        phase: ContextBudgetPhase::Continuation,
                        estimated_tokens: request_input_tokens,
                        threshold_tokens: self.context_budget.threshold_tokens(),
                        provider_rejected: true,
                        partial_output: None,
                        message: failure.error.to_string(),
                    };
                    return Err(self.fail_turn_request_build(error.into(), &mut state, &mut run));
                }
                Err(failure) if !auto_continue_used && failure.eligible_for_auto_continue() => {
                    terminal_try!(cancellation.check());
                    let _ = self.record_auto_continue_decision(
                        &failure,
                        "continuing",
                        None,
                        &mut state,
                        &mut run,
                    );
                    terminal_try!(self.auto_continue_after_incomplete_stream(&mut state, &mut run));
                    state.output.recovered_incomplete_stream = true;
                    state.output.auto_compaction_blocked_by_recovery = true;
                    auto_continue_used = true;
                    continue;
                }
                Err(failure) => {
                    return Err(self.fail_provider_stream(
                        failure,
                        auto_continue_used,
                        &mut state,
                        &mut run,
                    ));
                }
            };
            if let Err(error) = self.run_reasoning_message_hooks(
                &stream_result.reasoning_summaries,
                &mut state,
                &mut run,
                &cancellation,
            ) {
                let _ = self.record_terminal_failure(&mut state, &mut run, &error);
                return Err(error);
            }

            if let Some(input_tokens) = stream_result.provider_input_tokens {
                state
                    .request_projection_cache
                    .calibrate_anthropic_input_tokens(estimated_input_tokens, input_tokens);
            }
            let steering_batch = steering.as_ref().and_then(AgentSteering::observe_collapsed);
            let reasoning_only = stream_result.tool_calls.is_empty()
                && state.turn_state.assistant_segment().trim().is_empty()
                && !stream_result.reasoning_summaries.is_empty();
            if reasoning_only {
                if let Some(batch) = steering_batch.clone()
                    && !defer_final_steering
                {
                    terminal_try!(cancellation.check());
                    state.turn_state.finish_text_action_for_continuation();
                    terminal_try!(inject_steering_update_at_continuation_boundary(
                        steering.as_ref(),
                        Some(batch),
                        &mut state.turn_state,
                        &state.session_persistence,
                        &mut run.output_sink,
                        expand_steering_prompt,
                    ));
                    tool_execution_expectation.invalidate();
                    continue;
                }
                if steering_batch.is_none() && !auto_continue_used {
                    terminal_try!(
                        self.auto_continue_after_reasoning_only_turn(&mut state, &mut run)
                    );
                    state.output.auto_compaction_blocked_by_recovery = true;
                    auto_continue_used = true;
                    continue;
                }
            }
            if stream_result.tool_calls.is_empty()
                && !auto_continue_used
                && !state.turn_state.has_tool_protocol_activity()
                && completion_needs_tool_recovery_for_expectation(
                    &tool_execution_expectation,
                    state.turn_state.assistant_segment(),
                    &state.tool_request_configuration.advertised_tool_names,
                )
            {
                terminal_try!(cancellation.check());
                staged_dangling_tool_recovery = true;
                continue;
            }

            if stream_result.tool_calls.is_empty() {
                match terminal_try!(self.finish_turn_without_tool_calls(
                    &mut state,
                    &mut run,
                    &cancellation,
                    &turn_steering,
                    steering_batch,
                    &mut tool_execution_expectation,
                )) {
                    TurnLoopStep::Continue => continue,
                    TurnLoopStep::Break => break,
                }
            }

            let context_window_usage = crate::output::ContextWindowUsage {
                current_tokens: stream_result
                    .provider_input_tokens
                    .unwrap_or(request_input_tokens),
                max_tokens: self.context_budget.max_tokens,
            };
            terminal_try!(self.run_tool_turn_and_maybe_emit_assistant_complete(
                stream_result.tool_calls,
                context_window_usage,
                &mut state,
                &mut run,
                &cancellation,
            ));
            if state.output.manual_compaction_request.is_some() {
                break;
            }
            if let Err(error) = cancellation.check() {
                let _ = self.record_cancelled_terminal_status(&mut state, &mut run);
                return Err(error);
            }
            let steering_batch = steering.as_ref().and_then(AgentSteering::observe_collapsed);
            let steering_provider_text = steering_batch
                .as_ref()
                .map(|batch| expand_steering_prompt(&batch.text));
            self.check_continuation_soft_budget(
                &mut state,
                &mut run,
                steering_provider_text.as_deref(),
            )?;
            if terminal_try!(inject_steering_update_at_continuation_boundary(
                steering.as_ref(),
                steering_batch,
                &mut state.turn_state,
                &state.session_persistence,
                &mut run.output_sink,
                |text| steering_provider_text.unwrap_or_else(|| text.to_string()),
            )) {
                tool_execution_expectation.invalidate();
            }
        }
        state.title_guard.finish();
        state.output.persistence_degraded = state.session_persistence.is_degraded();
        Ok(state.output)
    }

    /// Records terminal status for a request that could not be built. Continuation
    /// budget overflows keep partial output so automatic compaction can recover.
    pub(super) fn fail_turn_request_build(
        &self,
        error: anyhow::Error,
        state: &mut PrintTurnState<'_>,
        run: &mut AgentRunRequest<'_, '_>,
    ) -> anyhow::Error {
        state.output.persistence_degraded = state.session_persistence.is_degraded();
        let is_recoverable_continuation_budget = !state.output.persistence_degraded
            && run.continuation_auto_compaction_policy.is_some()
            && error
                .downcast_ref::<ContextBudgetError>()
                .is_some_and(|budget| budget.phase() == ContextBudgetPhase::Continuation);
        if is_recoverable_continuation_budget {
            let _ = state.session_persistence.record_terminal_status(
                TurnStatus::CompactionRequired,
                &state.output.text,
                &mut run.output_sink,
            );
        } else {
            let _ = self.record_terminal_failure(state, run, &error);
        }
        state.output.persistence_degraded = state.session_persistence.is_degraded();
        match error.downcast::<ContextBudgetError>() {
            Ok(budget) if budget.phase() == ContextBudgetPhase::Continuation => budget
                .with_partial_output(std::mem::take(&mut state.output))
                .into(),
            Ok(budget) => budget.into(),
            Err(error) => error,
        }
    }

    /// Records why a failed provider stream was not auto-continued.
    pub(super) fn fail_provider_stream(
        &self,
        failure: ProviderStreamFailure,
        auto_continue_used: bool,
        state: &mut PrintTurnState<'_>,
        run: &mut AgentRunRequest<'_, '_>,
    ) -> anyhow::Error {
        let reason = if auto_continue_used {
            Some("auto-continue already used for this turn")
        } else {
            failure.auto_continue_block_reason()
        };
        if failure.recovery_diagnostic_relevant() {
            let _ = self.record_auto_continue_decision(&failure, "blocked", reason, state, run);
        }
        self.record_provider_stream_failure(&failure, state, run);
        failure.error
    }

    /// Completes a response with no tool calls, continuing only for queued
    /// steering or completion verification.
    pub(super) fn finish_turn_without_tool_calls(
        &self,
        state: &mut PrintTurnState<'_>,
        run: &mut AgentRunRequest<'_, '_>,
        cancellation: &AgentCancellation,
        steering: &TurnSteering<'_>,
        steering_batch: Option<SteeringBatch>,
        tool_execution_expectation: &mut ToolExecutionExpectation,
    ) -> anyhow::Result<TurnLoopStep> {
        if state.turn_state.assistant_segment().trim().is_empty()
            && let Some(batch) = steering_batch
        {
            if steering.defer_final {
                return Ok(TurnLoopStep::Break);
            }
            cancellation.check()?;
            state.turn_state.finish_text_action_for_continuation();
            inject_steering_update_at_continuation_boundary(
                steering.steering,
                Some(batch),
                &mut state.turn_state,
                &state.session_persistence,
                &mut run.output_sink,
                steering.expand,
            )?;
            tool_execution_expectation.invalidate();
            return Ok(TurnLoopStep::Continue);
        }

        if self.verify_or_continue_terminal_completion(state, run, cancellation)? {
            return Ok(TurnLoopStep::Continue);
        }
        self.complete_assistant_turn_without_tools(state, run, cancellation)?;
        cancellation.check()?;
        if !steering.defer_final {
            let steering_batch = steering.steering.and_then(AgentSteering::observe_collapsed);
            if steering_batch.is_some() {
                state.turn_state.finish_text_action_for_continuation();
                let steering_was_injected = inject_steering_update_at_continuation_boundary(
                    steering.steering,
                    steering_batch,
                    &mut state.turn_state,
                    &state.session_persistence,
                    &mut run.output_sink,
                    steering.expand,
                )?;
                if steering_was_injected {
                    tool_execution_expectation.invalidate();
                    return Ok(TurnLoopStep::Continue);
                }
            }
        }
        Ok(TurnLoopStep::Break)
    }

    /// Stops before a continuation whose projected request reaches the soft
    /// compaction threshold, handing partial output to automatic compaction.
    pub(super) fn check_continuation_soft_budget(
        &self,
        state: &mut PrintTurnState<'_>,
        run: &mut AgentRunRequest<'_, '_>,
        steering_provider_text: Option<&str>,
    ) -> anyhow::Result<()> {
        if state.session_persistence.is_degraded()
            || state.output.auto_compaction_blocked_by_recovery
        {
            return Ok(());
        }
        let Some(&(soft_threshold, _)) = run.continuation_auto_compaction_policy.as_ref() else {
            return Ok(());
        };
        let temporary_steering = steering_provider_text
            .map(|text| ProviderConversationItem::Message(ChatMessage::user(text)));
        let temporary_suffix = temporary_steering.as_slice();
        let turn_items = state.turn_state.request_items_slice();
        let has_skill_reads = state.base_conversation.iter().chain(turn_items).any(|item| {
            matches!(item, ProviderConversationItem::ToolResult(result) if !result.skill_reads.is_empty())
        });
        let projection = if has_skill_reads {
            // Rebuild skill references before comparing this request with the
            // last provider-observed request; never estimate a raw suffix.
            let turn_with_steering = turn_items
                .iter()
                .chain(temporary_suffix)
                .cloned()
                .collect::<Vec<_>>();
            let request = self.request_from_shared_conversation(
                Arc::clone(&state.base_conversation),
                &turn_with_steering,
                run.semantic_progress_timeout,
                state.prompt_cache_key.as_deref(),
                &state.tool_request_configuration,
            );
            project_provider_request_input_tokens(&self.provider_id, &request)
        } else {
            state
                .request_projection_cache
                .project_deterministic_turn_items(turn_items, temporary_suffix)
        };
        let projection = state
            .request_projection_cache
            .apply_usage_calibration(projection);
        if projection.tokens < soft_threshold {
            return Ok(());
        }
        let _ = state.session_persistence.record_terminal_status(
            TurnStatus::CompactionRequired,
            &state.output.text,
            &mut run.output_sink,
        );
        state.output.persistence_degraded = state.session_persistence.is_degraded();
        Err(ContextBudgetError::new(
            ContextBudgetPhase::Continuation,
            projection.tokens,
            soft_threshold,
            self.context_budget.max_tokens,
            self.context_budget.reserve_tokens,
        )
        .with_partial_output(std::mem::take(&mut state.output))
        .into())
    }
}