codetether 1.2.2__py3-none-any.whl

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 (66) hide show
  1. a2a_server/__init__.py +29 -0
  2. a2a_server/a2a_agent_card.py +365 -0
  3. a2a_server/a2a_errors.py +1133 -0
  4. a2a_server/a2a_executor.py +926 -0
  5. a2a_server/a2a_router.py +1033 -0
  6. a2a_server/a2a_types.py +344 -0
  7. a2a_server/agent_card.py +408 -0
  8. a2a_server/agents_server.py +271 -0
  9. a2a_server/auth_api.py +349 -0
  10. a2a_server/billing_api.py +638 -0
  11. a2a_server/billing_service.py +712 -0
  12. a2a_server/billing_webhooks.py +501 -0
  13. a2a_server/config.py +96 -0
  14. a2a_server/database.py +2165 -0
  15. a2a_server/email_inbound.py +398 -0
  16. a2a_server/email_notifications.py +486 -0
  17. a2a_server/enhanced_agents.py +919 -0
  18. a2a_server/enhanced_server.py +160 -0
  19. a2a_server/hosted_worker.py +1049 -0
  20. a2a_server/integrated_agents_server.py +347 -0
  21. a2a_server/keycloak_auth.py +750 -0
  22. a2a_server/livekit_bridge.py +439 -0
  23. a2a_server/marketing_tools.py +1364 -0
  24. a2a_server/mcp_client.py +196 -0
  25. a2a_server/mcp_http_server.py +2256 -0
  26. a2a_server/mcp_server.py +191 -0
  27. a2a_server/message_broker.py +725 -0
  28. a2a_server/mock_mcp.py +273 -0
  29. a2a_server/models.py +494 -0
  30. a2a_server/monitor_api.py +5904 -0
  31. a2a_server/opencode_bridge.py +1594 -0
  32. a2a_server/redis_task_manager.py +518 -0
  33. a2a_server/server.py +726 -0
  34. a2a_server/task_manager.py +668 -0
  35. a2a_server/task_queue.py +742 -0
  36. a2a_server/tenant_api.py +333 -0
  37. a2a_server/tenant_middleware.py +219 -0
  38. a2a_server/tenant_service.py +760 -0
  39. a2a_server/user_auth.py +721 -0
  40. a2a_server/vault_client.py +576 -0
  41. a2a_server/worker_sse.py +873 -0
  42. agent_worker/__init__.py +8 -0
  43. agent_worker/worker.py +4877 -0
  44. codetether/__init__.py +10 -0
  45. codetether/__main__.py +4 -0
  46. codetether/cli.py +112 -0
  47. codetether/worker_cli.py +57 -0
  48. codetether-1.2.2.dist-info/METADATA +570 -0
  49. codetether-1.2.2.dist-info/RECORD +66 -0
  50. codetether-1.2.2.dist-info/WHEEL +5 -0
  51. codetether-1.2.2.dist-info/entry_points.txt +4 -0
  52. codetether-1.2.2.dist-info/licenses/LICENSE +202 -0
  53. codetether-1.2.2.dist-info/top_level.txt +5 -0
  54. codetether_voice_agent/__init__.py +6 -0
  55. codetether_voice_agent/agent.py +445 -0
  56. codetether_voice_agent/codetether_mcp.py +345 -0
  57. codetether_voice_agent/config.py +16 -0
  58. codetether_voice_agent/functiongemma_caller.py +380 -0
  59. codetether_voice_agent/session_playback.py +247 -0
  60. codetether_voice_agent/tools/__init__.py +21 -0
  61. codetether_voice_agent/tools/definitions.py +135 -0
  62. codetether_voice_agent/tools/handlers.py +380 -0
  63. run_server.py +314 -0
  64. ui/monitor-tailwind.html +1790 -0
  65. ui/monitor.html +1775 -0
  66. ui/monitor.js +2662 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ a2a_server
