mindroot 10.6.0__py3-none-any.whl → 10.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.

Potentially problematic release.


This version of mindroot might be problematic. Click here for more details.

@@ -1,495 +0,0 @@
1
- from fastapi import APIRouter, HTTPException, Request, Response, Depends, Query
2
- from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
3
- from fastapi import File, UploadFile, Form
4
- from sse_starlette.sse import EventSourceResponse
5
- from .models import MessageParts
6
- from lib.providers.services import service, service_manager
7
- from .services import init_chat_session, send_message_to_agent, subscribe_to_agent_messages, get_chat_history, run_task
8
- from lib.templates import render
9
- from lib.auth.auth import require_user
10
- from lib.plugins import list_enabled
11
- import nanoid
12
- from lib.providers.commands import *
13
- import asyncio
14
- from lib.chatcontext import get_context, ChatContext
15
- from typing import List
16
- from lib.providers.services import service, service_manager
17
- from lib.providers.commands import command_manager
18
- from lib.utils.debug import debug_box
19
- from lib.session_files import load_session_data, save_session_data
20
- import os
21
- import json
22
- from lib.chatcontext import ChatContext
23
- import shutil
24
- from pydantic import BaseModel
25
- from lib.auth.api_key import verify_api_key
26
- from .services import active_send_tasks, cancel_active_send_task, get_active_send_tasks, cleanup_completed_tasks
27
-
28
- router = APIRouter()
29
-
30
- # Global dictionary to store tasks
31
- tasks = {}
32
-
33
- @router.post("/chat/{log_id}/{task_id}/cancel")
34
- async def cancel_chat(request: Request, log_id: str, task_id: str):
35
- debug_box("cancel_chat")
36
- print("Trying to cancel task", task_id)
37
- user = request.state.user.username
38
- context = await get_context(log_id, user)
39
- debug_box(str(context))
40
-
41
- # Cancel the active send_message_to_agent task if it exists
42
- if log_id in active_send_tasks:
43
- task_info = active_send_tasks[log_id]
44
- task = task_info['task']
45
-
46
- if not task.done():
47
- print(f"Cancelling active send_message_to_agent task for session {log_id}")
48
- task.cancel()
49
- context.data['task_cancelled'] = True
50
- context.data['cancel_current_turn'] = True
51
-
52
- # Also cancel the router task if it exists
53
- if task_id in tasks:
54
- tasks[task_id].cancel()
55
- del tasks[task_id]
56
-
57
- return {"status": "ok", "message": "Task cancelled successfully"}
58
- else:
59
- return {"status": "error", "message": "No active task found"}
60
- else:
61
- return {"status": "error", "message": "No active task found for this session"}
62
-
63
-
64
- @router.get("/context1/{log_id}")
65
- async def context1(request: Request, log_id: str):
66
- user = request.state.user.username
67
- context = await get_context(log_id, user)
68
- print(context)
69
- return "ok"
70
-
71
-
72
- # need to serve persona images from ./personas/local/[persona_path]/avatar.png
73
- @router.get("/chat/personas/{persona_path:path}/avatar.png")
74
- async def get_persona_avatar(persona_path: str):
75
- # Check if this is a registry persona with deduplicated assets
76
- if persona_path.startswith("registry/"):
77
- persona_json_path = f"personas/{persona_path}/persona.json"
78
- if os.path.exists(persona_json_path):
79
- try:
80
- with open(persona_json_path, "r") as f:
81
- persona_data = json.load(f)
82
-
83
- # Check if persona has asset hashes (deduplicated storage)
84
- asset_hashes = persona_data.get("asset_hashes", {})
85
- if "avatar" in asset_hashes:
86
- # Redirect to deduplicated asset endpoint
87
- return RedirectResponse(f"/assets/{asset_hashes['avatar']}")
88
- except Exception as e:
89
- print(f"Error checking for deduplicated assets: {e}")
90
-
91
- # Handle registry personas: registry/owner/name
92
- if persona_path.startswith('registry/'):
93
- file_path = f"personas/{persona_path}/avatar.png"
94
- else:
95
- # Legacy support: check local first, then shared
96
- file_path = f"personas/local/{persona_path}/avatar.png"
97
- if not os.path.exists(file_path):
98
- file_path = f"personas/registry/{persona_path}/avatar.png"
99
-
100
- if not os.path.exists(file_path):
101
- resolved = os.path.realpath(file_path)
102
- return {"error": "File not found: " + resolved}
103
-
104
- with open(file_path, "rb") as f:
105
- image_bytes = f.read()
106
-
107
- return Response(
108
- content=image_bytes,
109
- media_type="image/png",
110
- headers={
111
- "Cache-Control": "max-age=3600",
112
- "Content-Disposition": "inline; filename=avatar.png"
113
- }
114
- )
115
-
116
- @router.get("/chat/personas/{persona_path:path}/faceref.png")
117
- async def get_persona_faceref(persona_path: str):
118
- # Check if this is a registry persona with deduplicated assets
119
- if persona_path.startswith("registry/"):
120
- persona_json_path = f"personas/{persona_path}/persona.json"
121
- if os.path.exists(persona_json_path):
122
- try:
123
- with open(persona_json_path, "r") as f:
124
- persona_data = json.load(f)
125
-
126
- # Check if persona has asset hashes (deduplicated storage)
127
- asset_hashes = persona_data.get("asset_hashes", {})
128
- if "faceref" in asset_hashes:
129
- # Redirect to deduplicated asset endpoint
130
- return RedirectResponse(f"/assets/{asset_hashes['faceref']}")
131
- except Exception as e:
132
- print(f"Error checking for deduplicated assets: {e}")
133
-
134
- # Handle registry personas: registry/owner/name
135
- if persona_path.startswith('registry/'):
136
- file_path = f"personas/{persona_path}/faceref.png"
137
- else:
138
- # Legacy support: check local first, then shared
139
- file_path = f"personas/local/{persona_path}/faceref.png"
140
- if not os.path.exists(file_path):
141
- file_path = f"personas/registry/{persona_path}/faceref.png"
142
-
143
- if not os.path.exists(file_path):
144
- # Fallback to avatar if faceref doesn't exist
145
- return RedirectResponse(f"/chat/personas/{persona_path}/avatar.png")
146
-
147
- with open(file_path, "rb") as f:
148
- image_bytes = f.read()
149
-
150
- return Response(
151
- content=image_bytes,
152
- media_type="image/png",
153
- headers={
154
- "Cache-Control": "max-age=3600",
155
- "Content-Disposition": "inline; filename=faceref.png"
156
- }
157
- )
158
-
159
- @router.get("/chat/{log_id}/events")
160
- async def chat_events(log_id: str):
161
- return EventSourceResponse(await subscribe_to_agent_messages(log_id))
162
-
163
-
164
- @router.post("/chat/{log_id}/send")
165
- async def send_message(request: Request, log_id: str, message_parts: List[MessageParts] ):
166
- user = request.state.user
167
- debug_box("send_message")
168
-
169
-
170
- context = await get_context(log_id, user.username)
171
- debug_box(str(context))
172
- #context = ChatContext(command_manager, service_manager, user=user.user)
173
- task = asyncio.create_task(send_message_to_agent(log_id, message_parts, context=context, user=user))
174
- #task = asyncio.create_task(send_message_to_agent(log_id, message_parts, user=user))
175
-
176
- task_id = nanoid.generate()
177
-
178
-
179
- # Check if there's already an active task for this session and cancel it
180
- if log_id in active_send_tasks:
181
- existing_task_info = active_send_tasks[log_id]
182
- existing_task = existing_task_info['task']
183
- if not existing_task.done():
184
- print(f"Cancelling existing task for session {log_id} before starting new one")
185
- existing_task.cancel()
186
-
187
- tasks[task_id] = task
188
-
189
- return {"status": "ok", "task_id": task_id}
190
-
191
- @router.get("/chat/{log_id}/active_tasks")
192
- async def get_active_tasks(request: Request, log_id: str):
193
- """
194
- Get information about active tasks for a session (for debugging)
195
- """
196
- user = request.state.user.username
197
-
198
- active_info = {}
199
- if log_id in active_send_tasks:
200
- task_info = active_send_tasks[log_id]
201
- task = task_info['task']
202
- active_info = {
203
- "session_id": log_id,
204
- "task_active": not task.done(),
205
- "task_cancelled": task.cancelled() if task else False,
206
- "created_at": task_info.get('created_at'),
207
- "router_tasks": [tid for tid, t in tasks.items() if not t.done()]
208
- }
209
-
210
- return {"status": "ok", "active_tasks": active_info}
211
-
212
- @router.post("/chat/{log_id}/cancel_send_task")
213
- async def cancel_send_task_endpoint(request: Request, log_id: str):
214
- """
215
- Cancel the active send_message_to_agent task for a session.
216
- """
217
- user = request.state.user.username
218
- context = await get_context(log_id, user)
219
-
220
- result = await cancel_active_send_task(log_id, context=context)
221
- return result
222
-
223
- @router.get("/chat/active_send_tasks")
224
- async def get_all_active_send_tasks(request: Request):
225
- """
226
- Get information about all active send_message_to_agent tasks.
227
- """
228
- result = await get_active_send_tasks()
229
- return result
230
-
231
- @router.post("/chat/cleanup_completed_tasks")
232
- async def cleanup_completed_tasks_endpoint(request: Request):
233
- """
234
- Clean up completed tasks from memory.
235
- """
236
- result = await cleanup_completed_tasks()
237
- return result
238
-
239
- @router.get("/agent/{agent_name}", response_class=HTMLResponse)
240
- async def get_chat_html(request: Request, agent_name: str, api_key: str = Query(None), embed: bool = Query(False)):
241
- # Handle API key authentication if provided
242
- if api_key:
243
- try:
244
- user_data = await verify_api_key(api_key)
245
- if not user_data:
246
- raise HTTPException(status_code=401, detail="Invalid API key")
247
- # Create a mock user object for API key users
248
- class MockUser:
249
- def __init__(self, username):
250
- self.username = username
251
- user = MockUser(user_data['username'])
252
- except Exception as e:
253
- raise HTTPException(status_code=401, detail="Invalid API key")
254
- else:
255
- # Use regular authentication
256
- if not hasattr(request.state, "user"):
257
- return RedirectResponse("/login")
258
- user = request.state.user
259
-
260
- log_id = nanoid.generate()
261
- plugins = list_enabled()
262
- print("Init chat with user", user)
263
- print(f"Init chat with {agent_name}")
264
- await init_chat_session(user, agent_name, log_id)
265
-
266
- if hasattr(request.state, "access_token"):
267
- debug_box("Access token found in request state, saving to session file")
268
- access_token = request.state.access_token
269
- await save_session_data(log_id, "access_token", access_token)
270
- print("..")
271
- debug_box("Access token saved to session file")
272
- else:
273
- debug_box("No access token found in request state")
274
-
275
- # If embed mode is requested, redirect to embed session
276
- if embed:
277
- return RedirectResponse(f"/session/{agent_name}/{log_id}?embed=true")
278
-
279
- # Regular redirect
280
- return RedirectResponse(f"/session/{agent_name}/{log_id}")
281
-
282
- @router.get("/makesession/{agent_name}")
283
- async def make_session(request: Request, agent_name: str):
284
- """
285
- Create a new chat session for the specified agent.
286
- Returns a redirect to the chat session page.
287
- """
288
- if not hasattr(request.state, "user"):
289
- return RedirectResponse("/login")
290
- user = request.state.user
291
- log_id = nanoid.generate()
292
-
293
- await init_chat_session(user, agent_name, log_id)
294
- return JSONResponse({ "log_id": log_id })
295
-
296
- @router.get("/history/{agent_name}/{log_id}")
297
- async def chat_history(request: Request, agent_name: str, log_id: str):
298
- user = request.state.user.username
299
- history = await get_chat_history(agent_name, log_id, user)
300
- if history is None or len(history) == 0:
301
- try:
302
- print("trying to load from system session")
303
- history = await get_chat_history(agent_name, log_id, "system")
304
- except Exception as e:
305
- print("Error loading from system session:", e)
306
- history = []
307
- pass
308
- return history
309
-
310
- @router.get("/session/{agent_name}/{log_id}")
311
- async def chat_session(request: Request, agent_name: str, log_id: str, embed: bool = Query(False)):
312
- # Check authentication (API key or regular user)
313
- plugins = list_enabled()
314
- if not hasattr(request.state, "user"):
315
- return RedirectResponse("/login")
316
-
317
- user = request.state.user
318
- agent = await service_manager.get_agent_data(agent_name)
319
- persona = agent['persona']['name']
320
- print("persona is:", persona)
321
- auth_token = None
322
- try:
323
- auth_token = await load_session_data(log_id, "access_token")
324
- except:
325
- pass
326
- chat_data = {"log_id": log_id, "agent_name": agent_name, "user": user, "persona": persona }
327
-
328
- if auth_token is not None:
329
- chat_data["access_token"] = auth_token
330
-
331
- # Add embed mode flag
332
- if embed:
333
- chat_data["embed_mode"] = True
334
-
335
- html = await render('chat', chat_data)
336
- return HTMLResponse(html)
337
-
338
- # use starlette staticfiles to mount ./imgs
339
- app.mount("/published", StaticFiles(directory=str(published_dir)), name="published_indices")
340
-
341
- class TaskRequest(BaseModel):
342
- instructions: str
343
-
344
- @router.post("/task/{agent_name}")
345
- async def run_task_route(request: Request, agent_name: str, task_request: TaskRequest = None):
346
- """
347
- Run a task for an agent with the given instructions.
348
- This endpoint allows programmatic interaction with agents without a full chat session.
349
-
350
- Parameters:
351
- - agent_name: The name of the agent to run the task
352
- - instructions: The instructions/prompt to send to the agent
353
-
354
- Returns:
355
- - JSON with results and log_id for tracking
356
- """
357
-
358
- user = request.state.user.username
359
-
360
- instructions = None
361
- if task_request is not None:
362
- instructions = task_request.instructions
363
-
364
- if not instructions:
365
- return {"status": "error", "message": "No instructions provided"}
366
-
367
- task_result, full_results, log_id = await run_task(instructions=instructions, agent_name=agent_name, user=user)
368
- print(task_result)
369
- print(full_results)
370
- print(log_id)
371
- return {"status": "ok", "results": task_result, "full_results": full_results, "log_id": log_id}
372
-
373
-
374
- @router.post("/chat/{log_id}/upload")
375
- async def upload_file(request: Request, log_id: str, file: UploadFile = File(...)):
376
- """
377
- Upload a file and store it in a user-specific directory.
378
- Returns the file path that can be used in messages.
379
- """
380
- user = request.state.user.username
381
-
382
- # Create user uploads directory if it doesn't exist
383
- user_upload_dir = f"data/users/{user}/uploads/{log_id}"
384
- os.makedirs(user_upload_dir, exist_ok=True)
385
-
386
- # Generate a safe filename to prevent path traversal
387
- filename = os.path.basename(file.filename)
388
- file_path = os.path.join(user_upload_dir, filename)
389
-
390
- # Save the file
391
- with open(file_path, "wb") as buffer:
392
- shutil.copyfileobj(file.file, buffer)
393
-
394
- # Return the file information
395
- return {
396
- "status": "ok",
397
- "filename": filename,
398
- "path": file_path,
399
- "mime_type": file.content_type
400
- }
401
-
402
-
403
- from lib.chatlog import count_tokens_for_log_id
404
-
405
- @router.get("/chat/{log_id}/tokens")
406
- async def get_token_count(request: Request, log_id: str):
407
- """
408
- Get token counts for a chat log identified by log_id, including any delegated tasks.
409
-
410
- Parameters:
411
- - log_id: The log ID to count tokens for
412
-
413
- Returns:
414
- - JSON with token counts or error message if log not found
415
- """
416
- token_counts = await count_tokens_for_log_id(log_id)
417
-
418
- if token_counts is None:
419
- return {"status": "error", "message": f"Chat log with ID {log_id} not found"}
420
-
421
-
422
- return {"status": "ok", "token_counts": token_counts}
423
-
424
- @router.get("/chat/del_session/{log_id}")
425
- async def delete_chat_session(request: Request, log_id: str, user=Depends(require_user)):
426
- """
427
- Delete a chat session by log_id, including chat logs, context files, and all child sessions.
428
-
429
- Parameters:
430
- - log_id: The log ID of the session to delete
431
-
432
- Returns:
433
- - JSON with success status and message
434
- """
435
- try:
436
- # Try to determine the agent name from the context file first
437
- agent_name = "unknown"
438
- context_dir = os.environ.get('CHATCONTEXT_DIR', 'data/context')
439
- context_file_path = f"{context_dir}/{user.username}/context_{log_id}.json"
440
-
441
- if os.path.exists(context_file_path):
442
- try:
443
- with open(context_file_path, 'r') as f:
444
- context_data = json.load(f)
445
- agent_name = context_data.get('agent_name', 'unknown')
446
- print(f"Found agent name '{agent_name}' from context file for log_id {log_id}")
447
- except Exception as e:
448
- print(f"Error reading context file {context_file_path}: {e}")
449
-
450
- # If we still don't have the agent name, try to find the chatlog file
451
- if agent_name == "unknown":
452
- from lib.chatlog import find_chatlog_file
453
- chatlog_path = find_chatlog_file(log_id)
454
- if chatlog_path:
455
- # Extract agent from path: data/chat/{user}/{agent}/chatlog_{log_id}.json
456
- path_parts = chatlog_path.split(os.sep)
457
- if len(path_parts) >= 3:
458
- agent_name = path_parts[-2] # Agent is the second-to-last part
459
- print(f"Found agent name '{agent_name}' from chatlog file path for log_id {log_id}")
460
-
461
- await ChatContext.delete_session_by_id(log_id=log_id, user=user.username, agent=agent_name, cascade=True)
462
-
463
- return {"status": "ok", "message": f"Chat session {log_id} deleted successfully"}
464
- except Exception as e:
465
- print(f"Error deleting chat session {log_id}: {e}")
466
- raise HTTPException(status_code=500, detail=f"Error deleting chat session: {str(e)}")
467
-
468
-
469
- @router.get("/chat/{log_id}/tokens")
470
- async def get_token_count_alt(request: Request, log_id: str):
471
- """
472
- Alternative token count endpoint using token_counter module.
473
-
474
- Parameters:
475
- - log_id: The log ID to count tokens for
476
-
477
- Returns:
478
- - JSON with token counts or error message if log not found
479
- """
480
- from lib.token_counter import count_tokens_for_log_id
481
-
482
- token_counts = await count_tokens_for_log_id(log_id)
483
-
484
- if token_counts is None:
485
- return {"status": "error", "message": f"Chat log with ID {log_id} not found"}
486
-
487
-
488
- return {"status": "ok", "token_counts": token_counts}
489
-
490
- # Include widget routes
491
- try:
492
- from .widget_routes import router as widget_router
493
- router.include_router(widget_router)
494
- except ImportError as e:
495
- print(f"Warning: Could not load widget routes: {e}")