Repository: letta-ai/letta

Issue:
json schema doesn't update after tool editing via ADE
**Describe the bug**

When editing a tool via the ADE, the changes are saved, but the json_schema doesn't reflect the updates. After modifying the tool and making a REST API call to verify the state, I noticed that the json_schema remained unchanged.

For example, I initially created a basic roll_d20 tool. After editing it to add a new function, the json_schema still showed the original version without the new changes.

<img width="651" alt="Bildschirmfoto 2024-10-12 um 14 05 46" src="https://github.com/user-attachments/assets/fb6bb7f6-0bee-44b8-aaa8-c3403860fbb2">

Hints from issue comments:
@mattzh72: I see - I'll add code to autogenerate the schema if the `source_code` is updated in the Tool.

Solution patch:
diff --git a/examples/swarm/simple.py b/examples/swarm/simple.py
index e5595dd5..407abc08 100644
--- a/examples/swarm/simple.py
+++ b/examples/swarm/simple.py
@@ -48,8 +48,8 @@ swarm.client.set_default_embedding_config(EmbeddingConfig.default_config(provide
 swarm.client.set_default_llm_config(LLMConfig.default_config(model_name="gpt-4"))
 
 # create tools
-transfer_a = swarm.client.create_tool(transfer_agent_a, terminal=True)
-transfer_b = swarm.client.create_tool(transfer_agent_b, terminal=True)
+transfer_a = swarm.client.create_tool(transfer_agent_a)
+transfer_b = swarm.client.create_tool(transfer_agent_b)
 
 # create agents
 if swarm.client.get_agent_id("agentb"):
diff --git a/letta/client/client.py b/letta/client/client.py
index f0d5203f..30b53f2d 100644
--- a/letta/client/client.py
+++ b/letta/client/client.py
@@ -205,6 +205,7 @@ class AbstractClient(object):
         self,
         id: str,
         name: Optional[str] = None,
+        description: Optional[str] = None,
         func: Optional[Callable] = None,
         tags: Optional[List[str]] = None,
     ) -> Tool:
@@ -1302,6 +1303,7 @@ class RESTClient(AbstractClient):
         self,
         id: str,
         name: Optional[str] = None,
+        description: Optional[str] = None,
         func: Optional[Callable] = None,
         tags: Optional[List[str]] = None,
     ) -> Tool:
@@ -1324,7 +1326,7 @@ class RESTClient(AbstractClient):
 
         source_type = "python"
 
-        request = ToolUpdate(source_type=source_type, source_code=source_code, tags=tags, name=name)
+        request = ToolUpdate(description=description, source_type=source_type, source_code=source_code, tags=tags, name=name)
         response = requests.patch(f"{self.base_url}/{self.api_prefix}/tools/{id}", json=request.model_dump(), headers=self.headers)
         if response.status_code != 200:
             raise ValueError(f"Failed to update tool: {response.text}")
@@ -2233,7 +2235,6 @@ class LocalClient(AbstractClient):
     def load_langchain_tool(self, langchain_tool: "LangChainBaseTool", additional_imports_module_attr_map: dict[str, str] = None) -> Tool:
         tool_create = ToolCreate.from_langchain(
             langchain_tool=langchain_tool,
-            organization_id=self.org_id,
             additional_imports_module_attr_map=additional_imports_module_attr_map,
         )
         return self.server.tool_manager.create_or_update_tool(tool_create, actor=self.user)
@@ -2242,12 +2243,11 @@ class LocalClient(AbstractClient):
         tool_create = ToolCreate.from_crewai(
             crewai_tool=crewai_tool,
             additional_imports_module_attr_map=additional_imports_module_attr_map,
-            organization_id=self.org_id,
         )
         return self.server.tool_manager.create_or_update_tool(tool_create, actor=self.user)
 
     def load_composio_tool(self, action: "ActionType") -> Tool:
-        tool_create = ToolCreate.from_composio(action=action, organization_id=self.org_id)
+        tool_create = ToolCreate.from_composio(action=action)
         return self.server.tool_manager.create_or_update_tool(tool_create, actor=self.user)
 
     # TODO: Use the above function `add_tool` here as there is duplicate logic
@@ -2257,7 +2257,6 @@ class LocalClient(AbstractClient):
         name: Optional[str] = None,
         update: Optional[bool] = True,  # TODO: actually use this
         tags: Optional[List[str]] = None,
-        terminal: Optional[bool] = False,
     ) -> Tool:
         """
         Create a tool. This stores the source code of function on the server, so that the server can execute the function and generate an OpenAI JSON schemas for it when using with an agent.
@@ -2267,7 +2266,6 @@ class LocalClient(AbstractClient):
             name: (str): Name of the tool (must be unique per-user.)
             tags (Optional[List[str]], optional): Tags for the tool. Defaults to None.
             update (bool, optional): Update the tool if it already exists. Defaults to True.
-            terminal (bool, optional): Whether the tool is a terminal tool (no more agent steps). Defaults to False.
 
         Returns:
             tool (Tool): The created tool.
@@ -2287,7 +2285,6 @@ class LocalClient(AbstractClient):
                 source_code=source_code,
                 name=name,
                 tags=tags,
-                terminal=terminal,
             ),
             actor=self.user,
         )
@@ -2296,6 +2293,7 @@ class LocalClient(AbstractClient):
         self,
         id: str,
         name: Optional[str] = None,
+        description: Optional[str] = None,
         func: Optional[callable] = None,
         tags: Optional[List[str]] = None,
     ) -> Tool:
@@ -2316,6 +2314,7 @@ class LocalClient(AbstractClient):
             "source_code": parse_source_code(func) if func else None,
             "tags": tags,
             "name": name,
+            "description": description,
         }
 
         # Filter out any None values from the dictionary
diff --git a/letta/functions/functions.py b/letta/functions/functions.py
index 422cf72b..cc2fc358 100644
--- a/letta/functions/functions.py
+++ b/letta/functions/functions.py
@@ -7,10 +7,9 @@ from typing import Optional
 
 from letta.constants import CLI_WARNING_PREFIX
 from letta.functions.schema_generator import generate_schema
-from letta.schemas.tool import ToolCreate
 
 
-def derive_openai_json_schema(tool_create: ToolCreate) -> dict:
+def derive_openai_json_schema(source_code: str, name: Optional[str]) -> dict:
     # auto-generate openai schema
     try:
         # Define a custom environment with necessary imports
@@ -19,14 +18,14 @@ def derive_openai_json_schema(tool_create: ToolCreate) -> dict:
         }
 
         env.update(globals())
-        exec(tool_create.source_code, env)
+        exec(source_code, env)
 
         # get available functions
         functions = [f for f in env if callable(env[f])]
 
         # TODO: not sure if this always works
         func = env[functions[-1]]
-        json_schema = generate_schema(func, terminal=tool_create.terminal, name=tool_create.name)
+        json_schema = generate_schema(func, name=name)
         return json_schema
     except Exception as e:
         raise RuntimeError(f"Failed to execute source code: {e}")
@@ -51,7 +50,7 @@ def load_function_set(module: ModuleType) -> dict:
             if attr_name in function_dict:
                 raise ValueError(f"Found a duplicate of function name '{attr_name}'")
 
-            generated_schema = generate_schema(attr, terminal=False)
+            generated_schema = generate_schema(attr)
             function_dict[attr_name] = {
                 "module": inspect.getsource(module),
                 "python_function": attr,
diff --git a/letta/functions/schema_generator.py b/letta/functions/schema_generator.py
index 2abb0f4b..ace26cf2 100644
--- a/letta/functions/schema_generator.py
+++ b/letta/functions/schema_generator.py
@@ -74,7 +74,7 @@ def pydantic_model_to_open_ai(model):
     }
 
 
-def generate_schema(function, terminal: Optional[bool], name: Optional[str] = None, description: Optional[str] = None) -> dict:
+def generate_schema(function, name: Optional[str] = None, description: Optional[str] = None) -> dict:
     # Get the signature of the function
     sig = inspect.signature(function)
 
@@ -128,7 +128,7 @@ def generate_schema(function, terminal: Optional[bool], name: Optional[str] = No
 
     # append the heartbeat
     # TODO: don't hard-code
-    if function.__name__ not in ["send_message", "pause_heartbeats"] and not terminal:
+    if function.__name__ not in ["send_message", "pause_heartbeats"]:
         schema["parameters"]["properties"]["request_heartbeat"] = {
             "type": "boolean",
             "description": "Request an immediate heartbeat after function execution. Set to `True` if you want to send a follow-up message or run a follow-up function.",
diff --git a/letta/orm/tool.py b/letta/orm/tool.py
index b8f2ba1d..acf2761b 100644
--- a/letta/orm/tool.py
+++ b/letta/orm/tool.py
@@ -38,8 +38,5 @@ class Tool(SqlalchemyBase, OrganizationMixin):
         String, nullable=True, doc="the module path from which this tool was derived in the codebase."
     )
 
-    # TODO: add terminal here eventually
-    # This was an intentional decision by Sarah
-
     # relationships
     organization: Mapped["Organization"] = relationship("Organization", back_populates="tools", lazy="selectin")
diff --git a/letta/schemas/tool.py b/letta/schemas/tool.py
index 9f54f25b..effbd792 100644
--- a/letta/schemas/tool.py
+++ b/letta/schemas/tool.py
@@ -10,7 +10,6 @@ from letta.functions.helpers import (
 from letta.functions.schema_generator import generate_schema_from_args_schema
 from letta.schemas.letta_base import LettaBase
 from letta.schemas.openai.chat_completions import ToolCall
-from letta.services.organization_manager import OrganizationManager
 
 
 class BaseTool(LettaBase):
@@ -69,10 +68,9 @@ class ToolCreate(LettaBase):
     json_schema: Optional[Dict] = Field(
         None, description="The JSON schema of the function (auto-generated from source_code if not provided)"
     )
-    terminal: Optional[bool] = Field(None, description="Whether the tool is a terminal tool (allow requesting heartbeats).")
 
     @classmethod
-    def from_composio(cls, action: "ActionType", organization_id: str = OrganizationManager.DEFAULT_ORG_ID) -> "ToolCreate":
+    def from_composio(cls, action: "ActionType") -> "ToolCreate":
         """
         Class method to create an instance of Letta-compatible Composio Tool.
         Check https://docs.composio.dev/introduction/intro/overview to look at options for from_composio
@@ -114,7 +112,6 @@ class ToolCreate(LettaBase):
         cls,
         langchain_tool: "LangChainBaseTool",
         additional_imports_module_attr_map: dict[str, str] = None,
-        organization_id: str = OrganizationManager.DEFAULT_ORG_ID,
     ) -> "ToolCreate":
         """
         Class method to create an instance of Tool from a Langchain tool (must be from langchain_community.tools).
@@ -147,7 +144,6 @@ class ToolCreate(LettaBase):
         cls,
         crewai_tool: "CrewAIBaseTool",
         additional_imports_module_attr_map: dict[str, str] = None,
-        organization_id: str = OrganizationManager.DEFAULT_ORG_ID,
     ) -> "ToolCreate":
         """
         Class method to create an instance of Tool from a crewAI BaseTool object.
@@ -212,5 +208,7 @@ class ToolUpdate(LettaBase):
     tags: Optional[List[str]] = Field(None, description="Metadata tags.")
     module: Optional[str] = Field(None, description="The source code of the function.")
     source_code: Optional[str] = Field(None, description="The source code of the function.")
-    json_schema: Optional[Dict] = Field(None, description="The JSON schema of the function.")
     source_type: Optional[str] = Field(None, description="The type of the source code.")
