### Start K-Dense BYOK Services Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Clone the repository, configure the environment variables by copying and editing the example .env file, and then run the start script to launch the services. ```bash git clone https://github.com/K-Dense-AI/k-dense-byok.git cd k-dense-byok cp kady_agent/env.example kady_agent/.env # Edit kady_agent/.env and add OPENROUTER_API_KEY ./start.sh # Opens http://localhost:3000 automatically # Backend API: http://localhost:8000 # LiteLLM proxy: http://localhost:4000 ``` -------------------------------- ### Install Ollama and Start Daemon Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/docs/local-models-ollama.md Installs Ollama using the official script and starts the Ollama server daemon. Ensure this is running before pulling models or connecting the agent. ```bash # macOS / Linux curl -fsSL https://ollama.com/install.sh | sh ollama serve ``` -------------------------------- ### Start the K-Dense BYOK Application Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/README.md Execute this script to start the application. It automatically installs necessary dependencies like Python packages, Node.js, and the Gemini CLI on the first run. Subsequent starts are faster. ```bash ./start.sh ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Install Node.js dependencies for the frontend. Navigate to the 'web' directory first. ```bash npm install ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Start the Next.js development server on port 3000. Ensure you are in the 'web' directory. ```bash npm run dev ``` -------------------------------- ### Run Development Server Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/web/README.md Use these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Create a new project Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a new project, setting up its on-disk structure and scheduling background tasks for environment setup. The project record is returned immediately. ```APIDOC ## POST /projects ### Description Creates the on-disk skeleton immediately and schedules a background task that installs the Python venv and downloads the scientific skills catalogue. Returns the project record without waiting for the background bootstrap. ### Method POST ### Endpoint /projects ### Parameters #### Query Parameters - **X-Project-Id** (string) - Required - Identifier for the project context. #### Request Body - **name** (string) - Required - The name of the new project. - **description** (string) - Optional - A description for the project. - **tags** (array of strings) - Optional - Tags to associate with the project. - **spendLimitUsd** (number) - Optional - The spending limit for the project in USD. ### Response #### Success Response (201) - **id** (string) - Unique identifier for the newly created project. - **name** (string) - The name of the project. - **description** (string) - A description for the project. - **tags** (array of strings) - Tags associated with the project. - **createdAt** (string) - Timestamp when the project was created. - **updatedAt** (string) - Timestamp when the project was last updated. - **archived** (boolean) - Indicates if the project is archived. - **spendLimitUsd** (number) - The spending limit for the project in USD. ### Request Example ```bash curl -X POST http://localhost:8000/projects \ -H "Content-Type: application/json" \ -d '{ "name": "Drug Discovery", "description": "Virtual screening pipeline", "tags": ["chemistry", "drug-discovery"], "spendLimitUsd": 25.0 }' ``` ### Response Example ```json { "id": "drug-discovery-f3a9b2", "name": "Drug Discovery", "description": "Virtual screening pipeline", "tags": ["chemistry", "drug-discovery"], "createdAt": "2025-05-10T14:00:00+00:00", "updatedAt": "2025-05-10T14:00:00+00:00", "archived": false, "spendLimitUsd": 25.0 } ``` ``` -------------------------------- ### Install and Refresh Dependencies with uv Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Use this command to install or refresh dependencies for the Python backend. Ensure Python version is 3.13 or higher. ```bash uv sync ``` -------------------------------- ### Create New Project Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a new project with specified metadata. The project's on-disk skeleton is created immediately, and background tasks for venv and skills catalog installation are scheduled. Returns the project record without waiting for background tasks to complete. Requires 'Content-Type' and 'X-Project-Id' headers. ```bash curl -X POST http://localhost:8000/projects \ -H "Content-Type: application/json" \ -d '{ \ "name": "Drug Discovery", \ "description": "Virtual screening pipeline", \ "tags": ["chemistry", "drug-discovery"], \ "spendLimitUsd": 25.0 \ }' # Response (201) { "id": "drug-discovery-f3a9b2", "name": "Drug Discovery", "description": "Virtual screening pipeline", "tags": ["chemistry", "drug-discovery"], "createdAt": "2025-05-10T14:00:00+00:00", "updatedAt": "2025-05-10T14:00:00+00:00", "archived": false, "spendLimitUsd": 25.0 } ``` -------------------------------- ### POST /settings/mcps/{name}/sign-in Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Starts an OAuth 2.0 + PKCE flow for an HTTP MCP server. Returns the authorize URL the user must visit in their browser. ```APIDOC ## POST /settings/mcps/{name}/sign-in ### Description Starts an OAuth 2.0 + PKCE flow for an HTTP MCP server. Returns the authorize URL the user must visit in their browser. ### Method POST ### Endpoint /settings/mcps/{name}/sign-in ### Parameters #### Path Parameters - **name** (string) - Required - The name of the MCP server. #### Headers - **X-Project-Id** (string) - Required - The project ID. ### Request Example ```bash curl -X POST "http://localhost:8000/settings/mcps/paperclip/sign-in" \ -H "X-Project-Id: genomics-abc123" ``` ### Response #### Success Response (200) - **authUrl** (string) - The URL to authorize the OAuth flow. - **redirectUri** (string) - The URI to redirect to after authorization. ``` -------------------------------- ### GET /skills Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Lists all installed scientific skills for the active project's sandbox. Returns metadata for each skill. ```APIDOC ## GET /skills ### Description Returns metadata for all Gemini CLI skills installed in the active project's sandbox. ### Method GET ### Endpoint `/skills` ### Response #### Success Response (200) - An array of skill objects, each containing: - **id** (string) - The unique identifier for the skill. - **name** (string) - The display name of the skill. - **description** (string) - A brief description of the skill's functionality. - **author** (string) - The author or maintainer of the skill. - **license** (string) - The license under which the skill is distributed. - **compatibility** (string) - The compatibility version of the Gemini CLI required. ``` -------------------------------- ### List Installed Scientific Skills Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves metadata for all Gemini CLI skills installed in the project's sandbox. Useful for discovering available tools. ```bash curl "http://localhost:8000/skills" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### GET /settings/browser-use Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the current browser automation configuration. ```APIDOC ## GET /settings/browser-use ### Description Retrieves the current browser automation configuration. ### Method GET ### Endpoint /settings/browser-use ### Parameters #### Headers - **X-Project-Id** (string) - Required - The project ID. ### Request Example ```bash curl "http://localhost:8000/settings/browser-use" \ -H "X-Project-Id: genomics-abc123" ``` ### Response #### Success Response (200) - **config** (object) - The browser automation configuration. - **enabled** (boolean) - Whether browser automation is enabled. - **headed** (boolean) - Whether the browser should run in headed mode. - **profile** (string) - The browser profile to use. - **session** (string | null) - The session identifier, if any. ``` -------------------------------- ### Get Browser Automation Configuration Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the current configuration for browser automation. Requires the project ID. ```bash curl "http://localhost:8000/settings/browser-use" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### Get Sandbox File Tree Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the active project's sandbox as a nested JSON tree. User-visible paths are included, while hidden directories like .kady/, .gemini/, and .venv/ are excluded. Requires an 'X-Project-Id' header. ```bash curl "http://localhost:8000/sandbox/tree" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### Get Turn Manifest Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Returns the full reproducibility manifest for a turn, including input hashes, model versions, MCP servers, delegation records, and output deliverables. ```bash curl "http://localhost:8000/turns/sess_abc123/018f3a1b0000abc1234/manifest" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### Get Project Cost Summary Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the cumulative USD spend for a project, aggregated across all sessions, along with budget classification. Requires an 'X-Project-Id' header. ```bash curl http://localhost:8000/projects/genomics-abc123/costs \ -H "X-Project-Id: default" # Response { "projectId": "genomics-abc123", "totalUsd": 3.47, "orchestratorUsd": 0.82, "expertUsd": 2.65, "totalTokens": 148200, "sessionCount": 4, "hasPending": false, "bySession": { "sess_01": {"sessionId": "sess_01", "totalUsd": 1.20, "totalTokens": 52000} }, "limitUsd": 10.0, "budget": { "totalUsd": 3.47, "limitUsd": 10.0, "ratio": 0.347, "state": "ok" } } ``` -------------------------------- ### Initialize Project Sandbox with uv Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Initialize or refresh the project sandbox, including downloading skills, using uv to run the prep_sandbox.py script. ```bash uv run python prep_sandbox.py ``` -------------------------------- ### Clone and Navigate Project Directory Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/README.md Use these bash commands to download the project and enter its directory. This is the first step in setting up the K-Dense BYOK project. ```bash git clone https://github.com/K-Dense-AI/k-dense-byok.git cd k-dense-byok ``` -------------------------------- ### Build Frontend for Production Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Create a production build of the frontend application. ```bash npm run build ``` -------------------------------- ### GET /health Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Performs a health check on the system. ```APIDOC ## GET /health ### Description Performs a health check on the system. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The health status of the system (e.g., "ok"). ``` -------------------------------- ### Initialize Project Sandbox Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Initializes the project sandbox, synchronizing the virtual environment and downloading necessary skills. Returns paths related to the sandbox. ```python from kady_agent.projects import init_project_sandbox paths = init_project_sandbox(meta.id, sync_venv=True, download_skills=True) print(paths.sandbox) # Path("projects/proteomics-study-a1b2c3/sandbox") ``` -------------------------------- ### GET /ollama/models Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Proxies to `OLLAMA_BASE_URL` and returns discovered models in the UI's model shape. ```APIDOC ## GET /ollama/models ### Description Proxies to `OLLAMA_BASE_URL` (default: `http://localhost:11434`) and returns discovered models in the UI's model shape. ### Method GET ### Endpoint /ollama/models ### Response #### Success Response (200) - **available** (boolean) - Indicates if models are available. - **models** (array) - A list of discovered models. - **id** (string) - The unique identifier for the model. - **label** (string) - The display label for the model. - **provider** (string) - The provider of the model (e.g., "Ollama"). - **tier** (string) - The pricing tier of the model. - **context_length** (integer) - The context length supported by the model. - **pricing** (object) - Pricing information for the model. - **prompt** (number) - Cost per prompt token. - **completion** (number) - Cost per completion token. - **modality** (string) - The modality of the model (e.g., "text->text"). - **description** (string) - A description of the model. ``` -------------------------------- ### GET /config Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves non-secret feature flags, such as whether Modal remote compute is configured. ```APIDOC ## GET /config ### Description Retrieves non-secret feature flags, such as whether Modal remote compute is configured. ### Method GET ### Endpoint /config ### Response #### Success Response (200) - **modal_configured** (boolean) - Indicates if Modal remote compute is configured. ``` -------------------------------- ### Configure API Keys and Models Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Set up API keys for various services like OpenRouter, Exa, Parallel, and Modal, and optionally override default model configurations. ```bash # kady_agent/.env # Required: LLM access via OpenRouter OPENROUTER_API_KEY=sk-or-v1-... # Optional: override default models DEFAULT_AGENT_MODEL=openrouter/anthropic/claude-opus-4.7 DEFAULT_EXPERT_MODEL=openrouter/google/gemini-3.1-pro-preview # Optional: web search (choose one or both) EXA_API_KEY=... PARALLEL_API_KEY=... # Optional: remote compute on Modal GPUs MODAL_TOKEN_ID=... MODAL_TOKEN_SECRET=... # Optional: point at a non-standard Ollama instance OLLAMA_BASE_URL=http://localhost:11434 # Optional: override project storage location KADY_PROJECTS_ROOT=/data/kady-projects ``` -------------------------------- ### GET /system/chrome-profiles Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Returns all Chrome browser profiles found on the current machine for browser automation configuration. ```APIDOC ## GET /system/chrome-profiles ### Description Returns all Chrome browser profiles found on the current machine for browser automation configuration. ### Method GET ### Endpoint /system/chrome-profiles ### Response #### Success Response (200) - **profiles** (array) - A list of detected Chrome profiles. - **id** (string) - The unique identifier for the profile. - **name** (string) - The name of the profile. - **email** (string) - The email associated with the profile. - **path** (string) - The file system path to the profile directory. ``` -------------------------------- ### init_project_sandbox Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Initializes the project sandbox, including setting up a virtual environment and downloading necessary skills. This is typically called as a background task. ```APIDOC ## init_project_sandbox ### Description Initializes the project sandbox, including setting up a virtual environment and downloading necessary skills. This is typically called as a background task. ### Parameters - **meta.id**: (string) - Identifier for the project. - **sync_venv**: (boolean) - Whether to synchronize the virtual environment. Defaults to True. - **download_skills**: (boolean) - Whether to download skills. Defaults to True. ### Returns - paths: An object containing paths related to the project sandbox. ``` -------------------------------- ### Get Feature Flags Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves non-secret feature flags, such as whether Modal remote compute is configured. No authentication required. ```bash curl "http://localhost:8000/config" ``` -------------------------------- ### Initialize Sandbox Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Idempotent operation to (re-)initialize the project sandbox. This includes setting up GEMINI.md, .gemini/settings.json, pyproject.toml, syncing the virtual environment, and downloading scientific skills. Requires 'Content-Type' and 'X-Project-Id' headers. ```bash curl -X POST http://localhost:8000/projects/genomics-abc123/sandbox/init \ -H "Content-Type: application/json" \ -H "X-Project-Id: default" \ -d '{"sync_venv": true, "download_skills": true}' # Response {"ok": true} ``` -------------------------------- ### GET /settings/mcps/status Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Probes each configured MCP server to determine its authentication status, such as signed-in, needs OAuth, or token expiry. ```APIDOC ## GET /settings/mcps/status ### Description Probes each configured MCP server and returns auth status (signed-in, needs OAuth, token expiry). ### Method GET ### Endpoint `/settings/mcps/status` ### Response #### Success Response (200) - A JSON object detailing the authentication status for each MCP server. ``` -------------------------------- ### Create Project Programmatically Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a project entry and its on-disk skeleton using the `create_project` function. Requires project name, description, tags, and spend limit. Prints the project ID and its dictionary representation. ```python from kady_agent.projects import create_project, init_project_sandbox # Create the registry entry and on-disk skeleton meta = create_project( name="Proteomics Study", description="LC-MS/MS data analysis", tags=["proteomics", "mass-spec"], spend_limit_usd=50.0, ) print(meta.id) # e.g. "proteomics-study-a1b2c3" print(meta.to_dict()) # full serializable dict ``` -------------------------------- ### create_project() Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a project programmatically, including the registry entry and on-disk skeleton. ```APIDOC ## create_project() ### Description Creates a project programmatically, including the registry entry and on-disk skeleton. ### Parameters - **name** (string) - Required - The name of the project. - **description** (string) - Optional - A description for the project. - **tags** (list of strings) - Optional - Tags associated with the project. - **spend_limit_usd** (float) - Optional - The spending limit for the project in USD. ### Returns - **meta** (object) - Metadata about the created project. - **id** (string) - The unique identifier for the project. - **to_dict()** (function) - Returns a serializable dictionary representation of the project metadata. ``` -------------------------------- ### GET /settings/mcps Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the active project's custom MCP server definitions. Returns a JSON object keyed by server name. ```APIDOC ## GET /settings/mcps ### Description Returns the active project's custom MCP server definitions as a JSON object keyed by server name. ### Method GET ### Endpoint `/settings/mcps` ### Response #### Success Response (200) - A JSON object where keys are MCP server names and values are their definitions. Definitions can include: - **command** (string) - The command to execute for the MCP server. - **args** (array of strings) - Arguments for the command. - **httpUrl** (string) - The HTTP URL for the MCP server. - **headers** (object) - Custom headers to send with HTTP requests. ``` -------------------------------- ### Project Layout Overview Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/docs/architecture.md Illustrates the directory structure of the K-Dense BYOK project, highlighting key files and directories for server, agent, web, documentation, and user projects. ```tree k-dense-byok/ ├── start.sh ← The one script that starts everything ├── server.py ← Backend server ├── kady_agent/ ← Kady's brain: instructions, tools, and config │ ├── env.example ← Template for your API keys (copy to .env) │ ├── .env ← Your API keys (created from env.example) │ ├── agent.py ← Main agent definition │ └── tools/ ← Tools Kady can use (web search, delegation, etc.) ├── web/ ← Frontend (the UI you see in your browser) ├── docs/ ← Extended documentation (this folder) └── projects/ ← All user work, one subdirectory per named project ├── index.json ← Project registry (names, tags, archived flag) └── default/ ← The "Default" project ├── project.json ← Project metadata ├── sandbox/ ← Workspace for files and expert tasks │ └── .kady/ │ └── runs// ← Per-tab cost ledger and turn artifacts ├── custom_mcps.json ← Per-project custom MCP servers └── sessions.db ← Chat history (SQLite, one session per chat tab) ``` -------------------------------- ### Get Turn Manifest Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Returns the full reproducibility manifest for a specific turn, including input hashes, model versions, and output deliverables. ```APIDOC ## GET /turns/{session_id}/{turn_id}/manifest — Get turn manifest Returns the full reproducibility manifest for a turn: input hashes, model versions, MCP servers used, delegation records, and output deliverables. ### Method GET ### Endpoint /turns/{session_id}/{turn_id}/manifest ### Path Parameters - **session_id** (string) - Required - The ID of the session. - **turn_id** (string) - Required - The ID of the turn. ### Headers - **X-Project-Id**: string ### Response #### Success Response (200) - **turnId** (string) - The ID of the turn. - **sessionId** (string) - The ID of the session. - **timestamp** (string) - The timestamp of the turn. - **input** (object) - Information about the turn's input. - **promptSha256** (string) - SHA256 hash of the prompt. - **promptPreview** (string) - A preview of the prompt. - **attachments** (array) - List of input attachments. - **path** (string) - Path of the attachment. - **sha256** (string) - SHA256 hash of the attachment. - **bytes** (integer) - Size of the attachment in bytes. - **databases** (array) - List of databases used. - **skills** (array) - List of skills invoked. - **compute** (object or null) - Compute details, if any. - **env** (object) - Environment details. - **kadyVersion** (string) - Kady version. - **model** (string) - Model used. - **expertModel** (string) - Expert model used. - **pythonVersion** (string) - Python version. - **seed** (string) - Random seed. - **delegations** (array) - List of delegations made during the turn. - **id** (string) - Delegation ID. - **durationMs** (integer) - Duration of delegation in milliseconds. - **skillsUsed** (array) - Skills used in delegation. - **deliverables** (array) - Deliverables produced by delegation. - **output** (object) - Information about the turn's output. - **durationMs** (integer) - Duration of the turn in milliseconds. - **deliverables** (array) - List of output deliverables. - **citations** (object) - Citation information. - **total** (integer) - Total number of citations. - **verified** (integer) - Number of verified citations. - **unresolved** (integer) - Number of unresolved citations. - **manifestSha256** (string) - SHA256 hash of the manifest. ``` -------------------------------- ### Run All Backend Tests with uv Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Execute all backend tests using uv. This command is equivalent to the CI test suite. ```bash uv run pytest ``` -------------------------------- ### Get MCP Server Auth Status Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Probes each configured MCP server to determine its authentication status, such as signed-in, requiring OAuth, or token expiry. ```bash curl "http://localhost:8000/settings/mcps/status" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### MCP Configuration: write_merged_settings() and load_custom_mcps() Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Demonstrates how to load, modify, and save custom MCP configurations, then write the merged settings for the Gemini CLI. It also shows how to obtain an access token. ```APIDOC ## `write_merged_settings()` / `load_custom_mcps()` — MCP configuration ### Description This function allows users to manage custom Machine Communication Protocol (MCP) configurations. It enables loading existing custom MCPs, adding new ones, saving the changes, and then writing the merged settings to a file compatible with the Gemini CLI. Additionally, it includes a mechanism to retrieve an OAuth access token. ### Method Python SDK functions ### Parameters None explicitly documented for the primary functions, but `set_active_project` takes a project ID string, and `write_merged_settings` takes a directory path. ### Request Example ```python from kady_agent.mcp import ( build_default_settings, load_custom_mcps, save_custom_mcps, write_merged_settings, get_access_token, ) from kady_agent.projects import set_active_project, ACTIVE_PROJECT, active_paths token = set_active_project("genomics-abc123") try: # Read current custom servers custom = load_custom_mcps() print(custom) # {"my-server": {"command": "uvx", "args": [...]}} # Add a new server custom["pubchem"] = {"httpUrl": "https://pubchem.example.com/mcp"} save_custom_mcps(custom) # Rebuild and write the merged settings.json for the Gemini CLI paths = active_paths() write_merged_settings(paths.gemini_settings_dir) # Check/refresh an OAuth token before spawning the expert access_token = await get_access_token("paperclip") if access_token: print("Token valid:", access_token[:20] + "...") finally: ACTIVE_PROJECT.reset(token) ``` ### Response #### Success Response - `custom` (dict) - A dictionary representing the loaded custom MCP configurations. - `access_token` (str) - A valid OAuth token if retrieved successfully. #### Response Example ```json { "my-server": {"command": "uvx", "args": [...]}, "pubchem": {"httpUrl": "https://pubchem.example.com/mcp"} } ``` ``` Token valid: sk-or-v1-... ``` ``` -------------------------------- ### Get Custom MCP Servers Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves the active project's custom MCP server definitions. The response is a JSON object keyed by server name. ```bash curl "http://localhost:8000/settings/mcps" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### Project Sandbox Layout Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Illustrates the directory structure for project data, including registry, metadata, custom servers, chat sessions, and sandbox files for LLM call costs and reproducibility manifests. ```json { "projects/": { "index.json": "project registry (names, tags, archived flag)", "/": { "project.json": "metadata", "custom_mcps.json": "per-project MCP servers (UI-edited)", "sessions.db": "SQLite, one row per chat tab", "sandbox/": "files visible to all tabs in the project", " .kady/runs//": { " costs.jsonl": "cost ledger (one row per LLM call)", " /manifest.json": "reproducibility manifest per turn" } } } } ``` -------------------------------- ### Download Entire Sandbox as ZIP Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Downloads the entire sandbox content as a single ZIP archive. ```bash curl "http://localhost:8000/sandbox/download-all" \ -H "X-Project-Id: genomics-abc123" \ --output sandbox.zip ``` -------------------------------- ### Write a file Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates or overwrites a sandbox file. Accepts any content-type; binary and text both work. ```APIDOC ## PUT /sandbox/file — Write a file Creates or overwrites a sandbox file. Accepts any content-type; binary and text both work. ### Method PUT ### Endpoint /sandbox/file ### Parameters #### Query Parameters - **path** (string) - Required - The path to the file to write. #### Request Body - (any) - The content of the file. ### Request Example ```bash # Write a markdown report curl -X PUT "http://localhost:8000/sandbox/file?path=results/notes.md" \ -H "X-Project-Id: genomics-abc123" \ -H "Content-Type: text/plain" \ --data-binary "# Analysis Notes\n\nSNP count: 1024" ``` ### Response #### Success Response (200) - **saved** (string) - The path of the saved file. - **size** (integer) - The size of the saved file in bytes. ### Response Example ```json {"saved": "results/notes.md", "size": 38} ``` ``` -------------------------------- ### Run Frontend Tests Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Execute the frontend unit and integration tests using Vitest. ```bash npm run test ``` -------------------------------- ### Create a directory Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a new directory within the sandbox. ```APIDOC ## POST /sandbox/mkdir — Create a directory Creates a new directory within the sandbox. ### Method POST ### Endpoint /sandbox/mkdir ### Parameters #### Request Body - **path** (string) - Required - The path for the new directory. ### Request Example ```bash curl -X POST "http://localhost:8000/sandbox/mkdir" \ -H "Content-Type: application/json" \ -H "X-Project-Id: genomics-abc123" \ -d '{"path": "figures"}' ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. ### Response Example ```json {"ok": true} ``` ``` -------------------------------- ### Generate Backend Test Coverage Report with uv Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Generate a test coverage report for the backend using uv. The command fails if coverage is below 70%. ```bash uv run pytest --cov ``` -------------------------------- ### Manage MCPs and Write Settings Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Load, modify, and save custom MCP configurations, then write the merged settings for the Gemini CLI. Ensure you have a valid OAuth token before spawning an expert. ```python from kady_agent.mcp import ( build_default_settings, load_custom_mcps, save_custom_mcps, write_merged_settings, get_access_token, ) from kady_agent.projects import set_active_project, ACTIVE_PROJECT, active_paths token = set_active_project("genomics-abc123") try: # Read current custom servers custom = load_custom_mcps() print(custom) # {"my-server": {"command": "uvx", "args": [...]}} # Add a new server custom["pubchem"] = {"httpUrl": "https://pubchem.example.com/mcp"} save_custom_mcps(custom) # Rebuild and write the merged settings.json for the Gemini CLI paths = active_paths() write_merged_settings(paths.gemini_settings_dir) # Check/refresh an OAuth token before spawning the expert access_token = await get_access_token("paperclip") if access_token: print("Token valid:", access_token[:20] + "...") finally: ACTIVE_PROJECT.reset(token) ``` -------------------------------- ### Create Sandbox Directory Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates a new directory within the sandbox. ```bash curl -X POST "http://localhost:8000/sandbox/mkdir" \ -H "Content-Type: application/json" \ -H "X-Project-Id: genomics-abc123" \ -d '{"path": "figures"}' ``` -------------------------------- ### List All Projects Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Retrieves a list of all projects, including archived ones. Requires an 'X-Project-Id' header. ```bash curl http://localhost:8000/projects \ -H "X-Project-Id: default" # Response [ { "id": "genomics-abc123", "name": "Genomics Study", "description": "GWAS analysis project", "tags": ["genomics", "GWAS"], "createdAt": "2025-01-10T12:00:00+00:00", "updatedAt": "2025-01-15T09:30:00+00:00", "archived": false, "spendLimitUsd": 10.0 } ] ``` -------------------------------- ### Write Sandbox File Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Creates or overwrites a sandbox file. Accepts any content-type; binary and text both work. ```bash # Write a markdown report curl -X PUT "http://localhost:8000/sandbox/file?path=results/notes.md" \ -H "X-Project-Id: genomics-abc123" \ -H "Content-Type: text/plain" \ --data-binary "# Analysis Notes\n\nSNP count: 1024" ``` -------------------------------- ### Run Integration Tests with uv Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/AGENTS.md Execute only the FastAPI and multi-module integration tests for the backend using uv. ```bash uv run pytest -m integration ``` -------------------------------- ### Serve File Inline Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Returns the file with its correct MIME type for in-browser rendering (images, PDFs, etc.). ```bash # Embed in an tag or open PDF in browser curl "http://localhost:8000/sandbox/raw?path=figures/volcano_plot.png" \ -H "X-Project-Id: genomics-abc123" \ --output volcano_plot.png ``` -------------------------------- ### List OpenRouter Models with Tool Support Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/docs/model-selection.md This Python code uses the OpenRouter SDK to list models that support the 'tools' parameter. These models are suitable for Kady's orchestrator and expert tasks. ```python client.models.list(supported_parameters="tools") ``` -------------------------------- ### Download entire sandbox as ZIP Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Downloads the entire sandbox content as a ZIP archive. ```APIDOC ## GET /sandbox/download-all — Download entire sandbox as ZIP Downloads the entire sandbox content as a ZIP archive. ### Method GET ### Endpoint /sandbox/download-all ### Request Example ```bash curl "http://localhost:8000/sandbox/download-all" \ -H "X-Project-Id: genomics-abc123" \ --output sandbox.zip ``` ``` -------------------------------- ### Sign in to MCP Server Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Initiates an OAuth 2.0 + PKCE flow for an HTTP MCP server. Requires the server name and project ID. Returns an authorization URL for the user to visit. ```bash curl -X POST "http://localhost:8000/settings/mcps/paperclip/sign-in" \ -H "X-Project-Id: genomics-abc123" ``` -------------------------------- ### Download Directory as ZIP Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Zips a directory (excluding hidden files and system entries) and streams it back as a ZIP archive. ```bash curl "http://localhost:8000/sandbox/download-dir?path=results" \ -H "X-Project-Id: genomics-abc123" \ --output results.zip ``` -------------------------------- ### (Re-)initialize sandbox Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Idempotently initializes or re-initializes the project's sandbox environment. This includes setting up core files, synchronizing virtual environments, and downloading necessary skills. ```APIDOC ## POST /projects/{project_id}/sandbox/init ### Description Idempotent: lays down `GEMINI.md`, merged `.gemini/settings.json`, `pyproject.toml`, runs `uv sync`, and downloads scientific skills. ### Method POST ### Endpoint /projects/{project_id}/sandbox/init ### Parameters #### Path Parameters - **project_id** (string) - Required - The ID of the project whose sandbox to initialize. #### Query Parameters - **X-Project-Id** (string) - Required - Identifier for the project context. #### Request Body - **sync_venv** (boolean) - Optional - Whether to synchronize the virtual environment. Defaults to `true` if not specified. - **download_skills** (boolean) - Optional - Whether to download scientific skills. Defaults to `true` if not specified. ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the initialization was successful. ### Request Example ```bash curl -X POST http://localhost:8000/projects/genomics-abc123/sandbox/init \ -H "Content-Type: application/json" \ -H "X-Project-Id: default" \ -d '{"sync_venv": true, "download_skills": true}' ``` ### Response Example ```json {"ok": true} ``` ``` -------------------------------- ### Record Deliverables for Kady Agent Source: https://github.com/k-dense-ai/k-dense-byok/blob/main/kady_agent/instructions/gemini_cli.md Creates a JSON file listing all files created or modified during a delegation, excluding internal Kady directories. This is essential for tracking outputs. ```bash cat > .kady/expert/$KADY_DELEGATION_ID/deliverables.json <<'EOF' [ "report/analysis.md", "figures/fig1.png" ] EOF ``` -------------------------------- ### Check Project Budget Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Verify the project's budget status against a specified limit in USD. The result indicates if the budget is 'ok', 'warn' (approaching limit), or 'exceeded'. ```python from kady_agent.runtime import check_project_budget result = check_project_budget( project_id="genomics-abc123", limit_usd=10.0, ) # result["state"] is one of: "ok", "warn" (>= 80%), "exceeded" (>= 100%) print(result) # { # "totalUsd": 7.84, # "limitUsd": 10.0, # "ratio": 0.784, # "state": "warn" # } ``` -------------------------------- ### Project Budget Check: check_project_budget() Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Checks the budget for a given project against a specified limit in USD. Returns the current spending status and ratio. ```APIDOC ## `check_project_budget()` — Spend limit enforcement ### Description This function enforces spend limits by checking the current budget utilization for a specified project against a defined monetary limit. It returns a status indicating whether the budget is okay, nearing a warning threshold, or has been exceeded. ### Method Python SDK function ### Parameters - **project_id** (str) - Required - The unique identifier for the project. - **limit_usd** (float) - Required - The budget limit in US Dollars. ### Request Example ```python from kady_agent.runtime import check_project_budget result = check_project_budget( project_id="genomics-abc123", limit_usd=10.0, ) # result["state"] is one of: "ok", "warn" (>= 80%), "exceeded" (>= 100%) print(result) ``` ### Response #### Success Response - `totalUsd` (float) - The total amount spent in USD. - `limitUsd` (float) - The budget limit in USD. - `ratio` (float) - The ratio of total spent to the limit. - `state` (str) - The budget status: "ok", "warn", or "exceeded". #### Response Example ```json { "totalUsd": 7.84, "limitUsd": 10.0, "ratio": 0.784, "state": "warn" } ``` ``` -------------------------------- ### Manage Turn Lifecycle with Open/Close Turn Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Manages the lifecycle of a turn in the manifest, from opening with initial parameters to closing with the assistant's reply. Requires `asyncio`. ```python import asyncio from kady_agent.runtime import open_turn, close_turn from kady_agent.projects import set_active_project, ACTIVE_PROJECT async def tracked_turn(): token = set_active_project("genomics-abc123") try: turn_id, manifest = await open_turn( session_id="sess_abc123", user_text="Analyze the uploaded FASTA file", attachments=["user_data/sequences.fasta"], model="openrouter/anthropic/claude-opus-4.7", expert_model="openrouter/google/gemini-3.1-pro-preview", skills=["bioinformatics"], databases=["NCBI"], ) print(f"Turn opened: {turn_id}") print(f"Seed: {manifest['env']['seed']}") # reproducibility seed # ... agent runs here ... assistant_reply = "I analyzed the sequences and found 3 novel variants." final_manifest = await close_turn( session_id="sess_abc123", turn_id=turn_id, assistant_text=assistant_reply, ) print(f"Duration: {final_manifest['output']['durationMs']} ms") print(f"Deliverables: {final_manifest['output']['deliverables']}") finally: ACTIVE_PROJECT.reset(token) asyncio.run(tracked_turn()) ``` -------------------------------- ### Download directory as ZIP Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Zips a directory (excluding hidden files and system entries) and streams it back. ```APIDOC ## GET /sandbox/download-dir — Download directory as ZIP Zips a directory (excluding hidden files and system entries) and streams it back. ### Method GET ### Endpoint /sandbox/download-dir ### Parameters #### Query Parameters - **path** (string) - Required - The path to the directory to zip and download. ### Request Example ```bash curl "http://localhost:8000/sandbox/download-dir?path=results" \ -H "X-Project-Id: genomics-abc123" \ --output results.zip ``` ``` -------------------------------- ### delegate_task() Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Spawns the Gemini CLI expert as a subprocess within the project sandbox to execute a given prompt and returns the results. ```APIDOC ## delegate_task() ### Description Spawns the Gemini CLI expert as a subprocess within the project sandbox to execute a given prompt and returns the results, including skills and tools used. ### Parameters - **prompt**: (string) - The prompt to be executed by the Gemini CLI expert. - **working_directory**: (string, optional) - The working directory for the subprocess. Defaults to the project sandbox. ### Returns - result: A dictionary containing the expert's final response text, skills used, tools used, and error status. - `result`: (string) - The expert's final response text. - `skills_used`: (list of strings) - A list of skills utilized by the expert. - `tools_used`: (dict) - A dictionary detailing the usage of various tools. - `error`: (boolean) - True if the subprocess failed. - `budgetBlocked`: (boolean) - True if the spend limit was exceeded. ### Example Usage ```python import asyncio from kady_agent.tools.gemini_cli import delegate_task from kady_agent.projects import set_active_project, ACTIVE_PROJECT async def run_expert(): token = set_active_project("genomics-abc123") try: result = await delegate_task( prompt="Run GWAS on the uploaded variants.vcf and produce a Manhattan plot", working_directory=None, # defaults to project sandbox ) finally: ACTIVE_PROJECT.reset(token) print(result["result"]) print(result["skills_used"]) print(result["tools_used"]) asyncio.run(run_expert()) ``` ``` -------------------------------- ### Read Sandbox File (Text) Source: https://context7.com/k-dense-ai/k-dense-byok/llms.txt Reads a sandbox file as plain text. Files larger than 512 KB are rejected. ```bash curl "http://localhost:8000/sandbox/file?path=results/report.md" \ -H "X-Project-Id: genomics-abc123" ```