meshagent-cli 0.7.0__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.
@@ -0,0 +1,601 @@
1
+ import typer
2
+ from rich import print
3
+ from typing import Annotated, Optional
4
+ from meshagent.tools import Toolkit
5
+ from meshagent.tools.storage import StorageToolkitBuilder
6
+ from meshagent.agents.config import RulesConfig
7
+
8
+ from meshagent.cli.common_options import (
9
+ ProjectIdOption,
10
+ RoomOption,
11
+ )
12
+ from meshagent.api import (
13
+ RoomClient,
14
+ WebSocketClientProtocol,
15
+ ParticipantToken,
16
+ ApiScope,
17
+ RoomException,
18
+ )
19
+ from meshagent.api.helpers import meshagent_base_url, websocket_room_url
20
+ from meshagent.cli import async_typer
21
+ from meshagent.cli.helper import (
22
+ get_client,
23
+ resolve_project_id,
24
+ resolve_room,
25
+ resolve_key,
26
+ )
27
+
28
+ from meshagent.openai import OpenAIResponsesAdapter
29
+
30
+ from typing import List
31
+ from pathlib import Path
32
+
33
+ from meshagent.openai.tools.responses_adapter import (
34
+ WebSearchToolkitBuilder,
35
+ MCPToolkitBuilder,
36
+ WebSearchTool,
37
+ LocalShellConfig,
38
+ ShellConfig,
39
+ WebSearchConfig,
40
+ ApplyPatchConfig,
41
+ ApplyPatchTool,
42
+ ApplyPatchToolkitBuilder,
43
+ )
44
+
45
+ from meshagent.api import RequiredToolkit, RequiredSchema
46
+ from meshagent.api.services import ServiceHost
47
+ import logging
48
+ import os.path
49
+
50
+ logger = logging.getLogger("chatbot")
51
+
52
+ app = async_typer.AsyncTyper(help="Join a chatbot to a room")
53
+
54
+
55
+ def build_chatbot(
56
+ *,
57
+ model: str,
58
+ agent_name: str,
59
+ rule: List[str],
60
+ toolkit: List[str],
61
+ schema: List[str],
62
+ image_generation: Optional[str] = None,
63
+ local_shell: Optional[str] = None,
64
+ shell: Optional[str] = None,
65
+ apply_patch: Optional[str] = None,
66
+ computer_use: Optional[str] = None,
67
+ web_search: Optional[str] = None,
68
+ mcp: Optional[str] = None,
69
+ storage: Optional[str] = None,
70
+ require_image_generation: Optional[str] = None,
71
+ require_local_shell: Optional[str] = None,
72
+ require_shell: Optional[str] = None,
73
+ require_apply_patch: Optional[str] = None,
74
+ require_computer_use: Optional[str] = None,
75
+ require_web_search: Optional[str] = None,
76
+ require_mcp: Optional[str] = None,
77
+ require_storage: Optional[str] = None,
78
+ rules_file: Optional[str] = None,
79
+ room_rules_path: Optional[str] = None,
80
+ working_directory: Optional[str] = None,
81
+ ):
82
+ from meshagent.agents.chat import ChatBot
83
+
84
+ from meshagent.tools.storage import StorageToolkit
85
+
86
+ from meshagent.agents.chat import (
87
+ ChatBotThreadOpenAIImageGenerationToolkitBuilder,
88
+ ChatBotThreadLocalShellToolkitBuilder,
89
+ ChatBotThreadOpenAIImageGenerationTool,
90
+ ChatBotThreadLocalShellTool,
91
+ ChatBotThreadShellTool,
92
+ ChatBotThreadShellToolkitBuilder,
93
+ ImageGenerationConfig,
94
+ )
95
+
96
+ requirements = []
97
+
98
+ toolkits = []
99
+
100
+ for t in toolkit:
101
+ requirements.append(RequiredToolkit(name=t))
102
+
103
+ for t in schema:
104
+ requirements.append(RequiredSchema(name=t))
105
+
106
+ client_rules = {}
107
+
108
+ if rules_file is not None:
109
+ try:
110
+ with open(Path(os.path.expanduser(rules_file)).resolve(), "r") as f:
111
+ rules_config = RulesConfig.parse(f.read())
112
+ rule = rules_config.rules
113
+ client_rules = rules_config.client_rules
114
+
115
+ except FileNotFoundError:
116
+ print(f"[yellow]rules file not found at {rules_file}[/yellow]")
117
+
118
+ BaseClass = ChatBot
119
+ if computer_use:
120
+ from meshagent.computers.agent import ComputerAgent
121
+
122
+ if ComputerAgent is None:
123
+ raise RuntimeError(
124
+ "Computer use is enabled, but meshagent.computers is not installed."
125
+ )
126
+ BaseClass = ComputerAgent
127
+ llm_adapter = OpenAIResponsesAdapter(
128
+ model=model,
129
+ response_options={
130
+ "reasoning": {"generate_summary": "concise"},
131
+ "truncation": "auto",
132
+ },
133
+ )
134
+ else:
135
+ llm_adapter = OpenAIResponsesAdapter(
136
+ model=model,
137
+ )
138
+
139
+ class CustomChatbot(BaseClass):
140
+ def __init__(self):
141
+ super().__init__(
142
+ llm_adapter=llm_adapter,
143
+ name=agent_name,
144
+ requires=requirements,
145
+ toolkits=toolkits,
146
+ rules=rule if len(rule) > 0 else None,
147
+ client_rules=client_rules,
148
+ )
149
+
150
+ async def get_rules(self, *, thread_context, participant):
151
+ rules = await super().get_rules(
152
+ thread_context=thread_context, participant=participant
153
+ )
154
+
155
+ if room_rules_path is not None:
156
+ for p in room_rules_path:
157
+ try:
158
+ room_rules = await self.room.storage.download(path=p)
159
+
160
+ rules_txt = room_rules.data.decode()
161
+
162
+ rules_config = RulesConfig.parse(rules_txt)
163
+
164
+ if rules_config.rules is not None:
165
+ rules.extend(rules_config.rules)
166
+
167
+ client = participant.get_attribute("client")
168
+
169
+ if rules_config.client_rules is not None and client is not None:
170
+ cr = rules_config.client_rules.get(client)
171
+ if cr is not None:
172
+ rules.extend(cr)
173
+
174
+ except RoomException:
175
+ try:
176
+ logger.info("attempting to initialize rules file")
177
+ handle = await self.room.storage.open(
178
+ path=p, overwrite=False
179
+ )
180
+ await self.room.storage.write(
181
+ handle=handle,
182
+ data="# Add rules to this file to customize your agent's behavior, lines starting with # will be ignored.\n\n".encode(),
183
+ )
184
+ await self.room.storage.close(handle=handle)
185
+
186
+ except RoomException:
187
+ pass
188
+ logger.info(
189
+ f"unable to load rules from {room_rules_path}, continuing with default rules"
190
+ )
191
+ pass
192
+
193
+ print(f"using rules {rules}", flush=True)
194
+
195
+ return rules
196
+
197
+ async def get_thread_toolkits(self, *, thread_context, participant):
198
+ providers = []
199
+
200
+ if require_image_generation:
201
+ providers.append(
202
+ ChatBotThreadOpenAIImageGenerationTool(
203
+ thread_context=thread_context,
204
+ config=ImageGenerationConfig(
205
+ name="image_generation",
206
+ partial_images=3,
207
+ ),
208
+ )
209
+ )
210
+
211
+ if require_local_shell:
212
+ providers.append(
213
+ ChatBotThreadLocalShellTool(
214
+ working_directory=working_directory,
215
+ thread_context=thread_context,
216
+ config=LocalShellConfig(name="local_shell"),
217
+ )
218
+ )
219
+
220
+ if require_shell:
221
+ providers.append(
222
+ ChatBotThreadShellTool(
223
+ thread_context=thread_context,
224
+ working_directory=working_directory,
225
+ config=ShellConfig(name="shell"),
226
+ )
227
+ )
228
+
229
+ if require_apply_patch:
230
+ providers.append(
231
+ ApplyPatchTool(
232
+ config=ApplyPatchConfig(name="apply_patch"),
233
+ )
234
+ )
235
+
236
+ if require_mcp:
237
+ raise Exception(
238
+ "mcp tool cannot be required by cli currently, use 'optional' instead"
239
+ )
240
+
241
+ if require_web_search:
242
+ providers.append(
243
+ WebSearchTool(config=WebSearchConfig(name="web_search"))
244
+ )
245
+
246
+ if require_storage:
247
+ providers.extend(StorageToolkit().tools)
248
+
249
+ tk = await super().get_thread_toolkits(
250
+ thread_context=thread_context, participant=participant
251
+ )
252
+ return [
253
+ *(
254
+ [Toolkit(name="tools", tools=providers)]
255
+ if len(providers) > 0
256
+ else []
257
+ ),
258
+ *tk,
259
+ ]
260
+
261
+ async def get_thread_toolkit_builders(self, *, thread_context, participant):
262
+ providers = []
263
+
264
+ if image_generation:
265
+ providers.append(
266
+ ChatBotThreadOpenAIImageGenerationToolkitBuilder(
267
+ thread_context=thread_context
268
+ )
269
+ )
270
+
271
+ if apply_patch:
272
+ providers.append(
273
+ ApplyPatchToolkitBuilder(thread_context=thread_context)
274
+ )
275
+
276
+ if local_shell:
277
+ providers.append(
278
+ ChatBotThreadLocalShellToolkitBuilder(
279
+ thread_context=thread_context,
280
+ working_directory=working_directory,
281
+ )
282
+ )
283
+
284
+ if shell:
285
+ providers.append(
286
+ ChatBotThreadShellToolkitBuilder(
287
+ thread_context=thread_context,
288
+ working_directory=working_directory,
289
+ )
290
+ )
291
+
292
+ if mcp:
293
+ providers.append(MCPToolkitBuilder())
294
+
295
+ if web_search:
296
+ providers.append(WebSearchToolkitBuilder())
297
+
298
+ if storage:
299
+ providers.append(StorageToolkitBuilder())
300
+
301
+ return providers
302
+
303
+ return CustomChatbot
304
+
305
+
306
+ @app.async_command("join")
307
+ async def make_call(
308
+ *,
309
+ project_id: ProjectIdOption = None,
310
+ room: RoomOption,
311
+ role: str = "agent",
312
+ agent_name: Annotated[str, typer.Option(..., help="Name of the agent to call")],
313
+ rule: Annotated[List[str], typer.Option("--rule", "-r", help="a system rule")] = [],
314
+ room_rules: Annotated[
315
+ List[str],
316
+ typer.Option(
317
+ "--room-rules",
318
+ "-rr",
319
+ help="a path to a rules file within the room that can be used to customize the agent's behavior",
320
+ ),
321
+ ] = [],
322
+ rules_file: Optional[str] = None,
323
+ toolkit: Annotated[
324
+ List[str],
325
+ typer.Option("--toolkit", "-t", help="the name or url of a required toolkit"),
326
+ ] = [],
327
+ schema: Annotated[
328
+ List[str],
329
+ typer.Option("--schema", "-s", help="the name or url of a required schema"),
330
+ ] = [],
331
+ model: Annotated[
332
+ str, typer.Option(..., help="Name of the LLM model to use for the chatbot")
333
+ ] = "gpt-5.1",
334
+ image_generation: Annotated[
335
+ Optional[str], typer.Option(..., help="Name of an image gen model")
336
+ ] = None,
337
+ computer_use: Annotated[
338
+ Optional[bool],
339
+ typer.Option(
340
+ ..., help="Enable computer use (requires computer-use-preview model)"
341
+ ),
342
+ ] = False,
343
+ local_shell: Annotated[
344
+ Optional[bool], typer.Option(..., help="Enable local shell tool calling")
345
+ ] = False,
346
+ shell: Annotated[
347
+ Optional[bool], typer.Option(..., help="Enable function shell tool calling")
348
+ ] = False,
349
+ apply_patch: Annotated[
350
+ Optional[bool], typer.Option(..., help="Enable apply patch tool")
351
+ ] = False,
352
+ web_search: Annotated[
353
+ Optional[bool], typer.Option(..., help="Enable web search tool calling")
354
+ ] = False,
355
+ mcp: Annotated[
356
+ Optional[bool], typer.Option(..., help="Enable mcp tool calling")
357
+ ] = False,
358
+ storage: Annotated[
359
+ Optional[bool], typer.Option(..., help="Enable storage toolkit")
360
+ ] = False,
361
+ require_image_generation: Annotated[
362
+ Optional[str], typer.Option(..., help="Name of an image gen model", hidden=True)
363
+ ] = None,
364
+ require_computer_use: Annotated[
365
+ Optional[bool],
366
+ typer.Option(
367
+ ...,
368
+ help="Enable computer use (requires computer-use-preview model)",
369
+ hidden=True,
370
+ ),
371
+ ] = False,
372
+ require_local_shell: Annotated[
373
+ Optional[bool],
374
+ typer.Option(..., help="Enable local shell tool calling", hidden=True),
375
+ ] = False,
376
+ require_shell: Annotated[
377
+ Optional[bool],
378
+ typer.Option(..., help="Enable function shell tool calling", hidden=True),
379
+ ] = False,
380
+ require_apply_patch: Annotated[
381
+ Optional[bool],
382
+ typer.Option(..., help="Enable apply patch tool calling", hidden=True),
383
+ ] = False,
384
+ require_web_search: Annotated[
385
+ Optional[bool],
386
+ typer.Option(..., help="Enable web search tool calling", hidden=True),
387
+ ] = False,
388
+ require_mcp: Annotated[
389
+ Optional[bool], typer.Option(..., help="Enable mcp tool calling", hidden=True)
390
+ ] = False,
391
+ require_storage: Annotated[
392
+ Optional[bool], typer.Option(..., help="Enable storage toolkit", hidden=True)
393
+ ] = False,
394
+ working_directory: Annotated[
395
+ Optional[str],
396
+ typer.Option(..., help="The default working directory for shell commands"),
397
+ ] = None,
398
+ key: Annotated[
399
+ str,
400
+ typer.Option("--key", help="an api key to sign the token with"),
401
+ ] = None,
402
+ ):
403
+ key = await resolve_key(project_id=project_id, key=key)
404
+ account_client = await get_client()
405
+ try:
406
+ project_id = await resolve_project_id(project_id=project_id)
407
+ room = resolve_room(room)
408
+
409
+ token = ParticipantToken(
410
+ name=agent_name,
411
+ )
412
+
413
+ token.add_api_grant(ApiScope.agent_default())
414
+
415
+ token.add_role_grant(role=role)
416
+ token.add_room_grant(room)
417
+
418
+ jwt = token.to_jwt(api_key=key)
419
+
420
+ print("[bold green]Connecting to room...[/bold green]", flush=True)
421
+ async with RoomClient(
422
+ protocol=WebSocketClientProtocol(
423
+ url=websocket_room_url(room_name=room, base_url=meshagent_base_url()),
424
+ token=jwt,
425
+ )
426
+ ) as client:
427
+ requirements = []
428
+
429
+ for t in toolkit:
430
+ requirements.append(RequiredToolkit(name=t))
431
+
432
+ for t in schema:
433
+ requirements.append(RequiredSchema(name=t))
434
+
435
+ CustomChatbot = build_chatbot(
436
+ computer_use=computer_use,
437
+ model=model,
438
+ local_shell=local_shell,
439
+ shell=shell,
440
+ apply_patch=apply_patch,
441
+ agent_name=agent_name,
442
+ rule=rule,
443
+ toolkit=toolkit,
444
+ schema=schema,
445
+ rules_file=rules_file,
446
+ image_generation=image_generation,
447
+ web_search=web_search,
448
+ mcp=mcp,
449
+ storage=storage,
450
+ require_apply_patch=require_apply_patch,
451
+ require_web_search=require_web_search,
452
+ require_local_shell=require_local_shell,
453
+ require_shell=require_shell,
454
+ require_image_generation=require_image_generation,
455
+ require_mcp=require_mcp,
456
+ require_storage=require_storage,
457
+ room_rules_path=room_rules,
458
+ working_directory=working_directory,
459
+ )
460
+
461
+ bot = CustomChatbot()
462
+
463
+ await bot.start(room=client)
464
+ try:
465
+ print(
466
+ f"[bold green]Open the studio to interact with your agent: {meshagent_base_url().replace('api.', 'studio.')}/projects/{project_id}/rooms/{client.room_name}[/bold green]",
467
+ flush=True,
468
+ )
469
+ await client.protocol.wait_for_close()
470
+ except KeyboardInterrupt:
471
+ await bot.stop()
472
+
473
+ finally:
474
+ await account_client.close()
475
+
476
+
477
+ @app.async_command("service")
478
+ async def service(
479
+ *,
480
+ agent_name: Annotated[str, typer.Option(..., help="Name of the agent to call")],
481
+ rule: Annotated[List[str], typer.Option("--rule", "-r", help="a system rule")] = [],
482
+ rules_file: Optional[str] = None,
483
+ room_rules: Annotated[
484
+ List[str],
485
+ typer.Option(
486
+ "--room-rules",
487
+ "-rr",
488
+ help="a path to a rules file within the room that can be used to customize the agent's behavior",
489
+ ),
490
+ ] = [],
491
+ toolkit: Annotated[
492
+ List[str],
493
+ typer.Option("--toolkit", "-t", help="the name or url of a required toolkit"),
494
+ ] = [],
495
+ schema: Annotated[
496
+ List[str],
497
+ typer.Option("--schema", "-s", help="the name or url of a required schema"),
498
+ ] = [],
499
+ model: Annotated[
500
+ str, typer.Option(..., help="Name of the LLM model to use for the chatbot")
501
+ ] = "gpt-5.1",
502
+ image_generation: Annotated[
503
+ Optional[str], typer.Option(..., help="Name of an image gen model")
504
+ ] = None,
505
+ local_shell: Annotated[
506
+ Optional[bool], typer.Option(..., help="Enable local shell tool calling")
507
+ ] = False,
508
+ shell: Annotated[
509
+ Optional[bool], typer.Option(..., help="Enable function shell tool calling")
510
+ ] = False,
511
+ apply_patch: Annotated[
512
+ Optional[bool], typer.Option(..., help="Enable apply patch tool")
513
+ ] = False,
514
+ computer_use: Annotated[
515
+ Optional[bool],
516
+ typer.Option(
517
+ ..., help="Enable computer use (requires computer-use-preview model)"
518
+ ),
519
+ ] = False,
520
+ web_search: Annotated[
521
+ Optional[bool], typer.Option(..., help="Enable web search tool calling")
522
+ ] = False,
523
+ mcp: Annotated[
524
+ Optional[bool], typer.Option(..., help="Enable mcp tool calling")
525
+ ] = False,
526
+ storage: Annotated[
527
+ Optional[bool], typer.Option(..., help="Enable storage toolkit")
528
+ ] = False,
529
+ require_image_generation: Annotated[
530
+ Optional[str], typer.Option(..., help="Name of an image gen model", hidden=True)
531
+ ] = None,
532
+ require_computer_use: Annotated[
533
+ Optional[bool],
534
+ typer.Option(
535
+ ...,
536
+ help="Enable computer use (requires computer-use-preview model)",
537
+ hidden=True,
538
+ ),
539
+ ] = False,
540
+ require_local_shell: Annotated[
541
+ Optional[bool],
542
+ typer.Option(..., help="Enable local shell tool calling", hidden=True),
543
+ ] = False,
544
+ require_shell: Annotated[
545
+ Optional[bool],
546
+ typer.Option(..., help="Enable function shell tool calling", hidden=True),
547
+ ] = False,
548
+ require_apply_patch: Annotated[
549
+ Optional[bool], typer.Option(..., help="Enable apply patch tool", hidden=True)
550
+ ] = False,
551
+ require_web_search: Annotated[
552
+ Optional[bool],
553
+ typer.Option(..., help="Enable web search tool calling", hidden=True),
554
+ ] = False,
555
+ require_mcp: Annotated[
556
+ Optional[bool], typer.Option(..., help="Enable mcp tool calling", hidden=True)
557
+ ] = False,
558
+ require_storage: Annotated[
559
+ Optional[bool], typer.Option(..., help="Enable storage toolkit", hidden=True)
560
+ ] = False,
561
+ working_directory: Annotated[
562
+ Optional[str],
563
+ typer.Option(..., help="The default working directory for shell commands"),
564
+ ] = None,
565
+ host: Annotated[Optional[str], typer.Option()] = None,
566
+ port: Annotated[Optional[int], typer.Option()] = None,
567
+ path: Annotated[str, typer.Option()] = "/agent",
568
+ ):
569
+ print("[bold green]Connecting to room...[/bold green]", flush=True)
570
+
571
+ service = ServiceHost(host=host, port=port)
572
+ service.add_path(
573
+ path=path,
574
+ cls=build_chatbot(
575
+ computer_use=computer_use,
576
+ model=model,
577
+ local_shell=local_shell,
578
+ shell=shell,
579
+ apply_patch=apply_patch,
580
+ agent_name=agent_name,
581
+ rule=rule,
582
+ toolkit=toolkit,
583
+ schema=schema,
584
+ rules_file=rules_file,
585
+ web_search=web_search,
586
+ image_generation=image_generation,
587
+ mcp=mcp,
588
+ storage=storage,
589
+ require_web_search=require_web_search,
590
+ require_shell=require_shell,
591
+ require_apply_patch=require_apply_patch,
592
+ require_local_shell=require_local_shell,
593
+ require_image_generation=require_image_generation,
594
+ require_mcp=require_mcp,
595
+ require_storage=require_storage,
596
+ room_rules_path=room_rules,
597
+ working_directory=working_directory,
598
+ ),
599
+ )
600
+
601
+ await service.run()