a3s 0.10.1

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Non-interactive DeepResearch execution and report synthesis.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use a3s_code_core::config::CodeConfig;
use a3s_code_core::{Agent, AgentSession, SessionOptions, ToolCallResult};

use crate::budget::{
    budget_plan_for_effort_index, BudgetPlan, BudgetWorkload, DEFAULT_TUI_EFFORT_INDEX,
};

const RESEARCH_TOOL_EXEC_TIMEOUT_MS: u64 = 30 * 60 * 1000;
const RESEARCH_DUPLICATE_TOOL_CALL_THRESHOLD: u32 = 12;
pub(crate) const DEEP_RESEARCH_SYNTHESIS_TIMEOUT_MS: u64 =
    crate::tui::DEEP_RESEARCH_SECTIONED_SYNTHESIS_TIMEOUT_MS;
const DEEP_RESEARCH_ABORT_GRACE_MS: u64 = 2_000;
const DEEP_RESEARCH_ABORT_SETTLE_MS: u64 = 250;

pub(crate) fn deep_research_default_budget() -> BudgetPlan {
    budget_plan_for_effort_index(DEFAULT_TUI_EFFORT_INDEX, None, BudgetWorkload::DeepResearch)
}

#[cfg(test)]
pub(crate) fn deep_research_workflow_args(query: &str) -> serde_json::Value {
    crate::tui::deep_research_cli_workflow_args_for_budget(
        query,
        deep_research_default_budget(),
        None,
    )
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DeepResearchCliOptions {
    query: String,
    evidence_scope: Option<crate::tui::DeepResearchEvidenceScope>,
}

fn parse_deepresearch_args(args: &[String]) -> anyhow::Result<DeepResearchCliOptions> {
    let mut evidence_scope = None;
    let mut query_parts = Vec::new();
    for arg in args {
        match arg.as_str() {
            "--local" | "--os" => {
                anyhow::bail!(
                    "DeepResearch runtime selection has been removed; use --web or --local-only to choose the evidence scope"
                )
            }
            "--local-only" | "--offline" => {
                if evidence_scope == Some(crate::tui::DeepResearchEvidenceScope::WebAndWorkspace) {
                    anyhow::bail!("--local-only conflicts with --web");
                }
                evidence_scope = Some(crate::tui::DeepResearchEvidenceScope::LocalOnly);
            }
            "--web" => {
                if evidence_scope == Some(crate::tui::DeepResearchEvidenceScope::LocalOnly) {
                    anyhow::bail!("--web conflicts with --local-only");
                }
                evidence_scope = Some(crate::tui::DeepResearchEvidenceScope::WebAndWorkspace);
            }
            "-h" | "--help" | "help" => {
                anyhow::bail!("usage: a3s code deepresearch [--local-only|--web] <query>");
            }
            value if value.starts_with('-') => {
                anyhow::bail!("unknown a3s code deepresearch option `{value}`")
            }
            value => query_parts.push(value.to_string()),
        }
    }
    let query = query_parts.join(" ").trim().to_string();
    if query.is_empty() {
        anyhow::bail!("usage: a3s code deepresearch [--local-only|--web] <query>");
    }
    Ok(DeepResearchCliOptions {
        query,
        evidence_scope,
    })
}

pub(crate) async fn execute_deepresearch_in(
    args: &[String],
    workspace: &Path,
    code_config: CodeConfig,
    memory_dir: PathBuf,
) -> anyhow::Result<DeepResearchReportSynthesis> {
    let opts = parse_deepresearch_args(args)?;
    execute_deepresearch_query_in(
        &opts.query,
        opts.evidence_scope,
        deep_research_default_budget(),
        workspace,
        code_config,
        memory_dir,
    )
    .await
}

pub(crate) async fn execute_deepresearch_query_in(
    query: &str,
    evidence_scope: Option<crate::tui::DeepResearchEvidenceScope>,
    budget: BudgetPlan,
    workspace: &Path,
    code_config: CodeConfig,
    memory_dir: PathBuf,
) -> anyhow::Result<DeepResearchReportSynthesis> {
    let query = query.trim();
    if query.is_empty() {
        anyhow::bail!("DeepResearch query must not be empty");
    }
    let workspace_text = workspace.to_string_lossy().to_string();
    let (session, report_tool_gate) =
        build_deepresearch_session(&workspace_text, code_config, memory_dir).await?;
    eprintln!("deepresearch: gathering evidence via the host-managed workflow…");
    let mut workflow_args =
        crate::tui::deep_research_cli_workflow_args_for_budget(query, budget, evidence_scope);
    let run_id = crate::tui::ensure_deep_research_workflow_run_id(&mut workflow_args)
        .ok_or_else(|| anyhow::anyhow!("failed to assign a DeepResearch workflow run ID"))?;
    let workflow = run_deepresearch_inquiry(Arc::clone(&session), workflow_args.clone()).await;
    let workflow_succeeded = workflow.as_ref().is_ok_and(|result| result.exit_code == 0);
    let (workflow_output, exit_code, metadata) = match workflow {
        Ok(result) => (result.output, result.exit_code, result.metadata),
        Err(error) => (error, 1, None),
    };

    let mut synthesis = match crate::tui::deep_research_evidence_first_published_report(
        workspace,
        query,
        &workflow_output,
    )
    .map_err(anyhow::Error::msg)?
    {
        Some(published) => {
            let text = crate::tui::clean_deep_research_final_text_from_artifacts(
                &published.artifacts,
                workspace,
            )
            .unwrap_or_else(|| "DeepResearch report published without a text preview.".to_string());
            let status = match published.publication {
                crate::tui::DeepResearchEvidenceFirstPublication::Synthesized => {
                    DeepResearchReportStatus::Completed
                }
                crate::tui::DeepResearchEvidenceFirstPublication::SourceBacked => {
                    DeepResearchReportStatus::Degraded
                }
                crate::tui::DeepResearchEvidenceFirstPublication::NoEvidence => {
                    DeepResearchReportStatus::Degraded
                }
            };
            DeepResearchReportSynthesis {
                text,
                artifacts: ResearchReportArtifacts {
                    markdown: published.artifacts.markdown,
                    html: published.artifacts.html,
                },
                status,
            }
        }
        None => {
            synthesize_deepresearch_report(
                &session,
                workspace,
                query,
                &workflow_output,
                exit_code,
                metadata.as_ref(),
                &run_id,
                &report_tool_gate,
            )
            .await?
        }
    };
    let requested_outcome = match synthesis.status {
        DeepResearchReportStatus::Completed => crate::tui::ResearchOutcome::Completed,
        DeepResearchReportStatus::Qualified => crate::tui::ResearchOutcome::Qualified,
        DeepResearchReportStatus::Degraded => crate::tui::ResearchOutcome::Degraded,
    };
    let journal_artifacts = crate::tui::ResearchReportArtifacts {
        markdown: synthesis.artifacts.markdown.clone(),
        html: synthesis.artifacts.html.clone(),
    };
    let settled_outcome =
        crate::tui::settle_deep_research_cli_run(crate::tui::DeepResearchCliSettlement {
            workspace,
            run_id: &run_id,
            query,
            workflow_succeeded,
            workflow_output: &workflow_output,
            workflow_metadata: metadata.as_ref(),
            requested_outcome,
            artifacts: &journal_artifacts,
        })
        .await
        .map_err(anyhow::Error::msg)?;
    synthesis.status = match settled_outcome {
        crate::tui::ResearchOutcome::Completed => DeepResearchReportStatus::Completed,
        crate::tui::ResearchOutcome::Qualified => DeepResearchReportStatus::Qualified,
        crate::tui::ResearchOutcome::Degraded | crate::tui::ResearchOutcome::Failed => {
            DeepResearchReportStatus::Degraded
        }
        crate::tui::ResearchOutcome::Active => {
            return Err(anyhow::anyhow!(
                "DeepResearch CLI journal remained active after terminal settlement"
            ));
        }
    };
    Ok(synthesis)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeepResearchReportStatus {
    Completed,
    Qualified,
    Degraded,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ResearchReportArtifacts {
    pub(crate) markdown: PathBuf,
    pub(crate) html: PathBuf,
}

#[derive(Clone, Default)]
pub(crate) struct DeepResearchReportToolGate {
    report_only: Arc<AtomicBool>,
}

impl DeepResearchReportToolGate {
    pub(crate) fn set_report_only(&self, enabled: bool) {
        self.report_only.store(enabled, Ordering::SeqCst);
    }

    pub(crate) fn report_only(&self) -> bool {
        self.report_only.load(Ordering::SeqCst)
    }
}

#[derive(Debug)]
pub(crate) struct DeepResearchReportSynthesis {
    pub(crate) text: String,
    pub(crate) artifacts: ResearchReportArtifacts,
    pub(crate) status: DeepResearchReportStatus,
}

#[allow(clippy::too_many_arguments)]
async fn synthesize_deepresearch_report(
    session: &AgentSession,
    workspace: &Path,
    query: &str,
    workflow_output: &str,
    exit_code: i32,
    metadata: Option<&serde_json::Value>,
    run_id: &str,
    report_tool_gate: &DeepResearchReportToolGate,
) -> anyhow::Result<DeepResearchReportSynthesis> {
    eprintln!("deepresearch: synthesizing report artifacts…");
    let qualified =
        match crate::tui::deep_research_cli_report_is_qualified(query, workflow_output, metadata) {
            Ok(qualified) => qualified,
            Err(reason) => {
                report_tool_gate.set_report_only(false);
                let reason = format!("report plan rejected: {reason}");
                eprintln!("deepresearch: {reason}");
                return materialize_deepresearch_cli_recovery(
                    workspace,
                    query,
                    &reason,
                    workflow_output,
                    metadata,
                );
            }
        };
    if !crate::tui::deep_research_cli_sectioned_report_available(workflow_output, metadata) {
        report_tool_gate.set_report_only(false);
        let reason =
            "report plan rejected: current DeepResearch output has no reportable Outlining Inquiry";
        eprintln!("deepresearch: {reason}");
        return materialize_deepresearch_cli_recovery(
            workspace,
            query,
            reason,
            workflow_output,
            metadata,
        );
    }

    report_tool_gate.set_report_only(true);
    let mut completed_workflow_output = workflow_output.to_string();
    let mut completed_metadata = metadata.cloned();
    let generated = match tokio::time::timeout(
        std::time::Duration::from_millis(DEEP_RESEARCH_SYNTHESIS_TIMEOUT_MS),
        crate::tui::complete_deep_research_cli_sectioned_report(
            session,
            query,
            &mut completed_workflow_output,
            &mut completed_metadata,
            run_id,
            DEEP_RESEARCH_SYNTHESIS_TIMEOUT_MS,
        ),
    )
    .await
    {
        Ok(Ok(result)) => crate::tui::materialize_deep_research_cli_generated_report(
            workspace,
            query,
            &result.output,
            result.exit_code,
            &completed_workflow_output,
            completed_metadata.as_ref(),
        ),
        Ok(Err(error)) => Err(format!("sectioned report generation failed: {error}")),
        Err(_) => {
            let _ = session
                .cancel_and_settle(
                    std::time::Duration::from_millis(DEEP_RESEARCH_ABORT_GRACE_MS),
                    std::time::Duration::from_millis(DEEP_RESEARCH_ABORT_SETTLE_MS),
                )
                .await;
            Err(format!(
                "sectioned report generation timed out after {DEEP_RESEARCH_SYNTHESIS_TIMEOUT_MS} ms"
            ))
        }
    };
    report_tool_gate.set_report_only(false);

    match generated {
        Ok((text, markdown, html)) => Ok(DeepResearchReportSynthesis {
            text,
            artifacts: ResearchReportArtifacts { markdown, html },
            status: if qualified || exit_code != 0 {
                DeepResearchReportStatus::Qualified
            } else {
                DeepResearchReportStatus::Completed
            },
        }),
        Err(reason) => {
            eprintln!("deepresearch: structured report rejected: {reason}");
            materialize_deepresearch_cli_recovery(
                workspace,
                query,
                &reason,
                &completed_workflow_output,
                completed_metadata.as_ref(),
            )
        }
    }
}

fn materialize_deepresearch_cli_recovery(
    workspace: &Path,
    query: &str,
    reason: &str,
    workflow_output: &str,
    metadata: Option<&serde_json::Value>,
) -> anyhow::Result<DeepResearchReportSynthesis> {
    let (text, markdown, html) = crate::tui::materialize_deep_research_cli_recovery_report(
        workspace,
        query,
        reason,
        workflow_output,
        metadata,
    )
    .map_err(anyhow::Error::msg)?;
    Ok(DeepResearchReportSynthesis {
        text,
        artifacts: ResearchReportArtifacts { markdown, html },
        status: DeepResearchReportStatus::Degraded,
    })
}

fn deepresearch_cli_permission_policy() -> a3s_code_core::permissions::PermissionPolicy {
    let mut policy = a3s_code_core::permissions::PermissionPolicy::new()
        .deny_all(&[
            "Write(/**)",
            "Edit(/**)",
            "Write(**/../**)",
            "Edit(**/../**)",
        ])
        .allow_all(&[
            "Read(*)",
            "Grep(*)",
            "Glob(*)",
            "LS(*)",
            "read(*)",
            "grep(*)",
            "glob(*)",
            "ls(*)",
            "web_search(*)",
            "web_fetch(*)",
        ]);
    policy.default_decision = a3s_code_core::permissions::PermissionDecision::Deny;
    policy
}

#[derive(Clone)]
struct DeepResearchPermissionChecker {
    base: a3s_code_core::permissions::PermissionPolicy,
    report_tool_gate: DeepResearchReportToolGate,
}

impl a3s_code_core::permissions::PermissionChecker for DeepResearchPermissionChecker {
    fn check(
        &self,
        tool_name: &str,
        args: &serde_json::Value,
    ) -> a3s_code_core::permissions::PermissionDecision {
        if self.report_tool_gate.report_only() {
            deep_research_report_phase_tool_permission(tool_name, args)
        } else {
            self.base.check(tool_name, args)
        }
    }
}

pub(crate) fn deep_research_report_phase_tool_permission(
    tool_name: &str,
    _args: &serde_json::Value,
) -> a3s_code_core::permissions::PermissionDecision {
    match tool_name.to_ascii_lowercase().as_str() {
        "generate_object" => a3s_code_core::permissions::PermissionDecision::Allow,
        _ => a3s_code_core::permissions::PermissionDecision::Deny,
    }
}

async fn build_deepresearch_session(
    workspace: &str,
    code_config: CodeConfig,
    memory_dir: PathBuf,
) -> anyhow::Result<(Arc<AgentSession>, DeepResearchReportToolGate)> {
    build_deepresearch_session_with_resolver(
        workspace,
        code_config,
        memory_dir,
        crate::session_llm::resolve_session_llm_client,
    )
    .await
}

async fn build_deepresearch_session_with_resolver<F>(
    workspace: &str,
    code_config: CodeConfig,
    memory_dir: PathBuf,
    resolve_llm_client: F,
) -> anyhow::Result<(Arc<AgentSession>, DeepResearchReportToolGate)>
where
    F: FnOnce(
        &CodeConfig,
        &SessionOptions,
        &str,
    ) -> Result<Arc<dyn a3s_code_core::llm::LlmClient>, String>,
{
    let permission_policy = deepresearch_cli_permission_policy();
    let report_tool_gate = DeepResearchReportToolGate::default();
    let session_id = deep_research_execution_id();
    let opts = SessionOptions::new()
        .with_session_id(&session_id)
        .with_confirmation_policy(a3s_code_core::hitl::ConfirmationPolicy::default())
        .with_permission_policy(permission_policy.clone())
        .with_permission_checker(Arc::new(DeepResearchPermissionChecker {
            base: permission_policy,
            report_tool_gate: report_tool_gate.clone(),
        }))
        .with_tool_timeout(RESEARCH_TOOL_EXEC_TIMEOUT_MS)
        .with_duplicate_tool_call_threshold(RESEARCH_DUPLICATE_TOOL_CALL_THRESHOLD)
        .with_file_memory(memory_dir)
        // DeepResearch invokes only host-owned tools. Keep one manual `task`
        // slot for the optional local-workspace retrieval step; never expose
        // automatic delegation, parallel fan-out, or parent continuations.
        .with_continuation(false)
        .with_max_parallel_tasks(1)
        .with_auto_delegation_enabled(false)
        .with_auto_parallel_delegation(false)
        .with_manual_delegation_enabled(true);
    let llm_client = resolve_llm_client(&code_config, &opts, &session_id)
        .map_err(|error| anyhow::anyhow!("failed to resolve DeepResearch model: {error}"))?;
    let opts = opts.with_llm_client(llm_client);
    let agent = Agent::from_config(code_config)
        .await
        .map_err(|e| anyhow::anyhow!("failed to load DeepResearch agent: {e}"))?;
    let session = agent
        .session_async(workspace.to_string(), Some(opts))
        .await?;
    session.register_dynamic_workflow_runtime()?;
    Ok((Arc::new(session), report_tool_gate))
}

fn deep_research_execution_id() -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    format!("research-{nanos:016x}-{:x}", std::process::id())
}

async fn run_deepresearch_inquiry(
    session: Arc<AgentSession>,
    args: serde_json::Value,
) -> Result<ToolCallResult, String> {
    let timeout_ms = crate::tui::DEEP_RESEARCH_EVIDENCE_FIRST_HOST_TIMEOUT_MS;
    let (mut progress_rx, workflow_join) =
        crate::tui::spawn_deep_research_evidence_first(session, args);
    let workflow_abort = workflow_join.abort_handle();
    let progress_drain = tokio::spawn(async move { while progress_rx.recv().await.is_some() {} });
    let result = match tokio::time::timeout(
        std::time::Duration::from_millis(timeout_ms),
        workflow_join,
    )
    .await
    {
        Ok(Ok(result)) => result.map_err(|err| err.to_string()),
        Ok(Err(err)) => Err(err.to_string()),
        Err(_) => {
            workflow_abort.abort();
            Err(format!(
                "DeepResearch timed out after {timeout_ms} ms while acquiring sources and publishing its Host-owned report"
            ))
        }
    };
    progress_drain.abort();
    result.map(|mut result| {
        result.output = crate::tui::deep_research_cli_canonical_workflow_output(
            &result.output,
            result.metadata.as_ref(),
        );
        result
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    // Frozen replay tests stay isolated from production control flow.
    #[path = "baseline.rs"]
    mod baseline;
    #[path = "cli.rs"]
    mod cli;
    #[path = "workflow.rs"]
    mod workflow;
    use a3s_code_core::llm::{
        ContentBlock, LlmClient, LlmResponse, Message, StreamEvent, TokenUsage, ToolDefinition,
    };
    use async_trait::async_trait;
    use std::collections::VecDeque;
    use std::sync::Mutex;
    use tokio::sync::mpsc;
    use tokio_util::sync::CancellationToken;

    struct ScriptedLlmClient {
        responses: Mutex<VecDeque<LlmResponse>>,
    }

    #[async_trait]
    impl LlmClient for ScriptedLlmClient {
        fn model_generation_concurrency(&self) -> a3s_code_core::llm::ModelGenerationConcurrency {
            a3s_code_core::llm::ModelGenerationConcurrency::bounded(
                std::num::NonZeroUsize::new(1).expect("scripted test concurrency is non-zero"),
            )
        }

        async fn complete(
            &self,
            messages: &[Message],
            system: Option<&str>,
            tools: &[ToolDefinition],
        ) -> anyhow::Result<LlmResponse> {
            Ok(self.response_for_messages(messages, system, tools))
        }

        async fn complete_streaming(
            &self,
            messages: &[Message],
            system: Option<&str>,
            tools: &[ToolDefinition],
            _cancel_token: CancellationToken,
        ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
            let response = self.response_for_messages(messages, system, tools);
            let (tx, rx) = mpsc::channel(1);
            tokio::spawn(async move {
                let _ = tx.send(StreamEvent::Done(response)).await;
            });
            Ok(rx)
        }

        fn native_structured_support(
            &self,
        ) -> a3s_code_core::llm::structured::NativeStructuredSupport {
            a3s_code_core::llm::structured::NativeStructuredSupport::ForcedTool
        }
    }

    impl ScriptedLlmClient {
        fn new(responses: Vec<LlmResponse>) -> Self {
            Self {
                responses: Mutex::new(responses.into()),
            }
        }

        fn response_for_messages(
            &self,
            _messages: &[Message],
            _system: Option<&str>,
            _tools: &[ToolDefinition],
        ) -> LlmResponse {
            self.next_response()
        }

        fn next_response(&self) -> LlmResponse {
            self.responses
                .lock()
                .unwrap()
                .pop_front()
                .unwrap_or_else(|| text_response("DONE"))
        }
    }

    fn text_response(text: impl Into<String>) -> LlmResponse {
        LlmResponse {
            message: Message {
                role: "assistant".into(),
                content: vec![ContentBlock::Text { text: text.into() }],
                reasoning_content: None,
            },
            usage: TokenUsage::default(),
            stop_reason: Some("stop".into()),
            token_logprobs: Vec::new(),
            meta: None,
        }
    }

    fn tool_call_response(id: &str, name: &str, input: serde_json::Value) -> LlmResponse {
        LlmResponse {
            message: Message {
                role: "assistant".into(),
                content: vec![ContentBlock::ToolUse {
                    id: id.into(),
                    name: name.into(),
                    input,
                }],
                reasoning_content: None,
            },
            usage: TokenUsage::default(),
            stop_reason: Some("tool_use".into()),
            token_logprobs: Vec::new(),
            meta: None,
        }
    }

    fn test_config(path: &std::path::Path) {
        std::fs::write(
            path,
            "default_model = \"openai/x\"\n\
             providers \"openai\" {\n  apiKey = \"x\"\n  baseUrl = \"http://127.0.0.1:1\"\n  \
             models \"x\" { name = \"x\" }\n}\n\
             memory {\n  llmExtraction = false\n}\n",
        )
        .unwrap();
    }
}