{
  "openapi": "3.1.0",
  "info": {
    "title": "DG-i™ API v2",
    "version": "2.0.0",
    "description": "DG-i™ is your AI data assistant that can analyze data, write code, do research, and automate tasks. Think of it as having a smart colleague who can help with data and coding work.\n\n## Quick Start for Developers\n\n**The Basics:**\n1. **Sessions** = Conversations with the AI (like chat rooms)\n2. **Tasks** = Work you ask the AI to do (returns a task_id to track progress)\n3. **Files** = Your data (CSV) and code (Python scripts)\n4. **Connections** = The credentials to access your databases, APIs and more\n\n**Simple Example - Ask a Question:**\n```\n1. Create session: POST /v2/session/new\n2. Create task: POST /v2/{session_id}/task/new with {\"question\": \"analyze my data\"}\n3. Get updates: GET /v2/tasks/{task_id}/messages\n4. Task done when status = 'completed'\n```\n\n## Code Execution Guide\n\n**When AI writes code for you:**\n1. AI creates a folder like `code_execution_123456789` with Python files\n2. Main file is always `script.py` (entry point)\n3. You can edit any file, but execution always starts from `script.py`\n\n**To run the code:**\n```\nPOST /v2/{session_id}/task/new\n{\n  \"run_file\": \"code_execution_123456789/script.py\"\n}\n```\n\n**To see console output (like print statements):**\n- Poll `/v2/tasks/{task_id}/messages` every 100ms\n- Use `?timestamp={last_msg_timestamp}` to get only new messages\n- If no messages show up, try `/v2/tasks/{task_id}/output` as backup",
    "contact": {
      "email": "cm@datagran.io",
      "name": "API Support"
    }
  },
  "servers": [
    {
      "url": "https://api.dgintel.ai",
      "description": "Production server"
    }
  ],
  "security": [
    {
      "HTTPBearer": []
    }
  ],
  "tags": [
    {
      "name": "Core",
      "description": "Essential endpoints for API testing and health checks"
    },
    {
      "name": "Auth",
      "description": "Endpoints for authenticating users. Login returns the list of organizations the user belongs to."
    },
    {
      "name": "Sessions",
      "description": "Manage chat sessions for organizing conversations and tasks"
    },
    {
      "name": "Tasks",
      "description": "Think of Tasks as 'jobs' you give to the AI agent. You create a task, the AI works on it, and you get results back.\n\n**What are Tasks?**\nTasks are how you ask the AI to do work - analyze data, write code, do research, or run Python scripts.\n\n**Basic Flow:**\n1. Create a task → Get a task_id\n2. Check progress using task_id\n3. Get results when done\n\n**Types of Tasks:**\n- **Question**: Ask the AI to analyze data or answer questions\n- **Deep Research**: Request comprehensive research on a topic\n- **Run File**: Execute Python code (always runs 'script.py' in the specified directory)\n\n**Getting Results:**\n- Use `/messages` endpoint to get updates while task is running (poll every 100ms for real-time updates)\n- For code execution, if no messages appear, use `/output` endpoint as backup\n- Task is done when status = 'completed'\n\n**Pro Tip:** Save your task_id! You'll need it to check progress and get results."
    },
    {
      "name": "Files",
      "description": "Manage two types of files: 1) CSV files for data analysis (uploaded via /files/upload), and 2) Code execution files in directories like 'code_execution_123456789' containing Python scripts. Code execution ALWAYS runs 'script.py' within the specified directory. To edit and run code: save your changes using POST /file/{filePath}, then execute using run_file: '{code_execution_dir}/script.py'"
    },
    {
      "name": "Connections",
      "description": "Manage secure connections to external databases and APIs. Share connections with team members to give them read-only access to credentials. Owners have full control (create, update, delete, share), while shared users can only view connection details and credentials."
    },
    {
      "name": "Scheduled Jobs",
      "description": "Automate recurring tasks with scheduled job management"
    },
    {
      "name": "Understanding",
      "description": "Deep Understanding creates AI knowledge bases from GitHub repos and URLs, giving your AI agent comprehensive context about your codebase or documentation.\n\n**What is Deep Understanding?**\nIt's like teaching the AI about your specific project. The AI analyzes your GitHub repo, documentation, and support URLs to build a knowledge base that it references during tasks.\n\n## Implementation Guide\n\n**Step 1: Store GitHub Token** (one-time setup)\n```\nPOST /v2/connections/new\n{\n  \"type\": \"api\",\n  \"name\": \"Github MyProject\",\n  \"credentials\": { \"Token\": \"github_token_here\" }\n}\n→ Returns connection_id (use as metadata_store_id)\n```\n\n**Step 2: Create Understanding**\n```\nPOST /v2/understanding/new\n{\n  \"name\": \"My Project\",\n  \"metadata_store_id\": \"connection_id_from_step1\",\n  \"github_repo\": { \"url\": \"https://github.com/user/repo\" },\n  \"support_urls\": { \"general\": \"https://docs.example.com\" }\n}\n→ Returns understanding_id\n```\n\n**Step 3: Start Deep Research** (analyzes your repo)\n```\nPOST /v2/task/new\n{\n  \"deep_research\": \"understanding_id_from_step2\"\n}\n→ AI spends 5-30 min analyzing entire codebase\n→ Generates comprehensive PDF documentation\n```\n\n**Step 4: Use in Any Task**\n```\nPOST /v2/{session_id}/task/new\n{\n  \"question\": \"How does the auth system work?\",\n  \"understanding_id\": \"your_understanding_id\"\n}\n→ AI answers with full context of your codebase\n```\n\n**Key Points:**\n- GitHub token stored securely in metadata store\n- Supports private repos through OAuth\n- Generated PDF available via base64 in GET /understanding/{id}\n- Understanding persists across all sessions\n- Poll task status to know when analysis is complete"
    },
    {
      "name": "Organizations",
      "description": "Manage organization members.\n\nKey implementation notes:\n- Only organization owners can list or add members (non-owners receive HTTP 403)\n- Members must be registered users (no auto-creation)\n- Prevents duplicate memberships\n- Prevents owner from adding themselves\n- No delete endpoint currently available\n- New organizations return an empty members array\n- Authentication required: Bearer token (JWT or API key starting with dgi_)"
    }
  ],
  "paths": {
    "/v2/hello": {
      "get": {
        "tags": ["Core"],
        "summary": "Test API Connection",
        "description": "A simple endpoint to test your API connection and authentication. Returns a greeting with timestamp to confirm your API key is working correctly.",
        "operationId": "hello_v2",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "operational"
                    },
                    "version": {
                      "type": "string", 
                      "example": "1.0.0"
                    },
                    "timestamp": {
                      "type": "string",
                      "format": "date-time",
                      "example": "2025-09-10T12:00:00Z"
                    }
                  }
                }
              }
            }
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/session/new": {
      "post": {
        "tags": ["Sessions"],
        "summary": "Create New Session",
        "description": "Creates a new chat session for organizing your conversations and tasks. Each session maintains its own context and history, allowing you to work on multiple projects simultaneously.",
        "operationId": "new_session_v2",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "string",
                  "example": "session_abc123def456"
                }
              }
            }
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/sessions": {
      "get": {
        "tags": ["Sessions"],
        "summary": "List Sessions",
        "description": "Retrieves a paginated list of your chat sessions, including session IDs, titles, and creation dates. Use this to manage and navigate between your different projects and conversations.",
        "operationId": "list_sessions_v2",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            },
            "description": "Page number for pagination"
          }
        ],
        "responses": {
          "200": {
            "description": "Sessions retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "OK"
                    },
                    "sessions": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "session_id": {
                            "type": "string",
                            "example": "session_abc123def456"
                          },
                          "session_title": {
                            "type": "string",
                            "nullable": true,
                            "example": "Sales Data Analysis"
                          },
                          "created_at": {
                            "type": "string",
                            "format": "date-time",
                            "example": "2025-09-10T10:30:00Z"
                          }
                        }
                      }
                    },
                    "pagination": {
                      "type": "object",
                      "properties": {
                        "total": {"type": "integer"},
                        "page": {"type": "integer"},
                        "has_more": {"type": "boolean"}
                      }
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/sessions/{session_id}": {
      "put": {
        "tags": ["Sessions"],
        "summary": "Update Session",
        "description": "Updates a session's title or other properties. Use this to organize your sessions with meaningful names that help you identify different projects or workflows.",
        "operationId": "update_session_v2",
        "parameters": [
          {
            "name": "session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to update"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "session_title": {
                    "type": "string",
                    "example": "Q4 Sales Analysis Project"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Session updated successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/session/{chat_session_id}": {
      "delete": {
        "tags": ["Sessions"],
        "summary": "Delete Session",
        "description": "Permanently deletes a chat session and all its associated history, files, and tasks. This action cannot be undone, so use carefully when cleaning up completed projects.",
        "operationId": "delete_session_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to delete"
          }
        ],
        "responses": {
          "200": {
            "description": "Session deleted successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/{chat_session_id}/history": {
      "get": {
        "tags": ["Sessions"],
        "summary": "Get Session History",
        "description": "Retrieves the complete conversation history for a specific chat session, including all questions asked and responses received. Useful for reviewing past interactions and maintaining context.",
        "operationId": "get_session_history_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to get history for"
          }
        ],
        "responses": {
          "200": {
            "description": "Session history retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "history": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "message": {
                            "type": "string",
                            "example": "Analyze the sales data"
                          },
                          "message_type": {
                            "type": "string",
                            "enum": ["question", "answer"],
                            "example": "question"
                          },
                          "timestamp": {
                            "type": "string",
                            "format": "date-time",
                            "example": "2025-09-10T10:30:00Z"
                          },
                          "task_id": {
                            "type": "string",
                            "nullable": true,
                            "example": "task_xyz789abc123"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/{chat_session_id}/task/new": {
      "post": {
        "tags": ["Tasks"],
        "summary": "Create Task in Session",
        "description": "Creates a new task within an existing chat session. Tasks can be questions for data analysis, file execution requests, or deep research queries. For CODE EXECUTION: After editing files in a code_execution directory, create a task with run_file: '{code_execution_dir}/script.py'. Example: if your previous task returned code_execution_dir: 'code_execution_20250430203628', and you've edited files in that directory, execute with run_file: 'code_execution_20250430203628/script.py'. The system ALWAYS runs script.py as the entry point.",
        "operationId": "new_task_with_session_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID where you want to create the task"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "question": {
                    "type": "string",
                    "description": "Natural language question or instruction for data analysis",
                    "example": "Analyze the sales data and show trends"
                  },
                  "run_file": {
                    "type": "string",
                    "description": "Path to execute code. For code execution directories, use format: '{code_execution_dir}/script.py' where code_execution_dir is from a previous task (e.g., 'code_execution_123456789/script.py'). The system ALWAYS executes 'script.py' within the specified directory, regardless of which file you're editing.",
                    "example": "code_execution_123456789/script.py"
                  },
                  "deep_research": {
                    "type": "string",
                    "description": "Understanding ID to trigger deep analysis. This starts a 5-30 minute process where AI analyzes the GitHub repo and generates comprehensive documentation",
                    "example": "understanding_xyz789abc123"
                  },
                  "understanding_id": {
                    "type": "string",
                    "description": "ID of an existing Understanding to use as context. The AI will have full knowledge of your codebase when answering questions",
                    "example": "understanding_xyz789abc123"
                  },
                  "resume_from_checkpoint_id": {
                    "type": "string",
                    "description": "Checkpoint ID to resume from previous state",
                    "example": "1f02a823-e208-6a11-800f-0e74e6ec030a"
                  }
                },
                "description": "Provide exactly one of: question, run_file, or deep_research"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Task created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "string",
                  "example": "task_xyz789abc123"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "detail": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "loc": {"type": "array"},
                          "msg": {"type": "string"},
                          "type": {"type": "string"}
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/task/new": {
      "post": {
        "tags": ["Tasks"],
        "summary": "Create Sessionless Task",
        "description": "Creates a new task without a session context, primarily used for deep research tasks. These tasks run independently and are ideal for comprehensive analysis that doesn't need conversation history.",
        "operationId": "new_task_sessionless_v2",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "question": {
                    "type": "string",
                    "description": "Natural language question or instruction",
                    "example": "Analyze market trends for electric vehicles"
                  },
                  "run_file": {
                    "type": "string",
                    "description": "Path to execute code. For code execution directories, use format: '{code_execution_dir}/script.py' where code_execution_dir is from a previous task (e.g., 'code_execution_123456789/script.py'). The system ALWAYS executes 'script.py' within the specified directory, regardless of which file you're editing.",
                    "example": "code_execution_123456789/script.py"
                  },
                  "deep_research": {
                    "type": "string",
                    "description": "Understanding ID to trigger deep analysis. This starts a 5-30 minute process where AI analyzes the GitHub repo and generates comprehensive documentation",
                    "example": "understanding_xyz789abc123"
                  },
                  "understanding_id": {
                    "type": "string",
                    "description": "ID of an existing Understanding to use as context. The AI will have full knowledge of your codebase when answering questions",
                    "example": "understanding_xyz789abc123"
                  },
                  "resume_from_checkpoint_id": {
                    "type": "string",
                    "description": "Checkpoint ID to resume from previous state",
                    "example": "1f02a823-e208-6a11-800f-0e74e6ec030a"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Task created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "string",
                  "example": "task_xyz789abc123"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/tasks/{task_id}": {
      "get": {
        "tags": ["Tasks"],
        "summary": "Get Task Details",
        "description": "Retrieves detailed information about a specific task, including its current status, execution results, and any generated outputs or files.",
        "operationId": "get_task_v2",
        "parameters": [
          {
            "name": "task_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The task ID to retrieve details for"
          }
        ],
        "responses": {
          "200": {
            "description": "Task details retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "description": "Task details including status and results"
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/tasks/{task_id}/output": {
      "get": {
        "tags": ["Tasks"],
        "summary": "Get Code Execution Output",
        "description": "Retrieves the complete console output from a code execution task. This is the FALLBACK method specifically for CODE EXECUTION tasks when the messages endpoint doesn't return logs. Returns the entire stdout/stderr as a single string. Only use this after task_status='completed' and if messages endpoint returned no console output for a code execution task.",
        "operationId": "get_task_output_v2",
        "parameters": [
          {
            "name": "task_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The task ID to get output from"
          }
        ],
        "responses": {
          "200": {
            "description": "Task output retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "output": {
                      "type": "string",
                      "description": "Complete execution log as a single string with all stdout/stderr from the script",
                      "example": "Starting script execution...\nLoading pandas library\nReading data.csv\nData shape: (1000, 5)\nAnalysis complete!\nResults saved to output.csv"
                    },
                    "status": {
                      "type": "string",
                      "example": "completed"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/tasks/{task_id}/messages": {
      "get": {
        "tags": ["Tasks"],
        "summary": "Get Task Messages",
        "description": "Retrieves messages from a running or completed task. Use polling with timestamps to get real-time updates as the AI agent works. For CODE EXECUTION tasks specifically, this is the primary method for getting console output - poll every 100ms to stream logs as they're generated. For ALL task types, use the timestamp parameter for pagination to get only new messages since your last request. Continue polling until task_status='completed'. When stream_url is present, the agent is using computer use. For code execution tasks that don't stream messages, use the /output endpoint as fallback.",
        "operationId": "get_task_messages_v2",
        "parameters": [
          {
            "name": "task_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The task ID to get messages from"
          },
          {
            "name": "timestamp",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date-time"
            },
            "description": "Pagination cursor - only return messages created after this timestamp. Use the timestamp from the last message in previous response to get new logs only. Essential for real-time polling to avoid duplicate messages."
          }
        ],
        "responses": {
          "200": {
            "description": "Task messages retrieved successfully. Messages vary by task type: data analysis updates, research progress, or console output for code execution. Poll using timestamp from last message for real-time updates.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "task_status": {
                      "type": "string",
                      "enum": ["new", "in_progress", "completed", "interrupted"],
                      "example": "in_progress"
                    },
                    "messages": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "msg": {
                            "type": "string",
                            "description": "The message content. Varies by task type: status updates for data analysis, research findings, or console output (stdout/stderr) for code execution.",
                            "example": "Loading libraries...\nProcessing data...\nAnalysis complete!"
                          },
                          "timestamp": {
                            "type": "string",
                            "format": "date-time",
                            "description": "When this log message was generated. Use as pagination cursor for next request.",
                            "example": "2025-09-10T14:16:13.238Z"
                          },
                          "stream_url": {
                            "type": "string",
                            "nullable": true,
                            "description": "URL to view computer use stream when agent is using computer use",
                            "example": "https://stream.dgintel.ai/computer_use_xyz789"
                          }
                        }
                      }
                    },
                    "question": {
                      "type": "string",
                      "nullable": true,
                      "description": "The original question or task (present when task is completed)",
                      "example": "explain data"
                    },
                    "answer": {
                      "type": "string",
                      "nullable": true,
                      "description": "The final answer from the AI agent (present when task is completed)",
                      "example": "This dataset has two columns, named \"a\" and \"b,\" and two rows in total. Both columns are integers with no missing values."
                    },
                    "code_execution_dir": {
                      "type": "string",
                      "nullable": true,
                      "description": "Directory containing the code execution environment. Use this to: 1) Save/edit files within this directory, 2) Execute code by running '{code_execution_dir}/script.py'. The main executable is ALWAYS 'script.py' in this directory. To run code after editing: POST your changes to /file/{code_execution_dir}/your_file.py, then create a task with run_file: '{code_execution_dir}/script.py'",
                      "example": "code_execution_20250430203628"
                    },
                    "preview_url": {
                      "type": "string",
                      "nullable": true,
                      "description": "URL to preview deployed website or application (present when task created a web preview)",
                      "example": "https://datagran-apps-deployer-fd829334-bboz53hena-uc.a.run.app"
                    },
                    "status": {
                      "type": "string",
                      "nullable": true,
                      "description": "Overall completion status (present in final response)",
                      "example": "completed"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/{chat_session_id}/files/upload": {
      "post": {
        "tags": ["Files"],
        "summary": "Upload CSV File to Session",
        "description": "Uploads a CSV file to a specific chat session for data analysis. This endpoint is ONLY for CSV data files. For code files, use the POST /file/{filePath} endpoint instead. The AI agent can analyze, process, or visualize the uploaded CSV data in subsequent tasks.",
        "operationId": "upload_file_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to upload the file to"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "The CSV file to upload (only CSV format supported)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "File uploaded successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"],
                      "example": "OK"
                    },
                    "error_message": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/{chat_session_id}/files": {
      "get": {
        "tags": ["Files"],
        "summary": "List Session Files",
        "description": "Lists all files in a chat session in a tree structure, including: 1) CSV data files uploaded for analysis, 2) Code execution directories (e.g., 'code_execution_123456789') containing Python scripts. The code execution directories are created when tasks generate code, and contain editable Python files with 'script.py' as the main executable.",
        "operationId": "list_files_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to list files for"
          }
        ],
        "responses": {
          "200": {
            "description": "Files listed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"],
                      "example": "OK"
                    },
                    "files": {
                      "type": "object",
                      "description": "Tree structure of files and directories"
                    },
                    "error_message": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/{chat_session_id}/file/{file_path}": {
      "get": {
        "tags": ["Files"],
        "summary": "Download File",
        "description": "Generates a signed download URL for a specific file in a chat session. Use this to securely access files that were uploaded or generated during task execution.",
        "operationId": "get_file_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID containing the file"
          },
          {
            "name": "file_path",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Path to the file relative to the session directory"
          }
        ],
        "responses": {
          "200": {
            "description": "Download URL generated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"]
                    },
                    "download_url": {
                      "type": "string",
                      "nullable": true,
                      "example": "https://storage.dgintel.ai/signed-url-here"
                    },
                    "error_message": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      },
      "post": {
        "tags": ["Files"],
        "summary": "Save File",
        "description": "Saves a file to a specific path in a chat session. Use this for: 1) Uploading CSV data files, 2) Saving/updating Python code files in code_execution directories. For code execution: save your edited files to '{code_execution_dir}/filename.py', then run the code by creating a task with run_file: '{code_execution_dir}/script.py'. The system ALWAYS executes 'script.py' as the entry point.",
        "operationId": "save_file_v2",
        "parameters": [
          {
            "name": "chat_session_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The session ID to save the file to"
          },
          {
            "name": "file_path",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Path where the file should be saved"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "File saved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"]
                    },
                    "error_message": {
                      "type": "string",
                      "nullable": true
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/connections/new": {
      "post": {
        "tags": ["Connections"],
        "summary": "Create Connection",
        "description": "Creates a new secure connection to external services like databases, APIs, or GitHub. Credentials are encrypted and stored securely. For Deep Understanding, use this to store GitHub tokens that allow the AI to access your private repositories. The returned connection_id is used as metadata_store_id when creating Understandings.",
        "operationId": "new_connection_v2",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "type": {
                    "type": "string",
                    "enum": ["database", "api", "other"],
                    "example": "database"
                  },
                  "name": {
                    "type": "string",
                    "example": "Production Database"
                  },
                  "description": {
                    "type": "string",
                    "example": "Main PostgreSQL database for sales data"
                  },
                  "credentials": {
                    "type": "object",
                    "description": "Connection credentials (will be encrypted)",
                    "example": {
                      "host": "db.example.com",
                      "username": "readonly_user",
                      "password": "secure_password",
                      "database": "sales_db"
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Connection created successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/connections": {
      "get": {
        "tags": ["Connections"],
        "summary": "List Connections",
        "description": "Retrieves a paginated list of your configured connections. Shows connection details without exposing sensitive credentials, helping you manage your data source integrations.",
        "operationId": "list_connections_v2",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            },
            "description": "Page number for pagination"
          },
          {
            "name": "connection_type",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": ["database", "api", "other"]
            },
            "description": "Filter connections by type"
          },
          {
            "name": "include_shared",
            "in": "query",
            "required": false,
            "schema": {
              "type": "boolean",
              "default": false
            },
            "description": "Include connections shared with you by other users. When true, returns both owned and shared connections. When false (default), returns only connections you own."
          }
        ],
        "responses": {
          "200": {
            "description": "Connections retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "OK"
                    },
                    "connections": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "connection_id": {
                            "type": "string",
                            "example": "conn_abc123def456"
                          },
                          "type": {
                            "type": "string",
                            "enum": ["database", "api", "other"]
                          },
                          "name": {
                            "type": "string",
                            "example": "Production Database"
                          },
                          "description": {
                            "type": "string",
                            "example": "Main PostgreSQL database"
                          },
                          "created_at": {
                            "type": "string",
                            "format": "date-time"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/connections/{connection_id}": {
      "get": {
        "tags": ["Connections"],
        "summary": "Get Connection",
        "description": "Retrieves detailed information about a specific connection, including decrypted credentials. Use this when you need to verify connection settings or troubleshoot connectivity issues.",
        "operationId": "get_connection_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID to retrieve"
          }
        ],
        "responses": {
          "200": {
            "description": "Connection details retrieved successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      },
      "put": {
        "tags": ["Connections"],
        "summary": "Update Connection",
        "description": "Updates an existing connection's details, name, description, or credentials. Useful for maintaining connection information as your infrastructure or access requirements change.",
        "operationId": "update_connection_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID to update"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "nullable": true,
                    "example": "Updated Database Name"
                  },
                  "description": {
                    "type": "string",
                    "nullable": true,
                    "example": "Updated description"
                  },
                  "credentials": {
                    "type": "object",
                    "nullable": true,
                    "description": "Updated credentials (will be re-encrypted)"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Connection updated successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/connections/{connection_id}/share": {
      "post": {
        "tags": ["Connections"],
        "summary": "Share Connection with Users",
        "description": "Shares a connection with specific users by email, granting them read-only access to view the connection and its credentials. Only connection owners can share. Users must exist in the system. Optionally restrict sharing to members of a specific organization.",
        "operationId": "share_connection_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID to share"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["user_emails"],
                "properties": {
                  "user_emails": {
                    "type": "array",
                    "items": {
                      "type": "string",
                      "format": "email"
                    },
                    "description": "List of user email addresses to share with. Users must be registered in the system.",
                    "example": ["john@company.com", "jane@company.com"]
                  },
                  "organization_id": {
                    "type": "string",
                    "nullable": true,
                    "description": "Optional: Restrict sharing to users who are members of this organization",
                    "example": "68ccaa60bfafc83d7faa92dd"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Share operation completed",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "connection_id": {
                      "type": "string",
                      "example": "68d31f755049e2147be506f9"
                    },
                    "results": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "email": {
                            "type": "string",
                            "format": "email"
                          },
                          "user_id": {
                            "type": "string",
                            "nullable": true
                          },
                          "status": {
                            "type": "string",
                            "enum": ["shared", "already_shared", "not_found", "not_in_organization", "error"]
                          },
                          "message": {
                            "type": "string"
                          }
                        }
                      }
                    },
                    "total_shared": {
                      "type": "integer",
                      "description": "Number of users successfully shared with"
                    },
                    "total_failed": {
                      "type": "integer",
                      "description": "Number of users that failed to share with"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Forbidden - Only connection owners can share"
          },
          "404": {
            "description": "Connection not found"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}],
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X POST \\\n  'https://api.dgintel.ai/v2/connections/conn_123/share' \\\n  -H 'Authorization: Bearer dgi_***' \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"user_emails\": [\"john@company.com\", \"jane@company.com\"]}'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/connections/conn_123/share', {\n  method: 'POST',\n  headers: {\n    Authorization: 'Bearer ' + process.env.API_KEY,\n    'Content-Type': 'application/json'\n  },\n  body: JSON.stringify({\n    user_emails: ['john@company.com', 'jane@company.com']\n  })\n});\nconst data = await res.json();\nconsole.log(`Shared with ${data.total_shared} users`);"
          }
        ]
      }
    },
    "/v2/connections/{connection_id}/access": {
      "get": {
        "tags": ["Connections"],
        "summary": "List Connection Access",
        "description": "Lists all users who have access to a connection, including the owner and all users with whom the connection has been shared. Available to both owners and users with shared access.",
        "operationId": "list_connection_access_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID to get access list for"
          }
        ],
        "responses": {
          "200": {
            "description": "Access list retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "connection_id": {
                      "type": "string",
                      "example": "68d31f755049e2147be506f9"
                    },
                    "connection_name": {
                      "type": "string",
                      "example": "Production Database"
                    },
                    "owner": {
                      "type": "object",
                      "properties": {
                        "user_id": {
                          "type": "string"
                        },
                        "email": {
                          "type": "string",
                          "format": "email"
                        },
                        "access_type": {
                          "type": "string",
                          "enum": ["owner"]
                        }
                      }
                    },
                    "shared_users": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "user_id": {
                            "type": "string"
                          },
                          "email": {
                            "type": "string",
                            "format": "email"
                          },
                          "access_type": {
                            "type": "string",
                            "enum": ["shared"]
                          },
                          "added_at": {
                            "type": "string",
                            "format": "date-time",
                            "nullable": true
                          }
                        }
                      }
                    },
                    "total_users": {
                      "type": "integer",
                      "description": "Total number of users with access (owner + shared users)"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Forbidden - User does not have access to this connection"
          },
          "404": {
            "description": "Connection not found"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}],
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X GET \\\n  'https://api.dgintel.ai/v2/connections/conn_123/access' \\\n  -H 'Authorization: Bearer dgi_***'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/connections/conn_123/access', {\n  headers: { Authorization: 'Bearer ' + process.env.API_KEY }\n});\nconst data = await res.json();\nconsole.log(`Total users with access: ${data.total_users}`);"
          }
        ]
      }
    },
    "/v2/connections/{connection_id}/share/{user_id}": {
      "delete": {
        "tags": ["Connections"],
        "summary": "Revoke User Access (Owner Only)",
        "description": "Revokes a specific user's access to a connection. Only the connection owner can revoke access. The user will immediately lose the ability to view the connection and its credentials.",
        "operationId": "revoke_connection_access_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID"
          },
          {
            "name": "user_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The user ID whose access should be revoked"
          }
        ],
        "responses": {
          "200": {
            "description": "Access revoked successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "connection_id": {
                      "type": "string"
                    },
                    "revoked_user_id": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string",
                      "enum": ["OK"]
                    },
                    "message": {
                      "type": "string",
                      "example": "Successfully revoked user's access to the connection"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Forbidden - Only connection owners can revoke access"
          },
          "404": {
            "description": "Connection or user not found"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}],
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X DELETE \\\n  'https://api.dgintel.ai/v2/connections/conn_123/share/user_456' \\\n  -H 'Authorization: Bearer dgi_***'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/connections/conn_123/share/user_456', {\n  method: 'DELETE',\n  headers: { Authorization: 'Bearer ' + process.env.API_KEY }\n});\nconst data = await res.json();\nconsole.log(data.message);"
          }
        ]
      }
    },
    "/v2/connections/{connection_id}/unshare": {
      "delete": {
        "tags": ["Connections"],
        "summary": "Remove Yourself from Shared Connection",
        "description": "Allows a user to remove themselves from a connection that was shared with them. After removal, the user will no longer have access to view the connection. Connection owners cannot use this endpoint.",
        "operationId": "unshare_connection_self_v2",
        "parameters": [
          {
            "name": "connection_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The connection ID to remove yourself from"
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully removed from connection",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "connection_id": {
                      "type": "string"
                    },
                    "revoked_user_id": {
                      "type": "string"
                    },
                    "status": {
                      "type": "string",
                      "enum": ["OK"]
                    },
                    "message": {
                      "type": "string",
                      "example": "Successfully removed yourself from the shared connection"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "Forbidden - Connection owners cannot use this endpoint, or user doesn't have access to this connection"
          },
          "404": {
            "description": "Connection not found"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}],
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X DELETE \\\n  'https://api.dgintel.ai/v2/connections/conn_123/unshare' \\\n  -H 'Authorization: Bearer dgi_***'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/connections/conn_123/unshare', {\n  method: 'DELETE',\n  headers: { Authorization: 'Bearer ' + process.env.API_KEY }\n});\nconst data = await res.json();\nconsole.log(data.message);"
          }
        ]
      }
    },
    "/v2/schedule-job": {
      "post": {
        "tags": ["Scheduled Jobs"],
        "summary": "Schedule Job",
        "description": "Creates a new scheduled job that will automatically run tasks at specified intervals using cron syntax. Perfect for automating recurring data analysis, reports, or monitoring tasks.",
        "operationId": "schedule_job_v2",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "chat_session_id": {
                    "type": "string",
                    "example": "session_abc123def456"
                  },
                  "run_file": {
                    "type": "string",
                    "example": "daily_report.py",
                    "description": "File to execute on schedule"
                  },
                  "cron_schedule": {
                    "type": "string",
                    "nullable": true,
                    "example": "0 9 * * 1-5",
                    "description": "Cron expression for scheduling"
                  },
                  "cron_text": {
                    "type": "string",
                    "nullable": true,
                    "example": "Every weekday at 9 AM",
                    "description": "Human-readable schedule description"
                  },
                  "status": {
                    "type": "string",
                    "enum": ["active", "inactive"],
                    "default": "active"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Scheduled job created successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/scheduled-jobs": {
      "get": {
        "tags": ["Scheduled Jobs"],
        "summary": "List Scheduled Jobs",
        "description": "Retrieves a paginated list of your scheduled jobs with filtering and sorting options. Monitor your automated tasks, check their status, and see when they'll run next.",
        "operationId": "list_scheduled_jobs_v2",
        "parameters": [
          {
            "name": "status",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": ["active", "inactive"]
            },
            "description": "Filter by job status"
          },
          {
            "name": "chat_session_id",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            },
            "description": "Filter by specific chat session"
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "maximum": 100,
              "minimum": 1,
              "default": 50
            },
            "description": "Number of jobs to return"
          },
          {
            "name": "offset",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            },
            "description": "Number of jobs to skip"
          }
        ],
        "responses": {
          "200": {
            "description": "Scheduled jobs retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "jobs": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "example": "job_xyz789abc123"
                          },
                          "chat_session_id": {
                            "type": "string"
                          },
                          "run_file": {
                            "type": "string",
                            "example": "daily_report.py"
                          },
                          "cron_schedule": {
                            "type": "string",
                            "example": "0 9 * * 1-5"
                          },
                          "status": {
                            "type": "string",
                            "enum": ["active", "inactive"]
                          },
                          "next_run_time": {
                            "type": "string",
                            "format": "date-time",
                            "nullable": true
                          }
                        }
                      }
                    },
                    "total_count": {
                      "type": "integer"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/scheduled-jobs/{job_id}": {
      "patch": {
        "tags": ["Scheduled Jobs"],
        "summary": "Update Scheduled Job",
        "description": "Updates a scheduled job's status to activate or deactivate it. Use this to temporarily pause jobs without deleting them, or to reactivate jobs when needed.",
        "operationId": "update_scheduled_job_v2",
        "parameters": [
          {
            "name": "job_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The job ID to update"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "status": {
                    "type": "string",
                    "enum": ["active", "inactive"],
                    "description": "New status for the scheduled job"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Scheduled job updated successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/trigger-job/{scheduled_job_id}": {
      "get": {
        "tags": ["Scheduled Jobs"],
        "summary": "Trigger Job",
        "description": "Manually triggers a scheduled job to run immediately, regardless of its normal schedule. Useful for testing jobs or running them on-demand when needed.",
        "operationId": "trigger_job_v2",
        "parameters": [
          {
            "name": "scheduled_job_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The scheduled job ID to trigger"
          }
        ],
        "responses": {
          "200": {
            "description": "Job triggered successfully"
          },
          "422": {
            "description": "Validation Error"
          }
        }
      }
    },
    "/v2/understanding/new": {
      "post": {
        "tags": ["Understanding"],
        "summary": "Create Understanding",
        "description": "Creates a new Understanding document from a GitHub repository or URLs. This builds a knowledge base that your AI agent uses as context in all future tasks. After creation, start a deep_research task to analyze the repository. The process takes 5-30 minutes and generates a comprehensive PDF documentation of your codebase.",
        "operationId": "new_understanding_v2",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string",
                    "example": "Company Sales Process"
                  },
                  "description": {
                    "type": "string",
                    "nullable": true,
                    "example": "Documentation of our sales pipeline and processes"
                  },
                  "metadata_store_id": {
                    "type": "string",
                    "nullable": true,
                    "description": "Connection ID from /connections/new containing GitHub token for private repo access",
                    "example": "conn_abc123def456"
                  },
                  "github_repo": {
                    "type": "object",
                    "properties": {
                      "url": {
                        "type": "string",
                        "example": "https://github.com/username/repository"
                      }
                    },
                    "description": "GitHub repository to analyze. Supports both public and private repos (private requires metadata_store_id)"
                  },
                  "support_urls": {
                    "type": "object",
                    "properties": {
                      "general": {
                        "type": "string",
                        "example": "https://docs.example.com"
                      }
                    },
                    "description": "Additional documentation URLs to include in the understanding"
                  },
                  "vector_store": {
                    "type": "string",
                    "nullable": true,
                    "description": "Vector store configuration"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Understanding created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "understanding_id": {
                      "type": "string",
                      "example": "understanding_xyz789abc123"
                    },
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"]
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/understanding/new/upload": {
      "post": {
        "tags": ["Understanding"],
        "summary": "Create Understanding from Markdown File",
        "description": "Creates a new Understanding document by uploading a markdown file directly. This is an alternative to analyzing GitHub repositories - simply upload your documentation as a .md file. The AI will use this content as context in all future tasks where this understanding_id is referenced.",
        "operationId": "new_understanding_upload_v2",
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": ["name", "md_file"],
                "properties": {
                  "name": {
                    "type": "string",
                    "description": "Name for this Understanding document",
                    "example": "ACME Doc"
                  },
                  "description": {
                    "type": "string",
                    "description": "Optional description of the understanding content",
                    "example": "Company documentation and processes"
                  },
                  "md_file": {
                    "type": "string",
                    "format": "binary",
                    "description": "The markdown (.md) file containing your documentation"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Understanding created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "understanding_id": {
                      "type": "string",
                      "example": "understanding_xyz789abc123"
                    },
                    "status": {
                      "type": "string",
                      "enum": ["OK", "ERROR"]
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}],
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -X POST \\\n  'https://api.dgintel.ai/v2/understanding/new/upload' \\\n  -H 'Authorization: Bearer dgi_***' \\\n  -F 'name=ACME Doc' \\\n  -F 'description=Company documentation' \\\n  -F 'md_file=@./understanding.md'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const formData = new FormData();\nformData.append('name', 'ACME Doc');\nformData.append('description', 'Company documentation');\nformData.append('md_file', fs.createReadStream('./understanding.md'));\n\nconst res = await fetch('https://api.dgintel.ai/v2/understanding/new/upload', {\n  method: 'POST',\n  headers: { Authorization: 'Bearer ' + process.env.API_KEY },\n  body: formData\n});\nconst data = await res.json();\nconsole.log('Understanding ID:', data.understanding_id);"
          }
        ]
      }
    },
    "/v2/understandings": {
      "get": {
        "tags": ["Understanding"],
        "summary": "List Understandings",
        "description": "Retrieves all Understanding documents you've created, showing their names and whether they have associated vector stores for semantic search capabilities.",
        "operationId": "list_understandings_v2",
        "responses": {
          "200": {
            "description": "Understandings retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "OK"
                    },
                    "understandings": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "understanding_id": {
                            "type": "string",
                            "example": "understanding_xyz789abc123"
                          },
                          "name": {
                            "type": "string",
                            "example": "Company Sales Process"
                          },
                          "has_vector_store": {
                            "type": "boolean",
                            "example": true
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/understanding/{understanding_id}": {
      "get": {
        "tags": ["Understanding"],
        "summary": "Get Understanding",
        "description": "Retrieves a specific Understanding document including the generated PDF documentation. The PDF is returned as base64 encoded string after the deep_research task completes. Use this to download the comprehensive analysis of your codebase that the AI generated. The PDF contains architecture overview, key components, and detailed documentation.",
        "operationId": "get_understanding_v2",
        "parameters": [
          {
            "name": "understanding_id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "The understanding ID to retrieve"
          }
        ],
        "responses": {
          "200": {
            "description": "Understanding retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "name": {
                      "type": "string",
                      "example": "Company Sales Process"
                    },
                    "date_created": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "pdf_base64": {
                      "type": "string",
                      "description": "Base64 encoded PDF containing the complete analysis of your codebase. Available after deep_research task completes. Use this to download: create a link with href='data:application/pdf;base64,{pdf_base64}'"
                    },
                    "task_id": {
                      "type": "string",
                      "nullable": true,
                      "description": "ID of the deep_research task. Use this to check if analysis is complete via /tasks/{task_id}"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error"
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    }
  ,
    "/auth/login": {
      "post": {
        "tags": ["Auth"],
        "summary": "Login",
        "description": "Authenticates using Bearer token (JWT or API key starting with dgi_). No request body required. Returns the user's organizations in the 'organizations' field.",
        "operationId": "auth_login",
        "responses": {
          "200": {
            "description": "Login successful",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/LoginResponse"
                }
              }
            }
          }
        },
        "security": [{"HTTPBearer": []}]
      }
    },
    "/v2/organizations/{org_id}/members": {
      "get": {
        "tags": ["Organizations"],
        "summary": "List Organization Members",
        "description": "Lists all members of an organization.\n\nPermissions:\n- Owner-only access. The caller must be the organization's owner; otherwise returns HTTP 403.\n\nAuthentication:\n- Requires Bearer token (JWT or API key starting with dgi_).\n\nResponse details:\n- Returns organization name and owner email\n- Provides total member count and detailed member info\n- New organizations return an empty members array\n\nErrors:\n- 403 Forbidden: User is not the organization owner\n- 404 Not Found: Invalid organization ID",
        "operationId": "list_org_members",
        "parameters": [
          {
            "name": "org_id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "Organization ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Members retrieved successfully",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/OrganizationMembersResponse" },
                "examples": {
                  "success": {
                    "summary": "Example organization members response",
                    "value": {
                      "organization_id": "org_123",
                      "organization_name": "Acme Inc.",
                      "owner_email": "owner@acme.com",
                      "members": [
                        { "id": "user_1", "email": "alice@acme.com", "joined_at": "2025-09-10T12:00:00Z" },
                        { "id": "user_2", "email": "bob@acme.com", "joined_at": null }
                      ],
                      "total_count": 2
                    }
                  }
                }
              }
            }
          },
          "403": { "description": "Forbidden - User is not the organization owner" },
          "404": { "description": "Not Found - Invalid organization ID" }
        },
        "security": [{"HTTPBearer": []}]
        ,
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -sS -X GET \\\n+  'https://api.dgintel.ai/v2/organizations/org_123/members' \\\n+  -H 'Authorization: Bearer dgi_***'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/organizations/org_123/members', { headers: { Authorization: 'Bearer ' + process.env.API_KEY } });\nif (res.status === 403) throw new Error('Not owner');\nif (res.status === 404) throw new Error('Invalid organization ID');\nconst data = await res.json();"
          }
        ]
      },
      "post": {
        "tags": ["Organizations"],
        "summary": "Add Member to Organization",
        "description": "Adds an existing, registered user to the organization.\n\nPermissions:\n- Owner-only access. The caller must be the organization's owner; otherwise returns HTTP 403.\n\nAuthentication:\n- Requires Bearer token (JWT or API key starting with dgi_).\n\nValidation and safeguards:\n- User must already exist in the system (no auto-creation)\n- Duplicate memberships are prevented\n- Owner cannot add themselves\n\nErrors (returned as 200 with status=ERROR unless noted):\n- User doesn't exist: status=ERROR, message=\"User with email {email} does not exist. User must be registered first.\"\n- Duplicate member: status=ERROR, message=\"User {email} is already a member of this organization\"\n- Owner self-add: status=ERROR, message=\"Organization owner is already a member\"\n- 403 Forbidden: User is not the organization owner\n- 404 Not Found: Invalid organization ID",
        "operationId": "add_org_member",
        "parameters": [
          {
            "name": "org_id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "Organization ID"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/AddOrganizationMemberRequest" },
              "example": { "email": "member@example.com" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Add member result",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/AddOrganizationMemberResponse" },
                "examples": {
                  "success": {
                    "summary": "Member added successfully",
                    "value": { "status": "OK", "message": "User added to organization", "user_id": "user_3" }
                  },
                  "user_does_not_exist": {
                    "summary": "User must be registered first",
                    "value": { "status": "ERROR", "message": "User with email charlie@acme.com does not exist. User must be registered first.", "user_id": null }
                  },
                  "duplicate_member": {
                    "summary": "Duplicate membership prevented",
                    "value": { "status": "ERROR", "message": "User bob@acme.com is already a member of this organization", "user_id": null }
                  },
                  "owner_self_add": {
                    "summary": "Owner cannot add themselves",
                    "value": { "status": "ERROR", "message": "Organization owner is already a member", "user_id": null }
                  }
                }
              }
            }
          },
          "403": { "description": "Forbidden - User is not the organization owner" },
          "404": { "description": "Not Found - Invalid organization ID" }
        },
        "security": [{"HTTPBearer": []}]
        ,
        "x-codeSamples": [
          {
            "lang": "curl",
            "label": "cURL",
            "source": "curl -sS -X POST \\\n+  'https://api.dgintel.ai/v2/organizations/org_123/members' \\\n+  -H 'Authorization: Bearer dgi_***' \\\n+  -H 'Content-Type: application/json' \\\n+  -d '{\"email\":\"new.user@acme.com\"}'"
          },
          {
            "lang": "node",
            "label": "Node.js (fetch)",
            "source": "const res = await fetch('https://api.dgintel.ai/v2/organizations/org_123/members', { method: 'POST', headers: { Authorization: 'Bearer ' + process.env.API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'new.user@acme.com' }) });\nif (res.status === 403) throw new Error('Not owner');\nif (res.status === 404) throw new Error('Invalid organization ID');\nconst data = await res.json();"
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "HTTPBearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "Authentication via Bearer token. Supports JWT tokens and API keys (starting with dgi_). Get your API key from https://app.dgintel.ai/."
      }
    },
    "schemas": {
      "OrganizationSummary": {
        "type": "object",
        "properties": {
          "organization_id": { "type": "string" },
          "name": { "type": "string" }
        },
        "required": ["organization_id", "name"]
      },
      "LoginResponse": {
        "type": "object",
        "properties": {
          "organizations": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/OrganizationSummary" }
          }
        },
        "required": ["organizations"]
      },
      "OrganizationMember": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "email": { "type": "string", "format": "email" },
          "joined_at": { "type": "string", "format": "date-time", "nullable": true }
        },
        "required": ["id", "email"]
      },
      "OrganizationMembersResponse": {
        "type": "object",
        "properties": {
          "organization_id": { "type": "string" },
          "organization_name": { "type": "string" },
          "owner_email": { "type": "string", "format": "email" },
          "members": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/OrganizationMember" }
          },
          "total_count": { "type": "integer", "minimum": 0 }
        },
        "required": ["organization_id", "organization_name", "owner_email", "members", "total_count"]
      },
      "AddOrganizationMemberRequest": {
        "type": "object",
        "properties": {
          "email": { "type": "string", "format": "email" }
        },
        "required": ["email"]
      },
      "AddOrganizationMemberResponse": {
        "type": "object",
        "properties": {
          "status": { "type": "string", "enum": ["OK", "ERROR"] },
          "message": { "type": "string" },
          "user_id": { "type": ["string", "null"] }
        },
        "required": ["status", "message", "user_id"]
      },
      "TaskStatus": {
        "type": "string",
        "enum": ["new", "in_progress", "completed", "interrupted"],
        "description": "Current status of the task"
      },
      "Message": {
        "type": "object",
        "properties": {
          "msg": {
            "type": "string",
            "description": "The message content"
          },
          "timestamp": {
            "type": "string",
            "format": "date-time",
            "description": "When the message was created"
          },
          "stream_url": {
            "type": "string",
            "nullable": true,
            "description": "URL to view computer use stream"
          }
        },
        "required": ["msg", "timestamp"]
      }
    }
  }
}
