Skip to content

Agents

dotagents._agents

Agent registry: base Agent type + per-agent adapters (Plan 00).

Agent

Base class for dotagents adapters.

Identity (plan 08): each adapter declares its harness_id (the stable ecosystem name, e.g. claude-code -- NOT the short registry name), vendor (provider family), and model_source_vars (the vendor-native env vars to read a running model id from, in precedence order). These feed stamp_identity which emits the standardized AGENTS_*/AGENT vars.

context_files = [] class-attribute instance-attribute

detect_env_vars = [] class-attribute instance-attribute

harness_id = '' class-attribute instance-attribute

harness_loads = [] class-attribute instance-attribute

model_source_vars = [] class-attribute instance-attribute

name = '' class-attribute instance-attribute

vendor = '' class-attribute instance-attribute

detect(root)

Return True if this agent's config is present in the given root.

Source code in src/dotagents/_agents.py
67
68
69
def detect(self, root: Path) -> bool:
    """Return True if this agent's config is present in the given root."""
    return any((root / f).exists() for f in self.context_files)

detect_env(environ)

Return True if this agent's harness is running based on env vars.

Default: True if any declared marker var is present. Adapters whose markers are prefixes (e.g. Codex's CODEX_SANDBOX_*) override this.

Source code in src/dotagents/_agents.py
29
30
31
32
33
34
35
def detect_env(self, environ: dict[str, str]) -> bool:
    """Return True if this agent's harness is running based on env vars.

    Default: True if any declared marker var is present. Adapters whose
    markers are prefixes (e.g. Codex's ``CODEX_SANDBOX_*``) override this.
    """
    return any(var in environ for var in self.detect_env_vars)

resolve_model(environ)

Return the running model id from the first populated source var, or None.

Source code in src/dotagents/_agents.py
37
38
39
40
41
42
43
def resolve_model(self, environ: dict[str, str]) -> "Optional[str]":
    """Return the running model id from the first populated source var, or None."""
    for var in self.model_source_vars:
        val = environ.get(var)
        if val:
            return val
    return None

wire_hooks(dest, *, dry_run, logger, config_root=None)

Wire up hooks in the agent's settings, if this adapter supports it.

A no-op on the base class: the hook schema is harness-specific, so only adapters with a verified schema override this. config_root overrides the agent's own config dir (e.g. ~/.claude) and exists so tests can redirect writes away from the real one.

Source code in src/dotagents/_agents.py
55
56
57
58
59
60
61
62
63
64
65
def wire_hooks(
    self, dest: Path, *, dry_run: bool, logger, config_root: "Optional[Path]" = None
) -> None:
    """Wire up hooks in the agent's settings, if this adapter supports it.

    A no-op on the base class: the hook schema is harness-specific, so only
    adapters with a *verified* schema override this. `config_root` overrides
    the agent's own config dir (e.g. `~/.claude`) and exists so tests can
    redirect writes away from the real one.
    """
    pass

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Write the base configuration files for this agent (used by init/install).

Source code in src/dotagents/_agents.py
45
46
47
48
49
def write_base_config(
    self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger
) -> None:
    """Write the base configuration files for this agent (used by init/install)."""
    pass

write_context(dest, effective_context, *, force, dry_run, logger)

Write the assembled context file for this agent (used by context generator).

Source code in src/dotagents/_agents.py
51
52
53
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    """Write the assembled context file for this agent (used by context generator)."""
    pass

AntigravityAgent

Bases: Agent

PRETOOLUSE_HOOK_SCRIPT = 'preinvocation_antigravity_context.py' class-attribute instance-attribute

context_files = ['.agents/rules/dotagents.md'] class-attribute instance-attribute

detect_env_vars = [] class-attribute instance-attribute

harness_id = 'antigravity' class-attribute instance-attribute

harness_loads = ['~/.gemini/GEMINI.md', '.agents/rules/dotagents.md'] class-attribute instance-attribute

model_source_vars = [] class-attribute instance-attribute

name = 'antigravity' class-attribute instance-attribute

vendor = 'google' class-attribute instance-attribute

wire_hooks(dest, *, dry_run, logger, config_root=None)

Deploys the context-injection script and wires it as a PreInvocation handler in <config_root|~/.gemini/config>/hooks.json.

Global scope only (~/.gemini/config/hooks.json), like the plugin directory it mirrors (~/.gemini/config/plugins/) -- Antigravity's docs describe this as making a plugin/hook "active across all workspaces", and PreInvocation carries no per-project matcher to scope it more narrowly (confirmed: PreInvocation's matcher is documented as ignored).

