-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
722 lines (656 loc) · 25.7 KB
/
Copy pathcli.py
File metadata and controls
722 lines (656 loc) · 25.7 KB
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import json
import os
import shutil
import sys
from pathlib import Path
import typer
from agentdiff.ci.baseline import decide_rotation
from agentdiff.ci.github import post_pr_comment
from agentdiff.config import (
AgentDiffConfig,
TolerancesConfig,
find_config_file,
load_config,
)
from agentdiff.engine.comparator import compare, compare_envelope
from agentdiff.engine.explanations import format_explanations, locate_culprit
from agentdiff.engine.tree import render_tree
from agentdiff.governance import diff_gate_thresholds, provenance_line
from agentdiff.loader import load_baseline, load_trace
from agentdiff.models.envelope import BaselineEnvelope
from agentdiff.models.step import StepStatus
from agentdiff.recorder import record_run, save_trace
from agentdiff.reporters.markdown import generate_markdown
from agentdiff.reporters.pr import generate_pr_markdown
from agentdiff.reporters.terminal import print_report
from agentdiff.staleness import check_baseline_staleness
from agentdiff.testing.assertions import evaluate_gate
app = typer.Typer(
help="AgentDiff CLI - Compare multi-turn agent execution trajectories."
)
@app.command(name="record")
def record(
target: str = typer.Argument(
...,
help="Callable to run, as 'module:function' or 'module:Class.method'.",
),
out: str = typer.Option(
...,
"--out",
"-o",
help="Path to write the captured trace JSON (e.g. traces/run.json).",
),
input_json: str | None = typer.Option(
None,
"--input",
"-i",
help="JSON object passed to the callable as kwargs (or a single positional arg if not an object). Use '@file.json' to read from a file.",
),
name: str | None = typer.Option(
None,
"--name",
help="Agent name recorded in the trace (default: function name).",
),
runs: int = typer.Option(
1,
"--runs",
"-n",
min=1,
help="Run the callable N times and save a statistical baseline "
"envelope (N >= 2) instead of a single trace.",
),
):
"""Runs an agent callable once and captures its trajectory as a trace.
Example:
agentdiff record my_agent:run --input '{"question": "hi"}' --out traces/run.json
The captured trace is a canonical AgentDiff JSON, ready for:
agentdiff diff traces/baseline.json traces/run.json
"""
task_input: dict | None = None
if input_json:
try:
if input_json.startswith("@"):
task_input = json.loads(
Path(input_json[1:]).read_text(encoding="utf-8")
)
else:
task_input = json.loads(input_json)
except (json.JSONDecodeError, FileNotFoundError) as e:
typer.echo(f"Invalid --input: {e}", err=True)
sys.exit(2)
if not isinstance(task_input, dict):
task_input = {"input": task_input}
try:
traces = []
for i in range(runs):
if runs > 1:
typer.echo(f"Recording run {i + 1}/{runs}...")
traces.append(record_run(target, task_input=task_input, agent_name=name))
except ValueError as e:
typer.echo(f"Error: {e}", err=True)
sys.exit(2)
except Exception as e:
typer.echo(f"Recording failed: {e}", err=True)
sys.exit(3)
trace = traces[0]
if runs > 1:
envelope = BaselineEnvelope.from_runs(traces)
Path(out).write_text(envelope.model_dump_json(), encoding="utf-8")
failed = sum(
1 for t in traces if t.steps and t.steps[0].status == StepStatus.ERROR
)
typer.echo(
f"Recorded envelope ({runs} runs) → {out}"
+ (f" ⚠ {failed} run(s) failed" if failed else "")
)
sys.exit(1 if failed == runs else 0)
path = save_trace(trace, out)
if trace.steps[0].status == StepStatus.ERROR:
typer.echo(
f"Recorded FAILED run → {path}\n error: {trace.steps[0].error_message}",
err=True,
)
sys.exit(1)
typer.echo(f"Recorded run → {path}")
typer.echo(f" agent: {trace.agent_name} · latency: {trace.total_latency_ms:.0f}ms")
typer.echo(f"Next: agentdiff diff <baseline> {path}")
@app.command(name="init")
def init(
scenario: str = typer.Option(
"default",
"--scenario",
help="Scenario name written into agentdiff.toml and the workflow.",
),
runs: int = typer.Option(
3,
"--runs",
"-n",
min=1,
help="Sample runs recorded into the baseline envelope.",
),
adapter: str | None = typer.Option(
None,
"--adapter",
help="Override framework detection (langgraph, crewai, openai_agents, openinference, generic).",
),
force: bool = typer.Option(
False,
"--force",
help="Overwrite existing agentdiff.toml / workflow files.",
),
with_approve: bool = typer.Option(
False,
"--with-approve",
help="Also write the /agentdiff approve bot workflow (see docs for the GitHub App identity setup).",
),
):
"""Zero-config wizard: detect your framework, write agentdiff.toml + CI gate.
Example:
agentdiff init --scenario customer_refund --runs 5
"""
from agentdiff.init_wizard import (
FRAMEWORKS,
GENERIC,
detect_framework,
write_config,
)
if adapter:
match = next(
(f for f in (*FRAMEWORKS, GENERIC) if f.key == adapter.lower()), None
)
if match is None:
typer.echo(
f"Unknown adapter {adapter!r}. Known: {', '.join(f.key for f in (*FRAMEWORKS, GENERIC))}",
err=True,
)
sys.exit(2)
framework = match
else:
framework = detect_framework()
typer.echo(f"Detected framework: {framework.label} ({framework.note})")
try:
created = write_config(
Path.cwd(),
framework=framework,
scenario=scenario,
runs=runs,
force=force,
with_approve=with_approve,
)
except FileExistsError as e:
typer.echo(f"Error: {e}", err=True)
sys.exit(2)
for path in created:
typer.echo(f"Wrote {path}")
next_steps = (
f"\nNext steps:\n"
f" 1. Record a baseline envelope:\n"
f" agentdiff record <your_agent:run> --runs {runs} "
f"--out baselines/{scenario}.envelope.json\n"
f" 2. Commit agentdiff.toml, the workflow(s), and the baseline.\n"
f" 3. Open a PR — AgentDiff gates it automatically.\n"
f" 4. Reviewers bless accepted drift with: /agentdiff approve\n"
)
if with_approve:
next_steps += (
" (set the AgentDiff GitHub App secrets for the branded\n"
" agentdiff[bot] identity and automatic check re-runs)\n"
)
typer.echo(next_steps)
@app.command(name="approve")
def approve(
baseline_path: str = typer.Argument(
..., help="Path to the baseline (trace JSON or statistical envelope)."
),
candidate_path: str = typer.Argument(
..., help="Path to the candidate trace being blessed (the PR's run)."
),
scenario: str | None = typer.Option(
None, "--scenario", help="Scenario name from agentdiff.toml."
),
runs: int = typer.Option(
3, "--runs", min=2, help="Rolling window size kept for statistical envelopes."
),
pr: int | None = typer.Option(
None, "--pr", help="Post the approval confirmation as a GitHub PR comment."
),
):
"""Blesses a candidate run as the new golden baseline (Pillar 3).
Used by the /agentdiff approve PR bot. Path drift and cost spikes are
human-blessable; loop violations are NEVER blessable — the command
refuses and the loop must be fixed.
Example:
agentdiff approve baselines/refund.envelope.json traces/pr-12.json --pr 12
"""
from agentdiff.ci.approve import approve_candidate
from agentdiff.ci.github import post_pr_comment
cfg = load_config(None)
scenario_cfg = cfg.scenario(scenario)
try:
decision = approve_candidate(
baseline_path,
candidate_path,
scenario_cfg=scenario_cfg,
sample_runs=runs,
)
except (json.JSONDecodeError, ValueError, FileNotFoundError) as e:
typer.echo(f"Error loading traces: {e}", err=True)
sys.exit(2)
except Exception as e:
typer.echo(f"Approve failed: {e}", err=True)
sys.exit(3)
if not decision.approved:
typer.echo("✖ Approval REFUSED", err=True)
for message in decision.refusals:
typer.echo(f" - {message}", err=True)
typer.echo(decision.reason, err=True)
sys.exit(1)
typer.echo(f"✅ Baseline updated at {baseline_path}")
typer.echo(f" {decision.reason}")
if pr is not None:
lines = [
"## AgentDiff — baseline approved ✅",
"",
f"Blessed by @{os.environ.get('AGENTDIFF_APPROVER', 'a reviewer')} "
"via `/agentdiff approve`.",
"",
f"{decision.reason}.",
"",
"The AgentDiff check will pass on the next run of this PR.",
"",
"<sub>Loop violations are never blessable (policy D3).</sub>",
]
try:
comment = post_pr_comment("\n".join(lines), pr)
typer.echo(f"Posted approval comment: {comment.get('html_url')}")
except (ValueError, RuntimeError) as e:
typer.echo(f"Warning: could not post PR comment: {e}", err=True)
sys.exit(0)
def _resolve_cli(cfg: AgentDiffConfig, **values):
"""Returns config-provided values for any option left at its sentinel."""
resolved = {}
for key, val in values.items():
if val is not None:
resolved[key] = val
elif key == "adapter":
resolved[key] = cfg.adapter.name or "auto"
elif key == "max_tool_repeats":
resolved[key] = cfg.invariants.max_tool_repeats
else:
resolved[key] = getattr(cfg.cli, key, None)
return resolved
@app.command(name="diff")
def diff(
baseline_path: str = typer.Argument(..., help="Path to baseline trace JSON file"),
candidate_path: str = typer.Argument(..., help="Path to candidate trace JSON file"),
adapter: str | None = typer.Option(
None,
help="Telemetry adapter: auto, generic, openinference, langfuse, langsmith, openai_agents (default: config or auto)",
),
format: str | None = typer.Option(
None,
help="Output format: terminal, json, markdown, pr (default: config or terminal)",
),
output_file: str | None = typer.Option(
None, help="Write output to specified file path"
),
config: str | None = typer.Option(
None,
"--config",
help="Path to an agentdiff.toml config file (default: auto-discovered agentdiff.toml).",
),
explain: bool = typer.Option(
False,
"--explain",
help="Print human-readable explanations of why the run diverged.",
),
tree: bool = typer.Option(
False,
"--tree",
help="Print a collapsed, capped divergence view of the trajectories.",
),
fail_on_regression: bool = typer.Option(
False, help="Return exit code 1 if regressions are detected"
),
max_loops: int | None = typer.Option(
None, help="Maximum allowed loop count before regression (default: config or 0)"
),
max_divergence: float | None = typer.Option(
None, help="Maximum allowed TDI before regression (default: config or 0.3)"
),
max_cost_delta: float | None = typer.Option(
None,
help="Maximum allowed cost increase %% before regression (default: config or 10.0)",
),
max_recovery_ratio: float | None = typer.Option(
None,
help="Maximum allowed Recovery Step Ratio (RSR) before regression "
"(candidate vs baseline post-error recovery effort; opt-in).",
),
allow_identical_loops: bool = typer.Option(
False,
"--allow-identical-loops",
help="Disable the cyclical-tool-loop hard invariant (same endpoint "
"called >= 2 times with identical inputs and stagnant outputs).",
),
max_tool_repeats: int | None = typer.Option(
None,
"--max-tool-repeats",
help="Hard cap on calls to any single endpoint (opt-in invariant; "
"default: config or disabled).",
),
baseline_store: str | None = typer.Option(
None,
"--baseline",
"-b",
help="Path to a persistent baseline trace file. First run establishes it when --update-baseline is set.",
),
update_baseline: bool = typer.Option(
False,
"--update-baseline",
help="Overwrite the persistent baseline with the candidate after a clean diff.",
),
pr: int | None = typer.Option(
None,
"--pr",
help="Post the PR-ready markdown as a comment to this GitHub PR number.",
),
baseline_rotation: str = typer.Option(
"manual",
"--baseline-rotation",
help="Baseline rotation policy: manual, auto, or staged.",
),
max_drift: float = typer.Option(
0.05, help="Max TDI a clean run may have for staged auto-rotation."
),
baseline_config: str | None = typer.Option(
None,
"--baseline-config",
help="Path to the agentdiff.toml the BASELINE was recorded with. When gate values differ from this run's config, the report flags the change (Goodhart guard).",
),
stale_days: int | None = typer.Option(
None,
"--stale-days",
help="Warn (with --explain) when the baseline file is older than this many days (default: config or 30).",
),
scenario: str | None = typer.Option(
None,
"--scenario",
help="Scenario name from agentdiff.toml ([scenario.<name>]) whose gates and tolerances apply.",
),
):
"""Compares baseline and candidate agent trajectories."""
cfg = load_config(config)
config_source = config or (str(find_config_file()) if find_config_file() else None)
threshold_changes: list = []
if baseline_config:
try:
baseline_cfg = load_config(baseline_config)
except FileNotFoundError as e:
typer.echo(f"Baseline config not found: {e}", err=True)
sys.exit(2)
threshold_changes = diff_gate_thresholds(baseline_cfg, cfg)
stale_days = (
stale_days
if stale_days is not None
else getattr(cfg.cli, "stale_baseline_days", 30)
)
values = _resolve_cli(
cfg,
adapter=adapter,
format=format,
max_loops=max_loops,
max_divergence=max_divergence,
max_cost_delta=max_cost_delta,
max_recovery_ratio=max_recovery_ratio,
baseline_store=baseline_store,
max_tool_repeats=max_tool_repeats,
)
adapter = values["adapter"]
format = values["format"] or "terminal"
max_loops = values["max_loops"] or 0
max_divergence = values["max_divergence"]
if max_divergence is None:
max_divergence = 0.3
max_cost_delta = values["max_cost_delta"]
if max_cost_delta is None:
max_cost_delta = 10.0
max_recovery_ratio = values["max_recovery_ratio"]
baseline_store = values["baseline_store"]
max_tool_repeats = values["max_tool_repeats"]
scenario_cfg = cfg.scenario(scenario)
invariants = scenario_cfg.hard_invariants if scenario_cfg else cfg.invariants
if not allow_identical_loops:
fail_on_identical_loops = invariants.fail_on_identical_loops
else:
fail_on_identical_loops = False
if invariants.max_tool_repeats is not None and max_tool_repeats is None:
max_tool_repeats = invariants.max_tool_repeats
detect_loops = cfg.compare.detect_loops
strict_tool_signatures = cfg.compare.strict_tool_signatures
try:
# Validate the candidate parses before we do anything else
candidate = load_trace(candidate_path, adapter)
# Resolve the baseline: either an explicit store or the positional path
if baseline_store:
if not os.path.exists(baseline_store):
if update_baseline:
envelope = BaselineEnvelope.from_runs(
[candidate],
scenario=scenario or "default",
mode=scenario_cfg.mode if scenario_cfg else "statistical",
)
Path(baseline_store).write_text(
envelope.model_dump_json(), encoding="utf-8"
)
typer.echo(
f"Baseline established at {baseline_store} from {candidate_path}"
)
sys.exit(0)
typer.echo(
f"Baseline not found at {baseline_store}. "
"Run with --update-baseline to establish it.",
err=True,
)
sys.exit(2)
actual_baseline = baseline_store
else:
actual_baseline = baseline_path
# F7 — surface baseline age so stale baselines are re-recorded deliberately
staleness = check_baseline_staleness(
actual_baseline, stale_after_days=stale_days
)
baseline_env = load_baseline(actual_baseline, adapter)
except (json.JSONDecodeError, ValueError, FileNotFoundError) as e:
typer.echo(f"Error loading or parsing trace: {e}", err=True)
sys.exit(2)
except Exception as e:
typer.echo(f"Ingestion error: {e}", err=True)
sys.exit(2)
# G7 provenance must describe the gate that actually judged this run —
# in envelope mode that is the scenario tolerances, not the legacy knobs.
gate_provenance = provenance_line(
cfg, config_source, scenario_cfg=scenario_cfg, envelope=baseline_env
)
try:
recovery_kwargs = {}
if max_recovery_ratio is not None:
# explicit threshold wins; otherwise the 3.0 recovery-cascade
# default (PRD failure class) applies inside the gate
recovery_kwargs["max_recovery_step_ratio"] = max_recovery_ratio
if baseline_env.mode == "statistical" and baseline_env.n_runs >= 2:
# Pillar 1 — statistical envelope: judge against normal variance
tol = scenario_cfg.tolerances if scenario_cfg else TolerancesConfig()
cost_pct = scenario_cfg.max_cost_increase_pct if scenario_cfg else 20.0
report, gate = compare_envelope(
baseline_env,
candidate,
max_divergence=tol.divergence_ceiling,
max_cost_increase_pct=cost_pct,
max_loops=max_loops,
step_count_std_dev=tol.step_count_std_dev,
fail_on_identical_loops=fail_on_identical_loops,
max_tool_repeats=max_tool_repeats,
**recovery_kwargs,
)
else:
# Strict mode: single-run comparison (v1 behavior, unchanged)
report = compare(
baseline_env.runs[0],
candidate,
detect_loops=detect_loops,
strict_tool_signatures=strict_tool_signatures,
)
gate = evaluate_gate(
report,
max_divergence=max_divergence,
max_cost_increase_pct=max_cost_delta,
max_loops=max_loops,
fail_on_identical_loops=fail_on_identical_loops,
max_tool_repeats=max_tool_repeats,
**recovery_kwargs,
)
has_regression = not gate.passed
report.warnings = gate.warnings
report.violations = gate.violations
if has_regression:
report.passed = False
# Format output
output_content = ""
if format.lower() == "terminal":
# For console printing we write directly, but we can capture it or format differently if output_file is active
if output_file:
# If writing terminal format to file, output the text summary representation
output_content = report.summary() + f"\n{gate_provenance}\n"
else:
print_report(report, gate_provenance=gate_provenance)
elif format.lower() == "json":
report.gate_provenance = gate_provenance
output_content = report.model_dump_json(indent=2)
if not output_file:
typer.echo(output_content)
elif format.lower() == "markdown":
output_content = generate_markdown(report)
if not output_file:
typer.echo(output_content)
elif format.lower() == "pr":
output_content = generate_pr_markdown(
report,
max_divergence=max_divergence,
max_loops=max_loops,
max_cost_delta=max_cost_delta,
max_recovery_ratio=max_recovery_ratio,
threshold_changes=threshold_changes,
gate_provenance=gate_provenance,
)
if not output_file:
typer.echo(output_content)
else:
typer.echo(f"Unsupported format: {format}", err=True)
sys.exit(2)
# Print human-readable explanations when requested
if explain:
typer.echo("\n" + format_explanations(report))
culprit = locate_culprit(report)
if culprit:
typer.echo("\n" + culprit.render())
if staleness.is_stale:
typer.echo(f"\n! {staleness.render()}")
if threshold_changes:
typer.echo("\nGate thresholds changed vs baseline config:")
for change in threshold_changes:
typer.echo(f" ! {change.render()}")
# Print the collapsed divergence tree when requested
if tree:
typer.echo("\n" + render_tree(report))
# Post PR-ready markdown as a GitHub PR comment when requested
if pr is not None:
body = generate_pr_markdown(
report,
max_divergence=max_divergence,
max_loops=max_loops,
max_cost_delta=max_cost_delta,
max_recovery_ratio=max_recovery_ratio,
threshold_changes=threshold_changes,
gate_provenance=gate_provenance,
)
comment = post_pr_comment(body, pr)
url = comment.get("html_url")
typer.echo(f"Posted AgentDiff comment to PR #{pr}: {url}")
# Write to file if requested
if output_file:
with open(output_file, "w", encoding="utf-8") as f:
f.write(output_content)
# Update the persistent baseline per the rotation policy
if baseline_store:
decision = decide_rotation(
report,
policy=baseline_rotation,
max_drift=max_drift,
explicit_update=update_baseline,
)
if decision.rotate:
if baseline_env.mode == "statistical" and baseline_env.n_runs >= 2:
# Rolling window: append the candidate, keep the most
# recent sample_runs, recompute the bands.
baseline_env.runs.append(candidate)
keep = scenario_cfg.sample_runs if scenario_cfg else 3
keep = max(2, keep)
baseline_env.runs = baseline_env.runs[-keep:]
baseline_env.refresh()
Path(baseline_store).write_text(
baseline_env.model_dump_json(), encoding="utf-8"
)
else:
shutil.copyfile(candidate_path, baseline_store)
typer.echo(f"Baseline updated at {baseline_store}: {decision.reason}")
elif update_baseline:
typer.echo(f"Baseline not updated: {decision.reason}")
# Enforce exit code protocol
if fail_on_regression and has_regression:
sys.exit(1)
sys.exit(0)
except SystemExit:
raise
except Exception as e:
typer.echo(f"Internal comparison error: {e}", err=True)
sys.exit(3)
def main():
try:
app()
except SystemExit as e:
sys.exit(e.code)
except Exception as e:
print(f"Unhandled error: {e}", file=sys.stderr)
sys.exit(3)
def _install_diff_default() -> None:
"""E1 compat: `agentdiff base.json cand.json` (no subcommand) means `diff`.
With two commands registered, Typer requires an explicit subcommand. We
patch the built click.Group so a leading positional that isn't a known
command is treated as `diff ...`. Works for the real CLI and CliRunner.
"""
import typer.main
original_get_command = typer.main.get_command
def get_command_with_default(typer_app):
group = original_get_command(typer_app)
if not getattr(group, "_diff_default", False):
original_parse_args = group.parse_args
def parse_args(ctx, args):
if (
args
and args[0] not in group.commands
and not args[0].startswith("-")
):
args = ["diff", *args]
original_parse_args(ctx, args)
group.parse_args = parse_args
group._diff_default = True
return group
typer.main.get_command = get_command_with_default
# typer.testing binds get_command at import time — patch its reference too
import typer.testing as testing_module
if getattr(testing_module, "_get_command", None) is original_get_command:
testing_module._get_command = get_command_with_default
_install_diff_default()
if __name__ == "__main__":
main()