+    json_schema: Optional[Dict] = Field(
+        None, description="The JSON schema of the function (auto-generated from source_code if not provided)"
+    )
diff --git a/letta/server/rest_api/admin/__init__.py b/letta/server/rest_api/admin/__init__.py
deleted file mode 100644
index e69de29b..00000000
diff --git a/letta/server/rest_api/admin/agents.py b/letta/server/rest_api/admin/agents.py
deleted file mode 100644
index 21812770..00000000
--- a/letta/server/rest_api/admin/agents.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from typing import List
-
-from fastapi import APIRouter
-
-from letta.schemas.agent import AgentState
-from letta.server.rest_api.interface import QueuingInterface
-from letta.server.server import SyncServer
-
-router = APIRouter()
-
-
-def setup_agents_admin_router(server: SyncServer, interface: QueuingInterface):
-    @router.get("/agents", tags=["agents"], response_model=List[AgentState])
-    def get_all_agents():
-        """
-        Get a list of all agents in the database
-        """
-        interface.clear()
-        return server.list_agents()
-
-    return router
diff --git a/letta/server/rest_api/admin/tools.py b/letta/server/rest_api/admin/tools.py
deleted file mode 100644
index e857b79e..00000000
--- a/letta/server/rest_api/admin/tools.py
+++ /dev/null
@@ -1,82 +0,0 @@
-from typing import List, Literal, Optional
-
-from fastapi import APIRouter, Body, HTTPException
-from pydantic import BaseModel, Field
-
-from letta.schemas.tool import Tool as ToolModel  # TODO: modify
-from letta.server.rest_api.interface import QueuingInterface
-from letta.server.server import SyncServer
-
-router = APIRouter()
-
-
-class ListToolsResponse(BaseModel):
-    tools: List[ToolModel] = Field(..., description="List of tools (functions).")
-
-
-class CreateToolRequest(BaseModel):
-    json_schema: dict = Field(..., description="JSON schema of the tool.")
-    source_code: str = Field(..., description="The source code of the function.")
-    source_type: Optional[Literal["python"]] = Field(None, description="The type of the source code.")
-    tags: Optional[List[str]] = Field(None, description="Metadata tags.")
-
-
-class CreateToolResponse(BaseModel):
-    tool: ToolModel = Field(..., description="Information about the newly created tool.")
-
-
-def setup_tools_index_router(server: SyncServer, interface: QueuingInterface):
-
-    @router.delete("/tools/{tool_name}", tags=["tools"])
-    async def delete_tool(
-        tool_name: str,
-        # user_id: uuid.UUID = Depends(get_current_user_with_server), # TODO: add back when user-specific
-    ):
-        """
-        Delete a tool by name
-        """
-        # Clear the interface
-        interface.clear()
-        # tool = server.ms.delete_tool(user_id=user_id, tool_name=tool_name) TODO: add back when user-specific
-        server.ms.delete_tool(name=tool_name, user_id=None)
-
-    @router.get("/tools/{tool_name}", tags=["tools"], response_model=ToolModel)
-    async def get_tool(tool_name: str):
-        """
-        Get a tool by name
-        """
-        # Clear the interface
-        interface.clear()
-        # tool = server.ms.get_tool(user_id=user_id, tool_name=tool_name) TODO: add back when user-specific
-        tool = server.ms.get_tool(tool_name=tool_name, user_id=None)
-        if tool is None:
-            # return 404 error
-            raise HTTPException(status_code=404, detail=f"Tool with name {tool_name} not found.")
-        return tool
-
-    @router.get("/tools", tags=["tools"], response_model=ListToolsResponse)
-    async def list_all_tools():
-        """
-        Get a list of all tools available to agents created by a user
-        """
-        # Clear the interface
-        interface.clear()
-        # tools = server.ms.list_tools(user_id=user_id) TODO: add back when user-specific
-        tools = server.ms.list_tools(user_id=None)
-        return ListToolsResponse(tools=tools)
-
-    @router.post("/tools", tags=["tools"], response_model=ToolModel)
-    async def create_tool(
-        request: CreateToolRequest = Body(...),
-    ):
-        """
-        Create a new tool
-        """
-        try:
-            return server.create_tool(
-                json_schema=request.json_schema, source_code=request.source_code, source_type=request.source_type, tags=request.tags
-            )
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"Failed to create tool: {e}")
-
-    return router
diff --git a/letta/server/rest_api/admin/users.py b/letta/server/rest_api/admin/users.py
deleted file mode 100644
index 02fd91aa..00000000
--- a/letta/server/rest_api/admin/users.py
+++ /dev/null
@@ -1,98 +0,0 @@
-from typing import List, Optional
-
-from fastapi import APIRouter, Body, HTTPException, Query
-
-from letta.schemas.api_key import APIKey, APIKeyCreate
-from letta.schemas.user import User, UserCreate
-from letta.server.rest_api.interface import QueuingInterface
-from letta.server.server import SyncServer
-
-router = APIRouter()
-
-
-def setup_admin_router(server: SyncServer, interface: QueuingInterface):
-    @router.get("/users", tags=["admin"], response_model=List[User])
-    def get_all_users(cursor: Optional[str] = Query(None), limit: Optional[int] = Query(50)):
-        """
-        Get a list of all users in the database
-        """
-        try:
-            # TODO: make this call a server function
-            _, users = server.ms.get_all_users(cursor=cursor, limit=limit)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-        return users
-
-    @router.post("/users", tags=["admin"], response_model=User)
-    def create_user(request: UserCreate = Body(...)):
-        """
-        Create a new user in the database
-        """
-        try:
-            user = server.user_manager.create_user(request)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-        return user
-
-    @router.delete("/users", tags=["admin"], response_model=User)
-    def delete_user(
-        user_id: str = Query(..., description="The user_id key to be deleted."),
-    ):
-        # TODO make a soft deletion, instead of a hard deletion
-        try:
-            user = server.ms.get_user(user_id=user_id)
-            if user is None:
-                raise HTTPException(status_code=404, detail=f"User does not exist")
-            server.ms.delete_user(user_id=user_id)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-        return user
-
-    @router.post("/users/keys", tags=["admin"], response_model=APIKey)
-    def create_new_api_key(request: APIKeyCreate = Body(...)):
-        """
-        Create a new API key for a user
-        """
-        try:
-            api_key = server.create_api_key(request)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-        return api_key
-
-    @router.get("/users/keys", tags=["admin"], response_model=List[APIKey])
-    def get_api_keys(
-        user_id: str = Query(..., description="The unique identifier of the user."),
-    ):
-        """
-        Get a list of all API keys for a user
-        """
-        try:
-            if server.ms.get_user(user_id=user_id) is None:
-                raise HTTPException(status_code=404, detail=f"User does not exist")
-            api_keys = server.ms.get_all_api_keys_for_user(user_id=user_id)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-        return api_keys
-
-    @router.delete("/users/keys", tags=["admin"], response_model=APIKey)
-    def delete_api_key(
-        api_key: str = Query(..., description="The API key to be deleted."),
-    ):
-        try:
-            return server.delete_api_key(api_key)
-        except HTTPException:
-            raise
-        except Exception as e:
-            raise HTTPException(status_code=500, detail=f"{e}")
-
-    return router
diff --git a/letta/server/server.py b/letta/server/server.py
index ba1b8d75..83ba2a96 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -820,7 +820,7 @@ class SyncServer(Server):
                     continue
                 source_code = parse_source_code(func)
                 # memory functions are not terminal
