adk-coder 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. adk_coder-0.1.0/LICENSE +201 -0
  2. adk_coder-0.1.0/PKG-INFO +112 -0
  3. adk_coder-0.1.0/README.md +84 -0
  4. adk_coder-0.1.0/adk_coder/__init__.py +3 -0
  5. adk_coder-0.1.0/adk_coder/agent_factory.py +184 -0
  6. adk_coder-0.1.0/adk_coder/api_key.py +80 -0
  7. adk_coder-0.1.0/adk_coder/cli/__init__.py +1 -0
  8. adk_coder-0.1.0/adk_coder/cli/config.py +53 -0
  9. adk_coder-0.1.0/adk_coder/cli/sessions.py +114 -0
  10. adk_coder-0.1.0/adk_coder/confirmation.py +81 -0
  11. adk_coder-0.1.0/adk_coder/constants.py +11 -0
  12. adk_coder-0.1.0/adk_coder/main.py +332 -0
  13. adk_coder-0.1.0/adk_coder/models.py +48 -0
  14. adk_coder-0.1.0/adk_coder/policy.py +253 -0
  15. adk_coder-0.1.0/adk_coder/projects.py +90 -0
  16. adk_coder-0.1.0/adk_coder/retry_gemini.py +108 -0
  17. adk_coder-0.1.0/adk_coder/settings.py +79 -0
  18. adk_coder-0.1.0/adk_coder/skills/__init__.py +3 -0
  19. adk_coder-0.1.0/adk_coder/skills/_skills.py +222 -0
  20. adk_coder-0.1.0/adk_coder/skills/builtin/__init__.py +0 -0
  21. adk_coder-0.1.0/adk_coder/skills/builtin/feature-dev/SKILL.md +124 -0
  22. adk_coder-0.1.0/adk_coder/skills/builtin/feature-dev/agents/code-architect.md +33 -0
  23. adk_coder-0.1.0/adk_coder/skills/builtin/feature-dev/agents/code-explorer.md +50 -0
  24. adk_coder-0.1.0/adk_coder/skills/builtin/feature-dev/agents/code-reviewer.md +40 -0
  25. adk_coder-0.1.0/adk_coder/skills/builtin/skill-creator/SKILL.md +382 -0
  26. adk_coder-0.1.0/adk_coder/skills/builtin/skill-creator/scripts/init_skill.py +214 -0
  27. adk_coder-0.1.0/adk_coder/skills/builtin/skill-creator/scripts/package_skill.py +72 -0
  28. adk_coder-0.1.0/adk_coder/skills/builtin/skill-creator/scripts/validate_skill.py +120 -0
  29. adk_coder-0.1.0/adk_coder/status.py +89 -0
  30. adk_coder-0.1.0/adk_coder/summarize.py +165 -0
  31. adk_coder-0.1.0/adk_coder/tools.py +584 -0
  32. adk_coder-0.1.0/adk_coder/tui.py +1116 -0
  33. adk_coder-0.1.0/adk_coder.egg-info/PKG-INFO +112 -0
  34. adk_coder-0.1.0/adk_coder.egg-info/SOURCES.txt +42 -0
  35. adk_coder-0.1.0/adk_coder.egg-info/dependency_links.txt +1 -0
  36. adk_coder-0.1.0/adk_coder.egg-info/entry_points.txt +2 -0
  37. adk_coder-0.1.0/adk_coder.egg-info/requires.txt +17 -0
  38. adk_coder-0.1.0/adk_coder.egg-info/top_level.txt +1 -0
  39. adk_coder-0.1.0/pyproject.toml +57 -0
  40. adk_coder-0.1.0/setup.cfg +4 -0
  41. adk_coder-0.1.0/tests/test_api_key.py +145 -0
  42. adk_coder-0.1.0/tests/test_policy.py +196 -0
  43. adk_coder-0.1.0/tests/test_settings.py +105 -0
  44. adk_coder-0.1.0/tests/test_tools.py +105 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: adk_coder