Source code in src/dotagents/_agents.py
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
def wire_hooks(
    self, dest: Path, *, dry_run: bool, logger, config_root: "Optional[Path]" = None
) -> None:
    """Deploys the context-injection script and wires it as a
    `PreInvocation` handler in `<config_root|~/.gemini/config>/hooks.json`.

    Global scope only (`~/.gemini/config/hooks.json`), like the plugin
    directory it mirrors (`~/.gemini/config/plugins/`) -- Antigravity's
    docs describe this as making a plugin/hook "active across all
    workspaces", and PreInvocation carries no per-project matcher to
    scope it more narrowly (confirmed: PreInvocation's matcher is
    documented as ignored).
    """
    import shutil

    from dotagents import _hooks
    from dotagents.cli._common import BASE_ROOT

    root = Path(config_root) if config_root else (Path.home() / ".gemini" / "config")

    src_script = Path(BASE_ROOT) / "dotagents" / "hooks" / self.PRETOOLUSE_HOOK_SCRIPT
    if not src_script.is_file():
        if logger:
            logger.warning("Antigravity hook script missing from package: %s", src_script)
        return

    dest_dir = root / "hooks"
    dest_script = dest_dir / self.PRETOOLUSE_HOOK_SCRIPT
    script_changed = not dest_script.is_file() or (
        dest_script.read_bytes() != src_script.read_bytes()
    )
    if script_changed and not dry_run:
        dest_dir.mkdir(parents=True, exist_ok=True)
        shutil.copy2(str(src_script), str(dest_script))

    hooks_path = root / "hooks.json"
    data = _hooks.load_settings(hooks_path)
    # dotagents' own top-level key, matching the docs' example shape
    # (`{"reminder": {"PreInvocation": [...]}}` -- named entries, not a
    # bare top-level "hooks" object the way Claude/Codex's schema is).
    entry = data.get("dotagents")
    if not isinstance(entry, dict):
        entry = {}

    script_path = dest_script.resolve()
    command = 'python "%s"' % script_path.as_posix()
    preinvocation, pi_changed = _hooks.merge_hook(
        entry.get("PreInvocation"),
        command,
        status_message="Loading agent context",
    )
    entry["PreInvocation"] = preinvocation
    data["dotagents"] = entry

    if not (script_changed or pi_changed):
        if logger:
            logger.info("hooks already wired: %s", hooks_path)
        return

    if dry_run:
        if logger:
            logger.info("would wire PreInvocation hook: %s", hooks_path)
        return
    _hooks.write_settings(hooks_path, data)
    if logger:
        logger.info("wired PreInvocation hook: %s", hooks_path)

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
449
450
451
452
453
454
455
456
457
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, timestamped_backup_root
    backup_root = timestamped_backup_root(dest) if force else None
    branch = merge_block(
        dest / "AGENTS.md",
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: AGENTS.md (Antigravity)", branch)

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
459
460
461
462
463
464
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / ".agents" / "rules" / "dotagents.md"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

ClaudeAgent

Bases: Agent

CWD_CHANGED_COMMAND = '[ -f AGENTS.md ] && cat AGENTS.md || true' class-attribute instance-attribute

CWD_CHANGED_COMMAND_POWERSHELL = 'if (Test-Path AGENTS.md) { Get-Content AGENTS.md -Raw }' class-attribute instance-attribute

PRETOOLUSE_POWERSHELL_COMMAND = '$h = [Console]::In.ReadToEnd() | ConvertFrom-Json; if ($h.tool_name -eq "PowerShell" -and -not $env:AGENTS_RUNTIME_SET -and $h.tool_input.command) { $p = \'if (-not $env:AGENTS_RUNTIME_SET) { $env:AGENTS_RUNTIME_SET = "1"; & "$HOME\\.agents\\bin\\dotagents.cmd" env --format powershell 2>$null | Invoke-Expression }; \'; $u = $h.tool_input.PSObject.Copy(); $u.command = $p + $h.tool_input.command; @{hookSpecificOutput=@{hookEventName="PreToolUse";permissionDecision="allow";updatedInput=$u}} | ConvertTo-Json -Depth 10 -Compress }' class-attribute instance-attribute

SESSION_START_COMMAND = 'if [ -n "$CLAUDE_ENV_FILE" ]; then %(path)s dotagents env --diff --format export >> "$CLAUDE_ENV_FILE"; fi; %(path)s dotagents context' % {'path': _HOOK_PATH} class-attribute instance-attribute

SESSION_START_COMMAND_POWERSHELL = '& "$env:USERPROFILE\\.agents\\bin\\dotagents.cmd" context' class-attribute instance-attribute

context_files = ['CLAUDE.md'] class-attribute instance-attribute

detect_env_vars = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT'] class-attribute instance-attribute

harness_id = 'claude-code' class-attribute instance-attribute

harness_loads = ['~/.agents/AGENTS.md', 'AGENTS.md'] class-attribute instance-attribute

model_source_vars = ['ANTHROPIC_MODEL'] class-attribute instance-attribute

name = 'claude' class-attribute instance-attribute

vendor = 'anthropic' class-attribute instance-attribute

wire_hooks(dest, *, dry_run, logger, config_root=None)

Link the shared skills dir into ~/.claude and merge our two hooks.

Additive and idempotent: unrelated settings keys and foreign hooks survive, and a second run writes nothing.

Source code in src/dotagents/_agents.py
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
def wire_hooks(
    self,
    dest: Path,
    *,
    dry_run: bool,
    logger,
    config_root: "Optional[Path]" = None,
) -> None:
    """Link the shared skills dir into `~/.claude` and merge our two hooks.

    Additive and idempotent: unrelated settings keys and foreign hooks survive,
    and a second run writes nothing.
    """
    import os

    from dotagents import _hooks, _skills

    # Scope-aware, like the rest of dotagents: a project-scope `init` must not
    # silently edit the user's GLOBAL settings. `dest` is `<scope>/.agents`, so
    # its parent is the project root in project scope and $HOME in user scope.
    if config_root:
        root = Path(config_root)
    elif Path(dest).expanduser().resolve() == (Path.home() / ".agents").resolve():
        root = Path.home() / ".claude"
    else:
        root = Path(dest).parent / ".claude"

    # 1. Skills last mile. Publishing into `<scope>/skills/` only helps if the
    #    agent reads that dir; without this link it never does.
    shared_skills = Path(dest) / "skills"
    if not shared_skills.is_dir():
        if logger:
            logger.info("no skills to link (%s absent)", shared_skills)
    elif dry_run:
        if logger:
            logger.info("would link skills: %s -> %s", shared_skills, root / "skills")
    else:
        result = _skills.sync_path(shared_skills, root / "skills", prefer_symlink=True)
        if not result.success:
            if logger:
                logger.warning("skills not linked: %s", result.message)
        else:
            if logger:
                logger.info("skills (%s): %s", result.mode, result.message)
            if result.mode == "copy" and logger:
                logger.warning(
                    "skills were COPIED, not symlinked (no symlink support here): "
                    "the copy is a point-in-time snapshot and goes stale when overlay "
                    "skills change -- re-run `dotagents init` to refresh it"
                )

    # 2. Hooks. In a project, write `settings.local.json` -- the gitignored
    # personal file. `settings.json` there is checked into source control, and
    # these hooks carry machine-specific paths that must never be committed.
    is_user_scope = root == (Path.home() / ".claude")
    settings_path = root / (
        "settings.json" if is_user_scope else "settings.local.json"
    )
    settings = _hooks.load_settings(settings_path)
    hooks = settings.get("hooks")
    if not isinstance(hooks, dict):
        hooks = {}
    changed = False

    # Legacy lowercase key from the precursor -- fold it in, then drop it.
    legacy = hooks.pop("session_start", None)
    if legacy is not None:
        changed = True

    # Two independent handlers per event: bash-syntax (works with Git Bash on
    # Windows and on every POSIX host) and a PowerShell-native equivalent
    # (works on Windows without Git Bash, where hooks.md's documented default
    # silently routes the bash-syntax command through PowerShell instead --
    # a hard parse error, verified directly). Both fire unconditionally every
    # session (hooks.md: every handler in a matched group runs); the one
    # whose interpreter is absent on this machine fails harmlessly, the other
    # carries the real effect. Chained `merge_hook` calls, each keyed by its
    # own `status_message` so they merge/refresh independently and never
    # collide with each other's identity.
    session_start, ss_changed_1 = _hooks.merge_hook(
        hooks.get("SessionStart", legacy),
        self.SESSION_START_COMMAND,
        status_message="Loading agent context",
    )
    session_start, ss_changed_2 = _hooks.merge_hook(
        session_start,
        self.SESSION_START_COMMAND_POWERSHELL,
        status_message="Loading agent context (PowerShell)",
        shell="powershell",
    )
    hooks["SessionStart"] = session_start
    ss_changed = ss_changed_1 or ss_changed_2

    cwd_changed, cc_changed_1 = _hooks.merge_hook(
        hooks.get("CwdChanged"),
        self.CWD_CHANGED_COMMAND,
        status_message="Checking for AGENTS.md",
    )
    cwd_changed, cc_changed_2 = _hooks.merge_hook(
        cwd_changed,
        self.CWD_CHANGED_COMMAND_POWERSHELL,
        status_message="Checking for AGENTS.md (PowerShell)",
        shell="powershell",
    )
    hooks["CwdChanged"] = cwd_changed
    cc_changed = cc_changed_1 or cc_changed_2

    pt_changed = False
    if os.name == "nt":
        pt_changed = self._wire_powershell_pretooluse(hooks)

    if not (changed or ss_changed or cc_changed or pt_changed):
        if logger:
            logger.info("hooks already wired: %s", settings_path)
        return

    settings["hooks"] = hooks
    if dry_run:
        if logger:
            logger.info("would wire SessionStart + CwdChanged hooks: %s", settings_path)
        return
    _hooks.write_settings(settings_path, settings)
    if logger:
        logger.info(
            "wired SessionStart + CwdChanged%s hooks: %s",
            " + PreToolUse" if pt_changed else "",
            settings_path,
        )

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, merge_claude_md, timestamped_backup_root

    backup_root = timestamped_backup_root(dest) if force else None

    branch = merge_block(
        dest / "AGENTS.md",
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: AGENTS.md", branch)

    claude_md_src = src / "CLAUDE.md"
    if claude_md_src.exists():
        branch = merge_claude_md(
            dest / "CLAUDE.md",
            claude_md_src.read_text(encoding="utf-8"),
            force=force, dry_run=dry_run, backup_root=backup_root,
        )
        if logger: logger.info("%s: CLAUDE.md", branch)

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
382
383
384
385
386
387
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / "CONTEXT.md"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

CodexAgent

Bases: Agent

ENV_BLOCK_BEGIN = '# dotagents:begin' class-attribute instance-attribute

ENV_BLOCK_END = '# dotagents:end' class-attribute instance-attribute

ENV_BLOCK_SKIP = frozenset({'PATH'}) class-attribute instance-attribute

PRETOOLUSE_HOOK_SCRIPT = 'pretooluse_codex_env.py' class-attribute instance-attribute

SESSION_START_COMMAND = 'PATH=".agents/bin:$HOME/.agents/bin:$PATH" dotagents context' class-attribute instance-attribute

context_files = ['AGENTS.md'] class-attribute instance-attribute

detect_env_vars = ['CODEX_HOME', 'CODEX_SANDBOX'] class-attribute instance-attribute

harness_id = 'codex' class-attribute instance-attribute

harness_loads = ['AGENTS.md'] class-attribute instance-attribute

model_source_vars = ['OPENAI_MODEL'] class-attribute instance-attribute

name = 'codex' class-attribute instance-attribute

vendor = 'openai' class-attribute instance-attribute

detect_env(environ)

Source code in src/dotagents/_agents.py
582
583
584
585
586
def detect_env(self, environ: "dict[str, str]") -> bool:
    # Exact markers plus any CODEX_SANDBOX_* variant (prefix match).
    if any(var in environ for var in self.detect_env_vars):
        return True
    return any(k.startswith("CODEX_SANDBOX") for k in environ)

wire_hooks(dest, *, dry_run, logger, config_root=None)

Merge SessionStart + PreToolUse into <codex-home>/hooks.json, and deploy the PreToolUse env-loader script alongside it.

Source code in src/dotagents/_agents.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def wire_hooks(
    self, dest: Path, *, dry_run: bool, logger, config_root: "Optional[Path]" = None
) -> None:
    """Merge SessionStart + PreToolUse into `<codex-home>/hooks.json`, and
    deploy the PreToolUse env-loader script alongside it."""
    from dotagents import _hooks

    root = self._config_root(config_root)

    script_changed = self._deploy_pretooluse_script(root, dry_run=dry_run, logger=logger)

    hooks_path = root / "hooks.json"
    data = _hooks.load_settings(hooks_path)
    hooks = data.get("hooks")
    if not isinstance(hooks, dict):
        hooks = {}

    session_start, ss_changed = _hooks.merge_hook(
        hooks.get("SessionStart"),
        self.SESSION_START_COMMAND,
        status_message="Loading agent context",
    )
    hooks["SessionStart"] = session_start

    # Absolute path, quoted for a possible space (e.g. under a Windows
    # %USERPROFILE% containing one). Not `$HOME`-relative like the Bash
    # SessionStart commands: those are portable shell snippets meant to
    # read the same on any machine, but this hooks.json is itself
    # machine-local config generated fresh by THIS `wire_hooks` call, on
    # the machine it will run on -- there is no portability requirement.
    #
    # `commandWindows` uses `python`, not `python3`: on Windows `python3`
    # is commonly a Microsoft Store app-execution-alias stub that can
    # silently no-op (this session's own dev box has exactly that --
    # `python3` resolves to the Store alias, `python` to the real
    # interpreter). Codex's docs only ever show `python3`, presumably
    # written for POSIX hosts; `commandWindows` is the documented
    # Windows-only override, same mechanism as Claude's dual-shell hooks.
    script_path = (root / "hooks" / self.PRETOOLUSE_HOOK_SCRIPT).resolve()
    pretooluse_command = 'python3 "%s"' % script_path.as_posix()
    pretooluse_command_windows = 'python "%s"' % str(script_path)
    pretooluse, pt_changed = _hooks.merge_hook(
        hooks.get("PreToolUse"),
        pretooluse_command,
        matcher="Bash",
        status_message="Loading agent env",
        command_windows=pretooluse_command_windows,
    )
    hooks["PreToolUse"] = pretooluse

    if not (ss_changed or pt_changed or script_changed):
        if logger:
            logger.info("hooks already wired: %s", hooks_path)
        return

    data["hooks"] = hooks
    if dry_run:
        if logger:
            logger.info("would wire SessionStart + PreToolUse hooks: %s", hooks_path)
        return
    _hooks.write_settings(hooks_path, data)
    if logger:
        logger.info("wired SessionStart + PreToolUse hooks: %s", hooks_path)

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
588
589
590
591
592
593
594
595
596
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, timestamped_backup_root
    backup_root = timestamped_backup_root(dest) if force else None
    branch = merge_block(
        dest / "AGENTS.md",
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: AGENTS.md (Codex)", branch)

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
818
819
820
821
822
823
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / "AGENTS.md"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

write_env_block(env, *, dry_run, logger, config_root=None)

Write env into a managed [shell_environment_policy] block in config.toml, so Codex injects those vars into every subprocess.

Source code in src/dotagents/_agents.py
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
723
724
725
726
727
def write_env_block(
    self,
    env: "dict[str, str]",
    *,
    dry_run: bool,
    logger,
    config_root: "Optional[Path]" = None,
) -> None:
    """Write `env` into a managed `[shell_environment_policy]` block in
    `config.toml`, so Codex injects those vars into every subprocess."""
    from dotagents._merge import merge_block

    env = {k: v for k, v in env.items() if k not in self.ENV_BLOCK_SKIP}
    if not env:
        if logger:
            logger.info("no env vars to write for codex")
        return

    root = self._config_root(config_root)
    lines = [
        self.ENV_BLOCK_BEGIN,
        "# Managed by dotagents -- edits inside this block are overwritten by",
        "# `dotagents init`. Values are a snapshot: re-run init after changing",
        "# your env layers. Add your own settings OUTSIDE the markers.",
        "[shell_environment_policy]",
        "set = {%s}"
        % ", ".join(
            '%s = "%s"' % (key, self._toml_escape(env[key])) for key in sorted(env)
        ),
        self.ENV_BLOCK_END,
    ]
    block = "\n".join(lines) + "\n"

    config_path = root / "config.toml"
    if not dry_run:
        config_path.parent.mkdir(parents=True, exist_ok=True)
    branch = merge_block(
        config_path,
        block,
        dry_run=dry_run,
        begin_marker=self.ENV_BLOCK_BEGIN,
        end_marker=self.ENV_BLOCK_END,
        append=True,
    )
    if logger:
        verb = "would write" if dry_run else branch
        logger.info("%s: %s (%d vars)", verb, config_path, len(env))

CopilotAgent

Bases: Agent

context_files = ['.github/copilot-instructions.md'] class-attribute instance-attribute

detect_env_vars = [] class-attribute instance-attribute

harness_id = 'copilot' class-attribute instance-attribute

harness_loads = ['.github/copilot-instructions.md'] class-attribute instance-attribute

model_source_vars = ['COPILOT_MODEL'] class-attribute instance-attribute

name = 'copilot' class-attribute instance-attribute

vendor = 'github' class-attribute instance-attribute

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
871
872
873
874
875
876
877
878
879
880
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, timestamped_backup_root
    backup_root = timestamped_backup_root(dest) if force else None
    target = dest / ".github" / "copilot-instructions.md"
    branch = merge_block(
        target,
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: %s", branch, target.relative_to(dest))

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
882
883
884
885
886
887
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / ".github" / "copilot-instructions.md"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

CursorAgent

Bases: Agent

context_files = ['.cursorrules', '.cursor/rules/'] class-attribute instance-attribute

detect_env_vars = ['CURSOR_AGENT'] class-attribute instance-attribute

harness_id = 'cursor' class-attribute instance-attribute

harness_loads = ['.cursorrules', '.cursor/rules/'] class-attribute instance-attribute

model_source_vars = ['CURSOR_DEFAULT_MODEL'] class-attribute instance-attribute

name = 'cursor' class-attribute instance-attribute

vendor = 'cursor' class-attribute instance-attribute

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
839
840
841
842
843
844
845
846
847
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, timestamped_backup_root
    backup_root = timestamped_backup_root(dest) if force else None
    branch = merge_block(
        dest / ".cursorrules",
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: .cursorrules", branch)

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
849
850
851
852
853
854
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / ".cursorrules"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

GeminiAgent

Bases: Agent

context_files = ['GEMINI.md'] class-attribute instance-attribute

detect_env_vars = ['GEMINI_CLI'] class-attribute instance-attribute

harness_id = 'gemini-cli' class-attribute instance-attribute

harness_loads = ['GEMINI.md'] class-attribute instance-attribute

model_source_vars = ['GEMINI_MODEL'] class-attribute instance-attribute

name = 'gemini' class-attribute instance-attribute

vendor = 'google' class-attribute instance-attribute

write_base_config(dest, src, base_agents_text, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
402
403
404
405
406
407
408
409
410
def write_base_config(self, dest: Path, src: Path, base_agents_text: str, *, force: bool, dry_run: bool, logger) -> None:
    from dotagents._merge import merge_block, timestamped_backup_root
    backup_root = timestamped_backup_root(dest) if force else None
    branch = merge_block(
        dest / "GEMINI.md",
        base_agents_text,
        force=force, dry_run=dry_run, backup_root=backup_root,
    )
    if logger: logger.info("%s: GEMINI.md", branch)

write_context(dest, effective_context, *, force, dry_run, logger)

Source code in src/dotagents/_agents.py
412
413
414
415
416
417
def write_context(self, dest: Path, effective_context: str, *, force: bool, dry_run: bool, logger) -> None:
    target = dest / "GEMINI.md"
    if not dry_run:
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(effective_context, encoding="utf-8")
    if logger: logger.info("wrote context to %s", target)

get_agent(name)

Source code in src/dotagents/_agents.py
900
901
902
def get_agent(name: str) -> Optional[Agent]:
    cls = _REGISTRY.get(name)
    return cls() if cls else None

get_all_agents()

Source code in src/dotagents/_agents.py
904
905
def get_all_agents() -> list[Agent]:
    return [cls() for cls in _REGISTRY.values()]

resolve_active_agent(environ, explicit=None, root=None)

Resolve the active agent by precedence (plan 00).

Precedence: explicit (--agents) > $AGENTS_HARNESS (registry name or harness_id) > env-var detection (detect_env) > config-file detection (detect(root)) > default (claude).

root is where config-file detect() looks (default: cwd).

Source code in src/dotagents/_agents.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
def resolve_active_agent(
    environ: dict[str, str],
    explicit: Optional[str] = None,
    root: Optional[Path] = None,
) -> Agent:
    """Resolve the active agent by precedence (plan 00).

    Precedence: explicit (--agents) > $AGENTS_HARNESS (registry name or
    harness_id) > env-var detection (detect_env) > config-file detection
    (detect(root)) > default (claude).

    ``root`` is where config-file detect() looks (default: cwd).
    """
    if explicit and explicit in _REGISTRY:
        return _REGISTRY[explicit]()

    stamped = environ.get("AGENTS_HARNESS")
    if stamped:
        alias = _harness_alias(stamped)
        if alias:
            return _REGISTRY[alias]()

    for name, cls in _REGISTRY.items():
        agent = cls()
        if agent.detect_env(environ):
            return agent

    # Config-file fallback: which agent's config is present in the tree?
    detect_root = root if root is not None else Path.cwd()
    for name, cls in _REGISTRY.items():
        agent = cls()
        try:
            if agent.detect(detect_root):
                return agent
        except OSError:
            pass

    return ClaudeAgent()

stamp_identity(environ, explicit=None, root=None)

Return the standardized AGENTS_* / AGENT identity vars (plan 08).

Emits AGENTS_HARNESS (the harness_id, e.g. claude-code -- NOT the short name), AGENTS_VENDOR, AGENT (= AGENTS_HARNESS, aligning with the emerging ecosystem marker used by Goose/Amp; agentsmd/agents.md#136), and, when derivable, AGENTS_MODEL (from the adapter's vendor model var) and AGENTS_AGENT (a named persona, from $AGENTS_AGENT if already set).

Never emits a var it cannot source (no empty AGENTS_MODEL=). Does NOT clobber a value already set in environ -- an explicit user/harness value wins. The deliberate curated mapping replaces the precursor's blanket CLAUDE_*->AGENTS_* rewrite (no AGENTS_CODE_SESSION_ID junk).

Source code in src/dotagents/_agents.py
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
def stamp_identity(
    environ: dict[str, str],
    explicit: Optional[str] = None,
    root: Optional[Path] = None,
) -> dict[str, str]:
    """Return the standardized ``AGENTS_*`` / ``AGENT`` identity vars (plan 08).

    Emits ``AGENTS_HARNESS`` (the harness_id, e.g. ``claude-code`` -- NOT the
    short name), ``AGENTS_VENDOR``, ``AGENT`` (= AGENTS_HARNESS, aligning with
    the emerging ecosystem marker used by Goose/Amp; agentsmd/agents.md#136),
    and, when derivable, ``AGENTS_MODEL`` (from the adapter's vendor model var)
    and ``AGENTS_AGENT`` (a named persona, from $AGENTS_AGENT if already set).

    Never emits a var it cannot source (no empty ``AGENTS_MODEL=``). Does NOT
    clobber a value already set in ``environ`` -- an explicit user/harness value
    wins. The deliberate curated mapping replaces the precursor's blanket
    ``CLAUDE_*``->``AGENTS_*`` rewrite (no ``AGENTS_CODE_SESSION_ID`` junk).
    """
    active = resolve_active_agent(environ, explicit=explicit, root=root)

    identity: dict[str, str] = {}

    def _set(key: str, value: "Optional[str]") -> None:
        if value and not environ.get(key):
            identity[key] = value

    _set("AGENTS_HARNESS", active.harness_id or active.name)
    _set("AGENTS_VENDOR", active.vendor)
    _set("AGENT", active.harness_id or active.name)
    _set("AGENTS_MODEL", active.resolve_model(environ))
    # A named persona (~/.agents/<agent>.md); only surface one already selected.
    _set("AGENTS_AGENT", environ.get("AGENTS_AGENT"))

    return identity