2
+ agent_worker
3
+ codetether
4
+ codetether_voice_agent
5
+ run_server
@@ -0,0 +1,6 @@
1
+ __version__ = '0.1.0'
2
+
3
+ from .agent import VoiceAgent
4
+ from .config import settings
5
+
6
+ __all__ = ['VoiceAgent', 'settings']
@@ -0,0 +1,445 @@
1
+ """LiveKit Voice Agent with Gemini 3 Live API and CodeTether MCP Integration.
2
+
3
+ This module provides a voice-enabled AI agent that uses Google's Gemini 3 Live API
4
+ for real-time voice conversation and integrates with CodeTether MCP tools for
5
+ task management and agent communication.
6
+ """
7
+
8
+ import asyncio
9
+ import json
10
+ import logging
11
+ import os
12
+ import sys
13
+ import uuid
14
+ from typing import Any, Dict, List, Optional
15
+
16
+
17
+ def _validate_environment():
18
+ """Validate required environment variables are set.
19
+
20
+ Raises:
21
+ SystemExit: If required environment variables are missing.
22
+ """
23
+ required_vars = {
24
+ 'LIVEKIT_API_KEY': 'Required for LiveKit worker registration',
25
+ 'LIVEKIT_API_SECRET': 'Required for LiveKit worker registration',
26
+ }
27
+
28
+ # At least one Google credential is required
29
+ google_api_key = os.getenv('GOOGLE_API_KEY', '').strip()
30
+ google_creds_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS', '').strip()
31
+
32
+ missing = []
33
+ for var, description in required_vars.items():
34
+ value = os.getenv(var)
35
+ if not value or value.strip() == '':
36
+ missing.append(f' - {var}: {description}')
37
+
38
+ if not google_api_key and not google_creds_path:
39
+ missing.append(
40
+ ' - GOOGLE_API_KEY or GOOGLE_APPLICATION_CREDENTIALS: '
41
+ 'Required for Gemini Live API authentication'
42
+ )
43
+
44
+ if missing:
45
+ error_msg = (
46
+ 'ERROR: Missing required environment variables:\n'
47
+ + '\n'.join(missing)
48
+ + '\n\nPlease ensure these are set in your deployment configuration.'
49
+ )
50
+ print(error_msg, file=sys.stderr)
51
+ logging.error(error_msg)
52
+ sys.exit(1)
53
+
54
+ # Log successful validation
55
+ print(f'Environment validation passed:', file=sys.stderr)
56
+ print(f' - LIVEKIT_API_KEY: set', file=sys.stderr)
57
+ print(f' - LIVEKIT_API_SECRET: set', file=sys.stderr)
58
+ if google_api_key:
59
+ print(
60
+ f' - GOOGLE_API_KEY: set (length: {len(google_api_key)})',
61
+ file=sys.stderr,
62
+ )
63
+ if google_creds_path:
64
+ print(
65
+ f' - GOOGLE_APPLICATION_CREDENTIALS: {google_creds_path}',
66
+ file=sys.stderr,
67
+ )
68
+
69
+
70
+ # Validate environment before importing anything else
71
+ _validate_environment()
72
+
73
+ from livekit.agents import (
74
+ Agent,
75
+ AgentSession,
76
+ AutoSubscribe,
77
+ JobContext,
78
+ WorkerOptions,
79
+ cli,
80
+ llm,
81
+ )
82
+ from livekit.plugins import google
83
+
84
+ from codetether_mcp import CodeTetherMCP
85
+ from functiongemma_caller import FunctionGemmaCaller
86
+ from session_playback import SessionPlayback
87
+
88
+ logger = logging.getLogger(__name__)
89
+
90
+ VOICES: Dict[str, str] = {
91
+ 'puck': 'Puck',
92
+ 'charon': 'Charon',
93
+ 'kore': 'Kore',
94
+ 'fenrir': 'Fenrir',
95
+ 'aoede': 'Aoede',
96
+ }
97
+
98
+ DEFAULT_VOICE = 'puck'
99
+
100
+ SYSTEM_INSTRUCTIONS = """You are a helpful voice assistant powered by Gemini 3 Live API.
101
+
102
+ Your core capabilities:
103
+ 1. Voice Conversation - You can speak naturally with users in real-time
104
+ 2. Task Management - Create, list, get, and cancel tasks
105
+ 3. Session Playback - Play back historical conversation sessions
106
+ 4. Agent Communication - Send messages to other agents in the system
107
+ 5. Session Management - Retrieve and continue previous conversations
108
+
109
+ Available Tools:
110
+ - create_task: Create a new task with title, description, optional codebase_id and priority
111
+ - list_tasks: List tasks with optional status and codebase_id filters
112
+ - get_task: Get details of a specific task by ID
113
+ - cancel_task: Cancel an active task by ID
114
+ - get_session_history: Retrieve message history for a session
115
+ - playback_session: Play back a session verbatim or as summary
116
+ - discover_agents: List available agents in the system
117
+ - send_message: Send a message to a specific agent
118
+
119
+ Guidelines:
120
+ - Speak clearly and concisely in your responses
121
+ - Use tools proactively when users ask for task management or information
122
+ - Confirm tool results before proceeding with related actions
123
+ - Handle errors gracefully and explain issues clearly
124
+ - For session playback, offer both verbatim and summary options
125
+ - When agents are mentioned, provide helpful information about their capabilities
126
+
127
+ Remember to adapt your communication style to be natural for voice interaction."""
128
+
129
+
130
+ def format_history_for_context(history: List[Dict[str, Any]]) -> str:
131
+ """Format message history into a readable string for context.
132
+
133
+ Args:
134
+ history: List of message dictionaries with 'role' and 'content' keys.
135
+
136
+ Returns:
137
+ A formatted string representation of the conversation history.
138
+ """
139
+ if not history:
140
+ return 'No previous conversation history.'
141
+
142
+ formatted_parts = []
143
+ for message in history:
144
+ role = message.get('role', 'unknown')
145
+ content = message.get('content', '')
146
+
147
+ if not content:
148
+ continue
149
+
150
+ if role == 'user':
151
+ formatted_parts.append(f'User: {content}')
152
+ elif role in ('assistant', 'agent'):
153
+ formatted_parts.append(f'Agent: {content}')
154
+ else:
155
+ formatted_parts.append(f'{role.capitalize()}: {content}')
156
+
157
+ return '\n'.join(formatted_parts)
158
+
159
+
160
+ def create_tools(mcp_client: CodeTetherMCP) -> List[llm.FunctionTool]:
161
+ """Create FunctionTool objects for the voice agent.
162
+
163
+ Args:
164
+ mcp_client: The CodeTether MCP client for tool execution.
165
+
166
+ Returns:
167
+ List of FunctionTool objects.
168
+ """
169
+ tools = []
170
+
171
+ # List tasks tool
172
+ @llm.function_tool(
173
+ name='list_tasks',
174
+ description='List tasks in the CodeTether system. Use this to show the user what tasks exist.',
175
+ )
176
+ async def list_tasks(status: Optional[str] = None) -> str:
177
+ """List tasks with optional status filter."""
178
+ try:
179
+ logger.info(f'Executing list_tasks with status: {status}')
180
+ tasks = await mcp_client.list_tasks(status=status)
181
+ if not tasks:
182
+ return 'There are no tasks in the system.'
183
+ task_list = ', '.join(
184
+ [f"'{t.title}' ({t.status})" for t in tasks[:5]]
185
+ )
186
+ return f'Found {len(tasks)} tasks: {task_list}'
187
+ except Exception as e:
188
+ logger.error(f'list_tasks failed: {e}')
189
+ return f'Sorry, there was an error listing tasks: {str(e)}'
190
+
191
+ tools.append(list_tasks)
192
+
193
+ # Create task tool
194
+ @llm.function_tool(
195
+ name='create_task',
196
+ description='Create a new task in the CodeTether system.',
197
+ )
198
+ async def create_task(
199
+ title: str,
200
+ description: str = '',
201
+ priority: int = 0,
202
+ ) -> str:
203
+ """Create a new task."""
204
+ try:
205
+ logger.info(f'Executing create_task: {title}')
206
+ task = await mcp_client.create_task(
207
+ title=title,
208
+ description=description,
209
+ codebase_id='global',
210
+ agent_type='build',
211
+ priority=priority,
212
+ )
213
+ return f"Created task '{task.title}' with ID {task.id}. Status: {task.status}"
214
+ except Exception as e:
215
+ logger.error(f'create_task failed: {e}')
216
+ return f'Sorry, there was an error creating the task: {str(e)}'
217
+
218
+ tools.append(create_task)
219
+
220
+ # Get task tool
221
+ @llm.function_tool(
222
+ name='get_task',
223
+ description='Get details about a specific task by its ID.',
224
+ )
225
+ async def get_task(task_id: str) -> str:
226
+ """Get task details."""
227
+ try:
228
+ logger.info(f'Executing get_task: {task_id}')
229
+ task = await mcp_client.get_task(task_id)
230
+ if task:
231
+ return f"Task '{task.title}' is {task.status}. Priority: {task.priority}"
232
+ return 'Task not found.'
233
+ except Exception as e:
234
+ logger.error(f'get_task failed: {e}')
235
+ return f'Sorry, there was an error getting the task: {str(e)}'
236
+
237
+ tools.append(get_task)
238
+
239
+ # Cancel task tool
240
+ @llm.function_tool(
241
+ name='cancel_task',
242
+ description='Cancel a running or pending task.',
243
+ )
244
+ async def cancel_task(task_id: str) -> str:
245
+ """Cancel a task."""
246
+ try:
247
+ logger.info(f'Executing cancel_task: {task_id}')
248
+ success = await mcp_client.cancel_task(task_id)
249
+ return (
250
+ 'Task cancelled successfully.'
251
+ if success
252
+ else 'Could not cancel the task.'
253
+ )
254
+ except Exception as e:
255
+ logger.error(f'cancel_task failed: {e}')
256
+ return f'Sorry, there was an error cancelling the task: {str(e)}'
257
+
258
+ tools.append(cancel_task)
259
+
260
+ # Discover agents tool
261
+ @llm.function_tool(
262
+ name='discover_agents',
263
+ description='Discover available CodeTether agents that can be messaged.',
264
+ )
265
+ async def discover_agents() -> str:
266
+ """Discover available agents."""
267
+ try:
268
+ logger.info('Executing discover_agents')
269
+ agents = await mcp_client.discover_agents()
270
+ if not agents:
271
+ return 'No agents are currently available.'
272
+ agent_names = ', '.join([a.name for a in agents[:5]])
273
+ return f'Found {len(agents)} agents: {agent_names}'
274
+ except Exception as e:
275
+ logger.error(f'discover_agents failed: {e}')
276
+ return f'Sorry, there was an error discovering agents: {str(e)}'
277
+
278
+ tools.append(discover_agents)
279
+
280
+ logger.info(f'Created {len(tools)} tools for voice agent')
281
+ return tools
282
+
283
+
284
+ async def entrypoint(ctx: JobContext) -> None:
285
+ """Main entrypoint for the voice agent.
286
+
287
+ Connects to the LiveKit room, initializes all components, and starts
288
+ the voice agent session with Gemini 3 Live API.
289
+
290
+ Args:
291
+ ctx: The job context containing room connection and metadata.
292
+ """
293
+ logger.info(f'Starting voice agent in room: {ctx.room.name}')
294
+
295
+ initial_ctx = ctx.room.metadata or '{}'
296
+ try:
297
+ metadata = json.loads(initial_ctx)
298
+ except (json.JSONDecodeError, TypeError):
299
+ metadata = {}
300
+
301
+ voice_id = metadata.get('voice', DEFAULT_VOICE)
302
+ codebase_id = metadata.get('codebase_id', 'global')
303
+ session_id = metadata.get('session_id')
304
+ mode = metadata.get('mode', 'interactive')
305
+ playback_style = metadata.get('playback_style', 'verbatim')
306
+
307
+ voice_name = VOICES.get(voice_id, VOICES[DEFAULT_VOICE])
308
+ logger.info(
309
+ f'Configuration - voice: {voice_name}, codebase_id: {codebase_id}, '
310
+ f'session_id: {session_id}, mode: {mode}, playback_style: {playback_style}'
311
+ )
312
+
313
+ logger.info('About to call ctx.connect()...')
314
+ try:
315
+ await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
316
+ logger.info('Connected to room successfully!')
317
+ except Exception as e:
318
+ logger.error(f'Failed to connect to room: {type(e).__name__}: {e}')
319
+ raise
320
+
321
+ logger.info('Waiting for participant...')
322
+ try:
323
+ participant = await ctx.wait_for_participant()
324
+ logger.info(f'Participant joined: {participant.identity}')
325
+ except Exception as e:
326
+ logger.error(f'Error waiting for participant: {type(e).__name__}: {e}')
327
+ raise
328
+
329
+ try:
330
+ api_url = os.getenv('CODETETHER_API_URL', 'http://localhost:8000')
331
+ logger.info(f'Creating CodeTetherMCP with API URL: {api_url}')
332
+ mcp_client = CodeTetherMCP(api_url=api_url)
333
+ logger.info(f'Initialized CodeTetherMCP with API URL: {api_url}')
334
+
335
+ function_caller = FunctionGemmaCaller()
336
+ logger.info('Initialized FunctionGemmaCaller')
337
+
338
+ session_playback = SessionPlayback(mcp_client=mcp_client)
339
+ logger.info('Initialized SessionPlayback')
340
+
341
+ session_history = None
342
+ if session_id:
343
+ try:
344
+ session_history = await mcp_client.get_session_messages(
345
+ session_id
346
+ )
347
+ logger.info(
348
+ f'Loaded session history: {len(session_history)} messages'
349
+ )
350
+ except Exception as e:
351
+ logger.warning(f'Failed to load session history: {e}')
352
+
353
+ context_string = ''
354
+ if session_history:
355
+ context_string = f'\n\nPrevious conversation context:\n{format_history_for_context(session_history)}'
356
+
357
+ full_instructions = SYSTEM_INSTRUCTIONS + context_string
358
+
359
+ logger.info(f'Creating Gemini RealtimeModel with voice: {voice_name}')
360
+
361
+ # Check if we have Vertex AI credentials (preferred) or fallback to API key
362
+ google_creds_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
363
+ google_api_key = os.getenv('GOOGLE_API_KEY')
364
+ use_vertex = google_creds_path and os.path.exists(google_creds_path)
365
+
366
+ if use_vertex:
367
+ logger.info(
368
+ f'Using Vertex AI with credentials from: {google_creds_path}'
369
+ )
370
+ # Get project ID from credentials file or environment
371
+ project_id = os.getenv('GOOGLE_CLOUD_PROJECT', 'spotlessbinco')
372
+ location = os.getenv('GOOGLE_CLOUD_LOCATION', 'us-central1')
373
+ logger.info(
374
+ f'Vertex AI project: {project_id}, location: {location}'
375
+ )
376
+
377
+ gemini_model = google.realtime.RealtimeModel(
378
+ model='gemini-live-2.5-flash-native-audio',
379
+ voice=voice_name,
380
+ instructions=full_instructions,
381
+ vertexai=True,
382
+ project=project_id,
383
+ location=location,
384
+ )
385
+ elif google_api_key:
386
+ logger.info(f'Using Google API key (length: {len(google_api_key)})')
387
+ gemini_model = google.realtime.RealtimeModel(
388
+ model='gemini-2.0-flash-exp',
389
+ voice=voice_name,
390
+ instructions=full_instructions,
391
+ api_key=google_api_key,
392
+ )
393
+ else:
394
+ logger.error(
395
+ 'No Google credentials found! Set GOOGLE_APPLICATION_CREDENTIALS or GOOGLE_API_KEY'
396
+ )
397
+ raise ValueError('No Google credentials configured')
398
+ logger.info('Gemini RealtimeModel created successfully')
399
+
400
+ # Create tools for the agent
401
+ try:
402
+ agent_tools = create_tools(mcp_client)
403
+ logger.info(f'Created {len(agent_tools)} tools for agent')
404
+ except Exception as e:
405
+ logger.error(f'Failed to create tools: {e}')
406
+ agent_tools = []
407
+
408
+ session = AgentSession(
409
+ llm=gemini_model,
410
+ tools=agent_tools if agent_tools else None,
411
+ )
412
+ logger.info('AgentSession created with tools')
413
+
414
+ if mode == 'playback' and session_id:
415
+ logger.info(
416
+ f'Starting session playback for session_id: {session_id}'
417
+ )
418
+ await session_playback.start(
419
+ session=session,
420
+ session_id=session_id,
421
+ style=playback_style,
422
+ )
423
+
424
+ logger.info(f'Starting agent session in room: {ctx.room.name}')
425
+
426
+ # Create the Agent with the Gemini model
427
+ agent = Agent(
428
+ instructions=full_instructions,
429
+ llm=gemini_model,
430
+ )
431
+
432
+ # Start the session with the agent and room
433
+ await session.start(agent=agent, room=ctx.room)
434
+
435
+ except Exception as e:
436
+ logger.error(f'Error in voice agent entrypoint: {e}')
437
+ raise
438
+
439
+
440
+ if __name__ == '__main__':
441
+ cli.run_app(
442
+ WorkerOptions(
443
+ entrypoint_fnc=entrypoint,
444
+ ),
445
+ )