3
+ Version: 0.1.0
4
+ Summary: Project short description.
5
+ Author-email: Allen Porter <allen.porter@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Source, https://github.com/allenporter/adk-coder
8
+ Requires-Python: >=3.14
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: python-dotenv>=1.0.0
12
+ Requires-Dist: google-adk>=1.25.1
13
+ Requires-Dist: click>=8.1.7
14
+ Requires-Dist: pyyaml>=6.0
15
+ Requires-Dist: rich>=13.7.0
16
+ Requires-Dist: textual>=0.47.1
17
+ Requires-Dist: portalocker>=2.8.2
18
+ Requires-Dist: psutil>=5.9.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=8.4.2; extra == "dev"
21
+ Requires-Dist: pytest-cov>=6.0.0; extra == "dev"
22
+ Requires-Dist: ty>=0.0.18; extra == "dev"
23
+ Requires-Dist: ruff>=0.8.1; extra == "dev"
24
+ Requires-Dist: pre-commit>=4.0.1; extra == "dev"
25
+ Requires-Dist: coverage>=7.13.4; extra == "dev"
26
+ Requires-Dist: pytest-asyncio>=1.3.0; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # adk-coder
30
+
31
+ `adk-coder` is a powerful, agentic development tool built on the [Google ADK (Agent Development Kit)](https://github.com/google/adk-python). It provides a terminal-based interface (TUI) for interacting with Gemini models that have direct access to your local filesystem and shell.
32
+
33
+ ## 🌟 Inspiration
34
+
35
+ This project is inspired by several leading agentic coding tools:
36
+ - **[gemini-cli](https://github.com/google/gemini-cli)**: For its clean architecture and focus on Google's Gemini models.
37
+ - **Claude Code**: For its robust, phase-based orchestration and multi-agent patterns.
38
+ - **Nano-Claw**: For its "Integrity-First" approach to code modification and file handling.
39
+
40
+ ## 🚀 Key Features
41
+
42
+ - **Interactive TUI**: A rich, responsive chat interface built with [Textual](https://textual.textualize.io/).
43
+ - **Filesystem Tools**: Built-in capabilities to `ls`, `cat`, `grep`, `write`, and `edit` files.
44
+ - **Shell Integration**: Execute bash commands with user-approved security guards.
45
+ - **Skill System**: Extensible via Markdown-based "Skills" that define custom instructions and tool usage. Includes high-level orchestration like `feature-dev` for guided software engineering.
46
+ - **Multi-Agent Orchestration**: Specialized sub-agents (`code-explorer`, `code-architect`, `code-reviewer`) can be launched to handle specific phases of a task without polluting the main conversation context.
47
+ - **Persistent Sessions**: Automatically remembers project context and chat history using SQLite.
48
+ - **Security First**: Granular permission modes (`ask`, `auto`, `plan`) to control tool execution.
49
+ - **Project Awareness**: Automatically maps workspace roots to unique IDs for isolated session management.
50
+
51
+ ## 🛠️ How It Works
52
+
53
+ `adk-coder` leverages Google ADK to orchestrate the agentic loop.
54
+
55
+ 1. **Orchestration**: Uses the `Runner` and `LlmAgent` from ADK to manage the conversation flow and tool execution.
56
+ 2. **Policy Engine**: A custom security plugin intercepts every tool call, checking it against a policy (e.g., read-only tools are allowed, while `bash` or `write_file` require a UI confirmation).
57
+ 3. **Context Management**: It detects the project root (via `.git`, `pyproject.toml`, etc.) and manages history in a global SQLite database at `~/.adk/`.
58
+
59
+ ## 🚥 Getting Started
60
+
61
+ ### Prerequisites
62
+
63
+ - Python 3.14+
64
+ - A Gemini API Key from [Google AI Studio](https://aistudio.google.com/apikey).
65
+
66
+ ### Installation
67
+
68
+ ```bash
69
+ # Clone the repository
70
+ git clone https://github.com/your-repo/adk-coder.git
71
+ cd adk-coder
72
+
73
+ # Install dependencies (using uv is recommended)
74
+ uv sync
75
+ ```
76
+
77
+ ### Configuration
78
+
79
+ Set your API key in a `.env` file or export it:
80
+
81
+ ```bash
82
+ export GOOGLE_API_KEY="your_api_key_here"
83
+ ```
84
+
85
+ ### Usage
86
+
87
+ Launch the interactive TUI:
88
+ ```bash
89
+ adk-coder
90
+ ```
91
+
92
+ Execute a one-off task:
93
+ ```bash
94
+ adk-coder chat "Review the current directory and list all python files" --print
95
+ ```
96
+
97
+ Manage global settings:
98
+ ```bash
99
+ adk-coder config set default_model gemini-3-flash-preview
100
+ ```
101
+
102
+ ## 🏗️ Development
103
+
104
+ This project uses a "Scripts to Rule Them All" pattern for development tasks:
105
+
106
+ - `./script/bootstrap`: Install dependencies and set up the environment.
107
+ - `./script/test`: Run the test suite (pytest).
108
+ - `./script/lint`: Run linting checks (ruff).
109
+
110
+ ## 📄 License
111
+
112
+ This project is licensed under the Apache 2.0 License.
@@ -0,0 +1,84 @@
1
+ # adk-coder
2
+
3
+ `adk-coder` is a powerful, agentic development tool built on the [Google ADK (Agent Development Kit)](https://github.com/google/adk-python). It provides a terminal-based interface (TUI) for interacting with Gemini models that have direct access to your local filesystem and shell.
4
+
5
+ ## 🌟 Inspiration
6
+
7
+ This project is inspired by several leading agentic coding tools:
8
+ - **[gemini-cli](https://github.com/google/gemini-cli)**: For its clean architecture and focus on Google's Gemini models.
9
+ - **Claude Code**: For its robust, phase-based orchestration and multi-agent patterns.
10
+ - **Nano-Claw**: For its "Integrity-First" approach to code modification and file handling.
11
+
12
+ ## 🚀 Key Features
13
+
14
+ - **Interactive TUI**: A rich, responsive chat interface built with [Textual](https://textual.textualize.io/).
15
+ - **Filesystem Tools**: Built-in capabilities to `ls`, `cat`, `grep`, `write`, and `edit` files.
16
+ - **Shell Integration**: Execute bash commands with user-approved security guards.
17
+ - **Skill System**: Extensible via Markdown-based "Skills" that define custom instructions and tool usage. Includes high-level orchestration like `feature-dev` for guided software engineering.
18
+ - **Multi-Agent Orchestration**: Specialized sub-agents (`code-explorer`, `code-architect`, `code-reviewer`) can be launched to handle specific phases of a task without polluting the main conversation context.
19
+ - **Persistent Sessions**: Automatically remembers project context and chat history using SQLite.
20
+ - **Security First**: Granular permission modes (`ask`, `auto`, `plan`) to control tool execution.
21
+ - **Project Awareness**: Automatically maps workspace roots to unique IDs for isolated session management.
22
+
23
+ ## 🛠️ How It Works
24
+
25
+ `adk-coder` leverages Google ADK to orchestrate the agentic loop.
26
+
27
+ 1. **Orchestration**: Uses the `Runner` and `LlmAgent` from ADK to manage the conversation flow and tool execution.
28
+ 2. **Policy Engine**: A custom security plugin intercepts every tool call, checking it against a policy (e.g., read-only tools are allowed, while `bash` or `write_file` require a UI confirmation).
29
+ 3. **Context Management**: It detects the project root (via `.git`, `pyproject.toml`, etc.) and manages history in a global SQLite database at `~/.adk/`.
30
+
31
+ ## 🚥 Getting Started
32
+
33
+ ### Prerequisites
34
+
35
+ - Python 3.14+
36
+ - A Gemini API Key from [Google AI Studio](https://aistudio.google.com/apikey).
37
+
38
+ ### Installation
39
+
40
+ ```bash
41
+ # Clone the repository
42
+ git clone https://github.com/your-repo/adk-coder.git
43
+ cd adk-coder
44
+
45
+ # Install dependencies (using uv is recommended)
46
+ uv sync
47
+ ```
48
+
49
+ ### Configuration
50
+
51
+ Set your API key in a `.env` file or export it:
52
+
53
+ ```bash
54
+ export GOOGLE_API_KEY="your_api_key_here"
55
+ ```
56
+
57
+ ### Usage
58
+
59
+ Launch the interactive TUI:
60
+ ```bash
61
+ adk-coder
62
+ ```
63
+
64
+ Execute a one-off task:
65
+ ```bash
66
+ adk-coder chat "Review the current directory and list all python files" --print
67
+ ```
68
+
69
+ Manage global settings:
70
+ ```bash
71
+ adk-coder config set default_model gemini-3-flash-preview
72
+ ```
73
+
74
+ ## 🏗️ Development
75
+
76
+ This project uses a "Scripts to Rule Them All" pattern for development tasks:
77
+
78
+ - `./script/bootstrap`: Install dependencies and set up the environment.
79
+ - `./script/test`: Run the test suite (pytest).
80
+ - `./script/lint`: Run linting checks (ruff).
81
+
82
+ ## 📄 License
83
+
84
+ This project is licensed under the Apache 2.0 License.
@@ -0,0 +1,3 @@
1
+ """
2
+ .. include:: ../README.md
3
+ """
@@ -0,0 +1,184 @@
1
+ import os
2
+ import sys
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import Any, Optional
6
+
7
+ import click
8
+
9
+ from adk_coder.api_key import load_api_key, load_env_file
10
+ from adk_coder.projects import find_project_root, get_session_db_path
11
+ from adk_coder.settings import load_settings
12
+ from adk_coder.constants import APP_NAME, DEFAULT_MODEL
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ SUPERVISOR_INSTRUCTION = """\
18
+ You are an expert AI software engineer and the primary supervisor for this adk-coder session.
19
+ Your goal is to help the user manage, explore, and modify their codebase efficiently and safely.
20
+
21
+ Guidelines:
22
+ - **Think First**: Use your internal reasoning (BuiltInPlanner) to plan your actions.
23
+ - **Use Specialized Skills**: For complex tasks like feature development, architecture changes, or deep exploration, prefer using the relevant 'Skill' (e.g., `feature-dev`).
24
+ - **Safety**: Always ask for confirmation before executing potentially destructive shell commands (via `bash`) or making large-scale file edits.
25
+ - **Precision**: When editing files, ensure you have read the relevant sections first to maintain project style and logic.
26
+ """
27
+
28
+ _NO_KEY_MESSAGE = """\
29
+ Error: No Gemini API key found.
30
+
31
+ To get started:
32
+ 1. Get a free API key from https://aistudio.google.com/apikey
33
+ 2. Create a .env file in your project directory with:
34
+
35
+ GOOGLE_API_KEY="YOUR_API_KEY"
36
+ GOOGLE_GENAI_USE_VERTEXAI=FALSE
37
+
38
+ adk-coder will load this file automatically on startup.
39
+
40
+ See: https://google.github.io/adk-docs/agents/models/google-gemini/#google-ai-studio
41
+ """
42
+
43
+
44
+ def _resolve_api_key() -> Optional[str]:
45
+ """Load .env then return the API key, or None."""
46
+ load_env_file(workspace_dir=os.getcwd())
47
+ return load_api_key()
48
+
49
+
50
+ def build_adk_agent(
51
+ model: str | None = None,
52
+ instruction: str | None = None,
53
+ tool_names: list[str] | None = None,
54
+ include_skills: bool = True,
55
+ agent_name: str = "adk_coder_agent",
56
+ ) -> Any:
57
+ """Builds and returns an LlmAgent for adk-coder."""
58
+ from adk_coder.skills import discover_skills
59
+ from adk_coder.tools import get_essential_tools
60
+ from adk_coder.retry_gemini import AdkRetryGemini
61
+ from google.adk.agents.llm_agent import LlmAgent
62
+ from google.adk.tools.skill_toolset import SkillToolset
63
+ from google.genai import types
64
+
65
+ # Ensure agent_name is a valid identifier (alphanumeric and underscores only)
66
+ agent_name = agent_name.replace("-", "_")
67
+
68
+ project_root = find_project_root()
69
+
70
+ # Defer loading of model settings
71
+ if model is None:
72
+ settings = load_settings(project_root)
73
+ model = settings.get("default_model") or DEFAULT_MODEL
74
+
75
+ # Load project-specific instructions if available
76
+ project_instructions = []
77
+ instruction_markers = ["AGENTS.md", "GEMINI.md", "CLAUDE.md"]
78
+ for marker in instruction_markers:
79
+ marker_path = project_root / marker
80
+ if marker_path.exists():
81
+ try:
82
+ project_instructions.append(
83
+ f"\n--- From {marker} ---\n"
84
+ + marker_path.read_text(encoding="utf-8")
85
+ )
86
+ except Exception as e:
87
+ logger.warning("Failed to read %s: %s", marker, e)
88
+
89
+ final_instruction = instruction or SUPERVISOR_INSTRUCTION
90
+ if project_instructions:
91
+ final_instruction += "\n\n## Project-Specific Instructions\n" + "\n".join(
92
+ project_instructions
93
+ )
94
+
95
+ retry_options = types.HttpRetryOptions(attempts=1, http_status_codes=[])
96
+ llm_model = AdkRetryGemini(model=model, retry_options=retry_options)
97
+
98
+ # Collect and filter tools
99
+ all_essential_tools = get_essential_tools()
100
+ if tool_names:
101
+ tools = [t for t in all_essential_tools if getattr(t, "name", "") in tool_names]
102
+ else:
103
+ tools = all_essential_tools
104
+
105
+ if include_skills:
106
+ skills = discover_skills(Path.cwd())
107
+ if skills:
108
+ tools.append(SkillToolset(skills))
109
+
110
+ # Construct the planner with thinking config
111
+ from google.adk.planners import BuiltInPlanner
112
+
113
+ planner = BuiltInPlanner(
114
+ thinking_config=types.ThinkingConfig(
115
+ include_thoughts=True,
116
+ thinking_budget=1024 if agent_name == "adk_coder_agent" else 512,
117
+ )
118
+ )
119
+
120
+ # Initialize the LlmAgent directly
121
+ return LlmAgent(
122
+ name=agent_name,
123
+ instruction=final_instruction,
124
+ tools=tools,
125
+ model=llm_model,
126
+ planner=planner,
127
+ )
128
+
129
+
130
+ def build_runner_or_exit(ctx: click.Context, model: str | None = None) -> Any:
131
+ """Resolve the API key and build a Runner, or print instructions and exit."""
132
+ # Defer loading of heavy SDK libraries
133
+ from adk_coder.policy import CustomPolicyEngine, SecurityPlugin, PermissionMode
134
+ from google.adk.apps.app import App, EventsCompactionConfig
135
+ from google.adk.runners import Runner
136
+ from google.adk.sessions.sqlite_session_service import SqliteSessionService
137
+
138
+ api_key = _resolve_api_key()
139
+ if not api_key:
140
+ click.echo(_NO_KEY_MESSAGE, err=True)
141
+ sys.exit(1)
142
+ # Set env var so google-genai client picks it up at init time
143
+ os.environ["GOOGLE_API_KEY"] = api_key
144
+ os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "FALSE")
145
+
146
+ # Create the agent lazily after api key setup
147
+ agent = build_adk_agent(model)
148
+
149
+ settings = load_settings(find_project_root())
150
+
151
+ # Navigate to get parent context params if needed
152
+ p_params = ctx.parent.params if ctx.parent else {}
153
+ mode_str = p_params.get("permission_mode")
154
+ if mode_str is None:
155
+ mode_str = settings.get("permission_mode", "ask")
156
+
157
+ permission_mode = PermissionMode(mode_str)
158
+
159
+ policy_engine = CustomPolicyEngine(mode=permission_mode)
160
+ security_plugin = SecurityPlugin(policy_engine=policy_engine)
161
+
162
+ # Configure session compaction to manage context growth.
163
+ compaction_config = EventsCompactionConfig(
164
+ compaction_interval=5, # Compact every 5 turns
165
+ overlap_size=1, # Keep 1 turn of overlap for continuity
166
+ token_threshold=50000, # Also compact if we hit 50k tokens
167
+ event_retention_size=10, # Keep at least 10 raw events
168
+ )
169
+
170
+ app = App(
171
+ name=APP_NAME,
172
+ root_agent=agent,
173
+ plugins=[security_plugin],
174
+ events_compaction_config=compaction_config,
175
+ )
176
+
177
+ db_path = str(get_session_db_path())
178
+ session_service = SqliteSessionService(db_path=db_path)
179
+
180
+ return Runner(
181
+ app=app,
182
+ session_service=session_service,
183
+ auto_create_session=True,
184
+ )
@@ -0,0 +1,80 @@
1
+ """API key loading, saving, and environment file support for adk-coder.
2
+
3
+ Priority order for API key resolution:
4
+ 1. GOOGLE_API_KEY environment variable
5
+ 2. GEMINI_API_KEY environment variable
6
+ 3. api_key field in ~/.adk/settings.json
7
+
8
+ This mirrors the approach used by gemini-cli, which reads GEMINI_API_KEY
9
+ from the environment or from OS keychain / ~/.gemini/ storage.
10
+ """
11
+
12
+ import os
13
+ from pathlib import Path
14
+
15
+ import dotenv
16
+
17
+ from adk_coder.settings import get_global_adk_dir, load_settings, save_settings
18
+
19
+ _ENV_VARS = ("GOOGLE_API_KEY", "GEMINI_API_KEY")
20
+ _SETTINGS_KEY = "api_key"
21
+
22
+
23
+ def load_api_key() -> str | None:
24
+ """Load the Gemini API key from environment variables or persisted settings.
25
+
26
+ Checks (in order):
27
+ 1. GOOGLE_API_KEY env var
28
+ 2. GEMINI_API_KEY env var
29
+ 3. api_key entry in ~/.adk/settings.json
30
+
31
+ Returns the key string, or None if no key is found.
32
+ """
33
+ for var in _ENV_VARS:
34
+ value = os.environ.get(var)
35
+ if value and value.strip():
36
+ return value.strip()
37
+
38
+ settings = load_settings()
39
+ stored: str | None = settings.get(_SETTINGS_KEY)
40
+ if stored and stored.strip():
41
+ return stored.strip()
42
+
43
+ return None
44
+
45
+
46
+ def save_api_key(api_key: str) -> None:
47
+ """Persist the given API key to ~/.adk/settings.json.
48
+
49
+ The key is stored under the ``api_key`` field in the settings dict.
50
+ """
51
+ settings = load_settings()
52
+ settings[_SETTINGS_KEY] = api_key.strip()
53
+ save_settings(settings)
54
+
55
+
56
+ def load_env_file(workspace_dir: str | None = None) -> None:
57
+ """Load environment variables from a .env file, if one is found.
58
+
59
+ Search order:
60
+ 1. <workspace_dir>/.adk/.env
61
+ 2. <workspace_dir>/.env
62
+ 3. ~/.adk/.env
63
+
64
+ Variables already set in the environment are not overwritten, matching
65
+ the behaviour of gemini-cli's ``loadEnvironment()``.
66
+ """
67
+ candidates: list[Path] = []
68
+
69
+ if workspace_dir:
70
+ workspace = Path(workspace_dir)
71
+ candidates.append(workspace / ".adk" / ".env")
72
+ candidates.append(workspace / ".env")
73
+
74
+ candidates.append(get_global_adk_dir() / ".env")
75
+
76
+ for candidate in candidates:
77
+ if candidate.is_file():
78
+ # override=False means existing env vars are not overwritten
79
+ dotenv.load_dotenv(candidate, override=False)
80
+ break
@@ -0,0 +1 @@
1
+ # CLI subcommands package