-                json_schema = generate_schema(func, terminal=False, name=func_name)
+                json_schema = generate_schema(func, name=func_name)
                 source_type = "python"
                 tags = ["memory", "memgpt-base"]
                 tool = self.tool_manager.create_or_update_tool(
diff --git a/letta/server/static_files/assets/index-d6b3669a.js b/letta/server/static_files/assets/index-b82c8d7c.js
similarity index 99%
rename from letta/server/static_files/assets/index-d6b3669a.js
rename to letta/server/static_files/assets/index-b82c8d7c.js
index ec3fb44c..e9c97380 100644
--- a/letta/server/static_files/assets/index-d6b3669a.js
+++ b/letta/server/static_files/assets/index-b82c8d7c.js
@@ -201,7 +201,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
 `});++r<e.length;)r&&n.push({type:"text",value:`
 `}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:`
 `}),n}function k3(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function C3(e,t){const n=Zxe(e,t),r=n.one(e,void 0),a=Kxe(n),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&o.children.push({type:"text",value:`
-`},a),o}function t1e(e,t){return e&&"run"in e?async function(n,r){const a=C3(n,{file:r,...t});await e.run(a,r)}:function(n,r){return C3(n,{file:r,...t||e})}}function _3(e){if(e)throw e}var Xp=Object.prototype.hasOwnProperty,zz=Object.prototype.toString,A3=Object.defineProperty,T3=Object.getOwnPropertyDescriptor,R3=function(t){return typeof Array.isArray=="function"?Array.isArray(t):zz.call(t)==="[object Array]"},N3=function(t){if(!t||zz.call(t)!=="[object Object]")return!1;var n=Xp.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&Xp.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||Xp.call(t,a)},I3=function(t,n){A3&&n.name==="__proto__"?A3(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},O3=function(t,n){if(n==="__proto__")if(Xp.call(t,n)){if(T3)return T3(t,n).value}else return;return t[n]},n1e=function e(){var t,n,r,a,o,i,s=arguments[0],l=1,c=arguments.length,u=!1;for(typeof s=="boolean"&&(u=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<c;++l)if(t=arguments[l],t!=null)for(n in t)r=O3(s,n),a=O3(t,n),s!==a&&(u&&a&&(N3(a)||(o=R3(a)))?(o?(o=!1,i=r&&R3(r)?r:[]):i=r&&N3(r)?r:{},I3(s,{name:n,newValue:e(u,i,a)})):typeof a<"u"&&I3(s,{name:n,newValue:a}));return s};const hx=Tc(n1e);function zk(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function r1e(){const e=[],t={run:n,use:r};return t;function n(...a){let o=-1;const i=a.pop();if(typeof i!="function")throw new TypeError("Expected function as last argument, not "+i);s(null,...a);function s(l,...c){const u=e[++o];let d=-1;if(l){i(l);return}for(;++d<a.length;)(c[d]===null||c[d]===void 0)&&(c[d]=a[d]);a=c,u?a1e(u,s)(...c):i(null,...c)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function a1e(e,t){let n;return r;function r(...i){const s=e.length>i.length;let l;s&&i.push(a);try{l=e.apply(this,i)}catch(c){const u=c;if(s&&n)throw u;return a(u)}s||(l&&l.then&&typeof l.then=="function"?l.then(o,a):l instanceof Error?a(l):o(l))}function a(i,...s){n||(n=!0,t(i,...s))}function o(i){a(null,i)}}const ka={basename:o1e,dirname:i1e,extname:s1e,join:l1e,sep:"/"};function o1e(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');_f(e);let n=0,r=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){n=a+1;break}}else r<0&&(o=!0,r=a+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let i=-1,s=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){n=a+1;break}}else i<0&&(o=!0,i=a+1),s>-1&&(e.codePointAt(a)===t.codePointAt(s--)?s<0&&(r=a):(s=-1,r=i));return n===r?r=i:r<0&&(r=e.length),e.slice(n,r)}function i1e(e){if(_f(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function s1e(e){_f(e);let t=e.length,n=-1,r=0,a=-1,o=0,i;for(;t--;){const s=e.codePointAt(t);if(s===47){if(i){r=t+1;break}continue}n<0&&(i=!0,n=t+1),s===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||n<0||o===0||o===1&&a===n-1&&a===r+1?"":e.slice(a,n)}function l1e(...e){let t=-1,n;for(;++t<e.length;)_f(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":c1e(n)}function c1e(e){_f(e);const t=e.codePointAt(0)===47;let n=u1e(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function u1e(e,t){let n="",r=0,a=-1,o=0,i=-1,s,l;for(;++i<=e.length;){if(i<e.length)s=e.codePointAt(i);else{if(s===47)break;s=47}if(s===47){if(!(a===i-1||o===1))if(a!==i-1&&o===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),a=i,o=0;continue}}else if(n.length>0){n="",r=0,a=i,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(a+1,i):n=e.slice(a+1,i),r=i-a-1;a=i,o=0}else s===46&&o>-1?o++:o=-1}return n}function _f(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const d1e={cwd:f1e};function f1e(){return"/"}function Uk(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function p1e(e){if(typeof e=="string")e=new URL(e);else if(!Uk(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return g1e(e)}function g1e(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const bx=["history","path","basename","stem","extname","dirname"];class Uz{constructor(t){let n;t?Uk(t)?n={path:t}:typeof t=="string"||m1e(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":d1e.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<bx.length;){const o=bx[r];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let a;for(a in n)bx.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?ka.basename(this.path):void 0}set basename(t){vx(t,"basename"),yx(t,"basename"),this.path=ka.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?ka.dirname(this.path):void 0}set dirname(t){D3(this.basename,"dirname"),this.path=ka.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?ka.extname(this.path):void 0}set extname(t){if(yx(t,"extname"),D3(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ka.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Uk(t)&&(t=p1e(t)),vx(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?ka.basename(this.path,this.extname):void 0}set stem(t){vx(t,"stem"),yx(t,"stem"),this.path=ka.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const a=this.message(t,n,r);throw a.fatal=!0,a}info(t,n,r){const a=this.message(t,n,r);return a.fatal=void 0,a}message(t,n,r){const a=new Bn(t,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function yx(e,t){if(e&&e.includes(ka.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+ka.sep+"`")}function vx(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function D3(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function m1e(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const h1e=function(e){const r=this.constructor.prototype,a=r[e],o=function(){return a.apply(o,arguments)};return Object.setPrototypeOf(o,r),o},b1e={}.hasOwnProperty;class GA extends h1e{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=r1e()}copy(){const t=new GA;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(hx(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Ex("data",this.frozen),this.namespace[t]=n,this):b1e.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ex("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(t,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=bp(t),r=this.parser||this.Parser;return Sx("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Sx("process",this.parser||this.Parser),wx("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(o,i){const s=bp(t),l=r.parse(s);r.run(l,s,function(u,d,g){if(u||!d||!g)return c(u);const m=d,y=r.stringify(m,g);S1e(y)?g.value=y:g.result=y,c(u,g)});function c(u,d){u||!d?i(u):o?o(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),Sx("processSync",this.parser||this.Parser),wx("processSync",this.compiler||this.Compiler),this.process(t,a),M3("processSync","process",n),r;function a(o,i){n=!0,_3(o),r=i}}run(t,n,r){L3(t),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?o(void 0,r):new Promise(o);function o(i,s){const l=bp(n);a.run(t,l,c);function c(u,d,g){const m=d||t;u?s(u):i?i(m):r(void 0,m,g)}}}runSync(t,n){let r=!1,a;return this.run(t,n,o),M3("runSync","run",r),a;function o(i,s){_3(i),a=s,r=!0}}stringify(t,n){this.freeze();const r=bp(n),a=this.compiler||this.Compiler;return wx("stringify",a),L3(t),a(t,r)}use(t,...n){const r=this.attachers,a=this.namespace;if(Ex("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?s(t):i(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(c){if(typeof c=="function")l(c,[]);else if(typeof c=="object")if(Array.isArray(c)){const[u,...d]=c;l(u,d)}else i(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function i(c){if(!("plugins"in c)&&!("settings"in c))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");s(c.plugins),c.settings&&(a.settings=hx(!0,a.settings,c.settings))}function s(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){const d=c[u];o(d)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function l(c,u){let d=-1,g=-1;for(;++d<r.length;)if(r[d][0]===c){g=d;break}if(g===-1)r.push([c,...u]);else if(u.length>0){let[m,...y]=u;const b=r[g][1];zk(b)&&zk(m)&&(m=hx(!0,b,m)),r[g]=[c,m,...y]}}}}const y1e=new GA().freeze();function Sx(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wx(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ex(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function L3(e){if(!zk(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function M3(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function bp(e){return v1e(e)?e:new Uz(e)}function v1e(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function S1e(e){return typeof e=="string"||w1e(e)}function w1e(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const E1e="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",P3=[],$3={allowDangerousHtml:!0},x1e=/^(https?|ircs?|mailto|xmpp)$/i,k1e=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function C1e(e){const t=e.allowedElements,n=e.allowElement,r=e.children||"",a=e.className,o=e.components,i=e.disallowedElements,s=e.rehypePlugins||P3,l=e.remarkPlugins||P3,c=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...$3}:$3,u=e.skipHtml,d=e.unwrapDisallowed,g=e.urlTransform||_1e,m=y1e().use(mxe).use(l).use(t1e,c).use(s),y=new Uz;typeof r=="string"&&(y.value=r);for(const h of k1e)Object.hasOwn(e,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+E1e+h.id,void 0);const b=m.parse(y);let w=m.runSync(b,y);return a&&(w={type:"element",tagName:"div",properties:{className:a},children:w.type==="root"?w.children:[w]}),sA(w,v),EEe(w,{Fragment:f.Fragment,components:o,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function v(h,S,E){if(h.type==="raw"&&E&&typeof S=="number")return u?E.children.splice(S,1):E.children[S]={type:"text",value:h.value},S;if(h.type==="element"){let k;for(k in mx)if(Object.hasOwn(mx,k)&&Object.hasOwn(h.properties,k)){const x=h.properties[k],C=mx[k];(C===null||C.includes(h.tagName))&&(h.properties[k]=g(String(x||""),k,h))}}if(h.type==="element"){let k=t?!t.includes(h.tagName):i?i.includes(h.tagName):!1;if(!k&&n&&typeof S=="number"&&(k=!n(h,S,E)),k&&E&&typeof S=="number")return d&&h.children?E.children.splice(S,1,...h.children):E.children.splice(S,1),S}}}function _1e(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return t<0||a>-1&&t>a||n>-1&&t>n||r>-1&&t>r||x1e.test(e.slice(0,t))?e:""}const A1e=p.memo(C1e,(e,t)=>e.children===t.children&&e.className===t.className),Bz=({message:e,className:t})=>f.jsx(A1e,{className:ee("prose-sm whitespace-pre-wrap break-words prose-p:m-0 prose-p:leading-relaxed prose-pre:p-0 prose-li:list-disc",t),remarkPlugins:[ife,bfe,Ile],components:{p({children:n}){return f.jsx("p",{children:n})},code({node:n,className:r,children:a,...o}){if(a.length){if(a[0]=="▍")return f.jsx("span",{className:"mt-1 animate-pulse cursor-default",children:"▍"});a[0]=a[0].replace("`▍`","▍")}const i=/language-(\w+)/.exec(r||"");return inline?f.jsx("code",{className:r,...o,children:a}):f.jsx(mz,{language:i&&i[1]||"",value:String(a).replace(/\n$/,""),...o},Math.random())}},children:e}),T1e=e=>f.jsx("div",{className:ee("flex min-h-8 max-w-lg items-end justify-start pl-10",e.className),children:f.jsx(Bz,{message:e.message,className:"whitespace-pre-wrap text-sm"})}),R1e=e=>f.jsxs(E_,{className:"w-fit max-w-lg p-2 text-xs [&>svg]:left-2.5 [&>svg]:top-2.5",variant:"destructive",children:[f.jsx(yq,{className:"h-4 w-4"}),f.jsx(z6,{children:"Something went wrong..."}),f.jsx(U6,{className:"text-xs",children:e.message})]}),N1e=({id:e,message:t})=>f.jsx("pre",{className:mie("mb-2 ml-8 w-fit max-w-xl overflow-x-scroll whitespace-pre-line rounded-lg border bg-muted p-2 text-xs font-normal text-muted-foreground"),children:t}),I1e=({message:e})=>f.jsx("p",{className:Tt("relative mb-2 ml-6 w-fit max-w-lg rounded-2xl border border-white bg-muted px-4 py-2 text-sm italic"),children:e}),O1e=({id:e,date:t})=>f.jsxs("span",{className:"!-mt-4 max-w-xl pr-6 text-right text-xs uppercase tracking-tight text-muted-foreground",children:["Message Receipt from ",t?Bs(t,"M/d/yy, h:mm a"):"Unknown"]}),D1e=()=>f.jsx("div",{className:"flex items-end justify-end",children:f.jsx("p",{className:"mb-2 w-fit max-w-lg rounded-2xl rounded-br-none border border-white bg-muted px-4 py-2 text-sm italic",children:"First login"})}),L1e=e=>f.jsx("div",{className:`${e.className} flex items-end justify-end`,children:f.jsxs("div",{className:"order-2 mx-2 flex max-w-lg flex-col items-end space-y-1 text-sm",children:[f.jsx("div",{className:"pr-1.5 text-xs text-muted-foreground",children:Bs(e.date,"MMM d yy, h:mm a")}),f.jsx(Bz,{message:e.message,className:"min-h-8 rounded-2xl rounded-br-none bg-white px-5 py-3 text-black"})]})}),M1e=({type:e,message:t,date:n,id:r},a,o=!0,i=!0,s=!0)=>{const l=e+t+n+r;if(e==="login")return f.jsx(D1e,{},l);if(e==="user")return f.jsx(L1e,{id:r,date:n,message:t??""},l);if(e==="error")return f.jsx(R1e,{date:n,message:t??""},l);if(e==="assistant")return f.jsx(T1e,{id:r,date:n,message:t??""},l);if(s&&e==="message-receipt")return f.jsx(O1e,{date:n},l);if(i&&e==="function-call")return f.jsx(N1e,{id:r,message:t},l);if(o&&e==="internal-monologue")return f.jsx(I1e,{message:t},l)};class sl extends Error{constructor(t,n){super(t+" at position "+n),this.position=n}}const yp=92,xx=47,P1e=42,F3=123,vp=125,j3=91,Sp=93,$1e=40,F1e=41,j1e=32,WA=10,Hz=9,Vz=13,z1e=8,U1e=12,sm=34,z3=43,U3=45,qz=39,Gz=48,Wz=57,Hi=44,wp=46,B1e=58,H1e=59,V1e=65,q1e=97,G1e=69,W1e=101,K1e=70,Y1e=102,Z1e=160,X1e=8192,Q1e=8202,J1e=8239,eke=8287,tke=12288,nke=8220,rke=8221,ake=8216,oke=8217,ike=96,ske=180;function lke(e){return e>=Gz&&e<=Wz||e>=V1e&&e<=K1e||e>=q1e&&e<=Y1e}function Vi(e){return e>=Gz&&e<=Wz}function cke(e){return e>=32&&e<=1114111}function ml(e){return uke.test(e)}const uke=/^[,:[\]/{}()\n+]$/;function dke(e){return ml(e)&&e!=="/"}function B3(e){return fke.test(e)||e&&Qp(e.charCodeAt(0))}const fke=/^[[{\w-]$/;function pke(e){return e===WA||e===Vz||e===Hz||e===z1e||e===U1e}function Ol(e){return e===j1e||e===WA||e===Hz||e===Vz}function gke(e){return e===Z1e||e>=X1e&&e<=Q1e||e===J1e||e===eke||e===tke}function Qp(e){return Kz(e)||Bk(e)}function Kz(e){return e===sm||e===nke||e===rke}function H3(e){return e===sm}function Bk(e){return e===qz||e===ake||e===oke||e===ike||e===ske}function V3(e){return e===qz}function yu(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const r=e.lastIndexOf(t);return r!==-1?e.substring(0,r)+(n?"":e.substring(r+1)):e}function Ea(e,t){let n=e.length;if(!Ol(e.charCodeAt(n-1)))return e+t;for(;Ol(e.charCodeAt(n-1));)n--;return e.substring(0,n)+t+e.substring(n)}function mke(e,t,n){return e.substring(0,t)+e.substring(t+n)}function hke(e){return/[,\n][ \t\r]*$/.test(e)}function bke(e){return/^\w+$/.test(e)}const yke={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","	":"\\t"},vke={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
+`},a),o}function t1e(e,t){return e&&"run"in e?async function(n,r){const a=C3(n,{file:r,...t});await e.run(a,r)}:function(n,r){return C3(n,{file:r,...t||e})}}function _3(e){if(e)throw e}var Xp=Object.prototype.hasOwnProperty,zz=Object.prototype.toString,A3=Object.defineProperty,T3=Object.getOwnPropertyDescriptor,R3=function(t){return typeof Array.isArray=="function"?Array.isArray(t):zz.call(t)==="[object Array]"},N3=function(t){if(!t||zz.call(t)!=="[object Object]")return!1;var n=Xp.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&Xp.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||Xp.call(t,a)},I3=function(t,n){A3&&n.name==="__proto__"?A3(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},O3=function(t,n){if(n==="__proto__")if(Xp.call(t,n)){if(T3)return T3(t,n).value}else return;return t[n]},n1e=function e(){var t,n,r,a,o,i,s=arguments[0],l=1,c=arguments.length,u=!1;for(typeof s=="boolean"&&(u=s,s=arguments[1]||{},l=2),(s==null||typeof s!="object"&&typeof s!="function")&&(s={});l<c;++l)if(t=arguments[l],t!=null)for(n in t)r=O3(s,n),a=O3(t,n),s!==a&&(u&&a&&(N3(a)||(o=R3(a)))?(o?(o=!1,i=r&&R3(r)?r:[]):i=r&&N3(r)?r:{},I3(s,{name:n,newValue:e(u,i,a)})):typeof a<"u"&&I3(s,{name:n,newValue:a}));return s};const hx=Tc(n1e);function zk(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function r1e(){const e=[],t={run:n,use:r};return t;function n(...a){let o=-1;const i=a.pop();if(typeof i!="function")throw new TypeError("Expected function as last argument, not "+i);s(null,...a);function s(l,...c){const u=e[++o];let d=-1;if(l){i(l);return}for(;++d<a.length;)(c[d]===null||c[d]===void 0)&&(c[d]=a[d]);a=c,u?a1e(u,s)(...c):i(null,...c)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function a1e(e,t){let n;return r;function r(...i){const s=e.length>i.length;let l;s&&i.push(a);try{l=e.apply(this,i)}catch(c){const u=c;if(s&&n)throw u;return a(u)}s||(l&&l.then&&typeof l.then=="function"?l.then(o,a):l instanceof Error?a(l):o(l))}function a(i,...s){n||(n=!0,t(i,...s))}function o(i){a(null,i)}}const ka={basename:o1e,dirname:i1e,extname:s1e,join:l1e,sep:"/"};function o1e(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');_f(e);let n=0,r=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){n=a+1;break}}else r<0&&(o=!0,r=a+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let i=-1,s=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){n=a+1;break}}else i<0&&(o=!0,i=a+1),s>-1&&(e.codePointAt(a)===t.codePointAt(s--)?s<0&&(r=a):(s=-1,r=i));return n===r?r=i:r<0&&(r=e.length),e.slice(n,r)}function i1e(e){if(_f(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function s1e(e){_f(e);let t=e.length,n=-1,r=0,a=-1,o=0,i;for(;t--;){const s=e.codePointAt(t);if(s===47){if(i){r=t+1;break}continue}n<0&&(i=!0,n=t+1),s===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||n<0||o===0||o===1&&a===n-1&&a===r+1?"":e.slice(a,n)}function l1e(...e){let t=-1,n;for(;++t<e.length;)_f(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":c1e(n)}function c1e(e){_f(e);const t=e.codePointAt(0)===47;let n=u1e(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function u1e(e,t){let n="",r=0,a=-1,o=0,i=-1,s,l;for(;++i<=e.length;){if(i<e.length)s=e.codePointAt(i);else{if(s===47)break;s=47}if(s===47){if(!(a===i-1||o===1))if(a!==i-1&&o===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),a=i,o=0;continue}}else if(n.length>0){n="",r=0,a=i,o=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(a+1,i):n=e.slice(a+1,i),r=i-a-1;a=i,o=0}else s===46&&o>-1?o++:o=-1}return n}function _f(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const d1e={cwd:f1e};function f1e(){return"/"}function Uk(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function p1e(e){if(typeof e=="string")e=new URL(e);else if(!Uk(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return g1e(e)}function g1e(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const bx=["history","path","basename","stem","extname","dirname"];class Uz{constructor(t){let n;t?Uk(t)?n={path:t}:typeof t=="string"||m1e(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":d1e.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<bx.length;){const o=bx[r];o in n&&n[o]!==void 0&&n[o]!==null&&(this[o]=o==="history"?[...n[o]]:n[o])}let a;for(a in n)bx.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?ka.basename(this.path):void 0}set basename(t){vx(t,"basename"),yx(t,"basename"),this.path=ka.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?ka.dirname(this.path):void 0}set dirname(t){D3(this.basename,"dirname"),this.path=ka.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?ka.extname(this.path):void 0}set extname(t){if(yx(t,"extname"),D3(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ka.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Uk(t)&&(t=p1e(t)),vx(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?ka.basename(this.path,this.extname):void 0}set stem(t){vx(t,"stem"),yx(t,"stem"),this.path=ka.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const a=this.message(t,n,r);throw a.fatal=!0,a}info(t,n,r){const a=this.message(t,n,r);return a.fatal=void 0,a}message(t,n,r){const a=new Bn(t,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function yx(e,t){if(e&&e.includes(ka.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+ka.sep+"`")}function vx(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function D3(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function m1e(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const h1e=function(e){const r=this.constructor.prototype,a=r[e],o=function(){return a.apply(o,arguments)};return Object.setPrototypeOf(o,r),o},b1e={}.hasOwnProperty;class GA extends h1e{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=r1e()}copy(){const t=new GA;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(hx(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Ex("data",this.frozen),this.namespace[t]=n,this):b1e.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ex("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(t,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=bp(t),r=this.parser||this.Parser;return Sx("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),Sx("process",this.parser||this.Parser),wx("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(o,i){const s=bp(t),l=r.parse(s);r.run(l,s,function(u,d,g){if(u||!d||!g)return c(u);const m=d,y=r.stringify(m,g);S1e(y)?g.value=y:g.result=y,c(u,g)});function c(u,d){u||!d?i(u):o?o(d):n(void 0,d)}}}processSync(t){let n=!1,r;return this.freeze(),Sx("processSync",this.parser||this.Parser),wx("processSync",this.compiler||this.Compiler),this.process(t,a),M3("processSync","process",n),r;function a(o,i){n=!0,_3(o),r=i}}run(t,n,r){L3(t),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?o(void 0,r):new Promise(o);function o(i,s){const l=bp(n);a.run(t,l,c);function c(u,d,g){const m=d||t;u?s(u):i?i(m):r(void 0,m,g)}}}runSync(t,n){let r=!1,a;return this.run(t,n,o),M3("runSync","run",r),a;function o(i,s){_3(i),a=s,r=!0}}stringify(t,n){this.freeze();const r=bp(n),a=this.compiler||this.Compiler;return wx("stringify",a),L3(t),a(t,r)}use(t,...n){const r=this.attachers,a=this.namespace;if(Ex("use",this.frozen),t!=null)if(typeof t=="function")l(t,n);else if(typeof t=="object")Array.isArray(t)?s(t):i(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function o(c){if(typeof c=="function")l(c,[]);else if(typeof c=="object")if(Array.isArray(c)){const[u,...d]=c;l(u,d)}else i(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function i(c){if(!("plugins"in c)&&!("settings"in c))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");s(c.plugins),c.settings&&(a.settings=hx(!0,a.settings,c.settings))}function s(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){const d=c[u];o(d)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function l(c,u){let d=-1,g=-1;for(;++d<r.length;)if(r[d][0]===c){g=d;break}if(g===-1)r.push([c,...u]);else if(u.length>0){let[m,...y]=u;const b=r[g][1];zk(b)&&zk(m)&&(m=hx(!0,b,m)),r[g]=[c,m,...y]}}}}const y1e=new GA().freeze();function Sx(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wx(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ex(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function L3(e){if(!zk(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function M3(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function bp(e){return v1e(e)?e:new Uz(e)}function v1e(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function S1e(e){return typeof e=="string"||w1e(e)}function w1e(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const E1e="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",P3=[],$3={allowDangerousHtml:!0},x1e=/^(https?|ircs?|mailto|xmpp)$/i,k1e=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function C1e(e){const t=e.allowedElements,n=e.allowElement,r=e.children||"",a=e.className,o=e.components,i=e.disallowedElements,s=e.rehypePlugins||P3,l=e.remarkPlugins||P3,c=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...$3}:$3,u=e.skipHtml,d=e.unwrapDisallowed,g=e.urlTransform||_1e,m=y1e().use(mxe).use(l).use(t1e,c).use(s),y=new Uz;typeof r=="string"&&(y.value=r);for(const h of k1e)Object.hasOwn(e,h.from)&&(""+h.from+(h.to?"use `"+h.to+"` instead":"remove it")+E1e+h.id,void 0);const b=m.parse(y);let w=m.runSync(b,y);return a&&(w={type:"element",tagName:"div",properties:{className:a},children:w.type==="root"?w.children:[w]}),sA(w,v),EEe(w,{Fragment:f.Fragment,components:o,ignoreInvalidStyle:!0,jsx:f.jsx,jsxs:f.jsxs,passKeys:!0,passNode:!0});function v(h,S,E){if(h.type==="raw"&&E&&typeof S=="number")return u?E.children.splice(S,1):E.children[S]={type:"text",value:h.value},S;if(h.type==="element"){let k;for(k in mx)if(Object.hasOwn(mx,k)&&Object.hasOwn(h.properties,k)){const x=h.properties[k],C=mx[k];(C===null||C.includes(h.tagName))&&(h.properties[k]=g(String(x||""),k,h))}}if(h.type==="element"){let k=t?!t.includes(h.tagName):i?i.includes(h.tagName):!1;if(!k&&n&&typeof S=="number"&&(k=!n(h,S,E)),k&&E&&typeof S=="number")return d&&h.children?E.children.splice(S,1,...h.children):E.children.splice(S,1),S}}}function _1e(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return t<0||a>-1&&t>a||n>-1&&t>n||r>-1&&t>r||x1e.test(e.slice(0,t))?e:""}const A1e=p.memo(C1e,(e,t)=>e.children===t.children&&e.className===t.className),Bz=({message:e,className:t})=>f.jsx(A1e,{className:ee("prose-sm whitespace-pre-wrap break-words prose-p:m-0 prose-p:leading-relaxed prose-pre:p-0 prose-li:list-disc",t),remarkPlugins:[ife,bfe,Ile],components:{p({children:n}){return f.jsx("p",{children:n})},code({node:n,className:r,children:a,...o}){if(!a)return null;if(a.length){if(a[0]=="▍")return f.jsx("span",{className:"mt-1 animate-pulse cursor-default",children:"▍"});a[0]=a[0].replace("`▍`","▍")}const i=/language-(\w+)/.exec(r||"");return inline?f.jsx("code",{className:r,...o,children:a}):f.jsx(mz,{language:i&&i[1]||"",value:String(a).replace(/\n$/,""),...o},Math.random())}},children:e}),T1e=e=>f.jsx("div",{className:ee("flex min-h-8 max-w-lg items-end justify-start pl-10",e.className),children:f.jsx(Bz,{message:e.message,className:"whitespace-pre-wrap text-sm"})}),R1e=e=>f.jsxs(E_,{className:"w-fit max-w-lg p-2 text-xs [&>svg]:left-2.5 [&>svg]:top-2.5",variant:"destructive",children:[f.jsx(yq,{className:"h-4 w-4"}),f.jsx(z6,{children:"Something went wrong..."}),f.jsx(U6,{className:"text-xs",children:e.message})]}),N1e=({id:e,message:t})=>f.jsx("pre",{className:mie("mb-2 ml-8 w-fit max-w-xl overflow-x-scroll whitespace-pre-line rounded-lg border bg-muted p-2 text-xs font-normal text-muted-foreground"),children:t}),I1e=({message:e})=>f.jsx("p",{className:Tt("relative mb-2 ml-6 w-fit max-w-lg rounded-2xl border border-white bg-muted px-4 py-2 text-sm italic"),children:e}),O1e=({id:e,date:t})=>f.jsxs("span",{className:"!-mt-4 max-w-xl pr-6 text-right text-xs uppercase tracking-tight text-muted-foreground",children:["Message Receipt from ",t?Bs(t,"M/d/yy, h:mm a"):"Unknown"]}),D1e=()=>f.jsx("div",{className:"flex items-end justify-end",children:f.jsx("p",{className:"mb-2 w-fit max-w-lg rounded-2xl rounded-br-none border border-white bg-muted px-4 py-2 text-sm italic",children:"First login"})}),L1e=e=>f.jsx("div",{className:`${e.className} flex items-end justify-end`,children:f.jsxs("div",{className:"order-2 mx-2 flex max-w-lg flex-col items-end space-y-1 text-sm",children:[f.jsx("div",{className:"pr-1.5 text-xs text-muted-foreground",children:Bs(e.date,"MMM d yy, h:mm a")}),f.jsx(Bz,{message:e.message,className:"min-h-8 rounded-2xl rounded-br-none bg-white px-5 py-3 text-black"})]})}),M1e=({type:e,message:t,date:n,id:r},a,o=!0,i=!0,s=!0)=>{const l=e+t+n+r;if(e==="login")return f.jsx(D1e,{},l);if(e==="user")return f.jsx(L1e,{id:r,date:n,message:t??""},l);if(e==="error")return f.jsx(R1e,{date:n,message:t??""},l);if(e==="assistant")return f.jsx(T1e,{id:r,date:n,message:t??""},l);if(s&&e==="message-receipt")return f.jsx(O1e,{date:n},l);if(i&&e==="function-call")return f.jsx(N1e,{id:r,message:t},l);if(o&&e==="internal-monologue")return f.jsx(I1e,{message:t},l)};class sl extends Error{constructor(t,n){super(t+" at position "+n),this.position=n}}const yp=92,xx=47,P1e=42,F3=123,vp=125,j3=91,Sp=93,$1e=40,F1e=41,j1e=32,WA=10,Hz=9,Vz=13,z1e=8,U1e=12,sm=34,z3=43,U3=45,qz=39,Gz=48,Wz=57,Hi=44,wp=46,B1e=58,H1e=59,V1e=65,q1e=97,G1e=69,W1e=101,K1e=70,Y1e=102,Z1e=160,X1e=8192,Q1e=8202,J1e=8239,eke=8287,tke=12288,nke=8220,rke=8221,ake=8216,oke=8217,ike=96,ske=180;function lke(e){return e>=Gz&&e<=Wz||e>=V1e&&e<=K1e||e>=q1e&&e<=Y1e}function Vi(e){return e>=Gz&&e<=Wz}function cke(e){return e>=32&&e<=1114111}function ml(e){return uke.test(e)}const uke=/^[,:[\]/{}()\n+]$/;function dke(e){return ml(e)&&e!=="/"}function B3(e){return fke.test(e)||e&&Qp(e.charCodeAt(0))}const fke=/^[[{\w-]$/;function pke(e){return e===WA||e===Vz||e===Hz||e===z1e||e===U1e}function Ol(e){return e===j1e||e===WA||e===Hz||e===Vz}function gke(e){return e===Z1e||e>=X1e&&e<=Q1e||e===J1e||e===eke||e===tke}function Qp(e){return Kz(e)||Bk(e)}function Kz(e){return e===sm||e===nke||e===rke}function H3(e){return e===sm}function Bk(e){return e===qz||e===ake||e===oke||e===ike||e===ske}function V3(e){return e===qz}function yu(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const r=e.lastIndexOf(t);return r!==-1?e.substring(0,r)+(n?"":e.substring(r+1)):e}function Ea(e,t){let n=e.length;if(!Ol(e.charCodeAt(n-1)))return e+t;for(;Ol(e.charCodeAt(n-1));)n--;return e.substring(0,n)+t+e.substring(n)}function mke(e,t,n){return e.substring(0,t)+e.substring(t+n)}function hke(e){return/[,\n][ \t\r]*$/.test(e)}function bke(e){return/^\w+$/.test(e)}const yke={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","	":"\\t"},vke={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
 `,r:"\r",t:"	"};function Ske(e){let t=0,n="";o()||L();const a=c(Hi);for(a&&i(),B3(e[t])&&hke(n)?(a||(n=Ea(n,",")),b()):a&&(n=yu(n,","));e.charCodeAt(t)===vp||e.charCodeAt(t)===Sp;)t++,i();if(t>=e.length)return n;R();function o(){i();const M=m()||y()||w()||h()||S()||k();return i(),M}function i(){const M=t;let U=s();do U=l(),U&&(U=s());while(U);return t>M}function s(){let M="",U;for(;(U=Ol(e.charCodeAt(t)))||gke(e.charCodeAt(t));)U?M+=e[t]:M+=" ",t++;return M.length>0?(n+=M,!0):!1}function l(){if(e.charCodeAt(t)===xx&&e.charCodeAt(t+1)===P1e){for(;t<e.length&&!wke(e,t);)t++;return t+=2,!0}if(e.charCodeAt(t)===xx&&e.charCodeAt(t+1)===xx){for(;t<e.length&&e.charCodeAt(t)!==WA;)t++;return!0}return!1}function c(M){return e.charCodeAt(t)===M?(n+=e[t],t++,!0):!1}function u(M){return e.charCodeAt(t)===M?(t++,!0):!1}function d(){return u(yp)}function g(){return i(),e.charCodeAt(t)===wp&&e.charCodeAt(t+1)===wp&&e.charCodeAt(t+2)===wp?(t+=3,i(),u(Hi),!0):!1}function m(){if(e.charCodeAt(t)===F3){n+="{",t++,i(),u(Hi)&&i();let M=!0;for(;t<e.length&&e.charCodeAt(t)!==vp;){let U;if(M?(U=!0,M=!1):(U=c(Hi),U||(n=Ea(n,",")),i()),g(),!(w()||k())){e.charCodeAt(t)===vp||e.charCodeAt(t)===F3||e.charCodeAt(t)===Sp||e.charCodeAt(t)===j3||e[t]===void 0?n=yu(n,","):D();break}i();const j=c(B1e),O=t>=e.length;j||(B3(e[t])||O?n=Ea(n,":"):H()),o()||(j||O?n+="null":H())}return e.charCodeAt(t)===vp?(n+="}",t++):n=Ea(n,"}"),!0}return!1}function y(){if(e.charCodeAt(t)===j3){n+="[",t++,i(),u(Hi)&&i();let M=!0;for(;t<e.length&&e.charCodeAt(t)!==Sp;)if(M?M=!1:c(Hi)||(n=Ea(n,",")),g(),!o()){n=yu(n,",");break}return e.charCodeAt(t)===Sp?(n+="]",t++):n=Ea(n,"]"),!0}return!1}function b(){let M=!0,U=!0;for(;U;)M?M=!1:c(Hi)||(n=Ea(n,",")),U=o();U||(n=yu(n,",")),n=`[
 `.concat(n,`
 ]`)}function w(){let M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,U=e.charCodeAt(t)===yp;if(U&&(t++,U=!0),Qp(e.charCodeAt(t))){const X=H3(e.charCodeAt(t))?H3:V3(e.charCodeAt(t))?V3:Bk(e.charCodeAt(t))?Bk:Kz,j=t,O=n.length;let A='"';for(t++;;){if(t>=e.length){const V=x(t-1);return!M&&ml(e.charAt(V))?(t=j,n=n.substring(0,O),w(!0)):(A=Ea(A,'"'),n+=A,!0)}else if(X(e.charCodeAt(t))){const V=t,P=A.length;if(A+='"',t++,n+=A,i(),M||t>=e.length||ml(e.charAt(t))||Qp(e.charCodeAt(t))||Vi(e.charCodeAt(t)))return v(),!0;if(ml(e.charAt(x(V-1))))return t=j,n=n.substring(0,O),w(!0);n=n.substring(0,O),t=V+1,A=A.substring(0,P)+"\\"+A.substring(P)}else{if(M&&ml(e[t]))return A=Ea(A,'"'),n+=A,v(),!0;if(e.charCodeAt(t)===yp){const V=e.charAt(t+1);if(vke[V]!==void 0)A+=e.slice(t,t+2),t+=2;else if(V==="u"){let N=2;for(;N<6&&lke(e.charCodeAt(t+N));)N++;N===6?(A+=e.slice(t,t+6),t+=6):t+N>=e.length?t=e.length:z()}else A+=V,t+=2}else{const V=e.charAt(t),P=e.charCodeAt(t);P===sm&&e.charCodeAt(t-1)!==yp?(A+="\\"+V,t++):pke(P)?(A+=yke[V],t++):(cke(P)||T(V),A+=V,t++)}}U&&d()}}return!1}function v(){let M=!1;for(i();e.charCodeAt(t)===z3;){M=!0,t++,i(),n=yu(n,'"',!0);const U=n.length;w()?n=mke(n,U,1):n=Ea(n,'"')}return M}function h(){const M=t;if(e.charCodeAt(t)===U3){if(t++,C())return _(M),!0;if(!Vi(e.charCodeAt(t)))return t=M,!1}for(;Vi(e.charCodeAt(t));)t++;if(e.charCodeAt(t)===wp){if(t++,C())return _(M),!0;if(!Vi(e.charCodeAt(t)))return t=M,!1;for(;Vi(e.charCodeAt(t));)t++}if(e.charCodeAt(t)===W1e||e.charCodeAt(t)===G1e){if(t++,(e.charCodeAt(t)===U3||e.charCodeAt(t)===z3)&&t++,C())return _(M),!0;if(!Vi(e.charCodeAt(t)))return t=M,!1;for(;Vi(e.charCodeAt(t));)t++}if(!C())return t=M,!1;if(t>M){const U=e.slice(M,t),X=/^0\d/.test(U);return n+=X?'"'.concat(U,'"'):U,!0}return!1}function S(){return E("true","true")||E("false","false")||E("null","null")||E("True","true")||E("False","false")||E("None","null")}function E(M,U){return e.slice(t,t+M.length)===M?(n+=U,t+=M.length,!0):!1}function k(){const M=t;for(;t<e.length&&!dke(e[t])&&!Qp(e.charCodeAt(t));)t++;if(t>M){if(e.charCodeAt(t)===$1e&&bke(e.slice(M,t).trim()))return t++,o(),e.charCodeAt(t)===F1e&&(t++,e.charCodeAt(t)===H1e&&t++),!0;{for(;Ol(e.charCodeAt(t-1))&&t>0;)t--;const U=e.slice(M,t);return n+=U==="undefined"?"null":JSON.stringify(U),e.charCodeAt(t)===sm&&t++,!0}}}function x(M){let U=M;for(;U>0&&Ol(e.charCodeAt(U));)U--;return U}function C(){return t>=e.length||ml(e[t])||Ol(e.charCodeAt(t))}function _(M){n+=e.slice(M,t)+"0"}function T(M){throw new sl("Invalid character "+JSON.stringify(M),t)}function R(){throw new sl("Unexpected character "+JSON.stringify(e[t]),t)}function L(){throw new sl("Unexpected end of json string",e.length)}function D(){throw new sl("Object key expected",t)}function H(){throw new sl("Colon expected",t)}function z(){const M=e.slice(t,t+6);throw new sl('Invalid unicode character "'.concat(M,'"'),t)}}function wke(e,t){return e[t]==="*"&&e[t+1]==="/"}const Eke=e=>{const t="api",n=[];if(e.role==="system")return n;if(e.role==="assistant")return n.push({id:e.id,source:t,type:"internal-monologue",message:e.text??"",date:new Date(e.created_at||"")}),(e.tool_calls??[]).forEach((o,i)=>{var s,l,c;if(o.type==="function"){const u=new Date(e.created_at||"");if(((s=o.function)==null?void 0:s.name)==="send_message"){let d={};try{d=JSON.parse(Ske(o.function.arguments))}catch(g){console.error("failed to parse send message arguments",g,o.function.arguments)}n.push({id:e.id,source:t,type:"assistant",date:u,message:(d==null?void 0:d.message)??""})}else n.push({id:e.id,source:t,type:"function-call",date:u,message:`${(l=o.function)==null?void 0:l.name}(${(c=o.function)==null?void 0:c.arguments})`??""})}}),n;if(e.role==="tool")return e.name==="send_message"?(n.push({id:e.id,source:t,type:"message-receipt",message:(e==null?void 0:e.text)||"",date:new Date(e.created_at||"")}),n):(n.push({id:e.id,source:t,type:"function-call",message:(e==null?void 0:e.text)||"",date:new Date(e.created_at||"")}),n);const r=new Date(e.created_at||""),a=JSON.parse((e==null?void 0:e.text)||"");return a.type==="login"&&n.push({id:e.id,source:t,type:"login",date:r,message:a.message}),a.type==="user_message"&&n.push({id:e.id,source:t,type:"user",date:r,message:a.message}),n},Yz=p.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:ee("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Yz.displayName="Card";const Zz=p.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:ee("flex flex-col space-y-1.5 p-6",e),...t}));Zz.displayName="CardHeader";const Xz=p.forwardRef(({className:e,...t},n)=>f.jsx("h3",{ref:n,className:ee("text-2xl font-semibold leading-none tracking-tight",e),...t}));Xz.displayName="CardTitle";const Qz=p.forwardRef(({className:e,...t},n)=>f.jsx("p",{ref:n,className:ee("text-sm text-muted-foreground",e),...t}));Qz.displayName="CardDescription";const Jz=p.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:ee("p-6 pt-0",e),...t}));Jz.displayName="CardContent";const eU=p.forwardRef(({className:e,...t},n)=>f.jsx("div",{ref:n,className:ee("flex items-center p-6 pt-0",e),...t}));eU.displayName="CardFooter";const xke=()=>{const{data:e}=Qm(),[t,n]=p.useState(null),{setAgent:r}=fh();return f.jsxs(Yz,{className:"mx-4 my-10 w-fit bg-background duration-700 animate-in slide-in-from-top slide-out-to-top sm:mx-auto ",children:[f.jsxs(Zz,{className:"pb-3",children:[f.jsx(Xz,{children:"Choose Agent"}),f.jsx(Qz,{children:"Pick an agent to start a conversation..."})]}),f.jsx(Jz,{className:"grid gap-1",children:(e??[]).map((a,o)=>{var i,s,l,c;return f.jsxs("button",{onClick:()=>n(a),className:ee("-mx-2 flex items-start space-x-4 rounded-md p-2 text-left transition-all",(t==null?void 0:t.name)===a.name?"bg-accent text-accent-foreground":"hover:bg-accent hover:text-accent-foreground"),children:[f.jsx(Uq,{className:"mt-px h-5 w-5"}),f.jsxs("div",{className:"space-y-1",children:[f.jsx("p",{className:"text-sm font-medium leading-none",children:a.name}),f.jsxs("p",{className:"text-sm text-muted-foreground",children:[((s=(i=a.memory)==null?void 0:i.memory)==null?void 0:s[fr].name)||""," | ",((c=(l=a.memory)==null?void 0:l.memory)==null?void 0:c[Qr].name)||""," | ",a.created_at]})]})]},o)})}),f.jsx(eU,{children:f.jsx(ue,{onClick:()=>t&&r(t),className:"w-full",children:"Start Chat"})})]})},kke=({className:e})=>f.jsxs("div",{className:e,children:[f.jsxs("span",{className:"relative flex h-4 w-4",children:[f.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75"}),f.jsx("span",{className:"relative inline-flex h-4 w-4 rounded-full bg-blue-600"})]}),f.jsx("span",{className:Tt("ml-4"),children:"Thinking..."})]}),Cke=({currentAgent:e,isLoading:t,previousMessages:n})=>{const{messagesRef:r,scrollRef:a,visibilityRef:o}=gle(),i=E9(),s=w9(),l=ese(),c=n.flatMap(Eke),u=ple(c);return e?f.jsx("div",{ref:a,className:"relative flex-1 overflow-auto",children:f.jsxs("div",{className:"flex flex-1 flex-col gap-4 px-4 pb-10 pt-6",ref:r,children:[u.map((d,g)=>{var b;return[((b=u[g-1])==null?void 0:b.type)==="user"||g===0?f.jsx(hle,{name:e.name,date:d.date},d.id+(e.id||"")+g):null,M1e(d,g,s,i,l)]}),t?f.jsx(kke,{className:"flex items-center px-3 py-3"}):null,f.jsx("div",{className:"h-px w-full",ref:o})]})}):f.jsx(mle,{children:f.jsx(xke,{})})},_ke=Xe({message:Ce().min(1,"Message cannot be empty...")}),Ake=e=>{const{formRef:t,onKeyDown:n}=pie(),r=bn({resolver:yn(_ke),defaultValues:{message:""}});function a(o){e.onSend(o.message),r.reset()}return f.jsx(vn,{...r,children:f.jsx("form",{ref:t,onSubmit:r.handleSubmit(a),className:"mx-4 mb-8 flex-none",children:f.jsx(ut,{control:r.control,name:"message",render:({field:o})=>f.jsxs(it,{className:"w-full",children:[f.jsx(yt,{className:"sr-only",children:"What's on your mind"}),f.jsx(pt,{className:"w-full",children:f.jsxs("div",{className:"relative overflow-hidden rounded-md border bg-background p-0.5 has-[:focus]:ring-2 has-[:focus]:ring-ring has-[:focus]:ring-offset-2 ",children:[f.jsx(qs,{onKeyDown:n,className:"h-20 w-full resize-none scroll-pb-10 rounded-none border-none pb-10 pt-4 focus-visible:ring-0",placeholder:"Type your message",...o}),f.jsxs("div",{className:"flex items-center justify-between p-4",children:[f.jsx("div",{}),f.jsxs(ue,{disabled:!e.enabled,type:"submit",children:[f.jsx(Fq,{className:"mr-2 size-5"})," Send"]})]})]})}),f.jsx(ct,{})]})})})})},Tke=(e,t,n)=>p.useCallback((r,a="user")=>{var s,l;if(!((l=(s=e==null?void 0:e.memory)==null?void 0:s.memory)!=null&&l[fr]))return;const o=new Date;o.setMilliseconds(0);const i=t({agentId:e.id||"",message:r,role:a,memoryName:e.memory.memory[fr].label||""});n(e.id||"",{id:i,type:a==="user"?"user_message":"system_message",message_type:"user_message",message:r,date:o})},[e,t,n]);function Rke(e,t,n,r,a,o,i,s){p.useEffect(()=>(e.current||(e.current=!0,setTimeout(()=>{!t||!n||(r.length===0||(a==null?void 0:a.agentId)!==n.id)&&(o({date:new Date,agentId:n.id||""}),i(s,"system"))},300)),()=>{e.current=!0}),[n,a==null?void 0:a.agentId,r.length,i,o,t])}const Nke=["internal_monologue","function_call","function_return"],Ike=()=>{const[e,t]=p.useState([]),n=To(),[r,a]=p.useState(!1),o=p.useCallback(async i=>{var g,m;const s=new AbortController,l=s.signal;t(y=>{var b,w;return[...y,{id:Wu(),name:(w=(b=n==null?void 0:n.memory)==null?void 0:b.memory)==null?void 0:w[fr].label,role:"user",text:JSON.stringify({type:"user_message",message:i,time:new Date().toISOString()}),created_at:new Date().toISOString()}]});const c={messages:[{role:"user",name:(m=(g=n==null?void 0:n.memory)==null?void 0:g.memory)==null?void 0:m[fr].label,text:i}],stream_steps:!0,stream_tokens:!0};a(!0);let u="",d=!1;v9(`${S9}/agents/${(n==null?void 0:n.id)||""}/messages`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:"Bearer password"},body:JSON.stringify(c),signal:l,onerror:()=>{s.abort(),a(!1)},onmessage:async y=>{if(["[DONE]","[DONE_GEN]","[DONE_STEP]"].includes(y.data)){a(!1);return}d||(t(h=>{var S,E;return[...h,{name:(E=(S=n==null?void 0:n.memory)==null?void 0:S.memory)==null?void 0:E[Qr].label,role:"assistant",id:Wu(),text:"",created_at:new Date().toISOString()}]}),d=!0);const b=Xe({internal_monologue:Ce()}).or(Xe({function_call:Xe({name:Ce(),arguments:Ce()})})).or(Xe({function_call:Xe({name:Ce()})})).or(Xe({function_call:Xe({arguments:Ce()})})).or(Xe({function_return:Ce(),status:Ce(),id:Ce()})).or(Xe({function_return:Ce(),date:Ce(),status:Ce(),id:Ce()})).and(Xe({date:Ce().optional().transform(h=>h?new Date(h):new Date)})).safeParse(JSON.parse(y.data));if(!b.success){console.log("error",b.error.message,y.data),s.abort();return}const w=b.data,v=Object.keys(w).find(h=>Nke.includes(h));if(v&&("internal_monologue"in w&&(u&&u!=="internal_monologue"&&t(h=>{var S,E;return[...h,{name:(E=(S=n==null?void 0:n.memory)==null?void 0:S.memory)==null?void 0:E[Qr].label,role:"assistant",id:Wu(),text:"",created_at:new Date().toISOString()}]}),t(h=>[...h.slice(0,h.length-1),{...h[h.length-1],text:(h[h.length-1].text||"")+w.internal_monologue}])),"function_call"in w&&t(h=>{var k,x,C;const S=h[h.length-1];let E=(k=S==null?void 0:S.tool_calls)==null?void 0:k[((S==null?void 0:S.tool_calls)||[]).length-1];return"name"in w.function_call&&(E={id:"1",type:"function",function:{name:w.function_call.name,arguments:""}}),"arguments"in w.function_call&&(E={...E,id:"1",function:{name:((x=E==null?void 0:E.function)==null?void 0:x.name)||"",arguments:((C=E==null?void 0:E.function)==null?void 0:C.arguments)+w.function_call.arguments}}),E?[...h.slice(0,h.length-1),{...S,tool_calls:[...(S.tool_calls||[]).slice(0,(S.tool_calls||[]).length-1),E]}]:h}),u=v,"function_return"in w)){if(w.function_return==="None")return;t(h=>{const S=h[h.length-1];return[...h.slice(0,h.length-1),{...S,tool_calls:[...S.tool_calls||[],{id:"1",type:"function",function:{name:"",arguments:JSON.stringify(w,null,2)}}]}]})}}})},[n]);return{isLoading:r,streamedMessages:e,getMessageResponse:o}},Oke=()=>{const e=To(),t=p.useRef(!1),n=zre(),r=jie((e==null?void 0:e.id)??""),{autoMessage:a,shouldSendAutoMessage:o}=x9(),{setLastAgentInitMessage:i}=fh(),{sendMessage:s}=AN(),{registerOnMessageCallback:l,registerOnLastMessageReplaceCallback:c,registerOnReplaceTemporaryIdsWithReturnedIdsCallback:u,abortStream:d}=AN(),{addMessage:g,replaceLastMessage:m,replaceMessageIds:y}=zie(),b=Tke(e,s,g),{streamedMessages:w,isLoading:v,getMessageResponse:h}=Ike(),S=lX({agentId:(e==null?void 0:e.id)??"",msgObject:!0,limit:1e3}),E=p.useCallback(_=>_?_.endsWith("Z")?_:`${_}Z`:"",[]),k=(S.data||[]).map(_=>({..._,created_at:E(_.created_at)}),[S.data]);Rke(t,o,e,r,n,i,b,a);const[x,C]=p.useState(!1);return p.useEffect(()=>{e&&d()},[d,e]),p.useEffect(()=>{l(_=>{e&&g(e.id||"",_)}),c(_=>{e&&m(e.id||"",_)}),u((_,T)=>{e&&y(e.id||"",_,T)})},[d,l,c,u,e,g,m,y]),f.jsxs(Fs,{className:"flex flex-col overflow-hidden",children:[f.jsxs("div",{className:"flex flex-none items-center space-x-2 border-b p-4",children:[f.jsx(ue,{className:"mr-2",asChild:!0,size:"iconSm",variant:"outline",children:f.jsx(bd,{to:"..",children:f.jsx(Eq,{className:"size-5"})})}),f.jsxs("div",{className:"flex w-full items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("h1",{className:Tt(),children:"Agent Chat"}),f.jsx("h2",{className:gie("text-foreground"),children:(e==null?void 0:e.name)??"Letta"})]}),e?f.jsxs("button",{onClick:async()=>{await navigator.clipboard.writeText((e==null?void 0:e.id)||""),C(!0),setTimeout(()=>C(!1),2e3)},className:ee(h9({variant:"secondary"}),"ml-2 opacity-80 hover:opacity-100"),children:[f.jsxs("span",{children:["Agent ID: ",e==null?void 0:e.id]}),x?f.jsx(Pm,{className:"ml-2 h-3 w-3"}):f.jsx(Cq,{className:"ml-2 h-3 w-3"})]}):null]})]}),f.jsxs("div",{className:"relative flex min-h-0 flex-1",children:[f.jsx(fle,{currentAgentId:e==null?void 0:e.id}),f.jsx("div",{className:"flex flex-1 border-l bg-muted/50",children:f.jsxs("div",{className:"relative mx-auto flex max-w-screen-lg flex-1 flex-col overflow-hidden",children:[f.jsx(fse,{}),f.jsx(Cke,{currentAgent:e,isLoading:v,previousMessages:[...k,...w],messages:r}),f.jsx(Ake,{enabled:!v,onSend:_=>{h(_)}})]})})]})]})},Dke={path:"agents/:agentName/chat",element:f.jsx(Oke,{})};function Lke(e,t,n){var r=this,a=p.useRef(null),o=p.useRef(0),i=p.useRef(null),s=p.useRef([]),l=p.useRef(),c=p.useRef(),u=p.useRef(e),d=p.useRef(!0);u.current=e;var g=typeof window<"u",m=!t&&t!==0&&g;if(typeof e!="function")throw new TypeError("Expected a function");t=+t||0;var y=!!(n=n||{}).leading,b=!("trailing"in n)||!!n.trailing,w="maxWait"in n,v="debounceOnServer"in n&&!!n.debounceOnServer,h=w?Math.max(+n.maxWait||0,t):null;p.useEffect(function(){return d.current=!0,function(){d.current=!1}},[]);var S=p.useMemo(function(){var E=function(R){var L=s.current,D=l.current;return s.current=l.current=null,o.current=R,c.current=u.current.apply(D,L)},k=function(R,L){m&&cancelAnimationFrame(i.current),i.current=m?requestAnimationFrame(R):setTimeout(R,L)},x=function(R){if(!d.current)return!1;var L=R-a.current;return!a.current||L>=t||L<0||w&&R-o.current>=h},C=function(R){return i.current=null,b&&s.current?E(R):(s.current=l.current=null,c.current)},_=function R(){var L=Date.now();if(x(L))return C(L);if(d.current){var D=t-(L-a.current),H=w?Math.min(D,h-(L-o.current)):D;k(R,H)}},T=function(){if(g||v){var R=Date.now(),L=x(R);if(s.current=[].slice.call(arguments),l.current=r,a.current=R,L){if(!i.current&&d.current)return o.current=a.current,k(_,t),y?E(a.current):c.current;if(w)return k(_,t),E(a.current)}return i.current||k(_,t),c.current}};return T.cancel=function(){i.current&&(m?cancelAnimationFrame(i.current):clearTimeout(i.current)),o.current=0,s.current=a.current=l.current=i.current=null},T.isPending=function(){return!!i.current},T.flush=function(){return i.current?C(Date.now()):c.current},T},[y,w,t,h,b,m,g,v]);return S}function Mke(e,t){return e===t}function Pke(e,t){return t}function Ih(e,t,n){var r=n&&n.equalityFn||Mke,a=p.useReducer(Pke,e),o=a[0],i=a[1],s=Lke(p.useCallback(function(c){return i(c)},[i]),t,n),l=p.useRef(e);return r(l.current,e)||(s(e),l.current=e),[o,s]}const $ke=Xe({agentId:Ce()});function Fke({source:e,closeDialog:t}){const{data:n,isLoading:r}=Qm(),a=x6(),{toast:o}=An(),i=Bt(),s=bn({resolver:yn($ke),mode:"onChange"}),l=c=>{a.mutate({agentId:c.agentId,sourceId:e.id||""},{onSuccess:()=>{t(),i.invalidateQueries({queryKey:sf()}),o({title:"Agent attached successfully!",duration:5e3})},onError:u=>{o({title:"Error attaching agent...",duration:5e3})}})};return f.jsx(vn,{...s,children:f.jsxs("form",{onSubmit:s.handleSubmit(l,c=>console.log(c)),className:"space-y-8",children:[f.jsx(ut,{control:s.control,name:"agentId",render:({field:c})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Agent to Attach to"}),f.jsxs(So,{disabled:r,onValueChange:c.onChange,value:c.value,children:[f.jsx(pt,{children:f.jsx(za,{children:f.jsx(wo,{placeholder:r?"Loading agents...":"Select an agent"})})}),f.jsx(Ua,{className:"max-h-[200px] overflow-y-auto",children:(n??[]).map(u=>f.jsx(Fn,{value:u.id||"",children:u.name},u.id))})]}),f.jsx(Mt,{children:"Select an agent to attach your data source to."}),f.jsx(ct,{})]})}),f.jsxs("div",{className:"flex items-center",children:[f.jsx(ue,{type:"submit",children:"Attach to Agent"}),a.isPending&&f.jsxs("div",{className:Tt("ml-4 flex items-center animate-in slide-in-from-bottom-2"),children:[f.jsx(un,{className:"mr-2 h-4 w-4 animate-spin "}),f.jsx("span",{children:"Attaching agent to data source..."})]})]})]})})}const jke=({open:e,onOpenChange:t,source:n})=>f.jsx(Kt,{open:e,onOpenChange:t,children:f.jsxs(Ht,{className:"max-h-[95svh] w-full sm:max-w-[800px]",children:[f.jsxs(Pt,{children:[f.jsxs($t,{children:["Attach Agent to ",(n==null?void 0:n.name)??"Source"]}),f.jsx(dn,{children:"The datasource will then become available to the agent to use for information."})]}),n?f.jsx(Fke,{source:n,closeDialog:()=>t(!1)}):f.jsx("p",{children:"No source and agent..."})]})}),zke=Xe({name:Ce().min(1,{message:"Name must be at least 1 character."}).max(30,{message:"Name must not be longer than 30 characters."}),description:Ce().max(2e3).min(0)}),Uke={name:"",description:""};function Bke({closeDialog:e}){const t=dX(),n=Bt(),{toast:r}=An(),a=bn({resolver:yn(zke),defaultValues:Uke,mode:"onChange"}),o=i=>{t.mutate({requestBody:{name:i.name,description:i.description}},{onSuccess:()=>{n.invalidateQueries({queryKey:sf()}),e(),r({title:"Source created successfully!",duration:5e3})},onError:s=>{r({title:"Error creating source",duration:5e3})}})};return f.jsx(vn,{...a,children:f.jsxs("form",{onSubmit:a.handleSubmit(o,i=>console.log(i)),className:"space-y-8",children:[f.jsx(ut,{control:a.control,name:"name",render:({field:i})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Name"}),f.jsx(pt,{children:f.jsx(_n,{...i})}),f.jsx(Mt,{children:"This is your sources display name. It can be a real name or a pseudonym."}),f.jsx(ct,{})]})}),f.jsx(ut,{control:a.control,name:"description",render:({field:i})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Description"}),f.jsx(pt,{children:f.jsx(qs,{placeholder:"Describe your source here",className:"resize-none",...i})}),f.jsx(ct,{})]})}),f.jsxs("div",{className:"flex items-center",children:[f.jsx(ue,{type:"submit",children:"Create Source"}),t.isPending&&f.jsxs("div",{className:Tt("ml-4 flex items-center animate-in slide-in-from-bottom-2"),children:[f.jsx(un,{className:"mr-2 h-4 w-4 animate-spin "}),f.jsx("span",{children:"Creating Source..."})]})]})]})})}const Hke=({open:e,onOpenChange:t})=>f.jsx(Kt,{open:e,onOpenChange:t,children:f.jsxs(Ht,{className:"max-h-[95svh] w-full sm:max-w-[800px]",children:[f.jsxs(Pt,{children:[f.jsx($t,{children:"Create Data Source"}),f.jsx(dn,{children:"Add a new data source here. Click create when you're done."})]}),f.jsx(Bke,{closeDialog:()=>t(!1)})]})}),Vke=({value:e,onValueChange:t})=>f.jsx("form",{children:f.jsxs("div",{className:"relative",children:[f.jsx(Ms,{className:"pointer-events-none absolute left-[12px] top-3 h-4 w-4 text-muted-foreground"}),f.jsx(_n,{placeholder:"Search data source",value:e,onChange:n=>t(n.target.value),className:"w-52 pl-8 lg:w-80"})]})}),qke=(e,t,n,r,a)=>[{accessorKey:"actions",header:"",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:f.jsxs("span",{className:"flex space-x-2",children:[f.jsx(ue,{onClick:()=>e(o.original),className:"!h-6 !w-6 !p-1",variant:"ghost",children:f.jsx(e4,{className:"h-3.5 w-3.5"})}),f.jsx(ue,{onClick:()=>t(o.original),className:"!h-6 !w-6 !p-1",variant:"ghost",children:f.jsx(Fm,{className:"h-3.5 w-3.5"})})]})})},{accessorKey:"name",header:"Name",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:o.getValue("name")})},{accessorFn:o=>{var i;return(i=o.embedding_config)==null?void 0:i.embedding_model},accessorKey:"embedding_model",header:"Embedding Model",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:o.getValue("embedding_model")})},{accessorFn:o=>{var i;return((i=o.embedding_config)==null?void 0:i.embedding_dim)??0},accessorKey:"embedding_dim",header:"Embedding Dimensions",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:o.getValue("embedding_dim")})},{accessorFn:o=>{var i;return((i=o.metadata_)==null?void 0:i.num_documents)??0},accessorKey:"num_documents",header:"Documents",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:o.getValue("num_documents")})},{accessorFn:o=>{var i;return((i=o.metadata_)==null?void 0:i.num_passages)??0},accessorKey:"num_passages",header:"Passages",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:o.getValue("num_passages")})},{accessorKey:"created_at",header:"Created At",cell:({row:o})=>f.jsx(Dn,{isLoading:a,children:$re(o,"created_at","Unknown")})},{accessorFn:o=>{var i;return(i=o.metadata_)==null?void 0:i.attached_agents},accessorKey:"attached_agents",header:"Attached To",cell:({row:o})=>{const i=o.getValue("attached_agents")??[];return f.jsx(Dn,{isLoading:a,children:f.jsxs("div",{className:"flex flex-wrap items-baseline",children:[f.jsxs(ue,{onClick:()=>n(o.original),variant:"ghost",className:"mr-1 h-5 !p-1 text-xs",size:"sm",children:[f.jsx("span",{className:"sr-only",children:"attach another agent"}),f.jsx(Mq,{className:"h-3 w-3"})]}),i.map(s=>f.jsxs(ue,{onClick:()=>r(o.original,s),variant:"ghost",className:"mr-1 h-5 !p-1 text-xs",size:"sm",children:[s.name,f.jsx(Dq,{className:"ml-2 h-3 w-3"})]},s.id)),i.length===0&&f.jsx("span",{className:"text-xs",children:"- None"})]})})}}],Gke=({nameFilter:e,className:t,onSourceUpload:n,onSourceEdit:r,onAttachAgent:a,onDetachAgent:o})=>{const{data:i,isError:s,isLoading:l}=h_(),c=(i??[]).filter(u=>u.name.includes(e));return f.jsx("div",{className:t,children:f.jsx(uf,{columns:qke(n,r,a,o,l),isLoading:l,error:s?"Failed to load sources":void 0,data:c,renderPagination:u=>f.jsx(df,{className:"mt-4",table:u})})})},Wke=({open:e,onOpenChange:t,source:n,agent:r})=>{const a=Bt(),o=k6(),{toast:i}=An(),s=()=>{!n||!r||o.mutate({agentId:r.id,sourceId:n.id||""},{onSuccess:()=>{t(!1),a.invalidateQueries({queryKey:sf()}),i({title:"Agent detached successfully!",duration:3e3})},onError:l=>i({title:"Failed to detach agent!",duration:3e3})})};return f.jsx(Kt,{open:n&&r&&e,onOpenChange:t,children:f.jsxs(Ht,{className:"max-h-[95svh] w-full sm:max-w-[800px]",children:[f.jsx(Pt,{children:f.jsxs($t,{children:["Detach Agent from ",(n==null?void 0:n.name)??"Source"]})}),f.jsx("p",{className:"pb-10",children:"The data source will then no longer be available to the agent to use for information."}),f.jsxs("div",{className:"flex space-x-2",children:[f.jsx(ue,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),f.jsxs(ue,{onClick:s,children:[o.isPending?"Detaching":"Detach"," Agent"]})]})]})})},Kke=Xe({name:Ce().min(1,{message:"Name must be at least 1 character."}).max(30,{message:"Name must not be longer than 30 characters."}),description:Ce().max(2e3).min(0)});function Yke({source:e,closeDialog:t}){const n=mX(),r=Bt(),{toast:a}=An(),o={name:e.name,description:e.description??""},i=bn({resolver:yn(Kke),defaultValues:o,mode:"onChange"}),s=l=>{n.mutate({sourceId:e.id||"",requestBody:{id:e.id||"",name:l.name||"",description:l.description}},{onSuccess:()=>{r.invalidateQueries({queryKey:sf()}),t(),a({title:"Source editd successfully!",duration:5e3})},onError:c=>{a({title:"Error creating source",duration:5e3})}})};return f.jsx(vn,{...i,children:f.jsxs("form",{onSubmit:i.handleSubmit(s,l=>console.log(l)),className:"space-y-8",children:[f.jsx(ut,{control:i.control,name:"name",render:({field:l})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Name"}),f.jsx(pt,{children:f.jsx(_n,{...l})}),f.jsx(Mt,{children:"This is your sources display name. It can be a real name or a pseudonym."}),f.jsx(ct,{})]})}),f.jsx(ut,{control:i.control,name:"description",render:({field:l})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Description"}),f.jsx(pt,{children:f.jsx(qs,{placeholder:"Describe your source here",className:"resize-none",...l})}),f.jsx(ct,{})]})}),f.jsxs("div",{className:"flex items-center",children:[f.jsx(ue,{type:"submit",children:"Edit Source"}),n.isPending&&f.jsxs("div",{className:Tt("ml-4 flex items-center animate-in slide-in-from-bottom-2"),children:[f.jsx(un,{className:"mr-2 h-4 w-4 animate-spin "}),f.jsx("span",{children:"Edit Source..."})]})]})]})})}const Zke=({open:e,onOpenChange:t,source:n})=>f.jsx(Kt,{open:e,onOpenChange:t,children:f.jsxs(Ht,{className:"max-h-[95svh] w-full sm:max-w-[800px]",children:[f.jsxs(Pt,{children:[f.jsx($t,{children:"Edit Data Source"}),f.jsx(dn,{children:"Edit an existing data source here."})]}),n?f.jsx(Yke,{source:n,closeDialog:()=>t(!1)}):f.jsx("p",{children:"No source..."})]})}),Xke=Xe({file:Nie(e=>e instanceof File)}),Qke=e=>{const t=C6(),{toast:n}=An(),r=Bt(),a=bn({resolver:yn(Xke),mode:"onChange"}),o=i=>{t.mutate({sourceId:e.source.id||"",formData:{file:i.file}},{onSuccess:()=>{r.invalidateQueries({queryKey:VZ()}),e.onComplete()},onError:s=>n({title:"Failed to upload file...",duration:5e3})})};return f.jsx(vn,{...a,children:f.jsxs("form",{onSubmit:a.handleSubmit(o),className:"space-y-8",children:[f.jsx(ut,{control:a.control,name:"file",render:({field:i})=>f.jsxs(it,{children:[f.jsx(yt,{children:"File"}),f.jsx(pt,{children:f.jsx(_n,{type:"file",ref:i.ref,disabled:i.disabled,name:i.name,onBlur:i.onBlur,onChange:s=>{var l,c;i.onChange((c=(l=s.target)==null?void 0:l.files)==null?void 0:c[0])}})}),f.jsx(Mt,{children:"File to upload."}),f.jsx(ct,{})]})}),f.jsxs("div",{className:"flex space-x-4",children:[f.jsx(ue,{children:"Upload File"}),t.isPending&&f.jsxs("div",{className:Tt("ml-4 flex items-center animate-in slide-in-from-bottom-2"),children:[f.jsx(un,{className:"mr-2 h-4 w-4 animate-spin "}),f.jsx("span",{children:"Creating Job to ingest file..."})]}),t.isSuccess&&f.jsxs("div",{className:Tt("ml-4 flex items-center text-emerald-600 animate-in slide-in-from-bottom-2"),children:[f.jsx(Mm,{className:"mr-2 h-4 w-4 "}),f.jsx("span",{children:"Job created! File ingestion started!"})]})]})]})})},Jke=Xe({sourceId:Ce(),file:Iie()}),eCe=({onComplete:e})=>{const t=h_(),n=C6(),{toast:r}=An(),a=bn({resolver:yn(Jke),defaultValues:{sourceId:"",file:void 0},mode:"onChange"}),o=Bt(),i=s=>{n.mutate({sourceId:s.sourceId,formData:{file:s.file}},{onSuccess:()=>{o.invalidateQueries({queryKey:b6()}),e()},onError:l=>r({title:"Failed to upload file...",duration:5e3})})};return f.jsx(vn,{...a,children:f.jsxs("form",{onSubmit:a.handleSubmit(i),className:"space-y-8",children:[f.jsx(ut,{control:a.control,name:"sourceId",render:({field:s})=>f.jsxs(it,{children:[f.jsx(yt,{children:"Upload to"}),f.jsx(pt,{children:f.jsxs(So,{value:s.value,name:s.name,onValueChange:s.onChange,disabled:t.isLoading,children:[f.jsx(za,{className:"w-full",children:f.jsx(wo,{placeholder:"Select a source"})}),f.jsx(Ua,{children:(t.data??[]).map(l=>f.jsx(Fn,{value:l.id||"",children:l.name},l.id))})]})}),f.jsx(Mt,{children:"Upload your data to this source."}),f.jsx(ct,{})]})}),f.jsx(ut,{control:a.control,name:"file",render:({field:s})=>f.jsxs(it,{children:[f.jsx(yt,{children:"File"}),f.jsx(pt,{children:f.jsx(_n,{type:"file",ref:s.ref,disabled:s.disabled,name:s.name,onBlur:s.onBlur,onChange:l=>{var c,u;s.onChange((u=(c=l.target)==null?void 0:c.files)==null?void 0:u[0])}})}),f.jsx(Mt,{children:"File to upload."}),f.jsx(ct,{})]})}),f.jsxs("div",{className:"flex space-x-4",children:[f.jsx(ue,{children:"Upload File"}),n.isPending&&f.jsxs("div",{className:Tt("ml-4 flex items-center animate-in slide-in-from-bottom-2"),children:[f.jsx(un,{className:"mr-2 h-4 w-4 animate-spin "}),f.jsx("span",{children:"Creating Job to ingest file..."})]}),n.isSuccess&&f.jsxs("div",{className:Tt("ml-4 flex items-center text-emerald-600 animate-in slide-in-from-bottom-2"),children:[f.jsx(Mm,{className:"mr-2 h-4 w-4 "}),f.jsx("span",{children:"Job created! File ingestion started!"})]})]})]})})},tCe=({source:e,open:t,onOpenChange:n})=>f.jsx(Kt,{open:t,onOpenChange:n,children:f.jsxs(Ht,{className:"max-h-[95svh] w-full sm:max-w-[800px]",children:[f.jsx(Pt,{children:f.jsxs($t,{children:["Upload Data ",e&&`to ${e.name}`]})}),e?f.jsx(Qke,{onComplete:()=>n(!1),source:e}):f.jsx(eCe,{onComplete:()=>n(!1)})]})}),tU="Progress",Oh=100,[nCe,_Te]=zn(tU),[rCe,aCe]=nCe(tU),nU=p.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:a,getValueLabel:o=sCe,...i}=e,s=Hk(a)?a:Oh,l=aU(r,s)?r:null,c=lm(l)?o(l,s):void 0;return p.createElement(rCe,{scope:n,value:l,max:s},p.createElement(ze.div,W({"aria-valuemax":s,"aria-valuemin":0,"aria-valuenow":lm(l)?l:void 0,"aria-valuetext":c,role:"progressbar","data-state":rU(l,s),"data-value":l??void 0,"data-max":s},i,{ref:t})))});nU.propTypes={max(e,t,n){const r=e[t],a=String(r);return r&&!Hk(r)?new Error(lCe(a,n)):null},value(e,t,n){const r=e[t],a=String(r),o=Hk(e.max)?e.max:Oh;return r!=null&&!aU(r,o)?new Error(cCe(a,n)):null}};const oCe="ProgressIndicator",iCe=p.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...a}=e,o=aCe(oCe,r);return p.createElement(ze.div,W({"data-state":rU(o.value,o.max),"data-value":(n=o.value)!==null&&n!==void 0?n:void 0,"data-max":o.max},a,{ref:t}))});function sCe(e,t){return`${Math.round(e/t*100)}%`}function rU(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function Hk(e){return lm(e)&&!isNaN(e)&&e>0}function aU(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function lCe(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Oh}\`.`}function cCe(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be:
diff --git a/letta/server/static_files/index.html b/letta/server/static_files/index.html
index e579c76e..57f107b9 100644
--- a/letta/server/static_files/index.html
+++ b/letta/server/static_files/index.html
@@ -29,7 +29,7 @@
 				}
 			}
 		</script>
-		<script type="module" crossorigin src="/assets/index-d6b3669a.js"></script>
+		<script type="module" crossorigin src="/assets/index-b82c8d7c.js"></script>
 		<link rel="stylesheet" href="/assets/index-3ab03d5b.css">
 	</head>
 	<body>
diff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.py
index e39d7462..b8325b6c 100644
--- a/letta/services/tool_manager.py
+++ b/letta/services/tool_manager.py
@@ -28,7 +28,9 @@ class ToolManager:
     def create_or_update_tool(self, tool_create: ToolCreate, actor: PydanticUser) -> PydanticTool:
         """Create a new tool based on the ToolCreate schema."""
         # Derive json_schema
-        derived_json_schema = tool_create.json_schema or derive_openai_json_schema(tool_create)
+        derived_json_schema = tool_create.json_schema or derive_openai_json_schema(
+            source_code=tool_create.source_code, name=tool_create.name
+        )
         derived_name = tool_create.name or derived_json_schema["name"]
 
         try:
@@ -36,7 +38,7 @@ class ToolManager:
             # This is important, because even if it's a different user, adding the same tool to the org should not happen
             tool = self.get_tool_by_name(tool_name=derived_name, actor=actor)
             # Put to dict and remove fields that should not be reset
-            update_data = tool_create.model_dump(exclude={"module", "terminal"}, exclude_unset=True)
+            update_data = tool_create.model_dump(exclude={"module"}, exclude_unset=True)
             # Remove redundant update fields
             update_data = {key: value for key, value in update_data.items() if getattr(tool, key) != value}
 
@@ -59,8 +61,7 @@ class ToolManager:
         """Create a new tool based on the ToolCreate schema."""
         # Create the tool
         with self.session_maker() as session:
-            # Include all fields except `terminal` (which is not part of ToolModel) at the moment
-            create_data = tool_create.model_dump(exclude={"terminal"})
+            create_data = tool_create.model_dump()
             tool = ToolModel(**create_data, organization_id=actor.organization_id)  # Unpack everything directly into ToolModel
             tool.create(session, actor=actor)
 
@@ -106,6 +107,22 @@ class ToolManager:
             for key, value in update_data.items():
                 setattr(tool, key, value)
 
+            # If source code is changed and a new json_schema is not provided, we want to auto-refresh the name and schema
+            # CAUTION: This will override any name/schema values the user passed in
+            if "source_code" in update_data.keys() and "json_schema" not in update_data.keys():
+                pydantic_tool = tool.to_pydantic()
+
+                # Decide whether or not to reset name
+                # If name was not explicitly passed in as part of the update, then we auto-generate a new name based on source code
+                name = None
+                if "name" in update_data.keys():
+                    name = update_data["name"]
+                new_schema = derive_openai_json_schema(source_code=pydantic_tool.source_code, name=name)
+
+                # The name will either be set (if explicit) or autogenerated from the source code
+                tool.name = new_schema["name"]
+                tool.json_schema = new_schema
+
             # Save the updated tool to the database
             tool.update(db_session=session, actor=actor)
 


Test patch:
diff --git a/tests/test_managers.py b/tests/test_managers.py
index 1dd3743d..c8232963 100644
--- a/tests/test_managers.py
+++ b/tests/test_managers.py
@@ -49,7 +49,7 @@ def tool_fixture(server: SyncServer):
     user = server.user_manager.create_default_user()
     other_user = server.user_manager.create_user(UserCreate(name="other", organization_id=org.id))
     tool_create = ToolCreate(description=description, tags=tags, source_code=source_code, source_type=source_type)
-    derived_json_schema = derive_openai_json_schema(tool_create)
+    derived_json_schema = derive_openai_json_schema(source_code=tool_create.source_code, name=tool_create.name)
     derived_name = derived_json_schema["name"]
     tool_create.json_schema = derived_json_schema
     tool_create.name = derived_name
@@ -182,7 +182,7 @@ def test_create_tool(server: SyncServer, tool_fixture):
     assert tool.tags == tool_create.tags
     assert tool.source_code == tool_create.source_code
     assert tool.source_type == tool_create.source_type
-    assert tool.json_schema == derive_openai_json_schema(tool_create)
+    assert tool.json_schema == derive_openai_json_schema(source_code=tool_create.source_code, name=tool_create.name)
 
 
 def test_get_tool_by_id(server: SyncServer, tool_fixture):
@@ -220,7 +220,6 @@ def test_get_tool_with_actor(server: SyncServer, tool_fixture):
 
 def test_list_tools(server: SyncServer, tool_fixture):
     tool = tool_fixture["tool"]
-    tool_fixture["organization"]
     user = tool_fixture["user"]
 
     # List tools (should include the one created by the fixture)
@@ -249,6 +248,85 @@ def test_update_tool_by_id(server: SyncServer, tool_fixture):
     assert updated_tool.description == updated_description
 
 
+def test_update_tool_source_code_refreshes_schema_and_name(server: SyncServer, tool_fixture):
+    def counter_tool(counter: int):
+        """
+        Args:
+            counter (int): The counter to count to.
+
+        Returns:
+            bool: If it successfully counted to the counter.
+        """
+        for c in range(counter):
+            print(c)
+
+        return True
+
+    # Test begins
+    tool = tool_fixture["tool"]
+    user = tool_fixture["user"]
+    og_json_schema = tool_fixture["tool_create"].json_schema
+
+    source_code = parse_source_code(counter_tool)
+
+    # Create a ToolUpdate object to modify the tool's source_code
+    tool_update = ToolUpdate(source_code=source_code)
+
+    # Update the tool using the manager method
+    server.tool_manager.update_tool_by_id(tool.id, tool_update, actor=user)
+
+    # Fetch the updated tool to verify the changes
+    updated_tool = server.tool_manager.get_tool_by_id(tool.id, actor=user)
+
+    # Assertions to check if the update was successful, and json_schema is updated as well
+    assert updated_tool.source_code == source_code
+    assert updated_tool.json_schema != og_json_schema
+
+    new_schema = derive_openai_json_schema(source_code=updated_tool.source_code, name=updated_tool.name)
+    assert updated_tool.json_schema == new_schema
+    assert updated_tool.name == new_schema["name"]
+
+
+def test_update_tool_source_code_refreshes_schema_only(server: SyncServer, tool_fixture):
+    def counter_tool(counter: int):
+        """
+        Args:
+            counter (int): The counter to count to.
+
+        Returns:
+            bool: If it successfully counted to the counter.
+        """
+        for c in range(counter):
+            print(c)
+
+        return True
+
+    # Test begins
+    tool = tool_fixture["tool"]
+    user = tool_fixture["user"]
+    og_json_schema = tool_fixture["tool_create"].json_schema
+
+    source_code = parse_source_code(counter_tool)
+    name = "test_function_name_explicit"
+
+    # Create a ToolUpdate object to modify the tool's source_code
+    tool_update = ToolUpdate(name=name, source_code=source_code)
+
+    # Update the tool using the manager method
+    server.tool_manager.update_tool_by_id(tool.id, tool_update, actor=user)
+
+    # Fetch the updated tool to verify the changes
+    updated_tool = server.tool_manager.get_tool_by_id(tool.id, actor=user)
+
+    # Assertions to check if the update was successful, and json_schema is updated as well
+    assert updated_tool.source_code == source_code
+    assert updated_tool.json_schema != og_json_schema
+
+    new_schema = derive_openai_json_schema(source_code=updated_tool.source_code, name=updated_tool.name)
+    assert updated_tool.json_schema == new_schema
+    assert updated_tool.name == name
+
+
 def test_update_tool_multi_user(server: SyncServer, tool_fixture):
     tool = tool_fixture["tool"]
     user = tool_fixture["user"]
@@ -272,7 +350,6 @@ def test_update_tool_multi_user(server: SyncServer, tool_fixture):
 
 def test_delete_tool_by_id(server: SyncServer, tool_fixture):
     tool = tool_fixture["tool"]
-    tool_fixture["organization"]
     user = tool_fixture["user"]
 
     # Delete the tool using the manager method
diff --git a/tests/test_schema_generator.py b/tests/test_schema_generator.py
index 3edcf0d1..d4eaec0c 100644
--- a/tests/test_schema_generator.py
+++ b/tests/test_schema_generator.py
@@ -42,21 +42,21 @@ def test_schema_generator():
             "required": ["message"],
         },
     }
-    generated_schema = generate_schema(send_message, terminal=True)
+    generated_schema = generate_schema(send_message)
     print(f"\n\nreference_schema={correct_schema}")
     print(f"\n\ngenerated_schema={generated_schema}")
     assert correct_schema == generated_schema
 
     # Check that missing types results in an error
     try:
-        _ = generate_schema(send_message_missing_types, terminal=True)
+        _ = generate_schema(send_message_missing_types)
         assert False
     except:
         pass
 
     # Check that missing docstring results in an error
     try:
-        _ = generate_schema(send_message_missing_docstring, terminal=True)
+        _ = generate_schema(send_message_missing_docstring)
         assert False
     except:
         pass