mirror of
https://github.com/Significant-Gravitas/AutoGPT.git
synced 2026-04-08 03:00:28 -04:00
Merge branch 'dev' into q53n42-codex/add-list-operation-blocks
This commit is contained in:
85
.github/workflows/platform-frontend-ci.yml
vendored
85
.github/workflows/platform-frontend-ci.yml
vendored
@@ -18,11 +18,14 @@ defaults:
|
||||
working-directory: autogpt_platform/frontend
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
setup:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
cache-key: ${{ steps.cache-key.outputs.key }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -32,6 +35,45 @@ jobs:
|
||||
- name: Enable corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Generate cache key
|
||||
id: cache-key
|
||||
run: echo "key=${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.pnpm-store
|
||||
key: ${{ steps.cache-key.outputs.key }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "21"
|
||||
|
||||
- name: Enable corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Restore dependencies cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.pnpm-store
|
||||
key: ${{ needs.setup.outputs.cache-key }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -40,9 +82,11 @@ jobs:
|
||||
|
||||
type-check:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -52,21 +96,29 @@ jobs:
|
||||
- name: Enable corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Restore dependencies cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.pnpm-store
|
||||
key: ${{ needs.setup.outputs.cache-key }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Generate API client
|
||||
run: pnpm generate:api-client
|
||||
|
||||
- name: Run tsc check
|
||||
run: pnpm type-check
|
||||
|
||||
chromatic:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup
|
||||
# Only run on dev branch pushes or PRs targeting dev
|
||||
if: github.ref == 'refs/heads/dev' || github.base_ref == 'dev'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -78,6 +130,14 @@ jobs:
|
||||
- name: Enable corepack
|
||||
run: corepack enable
|
||||
|
||||
- name: Restore dependencies cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.pnpm-store
|
||||
key: ${{ needs.setup.outputs.cache-key }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
@@ -91,6 +151,7 @@ jobs:
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -128,6 +189,14 @@ jobs:
|
||||
run: |
|
||||
docker compose -f ../docker-compose.yml up -d
|
||||
|
||||
- name: Restore dependencies cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.pnpm-store
|
||||
key: ${{ needs.setup.outputs.cache-key }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -177,6 +177,3 @@ autogpt_platform/backend/settings.py
|
||||
*.ign.*
|
||||
.test-contents
|
||||
.claude/settings.local.json
|
||||
|
||||
# Auto generated client
|
||||
autogpt_platform/frontend/src/api/__generated__
|
||||
|
||||
@@ -121,6 +121,7 @@ Key models (defined in `/backend/schema.prisma`):
|
||||
3. Define input/output schemas
|
||||
4. Implement `run` method
|
||||
5. Register in block registry
|
||||
6. Generate the block uuid using `uuid.uuid4()`
|
||||
|
||||
**Modifying the API:**
|
||||
1. Update route in `/backend/backend/server/routers/`
|
||||
|
||||
@@ -15,9 +15,9 @@ from backend.data.block import (
|
||||
)
|
||||
from backend.data.execution import ExecutionStatus
|
||||
from backend.data.model import SchemaField
|
||||
from backend.util import json
|
||||
from backend.util import json, retry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AgentExecutorBlock(Block):
|
||||
@@ -77,27 +77,42 @@ class AgentExecutorBlock(Block):
|
||||
use_db_query=False,
|
||||
)
|
||||
|
||||
logger = execution_utils.LogMetadata(
|
||||
logger=_logger,
|
||||
user_id=input_data.user_id,
|
||||
graph_eid=graph_exec.id,
|
||||
graph_id=input_data.graph_id,
|
||||
node_eid="*",
|
||||
node_id="*",
|
||||
block_name=self.name,
|
||||
)
|
||||
|
||||
try:
|
||||
async for name, data in self._run(
|
||||
graph_id=input_data.graph_id,
|
||||
graph_version=input_data.graph_version,
|
||||
graph_exec_id=graph_exec.id,
|
||||
user_id=input_data.user_id,
|
||||
logger=logger,
|
||||
):
|
||||
yield name, data
|
||||
except asyncio.CancelledError:
|
||||
logger.warning(
|
||||
f"Execution of graph {input_data.graph_id} version {input_data.graph_version} was cancelled."
|
||||
await self._stop(
|
||||
graph_exec_id=graph_exec.id,
|
||||
user_id=input_data.user_id,
|
||||
logger=logger,
|
||||
)
|
||||
await execution_utils.stop_graph_execution(
|
||||
graph_exec.id, use_db_query=False
|
||||
logger.warning(
|
||||
f"Execution of graph {input_data.graph_id}v{input_data.graph_version} was cancelled."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Execution of graph {input_data.graph_id} version {input_data.graph_version} failed: {e}, stopping execution."
|
||||
await self._stop(
|
||||
graph_exec_id=graph_exec.id,
|
||||
user_id=input_data.user_id,
|
||||
logger=logger,
|
||||
)
|
||||
await execution_utils.stop_graph_execution(
|
||||
graph_exec.id, use_db_query=False
|
||||
logger.error(
|
||||
f"Execution of graph {input_data.graph_id}v{input_data.graph_version} failed: {e}, execution is stopped."
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -107,6 +122,7 @@ class AgentExecutorBlock(Block):
|
||||
graph_version: int,
|
||||
graph_exec_id: str,
|
||||
user_id: str,
|
||||
logger,
|
||||
) -> BlockOutput:
|
||||
|
||||
from backend.data.execution import ExecutionEventType
|
||||
@@ -159,3 +175,25 @@ class AgentExecutorBlock(Block):
|
||||
f"Execution {log_id} produced {output_name}: {output_data}"
|
||||
)
|
||||
yield output_name, output_data
|
||||
|
||||
@retry.func_retry
|
||||
async def _stop(
|
||||
self,
|
||||
graph_exec_id: str,
|
||||
user_id: str,
|
||||
logger,
|
||||
) -> None:
|
||||
from backend.executor import utils as execution_utils
|
||||
|
||||
log_id = f"Graph exec-id: {graph_exec_id}"
|
||||
logger.info(f"Stopping execution of {log_id}")
|
||||
|
||||
try:
|
||||
await execution_utils.stop_graph_execution(
|
||||
graph_exec_id=graph_exec_id,
|
||||
user_id=user_id,
|
||||
use_db_query=False,
|
||||
)
|
||||
logger.info(f"Execution {log_id} stopped successfully.")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to stop execution {log_id}: {e}")
|
||||
|
||||
@@ -529,7 +529,7 @@ class CreateListBlock(Block):
|
||||
cur_size, cur_tokens = cur_size + 1, cur_tokens + tokens
|
||||
|
||||
# Yield final chunk if any
|
||||
if chunk:
|
||||
if chunk or not input_data.values:
|
||||
yield "list", chunk
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from enum import Enum
|
||||
|
||||
from google.oauth2.credentials import Credentials
|
||||
from googleapiclient.discovery import build
|
||||
@@ -16,6 +17,102 @@ from ._auth import (
|
||||
GoogleCredentialsInput,
|
||||
)
|
||||
|
||||
settings = Settings()
|
||||
GOOGLE_SHEETS_DISABLED = (
|
||||
not GOOGLE_OAUTH_IS_CONFIGURED
|
||||
or settings.config.app_env == AppEnvironment.PRODUCTION
|
||||
)
|
||||
|
||||
|
||||
def parse_a1_notation(a1: str) -> tuple[str | None, str]:
|
||||
"""Split an A1‑notation string into *(sheet_name, cell_range)*.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> parse_a1_notation("Sheet1!A1:B2")
|
||||
("Sheet1", "A1:B2")
|
||||
>>> parse_a1_notation("A1:B2")
|
||||
(None, "A1:B2")
|
||||
"""
|
||||
|
||||
if "!" in a1:
|
||||
sheet, cell_range = a1.split("!", 1)
|
||||
return sheet, cell_range
|
||||
return None, a1
|
||||
|
||||
|
||||
def _first_sheet_meta(service, spreadsheet_id: str) -> tuple[str, int]:
|
||||
"""Return *(title, sheetId)* for the first sheet in *spreadsheet_id*."""
|
||||
|
||||
meta = (
|
||||
service.spreadsheets()
|
||||
.get(spreadsheetId=spreadsheet_id, includeGridData=False)
|
||||
.execute()
|
||||
)
|
||||
first = meta["sheets"][0]["properties"]
|
||||
return first["title"], first["sheetId"]
|
||||
|
||||
|
||||
def resolve_sheet_name(service, spreadsheet_id: str, sheet_name: str | None) -> str:
|
||||
"""Resolve *sheet_name*, falling back to the workbook's first sheet if empty."""
|
||||
|
||||
if sheet_name:
|
||||
return sheet_name
|
||||
title, _ = _first_sheet_meta(service, spreadsheet_id)
|
||||
return title
|
||||
|
||||
|
||||
def sheet_id_by_name(service, spreadsheet_id: str, sheet_name: str) -> int | None:
|
||||
"""Return the *sheetId* for *sheet_name* (or `None` if not found)."""
|
||||
|
||||
meta = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
|
||||
for sh in meta.get("sheets", []):
|
||||
if sh.get("properties", {}).get("title") == sheet_name:
|
||||
return sh["properties"]["sheetId"]
|
||||
return None
|
||||
|
||||
|
||||
def _build_sheets_service(credentials: GoogleCredentials):
|
||||
settings = Settings()
|
||||
creds = Credentials(
|
||||
token=(
|
||||
credentials.access_token.get_secret_value()
|
||||
if credentials.access_token
|
||||
else None
|
||||
),
|
||||
refresh_token=(
|
||||
credentials.refresh_token.get_secret_value()
|
||||
if credentials.refresh_token
|
||||
else None
|
||||
),
|
||||
token_uri="https://oauth2.googleapis.com/token",
|
||||
client_id=settings.secrets.google_client_id,
|
||||
client_secret=settings.secrets.google_client_secret,
|
||||
scopes=credentials.scopes,
|
||||
)
|
||||
return build("sheets", "v4", credentials=creds)
|
||||
|
||||
|
||||
class SheetOperation(str, Enum):
|
||||
CREATE = "create"
|
||||
DELETE = "delete"
|
||||
COPY = "copy"
|
||||
|
||||
|
||||
class BatchOperationType(str, Enum):
|
||||
UPDATE = "update"
|
||||
CLEAR = "clear"
|
||||
|
||||
|
||||
class BatchOperation(BlockSchema):
|
||||
type: BatchOperationType = SchemaField(
|
||||
description="The type of operation to perform"
|
||||
)
|
||||
range: str = SchemaField(description="The A1 notation range for the operation")
|
||||
values: list[list[str]] = SchemaField(
|
||||
description="Values to update (only for UPDATE)", default=[]
|
||||
)
|
||||
|
||||
|
||||
class GoogleSheetsReadBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
@@ -38,15 +135,13 @@ class GoogleSheetsReadBlock(Block):
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
settings = Settings()
|
||||
super().__init__(
|
||||
id="5724e902-3635-47e9-a108-aaa0263a4988",
|
||||
description="This block reads data from a Google Sheets spreadsheet.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsReadBlock.Input,
|
||||
output_schema=GoogleSheetsReadBlock.Output,
|
||||
disabled=not GOOGLE_OAUTH_IS_CONFIGURED
|
||||
or settings.config.app_env == AppEnvironment.PRODUCTION,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"range": "Sheet1!A1:B2",
|
||||
@@ -73,32 +168,12 @@ class GoogleSheetsReadBlock(Block):
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = self._build_service(credentials, **kwargs)
|
||||
service = _build_sheets_service(credentials)
|
||||
data = await asyncio.to_thread(
|
||||
self._read_sheet, service, input_data.spreadsheet_id, input_data.range
|
||||
)
|
||||
yield "result", data
|
||||
|
||||
@staticmethod
|
||||
def _build_service(credentials: GoogleCredentials, **kwargs):
|
||||
creds = Credentials(
|
||||
token=(
|
||||
credentials.access_token.get_secret_value()
|
||||
if credentials.access_token
|
||||
else None
|
||||
),
|
||||
refresh_token=(
|
||||
credentials.refresh_token.get_secret_value()
|
||||
if credentials.refresh_token
|
||||
else None
|
||||
),
|
||||
token_uri="https://oauth2.googleapis.com/token",
|
||||
client_id=Settings().secrets.google_client_id,
|
||||
client_secret=Settings().secrets.google_client_secret,
|
||||
scopes=credentials.scopes,
|
||||
)
|
||||
return build("sheets", "v4", credentials=creds)
|
||||
|
||||
def _read_sheet(self, service, spreadsheet_id: str, range: str) -> list[list[str]]:
|
||||
sheet = service.spreadsheets()
|
||||
result = sheet.values().get(spreadsheetId=spreadsheet_id, range=range).execute()
|
||||
@@ -135,7 +210,7 @@ class GoogleSheetsWriteBlock(Block):
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsWriteBlock.Input,
|
||||
output_schema=GoogleSheetsWriteBlock.Output,
|
||||
disabled=not GOOGLE_OAUTH_IS_CONFIGURED,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"range": "Sheet1!A1:B2",
|
||||
@@ -164,7 +239,7 @@ class GoogleSheetsWriteBlock(Block):
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = GoogleSheetsReadBlock._build_service(credentials, **kwargs)
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._write_sheet,
|
||||
service,
|
||||
@@ -190,3 +265,790 @@ class GoogleSheetsWriteBlock(Block):
|
||||
.execute()
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class GoogleSheetsAppendBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(description="Spreadsheet ID")
|
||||
sheet_name: str = SchemaField(
|
||||
description="Optional sheet to append to (defaults to first sheet)",
|
||||
default="",
|
||||
)
|
||||
values: list[list[str]] = SchemaField(description="Rows to append")
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(description="Append API response")
|
||||
error: str = SchemaField(description="Error message, if any")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="531d50c0-d6b9-4cf9-a013-7bf783d313c7",
|
||||
description="Append data to a Google Sheet (sheet optional)",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsAppendBlock.Input,
|
||||
output_schema=GoogleSheetsAppendBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"values": [["Charlie", "95"]],
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
("result", {"updatedCells": 2, "updatedColumns": 2, "updatedRows": 1}),
|
||||
],
|
||||
test_mock={
|
||||
"_append_sheet": lambda *args, **kwargs: {
|
||||
"updatedCells": 2,
|
||||
"updatedColumns": 2,
|
||||
"updatedRows": 1,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._append_sheet,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.sheet_name,
|
||||
input_data.values,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _append_sheet(
|
||||
self,
|
||||
service,
|
||||
spreadsheet_id: str,
|
||||
sheet_name: str,
|
||||
values: list[list[str]],
|
||||
) -> dict:
|
||||
target_sheet = resolve_sheet_name(service, spreadsheet_id, sheet_name)
|
||||
body = {"values": values}
|
||||
return (
|
||||
service.spreadsheets()
|
||||
.values()
|
||||
.append(
|
||||
spreadsheetId=spreadsheet_id,
|
||||
range=f"{target_sheet}!A:A",
|
||||
valueInputOption="USER_ENTERED",
|
||||
insertDataOption="INSERT_ROWS",
|
||||
body=body,
|
||||
)
|
||||
.execute()
|
||||
)
|
||||
|
||||
|
||||
class GoogleSheetsClearBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(
|
||||
description="The ID of the spreadsheet to clear",
|
||||
)
|
||||
range: str = SchemaField(
|
||||
description="The A1 notation of the range to clear",
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(
|
||||
description="The result of the clear operation",
|
||||
)
|
||||
error: str = SchemaField(
|
||||
description="Error message if any",
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="84938266-0fc7-46e5-9369-adb0f6ae8015",
|
||||
description="This block clears data from a specified range in a Google Sheets spreadsheet.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsClearBlock.Input,
|
||||
output_schema=GoogleSheetsClearBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"range": "Sheet1!A1:B2",
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
("result", {"clearedRange": "Sheet1!A1:B2"}),
|
||||
],
|
||||
test_mock={
|
||||
"_clear_range": lambda *args, **kwargs: {
|
||||
"clearedRange": "Sheet1!A1:B2"
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._clear_range,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.range,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _clear_range(self, service, spreadsheet_id: str, range: str) -> dict:
|
||||
result = (
|
||||
service.spreadsheets()
|
||||
.values()
|
||||
.clear(spreadsheetId=spreadsheet_id, range=range)
|
||||
.execute()
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class GoogleSheetsMetadataBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets.readonly"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(
|
||||
description="The ID of the spreadsheet to get metadata for",
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(
|
||||
description="The metadata of the spreadsheet including sheets info",
|
||||
)
|
||||
error: str = SchemaField(
|
||||
description="Error message if any",
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="6a0be6ee-7a0d-4c92-819b-500630846ad0",
|
||||
description="This block retrieves metadata about a Google Sheets spreadsheet including sheet names and properties.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsMetadataBlock.Input,
|
||||
output_schema=GoogleSheetsMetadataBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
(
|
||||
"result",
|
||||
{
|
||||
"title": "Test Spreadsheet",
|
||||
"sheets": [{"title": "Sheet1", "sheetId": 0}],
|
||||
},
|
||||
),
|
||||
],
|
||||
test_mock={
|
||||
"_get_metadata": lambda *args, **kwargs: {
|
||||
"title": "Test Spreadsheet",
|
||||
"sheets": [{"title": "Sheet1", "sheetId": 0}],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._get_metadata,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _get_metadata(self, service, spreadsheet_id: str) -> dict:
|
||||
result = (
|
||||
service.spreadsheets()
|
||||
.get(spreadsheetId=spreadsheet_id, includeGridData=False)
|
||||
.execute()
|
||||
)
|
||||
return {
|
||||
"title": result.get("properties", {}).get("title"),
|
||||
"sheets": [
|
||||
{
|
||||
"title": sheet.get("properties", {}).get("title"),
|
||||
"sheetId": sheet.get("properties", {}).get("sheetId"),
|
||||
"gridProperties": sheet.get("properties", {}).get(
|
||||
"gridProperties", {}
|
||||
),
|
||||
}
|
||||
for sheet in result.get("sheets", [])
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class GoogleSheetsManageSheetBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(description="Spreadsheet ID")
|
||||
operation: SheetOperation = SchemaField(description="Operation to perform")
|
||||
sheet_name: str = SchemaField(
|
||||
description="Target sheet name (defaults to first sheet for delete)",
|
||||
default="",
|
||||
)
|
||||
source_sheet_id: int = SchemaField(
|
||||
description="Source sheet ID for copy", default=0
|
||||
)
|
||||
destination_sheet_name: str = SchemaField(
|
||||
description="New sheet name for copy", default=""
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(description="Operation result")
|
||||
error: str = SchemaField(description="Error message, if any")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="7940189d-b137-4ef1-aa18-3dd9a5bde9f3",
|
||||
description="Create, delete, or copy sheets (sheet optional)",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsManageSheetBlock.Input,
|
||||
output_schema=GoogleSheetsManageSheetBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"operation": SheetOperation.CREATE,
|
||||
"sheet_name": "NewSheet",
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[("result", {"success": True, "sheetId": 123})],
|
||||
test_mock={
|
||||
"_manage_sheet": lambda *args, **kwargs: {
|
||||
"success": True,
|
||||
"sheetId": 123,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._manage_sheet,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.operation,
|
||||
input_data.sheet_name,
|
||||
input_data.source_sheet_id,
|
||||
input_data.destination_sheet_name,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _manage_sheet(
|
||||
self,
|
||||
service,
|
||||
spreadsheet_id: str,
|
||||
operation: SheetOperation,
|
||||
sheet_name: str,
|
||||
source_sheet_id: int,
|
||||
destination_sheet_name: str,
|
||||
) -> dict:
|
||||
requests = []
|
||||
|
||||
# Ensure a target sheet name when needed
|
||||
target_name = resolve_sheet_name(service, spreadsheet_id, sheet_name)
|
||||
|
||||
if operation == SheetOperation.CREATE:
|
||||
requests.append({"addSheet": {"properties": {"title": target_name}}})
|
||||
elif operation == SheetOperation.DELETE:
|
||||
sid = sheet_id_by_name(service, spreadsheet_id, target_name)
|
||||
if sid is None:
|
||||
return {"error": f"Sheet '{target_name}' not found"}
|
||||
requests.append({"deleteSheet": {"sheetId": sid}})
|
||||
elif operation == SheetOperation.COPY:
|
||||
requests.append(
|
||||
{
|
||||
"duplicateSheet": {
|
||||
"sourceSheetId": source_sheet_id,
|
||||
"newSheetName": destination_sheet_name
|
||||
or f"Copy of {source_sheet_id}",
|
||||
}
|
||||
}
|
||||
)
|
||||
else:
|
||||
return {"error": f"Unknown operation: {operation}"}
|
||||
|
||||
body = {"requests": requests}
|
||||
result = (
|
||||
service.spreadsheets()
|
||||
.batchUpdate(spreadsheetId=spreadsheet_id, body=body)
|
||||
.execute()
|
||||
)
|
||||
return {"success": True, "result": result}
|
||||
|
||||
|
||||
class GoogleSheetsBatchOperationsBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(
|
||||
description="The ID of the spreadsheet to perform batch operations on",
|
||||
)
|
||||
operations: list[BatchOperation] = SchemaField(
|
||||
description="List of operations to perform",
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(
|
||||
description="The result of the batch operations",
|
||||
)
|
||||
error: str = SchemaField(
|
||||
description="Error message if any",
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="a4078584-6fe5-46e0-997e-d5126cdd112a",
|
||||
description="This block performs multiple operations on a Google Sheets spreadsheet in a single batch request.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsBatchOperationsBlock.Input,
|
||||
output_schema=GoogleSheetsBatchOperationsBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"operations": [
|
||||
{
|
||||
"type": BatchOperationType.UPDATE,
|
||||
"range": "A1:B1",
|
||||
"values": [["Header1", "Header2"]],
|
||||
},
|
||||
{
|
||||
"type": BatchOperationType.UPDATE,
|
||||
"range": "A2:B2",
|
||||
"values": [["Data1", "Data2"]],
|
||||
},
|
||||
],
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
("result", {"totalUpdatedCells": 4, "replies": []}),
|
||||
],
|
||||
test_mock={
|
||||
"_batch_operations": lambda *args, **kwargs: {
|
||||
"totalUpdatedCells": 4,
|
||||
"replies": [],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._batch_operations,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.operations,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _batch_operations(
|
||||
self, service, spreadsheet_id: str, operations: list[BatchOperation]
|
||||
) -> dict:
|
||||
update_data = []
|
||||
clear_ranges = []
|
||||
|
||||
for op in operations:
|
||||
if op.type == BatchOperationType.UPDATE:
|
||||
update_data.append(
|
||||
{
|
||||
"range": op.range,
|
||||
"values": op.values,
|
||||
}
|
||||
)
|
||||
elif op.type == BatchOperationType.CLEAR:
|
||||
clear_ranges.append(op.range)
|
||||
|
||||
results = {}
|
||||
|
||||
# Perform updates if any
|
||||
if update_data:
|
||||
update_body = {
|
||||
"valueInputOption": "USER_ENTERED",
|
||||
"data": update_data,
|
||||
}
|
||||
update_result = (
|
||||
service.spreadsheets()
|
||||
.values()
|
||||
.batchUpdate(spreadsheetId=spreadsheet_id, body=update_body)
|
||||
.execute()
|
||||
)
|
||||
results["updateResult"] = update_result
|
||||
|
||||
# Perform clears if any
|
||||
if clear_ranges:
|
||||
clear_body = {"ranges": clear_ranges}
|
||||
clear_result = (
|
||||
service.spreadsheets()
|
||||
.values()
|
||||
.batchClear(spreadsheetId=spreadsheet_id, body=clear_body)
|
||||
.execute()
|
||||
)
|
||||
results["clearResult"] = clear_result
|
||||
|
||||
return results
|
||||
|
||||
|
||||
class GoogleSheetsFindReplaceBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(
|
||||
description="The ID of the spreadsheet to perform find/replace on",
|
||||
)
|
||||
find_text: str = SchemaField(
|
||||
description="The text to find",
|
||||
)
|
||||
replace_text: str = SchemaField(
|
||||
description="The text to replace with",
|
||||
)
|
||||
sheet_id: int = SchemaField(
|
||||
description="The ID of the specific sheet to search (optional, searches all sheets if not provided)",
|
||||
default=-1,
|
||||
)
|
||||
match_case: bool = SchemaField(
|
||||
description="Whether to match case",
|
||||
default=False,
|
||||
)
|
||||
match_entire_cell: bool = SchemaField(
|
||||
description="Whether to match entire cell",
|
||||
default=False,
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(
|
||||
description="The result of the find/replace operation including number of replacements",
|
||||
)
|
||||
error: str = SchemaField(
|
||||
description="Error message if any",
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="accca760-8174-4656-b55e-5f0e82fee986",
|
||||
description="This block finds and replaces text in a Google Sheets spreadsheet.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsFindReplaceBlock.Input,
|
||||
output_schema=GoogleSheetsFindReplaceBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"find_text": "old_value",
|
||||
"replace_text": "new_value",
|
||||
"match_case": False,
|
||||
"match_entire_cell": False,
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
("result", {"occurrencesChanged": 5}),
|
||||
],
|
||||
test_mock={
|
||||
"_find_replace": lambda *args, **kwargs: {"occurrencesChanged": 5},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._find_replace,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.find_text,
|
||||
input_data.replace_text,
|
||||
input_data.sheet_id,
|
||||
input_data.match_case,
|
||||
input_data.match_entire_cell,
|
||||
)
|
||||
yield "result", result
|
||||
|
||||
def _find_replace(
|
||||
self,
|
||||
service,
|
||||
spreadsheet_id: str,
|
||||
find_text: str,
|
||||
replace_text: str,
|
||||
sheet_id: int,
|
||||
match_case: bool,
|
||||
match_entire_cell: bool,
|
||||
) -> dict:
|
||||
find_replace_request = {
|
||||
"find": find_text,
|
||||
"replacement": replace_text,
|
||||
"matchCase": match_case,
|
||||
"matchEntireCell": match_entire_cell,
|
||||
}
|
||||
|
||||
if sheet_id >= 0:
|
||||
find_replace_request["sheetId"] = sheet_id
|
||||
|
||||
requests = [{"findReplace": find_replace_request}]
|
||||
body = {"requests": requests}
|
||||
|
||||
result = (
|
||||
service.spreadsheets()
|
||||
.batchUpdate(spreadsheetId=spreadsheet_id, body=body)
|
||||
.execute()
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class GoogleSheetsFormatBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(description="Spreadsheet ID")
|
||||
range: str = SchemaField(description="A1 notation – sheet optional")
|
||||
background_color: dict = SchemaField(default={})
|
||||
text_color: dict = SchemaField(default={})
|
||||
bold: bool = SchemaField(default=False)
|
||||
italic: bool = SchemaField(default=False)
|
||||
font_size: int = SchemaField(default=10)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(description="API response or success flag")
|
||||
error: str = SchemaField(description="Error message, if any")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="270f2384-8089-4b5b-b2e3-fe2ea3d87c02",
|
||||
description="Format a range in a Google Sheet (sheet optional)",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsFormatBlock.Input,
|
||||
output_schema=GoogleSheetsFormatBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"spreadsheet_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"range": "A1:B2",
|
||||
"background_color": {"red": 1.0, "green": 0.9, "blue": 0.9},
|
||||
"bold": True,
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[("result", {"success": True})],
|
||||
test_mock={"_format_cells": lambda *args, **kwargs: {"success": True}},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._format_cells,
|
||||
service,
|
||||
input_data.spreadsheet_id,
|
||||
input_data.range,
|
||||
input_data.background_color,
|
||||
input_data.text_color,
|
||||
input_data.bold,
|
||||
input_data.italic,
|
||||
input_data.font_size,
|
||||
)
|
||||
if "error" in result:
|
||||
yield "error", result["error"]
|
||||
else:
|
||||
yield "result", result
|
||||
|
||||
def _format_cells(
|
||||
self,
|
||||
service,
|
||||
spreadsheet_id: str,
|
||||
a1_range: str,
|
||||
background_color: dict,
|
||||
text_color: dict,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
font_size: int,
|
||||
) -> dict:
|
||||
sheet_name, cell_range = parse_a1_notation(a1_range)
|
||||
sheet_name = resolve_sheet_name(service, spreadsheet_id, sheet_name)
|
||||
|
||||
sheet_id = sheet_id_by_name(service, spreadsheet_id, sheet_name)
|
||||
if sheet_id is None:
|
||||
return {"error": f"Sheet '{sheet_name}' not found"}
|
||||
|
||||
try:
|
||||
start_cell, end_cell = cell_range.split(":")
|
||||
start_col = ord(start_cell[0].upper()) - ord("A")
|
||||
start_row = int(start_cell[1:]) - 1
|
||||
end_col = ord(end_cell[0].upper()) - ord("A") + 1
|
||||
end_row = int(end_cell[1:])
|
||||
except (ValueError, IndexError):
|
||||
return {"error": f"Invalid range format: {a1_range}"}
|
||||
|
||||
cell_format: dict = {"userEnteredFormat": {}}
|
||||
if background_color:
|
||||
cell_format["userEnteredFormat"]["backgroundColor"] = background_color
|
||||
|
||||
text_format: dict = {}
|
||||
if text_color:
|
||||
text_format["foregroundColor"] = text_color
|
||||
if bold:
|
||||
text_format["bold"] = True
|
||||
if italic:
|
||||
text_format["italic"] = True
|
||||
if font_size != 10:
|
||||
text_format["fontSize"] = font_size
|
||||
if text_format:
|
||||
cell_format["userEnteredFormat"]["textFormat"] = text_format
|
||||
|
||||
body = {
|
||||
"requests": [
|
||||
{
|
||||
"repeatCell": {
|
||||
"range": {
|
||||
"sheetId": sheet_id,
|
||||
"startRowIndex": start_row,
|
||||
"endRowIndex": end_row,
|
||||
"startColumnIndex": start_col,
|
||||
"endColumnIndex": end_col,
|
||||
},
|
||||
"cell": cell_format,
|
||||
"fields": "userEnteredFormat(backgroundColor,textFormat)",
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
service.spreadsheets().batchUpdate(
|
||||
spreadsheetId=spreadsheet_id, body=body
|
||||
).execute()
|
||||
return {"success": True}
|
||||
|
||||
|
||||
class GoogleSheetsCreateSpreadsheetBlock(Block):
|
||||
class Input(BlockSchema):
|
||||
credentials: GoogleCredentialsInput = GoogleCredentialsField(
|
||||
["https://www.googleapis.com/auth/spreadsheets"]
|
||||
)
|
||||
title: str = SchemaField(
|
||||
description="The title of the new spreadsheet",
|
||||
)
|
||||
sheet_names: list[str] = SchemaField(
|
||||
description="List of sheet names to create (optional, defaults to single 'Sheet1')",
|
||||
default=["Sheet1"],
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
result: dict = SchemaField(
|
||||
description="The result containing spreadsheet ID and URL",
|
||||
)
|
||||
spreadsheet_id: str = SchemaField(
|
||||
description="The ID of the created spreadsheet",
|
||||
)
|
||||
spreadsheet_url: str = SchemaField(
|
||||
description="The URL of the created spreadsheet",
|
||||
)
|
||||
error: str = SchemaField(
|
||||
description="Error message if any",
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="c8d4c0d3-c76e-4c2a-8c66-4119817ea3d1",
|
||||
description="This block creates a new Google Sheets spreadsheet with specified sheets.",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=GoogleSheetsCreateSpreadsheetBlock.Input,
|
||||
output_schema=GoogleSheetsCreateSpreadsheetBlock.Output,
|
||||
disabled=GOOGLE_SHEETS_DISABLED,
|
||||
test_input={
|
||||
"title": "Test Spreadsheet",
|
||||
"sheet_names": ["Sheet1", "Data", "Summary"],
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_output=[
|
||||
("spreadsheet_id", "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"),
|
||||
(
|
||||
"spreadsheet_url",
|
||||
"https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
|
||||
),
|
||||
("result", {"success": True}),
|
||||
],
|
||||
test_mock={
|
||||
"_create_spreadsheet": lambda *args, **kwargs: {
|
||||
"spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
|
||||
"spreadsheetUrl": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, credentials: GoogleCredentials, **kwargs
|
||||
) -> BlockOutput:
|
||||
service = _build_sheets_service(credentials)
|
||||
result = await asyncio.to_thread(
|
||||
self._create_spreadsheet,
|
||||
service,
|
||||
input_data.title,
|
||||
input_data.sheet_names,
|
||||
)
|
||||
|
||||
if "error" in result:
|
||||
yield "error", result["error"]
|
||||
else:
|
||||
yield "spreadsheet_id", result["spreadsheetId"]
|
||||
yield "spreadsheet_url", result["spreadsheetUrl"]
|
||||
yield "result", {"success": True}
|
||||
|
||||
def _create_spreadsheet(self, service, title: str, sheet_names: list[str]) -> dict:
|
||||
try:
|
||||
# Create the initial spreadsheet
|
||||
spreadsheet_body = {
|
||||
"properties": {"title": title},
|
||||
"sheets": [
|
||||
{
|
||||
"properties": {
|
||||
"title": sheet_names[0] if sheet_names else "Sheet1"
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
result = service.spreadsheets().create(body=spreadsheet_body).execute()
|
||||
spreadsheet_id = result["spreadsheetId"]
|
||||
spreadsheet_url = result["spreadsheetUrl"]
|
||||
|
||||
# Add additional sheets if requested
|
||||
if len(sheet_names) > 1:
|
||||
requests = []
|
||||
for sheet_name in sheet_names[1:]:
|
||||
requests.append({"addSheet": {"properties": {"title": sheet_name}}})
|
||||
|
||||
if requests:
|
||||
batch_body = {"requests": requests}
|
||||
service.spreadsheets().batchUpdate(
|
||||
spreadsheetId=spreadsheet_id, body=batch_body
|
||||
).execute()
|
||||
|
||||
return {
|
||||
"spreadsheetId": spreadsheet_id,
|
||||
"spreadsheetUrl": spreadsheet_url,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
@@ -67,12 +67,11 @@ class AddMemoryBlock(Block, Mem0Base):
|
||||
metadata: dict[str, Any] = SchemaField(
|
||||
description="Optional metadata for the memory", default_factory=dict
|
||||
)
|
||||
|
||||
limit_memory_to_run: bool = SchemaField(
|
||||
description="Limit the memory to the run", default=False
|
||||
)
|
||||
limit_memory_to_agent: bool = SchemaField(
|
||||
description="Limit the memory to the agent", default=False
|
||||
description="Limit the memory to the agent", default=True
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
@@ -104,7 +103,12 @@ class AddMemoryBlock(Block, Mem0Base):
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
],
|
||||
test_output=[("action", "NO_CHANGE"), ("action", "NO_CHANGE")],
|
||||
test_output=[
|
||||
("action", "CREATED"),
|
||||
("memory", "test memory"),
|
||||
("action", "CREATED"),
|
||||
("memory", "test memory"),
|
||||
],
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_mock={"_get_client": lambda credentials: MockMemoryClient()},
|
||||
)
|
||||
@@ -117,7 +121,7 @@ class AddMemoryBlock(Block, Mem0Base):
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
graph_exec_id: str,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
try:
|
||||
client = self._get_client(credentials)
|
||||
@@ -178,6 +182,10 @@ class SearchMemoryBlock(Block, Mem0Base):
|
||||
default_factory=list,
|
||||
advanced=True,
|
||||
)
|
||||
metadata_filter: Optional[dict[str, Any]] = SchemaField(
|
||||
description="Optional metadata filters to apply",
|
||||
default=None,
|
||||
)
|
||||
limit_memory_to_run: bool = SchemaField(
|
||||
description="Limit the memory to the run", default=False
|
||||
)
|
||||
@@ -216,7 +224,7 @@ class SearchMemoryBlock(Block, Mem0Base):
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
graph_exec_id: str,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
try:
|
||||
client = self._get_client(credentials)
|
||||
@@ -235,6 +243,8 @@ class SearchMemoryBlock(Block, Mem0Base):
|
||||
filters["AND"].append({"run_id": graph_exec_id})
|
||||
if input_data.limit_memory_to_agent:
|
||||
filters["AND"].append({"agent_id": graph_id})
|
||||
if input_data.metadata_filter:
|
||||
filters["AND"].append({"metadata": input_data.metadata_filter})
|
||||
|
||||
result: list[dict[str, Any]] = client.search(
|
||||
input_data.query, version="v2", filters=filters
|
||||
@@ -260,11 +270,15 @@ class GetAllMemoriesBlock(Block, Mem0Base):
|
||||
categories: Optional[list[str]] = SchemaField(
|
||||
description="Filter by categories", default=None
|
||||
)
|
||||
metadata_filter: Optional[dict[str, Any]] = SchemaField(
|
||||
description="Optional metadata filters to apply",
|
||||
default=None,
|
||||
)
|
||||
limit_memory_to_run: bool = SchemaField(
|
||||
description="Limit the memory to the run", default=False
|
||||
)
|
||||
limit_memory_to_agent: bool = SchemaField(
|
||||
description="Limit the memory to the agent", default=False
|
||||
description="Limit the memory to the agent", default=True
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
@@ -274,11 +288,11 @@ class GetAllMemoriesBlock(Block, Mem0Base):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="45aee5bf-4767-45d1-a28b-e01c5aae9fc1",
|
||||
description="Retrieve all memories from Mem0 with pagination",
|
||||
description="Retrieve all memories from Mem0 with optional conversation filtering",
|
||||
input_schema=GetAllMemoriesBlock.Input,
|
||||
output_schema=GetAllMemoriesBlock.Output,
|
||||
test_input={
|
||||
"user_id": "test_user",
|
||||
"metadata_filter": {"type": "test"},
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_output=[
|
||||
@@ -296,7 +310,7 @@ class GetAllMemoriesBlock(Block, Mem0Base):
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
graph_exec_id: str,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
try:
|
||||
client = self._get_client(credentials)
|
||||
@@ -314,6 +328,8 @@ class GetAllMemoriesBlock(Block, Mem0Base):
|
||||
filters["AND"].append(
|
||||
{"categories": {"contains": input_data.categories}}
|
||||
)
|
||||
if input_data.metadata_filter:
|
||||
filters["AND"].append({"metadata": input_data.metadata_filter})
|
||||
|
||||
memories: list[dict[str, Any]] = client.get_all(
|
||||
filters=filters,
|
||||
@@ -326,14 +342,116 @@ class GetAllMemoriesBlock(Block, Mem0Base):
|
||||
yield "error", str(e)
|
||||
|
||||
|
||||
class GetLatestMemoryBlock(Block, Mem0Base):
|
||||
"""Block for retrieving the latest memory from Mem0"""
|
||||
|
||||
class Input(BlockSchema):
|
||||
credentials: CredentialsMetaInput[
|
||||
Literal[ProviderName.MEM0], Literal["api_key"]
|
||||
] = CredentialsField(description="Mem0 API key credentials")
|
||||
trigger: bool = SchemaField(
|
||||
description="An unused field that is used to trigger the block when you have no other inputs",
|
||||
default=False,
|
||||
advanced=False,
|
||||
)
|
||||
categories: Optional[list[str]] = SchemaField(
|
||||
description="Filter by categories", default=None
|
||||
)
|
||||
conversation_id: Optional[str] = SchemaField(
|
||||
description="Optional conversation ID to retrieve the latest memory from (uses run_id)",
|
||||
default=None,
|
||||
)
|
||||
metadata_filter: Optional[dict[str, Any]] = SchemaField(
|
||||
description="Optional metadata filters to apply",
|
||||
default=None,
|
||||
)
|
||||
limit_memory_to_run: bool = SchemaField(
|
||||
description="Limit the memory to the run", default=False
|
||||
)
|
||||
limit_memory_to_agent: bool = SchemaField(
|
||||
description="Limit the memory to the agent", default=True
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
memory: Optional[dict[str, Any]] = SchemaField(
|
||||
description="Latest memory if found"
|
||||
)
|
||||
found: bool = SchemaField(description="Whether a memory was found")
|
||||
error: str = SchemaField(description="Error message if operation fails")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="0f9d81b5-a145-4c23-b87f-01d6bf37b677",
|
||||
description="Retrieve the latest memory from Mem0 with optional key filtering",
|
||||
input_schema=GetLatestMemoryBlock.Input,
|
||||
output_schema=GetLatestMemoryBlock.Output,
|
||||
test_input={
|
||||
"metadata_filter": {"type": "test"},
|
||||
"credentials": TEST_CREDENTIALS_INPUT,
|
||||
},
|
||||
test_output=[
|
||||
("memory", {"id": "test-memory", "content": "test content"}),
|
||||
("found", True),
|
||||
],
|
||||
test_credentials=TEST_CREDENTIALS,
|
||||
test_mock={"_get_client": lambda credentials: MockMemoryClient()},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
input_data: Input,
|
||||
*,
|
||||
credentials: APIKeyCredentials,
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
graph_exec_id: str,
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
try:
|
||||
client = self._get_client(credentials)
|
||||
|
||||
filters: Filter = {
|
||||
"AND": [
|
||||
{"user_id": user_id},
|
||||
]
|
||||
}
|
||||
if input_data.limit_memory_to_run:
|
||||
filters["AND"].append({"run_id": graph_exec_id})
|
||||
if input_data.limit_memory_to_agent:
|
||||
filters["AND"].append({"agent_id": graph_id})
|
||||
if input_data.categories:
|
||||
filters["AND"].append(
|
||||
{"categories": {"contains": input_data.categories}}
|
||||
)
|
||||
if input_data.metadata_filter:
|
||||
filters["AND"].append({"metadata": input_data.metadata_filter})
|
||||
|
||||
memories: list[dict[str, Any]] = client.get_all(
|
||||
filters=filters,
|
||||
version="v2",
|
||||
)
|
||||
|
||||
if memories:
|
||||
# Return the latest memory (first in the list as they're sorted by recency)
|
||||
latest_memory = memories[0]
|
||||
yield "memory", latest_memory
|
||||
yield "found", True
|
||||
else:
|
||||
yield "memory", None
|
||||
yield "found", False
|
||||
|
||||
except Exception as e:
|
||||
yield "error", str(e)
|
||||
|
||||
|
||||
# Mock client for testing
|
||||
class MockMemoryClient:
|
||||
"""Mock Mem0 client for testing"""
|
||||
|
||||
def add(self, *args, **kwargs):
|
||||
return {"memory_id": "test-memory-id", "status": "success"}
|
||||
return {"results": [{"event": "CREATED", "memory": "test memory"}]}
|
||||
|
||||
def search(self, *args, **kwargs) -> list[dict[str, str]]:
|
||||
def search(self, *args, **kwargs) -> list[dict[str, Any]]:
|
||||
return [{"id": "test-memory", "content": "test content"}]
|
||||
|
||||
def get_all(self, *args, **kwargs) -> list[dict[str, str]]:
|
||||
|
||||
154
autogpt_platform/backend/backend/blocks/persistence.py
Normal file
154
autogpt_platform/backend/backend/blocks/persistence.py
Normal file
@@ -0,0 +1,154 @@
|
||||
import logging
|
||||
from typing import Any, Literal
|
||||
|
||||
from autogpt_libs.utils.cache import thread_cached
|
||||
|
||||
from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
|
||||
from backend.data.model import SchemaField
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@thread_cached
|
||||
def get_database_manager_client():
|
||||
from backend.executor import DatabaseManagerAsyncClient
|
||||
from backend.util.service import get_service_client
|
||||
|
||||
return get_service_client(DatabaseManagerAsyncClient, health_check=False)
|
||||
|
||||
|
||||
StorageScope = Literal["within_agent", "across_agents"]
|
||||
|
||||
|
||||
def get_storage_key(key: str, scope: StorageScope, graph_id: str) -> str:
|
||||
"""Generate the storage key based on scope"""
|
||||
if scope == "across_agents":
|
||||
return f"global#{key}"
|
||||
else:
|
||||
return f"agent#{graph_id}#{key}"
|
||||
|
||||
|
||||
class PersistInformationBlock(Block):
|
||||
"""Block for persisting key-value data for the current user with configurable scope"""
|
||||
|
||||
class Input(BlockSchema):
|
||||
key: str = SchemaField(description="Key to store the information under")
|
||||
value: Any = SchemaField(description="Value to store")
|
||||
scope: StorageScope = SchemaField(
|
||||
description="Scope of persistence: within_agent (shared across all runs of this agent) or across_agents (shared across all agents for this user)",
|
||||
default="within_agent",
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
value: Any = SchemaField(description="Value that was stored")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="1d055e55-a2b9-4547-8311-907d05b0304d",
|
||||
description="Persist key-value information for the current user",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=PersistInformationBlock.Input,
|
||||
output_schema=PersistInformationBlock.Output,
|
||||
test_input={
|
||||
"key": "user_preference",
|
||||
"value": {"theme": "dark", "language": "en"},
|
||||
"scope": "within_agent",
|
||||
},
|
||||
test_output=[
|
||||
("value", {"theme": "dark", "language": "en"}),
|
||||
],
|
||||
test_mock={
|
||||
"_store_data": lambda *args, **kwargs: {
|
||||
"theme": "dark",
|
||||
"language": "en",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self,
|
||||
input_data: Input,
|
||||
*,
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
node_exec_id: str,
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
# Determine the storage key based on scope
|
||||
storage_key = get_storage_key(input_data.key, input_data.scope, graph_id)
|
||||
|
||||
# Store the data
|
||||
yield "value", await self._store_data(
|
||||
user_id=user_id,
|
||||
node_exec_id=node_exec_id,
|
||||
key=storage_key,
|
||||
data=input_data.value,
|
||||
)
|
||||
|
||||
async def _store_data(
|
||||
self, user_id: str, node_exec_id: str, key: str, data: Any
|
||||
) -> Any | None:
|
||||
return await get_database_manager_client().set_execution_kv_data(
|
||||
user_id=user_id,
|
||||
node_exec_id=node_exec_id,
|
||||
key=key,
|
||||
data=data,
|
||||
)
|
||||
|
||||
|
||||
class RetrieveInformationBlock(Block):
|
||||
"""Block for retrieving key-value data for the current user with configurable scope"""
|
||||
|
||||
class Input(BlockSchema):
|
||||
key: str = SchemaField(description="Key to retrieve the information for")
|
||||
scope: StorageScope = SchemaField(
|
||||
description="Scope of persistence: within_agent (shared across all runs of this agent) or across_agents (shared across all agents for this user)",
|
||||
default="within_agent",
|
||||
)
|
||||
default_value: Any = SchemaField(
|
||||
description="Default value to return if key is not found", default=None
|
||||
)
|
||||
|
||||
class Output(BlockSchema):
|
||||
value: Any = SchemaField(description="Retrieved value or default value")
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
id="d8710fc9-6e29-481e-a7d5-165eb16f8471",
|
||||
description="Retrieve key-value information for the current user",
|
||||
categories={BlockCategory.DATA},
|
||||
input_schema=RetrieveInformationBlock.Input,
|
||||
output_schema=RetrieveInformationBlock.Output,
|
||||
test_input={
|
||||
"key": "user_preference",
|
||||
"scope": "within_agent",
|
||||
"default_value": {"theme": "light", "language": "en"},
|
||||
},
|
||||
test_output=[
|
||||
("value", {"theme": "light", "language": "en"}),
|
||||
],
|
||||
test_mock={"_retrieve_data": lambda *args, **kwargs: None},
|
||||
)
|
||||
|
||||
async def run(
|
||||
self, input_data: Input, *, user_id: str, graph_id: str, **kwargs
|
||||
) -> BlockOutput:
|
||||
# Determine the storage key based on scope
|
||||
storage_key = get_storage_key(input_data.key, input_data.scope, graph_id)
|
||||
|
||||
# Retrieve the data
|
||||
stored_value = await self._retrieve_data(
|
||||
user_id=user_id,
|
||||
key=storage_key,
|
||||
)
|
||||
|
||||
if stored_value is not None:
|
||||
yield "value", stored_value
|
||||
else:
|
||||
yield "value", input_data.default_value
|
||||
|
||||
async def _retrieve_data(self, user_id: str, key: str) -> Any | None:
|
||||
return await get_database_manager_client().get_execution_kv_data(
|
||||
user_id=user_id,
|
||||
key=key,
|
||||
)
|
||||
@@ -26,10 +26,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
@thread_cached
|
||||
def get_database_manager_client():
|
||||
from backend.executor import DatabaseManagerClient
|
||||
from backend.executor import DatabaseManagerAsyncClient
|
||||
from backend.util.service import get_service_client
|
||||
|
||||
return get_service_client(DatabaseManagerClient)
|
||||
return get_service_client(DatabaseManagerAsyncClient, health_check=False)
|
||||
|
||||
|
||||
def _get_tool_requests(entry: dict[str, Any]) -> list[str]:
|
||||
@@ -273,7 +273,7 @@ class SmartDecisionMakerBlock(Block):
|
||||
return re.sub(r"[^a-zA-Z0-9_-]", "_", s).lower()
|
||||
|
||||
@staticmethod
|
||||
def _create_block_function_signature(
|
||||
async def _create_block_function_signature(
|
||||
sink_node: "Node", links: list["Link"]
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -312,7 +312,7 @@ class SmartDecisionMakerBlock(Block):
|
||||
return {"type": "function", "function": tool_function}
|
||||
|
||||
@staticmethod
|
||||
def _create_agent_function_signature(
|
||||
async def _create_agent_function_signature(
|
||||
sink_node: "Node", links: list["Link"]
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -334,7 +334,7 @@ class SmartDecisionMakerBlock(Block):
|
||||
raise ValueError("Graph ID or Graph Version not found in sink node.")
|
||||
|
||||
db_client = get_database_manager_client()
|
||||
sink_graph_meta = db_client.get_graph_metadata(graph_id, graph_version)
|
||||
sink_graph_meta = await db_client.get_graph_metadata(graph_id, graph_version)
|
||||
if not sink_graph_meta:
|
||||
raise ValueError(
|
||||
f"Sink graph metadata not found: {graph_id} {graph_version}"
|
||||
@@ -374,7 +374,7 @@ class SmartDecisionMakerBlock(Block):
|
||||
return {"type": "function", "function": tool_function}
|
||||
|
||||
@staticmethod
|
||||
def _create_function_signature(node_id: str) -> list[dict[str, Any]]:
|
||||
async def _create_function_signature(node_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Creates function signatures for tools linked to a specified node within a graph.
|
||||
|
||||
@@ -396,13 +396,13 @@ class SmartDecisionMakerBlock(Block):
|
||||
db_client = get_database_manager_client()
|
||||
tools = [
|
||||
(link, node)
|
||||
for link, node in db_client.get_connected_output_nodes(node_id)
|
||||
for link, node in await db_client.get_connected_output_nodes(node_id)
|
||||
if link.source_name.startswith("tools_^_") and link.source_id == node_id
|
||||
]
|
||||
if not tools:
|
||||
raise ValueError("There is no next node to execute.")
|
||||
|
||||
return_tool_functions = []
|
||||
return_tool_functions: list[dict[str, Any]] = []
|
||||
|
||||
grouped_tool_links: dict[str, tuple["Node", list["Link"]]] = {}
|
||||
for link, node in tools:
|
||||
@@ -417,13 +417,13 @@ class SmartDecisionMakerBlock(Block):
|
||||
|
||||
if sink_node.block_id == AgentExecutorBlock().id:
|
||||
return_tool_functions.append(
|
||||
SmartDecisionMakerBlock._create_agent_function_signature(
|
||||
await SmartDecisionMakerBlock._create_agent_function_signature(
|
||||
sink_node, links
|
||||
)
|
||||
)
|
||||
else:
|
||||
return_tool_functions.append(
|
||||
SmartDecisionMakerBlock._create_block_function_signature(
|
||||
await SmartDecisionMakerBlock._create_block_function_signature(
|
||||
sink_node, links
|
||||
)
|
||||
)
|
||||
@@ -442,7 +442,7 @@ class SmartDecisionMakerBlock(Block):
|
||||
user_id: str,
|
||||
**kwargs,
|
||||
) -> BlockOutput:
|
||||
tool_functions = self._create_function_signature(node_id)
|
||||
tool_functions = await self._create_function_signature(node_id)
|
||||
yield "tool_functions", json.dumps(tool_functions)
|
||||
|
||||
input_data.conversation_history = input_data.conversation_history or []
|
||||
|
||||
@@ -161,7 +161,7 @@ async def test_smart_decision_maker_function_signature(server: SpinTestServer):
|
||||
)
|
||||
test_graph = await create_graph(server, test_graph, test_user)
|
||||
|
||||
tool_functions = SmartDecisionMakerBlock._create_function_signature(
|
||||
tool_functions = await SmartDecisionMakerBlock._create_function_signature(
|
||||
test_graph.nodes[0].id
|
||||
)
|
||||
assert tool_functions is not None, "Tool functions should not be None"
|
||||
|
||||
@@ -22,6 +22,7 @@ from prisma.models import (
|
||||
AgentGraphExecution,
|
||||
AgentNodeExecution,
|
||||
AgentNodeExecutionInputOutput,
|
||||
AgentNodeExecutionKeyValueData,
|
||||
)
|
||||
from prisma.types import (
|
||||
AgentGraphExecutionCreateInput,
|
||||
@@ -29,6 +30,7 @@ from prisma.types import (
|
||||
AgentGraphExecutionWhereInput,
|
||||
AgentNodeExecutionCreateInput,
|
||||
AgentNodeExecutionInputOutputCreateInput,
|
||||
AgentNodeExecutionKeyValueDataCreateInput,
|
||||
AgentNodeExecutionUpdateInput,
|
||||
AgentNodeExecutionWhereInput,
|
||||
)
|
||||
@@ -347,6 +349,7 @@ class NodeExecutionResult(BaseModel):
|
||||
|
||||
|
||||
async def get_graph_executions(
|
||||
graph_exec_id: str | None = None,
|
||||
graph_id: str | None = None,
|
||||
user_id: str | None = None,
|
||||
statuses: list[ExecutionStatus] | None = None,
|
||||
@@ -357,6 +360,8 @@ async def get_graph_executions(
|
||||
where_filter: AgentGraphExecutionWhereInput = {
|
||||
"isDeleted": False,
|
||||
}
|
||||
if graph_exec_id:
|
||||
where_filter["id"] = graph_exec_id
|
||||
if user_id:
|
||||
where_filter["userId"] = user_id
|
||||
if graph_id:
|
||||
@@ -588,12 +593,10 @@ async def update_graph_execution_start_time(
|
||||
|
||||
async def update_graph_execution_stats(
|
||||
graph_exec_id: str,
|
||||
status: ExecutionStatus,
|
||||
status: ExecutionStatus | None = None,
|
||||
stats: GraphExecutionStats | None = None,
|
||||
) -> GraphExecution | None:
|
||||
update_data: AgentGraphExecutionUpdateManyMutationInput = {
|
||||
"executionStatus": status
|
||||
}
|
||||
update_data: AgentGraphExecutionUpdateManyMutationInput = {}
|
||||
|
||||
if stats:
|
||||
stats_dict = stats.model_dump()
|
||||
@@ -601,6 +604,9 @@ async def update_graph_execution_stats(
|
||||
stats_dict["error"] = str(stats_dict["error"])
|
||||
update_data["stats"] = Json(stats_dict)
|
||||
|
||||
if status:
|
||||
update_data["executionStatus"] = status
|
||||
|
||||
updated_count = await AgentGraphExecution.prisma().update_many(
|
||||
where={
|
||||
"id": graph_exec_id,
|
||||
@@ -903,3 +909,57 @@ class AsyncRedisExecutionEventBus(AsyncRedisEventBus[ExecutionEvent]):
|
||||
) -> AsyncGenerator[ExecutionEvent, None]:
|
||||
async for event in self.listen_events(f"{user_id}/{graph_id}/{graph_exec_id}"):
|
||||
yield event
|
||||
|
||||
|
||||
# --------------------- KV Data Functions --------------------- #
|
||||
|
||||
|
||||
async def get_execution_kv_data(user_id: str, key: str) -> Any | None:
|
||||
"""
|
||||
Get key-value data for a user and key.
|
||||
|
||||
Args:
|
||||
user_id: The id of the User.
|
||||
key: The key to retrieve data for.
|
||||
|
||||
Returns:
|
||||
The data associated with the key, or None if not found.
|
||||
"""
|
||||
kv_data = await AgentNodeExecutionKeyValueData.prisma().find_unique(
|
||||
where={"userId_key": {"userId": user_id, "key": key}}
|
||||
)
|
||||
return (
|
||||
type_utils.convert(kv_data.data, type[Any])
|
||||
if kv_data and kv_data.data
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
async def set_execution_kv_data(
|
||||
user_id: str, node_exec_id: str, key: str, data: Any
|
||||
) -> Any | None:
|
||||
"""
|
||||
Set key-value data for a user and key.
|
||||
|
||||
Args:
|
||||
user_id: The id of the User.
|
||||
node_exec_id: The id of the AgentNodeExecution.
|
||||
key: The key to store data under.
|
||||
data: The data to store.
|
||||
"""
|
||||
resp = await AgentNodeExecutionKeyValueData.prisma().upsert(
|
||||
where={"userId_key": {"userId": user_id, "key": key}},
|
||||
data={
|
||||
"create": AgentNodeExecutionKeyValueDataCreateInput(
|
||||
userId=user_id,
|
||||
agentNodeExecutionId=node_exec_id,
|
||||
key=key,
|
||||
data=Json(data) if data is not None else None,
|
||||
),
|
||||
"update": {
|
||||
"agentNodeExecutionId": node_exec_id,
|
||||
"data": Json(data) if data is not None else None,
|
||||
},
|
||||
},
|
||||
)
|
||||
return type_utils.convert(resp.data, type[Any]) if resp and resp.data else None
|
||||
|
||||
@@ -5,12 +5,14 @@ from backend.data import db
|
||||
from backend.data.credit import UsageTransactionMetadata, get_user_credit_model
|
||||
from backend.data.execution import (
|
||||
create_graph_execution,
|
||||
get_execution_kv_data,
|
||||
get_graph_execution,
|
||||
get_graph_execution_meta,
|
||||
get_graph_executions,
|
||||
get_latest_node_execution,
|
||||
get_node_execution,
|
||||
get_node_executions,
|
||||
set_execution_kv_data,
|
||||
update_graph_execution_start_time,
|
||||
update_graph_execution_stats,
|
||||
update_node_execution_stats,
|
||||
@@ -101,6 +103,8 @@ class DatabaseManager(AppService):
|
||||
update_node_execution_stats = _(update_node_execution_stats)
|
||||
upsert_execution_input = _(upsert_execution_input)
|
||||
upsert_execution_output = _(upsert_execution_output)
|
||||
get_execution_kv_data = _(get_execution_kv_data)
|
||||
set_execution_kv_data = _(set_execution_kv_data)
|
||||
|
||||
# Graphs
|
||||
get_node = _(get_node)
|
||||
@@ -159,6 +163,8 @@ class DatabaseManagerClient(AppServiceClient):
|
||||
update_node_execution_stats = _(d.update_node_execution_stats)
|
||||
upsert_execution_input = _(d.upsert_execution_input)
|
||||
upsert_execution_output = _(d.upsert_execution_output)
|
||||
get_execution_kv_data = _(d.get_execution_kv_data)
|
||||
set_execution_kv_data = _(d.set_execution_kv_data)
|
||||
|
||||
# Graphs
|
||||
get_node = _(d.get_node)
|
||||
@@ -202,8 +208,11 @@ class DatabaseManagerAsyncClient(AppServiceClient):
|
||||
return DatabaseManager
|
||||
|
||||
create_graph_execution = d.create_graph_execution
|
||||
get_connected_output_nodes = d.get_connected_output_nodes
|
||||
get_latest_node_execution = d.get_latest_node_execution
|
||||
get_graph = d.get_graph
|
||||
get_graph_metadata = d.get_graph_metadata
|
||||
get_graph_execution_meta = d.get_graph_execution_meta
|
||||
get_node = d.get_node
|
||||
get_node_execution = d.get_node_execution
|
||||
get_node_executions = d.get_node_executions
|
||||
@@ -215,3 +224,5 @@ class DatabaseManagerAsyncClient(AppServiceClient):
|
||||
update_node_execution_status = d.update_node_execution_status
|
||||
update_node_execution_status_batch = d.update_node_execution_status_batch
|
||||
update_user_integrations = d.update_user_integrations
|
||||
get_execution_kv_data = d.get_execution_kv_data
|
||||
set_execution_kv_data = d.set_execution_kv_data
|
||||
|
||||
@@ -24,7 +24,7 @@ from backend.data.notifications import (
|
||||
NotificationType,
|
||||
)
|
||||
from backend.data.rabbitmq import SyncRabbitMQ
|
||||
from backend.executor.utils import create_execution_queue_config
|
||||
from backend.executor.utils import LogMetadata, create_execution_queue_config
|
||||
from backend.notifications.notifications import queue_notification
|
||||
from backend.util.exceptions import InsufficientBalanceError
|
||||
|
||||
@@ -98,35 +98,6 @@ utilization_gauge = Gauge(
|
||||
)
|
||||
|
||||
|
||||
class LogMetadata(TruncatedLogger):
|
||||
def __init__(
|
||||
self,
|
||||
user_id: str,
|
||||
graph_eid: str,
|
||||
graph_id: str,
|
||||
node_eid: str,
|
||||
node_id: str,
|
||||
block_name: str,
|
||||
max_length: int = 1000,
|
||||
):
|
||||
metadata = {
|
||||
"component": "ExecutionManager",
|
||||
"user_id": user_id,
|
||||
"graph_eid": graph_eid,
|
||||
"graph_id": graph_id,
|
||||
"node_eid": node_eid,
|
||||
"node_id": node_id,
|
||||
"block_name": block_name,
|
||||
}
|
||||
prefix = f"[ExecutionManager|uid:{user_id}|gid:{graph_id}|nid:{node_id}]|geid:{graph_eid}|neid:{node_eid}|{block_name}]"
|
||||
super().__init__(
|
||||
_logger,
|
||||
max_length=max_length,
|
||||
prefix=prefix,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
@@ -158,6 +129,7 @@ async def execute_node(
|
||||
node_block = node.block
|
||||
|
||||
log_metadata = LogMetadata(
|
||||
logger=_logger,
|
||||
user_id=user_id,
|
||||
graph_eid=graph_exec_id,
|
||||
graph_id=graph_id,
|
||||
@@ -421,7 +393,7 @@ class Executor:
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
@async_error_logged
|
||||
@async_error_logged(swallow=True)
|
||||
async def on_node_execution(
|
||||
cls,
|
||||
node_exec: NodeExecutionEntry,
|
||||
@@ -429,6 +401,7 @@ class Executor:
|
||||
nodes_input_masks: Optional[dict[str, dict[str, JsonValue]]] = None,
|
||||
) -> NodeExecutionStats:
|
||||
log_metadata = LogMetadata(
|
||||
logger=_logger,
|
||||
user_id=node_exec.user_id,
|
||||
graph_eid=node_exec.graph_exec_id,
|
||||
graph_id=node_exec.graph_id,
|
||||
@@ -529,11 +502,12 @@ class Executor:
|
||||
logger.info(f"[GraphExecutor] {cls.pid} started")
|
||||
|
||||
@classmethod
|
||||
@error_logged
|
||||
@error_logged(swallow=False)
|
||||
def on_graph_execution(
|
||||
cls, graph_exec: GraphExecutionEntry, cancel: threading.Event
|
||||
):
|
||||
log_metadata = LogMetadata(
|
||||
logger=_logger,
|
||||
user_id=graph_exec.user_id,
|
||||
graph_eid=graph_exec.graph_exec_id,
|
||||
graph_id=graph_exec.graph_id,
|
||||
@@ -581,6 +555,15 @@ class Executor:
|
||||
exec_stats.cputime += timing_info.cpu_time
|
||||
exec_stats.error = str(error) if error else exec_stats.error
|
||||
|
||||
if status not in {
|
||||
ExecutionStatus.COMPLETED,
|
||||
ExecutionStatus.TERMINATED,
|
||||
ExecutionStatus.FAILED,
|
||||
}:
|
||||
raise RuntimeError(
|
||||
f"Graph Execution #{graph_exec.graph_exec_id} ended with unexpected status {status}"
|
||||
)
|
||||
|
||||
if graph_exec_result := db_client.update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec.graph_exec_id,
|
||||
status=status,
|
||||
@@ -684,7 +667,6 @@ class Executor:
|
||||
|
||||
if _graph_exec := db_client.update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec.graph_exec_id,
|
||||
status=execution_status,
|
||||
stats=execution_stats,
|
||||
):
|
||||
send_execution_update(_graph_exec)
|
||||
@@ -853,6 +835,7 @@ class Executor:
|
||||
f"Failed graph execution {graph_exec.graph_exec_id}: {error}"
|
||||
)
|
||||
finally:
|
||||
# Cancel and wait for all node executions to complete
|
||||
for node_id, inflight_exec in running_node_execution.items():
|
||||
if inflight_exec.is_done():
|
||||
continue
|
||||
@@ -865,6 +848,28 @@ class Executor:
|
||||
log_metadata.info(f"Stopping node evaluation {node_id}")
|
||||
inflight_eval.cancel()
|
||||
|
||||
for node_id, inflight_exec in running_node_execution.items():
|
||||
if inflight_exec.is_done():
|
||||
continue
|
||||
try:
|
||||
inflight_exec.wait_for_cancellation(timeout=60.0)
|
||||
except TimeoutError:
|
||||
log_metadata.exception(
|
||||
f"Node execution #{node_id} did not stop in time, "
|
||||
"it may be stuck or taking too long."
|
||||
)
|
||||
|
||||
for node_id, inflight_eval in running_node_evaluation.items():
|
||||
if inflight_eval.done():
|
||||
continue
|
||||
try:
|
||||
inflight_eval.result(timeout=60.0)
|
||||
except TimeoutError:
|
||||
log_metadata.exception(
|
||||
f"Node evaluation #{node_id} did not stop in time, "
|
||||
"it may be stuck or taking too long."
|
||||
)
|
||||
|
||||
if execution_status in [ExecutionStatus.TERMINATED, ExecutionStatus.FAILED]:
|
||||
inflight_executions = db_client.get_node_executions(
|
||||
graph_exec.graph_exec_id,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import Future
|
||||
from typing import TYPE_CHECKING, Any, Callable, Optional, cast
|
||||
@@ -7,6 +8,8 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, cast
|
||||
from autogpt_libs.utils.cache import thread_cached
|
||||
from pydantic import BaseModel, JsonValue
|
||||
|
||||
from backend.data import execution as execution_db
|
||||
from backend.data import graph as graph_db
|
||||
from backend.data.block import (
|
||||
Block,
|
||||
BlockData,
|
||||
@@ -23,12 +26,8 @@ from backend.data.execution import (
|
||||
GraphExecutionStats,
|
||||
GraphExecutionWithNodes,
|
||||
RedisExecutionEventBus,
|
||||
create_graph_execution,
|
||||
get_node_executions,
|
||||
update_graph_execution_stats,
|
||||
update_node_execution_status_batch,
|
||||
)
|
||||
from backend.data.graph import GraphModel, Node, get_graph
|
||||
from backend.data.graph import GraphModel, Node
|
||||
from backend.data.model import CredentialsMetaInput
|
||||
from backend.data.rabbitmq import (
|
||||
AsyncRabbitMQ,
|
||||
@@ -55,6 +54,36 @@ logger = TruncatedLogger(logging.getLogger(__name__), prefix="[GraphExecutorUtil
|
||||
# ============ Resource Helpers ============ #
|
||||
|
||||
|
||||
class LogMetadata(TruncatedLogger):
|
||||
def __init__(
|
||||
self,
|
||||
logger: logging.Logger,
|
||||
user_id: str,
|
||||
graph_eid: str,
|
||||
graph_id: str,
|
||||
node_eid: str,
|
||||
node_id: str,
|
||||
block_name: str,
|
||||
max_length: int = 1000,
|
||||
):
|
||||
metadata = {
|
||||
"component": "ExecutionManager",
|
||||
"user_id": user_id,
|
||||
"graph_eid": graph_eid,
|
||||
"graph_id": graph_id,
|
||||
"node_eid": node_eid,
|
||||
"node_id": node_id,
|
||||
"block_name": block_name,
|
||||
}
|
||||
prefix = f"[ExecutionManager|uid:{user_id}|gid:{graph_id}|nid:{node_id}]|geid:{graph_eid}|neid:{node_eid}|{block_name}]"
|
||||
super().__init__(
|
||||
logger,
|
||||
max_length=max_length,
|
||||
prefix=prefix,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
@thread_cached
|
||||
def get_execution_event_bus() -> RedisExecutionEventBus:
|
||||
return RedisExecutionEventBus()
|
||||
@@ -653,8 +682,10 @@ def create_execution_queue_config() -> RabbitMQConfig:
|
||||
|
||||
|
||||
async def stop_graph_execution(
|
||||
user_id: str,
|
||||
graph_exec_id: str,
|
||||
use_db_query: bool = True,
|
||||
wait_timeout: float = 60.0,
|
||||
):
|
||||
"""
|
||||
Mechanism:
|
||||
@@ -664,66 +695,56 @@ async def stop_graph_execution(
|
||||
3. Update execution statuses in DB and set `error` outputs to `"TERMINATED"`.
|
||||
"""
|
||||
queue_client = await get_async_execution_queue()
|
||||
db = execution_db if use_db_query else get_db_async_client()
|
||||
await queue_client.publish_message(
|
||||
routing_key="",
|
||||
message=CancelExecutionEvent(graph_exec_id=graph_exec_id).model_dump_json(),
|
||||
exchange=GRAPH_EXECUTION_CANCEL_EXCHANGE,
|
||||
)
|
||||
|
||||
# Update the status of the graph execution
|
||||
if use_db_query:
|
||||
graph_execution = await update_graph_execution_stats(
|
||||
graph_exec_id,
|
||||
ExecutionStatus.TERMINATED,
|
||||
)
|
||||
else:
|
||||
graph_execution = await get_db_async_client().update_graph_execution_stats(
|
||||
graph_exec_id,
|
||||
ExecutionStatus.TERMINATED,
|
||||
if not wait_timeout:
|
||||
return
|
||||
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < wait_timeout:
|
||||
graph_exec = await db.get_graph_execution_meta(
|
||||
execution_id=graph_exec_id, user_id=user_id
|
||||
)
|
||||
|
||||
if graph_execution:
|
||||
await get_async_execution_event_bus().publish(graph_execution)
|
||||
else:
|
||||
raise NotFoundError(
|
||||
f"Graph execution #{graph_exec_id} not found for termination."
|
||||
)
|
||||
if not graph_exec:
|
||||
raise NotFoundError(f"Graph execution #{graph_exec_id} not found.")
|
||||
|
||||
# Update the status of the node executions
|
||||
if use_db_query:
|
||||
node_executions = await get_node_executions(
|
||||
graph_exec_id=graph_exec_id,
|
||||
statuses=[
|
||||
ExecutionStatus.QUEUED,
|
||||
ExecutionStatus.RUNNING,
|
||||
ExecutionStatus.INCOMPLETE,
|
||||
],
|
||||
)
|
||||
await update_node_execution_status_batch(
|
||||
[v.node_exec_id for v in node_executions],
|
||||
if graph_exec.status in [
|
||||
ExecutionStatus.TERMINATED,
|
||||
)
|
||||
else:
|
||||
node_executions = await get_db_async_client().get_node_executions(
|
||||
graph_exec_id=graph_exec_id,
|
||||
statuses=[
|
||||
ExecutionStatus.QUEUED,
|
||||
ExecutionStatus.RUNNING,
|
||||
ExecutionStatus.INCOMPLETE,
|
||||
],
|
||||
)
|
||||
await get_db_async_client().update_node_execution_status_batch(
|
||||
[v.node_exec_id for v in node_executions],
|
||||
ExecutionStatus.TERMINATED,
|
||||
)
|
||||
ExecutionStatus.COMPLETED,
|
||||
ExecutionStatus.FAILED,
|
||||
]:
|
||||
# If graph execution is terminated/completed/failed, cancellation is complete
|
||||
return
|
||||
|
||||
await asyncio.gather(
|
||||
*[
|
||||
get_async_execution_event_bus().publish(
|
||||
v.model_copy(update={"status": ExecutionStatus.TERMINATED})
|
||||
elif graph_exec.status in [
|
||||
ExecutionStatus.QUEUED,
|
||||
ExecutionStatus.INCOMPLETE,
|
||||
]:
|
||||
# If the graph is still on the queue, we can prevent them from being executed
|
||||
# by setting the status to TERMINATED.
|
||||
node_execs = await db.get_node_executions(
|
||||
graph_exec_id=graph_exec_id,
|
||||
statuses=[ExecutionStatus.QUEUED, ExecutionStatus.INCOMPLETE],
|
||||
)
|
||||
for v in node_executions
|
||||
]
|
||||
await db.update_node_execution_status_batch(
|
||||
[node_exec.node_exec_id for node_exec in node_execs],
|
||||
ExecutionStatus.TERMINATED,
|
||||
)
|
||||
await db.update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec_id,
|
||||
status=ExecutionStatus.TERMINATED,
|
||||
)
|
||||
|
||||
await asyncio.sleep(1.0)
|
||||
|
||||
raise TimeoutError(
|
||||
f"Timed out waiting for graph execution #{graph_exec_id} to terminate."
|
||||
)
|
||||
|
||||
|
||||
@@ -753,22 +774,16 @@ async def add_graph_execution(
|
||||
GraphExecutionEntry: The entry for the graph execution.
|
||||
Raises:
|
||||
ValueError: If the graph is not found or if there are validation errors.
|
||||
""" # noqa
|
||||
if use_db_query:
|
||||
graph: GraphModel | None = await get_graph(
|
||||
graph_id=graph_id,
|
||||
user_id=user_id,
|
||||
version=graph_version,
|
||||
include_subgraphs=True,
|
||||
)
|
||||
else:
|
||||
graph: GraphModel | None = await get_db_async_client().get_graph(
|
||||
graph_id=graph_id,
|
||||
user_id=user_id,
|
||||
version=graph_version,
|
||||
include_subgraphs=True,
|
||||
)
|
||||
"""
|
||||
gdb = graph_db if use_db_query else get_db_async_client()
|
||||
edb = execution_db if use_db_query else get_db_async_client()
|
||||
|
||||
graph: GraphModel | None = await gdb.get_graph(
|
||||
graph_id=graph_id,
|
||||
user_id=user_id,
|
||||
version=graph_version,
|
||||
include_subgraphs=True,
|
||||
)
|
||||
if not graph:
|
||||
raise NotFoundError(f"Graph #{graph_id} not found.")
|
||||
|
||||
@@ -787,22 +802,13 @@ async def add_graph_execution(
|
||||
nodes_input_masks=nodes_input_masks,
|
||||
)
|
||||
|
||||
if use_db_query:
|
||||
graph_exec = await create_graph_execution(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_version=graph.version,
|
||||
starting_nodes_input=starting_nodes_input,
|
||||
preset_id=preset_id,
|
||||
)
|
||||
else:
|
||||
graph_exec = await get_db_async_client().create_graph_execution(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_version=graph.version,
|
||||
starting_nodes_input=starting_nodes_input,
|
||||
preset_id=preset_id,
|
||||
)
|
||||
graph_exec = await edb.create_graph_execution(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_version=graph.version,
|
||||
starting_nodes_input=starting_nodes_input,
|
||||
preset_id=preset_id,
|
||||
)
|
||||
|
||||
try:
|
||||
queue = await get_async_execution_queue()
|
||||
@@ -821,28 +827,15 @@ async def add_graph_execution(
|
||||
return graph_exec
|
||||
except Exception as e:
|
||||
logger.error(f"Unable to publish graph #{graph_id} exec #{graph_exec.id}: {e}")
|
||||
|
||||
if use_db_query:
|
||||
await update_node_execution_status_batch(
|
||||
[node_exec.node_exec_id for node_exec in graph_exec.node_executions],
|
||||
ExecutionStatus.FAILED,
|
||||
)
|
||||
await update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec.id,
|
||||
status=ExecutionStatus.FAILED,
|
||||
stats=GraphExecutionStats(error=str(e)),
|
||||
)
|
||||
else:
|
||||
await get_db_async_client().update_node_execution_status_batch(
|
||||
[node_exec.node_exec_id for node_exec in graph_exec.node_executions],
|
||||
ExecutionStatus.FAILED,
|
||||
)
|
||||
await get_db_async_client().update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec.id,
|
||||
status=ExecutionStatus.FAILED,
|
||||
stats=GraphExecutionStats(error=str(e)),
|
||||
)
|
||||
|
||||
await edb.update_node_execution_status_batch(
|
||||
[node_exec.node_exec_id for node_exec in graph_exec.node_executions],
|
||||
ExecutionStatus.FAILED,
|
||||
)
|
||||
await edb.update_graph_execution_stats(
|
||||
graph_exec_id=graph_exec.id,
|
||||
status=ExecutionStatus.FAILED,
|
||||
stats=GraphExecutionStats(error=str(e)),
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
@@ -897,14 +890,10 @@ class NodeExecutionProgress:
|
||||
try:
|
||||
self.tasks[exec_id].result(wait_time)
|
||||
except TimeoutError:
|
||||
print(
|
||||
">>>>>>> -- Timeout, after waiting for",
|
||||
wait_time,
|
||||
"seconds for node_id",
|
||||
exec_id,
|
||||
)
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Task for exec ID {exec_id} failed with error: {str(e)}")
|
||||
pass
|
||||
return self.is_done(0)
|
||||
|
||||
def stop(self) -> list[str]:
|
||||
@@ -921,6 +910,25 @@ class NodeExecutionProgress:
|
||||
cancelled_ids.append(task_id)
|
||||
return cancelled_ids
|
||||
|
||||
def wait_for_cancellation(self, timeout: float = 5.0):
|
||||
"""
|
||||
Wait for all cancelled tasks to complete cancellation.
|
||||
|
||||
Args:
|
||||
timeout: Maximum time to wait for cancellation in seconds
|
||||
"""
|
||||
start_time = time.time()
|
||||
|
||||
while time.time() - start_time < timeout:
|
||||
# Check if all tasks are done (either completed or cancelled)
|
||||
if all(task.done() for task in self.tasks.values()):
|
||||
return True
|
||||
time.sleep(0.1) # Small delay to avoid busy waiting
|
||||
|
||||
raise TimeoutError(
|
||||
f"Timeout waiting for cancellation of tasks: {list(self.tasks.keys())}"
|
||||
)
|
||||
|
||||
def _pop_done_task(self, exec_id: str) -> bool:
|
||||
task = self.tasks.get(exec_id)
|
||||
if not task:
|
||||
@@ -933,8 +941,10 @@ class NodeExecutionProgress:
|
||||
return False
|
||||
|
||||
if task := self.tasks.pop(exec_id):
|
||||
self.on_done_task(exec_id, task.result())
|
||||
|
||||
try:
|
||||
self.on_done_task(exec_id, task.result())
|
||||
except Exception as e:
|
||||
logger.error(f"Task for exec ID {exec_id} failed with error: {str(e)}")
|
||||
return True
|
||||
|
||||
def _next_exec(self) -> str | None:
|
||||
|
||||
@@ -669,24 +669,57 @@ async def execute_graph(
|
||||
)
|
||||
async def stop_graph_run(
|
||||
graph_id: str, graph_exec_id: str, user_id: Annotated[str, Depends(get_user_id)]
|
||||
) -> execution_db.GraphExecution:
|
||||
if not await execution_db.get_graph_execution_meta(
|
||||
user_id=user_id, execution_id=graph_exec_id
|
||||
):
|
||||
raise HTTPException(404, detail=f"Agent execution #{graph_exec_id} not found")
|
||||
|
||||
await execution_utils.stop_graph_execution(graph_exec_id)
|
||||
|
||||
# Retrieve & return canceled graph execution in its final state
|
||||
result = await execution_db.get_graph_execution(
|
||||
execution_id=graph_exec_id, user_id=user_id
|
||||
) -> execution_db.GraphExecutionMeta:
|
||||
res = await _stop_graph_run(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_exec_id=graph_exec_id,
|
||||
)
|
||||
if not result:
|
||||
if not res:
|
||||
raise HTTPException(
|
||||
500,
|
||||
detail=f"Could not fetch graph execution #{graph_exec_id} after stopping",
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail=f"Graph execution #{graph_exec_id} not found.",
|
||||
)
|
||||
return result
|
||||
return res[0]
|
||||
|
||||
|
||||
@v1_router.post(
|
||||
path="/executions",
|
||||
summary="Stop graph executions",
|
||||
tags=["graphs"],
|
||||
dependencies=[Depends(auth_middleware)],
|
||||
)
|
||||
async def stop_graph_runs(
|
||||
graph_id: str, graph_exec_id: str, user_id: Annotated[str, Depends(get_user_id)]
|
||||
) -> list[execution_db.GraphExecutionMeta]:
|
||||
return await _stop_graph_run(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_exec_id=graph_exec_id,
|
||||
)
|
||||
|
||||
|
||||
async def _stop_graph_run(
|
||||
user_id: str,
|
||||
graph_id: Optional[str] = None,
|
||||
graph_exec_id: Optional[str] = None,
|
||||
) -> list[execution_db.GraphExecutionMeta]:
|
||||
graph_execs = await execution_db.get_graph_executions(
|
||||
user_id=user_id,
|
||||
graph_id=graph_id,
|
||||
graph_exec_id=graph_exec_id,
|
||||
statuses=[
|
||||
execution_db.ExecutionStatus.INCOMPLETE,
|
||||
execution_db.ExecutionStatus.QUEUED,
|
||||
execution_db.ExecutionStatus.RUNNING,
|
||||
],
|
||||
)
|
||||
stopped_execs = [
|
||||
execution_utils.stop_graph_execution(graph_exec_id=exec.id, user_id=user_id)
|
||||
for exec in graph_execs
|
||||
]
|
||||
await asyncio.gather(*stopped_execs)
|
||||
return graph_execs
|
||||
|
||||
|
||||
@v1_router.get(
|
||||
|
||||
@@ -215,6 +215,32 @@ async def get_library_agent_by_store_version_id(
|
||||
return None
|
||||
|
||||
|
||||
async def get_library_agent_by_graph_id(
|
||||
user_id: str,
|
||||
graph_id: str,
|
||||
graph_version: Optional[int] = None,
|
||||
) -> library_model.LibraryAgent | None:
|
||||
try:
|
||||
filter: prisma.types.LibraryAgentWhereInput = {
|
||||
"agentGraphId": graph_id,
|
||||
"userId": user_id,
|
||||
"isDeleted": False,
|
||||
}
|
||||
if graph_version is not None:
|
||||
filter["agentGraphVersion"] = graph_version
|
||||
|
||||
agent = await prisma.models.LibraryAgent.prisma().find_first(
|
||||
where=filter,
|
||||
include=library_agent_include(user_id),
|
||||
)
|
||||
if not agent:
|
||||
return None
|
||||
return library_model.LibraryAgent.from_db(agent)
|
||||
except prisma.errors.PrismaError as e:
|
||||
logger.error(f"Database error fetching library agent by graph ID: {e}")
|
||||
raise store_exceptions.DatabaseError("Failed to fetch library agent") from e
|
||||
|
||||
|
||||
async def add_generated_agent_image(
|
||||
graph: graph_db.GraphModel,
|
||||
library_agent_id: str,
|
||||
|
||||
@@ -92,6 +92,23 @@ async def get_library_agent(
|
||||
return await library_db.get_library_agent(id=library_agent_id, user_id=user_id)
|
||||
|
||||
|
||||
@router.get("/by-graph/{graph_id}")
|
||||
async def get_library_agent_by_graph_id(
|
||||
graph_id: str,
|
||||
version: Optional[int] = Query(default=None),
|
||||
user_id: str = Depends(autogpt_auth_lib.depends.get_user_id),
|
||||
) -> library_model.LibraryAgent:
|
||||
library_agent = await library_db.get_library_agent_by_graph_id(
|
||||
user_id, graph_id, version
|
||||
)
|
||||
if not library_agent:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Library agent for graph #{graph_id} and user #{user_id} not found",
|
||||
)
|
||||
return library_agent
|
||||
|
||||
|
||||
@router.get(
|
||||
"/marketplace/{store_listing_version_id}",
|
||||
summary="Get Agent By Store ID",
|
||||
|
||||
@@ -2,7 +2,17 @@ import functools
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Awaitable, Callable, Coroutine, ParamSpec, Tuple, TypeVar
|
||||
from typing import (
|
||||
Any,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Literal,
|
||||
ParamSpec,
|
||||
Tuple,
|
||||
TypeVar,
|
||||
overload,
|
||||
)
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -72,37 +82,115 @@ def async_time_measured(
|
||||
return async_wrapper
|
||||
|
||||
|
||||
def error_logged(func: Callable[P, T]) -> Callable[P, T | None]:
|
||||
@overload
|
||||
def error_logged(
|
||||
*, swallow: Literal[True]
|
||||
) -> Callable[[Callable[P, T]], Callable[P, T | None]]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def error_logged(
|
||||
*, swallow: Literal[False]
|
||||
) -> Callable[[Callable[P, T]], Callable[P, T]]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def error_logged() -> Callable[[Callable[P, T]], Callable[P, T | None]]: ...
|
||||
|
||||
|
||||
def error_logged(
|
||||
*, swallow: bool = True
|
||||
) -> (
|
||||
Callable[[Callable[P, T]], Callable[P, T | None]]
|
||||
| Callable[[Callable[P, T]], Callable[P, T]]
|
||||
):
|
||||
"""
|
||||
Decorator to suppress and log any exceptions raised by a function.
|
||||
Decorator to log any exceptions raised by a function, with optional suppression.
|
||||
|
||||
Args:
|
||||
swallow: Whether to suppress the exception (True) or re-raise it (False). Default is True.
|
||||
|
||||
Usage:
|
||||
@error_logged() # Default behavior (swallow errors)
|
||||
@error_logged(swallow=False) # Log and re-raise errors
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T | None:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"Error when calling function {func.__name__} with arguments {args} {kwargs}: {e}"
|
||||
)
|
||||
def decorator(f: Callable[P, T]) -> Callable[P, T | None]:
|
||||
@functools.wraps(f)
|
||||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T | None:
|
||||
try:
|
||||
return f(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"Error when calling function {f.__name__} with arguments {args} {kwargs}: {e}"
|
||||
)
|
||||
if not swallow:
|
||||
raise
|
||||
return None
|
||||
|
||||
return wrapper
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@overload
|
||||
def async_error_logged(
|
||||
func: Callable[P, Coroutine[Any, Any, T]],
|
||||
) -> Callable[P, Coroutine[Any, Any, T | None]]:
|
||||
*, swallow: Literal[True]
|
||||
) -> Callable[
|
||||
[Callable[P, Coroutine[Any, Any, T]]], Callable[P, Coroutine[Any, Any, T | None]]
|
||||
]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def async_error_logged(
|
||||
*, swallow: Literal[False]
|
||||
) -> Callable[
|
||||
[Callable[P, Coroutine[Any, Any, T]]], Callable[P, Coroutine[Any, Any, T]]
|
||||
]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def async_error_logged() -> Callable[
|
||||
[Callable[P, Coroutine[Any, Any, T]]],
|
||||
Callable[P, Coroutine[Any, Any, T | None]],
|
||||
]: ...
|
||||
|
||||
|
||||
def async_error_logged(*, swallow: bool = True) -> (
|
||||
Callable[
|
||||
[Callable[P, Coroutine[Any, Any, T]]],
|
||||
Callable[P, Coroutine[Any, Any, T | None]],
|
||||
]
|
||||
| Callable[
|
||||
[Callable[P, Coroutine[Any, Any, T]]], Callable[P, Coroutine[Any, Any, T]]
|
||||
]
|
||||
):
|
||||
"""
|
||||
Decorator to suppress and log any exceptions raised by an async function.
|
||||
Decorator to log any exceptions raised by an async function, with optional suppression.
|
||||
|
||||
Args:
|
||||
swallow: Whether to suppress the exception (True) or re-raise it (False). Default is True.
|
||||
|
||||
Usage:
|
||||
@async_error_logged() # Default behavior (swallow errors)
|
||||
@async_error_logged(swallow=False) # Log and re-raise errors
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T | None:
|
||||
try:
|
||||
return await func(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"Error when calling async function {func.__name__} with arguments {args} {kwargs}: {e}"
|
||||
)
|
||||
def decorator(
|
||||
f: Callable[P, Coroutine[Any, Any, T]]
|
||||
) -> Callable[P, Coroutine[Any, Any, T | None]]:
|
||||
@functools.wraps(f)
|
||||
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T | None:
|
||||
try:
|
||||
return await f(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
f"Error when calling async function {f.__name__} with arguments {args} {kwargs}: {e}"
|
||||
)
|
||||
if not swallow:
|
||||
raise
|
||||
return None
|
||||
|
||||
return wrapper
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import time
|
||||
|
||||
from backend.util.decorator import error_logged, time_measured
|
||||
import pytest
|
||||
|
||||
from backend.util.decorator import async_error_logged, error_logged, time_measured
|
||||
|
||||
|
||||
@time_measured
|
||||
@@ -9,18 +11,64 @@ def example_function(a: int, b: int, c: int) -> int:
|
||||
return a + b + c
|
||||
|
||||
|
||||
@error_logged
|
||||
def example_function_with_error(a: int, b: int, c: int) -> int:
|
||||
raise ValueError("This is a test error")
|
||||
@error_logged(swallow=True)
|
||||
def example_function_with_error_swallowed(a: int, b: int, c: int) -> int:
|
||||
raise ValueError("This error should be swallowed")
|
||||
|
||||
|
||||
@error_logged(swallow=False)
|
||||
def example_function_with_error_not_swallowed(a: int, b: int, c: int) -> int:
|
||||
raise ValueError("This error should NOT be swallowed")
|
||||
|
||||
|
||||
@async_error_logged(swallow=True)
|
||||
async def async_function_with_error_swallowed() -> int:
|
||||
raise ValueError("This async error should be swallowed")
|
||||
|
||||
|
||||
@async_error_logged(swallow=False)
|
||||
async def async_function_with_error_not_swallowed() -> int:
|
||||
raise ValueError("This async error should NOT be swallowed")
|
||||
|
||||
|
||||
def test_timer_decorator():
|
||||
"""Test that the time_measured decorator correctly measures execution time."""
|
||||
info, res = example_function(1, 2, 3)
|
||||
assert info.cpu_time >= 0
|
||||
assert info.wall_time >= 0.4
|
||||
assert res == 6
|
||||
|
||||
|
||||
def test_error_decorator():
|
||||
res = example_function_with_error(1, 2, 3)
|
||||
def test_error_decorator_swallow_true():
|
||||
"""Test that error_logged(swallow=True) logs and swallows errors."""
|
||||
res = example_function_with_error_swallowed(1, 2, 3)
|
||||
assert res is None
|
||||
|
||||
|
||||
def test_error_decorator_swallow_false():
|
||||
"""Test that error_logged(swallow=False) logs errors but re-raises them."""
|
||||
with pytest.raises(ValueError, match="This error should NOT be swallowed"):
|
||||
example_function_with_error_not_swallowed(1, 2, 3)
|
||||
|
||||
|
||||
def test_async_error_decorator_swallow_true():
|
||||
"""Test that async_error_logged(swallow=True) logs and swallows errors."""
|
||||
import asyncio
|
||||
|
||||
async def run_test():
|
||||
res = await async_function_with_error_swallowed()
|
||||
return res
|
||||
|
||||
res = asyncio.run(run_test())
|
||||
assert res is None
|
||||
|
||||
|
||||
def test_async_error_decorator_swallow_false():
|
||||
"""Test that async_error_logged(swallow=False) logs errors but re-raises them."""
|
||||
import asyncio
|
||||
|
||||
async def run_test():
|
||||
await async_function_with_error_not_swallowed()
|
||||
|
||||
with pytest.raises(ValueError, match="This async error should NOT be swallowed"):
|
||||
asyncio.run(run_test())
|
||||
|
||||
@@ -353,6 +353,10 @@ class Requests:
|
||||
max_redirects: int = 10,
|
||||
**kwargs,
|
||||
) -> Response:
|
||||
# Convert auth tuple to aiohttp.BasicAuth if necessary
|
||||
if "auth" in kwargs and isinstance(kwargs["auth"], tuple):
|
||||
kwargs["auth"] = aiohttp.BasicAuth(*kwargs["auth"])
|
||||
|
||||
if files is not None:
|
||||
if json is not None:
|
||||
raise ValueError(
|
||||
|
||||
@@ -51,7 +51,7 @@ class ServiceTestClient(AppServiceClient):
|
||||
subtract_async = endpoint_to_async(ServiceTest.subtract)
|
||||
|
||||
|
||||
@pytest.mark.asyncio(loop_scope="session")
|
||||
@pytest.mark.asyncio
|
||||
async def test_service_creation(server):
|
||||
with ServiceTest():
|
||||
client = get_service_client(ServiceTestClient)
|
||||
|
||||
@@ -254,6 +254,14 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
|
||||
default=True,
|
||||
description="Whether virus scanning is enabled or not",
|
||||
)
|
||||
clamav_max_concurrency: int = Field(
|
||||
default=10,
|
||||
description="The maximum number of concurrent scans to perform",
|
||||
)
|
||||
clamav_mark_failed_scans_as_clean: bool = Field(
|
||||
default=False,
|
||||
description="Whether to mark failed scans as clean or not",
|
||||
)
|
||||
|
||||
@field_validator("platform_base_url", "frontend_base_url")
|
||||
@classmethod
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import pyclamd
|
||||
import aioclamd
|
||||
from pydantic import BaseModel
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
@@ -21,37 +22,47 @@ class VirusScanResult(BaseModel):
|
||||
|
||||
|
||||
class VirusScannerSettings(BaseSettings):
|
||||
# Tunables for the scanner layer (NOT the ClamAV daemon).
|
||||
clamav_service_host: str = "localhost"
|
||||
clamav_service_port: int = 3310
|
||||
clamav_service_timeout: int = 60
|
||||
clamav_service_enabled: bool = True
|
||||
max_scan_size: int = 100 * 1024 * 1024 # 100 MB
|
||||
chunk_size: int = 25 * 1024 * 1024 # 25 MB (safe for 50MB stream limit)
|
||||
min_chunk_size: int = 128 * 1024 # 128 KB minimum
|
||||
max_retries: int = 8 # halve chunk ≤ max_retries times
|
||||
# If the service is disabled, all files are considered clean.
|
||||
mark_failed_scans_as_clean: bool = False
|
||||
# Client-side protective limits
|
||||
max_scan_size: int = 2 * 1024 * 1024 * 1024 # 2 GB guard-rail in memory
|
||||
min_chunk_size: int = 128 * 1024 # 128 KB hard floor
|
||||
max_retries: int = 8 # halve ≤ max_retries times
|
||||
# Concurrency throttle toward the ClamAV daemon. Do *NOT* simply turn this
|
||||
# up to the number of CPU cores; keep it ≤ (MaxThreads / pods) – 1.
|
||||
max_concurrency: int = 5
|
||||
|
||||
|
||||
class VirusScannerService:
|
||||
"""
|
||||
Thin async wrapper around ClamAV. Creates a fresh `ClamdNetworkSocket`
|
||||
per chunk (the class is *not* thread-safe) and falls back to smaller
|
||||
chunks when the daemon rejects the stream size.
|
||||
"""Fully-async ClamAV wrapper using **aioclamd**.
|
||||
|
||||
• Reuses a single `ClamdAsyncClient` connection (aioclamd keeps the socket open).
|
||||
• Throttles concurrent `INSTREAM` calls with an `asyncio.Semaphore` so we don't exhaust daemon worker threads or file descriptors.
|
||||
• Falls back to progressively smaller chunk sizes when the daemon rejects a stream as too large.
|
||||
"""
|
||||
|
||||
def __init__(self, settings: VirusScannerSettings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
def _new_client(self) -> pyclamd.ClamdNetworkSocket:
|
||||
return pyclamd.ClamdNetworkSocket(
|
||||
host=self.settings.clamav_service_host,
|
||||
port=self.settings.clamav_service_port,
|
||||
timeout=self.settings.clamav_service_timeout,
|
||||
self._client = aioclamd.ClamdAsyncClient(
|
||||
host=settings.clamav_service_host,
|
||||
port=settings.clamav_service_port,
|
||||
timeout=settings.clamav_service_timeout,
|
||||
)
|
||||
self._sem = asyncio.Semaphore(settings.max_concurrency)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@staticmethod
|
||||
def _parse_raw(raw: Optional[dict]) -> Tuple[bool, Optional[str]]:
|
||||
"""
|
||||
Convert pyclamd output to (infected?, threat_name).
|
||||
Convert aioclamd output to (infected?, threat_name).
|
||||
Returns (False, None) for clean.
|
||||
"""
|
||||
if not raw:
|
||||
@@ -59,24 +70,22 @@ class VirusScannerService:
|
||||
status, threat = next(iter(raw.values()))
|
||||
return status == "FOUND", threat
|
||||
|
||||
async def _scan_chunk(self, chunk: bytes) -> Tuple[bool, Optional[str]]:
|
||||
loop = asyncio.get_running_loop()
|
||||
client = self._new_client()
|
||||
try:
|
||||
raw = await loop.run_in_executor(None, client.scan_stream, chunk)
|
||||
return self._parse_raw(raw)
|
||||
|
||||
# ClamAV aborts the socket when >StreamMaxLength → BrokenPipe/Reset.
|
||||
except (BrokenPipeError, ConnectionResetError) as exc:
|
||||
raise RuntimeError("size-limit") from exc
|
||||
except Exception as exc:
|
||||
if "INSTREAM size limit exceeded" in str(exc):
|
||||
async def _instream(self, chunk: bytes) -> Tuple[bool, Optional[str]]:
|
||||
"""Scan **one** chunk with concurrency control."""
|
||||
async with self._sem:
|
||||
try:
|
||||
raw = await self._client.instream(io.BytesIO(chunk))
|
||||
return self._parse_raw(raw)
|
||||
except (BrokenPipeError, ConnectionResetError) as exc:
|
||||
raise RuntimeError("size-limit") from exc
|
||||
raise
|
||||
except Exception as exc:
|
||||
if "INSTREAM size limit exceeded" in str(exc):
|
||||
raise RuntimeError("size-limit") from exc
|
||||
raise
|
||||
|
||||
# --------------------------------------------------------------------- #
|
||||
# ------------------------------------------------------------------ #
|
||||
# Public API
|
||||
# --------------------------------------------------------------------- #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
async def scan_file(
|
||||
self, content: bytes, *, filename: str = "unknown"
|
||||
@@ -84,81 +93,74 @@ class VirusScannerService:
|
||||
"""
|
||||
Scan `content`. Returns a result object or raises on infrastructure
|
||||
failure (unreachable daemon, etc.).
|
||||
The algorithm always tries whole-file first. If the daemon refuses
|
||||
on size grounds, it falls back to chunked parallel scanning.
|
||||
"""
|
||||
if not self.settings.clamav_service_enabled:
|
||||
logger.warning("Virus scanning disabled – accepting %s", filename)
|
||||
logger.warning(f"Virus scanning disabled – accepting {filename}")
|
||||
return VirusScanResult(
|
||||
is_clean=True, scan_time_ms=0, file_size=len(content)
|
||||
)
|
||||
|
||||
if len(content) > self.settings.max_scan_size:
|
||||
logger.warning(
|
||||
f"File {filename} ({len(content)} bytes) exceeds max scan size ({self.settings.max_scan_size}), skipping virus scan"
|
||||
f"File {filename} ({len(content)} bytes) exceeds client max scan size ({self.settings.max_scan_size}); Stopping virus scan"
|
||||
)
|
||||
return VirusScanResult(
|
||||
is_clean=True, # Assume clean for oversized files
|
||||
is_clean=self.settings.mark_failed_scans_as_clean,
|
||||
file_size=len(content),
|
||||
scan_time_ms=0,
|
||||
threat_name=None,
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
if not await loop.run_in_executor(None, self._new_client().ping):
|
||||
# Ensure daemon is reachable (small RTT check)
|
||||
if not await self._client.ping():
|
||||
raise RuntimeError("ClamAV service is unreachable")
|
||||
|
||||
start = time.monotonic()
|
||||
chunk_size = self.settings.chunk_size
|
||||
|
||||
for retry in range(self.settings.max_retries + 1):
|
||||
chunk_size = len(content) # Start with full content length
|
||||
for retry in range(self.settings.max_retries):
|
||||
# For small files, don't check min_chunk_size limit
|
||||
if chunk_size < self.settings.min_chunk_size and chunk_size < len(content):
|
||||
break
|
||||
logger.debug(
|
||||
f"Scanning {filename} with chunk size: {chunk_size // 1_048_576} MB (retry {retry + 1}/{self.settings.max_retries})"
|
||||
)
|
||||
try:
|
||||
logger.debug(
|
||||
f"Scanning {filename} with chunk size: {chunk_size // 1_048_576}MB"
|
||||
)
|
||||
|
||||
# Scan all chunks with current chunk size
|
||||
for offset in range(0, len(content), chunk_size):
|
||||
chunk_data = content[offset : offset + chunk_size]
|
||||
infected, threat = await self._scan_chunk(chunk_data)
|
||||
tasks = [
|
||||
asyncio.create_task(self._instream(content[o : o + chunk_size]))
|
||||
for o in range(0, len(content), chunk_size)
|
||||
]
|
||||
for coro in asyncio.as_completed(tasks):
|
||||
infected, threat = await coro
|
||||
if infected:
|
||||
for t in tasks:
|
||||
if not t.done():
|
||||
t.cancel()
|
||||
return VirusScanResult(
|
||||
is_clean=False,
|
||||
threat_name=threat,
|
||||
file_size=len(content),
|
||||
scan_time_ms=int((time.monotonic() - start) * 1000),
|
||||
)
|
||||
|
||||
# All chunks clean
|
||||
return VirusScanResult(
|
||||
is_clean=True,
|
||||
file_size=len(content),
|
||||
scan_time_ms=int((time.monotonic() - start) * 1000),
|
||||
)
|
||||
|
||||
except RuntimeError as exc:
|
||||
if (
|
||||
str(exc) == "size-limit"
|
||||
and chunk_size > self.settings.min_chunk_size
|
||||
):
|
||||
if str(exc) == "size-limit":
|
||||
chunk_size //= 2
|
||||
logger.info(
|
||||
f"Chunk size too large for {filename}, reducing to {chunk_size // 1_048_576}MB (retry {retry + 1}/{self.settings.max_retries + 1})"
|
||||
)
|
||||
continue
|
||||
else:
|
||||
# Either not a size-limit error, or we've hit minimum chunk size
|
||||
logger.error(f"Cannot scan {filename}: {exc}")
|
||||
raise
|
||||
|
||||
# If we can't scan even with minimum chunk size, log warning and allow file
|
||||
logger.error(f"Cannot scan {filename}: {exc}")
|
||||
raise
|
||||
# Phase 3 – give up but warn
|
||||
logger.warning(
|
||||
f"Unable to virus scan {filename} ({len(content)} bytes) - chunk size limits exceeded. "
|
||||
f"Allowing file but recommend manual review."
|
||||
f"Unable to virus scan {filename} ({len(content)} bytes) even with minimum chunk size ({self.settings.min_chunk_size} bytes). Recommend manual review."
|
||||
)
|
||||
return VirusScanResult(
|
||||
is_clean=True, # Allow file when scanning impossible
|
||||
is_clean=self.settings.mark_failed_scans_as_clean,
|
||||
file_size=len(content),
|
||||
scan_time_ms=int((time.monotonic() - start) * 1000),
|
||||
threat_name=None,
|
||||
)
|
||||
|
||||
|
||||
@@ -172,6 +174,8 @@ def get_virus_scanner() -> VirusScannerService:
|
||||
clamav_service_host=settings.config.clamav_service_host,
|
||||
clamav_service_port=settings.config.clamav_service_port,
|
||||
clamav_service_enabled=settings.config.clamav_service_enabled,
|
||||
max_concurrency=settings.config.clamav_max_concurrency,
|
||||
mark_failed_scans_as_clean=settings.config.clamav_mark_failed_scans_as_clean,
|
||||
)
|
||||
_scanner = VirusScannerService(_settings)
|
||||
return _scanner
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
import pytest
|
||||
@@ -22,6 +21,7 @@ class TestVirusScannerService:
|
||||
clamav_service_port=3310,
|
||||
clamav_service_enabled=True,
|
||||
max_scan_size=10 * 1024 * 1024, # 10MB for testing
|
||||
mark_failed_scans_as_clean=False, # For testing, failed scans should be clean
|
||||
)
|
||||
|
||||
@pytest.fixture
|
||||
@@ -54,25 +54,51 @@ class TestVirusScannerService:
|
||||
# Create content larger than max_scan_size
|
||||
large_content = b"x" * (scanner.settings.max_scan_size + 1)
|
||||
|
||||
# Large files are allowed but marked as clean with a warning
|
||||
# Large files behavior depends on mark_failed_scans_as_clean setting
|
||||
result = await scanner.scan_file(large_content, filename="large_file.txt")
|
||||
assert result.is_clean is True
|
||||
assert result.is_clean == scanner.settings.mark_failed_scans_as_clean
|
||||
assert result.file_size == len(large_content)
|
||||
assert result.scan_time_ms == 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_file_too_large_both_configurations(self):
|
||||
"""Test large file handling with both mark_failed_scans_as_clean configurations"""
|
||||
large_content = b"x" * (10 * 1024 * 1024 + 1) # Larger than 10MB
|
||||
|
||||
# Test with mark_failed_scans_as_clean=True
|
||||
settings_clean = VirusScannerSettings(
|
||||
max_scan_size=10 * 1024 * 1024, mark_failed_scans_as_clean=True
|
||||
)
|
||||
scanner_clean = VirusScannerService(settings_clean)
|
||||
result_clean = await scanner_clean.scan_file(
|
||||
large_content, filename="large_file.txt"
|
||||
)
|
||||
assert result_clean.is_clean is True
|
||||
|
||||
# Test with mark_failed_scans_as_clean=False
|
||||
settings_dirty = VirusScannerSettings(
|
||||
max_scan_size=10 * 1024 * 1024, mark_failed_scans_as_clean=False
|
||||
)
|
||||
scanner_dirty = VirusScannerService(settings_dirty)
|
||||
result_dirty = await scanner_dirty.scan_file(
|
||||
large_content, filename="large_file.txt"
|
||||
)
|
||||
assert result_dirty.is_clean is False
|
||||
|
||||
# Note: ping method was removed from current implementation
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("pyclamd.ClamdNetworkSocket")
|
||||
async def test_scan_clean_file(self, mock_clamav_class, scanner):
|
||||
def mock_scan_stream(_):
|
||||
time.sleep(0.001) # Small delay to ensure timing > 0
|
||||
async def test_scan_clean_file(self, scanner):
|
||||
async def mock_instream(_):
|
||||
await asyncio.sleep(0.001) # Small delay to ensure timing > 0
|
||||
return None # No virus detected
|
||||
|
||||
mock_client = Mock()
|
||||
mock_client.ping.return_value = True
|
||||
mock_client.scan_stream = mock_scan_stream
|
||||
mock_clamav_class.return_value = mock_client
|
||||
mock_client.ping = AsyncMock(return_value=True)
|
||||
mock_client.instream = AsyncMock(side_effect=mock_instream)
|
||||
|
||||
# Replace the client instance that was created in the constructor
|
||||
scanner._client = mock_client
|
||||
|
||||
content = b"clean file content"
|
||||
result = await scanner.scan_file(content, filename="clean.txt")
|
||||
@@ -83,16 +109,17 @@ class TestVirusScannerService:
|
||||
assert result.scan_time_ms > 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("pyclamd.ClamdNetworkSocket")
|
||||
async def test_scan_infected_file(self, mock_clamav_class, scanner):
|
||||
def mock_scan_stream(_):
|
||||
time.sleep(0.001) # Small delay to ensure timing > 0
|
||||
async def test_scan_infected_file(self, scanner):
|
||||
async def mock_instream(_):
|
||||
await asyncio.sleep(0.001) # Small delay to ensure timing > 0
|
||||
return {"stream": ("FOUND", "Win.Test.EICAR_HDB-1")}
|
||||
|
||||
mock_client = Mock()
|
||||
mock_client.ping.return_value = True
|
||||
mock_client.scan_stream = mock_scan_stream
|
||||
mock_clamav_class.return_value = mock_client
|
||||
mock_client.ping = AsyncMock(return_value=True)
|
||||
mock_client.instream = AsyncMock(side_effect=mock_instream)
|
||||
|
||||
# Replace the client instance that was created in the constructor
|
||||
scanner._client = mock_client
|
||||
|
||||
content = b"infected file content"
|
||||
result = await scanner.scan_file(content, filename="infected.txt")
|
||||
@@ -103,11 +130,12 @@ class TestVirusScannerService:
|
||||
assert result.scan_time_ms > 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("pyclamd.ClamdNetworkSocket")
|
||||
async def test_scan_clamav_unavailable_fail_safe(self, mock_clamav_class, scanner):
|
||||
async def test_scan_clamav_unavailable_fail_safe(self, scanner):
|
||||
mock_client = Mock()
|
||||
mock_client.ping.return_value = False
|
||||
mock_clamav_class.return_value = mock_client
|
||||
mock_client.ping = AsyncMock(return_value=False)
|
||||
|
||||
# Replace the client instance that was created in the constructor
|
||||
scanner._client = mock_client
|
||||
|
||||
content = b"test content"
|
||||
|
||||
@@ -115,12 +143,13 @@ class TestVirusScannerService:
|
||||
await scanner.scan_file(content, filename="test.txt")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("pyclamd.ClamdNetworkSocket")
|
||||
async def test_scan_error_fail_safe(self, mock_clamav_class, scanner):
|
||||
async def test_scan_error_fail_safe(self, scanner):
|
||||
mock_client = Mock()
|
||||
mock_client.ping.return_value = True
|
||||
mock_client.scan_stream.side_effect = Exception("Scanning error")
|
||||
mock_clamav_class.return_value = mock_client
|
||||
mock_client.ping = AsyncMock(return_value=True)
|
||||
mock_client.instream = AsyncMock(side_effect=Exception("Scanning error"))
|
||||
|
||||
# Replace the client instance that was created in the constructor
|
||||
scanner._client = mock_client
|
||||
|
||||
content = b"test content"
|
||||
|
||||
@@ -150,16 +179,17 @@ class TestVirusScannerService:
|
||||
assert result.file_size == 1024
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch("pyclamd.ClamdNetworkSocket")
|
||||
async def test_concurrent_scans(self, mock_clamav_class, scanner):
|
||||
def mock_scan_stream(_):
|
||||
time.sleep(0.001) # Small delay to ensure timing > 0
|
||||
async def test_concurrent_scans(self, scanner):
|
||||
async def mock_instream(_):
|
||||
await asyncio.sleep(0.001) # Small delay to ensure timing > 0
|
||||
return None
|
||||
|
||||
mock_client = Mock()
|
||||
mock_client.ping.return_value = True
|
||||
mock_client.scan_stream = mock_scan_stream
|
||||
mock_clamav_class.return_value = mock_client
|
||||
mock_client.ping = AsyncMock(return_value=True)
|
||||
mock_client.instream = AsyncMock(side_effect=mock_instream)
|
||||
|
||||
# Replace the client instance that was created in the constructor
|
||||
scanner._client = mock_client
|
||||
|
||||
content1 = b"file1 content"
|
||||
content2 = b"file2 content"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "AgentNodeExecutionKeyValueData" (
|
||||
"userId" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"agentNodeExecutionId" TEXT NOT NULL,
|
||||
"data" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "AgentNodeExecutionKeyValueData_pkey" PRIMARY KEY ("userId","key")
|
||||
);
|
||||
46
autogpt_platform/backend/poetry.lock
generated
46
autogpt_platform/backend/poetry.lock
generated
@@ -17,6 +17,18 @@ aiormq = ">=6.8,<6.9"
|
||||
exceptiongroup = ">=1,<2"
|
||||
yarl = "*"
|
||||
|
||||
[[package]]
|
||||
name = "aioclamd"
|
||||
version = "1.0.0"
|
||||
description = "Asynchronous client for virus scanning with ClamAV"
|
||||
optional = false
|
||||
python-versions = ">=3.7,<4.0"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "aioclamd-1.0.0-py3-none-any.whl", hash = "sha256:4727da3953a4b38be4c2de1acb6b3bb3c94c1c171dcac780b80234ee6253f3d9"},
|
||||
{file = "aioclamd-1.0.0.tar.gz", hash = "sha256:7b14e94e3a2285cc89e2f4d434e2a01f322d3cb95476ce2dda015a7980876047"},
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aiodns"
|
||||
version = "3.4.0"
|
||||
@@ -3856,17 +3868,6 @@ cffi = ">=1.5.0"
|
||||
[package.extras]
|
||||
idna = ["idna (>=2.1)"]
|
||||
|
||||
[[package]]
|
||||
name = "pyclamd"
|
||||
version = "0.4.0"
|
||||
description = "pyClamd is a python interface to Clamd (Clamav daemon)."
|
||||
optional = false
|
||||
python-versions = "*"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "pyClamd-0.4.0.tar.gz", hash = "sha256:ddd588577e5db123760b6ddaac46b5c4b1d9044a00b5d9422de59f83a55c20fe"},
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pycodestyle"
|
||||
version = "2.13.0"
|
||||
@@ -5017,6 +5018,27 @@ statsig = ["statsig (>=0.55.3)"]
|
||||
tornado = ["tornado (>=6)"]
|
||||
unleash = ["UnleashClient (>=6.0.1)"]
|
||||
|
||||
[[package]]
|
||||
name = "setuptools"
|
||||
version = "80.9.0"
|
||||
description = "Easily download, build, install, upgrade, and uninstall Python packages"
|
||||
optional = false
|
||||
python-versions = ">=3.9"
|
||||
groups = ["main"]
|
||||
files = [
|
||||
{file = "setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922"},
|
||||
{file = "setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c"},
|
||||
]
|
||||
|
||||
[package.extras]
|
||||
check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1) ; sys_platform != \"cygwin\"", "ruff (>=0.8.0) ; sys_platform != \"cygwin\""]
|
||||
core = ["importlib_metadata (>=6) ; python_version < \"3.10\"", "jaraco.functools (>=4)", "jaraco.text (>=3.7)", "more_itertools", "more_itertools (>=8.8)", "packaging (>=24.2)", "platformdirs (>=4.2.2)", "tomli (>=2.0.1) ; python_version < \"3.11\"", "wheel (>=0.43.0)"]
|
||||
cover = ["pytest-cov"]
|
||||
doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "pyproject-hooks (!=1.1)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier", "towncrier (<24.7)"]
|
||||
enabler = ["pytest-enabler (>=2.2)"]
|
||||
test = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "ini2toml[lite] (>=0.14)", "jaraco.develop (>=7.21) ; python_version >= \"3.9\" and sys_platform != \"cygwin\"", "jaraco.envs (>=2.2)", "jaraco.path (>=3.7.2)", "jaraco.test (>=5.5)", "packaging (>=24.2)", "pip (>=19.1)", "pyproject-hooks (!=1.1)", "pytest (>=6,!=8.1.*)", "pytest-home (>=0.5)", "pytest-perf ; sys_platform != \"cygwin\"", "pytest-subprocess", "pytest-timeout", "pytest-xdist (>=3)", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel (>=0.44.0)"]
|
||||
type = ["importlib_metadata (>=7.0.2) ; python_version < \"3.10\"", "jaraco.develop (>=7.21) ; sys_platform != \"cygwin\"", "mypy (==1.14.*)", "pytest-mypy"]
|
||||
|
||||
[[package]]
|
||||
name = "sgmllib3k"
|
||||
version = "1.0.0"
|
||||
@@ -6380,4 +6402,4 @@ cffi = ["cffi (>=1.11)"]
|
||||
[metadata]
|
||||
lock-version = "2.1"
|
||||
python-versions = ">=3.10,<3.13"
|
||||
content-hash = "bd117a21d817a2a735ed923c383713dd08469938ef5f7d07c4222da1acca2b5c"
|
||||
content-hash = "b5c1201f27ee8d05d5d8c89702123df4293f124301d1aef7451591a351872260"
|
||||
|
||||
@@ -68,8 +68,9 @@ zerobouncesdk = "^1.1.1"
|
||||
# NOTE: please insert new dependencies in their alphabetical location
|
||||
pytest-snapshot = "^0.9.0"
|
||||
aiofiles = "^24.1.0"
|
||||
pyclamd = "^0.4.0"
|
||||
tiktoken = "^0.9.0"
|
||||
aioclamd = "^1.0.0"
|
||||
setuptools = "^80.9.0"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
aiohappyeyeballs = "^2.6.1"
|
||||
|
||||
@@ -413,6 +413,16 @@ model AgentNodeExecutionInputOutput {
|
||||
@@index([name, time])
|
||||
}
|
||||
|
||||
model AgentNodeExecutionKeyValueData {
|
||||
userId String
|
||||
key String
|
||||
agentNodeExecutionId String
|
||||
data Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime? @updatedAt
|
||||
@@id([userId, key])
|
||||
}
|
||||
|
||||
// Webhook that is registered with a provider and propagates to one or more nodes
|
||||
model IntegrationWebhook {
|
||||
id String @id @default(uuid())
|
||||
@@ -432,8 +442,8 @@ model IntegrationWebhook {
|
||||
|
||||
providerWebhookId String // Webhook ID assigned by the provider
|
||||
|
||||
AgentNodes AgentNode[]
|
||||
AgentPresets AgentPreset[]
|
||||
AgentNodes AgentNode[]
|
||||
AgentPresets AgentPreset[]
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ services:
|
||||
- SCHEDULER_HOST=scheduler_server
|
||||
- EXECUTIONMANAGER_HOST=executor
|
||||
- NOTIFICATIONMANAGER_HOST=rest_server
|
||||
- FRONTEND_BASE_URL=http://localhost:3000
|
||||
- NEXT_PUBLIC_FRONTEND_BASE_URL=http://localhost:3000
|
||||
- BACKEND_CORS_ALLOW_ORIGINS=["http://localhost:3000"]
|
||||
- ENCRYPTION_KEY=dvziYgz0KSK8FENhju0ZYi8-fRTfAdlz6YLhdB_jhNw= # DO NOT USE IN PRODUCTION!!
|
||||
- UNSUBSCRIBE_SECRET_KEY=HlP8ivStJjmbf6NKi78m_3FnOogut0t5ckzjsIqeaio= # DO NOT USE IN PRODUCTION!!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FRONTEND_BASE_URL=http://localhost:3000
|
||||
NEXT_PUBLIC_FRONTEND_BASE_URL=http://localhost:3000
|
||||
|
||||
NEXT_PUBLIC_AUTH_CALLBACK_URL=http://localhost:8006/auth/callback
|
||||
NEXT_PUBLIC_AGPT_SERVER_URL=http://localhost:8006/api
|
||||
@@ -23,7 +23,7 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAic
|
||||
## OAuth Callback URL
|
||||
## This should be {domain}/auth/callback
|
||||
## Only used if you're using Supabase and OAuth
|
||||
AUTH_CALLBACK_URL="${FRONTEND_BASE_URL}/auth/callback"
|
||||
AUTH_CALLBACK_URL="${NEXT_PUBLIC_FRONTEND_BASE_URL}/auth/callback"
|
||||
GA_MEASUREMENT_ID=G-FH2XK2W4GN
|
||||
|
||||
# When running locally, set NEXT_PUBLIC_BEHAVE_AS=CLOUD to use the a locally hosted marketplace (as is typical in development, and the cloud deployment), otherwise set it to LOCAL to have the marketplace open in a new tab
|
||||
|
||||
@@ -63,9 +63,150 @@ Every time a new Front-end dependency is added by you or others, you will need t
|
||||
- `pnpm type-check` - Run TypeScript type checking
|
||||
- `pnpm test` - Run Playwright tests
|
||||
- `pnpm test-ui` - Run Playwright tests with UI
|
||||
- `pnpm fetch:openapi` - Fetch OpenAPI spec from backend
|
||||
- `pnpm generate:api-client` - Generate API client from OpenAPI spec
|
||||
- `pnpm generate:api-all` - Fetch OpenAPI spec and generate API client
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
|
||||
|
||||
## 🔄 Data Fetching Strategy
|
||||
|
||||
> [!NOTE]
|
||||
> You don't need to run the OpenAPI commands below to run the Front-end. You will only need to run them when adding or modifying endpoints on the Backend API and wanting to use those on the Frontend.
|
||||
|
||||
This project uses an auto-generated API client powered by [**Orval**](https://orval.dev/), which creates type-safe API clients from OpenAPI specifications.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Backend Requirements**: Each API endpoint needs a summary and tag in the OpenAPI spec
|
||||
2. **Operation ID Generation**: FastAPI generates operation IDs using the pattern `{method}{tag}{summary}`
|
||||
3. **Spec Fetching**: The OpenAPI spec is fetched from `http://localhost:8006/openapi.json` and saved to the frontend
|
||||
4. **Spec Transformation**: The OpenAPI spec is cleaned up using a custom transformer (see `autogpt_platform/frontend/src/app/api/transformers`)
|
||||
5. **Client Generation**: Auto-generated client includes TypeScript types, API endpoints, and Zod schemas, organized by tags
|
||||
|
||||
### API Client Commands
|
||||
|
||||
```bash
|
||||
# Fetch OpenAPI spec from backend and generate client
|
||||
pnpm generate:api-all
|
||||
|
||||
# Only fetch the OpenAPI spec
|
||||
pnpm fetch:openapi
|
||||
|
||||
# Only generate the client (after spec is fetched)
|
||||
pnpm generate:api-client
|
||||
```
|
||||
|
||||
### Using the Generated Client
|
||||
|
||||
The generated client provides React Query hooks for both queries and mutations:
|
||||
|
||||
#### Queries (GET requests)
|
||||
|
||||
```typescript
|
||||
import { useGetV1GetNotificationPreferences } from "@/app/api/__generated__/endpoints/auth/auth";
|
||||
|
||||
const { data, isLoading, isError } = useGetV1GetNotificationPreferences({
|
||||
query: {
|
||||
select: (res) => res.data,
|
||||
// Other React Query options
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
#### Mutations (POST, PUT, DELETE requests)
|
||||
|
||||
```typescript
|
||||
import { useDeleteV2DeleteStoreSubmission } from "@/app/api/__generated__/endpoints/store/store";
|
||||
import { getGetV2ListMySubmissionsQueryKey } from "@/app/api/__generated__/endpoints/store/store";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutateAsync: deleteSubmission } = useDeleteV2DeleteStoreSubmission({
|
||||
mutation: {
|
||||
onSuccess: () => {
|
||||
// Invalidate related queries to refresh data
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: getGetV2ListMySubmissionsQueryKey(),
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Usage
|
||||
await deleteSubmission({
|
||||
submissionId: submission_id,
|
||||
});
|
||||
```
|
||||
|
||||
#### Server Actions
|
||||
|
||||
For server-side operations, you can also use the generated client functions directly:
|
||||
|
||||
```typescript
|
||||
import { postV1UpdateNotificationPreferences } from "@/app/api/__generated__/endpoints/auth/auth";
|
||||
|
||||
// In a server action
|
||||
const preferences = {
|
||||
email: "user@example.com",
|
||||
preferences: {
|
||||
AGENT_RUN: true,
|
||||
ZERO_BALANCE: false,
|
||||
// ... other preferences
|
||||
},
|
||||
daily_limit: 0,
|
||||
};
|
||||
|
||||
await postV1UpdateNotificationPreferences(preferences);
|
||||
```
|
||||
|
||||
#### Server-Side Prefetching
|
||||
|
||||
For server-side components, you can prefetch data on the server and hydrate it in the client cache. This allows immediate access to cached data when queries are called:
|
||||
|
||||
```typescript
|
||||
import { getQueryClient } from "@/lib/tanstack-query/getQueryClient";
|
||||
import {
|
||||
prefetchGetV2ListStoreAgentsQuery,
|
||||
prefetchGetV2ListStoreCreatorsQuery
|
||||
} from "@/app/api/__generated__/endpoints/store/store";
|
||||
import { HydrationBoundary, dehydrate } from "@tanstack/react-query";
|
||||
|
||||
// In your server component
|
||||
const queryClient = getQueryClient();
|
||||
|
||||
await Promise.all([
|
||||
prefetchGetV2ListStoreAgentsQuery(queryClient, {
|
||||
featured: true,
|
||||
}),
|
||||
prefetchGetV2ListStoreAgentsQuery(queryClient, {
|
||||
sorted_by: "runs",
|
||||
}),
|
||||
prefetchGetV2ListStoreCreatorsQuery(queryClient, {
|
||||
featured: true,
|
||||
sorted_by: "num_agents",
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
<HydrationBoundary state={dehydrate(queryClient)}>
|
||||
<MainMarkeplacePage />
|
||||
</HydrationBoundary>
|
||||
);
|
||||
```
|
||||
|
||||
This pattern improves performance by serving pre-fetched data from the server while maintaining the benefits of client-side React Query features.
|
||||
|
||||
### Configuration
|
||||
|
||||
The Orval configuration is located in `autogpt_platform/frontend/orval.config.ts`. It generates two separate clients:
|
||||
|
||||
1. **autogpt_api_client**: React Query hooks for client-side data fetching
|
||||
2. **autogpt_zod_schema**: Zod schemas for validation
|
||||
|
||||
For more details, see the [Orval documentation](https://orval.dev/) or check the configuration file.
|
||||
|
||||
## 🚚 Deploy
|
||||
|
||||
TODO
|
||||
|
||||
@@ -3,24 +3,19 @@ import { defineConfig } from "orval";
|
||||
export default defineConfig({
|
||||
autogpt_api_client: {
|
||||
input: {
|
||||
target: `./src/api/openapi.json`,
|
||||
target: `./src/app/api/openapi.json`,
|
||||
override: {
|
||||
transformer: "./src/api/transformers/fix-tags.mjs",
|
||||
transformer: "./src/app/api/transformers/fix-tags.mjs",
|
||||
},
|
||||
},
|
||||
output: {
|
||||
workspace: "./src/api",
|
||||
workspace: "./src/app/api",
|
||||
target: `./__generated__/endpoints`,
|
||||
schemas: "./__generated__/models",
|
||||
mode: "tags-split",
|
||||
client: "react-query",
|
||||
httpClient: "fetch",
|
||||
indexFiles: false,
|
||||
mock: {
|
||||
type: "msw",
|
||||
delay: 1000, // artifical latency
|
||||
generateEachHttpStatus: true, // helps us test error-handling scenarios and generate mocks for all HTTP statuses
|
||||
},
|
||||
override: {
|
||||
mutator: {
|
||||
path: "./mutators/custom-mutator.ts",
|
||||
@@ -31,29 +26,37 @@ export default defineConfig({
|
||||
useMutation: true,
|
||||
// Will add more as their use cases arise
|
||||
},
|
||||
operations: {
|
||||
"getV2List library agents": {
|
||||
query: {
|
||||
useInfinite: true,
|
||||
useInfiniteQueryParam: "page",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
hooks: {
|
||||
afterAllFilesWrite: "prettier --write",
|
||||
},
|
||||
},
|
||||
autogpt_zod_schema: {
|
||||
input: {
|
||||
target: `./src/api/openapi.json`,
|
||||
override: {
|
||||
transformer: "./src/api/transformers/fix-tags.mjs",
|
||||
},
|
||||
},
|
||||
output: {
|
||||
workspace: "./src/api",
|
||||
target: `./__generated__/zod-schema`,
|
||||
schemas: "./__generated__/models",
|
||||
mode: "tags-split",
|
||||
client: "zod",
|
||||
indexFiles: false,
|
||||
},
|
||||
hooks: {
|
||||
afterAllFilesWrite: "prettier --write",
|
||||
},
|
||||
},
|
||||
// autogpt_zod_schema: {
|
||||
// input: {
|
||||
// target: `./src/app/api/openapi.json`,
|
||||
// override: {
|
||||
// transformer: "./src/app/api/transformers/fix-tags.mjs",
|
||||
// },
|
||||
// },
|
||||
// output: {
|
||||
// workspace: "./src/app/api",
|
||||
// target: `./__generated__/zod-schema`,
|
||||
// schemas: "./__generated__/models",
|
||||
// mode: "tags-split",
|
||||
// client: "zod",
|
||||
// indexFiles: false,
|
||||
// },
|
||||
// hooks: {
|
||||
// afterAllFilesWrite: "prettier --write",
|
||||
// },
|
||||
// },
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbo",
|
||||
"build": "pnpm run generate:api-client && SKIP_STORYBOOK_TESTS=true next build",
|
||||
"build": "cross-env pnpm run generate:api-client && SKIP_STORYBOOK_TESTS=true next build",
|
||||
"start": "next start",
|
||||
"start:standalone": "cd .next/standalone && node server.js",
|
||||
"lint": "next lint && prettier --check .",
|
||||
@@ -17,7 +17,8 @@
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build",
|
||||
"test-storybook": "test-storybook",
|
||||
"fetch:openapi": "curl http://localhost:8006/openapi.json > ./src/api/openapi.json && prettier --write ./src/api/openapi.json",
|
||||
"test-storybook:ci": "concurrently -k -s first -n \"SB,TEST\" -c \"magenta,blue\" \"pnpm run build-storybook -- --quiet && npx http-server storybook-static --port 6006 --silent\" \"wait-on tcp:6006 && pnpm run test-storybook\"",
|
||||
"fetch:openapi": "curl http://localhost:8006/openapi.json > ./src/app/api/openapi.json && prettier --write ./src/app/api/openapi.json",
|
||||
"generate:api-client": "orval --config ./orval.config.ts",
|
||||
"generate:api-all": "pnpm run fetch:openapi && pnpm run generate:api-client"
|
||||
},
|
||||
@@ -95,13 +96,13 @@
|
||||
"devDependencies": {
|
||||
"@chromatic-com/storybook": "4.0.1",
|
||||
"@playwright/test": "1.53.1",
|
||||
"@storybook/addon-a11y": "9.0.13",
|
||||
"@storybook/addon-docs": "9.0.13",
|
||||
"@storybook/addon-links": "9.0.13",
|
||||
"@storybook/addon-onboarding": "9.0.13",
|
||||
"@storybook/nextjs": "9.0.13",
|
||||
"@storybook/addon-a11y": "9.0.14",
|
||||
"@storybook/addon-docs": "9.0.14",
|
||||
"@storybook/addon-links": "9.0.14",
|
||||
"@storybook/addon-onboarding": "9.0.14",
|
||||
"@storybook/nextjs": "9.0.14",
|
||||
"@tanstack/eslint-plugin-query": "5.81.2",
|
||||
"@tanstack/react-query-devtools": "5.81.2",
|
||||
"@tanstack/react-query-devtools": "5.81.5",
|
||||
"@types/canvas-confetti": "1.9.0",
|
||||
"@types/lodash": "4.17.19",
|
||||
"@types/negotiator": "0.6.4",
|
||||
@@ -112,18 +113,19 @@
|
||||
"axe-playwright": "2.1.0",
|
||||
"chromatic": "11.25.2",
|
||||
"concurrently": "9.2.0",
|
||||
"cross-env": "7.0.3",
|
||||
"eslint": "8.57.1",
|
||||
"eslint-config-next": "15.3.4",
|
||||
"eslint-plugin-storybook": "9.0.13",
|
||||
"eslint-plugin-storybook": "9.0.14",
|
||||
"import-in-the-middle": "1.14.2",
|
||||
"msw": "2.10.2",
|
||||
"msw-storybook-addon": "2.0.5",
|
||||
"orval": "7.10.0",
|
||||
"postcss": "8.5.6",
|
||||
"prettier": "3.6.1",
|
||||
"prettier": "3.6.2",
|
||||
"prettier-plugin-tailwindcss": "0.6.13",
|
||||
"require-in-the-middle": "7.5.2",
|
||||
"storybook": "9.0.13",
|
||||
"storybook": "9.0.14",
|
||||
"tailwindcss": "3.4.17",
|
||||
"typescript": "5.8.3"
|
||||
},
|
||||
|
||||
1229
autogpt_platform/frontend/pnpm-lock.yaml
generated
1229
autogpt_platform/frontend/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -14,11 +14,13 @@ export default function BuilderPage() {
|
||||
completeStep("BUILDER_OPEN");
|
||||
}, [completeStep]);
|
||||
|
||||
const _graphVersion = query.get("flowVersion");
|
||||
const graphVersion = _graphVersion ? parseInt(_graphVersion) : undefined
|
||||
return (
|
||||
<FlowEditor
|
||||
className="flow-container"
|
||||
flowID={query.get("flowID") as GraphID | null ?? undefined}
|
||||
flowVersion={query.get("flowVersion") ?? undefined}
|
||||
flowVersion={graphVersion}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// import LibraryNotificationDropdown from "./library-notification-dropdown";
|
||||
import LibraryUploadAgentDialog from "./library-upload-agent-dialog";
|
||||
import LibrarySearchBar from "./library-search-bar";
|
||||
import LibraryUploadAgentDialog from "../LibraryUploadAgentDialog/LibraryUploadAgentDialog";
|
||||
import LibrarySearchBar from "../LibrarySearchBar/LibrarySearchBar";
|
||||
|
||||
type LibraryActionHeaderProps = Record<string, never>;
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
|
||||
import LibrarySortMenu from "./library-sort-menu";
|
||||
import LibrarySortMenu from "../LibrarySortMenu/LibrarySortMenu";
|
||||
|
||||
export default function LibraryActionSubHeader(): React.ReactNode {
|
||||
const { agents } = useLibraryPageContext();
|
||||
interface LibraryActionSubHeaderProps {
|
||||
agentCount: number;
|
||||
}
|
||||
|
||||
export default function LibraryActionSubHeader({
|
||||
agentCount,
|
||||
}: LibraryActionSubHeaderProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between pb-[10px]">
|
||||
<div className="flex items-center gap-[10px] p-2">
|
||||
@@ -13,7 +16,7 @@ export default function LibraryActionSubHeader(): React.ReactNode {
|
||||
My agents
|
||||
</span>
|
||||
<span className="w-[70px] font-sans text-[14px] font-normal leading-6">
|
||||
{agents.length} agents
|
||||
{agentCount} agents
|
||||
</span>
|
||||
</div>
|
||||
<LibrarySortMenu />
|
||||
@@ -1,7 +1,12 @@
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { LibraryAgent } from "@/lib/autogpt-server-api";
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
|
||||
interface LibraryAgentCardProps {
|
||||
agent: LibraryAgent;
|
||||
}
|
||||
|
||||
export default function LibraryAgentCard({
|
||||
agent: {
|
||||
@@ -13,9 +18,7 @@ export default function LibraryAgentCard({
|
||||
creator_image_url,
|
||||
image_url,
|
||||
},
|
||||
}: {
|
||||
agent: LibraryAgent;
|
||||
}): React.ReactNode {
|
||||
}: LibraryAgentCardProps) {
|
||||
return (
|
||||
<div className="inline-flex w-full max-w-[434px] flex-col items-start justify-start gap-2.5 rounded-[26px] bg-white transition-all duration-300 hover:shadow-lg dark:bg-transparent dark:hover:shadow-gray-700">
|
||||
<Link
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
import LibraryActionSubHeader from "../LibraryActionSubHeader/LibraryActionSubHeader";
|
||||
import LibraryAgentCard from "../LibraryAgentCard/LibraryAgentCard";
|
||||
import { useLibraryAgentList } from "./useLibraryAgentList";
|
||||
|
||||
export default function LibraryAgentList() {
|
||||
const {
|
||||
agentLoading,
|
||||
allAgents: agents,
|
||||
isFetchingNextPage,
|
||||
isSearching,
|
||||
} = useLibraryAgentList();
|
||||
|
||||
const LoadingSpinner = () => (
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-t-2 border-neutral-800" />
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* TODO: We need a new endpoint on backend that returns total number of agents */}
|
||||
<LibraryActionSubHeader agentCount={agents.length} />
|
||||
<div className="px-2">
|
||||
{agentLoading ? (
|
||||
<div className="flex h-[200px] items-center justify-center">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{agents.map((agent) => (
|
||||
<LibraryAgentCard key={agent.id} agent={agent} />
|
||||
))}
|
||||
</div>
|
||||
{(isFetchingNextPage || isSearching) && (
|
||||
<div className="flex items-center justify-center py-4 pt-8">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useGetV2ListLibraryAgentsInfinite } from "@/app/api/__generated__/endpoints/library/library";
|
||||
import { LibraryAgentResponse } from "@/app/api/__generated__/models/libraryAgentResponse";
|
||||
import { useScrollThreshold } from "@/hooks/useScrollThreshold";
|
||||
import { useCallback } from "react";
|
||||
import { useLibraryPageContext } from "../state-provider";
|
||||
|
||||
export const useLibraryAgentList = () => {
|
||||
const { searchTerm, librarySort } = useLibraryPageContext();
|
||||
const {
|
||||
data: agents,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isLoading: agentLoading,
|
||||
isFetching,
|
||||
} = useGetV2ListLibraryAgentsInfinite(
|
||||
{
|
||||
page: 1,
|
||||
page_size: 8,
|
||||
search_term: searchTerm || undefined,
|
||||
sort_by: librarySort,
|
||||
},
|
||||
{
|
||||
query: {
|
||||
getNextPageParam: (lastPage) => {
|
||||
const pagination = (lastPage.data as LibraryAgentResponse).pagination;
|
||||
const isMore =
|
||||
pagination.current_page * pagination.page_size <
|
||||
pagination.total_items;
|
||||
|
||||
return isMore ? pagination.current_page + 1 : undefined;
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handleInfiniteScroll = useCallback(
|
||||
(scrollY: number) => {
|
||||
if (!hasNextPage || isFetchingNextPage) return;
|
||||
|
||||
const { scrollHeight, clientHeight } = document.documentElement;
|
||||
const SCROLL_THRESHOLD = 20;
|
||||
|
||||
if (scrollY + clientHeight >= scrollHeight - SCROLL_THRESHOLD) {
|
||||
fetchNextPage();
|
||||
}
|
||||
},
|
||||
[hasNextPage, isFetchingNextPage, fetchNextPage],
|
||||
);
|
||||
|
||||
useScrollThreshold(handleInfiniteScroll, 50);
|
||||
|
||||
const allAgents =
|
||||
agents?.pages.flatMap((page) => {
|
||||
const data = page.data as LibraryAgentResponse;
|
||||
return data.agents;
|
||||
}) ?? [];
|
||||
|
||||
return {
|
||||
allAgents,
|
||||
agentLoading,
|
||||
isFetchingNextPage,
|
||||
hasNextPage,
|
||||
isSearching: isFetching && !isFetchingNextPage,
|
||||
};
|
||||
};
|
||||
@@ -11,9 +11,9 @@ import {
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import LibraryNotificationCard, {
|
||||
import NotificationCard, {
|
||||
NotificationCardData,
|
||||
} from "./library-notification-card";
|
||||
} from "../LibraryNotificationCard/LibraryNotificationCard";
|
||||
|
||||
export default function LibraryNotificationDropdown(): React.ReactNode {
|
||||
const controls = useAnimationControls();
|
||||
@@ -109,7 +109,7 @@ export default function LibraryNotificationDropdown(): React.ReactNode {
|
||||
{notifications && notifications.length ? (
|
||||
notifications.map((notification) => (
|
||||
<DropdownMenuItem key={notification.id} className="p-0">
|
||||
<LibraryNotificationCard
|
||||
<NotificationCard
|
||||
notification={notification}
|
||||
onClose={() =>
|
||||
setNotifications((prev) => {
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Search, X } from "lucide-react";
|
||||
import { useLibrarySearchbar } from "./useLibrarySearchbar";
|
||||
|
||||
export default function LibrarySearchBar(): React.ReactNode {
|
||||
const { handleSearchInput, handleClear, setIsFocused, isFocused, inputRef } =
|
||||
useLibrarySearchbar();
|
||||
return (
|
||||
<div
|
||||
onClick={() => inputRef.current?.focus()}
|
||||
className="relative z-[21] mx-auto flex h-[50px] w-full max-w-[500px] flex-1 cursor-pointer items-center rounded-[45px] bg-[#EDEDED] px-[24px] py-[10px]"
|
||||
>
|
||||
<Search
|
||||
className="mr-2 h-[29px] w-[29px] text-neutral-900"
|
||||
strokeWidth={1.25}
|
||||
/>
|
||||
|
||||
<Input
|
||||
ref={inputRef}
|
||||
onFocus={() => setIsFocused(true)}
|
||||
onBlur={() => !inputRef.current?.value && setIsFocused(false)}
|
||||
onChange={handleSearchInput}
|
||||
className="flex-1 border-none font-sans text-[16px] font-normal leading-7 shadow-none focus:shadow-none focus:ring-0"
|
||||
type="text"
|
||||
placeholder="Search agents"
|
||||
/>
|
||||
|
||||
{isFocused && inputRef.current?.value && (
|
||||
<X
|
||||
className="ml-2 h-[29px] w-[29px] cursor-pointer text-neutral-900"
|
||||
strokeWidth={1.25}
|
||||
onClick={handleClear}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useLibraryPageContext } from "../state-provider";
|
||||
import { debounce } from "lodash";
|
||||
|
||||
export const useLibrarySearchbar = () => {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const { setSearchTerm } = useLibraryPageContext();
|
||||
|
||||
const debouncedSearch = debounce((value: string) => {
|
||||
setSearchTerm(value);
|
||||
}, 300);
|
||||
|
||||
const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const searchTerm = e.target.value;
|
||||
debouncedSearch(searchTerm);
|
||||
};
|
||||
|
||||
const handleClear = (e: React.MouseEvent) => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.value = "";
|
||||
inputRef.current.blur();
|
||||
setSearchTerm("");
|
||||
e.preventDefault();
|
||||
}
|
||||
setIsFocused(false);
|
||||
};
|
||||
|
||||
return {
|
||||
handleClear,
|
||||
handleSearchInput,
|
||||
isFocused,
|
||||
inputRef,
|
||||
setIsFocused,
|
||||
};
|
||||
};
|
||||
@@ -1,6 +1,4 @@
|
||||
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
|
||||
import { LibraryAgentSortEnum } from "@/lib/autogpt-server-api/types";
|
||||
import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
|
||||
"use client";
|
||||
import { ArrowDownNarrowWideIcon } from "lucide-react";
|
||||
import {
|
||||
Select,
|
||||
@@ -10,24 +8,11 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
|
||||
import { useLibrarySortMenu } from "./useLibrarySortMenu";
|
||||
|
||||
export default function LibrarySortMenu(): React.ReactNode {
|
||||
const api = useBackendAPI();
|
||||
const { setAgentLoading, setAgents, setLibrarySort, searchTerm } =
|
||||
useLibraryPageContext();
|
||||
const handleSortChange = async (value: LibraryAgentSortEnum) => {
|
||||
setLibrarySort(value);
|
||||
setAgentLoading(true);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
const response = await api.listLibraryAgents({
|
||||
search_term: searchTerm,
|
||||
sort_by: value,
|
||||
page: 1,
|
||||
});
|
||||
setAgents(response.agents);
|
||||
setAgentLoading(false);
|
||||
};
|
||||
|
||||
const { handleSortChange } = useLibrarySortMenu();
|
||||
return (
|
||||
<div className="flex items-center">
|
||||
<span className="hidden whitespace-nowrap sm:inline">sort by</span>
|
||||
@@ -38,10 +23,10 @@ export default function LibrarySortMenu(): React.ReactNode {
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value={LibraryAgentSortEnum.CREATED_AT}>
|
||||
<SelectItem value={LibraryAgentSort.createdAt}>
|
||||
Creation Date
|
||||
</SelectItem>
|
||||
<SelectItem value={LibraryAgentSortEnum.UPDATED_AT}>
|
||||
<SelectItem value={LibraryAgentSort.updatedAt}>
|
||||
Last Modified
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
@@ -0,0 +1,27 @@
|
||||
import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
|
||||
import { useLibraryPageContext } from "../state-provider";
|
||||
|
||||
export const useLibrarySortMenu = () => {
|
||||
const { setLibrarySort } = useLibraryPageContext();
|
||||
|
||||
const handleSortChange = (value: LibraryAgentSort) => {
|
||||
// Simply updating the sort state - React Query will handle the rest
|
||||
setLibrarySort(value);
|
||||
};
|
||||
|
||||
const getSortLabel = (sort: LibraryAgentSort) => {
|
||||
switch (sort) {
|
||||
case LibraryAgentSort.createdAt:
|
||||
return "Creation Date";
|
||||
case LibraryAgentSort.updatedAt:
|
||||
return "Last Modified";
|
||||
default:
|
||||
return "Last Modified";
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
handleSortChange,
|
||||
getSortLabel,
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { Upload, X } from "lucide-react";
|
||||
import { Button } from "@/components/agptui/Button";
|
||||
import {
|
||||
@@ -10,8 +9,6 @@ import {
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FileUploader } from "react-drag-drop-files";
|
||||
import {
|
||||
Form,
|
||||
@@ -23,13 +20,7 @@ import {
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Graph,
|
||||
GraphCreatable,
|
||||
sanitizeImportedGraph,
|
||||
} from "@/lib/autogpt-server-api";
|
||||
import { useBackendAPI } from "@/lib/autogpt-server-api/context";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { useLibraryUploadAgentDialog } from "./useLibraryUploadAgentDialog";
|
||||
|
||||
const fileTypes = ["JSON"];
|
||||
|
||||
@@ -37,98 +28,24 @@ const fileSchema = z.custom<File>((val) => val instanceof File, {
|
||||
message: "Must be a File object",
|
||||
});
|
||||
|
||||
const formSchema = z.object({
|
||||
export const uploadAgentFormSchema = z.object({
|
||||
agentFile: fileSchema,
|
||||
agentName: z.string().min(1, "Agent name is required"),
|
||||
agentDescription: z.string(),
|
||||
});
|
||||
|
||||
export default function LibraryUploadAgentDialog(): React.ReactNode {
|
||||
const [isDroped, setisDroped] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const api = useBackendAPI();
|
||||
const { toast } = useToast();
|
||||
const [agentObject, setAgentObject] = useState<GraphCreatable | null>(null);
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
agentName: "",
|
||||
agentDescription: "",
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
if (!agentObject) {
|
||||
form.setError("root", { message: "No Agent object to save" });
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
const payload: GraphCreatable = {
|
||||
...agentObject,
|
||||
name: values.agentName,
|
||||
description: values.agentDescription,
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await api.createGraph(payload);
|
||||
setIsOpen(false);
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Agent uploaded successfully",
|
||||
variant: "default",
|
||||
});
|
||||
const qID = "flowID";
|
||||
window.location.href = `/build?${qID}=${response.id}`;
|
||||
} catch (error) {
|
||||
form.setError("root", {
|
||||
message: `Could not create agent: ${error}`,
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (file: File) => {
|
||||
setTimeout(() => {
|
||||
setisDroped(false);
|
||||
}, 2000);
|
||||
|
||||
form.setValue("agentFile", file);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
try {
|
||||
const obj = JSON.parse(event.target?.result as string);
|
||||
if (
|
||||
!["name", "description", "nodes", "links"].every(
|
||||
(key) => key in obj && obj[key] != null,
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
"Invalid agent object in file: " + JSON.stringify(obj, null, 2),
|
||||
);
|
||||
}
|
||||
const agent = obj as Graph;
|
||||
sanitizeImportedGraph(agent);
|
||||
setAgentObject(agent);
|
||||
if (!form.getValues("agentName")) {
|
||||
form.setValue("agentName", agent.name);
|
||||
}
|
||||
if (!form.getValues("agentDescription")) {
|
||||
form.setValue("agentDescription", agent.description);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading agent file:", error);
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
setisDroped(false);
|
||||
};
|
||||
|
||||
const {
|
||||
onSubmit,
|
||||
isUploading,
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
isDroped,
|
||||
handleChange,
|
||||
form,
|
||||
setisDroped,
|
||||
agentObject,
|
||||
} = useLibraryUploadAgentDialog();
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogTrigger asChild>
|
||||
@@ -249,9 +166,9 @@ export default function LibraryUploadAgentDialog(): React.ReactNode {
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="mt-2 self-end"
|
||||
disabled={!agentObject || isLoading}
|
||||
disabled={!agentObject || isUploading}
|
||||
>
|
||||
{isLoading ? (
|
||||
{isUploading ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-b-2 border-t-2 border-white"></div>
|
||||
<span>Uploading...</span>
|
||||
@@ -0,0 +1,116 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { uploadAgentFormSchema } from "./LibraryUploadAgentDialog";
|
||||
import { usePostV1CreateNewGraph } from "@/app/api/__generated__/endpoints/graphs/graphs";
|
||||
import { GraphModel } from "@/app/api/__generated__/models/graphModel";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { useState } from "react";
|
||||
import { Graph } from "@/app/api/__generated__/models/graph";
|
||||
import { sanitizeImportedGraph } from "@/lib/autogpt-server-api";
|
||||
|
||||
export const useLibraryUploadAgentDialog = () => {
|
||||
const [isDroped, setisDroped] = useState(false);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const [agentObject, setAgentObject] = useState<Graph | null>(null);
|
||||
|
||||
const { mutateAsync: createGraph, isPending: isUploading } =
|
||||
usePostV1CreateNewGraph({
|
||||
mutation: {
|
||||
onSuccess: ({ data }) => {
|
||||
setIsOpen(false);
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Agent uploaded successfully",
|
||||
variant: "default",
|
||||
});
|
||||
const qID = "flowID";
|
||||
window.location.href = `/build?${qID}=${(data as GraphModel).id}`;
|
||||
},
|
||||
onError: () => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Error Uploading agent",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<z.infer<typeof uploadAgentFormSchema>>({
|
||||
resolver: zodResolver(uploadAgentFormSchema),
|
||||
defaultValues: {
|
||||
agentName: "",
|
||||
agentDescription: "",
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof uploadAgentFormSchema>) => {
|
||||
if (!agentObject) {
|
||||
form.setError("root", { message: "No Agent object to save" });
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: Graph = {
|
||||
...agentObject,
|
||||
name: values.agentName,
|
||||
description: values.agentDescription,
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
await createGraph({
|
||||
data: {
|
||||
graph: payload,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (file: File) => {
|
||||
setTimeout(() => {
|
||||
setisDroped(false);
|
||||
}, 2000);
|
||||
|
||||
form.setValue("agentFile", file);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
try {
|
||||
const obj = JSON.parse(event.target?.result as string);
|
||||
if (
|
||||
!["name", "description", "nodes", "links"].every(
|
||||
(key) => key in obj && obj[key] != null,
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
"Invalid agent object in file: " + JSON.stringify(obj, null, 2),
|
||||
);
|
||||
}
|
||||
const agent = obj as Graph;
|
||||
sanitizeImportedGraph(agent);
|
||||
setAgentObject(agent);
|
||||
if (!form.getValues("agentName")) {
|
||||
form.setValue("agentName", agent.name);
|
||||
}
|
||||
if (!form.getValues("agentDescription")) {
|
||||
form.setValue("agentDescription", agent.description);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading agent file:", error);
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
setisDroped(false);
|
||||
};
|
||||
|
||||
return {
|
||||
onSubmit,
|
||||
isUploading,
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
form,
|
||||
agentObject,
|
||||
isDroped,
|
||||
handleChange,
|
||||
setisDroped,
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
|
||||
import {
|
||||
createContext,
|
||||
useState,
|
||||
@@ -8,19 +9,14 @@ import {
|
||||
Dispatch,
|
||||
SetStateAction,
|
||||
} from "react";
|
||||
import { LibraryAgent, LibraryAgentSortEnum } from "@/lib/autogpt-server-api";
|
||||
|
||||
interface LibraryPageContextType {
|
||||
agents: LibraryAgent[];
|
||||
setAgents: Dispatch<SetStateAction<LibraryAgent[]>>;
|
||||
agentLoading: boolean;
|
||||
setAgentLoading: Dispatch<SetStateAction<boolean>>;
|
||||
searchTerm: string | undefined;
|
||||
setSearchTerm: Dispatch<SetStateAction<string | undefined>>;
|
||||
searchTerm: string;
|
||||
setSearchTerm: Dispatch<SetStateAction<string>>;
|
||||
uploadedFile: File | null;
|
||||
setUploadedFile: Dispatch<SetStateAction<File | null>>;
|
||||
librarySort: LibraryAgentSortEnum;
|
||||
setLibrarySort: Dispatch<SetStateAction<LibraryAgentSortEnum>>;
|
||||
librarySort: LibraryAgentSort;
|
||||
setLibrarySort: Dispatch<SetStateAction<LibraryAgentSort>>;
|
||||
}
|
||||
|
||||
export const LibraryPageContext = createContext<LibraryPageContextType>(
|
||||
@@ -32,21 +28,15 @@ export function LibraryPageStateProvider({
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [agents, setAgents] = useState<LibraryAgent[]>([]);
|
||||
const [agentLoading, setAgentLoading] = useState<boolean>(true);
|
||||
const [searchTerm, setSearchTerm] = useState<string | undefined>("");
|
||||
const [searchTerm, setSearchTerm] = useState<string>("");
|
||||
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
|
||||
const [librarySort, setLibrarySort] = useState<LibraryAgentSortEnum>(
|
||||
LibraryAgentSortEnum.UPDATED_AT,
|
||||
const [librarySort, setLibrarySort] = useState<LibraryAgentSort>(
|
||||
LibraryAgentSort.updatedAt,
|
||||
);
|
||||
|
||||
return (
|
||||
<LibraryPageContext.Provider
|
||||
value={{
|
||||
agents,
|
||||
setAgents,
|
||||
agentLoading,
|
||||
setAgentLoading,
|
||||
searchTerm,
|
||||
setSearchTerm,
|
||||
uploadedFile,
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client";
|
||||
import Link from "next/link";
|
||||
import { Metadata } from "next/types";
|
||||
|
||||
import {
|
||||
ArrowBottomRightIcon,
|
||||
@@ -7,15 +7,9 @@ import {
|
||||
} from "@radix-ui/react-icons";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
|
||||
import { LibraryPageStateProvider } from "./state-provider";
|
||||
import LibraryActionSubHeader from "@/components/library/library-action-sub-header";
|
||||
import LibraryActionHeader from "@/components/library/library-action-header";
|
||||
import LibraryAgentList from "@/components/library/library-agent-list";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Library - AutoGPT Platform",
|
||||
description: "Your collection of Agents on the AutoGPT Platform",
|
||||
};
|
||||
import { LibraryPageStateProvider } from "./components/state-provider";
|
||||
import LibraryActionHeader from "./components/LibraryActionHeader/LibraryActionHeader";
|
||||
import LibraryAgentList from "./components/LibraryAgentList/LibraryAgentList";
|
||||
|
||||
/**
|
||||
* LibraryPage Component
|
||||
@@ -25,13 +19,7 @@ export default function LibraryPage() {
|
||||
return (
|
||||
<main className="container min-h-screen space-y-4 pb-20 sm:px-8 md:px-12">
|
||||
<LibraryPageStateProvider>
|
||||
{/* Header section containing notifications, search functionality and upload mechanism */}
|
||||
<LibraryActionHeader />
|
||||
|
||||
{/* Subheader section containing agent counts and filtering options */}
|
||||
<LibraryActionSubHeader />
|
||||
|
||||
{/* Content section displaying agent list with counter and filtering options */}
|
||||
<LibraryAgentList />
|
||||
</LibraryPageStateProvider>
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import {
|
||||
getGetV1ListUserApiKeysQueryKey,
|
||||
useDeleteV1RevokeApiKey,
|
||||
useGetV1ListUserApiKeys,
|
||||
} from "@/api/__generated__/endpoints/api-keys/api-keys";
|
||||
import { APIKeyWithoutHash } from "@/api/__generated__/models/aPIKeyWithoutHash";
|
||||
} from "@/app/api/__generated__/endpoints/api-keys/api-keys";
|
||||
import { APIKeyWithoutHash } from "@/app/api/__generated__/models/aPIKeyWithoutHash";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { getQueryClient } from "@/lib/react-query/queryClient";
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import { useAPIkeysModals } from "./useAPIkeysModals";
|
||||
import { APIKeyPermission } from "@/api/__generated__/models/aPIKeyPermission";
|
||||
import { APIKeyPermission } from "@/app/api/__generated__/models/aPIKeyPermission";
|
||||
|
||||
export const APIKeysModals = () => {
|
||||
const {
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
import {
|
||||
getGetV1ListUserApiKeysQueryKey,
|
||||
usePostV1CreateNewApiKey,
|
||||
} from "@/api/__generated__/endpoints/api-keys/api-keys";
|
||||
import { APIKeyPermission } from "@/api/__generated__/models/aPIKeyPermission";
|
||||
import { CreateAPIKeyResponse } from "@/api/__generated__/models/createAPIKeyResponse";
|
||||
} from "@/app/api/__generated__/endpoints/api-keys/api-keys";
|
||||
import { APIKeyPermission } from "@/app/api/__generated__/models/aPIKeyPermission";
|
||||
import { CreateAPIKeyResponse } from "@/app/api/__generated__/models/createAPIKeyResponse";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { getQueryClient } from "@/lib/react-query/queryClient";
|
||||
import { useState } from "react";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { NotificationPreferenceDTO } from "@/lib/autogpt-server-api/types";
|
||||
import {
|
||||
postV1UpdateNotificationPreferences,
|
||||
postV1UpdateUserEmail,
|
||||
} from "@/api/__generated__/endpoints/auth/auth";
|
||||
} from "@/app/api/__generated__/endpoints/auth/auth";
|
||||
|
||||
export async function updateSettings(formData: FormData) {
|
||||
const supabase = await getServerSupabase();
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { NotificationPreference } from "@/api/__generated__/models/notificationPreference";
|
||||
import { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
|
||||
import { User } from "@supabase/supabase-js";
|
||||
import { useSettingsForm } from "./useSettingsForm";
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { updateSettings } from "../../actions";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { NotificationPreference } from "@/api/__generated__/models/notificationPreference";
|
||||
import { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
|
||||
import { User } from "@supabase/supabase-js";
|
||||
|
||||
export const useSettingsForm = ({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client";
|
||||
import { useGetV1GetNotificationPreferences } from "@/api/__generated__/endpoints/auth/auth";
|
||||
import { useGetV1GetNotificationPreferences } from "@/app/api/__generated__/endpoints/auth/auth";
|
||||
import { SettingsForm } from "@/app/(platform)/profile/(user)/settings/components/SettingsForm/SettingsForm";
|
||||
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
|
||||
import * as React from "react";
|
||||
|
||||
@@ -10,7 +10,8 @@ export async function sendResetEmail(email: string, turnstileToken: string) {
|
||||
{},
|
||||
async () => {
|
||||
const supabase = await getServerSupabase();
|
||||
const origin = process.env.FRONTEND_BASE_URL || "http://localhost:3000";
|
||||
const origin =
|
||||
process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "http://localhost:3000";
|
||||
|
||||
if (!supabase) {
|
||||
redirect("/error");
|
||||
|
||||
931
autogpt_platform/frontend/src/app/api/__generated__/endpoints/admin/admin.ts
generated
Normal file
931
autogpt_platform/frontend/src/app/api/__generated__/endpoints/admin/admin.ts
generated
Normal file
@@ -0,0 +1,931 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { AddUserCreditsResponse } from "../../models/addUserCreditsResponse";
|
||||
|
||||
import type { BodyPostV2AddCreditsToUser } from "../../models/bodyPostV2AddCreditsToUser";
|
||||
|
||||
import type { GetV2GetAdminListingsHistoryParams } from "../../models/getV2GetAdminListingsHistoryParams";
|
||||
|
||||
import type { GetV2GetAllUsersHistoryParams } from "../../models/getV2GetAllUsersHistoryParams";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { ReviewSubmissionRequest } from "../../models/reviewSubmissionRequest";
|
||||
|
||||
import type { StoreListingsWithVersionsResponse } from "../../models/storeListingsWithVersionsResponse";
|
||||
|
||||
import type { StoreSubmission } from "../../models/storeSubmission";
|
||||
|
||||
import type { UserHistoryResponse } from "../../models/userHistoryResponse";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* Get store listings with their version history for admins.
|
||||
|
||||
This provides a consolidated view of listings with their versions,
|
||||
allowing for an expandable UI in the admin dashboard.
|
||||
|
||||
Args:
|
||||
status: Filter by submission status (PENDING, APPROVED, REJECTED)
|
||||
search: Search by name, description, or user email
|
||||
page: Page number for pagination
|
||||
page_size: Number of items per page
|
||||
|
||||
Returns:
|
||||
StoreListingsWithVersionsResponse with listings and their versions
|
||||
* @summary Get Admin Listings History
|
||||
*/
|
||||
export type getV2GetAdminListingsHistoryResponse200 = {
|
||||
data: StoreListingsWithVersionsResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV2GetAdminListingsHistoryResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV2GetAdminListingsHistoryResponseComposite =
|
||||
| getV2GetAdminListingsHistoryResponse200
|
||||
| getV2GetAdminListingsHistoryResponse422;
|
||||
|
||||
export type getV2GetAdminListingsHistoryResponse =
|
||||
getV2GetAdminListingsHistoryResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV2GetAdminListingsHistoryUrl = (
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? "null" : value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0
|
||||
? `/api/store/admin/listings?${stringifiedParams}`
|
||||
: `/api/store/admin/listings`;
|
||||
};
|
||||
|
||||
export const getV2GetAdminListingsHistory = async (
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
options?: RequestInit,
|
||||
): Promise<getV2GetAdminListingsHistoryResponse> => {
|
||||
return customMutator<getV2GetAdminListingsHistoryResponse>(
|
||||
getGetV2GetAdminListingsHistoryUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV2GetAdminListingsHistoryQueryKey = (
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
) => {
|
||||
return [`/api/store/admin/listings`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getGetV2GetAdminListingsHistoryQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV2GetAdminListingsHistoryQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>
|
||||
> = ({ signal }) =>
|
||||
getV2GetAdminListingsHistory(params, { signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV2GetAdminListingsHistoryQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>
|
||||
>;
|
||||
export type GetV2GetAdminListingsHistoryQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV2GetAdminListingsHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: undefined | GetV2GetAdminListingsHistoryParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetAdminListingsHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetAdminListingsHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get Admin Listings History
|
||||
*/
|
||||
|
||||
export function useGetV2GetAdminListingsHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAdminListingsHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAdminListingsHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV2GetAdminListingsHistoryQueryOptions(
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Review a store listing submission.
|
||||
|
||||
Args:
|
||||
store_listing_version_id: ID of the submission to review
|
||||
request: Review details including approval status and comments
|
||||
user: Authenticated admin user performing the review
|
||||
|
||||
Returns:
|
||||
StoreSubmission with updated review information
|
||||
* @summary Review Store Submission
|
||||
*/
|
||||
export type postV2ReviewStoreSubmissionResponse200 = {
|
||||
data: StoreSubmission;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2ReviewStoreSubmissionResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2ReviewStoreSubmissionResponseComposite =
|
||||
| postV2ReviewStoreSubmissionResponse200
|
||||
| postV2ReviewStoreSubmissionResponse422;
|
||||
|
||||
export type postV2ReviewStoreSubmissionResponse =
|
||||
postV2ReviewStoreSubmissionResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2ReviewStoreSubmissionUrl = (
|
||||
storeListingVersionId: string,
|
||||
) => {
|
||||
return `/api/store/admin/submissions/${storeListingVersionId}/review`;
|
||||
};
|
||||
|
||||
export const postV2ReviewStoreSubmission = async (
|
||||
storeListingVersionId: string,
|
||||
reviewSubmissionRequest: ReviewSubmissionRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2ReviewStoreSubmissionResponse> => {
|
||||
return customMutator<postV2ReviewStoreSubmissionResponse>(
|
||||
getPostV2ReviewStoreSubmissionUrl(storeListingVersionId),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(reviewSubmissionRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2ReviewStoreSubmissionMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>,
|
||||
TError,
|
||||
{ storeListingVersionId: string; data: ReviewSubmissionRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>,
|
||||
TError,
|
||||
{ storeListingVersionId: string; data: ReviewSubmissionRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2ReviewStoreSubmission"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>,
|
||||
{ storeListingVersionId: string; data: ReviewSubmissionRequest }
|
||||
> = (props) => {
|
||||
const { storeListingVersionId, data } = props ?? {};
|
||||
|
||||
return postV2ReviewStoreSubmission(
|
||||
storeListingVersionId,
|
||||
data,
|
||||
requestOptions,
|
||||
);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2ReviewStoreSubmissionMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>
|
||||
>;
|
||||
export type PostV2ReviewStoreSubmissionMutationBody = ReviewSubmissionRequest;
|
||||
export type PostV2ReviewStoreSubmissionMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Review Store Submission
|
||||
*/
|
||||
export const usePostV2ReviewStoreSubmission = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>,
|
||||
TError,
|
||||
{ storeListingVersionId: string; data: ReviewSubmissionRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2ReviewStoreSubmission>>,
|
||||
TError,
|
||||
{ storeListingVersionId: string; data: ReviewSubmissionRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPostV2ReviewStoreSubmissionMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Download the agent file by streaming its content.
|
||||
|
||||
Args:
|
||||
store_listing_version_id (str): The ID of the agent to download
|
||||
|
||||
Returns:
|
||||
StreamingResponse: A streaming response containing the agent's graph data.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the agent is not found or an unexpected error occurs.
|
||||
* @summary Admin Download Agent File
|
||||
*/
|
||||
export type getV2AdminDownloadAgentFileResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV2AdminDownloadAgentFileResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV2AdminDownloadAgentFileResponseComposite =
|
||||
| getV2AdminDownloadAgentFileResponse200
|
||||
| getV2AdminDownloadAgentFileResponse422;
|
||||
|
||||
export type getV2AdminDownloadAgentFileResponse =
|
||||
getV2AdminDownloadAgentFileResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV2AdminDownloadAgentFileUrl = (
|
||||
storeListingVersionId: string,
|
||||
) => {
|
||||
return `/api/store/admin/submissions/download/${storeListingVersionId}`;
|
||||
};
|
||||
|
||||
export const getV2AdminDownloadAgentFile = async (
|
||||
storeListingVersionId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<getV2AdminDownloadAgentFileResponse> => {
|
||||
return customMutator<getV2AdminDownloadAgentFileResponse>(
|
||||
getGetV2AdminDownloadAgentFileUrl(storeListingVersionId),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV2AdminDownloadAgentFileQueryKey = (
|
||||
storeListingVersionId: string,
|
||||
) => {
|
||||
return [
|
||||
`/api/store/admin/submissions/download/${storeListingVersionId}`,
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getGetV2AdminDownloadAgentFileQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
storeListingVersionId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ??
|
||||
getGetV2AdminDownloadAgentFileQueryKey(storeListingVersionId);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>
|
||||
> = ({ signal }) =>
|
||||
getV2AdminDownloadAgentFile(storeListingVersionId, {
|
||||
signal,
|
||||
...requestOptions,
|
||||
});
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!storeListingVersionId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV2AdminDownloadAgentFileQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>
|
||||
>;
|
||||
export type GetV2AdminDownloadAgentFileQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV2AdminDownloadAgentFile<
|
||||
TData = Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
storeListingVersionId: string,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2AdminDownloadAgentFile<
|
||||
TData = Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
storeListingVersionId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2AdminDownloadAgentFile<
|
||||
TData = Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
storeListingVersionId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Admin Download Agent File
|
||||
*/
|
||||
|
||||
export function useGetV2AdminDownloadAgentFile<
|
||||
TData = Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
storeListingVersionId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2AdminDownloadAgentFile>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV2AdminDownloadAgentFileQueryOptions(
|
||||
storeListingVersionId,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Add Credits to User
|
||||
*/
|
||||
export type postV2AddCreditsToUserResponse200 = {
|
||||
data: AddUserCreditsResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2AddCreditsToUserResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2AddCreditsToUserResponseComposite =
|
||||
| postV2AddCreditsToUserResponse200
|
||||
| postV2AddCreditsToUserResponse422;
|
||||
|
||||
export type postV2AddCreditsToUserResponse =
|
||||
postV2AddCreditsToUserResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2AddCreditsToUserUrl = () => {
|
||||
return `/api/credits/admin/add_credits`;
|
||||
};
|
||||
|
||||
export const postV2AddCreditsToUser = async (
|
||||
bodyPostV2AddCreditsToUser: BodyPostV2AddCreditsToUser,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2AddCreditsToUserResponse> => {
|
||||
return customMutator<postV2AddCreditsToUserResponse>(
|
||||
getPostV2AddCreditsToUserUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(bodyPostV2AddCreditsToUser),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2AddCreditsToUserMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>,
|
||||
TError,
|
||||
{ data: BodyPostV2AddCreditsToUser },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>,
|
||||
TError,
|
||||
{ data: BodyPostV2AddCreditsToUser },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2AddCreditsToUser"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>,
|
||||
{ data: BodyPostV2AddCreditsToUser }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV2AddCreditsToUser(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2AddCreditsToUserMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>
|
||||
>;
|
||||
export type PostV2AddCreditsToUserMutationBody = BodyPostV2AddCreditsToUser;
|
||||
export type PostV2AddCreditsToUserMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Add Credits to User
|
||||
*/
|
||||
export const usePostV2AddCreditsToUser = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>,
|
||||
TError,
|
||||
{ data: BodyPostV2AddCreditsToUser },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2AddCreditsToUser>>,
|
||||
TError,
|
||||
{ data: BodyPostV2AddCreditsToUser },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV2AddCreditsToUserMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Get All Users History
|
||||
*/
|
||||
export type getV2GetAllUsersHistoryResponse200 = {
|
||||
data: UserHistoryResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV2GetAllUsersHistoryResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV2GetAllUsersHistoryResponseComposite =
|
||||
| getV2GetAllUsersHistoryResponse200
|
||||
| getV2GetAllUsersHistoryResponse422;
|
||||
|
||||
export type getV2GetAllUsersHistoryResponse =
|
||||
getV2GetAllUsersHistoryResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV2GetAllUsersHistoryUrl = (
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? "null" : value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0
|
||||
? `/api/credits/admin/users_history?${stringifiedParams}`
|
||||
: `/api/credits/admin/users_history`;
|
||||
};
|
||||
|
||||
export const getV2GetAllUsersHistory = async (
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
options?: RequestInit,
|
||||
): Promise<getV2GetAllUsersHistoryResponse> => {
|
||||
return customMutator<getV2GetAllUsersHistoryResponse>(
|
||||
getGetV2GetAllUsersHistoryUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV2GetAllUsersHistoryQueryKey = (
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/credits/admin/users_history`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getGetV2GetAllUsersHistoryQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV2GetAllUsersHistoryQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>
|
||||
> = ({ signal }) =>
|
||||
getV2GetAllUsersHistory(params, { signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV2GetAllUsersHistoryQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>
|
||||
>;
|
||||
export type GetV2GetAllUsersHistoryQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV2GetAllUsersHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: undefined | GetV2GetAllUsersHistoryParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetAllUsersHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetAllUsersHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get All Users History
|
||||
*/
|
||||
|
||||
export function useGetV2GetAllUsersHistory<
|
||||
TData = Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params?: GetV2GetAllUsersHistoryParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetAllUsersHistory>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV2GetAllUsersHistoryQueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
245
autogpt_platform/frontend/src/app/api/__generated__/endpoints/analytics/analytics.ts
generated
Normal file
245
autogpt_platform/frontend/src/app/api/__generated__/endpoints/analytics/analytics.ts
generated
Normal file
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type {
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { BodyPostV1LogRawAnalytics } from "../../models/bodyPostV1LogRawAnalytics";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { LogRawMetricRequest } from "../../models/logRawMetricRequest";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary Log Raw Metric
|
||||
*/
|
||||
export type postV1LogRawMetricResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1LogRawMetricResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1LogRawMetricResponseComposite =
|
||||
| postV1LogRawMetricResponse200
|
||||
| postV1LogRawMetricResponse422;
|
||||
|
||||
export type postV1LogRawMetricResponse = postV1LogRawMetricResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1LogRawMetricUrl = () => {
|
||||
return `/api/analytics/log_raw_metric`;
|
||||
};
|
||||
|
||||
export const postV1LogRawMetric = async (
|
||||
logRawMetricRequest: LogRawMetricRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1LogRawMetricResponse> => {
|
||||
return customMutator<postV1LogRawMetricResponse>(getPostV1LogRawMetricUrl(), {
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(logRawMetricRequest),
|
||||
});
|
||||
};
|
||||
|
||||
export const getPostV1LogRawMetricMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>,
|
||||
TError,
|
||||
{ data: LogRawMetricRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>,
|
||||
TError,
|
||||
{ data: LogRawMetricRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1LogRawMetric"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>,
|
||||
{ data: LogRawMetricRequest }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1LogRawMetric(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1LogRawMetricMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>
|
||||
>;
|
||||
export type PostV1LogRawMetricMutationBody = LogRawMetricRequest;
|
||||
export type PostV1LogRawMetricMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Log Raw Metric
|
||||
*/
|
||||
export const usePostV1LogRawMetric = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>,
|
||||
TError,
|
||||
{ data: LogRawMetricRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1LogRawMetric>>,
|
||||
TError,
|
||||
{ data: LogRawMetricRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1LogRawMetricMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Log Raw Analytics
|
||||
*/
|
||||
export type postV1LogRawAnalyticsResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1LogRawAnalyticsResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1LogRawAnalyticsResponseComposite =
|
||||
| postV1LogRawAnalyticsResponse200
|
||||
| postV1LogRawAnalyticsResponse422;
|
||||
|
||||
export type postV1LogRawAnalyticsResponse =
|
||||
postV1LogRawAnalyticsResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1LogRawAnalyticsUrl = () => {
|
||||
return `/api/analytics/log_raw_analytics`;
|
||||
};
|
||||
|
||||
export const postV1LogRawAnalytics = async (
|
||||
bodyPostV1LogRawAnalytics: BodyPostV1LogRawAnalytics,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1LogRawAnalyticsResponse> => {
|
||||
return customMutator<postV1LogRawAnalyticsResponse>(
|
||||
getPostV1LogRawAnalyticsUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(bodyPostV1LogRawAnalytics),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1LogRawAnalyticsMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>,
|
||||
TError,
|
||||
{ data: BodyPostV1LogRawAnalytics },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>,
|
||||
TError,
|
||||
{ data: BodyPostV1LogRawAnalytics },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1LogRawAnalytics"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>,
|
||||
{ data: BodyPostV1LogRawAnalytics }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1LogRawAnalytics(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1LogRawAnalyticsMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>
|
||||
>;
|
||||
export type PostV1LogRawAnalyticsMutationBody = BodyPostV1LogRawAnalytics;
|
||||
export type PostV1LogRawAnalyticsMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Log Raw Analytics
|
||||
*/
|
||||
export const usePostV1LogRawAnalytics = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>,
|
||||
TError,
|
||||
{ data: BodyPostV1LogRawAnalytics },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1LogRawAnalytics>>,
|
||||
TError,
|
||||
{ data: BodyPostV1LogRawAnalytics },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1LogRawAnalyticsMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
857
autogpt_platform/frontend/src/app/api/__generated__/endpoints/api-keys/api-keys.ts
generated
Normal file
857
autogpt_platform/frontend/src/app/api/__generated__/endpoints/api-keys/api-keys.ts
generated
Normal file
@@ -0,0 +1,857 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { APIKeyWithoutHash } from "../../models/aPIKeyWithoutHash";
|
||||
|
||||
import type { CreateAPIKeyRequest } from "../../models/createAPIKeyRequest";
|
||||
|
||||
import type { CreateAPIKeyResponse } from "../../models/createAPIKeyResponse";
|
||||
|
||||
import type { GetV1ListUserApiKeys200 } from "../../models/getV1ListUserApiKeys200";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { UpdatePermissionsRequest } from "../../models/updatePermissionsRequest";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* List all API keys for the user
|
||||
* @summary List user API keys
|
||||
*/
|
||||
export type getV1ListUserApiKeysResponse200 = {
|
||||
data: GetV1ListUserApiKeys200;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1ListUserApiKeysResponseComposite =
|
||||
getV1ListUserApiKeysResponse200;
|
||||
|
||||
export type getV1ListUserApiKeysResponse =
|
||||
getV1ListUserApiKeysResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1ListUserApiKeysUrl = () => {
|
||||
return `/api/api-keys`;
|
||||
};
|
||||
|
||||
export const getV1ListUserApiKeys = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1ListUserApiKeysResponse> => {
|
||||
return customMutator<getV1ListUserApiKeysResponse>(
|
||||
getGetV1ListUserApiKeysUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1ListUserApiKeysQueryKey = () => {
|
||||
return [`/api/api-keys`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1ListUserApiKeysQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetV1ListUserApiKeysQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>
|
||||
> = ({ signal }) => getV1ListUserApiKeys({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1ListUserApiKeysQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>
|
||||
>;
|
||||
export type GetV1ListUserApiKeysQueryError = unknown;
|
||||
|
||||
export function useGetV1ListUserApiKeys<
|
||||
TData = Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListUserApiKeys<
|
||||
TData = Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListUserApiKeys<
|
||||
TData = Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary List user API keys
|
||||
*/
|
||||
|
||||
export function useGetV1ListUserApiKeys<
|
||||
TData = Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListUserApiKeys>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1ListUserApiKeysQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new API key
|
||||
* @summary Create new API key
|
||||
*/
|
||||
export type postV1CreateNewApiKeyResponse200 = {
|
||||
data: CreateAPIKeyResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1CreateNewApiKeyResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1CreateNewApiKeyResponseComposite =
|
||||
| postV1CreateNewApiKeyResponse200
|
||||
| postV1CreateNewApiKeyResponse422;
|
||||
|
||||
export type postV1CreateNewApiKeyResponse =
|
||||
postV1CreateNewApiKeyResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1CreateNewApiKeyUrl = () => {
|
||||
return `/api/api-keys`;
|
||||
};
|
||||
|
||||
export const postV1CreateNewApiKey = async (
|
||||
createAPIKeyRequest: CreateAPIKeyRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1CreateNewApiKeyResponse> => {
|
||||
return customMutator<postV1CreateNewApiKeyResponse>(
|
||||
getPostV1CreateNewApiKeyUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(createAPIKeyRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1CreateNewApiKeyMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>,
|
||||
TError,
|
||||
{ data: CreateAPIKeyRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>,
|
||||
TError,
|
||||
{ data: CreateAPIKeyRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1CreateNewApiKey"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>,
|
||||
{ data: CreateAPIKeyRequest }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1CreateNewApiKey(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1CreateNewApiKeyMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>
|
||||
>;
|
||||
export type PostV1CreateNewApiKeyMutationBody = CreateAPIKeyRequest;
|
||||
export type PostV1CreateNewApiKeyMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Create new API key
|
||||
*/
|
||||
export const usePostV1CreateNewApiKey = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>,
|
||||
TError,
|
||||
{ data: CreateAPIKeyRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1CreateNewApiKey>>,
|
||||
TError,
|
||||
{ data: CreateAPIKeyRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1CreateNewApiKeyMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Get a specific API key
|
||||
* @summary Get specific API key
|
||||
*/
|
||||
export type getV1GetSpecificApiKeyResponse200 = {
|
||||
data: APIKeyWithoutHash;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1GetSpecificApiKeyResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV1GetSpecificApiKeyResponseComposite =
|
||||
| getV1GetSpecificApiKeyResponse200
|
||||
| getV1GetSpecificApiKeyResponse422;
|
||||
|
||||
export type getV1GetSpecificApiKeyResponse =
|
||||
getV1GetSpecificApiKeyResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1GetSpecificApiKeyUrl = (keyId: string) => {
|
||||
return `/api/api-keys/${keyId}`;
|
||||
};
|
||||
|
||||
export const getV1GetSpecificApiKey = async (
|
||||
keyId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<getV1GetSpecificApiKeyResponse> => {
|
||||
return customMutator<getV1GetSpecificApiKeyResponse>(
|
||||
getGetV1GetSpecificApiKeyUrl(keyId),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1GetSpecificApiKeyQueryKey = (keyId: string) => {
|
||||
return [`/api/api-keys/${keyId}`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1GetSpecificApiKeyQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
keyId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1GetSpecificApiKeyQueryKey(keyId);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>
|
||||
> = ({ signal }) =>
|
||||
getV1GetSpecificApiKey(keyId, { signal, ...requestOptions });
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!keyId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1GetSpecificApiKeyQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>
|
||||
>;
|
||||
export type GetV1GetSpecificApiKeyQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV1GetSpecificApiKey<
|
||||
TData = Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
keyId: string,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetSpecificApiKey<
|
||||
TData = Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
keyId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetSpecificApiKey<
|
||||
TData = Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
keyId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get specific API key
|
||||
*/
|
||||
|
||||
export function useGetV1GetSpecificApiKey<
|
||||
TData = Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
keyId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetSpecificApiKey>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1GetSpecificApiKeyQueryOptions(keyId, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke an API key
|
||||
* @summary Revoke API key
|
||||
*/
|
||||
export type deleteV1RevokeApiKeyResponse200 = {
|
||||
data: APIKeyWithoutHash;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type deleteV1RevokeApiKeyResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type deleteV1RevokeApiKeyResponseComposite =
|
||||
| deleteV1RevokeApiKeyResponse200
|
||||
| deleteV1RevokeApiKeyResponse422;
|
||||
|
||||
export type deleteV1RevokeApiKeyResponse =
|
||||
deleteV1RevokeApiKeyResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getDeleteV1RevokeApiKeyUrl = (keyId: string) => {
|
||||
return `/api/api-keys/${keyId}`;
|
||||
};
|
||||
|
||||
export const deleteV1RevokeApiKey = async (
|
||||
keyId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<deleteV1RevokeApiKeyResponse> => {
|
||||
return customMutator<deleteV1RevokeApiKeyResponse>(
|
||||
getDeleteV1RevokeApiKeyUrl(keyId),
|
||||
{
|
||||
...options,
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getDeleteV1RevokeApiKeyMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["deleteV1RevokeApiKey"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>,
|
||||
{ keyId: string }
|
||||
> = (props) => {
|
||||
const { keyId } = props ?? {};
|
||||
|
||||
return deleteV1RevokeApiKey(keyId, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DeleteV1RevokeApiKeyMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>
|
||||
>;
|
||||
|
||||
export type DeleteV1RevokeApiKeyMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Revoke API key
|
||||
*/
|
||||
export const useDeleteV1RevokeApiKey = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof deleteV1RevokeApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getDeleteV1RevokeApiKeyMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Suspend an API key
|
||||
* @summary Suspend API key
|
||||
*/
|
||||
export type postV1SuspendApiKeyResponse200 = {
|
||||
data: APIKeyWithoutHash;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1SuspendApiKeyResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1SuspendApiKeyResponseComposite =
|
||||
| postV1SuspendApiKeyResponse200
|
||||
| postV1SuspendApiKeyResponse422;
|
||||
|
||||
export type postV1SuspendApiKeyResponse =
|
||||
postV1SuspendApiKeyResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1SuspendApiKeyUrl = (keyId: string) => {
|
||||
return `/api/api-keys/${keyId}/suspend`;
|
||||
};
|
||||
|
||||
export const postV1SuspendApiKey = async (
|
||||
keyId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1SuspendApiKeyResponse> => {
|
||||
return customMutator<postV1SuspendApiKeyResponse>(
|
||||
getPostV1SuspendApiKeyUrl(keyId),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1SuspendApiKeyMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1SuspendApiKey"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>,
|
||||
{ keyId: string }
|
||||
> = (props) => {
|
||||
const { keyId } = props ?? {};
|
||||
|
||||
return postV1SuspendApiKey(keyId, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1SuspendApiKeyMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>
|
||||
>;
|
||||
|
||||
export type PostV1SuspendApiKeyMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Suspend API key
|
||||
*/
|
||||
export const usePostV1SuspendApiKey = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1SuspendApiKey>>,
|
||||
TError,
|
||||
{ keyId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1SuspendApiKeyMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Update API key permissions
|
||||
* @summary Update key permissions
|
||||
*/
|
||||
export type putV1UpdateKeyPermissionsResponse200 = {
|
||||
data: APIKeyWithoutHash;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type putV1UpdateKeyPermissionsResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type putV1UpdateKeyPermissionsResponseComposite =
|
||||
| putV1UpdateKeyPermissionsResponse200
|
||||
| putV1UpdateKeyPermissionsResponse422;
|
||||
|
||||
export type putV1UpdateKeyPermissionsResponse =
|
||||
putV1UpdateKeyPermissionsResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPutV1UpdateKeyPermissionsUrl = (keyId: string) => {
|
||||
return `/api/api-keys/${keyId}/permissions`;
|
||||
};
|
||||
|
||||
export const putV1UpdateKeyPermissions = async (
|
||||
keyId: string,
|
||||
updatePermissionsRequest: UpdatePermissionsRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<putV1UpdateKeyPermissionsResponse> => {
|
||||
return customMutator<putV1UpdateKeyPermissionsResponse>(
|
||||
getPutV1UpdateKeyPermissionsUrl(keyId),
|
||||
{
|
||||
...options,
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(updatePermissionsRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPutV1UpdateKeyPermissionsMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>,
|
||||
TError,
|
||||
{ keyId: string; data: UpdatePermissionsRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>,
|
||||
TError,
|
||||
{ keyId: string; data: UpdatePermissionsRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["putV1UpdateKeyPermissions"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>,
|
||||
{ keyId: string; data: UpdatePermissionsRequest }
|
||||
> = (props) => {
|
||||
const { keyId, data } = props ?? {};
|
||||
|
||||
return putV1UpdateKeyPermissions(keyId, data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PutV1UpdateKeyPermissionsMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>
|
||||
>;
|
||||
export type PutV1UpdateKeyPermissionsMutationBody = UpdatePermissionsRequest;
|
||||
export type PutV1UpdateKeyPermissionsMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Update key permissions
|
||||
*/
|
||||
export const usePutV1UpdateKeyPermissions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>,
|
||||
TError,
|
||||
{ keyId: string; data: UpdatePermissionsRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof putV1UpdateKeyPermissions>>,
|
||||
TError,
|
||||
{ keyId: string; data: UpdatePermissionsRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPutV1UpdateKeyPermissionsMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
535
autogpt_platform/frontend/src/app/api/__generated__/endpoints/auth/auth.ts
generated
Normal file
535
autogpt_platform/frontend/src/app/api/__generated__/endpoints/auth/auth.ts
generated
Normal file
@@ -0,0 +1,535 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { NotificationPreference } from "../../models/notificationPreference";
|
||||
|
||||
import type { NotificationPreferenceDTO } from "../../models/notificationPreferenceDTO";
|
||||
|
||||
import type { PostV1UpdateUserEmail200 } from "../../models/postV1UpdateUserEmail200";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary Get or create user
|
||||
*/
|
||||
export type postV1GetOrCreateUserResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1GetOrCreateUserResponseComposite =
|
||||
postV1GetOrCreateUserResponse200;
|
||||
|
||||
export type postV1GetOrCreateUserResponse =
|
||||
postV1GetOrCreateUserResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1GetOrCreateUserUrl = () => {
|
||||
return `/api/auth/user`;
|
||||
};
|
||||
|
||||
export const postV1GetOrCreateUser = async (
|
||||
options?: RequestInit,
|
||||
): Promise<postV1GetOrCreateUserResponse> => {
|
||||
return customMutator<postV1GetOrCreateUserResponse>(
|
||||
getPostV1GetOrCreateUserUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1GetOrCreateUserMutationOptions = <
|
||||
TError = unknown,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>,
|
||||
TError,
|
||||
void,
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>,
|
||||
TError,
|
||||
void,
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1GetOrCreateUser"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>,
|
||||
void
|
||||
> = () => {
|
||||
return postV1GetOrCreateUser(requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1GetOrCreateUserMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>
|
||||
>;
|
||||
|
||||
export type PostV1GetOrCreateUserMutationError = unknown;
|
||||
|
||||
/**
|
||||
* @summary Get or create user
|
||||
*/
|
||||
export const usePostV1GetOrCreateUser = <TError = unknown, TContext = unknown>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>,
|
||||
TError,
|
||||
void,
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1GetOrCreateUser>>,
|
||||
TError,
|
||||
void,
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1GetOrCreateUserMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Update user email
|
||||
*/
|
||||
export type postV1UpdateUserEmailResponse200 = {
|
||||
data: PostV1UpdateUserEmail200;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1UpdateUserEmailResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1UpdateUserEmailResponseComposite =
|
||||
| postV1UpdateUserEmailResponse200
|
||||
| postV1UpdateUserEmailResponse422;
|
||||
|
||||
export type postV1UpdateUserEmailResponse =
|
||||
postV1UpdateUserEmailResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1UpdateUserEmailUrl = () => {
|
||||
return `/api/auth/user/email`;
|
||||
};
|
||||
|
||||
export const postV1UpdateUserEmail = async (
|
||||
postV1UpdateUserEmailBody: string,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1UpdateUserEmailResponse> => {
|
||||
return customMutator<postV1UpdateUserEmailResponse>(
|
||||
getPostV1UpdateUserEmailUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(postV1UpdateUserEmailBody),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1UpdateUserEmailMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>,
|
||||
TError,
|
||||
{ data: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>,
|
||||
TError,
|
||||
{ data: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1UpdateUserEmail"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>,
|
||||
{ data: string }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1UpdateUserEmail(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1UpdateUserEmailMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>
|
||||
>;
|
||||
export type PostV1UpdateUserEmailMutationBody = string;
|
||||
export type PostV1UpdateUserEmailMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Update user email
|
||||
*/
|
||||
export const usePostV1UpdateUserEmail = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>,
|
||||
TError,
|
||||
{ data: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1UpdateUserEmail>>,
|
||||
TError,
|
||||
{ data: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1UpdateUserEmailMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Get notification preferences
|
||||
*/
|
||||
export type getV1GetNotificationPreferencesResponse200 = {
|
||||
data: NotificationPreference;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1GetNotificationPreferencesResponseComposite =
|
||||
getV1GetNotificationPreferencesResponse200;
|
||||
|
||||
export type getV1GetNotificationPreferencesResponse =
|
||||
getV1GetNotificationPreferencesResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1GetNotificationPreferencesUrl = () => {
|
||||
return `/api/auth/user/preferences`;
|
||||
};
|
||||
|
||||
export const getV1GetNotificationPreferences = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1GetNotificationPreferencesResponse> => {
|
||||
return customMutator<getV1GetNotificationPreferencesResponse>(
|
||||
getGetV1GetNotificationPreferencesUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1GetNotificationPreferencesQueryKey = () => {
|
||||
return [`/api/auth/user/preferences`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1GetNotificationPreferencesQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1GetNotificationPreferencesQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>
|
||||
> = ({ signal }) =>
|
||||
getV1GetNotificationPreferences({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1GetNotificationPreferencesQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>
|
||||
>;
|
||||
export type GetV1GetNotificationPreferencesQueryError = unknown;
|
||||
|
||||
export function useGetV1GetNotificationPreferences<
|
||||
TData = Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetNotificationPreferences<
|
||||
TData = Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetNotificationPreferences<
|
||||
TData = Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get notification preferences
|
||||
*/
|
||||
|
||||
export function useGetV1GetNotificationPreferences<
|
||||
TData = Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetNotificationPreferences>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1GetNotificationPreferencesQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Update notification preferences
|
||||
*/
|
||||
export type postV1UpdateNotificationPreferencesResponse200 = {
|
||||
data: NotificationPreference;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1UpdateNotificationPreferencesResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1UpdateNotificationPreferencesResponseComposite =
|
||||
| postV1UpdateNotificationPreferencesResponse200
|
||||
| postV1UpdateNotificationPreferencesResponse422;
|
||||
|
||||
export type postV1UpdateNotificationPreferencesResponse =
|
||||
postV1UpdateNotificationPreferencesResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1UpdateNotificationPreferencesUrl = () => {
|
||||
return `/api/auth/user/preferences`;
|
||||
};
|
||||
|
||||
export const postV1UpdateNotificationPreferences = async (
|
||||
notificationPreferenceDTO: NotificationPreferenceDTO,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1UpdateNotificationPreferencesResponse> => {
|
||||
return customMutator<postV1UpdateNotificationPreferencesResponse>(
|
||||
getPostV1UpdateNotificationPreferencesUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(notificationPreferenceDTO),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1UpdateNotificationPreferencesMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>,
|
||||
TError,
|
||||
{ data: NotificationPreferenceDTO },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>,
|
||||
TError,
|
||||
{ data: NotificationPreferenceDTO },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1UpdateNotificationPreferences"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>,
|
||||
{ data: NotificationPreferenceDTO }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1UpdateNotificationPreferences(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1UpdateNotificationPreferencesMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>
|
||||
>;
|
||||
export type PostV1UpdateNotificationPreferencesMutationBody =
|
||||
NotificationPreferenceDTO;
|
||||
export type PostV1UpdateNotificationPreferencesMutationError =
|
||||
HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Update notification preferences
|
||||
*/
|
||||
export const usePostV1UpdateNotificationPreferences = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>,
|
||||
TError,
|
||||
{ data: NotificationPreferenceDTO },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1UpdateNotificationPreferences>>,
|
||||
TError,
|
||||
{ data: NotificationPreferenceDTO },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPostV1UpdateNotificationPreferencesMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
322
autogpt_platform/frontend/src/app/api/__generated__/endpoints/blocks/blocks.ts
generated
Normal file
322
autogpt_platform/frontend/src/app/api/__generated__/endpoints/blocks/blocks.ts
generated
Normal file
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { GetV1ListAvailableBlocks200Item } from "../../models/getV1ListAvailableBlocks200Item";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { PostV1ExecuteGraphBlock200 } from "../../models/postV1ExecuteGraphBlock200";
|
||||
|
||||
import type { PostV1ExecuteGraphBlockBody } from "../../models/postV1ExecuteGraphBlockBody";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary List available blocks
|
||||
*/
|
||||
export type getV1ListAvailableBlocksResponse200 = {
|
||||
data: GetV1ListAvailableBlocks200Item[];
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1ListAvailableBlocksResponseComposite =
|
||||
getV1ListAvailableBlocksResponse200;
|
||||
|
||||
export type getV1ListAvailableBlocksResponse =
|
||||
getV1ListAvailableBlocksResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1ListAvailableBlocksUrl = () => {
|
||||
return `/api/blocks`;
|
||||
};
|
||||
|
||||
export const getV1ListAvailableBlocks = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1ListAvailableBlocksResponse> => {
|
||||
return customMutator<getV1ListAvailableBlocksResponse>(
|
||||
getGetV1ListAvailableBlocksUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1ListAvailableBlocksQueryKey = () => {
|
||||
return [`/api/blocks`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1ListAvailableBlocksQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1ListAvailableBlocksQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>
|
||||
> = ({ signal }) => getV1ListAvailableBlocks({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1ListAvailableBlocksQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>
|
||||
>;
|
||||
export type GetV1ListAvailableBlocksQueryError = unknown;
|
||||
|
||||
export function useGetV1ListAvailableBlocks<
|
||||
TData = Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListAvailableBlocks<
|
||||
TData = Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListAvailableBlocks<
|
||||
TData = Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary List available blocks
|
||||
*/
|
||||
|
||||
export function useGetV1ListAvailableBlocks<
|
||||
TData = Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListAvailableBlocks>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1ListAvailableBlocksQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Execute graph block
|
||||
*/
|
||||
export type postV1ExecuteGraphBlockResponse200 = {
|
||||
data: PostV1ExecuteGraphBlock200;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1ExecuteGraphBlockResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1ExecuteGraphBlockResponseComposite =
|
||||
| postV1ExecuteGraphBlockResponse200
|
||||
| postV1ExecuteGraphBlockResponse422;
|
||||
|
||||
export type postV1ExecuteGraphBlockResponse =
|
||||
postV1ExecuteGraphBlockResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1ExecuteGraphBlockUrl = (blockId: string) => {
|
||||
return `/api/blocks/${blockId}/execute`;
|
||||
};
|
||||
|
||||
export const postV1ExecuteGraphBlock = async (
|
||||
blockId: string,
|
||||
postV1ExecuteGraphBlockBody: PostV1ExecuteGraphBlockBody,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1ExecuteGraphBlockResponse> => {
|
||||
return customMutator<postV1ExecuteGraphBlockResponse>(
|
||||
getPostV1ExecuteGraphBlockUrl(blockId),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(postV1ExecuteGraphBlockBody),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1ExecuteGraphBlockMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>,
|
||||
TError,
|
||||
{ blockId: string; data: PostV1ExecuteGraphBlockBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>,
|
||||
TError,
|
||||
{ blockId: string; data: PostV1ExecuteGraphBlockBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1ExecuteGraphBlock"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>,
|
||||
{ blockId: string; data: PostV1ExecuteGraphBlockBody }
|
||||
> = (props) => {
|
||||
const { blockId, data } = props ?? {};
|
||||
|
||||
return postV1ExecuteGraphBlock(blockId, data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1ExecuteGraphBlockMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>
|
||||
>;
|
||||
export type PostV1ExecuteGraphBlockMutationBody = PostV1ExecuteGraphBlockBody;
|
||||
export type PostV1ExecuteGraphBlockMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Execute graph block
|
||||
*/
|
||||
export const usePostV1ExecuteGraphBlock = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>,
|
||||
TError,
|
||||
{ blockId: string; data: PostV1ExecuteGraphBlockBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1ExecuteGraphBlock>>,
|
||||
TError,
|
||||
{ blockId: string; data: PostV1ExecuteGraphBlockBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV1ExecuteGraphBlockMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
1480
autogpt_platform/frontend/src/app/api/__generated__/endpoints/credits/credits.ts
generated
Normal file
1480
autogpt_platform/frontend/src/app/api/__generated__/endpoints/credits/credits.ts
generated
Normal file
File diff suppressed because it is too large
Load Diff
265
autogpt_platform/frontend/src/app/api/__generated__/endpoints/email/email.ts
generated
Normal file
265
autogpt_platform/frontend/src/app/api/__generated__/endpoints/email/email.ts
generated
Normal file
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type {
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { PostV1HandlePostmarkEmailWebhooksBody } from "../../models/postV1HandlePostmarkEmailWebhooksBody";
|
||||
|
||||
import type { PostV1OneClickEmailUnsubscribeParams } from "../../models/postV1OneClickEmailUnsubscribeParams";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary One Click Email Unsubscribe
|
||||
*/
|
||||
export type postV1OneClickEmailUnsubscribeResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1OneClickEmailUnsubscribeResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1OneClickEmailUnsubscribeResponseComposite =
|
||||
| postV1OneClickEmailUnsubscribeResponse200
|
||||
| postV1OneClickEmailUnsubscribeResponse422;
|
||||
|
||||
export type postV1OneClickEmailUnsubscribeResponse =
|
||||
postV1OneClickEmailUnsubscribeResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1OneClickEmailUnsubscribeUrl = (
|
||||
params: PostV1OneClickEmailUnsubscribeParams,
|
||||
) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? "null" : value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0
|
||||
? `/api/email/unsubscribe?${stringifiedParams}`
|
||||
: `/api/email/unsubscribe`;
|
||||
};
|
||||
|
||||
export const postV1OneClickEmailUnsubscribe = async (
|
||||
params: PostV1OneClickEmailUnsubscribeParams,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1OneClickEmailUnsubscribeResponse> => {
|
||||
return customMutator<postV1OneClickEmailUnsubscribeResponse>(
|
||||
getPostV1OneClickEmailUnsubscribeUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1OneClickEmailUnsubscribeMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>,
|
||||
TError,
|
||||
{ params: PostV1OneClickEmailUnsubscribeParams },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>,
|
||||
TError,
|
||||
{ params: PostV1OneClickEmailUnsubscribeParams },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1OneClickEmailUnsubscribe"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>,
|
||||
{ params: PostV1OneClickEmailUnsubscribeParams }
|
||||
> = (props) => {
|
||||
const { params } = props ?? {};
|
||||
|
||||
return postV1OneClickEmailUnsubscribe(params, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1OneClickEmailUnsubscribeMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>
|
||||
>;
|
||||
|
||||
export type PostV1OneClickEmailUnsubscribeMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary One Click Email Unsubscribe
|
||||
*/
|
||||
export const usePostV1OneClickEmailUnsubscribe = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>,
|
||||
TError,
|
||||
{ params: PostV1OneClickEmailUnsubscribeParams },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1OneClickEmailUnsubscribe>>,
|
||||
TError,
|
||||
{ params: PostV1OneClickEmailUnsubscribeParams },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPostV1OneClickEmailUnsubscribeMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Handle Postmark Email Webhooks
|
||||
*/
|
||||
export type postV1HandlePostmarkEmailWebhooksResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1HandlePostmarkEmailWebhooksResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1HandlePostmarkEmailWebhooksResponseComposite =
|
||||
| postV1HandlePostmarkEmailWebhooksResponse200
|
||||
| postV1HandlePostmarkEmailWebhooksResponse422;
|
||||
|
||||
export type postV1HandlePostmarkEmailWebhooksResponse =
|
||||
postV1HandlePostmarkEmailWebhooksResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1HandlePostmarkEmailWebhooksUrl = () => {
|
||||
return `/api/email/`;
|
||||
};
|
||||
|
||||
export const postV1HandlePostmarkEmailWebhooks = async (
|
||||
postV1HandlePostmarkEmailWebhooksBody: PostV1HandlePostmarkEmailWebhooksBody,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1HandlePostmarkEmailWebhooksResponse> => {
|
||||
return customMutator<postV1HandlePostmarkEmailWebhooksResponse>(
|
||||
getPostV1HandlePostmarkEmailWebhooksUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(postV1HandlePostmarkEmailWebhooksBody),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1HandlePostmarkEmailWebhooksMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>,
|
||||
TError,
|
||||
{ data: PostV1HandlePostmarkEmailWebhooksBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>,
|
||||
TError,
|
||||
{ data: PostV1HandlePostmarkEmailWebhooksBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1HandlePostmarkEmailWebhooks"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>,
|
||||
{ data: PostV1HandlePostmarkEmailWebhooksBody }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV1HandlePostmarkEmailWebhooks(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1HandlePostmarkEmailWebhooksMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>
|
||||
>;
|
||||
export type PostV1HandlePostmarkEmailWebhooksMutationBody =
|
||||
PostV1HandlePostmarkEmailWebhooksBody;
|
||||
export type PostV1HandlePostmarkEmailWebhooksMutationError =
|
||||
HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Handle Postmark Email Webhooks
|
||||
*/
|
||||
export const usePostV1HandlePostmarkEmailWebhooks = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>,
|
||||
TError,
|
||||
{ data: PostV1HandlePostmarkEmailWebhooksBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1HandlePostmarkEmailWebhooks>>,
|
||||
TError,
|
||||
{ data: PostV1HandlePostmarkEmailWebhooksBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPostV1HandlePostmarkEmailWebhooksMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
2302
autogpt_platform/frontend/src/app/api/__generated__/endpoints/graphs/graphs.ts
generated
Normal file
2302
autogpt_platform/frontend/src/app/api/__generated__/endpoints/graphs/graphs.ts
generated
Normal file
File diff suppressed because it is too large
Load Diff
187
autogpt_platform/frontend/src/app/api/__generated__/endpoints/health/health.ts
generated
Normal file
187
autogpt_platform/frontend/src/app/api/__generated__/endpoints/health/health.ts
generated
Normal file
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary Health
|
||||
*/
|
||||
export type getHealthHealthResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getHealthHealthResponseComposite = getHealthHealthResponse200;
|
||||
|
||||
export type getHealthHealthResponse = getHealthHealthResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetHealthHealthUrl = () => {
|
||||
return `/health`;
|
||||
};
|
||||
|
||||
export const getHealthHealth = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getHealthHealthResponse> => {
|
||||
return customMutator<getHealthHealthResponse>(getGetHealthHealthUrl(), {
|
||||
...options,
|
||||
method: "GET",
|
||||
});
|
||||
};
|
||||
|
||||
export const getGetHealthHealthQueryKey = () => {
|
||||
return [`/health`] as const;
|
||||
};
|
||||
|
||||
export const getGetHealthHealthQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<Awaited<ReturnType<typeof getHealthHealth>>, TError, TData>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey = queryOptions?.queryKey ?? getGetHealthHealthQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getHealthHealth>>> = ({
|
||||
signal,
|
||||
}) => getHealthHealth({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetHealthHealthQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>
|
||||
>;
|
||||
export type GetHealthHealthQueryError = unknown;
|
||||
|
||||
export function useGetHealthHealth<
|
||||
TData = Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getHealthHealth>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetHealthHealth<
|
||||
TData = Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getHealthHealth>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetHealthHealth<
|
||||
TData = Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Health
|
||||
*/
|
||||
|
||||
export function useGetHealthHealth<
|
||||
TData = Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getHealthHealth>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetHealthHealthQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
1423
autogpt_platform/frontend/src/app/api/__generated__/endpoints/integrations/integrations.ts
generated
Normal file
1423
autogpt_platform/frontend/src/app/api/__generated__/endpoints/integrations/integrations.ts
generated
Normal file
File diff suppressed because it is too large
Load Diff
1704
autogpt_platform/frontend/src/app/api/__generated__/endpoints/library/library.ts
generated
Normal file
1704
autogpt_platform/frontend/src/app/api/__generated__/endpoints/library/library.ts
generated
Normal file
File diff suppressed because it is too large
Load Diff
666
autogpt_platform/frontend/src/app/api/__generated__/endpoints/onboarding/onboarding.ts
generated
Normal file
666
autogpt_platform/frontend/src/app/api/__generated__/endpoints/onboarding/onboarding.ts
generated
Normal file
@@ -0,0 +1,666 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { UserOnboardingUpdate } from "../../models/userOnboardingUpdate";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary Get onboarding status
|
||||
*/
|
||||
export type getV1GetOnboardingStatusResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1GetOnboardingStatusResponseComposite =
|
||||
getV1GetOnboardingStatusResponse200;
|
||||
|
||||
export type getV1GetOnboardingStatusResponse =
|
||||
getV1GetOnboardingStatusResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1GetOnboardingStatusUrl = () => {
|
||||
return `/api/onboarding`;
|
||||
};
|
||||
|
||||
export const getV1GetOnboardingStatus = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1GetOnboardingStatusResponse> => {
|
||||
return customMutator<getV1GetOnboardingStatusResponse>(
|
||||
getGetV1GetOnboardingStatusUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1GetOnboardingStatusQueryKey = () => {
|
||||
return [`/api/onboarding`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1GetOnboardingStatusQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1GetOnboardingStatusQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>
|
||||
> = ({ signal }) => getV1GetOnboardingStatus({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1GetOnboardingStatusQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>
|
||||
>;
|
||||
export type GetV1GetOnboardingStatusQueryError = unknown;
|
||||
|
||||
export function useGetV1GetOnboardingStatus<
|
||||
TData = Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetOnboardingStatus<
|
||||
TData = Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetOnboardingStatus<
|
||||
TData = Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get onboarding status
|
||||
*/
|
||||
|
||||
export function useGetV1GetOnboardingStatus<
|
||||
TData = Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetOnboardingStatus>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1GetOnboardingStatusQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Update onboarding progress
|
||||
*/
|
||||
export type patchV1UpdateOnboardingProgressResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type patchV1UpdateOnboardingProgressResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type patchV1UpdateOnboardingProgressResponseComposite =
|
||||
| patchV1UpdateOnboardingProgressResponse200
|
||||
| patchV1UpdateOnboardingProgressResponse422;
|
||||
|
||||
export type patchV1UpdateOnboardingProgressResponse =
|
||||
patchV1UpdateOnboardingProgressResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPatchV1UpdateOnboardingProgressUrl = () => {
|
||||
return `/api/onboarding`;
|
||||
};
|
||||
|
||||
export const patchV1UpdateOnboardingProgress = async (
|
||||
userOnboardingUpdate: UserOnboardingUpdate,
|
||||
options?: RequestInit,
|
||||
): Promise<patchV1UpdateOnboardingProgressResponse> => {
|
||||
return customMutator<patchV1UpdateOnboardingProgressResponse>(
|
||||
getPatchV1UpdateOnboardingProgressUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(userOnboardingUpdate),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPatchV1UpdateOnboardingProgressMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>,
|
||||
TError,
|
||||
{ data: UserOnboardingUpdate },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>,
|
||||
TError,
|
||||
{ data: UserOnboardingUpdate },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["patchV1UpdateOnboardingProgress"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>,
|
||||
{ data: UserOnboardingUpdate }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return patchV1UpdateOnboardingProgress(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PatchV1UpdateOnboardingProgressMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>
|
||||
>;
|
||||
export type PatchV1UpdateOnboardingProgressMutationBody = UserOnboardingUpdate;
|
||||
export type PatchV1UpdateOnboardingProgressMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Update onboarding progress
|
||||
*/
|
||||
export const usePatchV1UpdateOnboardingProgress = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>,
|
||||
TError,
|
||||
{ data: UserOnboardingUpdate },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof patchV1UpdateOnboardingProgress>>,
|
||||
TError,
|
||||
{ data: UserOnboardingUpdate },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPatchV1UpdateOnboardingProgressMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary Get recommended agents
|
||||
*/
|
||||
export type getV1GetRecommendedAgentsResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1GetRecommendedAgentsResponseComposite =
|
||||
getV1GetRecommendedAgentsResponse200;
|
||||
|
||||
export type getV1GetRecommendedAgentsResponse =
|
||||
getV1GetRecommendedAgentsResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1GetRecommendedAgentsUrl = () => {
|
||||
return `/api/onboarding/agents`;
|
||||
};
|
||||
|
||||
export const getV1GetRecommendedAgents = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1GetRecommendedAgentsResponse> => {
|
||||
return customMutator<getV1GetRecommendedAgentsResponse>(
|
||||
getGetV1GetRecommendedAgentsUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1GetRecommendedAgentsQueryKey = () => {
|
||||
return [`/api/onboarding/agents`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1GetRecommendedAgentsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1GetRecommendedAgentsQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>
|
||||
> = ({ signal }) => getV1GetRecommendedAgents({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1GetRecommendedAgentsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>
|
||||
>;
|
||||
export type GetV1GetRecommendedAgentsQueryError = unknown;
|
||||
|
||||
export function useGetV1GetRecommendedAgents<
|
||||
TData = Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetRecommendedAgents<
|
||||
TData = Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1GetRecommendedAgents<
|
||||
TData = Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get recommended agents
|
||||
*/
|
||||
|
||||
export function useGetV1GetRecommendedAgents<
|
||||
TData = Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1GetRecommendedAgents>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1GetRecommendedAgentsQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Check onboarding enabled
|
||||
*/
|
||||
export type getV1CheckOnboardingEnabledResponse200 = {
|
||||
data: unknown;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1CheckOnboardingEnabledResponseComposite =
|
||||
getV1CheckOnboardingEnabledResponse200;
|
||||
|
||||
export type getV1CheckOnboardingEnabledResponse =
|
||||
getV1CheckOnboardingEnabledResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1CheckOnboardingEnabledUrl = () => {
|
||||
return `/api/onboarding/enabled`;
|
||||
};
|
||||
|
||||
export const getV1CheckOnboardingEnabled = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1CheckOnboardingEnabledResponse> => {
|
||||
return customMutator<getV1CheckOnboardingEnabledResponse>(
|
||||
getGetV1CheckOnboardingEnabledUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1CheckOnboardingEnabledQueryKey = () => {
|
||||
return [`/api/onboarding/enabled`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1CheckOnboardingEnabledQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1CheckOnboardingEnabledQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>
|
||||
> = ({ signal }) =>
|
||||
getV1CheckOnboardingEnabled({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1CheckOnboardingEnabledQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>
|
||||
>;
|
||||
export type GetV1CheckOnboardingEnabledQueryError = unknown;
|
||||
|
||||
export function useGetV1CheckOnboardingEnabled<
|
||||
TData = Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1CheckOnboardingEnabled<
|
||||
TData = Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1CheckOnboardingEnabled<
|
||||
TData = Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Check onboarding enabled
|
||||
*/
|
||||
|
||||
export function useGetV1CheckOnboardingEnabled<
|
||||
TData = Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1CheckOnboardingEnabled>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1CheckOnboardingEnabledQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
139
autogpt_platform/frontend/src/app/api/__generated__/endpoints/otto/otto.ts
generated
Normal file
139
autogpt_platform/frontend/src/app/api/__generated__/endpoints/otto/otto.ts
generated
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type {
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { ApiResponse } from "../../models/apiResponse";
|
||||
|
||||
import type { ChatRequest } from "../../models/chatRequest";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* Proxy requests to Otto API while adding necessary security headers and logging.
|
||||
Requires an authenticated user.
|
||||
* @summary Proxy Otto Chat Request
|
||||
*/
|
||||
export type postV2ProxyOttoChatRequestResponse200 = {
|
||||
data: ApiResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2ProxyOttoChatRequestResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2ProxyOttoChatRequestResponseComposite =
|
||||
| postV2ProxyOttoChatRequestResponse200
|
||||
| postV2ProxyOttoChatRequestResponse422;
|
||||
|
||||
export type postV2ProxyOttoChatRequestResponse =
|
||||
postV2ProxyOttoChatRequestResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2ProxyOttoChatRequestUrl = () => {
|
||||
return `/api/otto/ask`;
|
||||
};
|
||||
|
||||
export const postV2ProxyOttoChatRequest = async (
|
||||
chatRequest: ChatRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2ProxyOttoChatRequestResponse> => {
|
||||
return customMutator<postV2ProxyOttoChatRequestResponse>(
|
||||
getPostV2ProxyOttoChatRequestUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(chatRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2ProxyOttoChatRequestMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>,
|
||||
TError,
|
||||
{ data: ChatRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>,
|
||||
TError,
|
||||
{ data: ChatRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2ProxyOttoChatRequest"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>,
|
||||
{ data: ChatRequest }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV2ProxyOttoChatRequest(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2ProxyOttoChatRequestMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>
|
||||
>;
|
||||
export type PostV2ProxyOttoChatRequestMutationBody = ChatRequest;
|
||||
export type PostV2ProxyOttoChatRequestMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Proxy Otto Chat Request
|
||||
*/
|
||||
export const usePostV2ProxyOttoChatRequest = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>,
|
||||
TError,
|
||||
{ data: ChatRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2ProxyOttoChatRequest>>,
|
||||
TError,
|
||||
{ data: ChatRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV2ProxyOttoChatRequestMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
895
autogpt_platform/frontend/src/app/api/__generated__/endpoints/presets/presets.ts
generated
Normal file
895
autogpt_platform/frontend/src/app/api/__generated__/endpoints/presets/presets.ts
generated
Normal file
@@ -0,0 +1,895 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { BodyPostV2ExecuteAPreset } from "../../models/bodyPostV2ExecuteAPreset";
|
||||
|
||||
import type { GetV2ListPresetsParams } from "../../models/getV2ListPresetsParams";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { LibraryAgentPreset } from "../../models/libraryAgentPreset";
|
||||
|
||||
import type { LibraryAgentPresetResponse } from "../../models/libraryAgentPresetResponse";
|
||||
|
||||
import type { LibraryAgentPresetUpdatable } from "../../models/libraryAgentPresetUpdatable";
|
||||
|
||||
import type { PostV2CreateANewPresetBody } from "../../models/postV2CreateANewPresetBody";
|
||||
|
||||
import type { PostV2ExecuteAPreset200 } from "../../models/postV2ExecuteAPreset200";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* Retrieve a paginated list of presets for the current user.
|
||||
* @summary List presets
|
||||
*/
|
||||
export type getV2ListPresetsResponse200 = {
|
||||
data: LibraryAgentPresetResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV2ListPresetsResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV2ListPresetsResponseComposite =
|
||||
| getV2ListPresetsResponse200
|
||||
| getV2ListPresetsResponse422;
|
||||
|
||||
export type getV2ListPresetsResponse = getV2ListPresetsResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV2ListPresetsUrl = (params: GetV2ListPresetsParams) => {
|
||||
const normalizedParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params || {}).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
normalizedParams.append(key, value === null ? "null" : value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
const stringifiedParams = normalizedParams.toString();
|
||||
|
||||
return stringifiedParams.length > 0
|
||||
? `/api/library/presets?${stringifiedParams}`
|
||||
: `/api/library/presets`;
|
||||
};
|
||||
|
||||
export const getV2ListPresets = async (
|
||||
params: GetV2ListPresetsParams,
|
||||
options?: RequestInit,
|
||||
): Promise<getV2ListPresetsResponse> => {
|
||||
return customMutator<getV2ListPresetsResponse>(
|
||||
getGetV2ListPresetsUrl(params),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV2ListPresetsQueryKey = (params: GetV2ListPresetsParams) => {
|
||||
return [`/api/library/presets`, ...(params ? [params] : [])] as const;
|
||||
};
|
||||
|
||||
export const getGetV2ListPresetsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: GetV2ListPresetsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV2ListPresetsQueryKey(params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>
|
||||
> = ({ signal }) => getV2ListPresets(params, { signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV2ListPresetsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>
|
||||
>;
|
||||
export type GetV2ListPresetsQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV2ListPresets<
|
||||
TData = Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: GetV2ListPresetsParams,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2ListPresets<
|
||||
TData = Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: GetV2ListPresetsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2ListPresets<
|
||||
TData = Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: GetV2ListPresetsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary List presets
|
||||
*/
|
||||
|
||||
export function useGetV2ListPresets<
|
||||
TData = Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
params: GetV2ListPresetsParams,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2ListPresets>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV2ListPresetsQueryOptions(params, options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new preset for the current user.
|
||||
* @summary Create a new preset
|
||||
*/
|
||||
export type postV2CreateANewPresetResponse200 = {
|
||||
data: LibraryAgentPreset;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2CreateANewPresetResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2CreateANewPresetResponseComposite =
|
||||
| postV2CreateANewPresetResponse200
|
||||
| postV2CreateANewPresetResponse422;
|
||||
|
||||
export type postV2CreateANewPresetResponse =
|
||||
postV2CreateANewPresetResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2CreateANewPresetUrl = () => {
|
||||
return `/api/library/presets`;
|
||||
};
|
||||
|
||||
export const postV2CreateANewPreset = async (
|
||||
postV2CreateANewPresetBody: PostV2CreateANewPresetBody,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2CreateANewPresetResponse> => {
|
||||
return customMutator<postV2CreateANewPresetResponse>(
|
||||
getPostV2CreateANewPresetUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(postV2CreateANewPresetBody),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2CreateANewPresetMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>,
|
||||
TError,
|
||||
{ data: PostV2CreateANewPresetBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>,
|
||||
TError,
|
||||
{ data: PostV2CreateANewPresetBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2CreateANewPreset"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>,
|
||||
{ data: PostV2CreateANewPresetBody }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV2CreateANewPreset(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2CreateANewPresetMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>
|
||||
>;
|
||||
export type PostV2CreateANewPresetMutationBody = PostV2CreateANewPresetBody;
|
||||
export type PostV2CreateANewPresetMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Create a new preset
|
||||
*/
|
||||
export const usePostV2CreateANewPreset = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>,
|
||||
TError,
|
||||
{ data: PostV2CreateANewPresetBody },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2CreateANewPreset>>,
|
||||
TError,
|
||||
{ data: PostV2CreateANewPresetBody },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV2CreateANewPresetMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Retrieve details for a specific preset by its ID.
|
||||
* @summary Get a specific preset
|
||||
*/
|
||||
export type getV2GetASpecificPresetResponse200 = {
|
||||
data: LibraryAgentPreset;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV2GetASpecificPresetResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV2GetASpecificPresetResponseComposite =
|
||||
| getV2GetASpecificPresetResponse200
|
||||
| getV2GetASpecificPresetResponse422;
|
||||
|
||||
export type getV2GetASpecificPresetResponse =
|
||||
getV2GetASpecificPresetResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV2GetASpecificPresetUrl = (presetId: string) => {
|
||||
return `/api/library/presets/${presetId}`;
|
||||
};
|
||||
|
||||
export const getV2GetASpecificPreset = async (
|
||||
presetId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<getV2GetASpecificPresetResponse> => {
|
||||
return customMutator<getV2GetASpecificPresetResponse>(
|
||||
getGetV2GetASpecificPresetUrl(presetId),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV2GetASpecificPresetQueryKey = (presetId: string) => {
|
||||
return [`/api/library/presets/${presetId}`] as const;
|
||||
};
|
||||
|
||||
export const getGetV2GetASpecificPresetQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
presetId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV2GetASpecificPresetQueryKey(presetId);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>
|
||||
> = ({ signal }) =>
|
||||
getV2GetASpecificPreset(presetId, { signal, ...requestOptions });
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!presetId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV2GetASpecificPresetQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>
|
||||
>;
|
||||
export type GetV2GetASpecificPresetQueryError = HTTPValidationError;
|
||||
|
||||
export function useGetV2GetASpecificPreset<
|
||||
TData = Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
presetId: string,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetASpecificPreset<
|
||||
TData = Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
presetId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV2GetASpecificPreset<
|
||||
TData = Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
presetId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary Get a specific preset
|
||||
*/
|
||||
|
||||
export function useGetV2GetASpecificPreset<
|
||||
TData = Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
presetId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV2GetASpecificPreset>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV2GetASpecificPresetQueryOptions(
|
||||
presetId,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing preset by its ID.
|
||||
* @summary Update an existing preset
|
||||
*/
|
||||
export type patchV2UpdateAnExistingPresetResponse200 = {
|
||||
data: LibraryAgentPreset;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type patchV2UpdateAnExistingPresetResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type patchV2UpdateAnExistingPresetResponseComposite =
|
||||
| patchV2UpdateAnExistingPresetResponse200
|
||||
| patchV2UpdateAnExistingPresetResponse422;
|
||||
|
||||
export type patchV2UpdateAnExistingPresetResponse =
|
||||
patchV2UpdateAnExistingPresetResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPatchV2UpdateAnExistingPresetUrl = (presetId: string) => {
|
||||
return `/api/library/presets/${presetId}`;
|
||||
};
|
||||
|
||||
export const patchV2UpdateAnExistingPreset = async (
|
||||
presetId: string,
|
||||
libraryAgentPresetUpdatable: LibraryAgentPresetUpdatable,
|
||||
options?: RequestInit,
|
||||
): Promise<patchV2UpdateAnExistingPresetResponse> => {
|
||||
return customMutator<patchV2UpdateAnExistingPresetResponse>(
|
||||
getPatchV2UpdateAnExistingPresetUrl(presetId),
|
||||
{
|
||||
...options,
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(libraryAgentPresetUpdatable),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPatchV2UpdateAnExistingPresetMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: LibraryAgentPresetUpdatable },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: LibraryAgentPresetUpdatable },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["patchV2UpdateAnExistingPreset"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>,
|
||||
{ presetId: string; data: LibraryAgentPresetUpdatable }
|
||||
> = (props) => {
|
||||
const { presetId, data } = props ?? {};
|
||||
|
||||
return patchV2UpdateAnExistingPreset(presetId, data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PatchV2UpdateAnExistingPresetMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>
|
||||
>;
|
||||
export type PatchV2UpdateAnExistingPresetMutationBody =
|
||||
LibraryAgentPresetUpdatable;
|
||||
export type PatchV2UpdateAnExistingPresetMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Update an existing preset
|
||||
*/
|
||||
export const usePatchV2UpdateAnExistingPreset = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: LibraryAgentPresetUpdatable },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof patchV2UpdateAnExistingPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: LibraryAgentPresetUpdatable },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPatchV2UpdateAnExistingPresetMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Delete an existing preset by its ID.
|
||||
* @summary Delete a preset
|
||||
*/
|
||||
export type deleteV2DeleteAPresetResponse204 = {
|
||||
data: void;
|
||||
status: 204;
|
||||
};
|
||||
|
||||
export type deleteV2DeleteAPresetResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type deleteV2DeleteAPresetResponseComposite =
|
||||
| deleteV2DeleteAPresetResponse204
|
||||
| deleteV2DeleteAPresetResponse422;
|
||||
|
||||
export type deleteV2DeleteAPresetResponse =
|
||||
deleteV2DeleteAPresetResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getDeleteV2DeleteAPresetUrl = (presetId: string) => {
|
||||
return `/api/library/presets/${presetId}`;
|
||||
};
|
||||
|
||||
export const deleteV2DeleteAPreset = async (
|
||||
presetId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<deleteV2DeleteAPresetResponse> => {
|
||||
return customMutator<deleteV2DeleteAPresetResponse>(
|
||||
getDeleteV2DeleteAPresetUrl(presetId),
|
||||
{
|
||||
...options,
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getDeleteV2DeleteAPresetMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["deleteV2DeleteAPreset"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>,
|
||||
{ presetId: string }
|
||||
> = (props) => {
|
||||
const { presetId } = props ?? {};
|
||||
|
||||
return deleteV2DeleteAPreset(presetId, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DeleteV2DeleteAPresetMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>
|
||||
>;
|
||||
|
||||
export type DeleteV2DeleteAPresetMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Delete a preset
|
||||
*/
|
||||
export const useDeleteV2DeleteAPreset = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof deleteV2DeleteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getDeleteV2DeleteAPresetMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* Execute a preset with the given graph and node input for the current user.
|
||||
* @summary Execute a preset
|
||||
*/
|
||||
export type postV2ExecuteAPresetResponse200 = {
|
||||
data: PostV2ExecuteAPreset200;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2ExecuteAPresetResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2ExecuteAPresetResponseComposite =
|
||||
| postV2ExecuteAPresetResponse200
|
||||
| postV2ExecuteAPresetResponse422;
|
||||
|
||||
export type postV2ExecuteAPresetResponse =
|
||||
postV2ExecuteAPresetResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2ExecuteAPresetUrl = (presetId: string) => {
|
||||
return `/api/library/presets/${presetId}/execute`;
|
||||
};
|
||||
|
||||
export const postV2ExecuteAPreset = async (
|
||||
presetId: string,
|
||||
bodyPostV2ExecuteAPreset: BodyPostV2ExecuteAPreset,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2ExecuteAPresetResponse> => {
|
||||
return customMutator<postV2ExecuteAPresetResponse>(
|
||||
getPostV2ExecuteAPresetUrl(presetId),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(bodyPostV2ExecuteAPreset),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2ExecuteAPresetMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: BodyPostV2ExecuteAPreset },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: BodyPostV2ExecuteAPreset },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2ExecuteAPreset"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>,
|
||||
{ presetId: string; data: BodyPostV2ExecuteAPreset }
|
||||
> = (props) => {
|
||||
const { presetId, data } = props ?? {};
|
||||
|
||||
return postV2ExecuteAPreset(presetId, data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2ExecuteAPresetMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>
|
||||
>;
|
||||
export type PostV2ExecuteAPresetMutationBody = BodyPostV2ExecuteAPreset;
|
||||
export type PostV2ExecuteAPresetMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Execute a preset
|
||||
*/
|
||||
export const usePostV2ExecuteAPreset = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: BodyPostV2ExecuteAPreset },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2ExecuteAPreset>>,
|
||||
TError,
|
||||
{ presetId: string; data: BodyPostV2ExecuteAPreset },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV2ExecuteAPresetMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
640
autogpt_platform/frontend/src/app/api/__generated__/endpoints/schedules/schedules.ts
generated
Normal file
640
autogpt_platform/frontend/src/app/api/__generated__/endpoints/schedules/schedules.ts
generated
Normal file
@@ -0,0 +1,640 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type {
|
||||
DataTag,
|
||||
DefinedInitialDataOptions,
|
||||
DefinedUseQueryResult,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UndefinedInitialDataOptions,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { DeleteV1DeleteExecutionSchedule200 } from "../../models/deleteV1DeleteExecutionSchedule200";
|
||||
|
||||
import type { GraphExecutionJobInfo } from "../../models/graphExecutionJobInfo";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { ScheduleCreationRequest } from "../../models/scheduleCreationRequest";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* @summary Create execution schedule
|
||||
*/
|
||||
export type postV1CreateExecutionScheduleResponse200 = {
|
||||
data: GraphExecutionJobInfo;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV1CreateExecutionScheduleResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV1CreateExecutionScheduleResponseComposite =
|
||||
| postV1CreateExecutionScheduleResponse200
|
||||
| postV1CreateExecutionScheduleResponse422;
|
||||
|
||||
export type postV1CreateExecutionScheduleResponse =
|
||||
postV1CreateExecutionScheduleResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV1CreateExecutionScheduleUrl = (graphId: string) => {
|
||||
return `/api/graphs/${graphId}/schedules`;
|
||||
};
|
||||
|
||||
export const postV1CreateExecutionSchedule = async (
|
||||
graphId: string,
|
||||
scheduleCreationRequest: ScheduleCreationRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV1CreateExecutionScheduleResponse> => {
|
||||
return customMutator<postV1CreateExecutionScheduleResponse>(
|
||||
getPostV1CreateExecutionScheduleUrl(graphId),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(scheduleCreationRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV1CreateExecutionScheduleMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>,
|
||||
TError,
|
||||
{ graphId: string; data: ScheduleCreationRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>,
|
||||
TError,
|
||||
{ graphId: string; data: ScheduleCreationRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV1CreateExecutionSchedule"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>,
|
||||
{ graphId: string; data: ScheduleCreationRequest }
|
||||
> = (props) => {
|
||||
const { graphId, data } = props ?? {};
|
||||
|
||||
return postV1CreateExecutionSchedule(graphId, data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV1CreateExecutionScheduleMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>
|
||||
>;
|
||||
export type PostV1CreateExecutionScheduleMutationBody = ScheduleCreationRequest;
|
||||
export type PostV1CreateExecutionScheduleMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Create execution schedule
|
||||
*/
|
||||
export const usePostV1CreateExecutionSchedule = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>,
|
||||
TError,
|
||||
{ graphId: string; data: ScheduleCreationRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV1CreateExecutionSchedule>>,
|
||||
TError,
|
||||
{ graphId: string; data: ScheduleCreationRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getPostV1CreateExecutionScheduleMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
/**
|
||||
* @summary List execution schedules for a graph
|
||||
*/
|
||||
export type getV1ListExecutionSchedulesForAGraphResponse200 = {
|
||||
data: GraphExecutionJobInfo[];
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1ListExecutionSchedulesForAGraphResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type getV1ListExecutionSchedulesForAGraphResponseComposite =
|
||||
| getV1ListExecutionSchedulesForAGraphResponse200
|
||||
| getV1ListExecutionSchedulesForAGraphResponse422;
|
||||
|
||||
export type getV1ListExecutionSchedulesForAGraphResponse =
|
||||
getV1ListExecutionSchedulesForAGraphResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAGraphUrl = (graphId: string) => {
|
||||
return `/api/graphs/${graphId}/schedules`;
|
||||
};
|
||||
|
||||
export const getV1ListExecutionSchedulesForAGraph = async (
|
||||
graphId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<getV1ListExecutionSchedulesForAGraphResponse> => {
|
||||
return customMutator<getV1ListExecutionSchedulesForAGraphResponse>(
|
||||
getGetV1ListExecutionSchedulesForAGraphUrl(graphId),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAGraphQueryKey = (
|
||||
graphId: string,
|
||||
) => {
|
||||
return [`/api/graphs/${graphId}/schedules`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAGraphQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
graphId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ??
|
||||
getGetV1ListExecutionSchedulesForAGraphQueryKey(graphId);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>
|
||||
> = ({ signal }) =>
|
||||
getV1ListExecutionSchedulesForAGraph(graphId, {
|
||||
signal,
|
||||
...requestOptions,
|
||||
});
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: !!graphId,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1ListExecutionSchedulesForAGraphQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>
|
||||
>;
|
||||
export type GetV1ListExecutionSchedulesForAGraphQueryError =
|
||||
HTTPValidationError;
|
||||
|
||||
export function useGetV1ListExecutionSchedulesForAGraph<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
graphId: string,
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListExecutionSchedulesForAGraph<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
graphId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListExecutionSchedulesForAGraph<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
graphId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary List execution schedules for a graph
|
||||
*/
|
||||
|
||||
export function useGetV1ListExecutionSchedulesForAGraph<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError = HTTPValidationError,
|
||||
>(
|
||||
graphId: string,
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAGraph>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions = getGetV1ListExecutionSchedulesForAGraphQueryOptions(
|
||||
graphId,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List execution schedules for a user
|
||||
*/
|
||||
export type getV1ListExecutionSchedulesForAUserResponse200 = {
|
||||
data: GraphExecutionJobInfo[];
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type getV1ListExecutionSchedulesForAUserResponseComposite =
|
||||
getV1ListExecutionSchedulesForAUserResponse200;
|
||||
|
||||
export type getV1ListExecutionSchedulesForAUserResponse =
|
||||
getV1ListExecutionSchedulesForAUserResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAUserUrl = () => {
|
||||
return `/api/schedules`;
|
||||
};
|
||||
|
||||
export const getV1ListExecutionSchedulesForAUser = async (
|
||||
options?: RequestInit,
|
||||
): Promise<getV1ListExecutionSchedulesForAUserResponse> => {
|
||||
return customMutator<getV1ListExecutionSchedulesForAUserResponse>(
|
||||
getGetV1ListExecutionSchedulesForAUserUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAUserQueryKey = () => {
|
||||
return [`/api/schedules`] as const;
|
||||
};
|
||||
|
||||
export const getGetV1ListExecutionSchedulesForAUserQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError = unknown,
|
||||
>(options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}) => {
|
||||
const { query: queryOptions, request: requestOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetV1ListExecutionSchedulesForAUserQueryKey();
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>
|
||||
> = ({ signal }) =>
|
||||
getV1ListExecutionSchedulesForAUser({ signal, ...requestOptions });
|
||||
|
||||
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
};
|
||||
|
||||
export type GetV1ListExecutionSchedulesForAUserQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>
|
||||
>;
|
||||
export type GetV1ListExecutionSchedulesForAUserQueryError = unknown;
|
||||
|
||||
export function useGetV1ListExecutionSchedulesForAUser<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options: {
|
||||
query: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
DefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): DefinedUseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListExecutionSchedulesForAUser<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
> &
|
||||
Pick<
|
||||
UndefinedInitialDataOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>
|
||||
>,
|
||||
"initialData"
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
export function useGetV1ListExecutionSchedulesForAUser<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
};
|
||||
/**
|
||||
* @summary List execution schedules for a user
|
||||
*/
|
||||
|
||||
export function useGetV1ListExecutionSchedulesForAUser<
|
||||
TData = Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError = unknown,
|
||||
>(
|
||||
options?: {
|
||||
query?: Partial<
|
||||
UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getV1ListExecutionSchedulesForAUser>>,
|
||||
TError,
|
||||
TData
|
||||
>
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseQueryResult<TData, TError> & {
|
||||
queryKey: DataTag<QueryKey, TData, TError>;
|
||||
} {
|
||||
const queryOptions =
|
||||
getGetV1ListExecutionSchedulesForAUserQueryOptions(options);
|
||||
|
||||
const query = useQuery(queryOptions, queryClient) as UseQueryResult<
|
||||
TData,
|
||||
TError
|
||||
> & { queryKey: DataTag<QueryKey, TData, TError> };
|
||||
|
||||
query.queryKey = queryOptions.queryKey;
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Delete execution schedule
|
||||
*/
|
||||
export type deleteV1DeleteExecutionScheduleResponse200 = {
|
||||
data: DeleteV1DeleteExecutionSchedule200;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type deleteV1DeleteExecutionScheduleResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type deleteV1DeleteExecutionScheduleResponseComposite =
|
||||
| deleteV1DeleteExecutionScheduleResponse200
|
||||
| deleteV1DeleteExecutionScheduleResponse422;
|
||||
|
||||
export type deleteV1DeleteExecutionScheduleResponse =
|
||||
deleteV1DeleteExecutionScheduleResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getDeleteV1DeleteExecutionScheduleUrl = (scheduleId: string) => {
|
||||
return `/api/schedules/${scheduleId}`;
|
||||
};
|
||||
|
||||
export const deleteV1DeleteExecutionSchedule = async (
|
||||
scheduleId: string,
|
||||
options?: RequestInit,
|
||||
): Promise<deleteV1DeleteExecutionScheduleResponse> => {
|
||||
return customMutator<deleteV1DeleteExecutionScheduleResponse>(
|
||||
getDeleteV1DeleteExecutionScheduleUrl(scheduleId),
|
||||
{
|
||||
...options,
|
||||
method: "DELETE",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getDeleteV1DeleteExecutionScheduleMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>,
|
||||
TError,
|
||||
{ scheduleId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>,
|
||||
TError,
|
||||
{ scheduleId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["deleteV1DeleteExecutionSchedule"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>,
|
||||
{ scheduleId: string }
|
||||
> = (props) => {
|
||||
const { scheduleId } = props ?? {};
|
||||
|
||||
return deleteV1DeleteExecutionSchedule(scheduleId, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type DeleteV1DeleteExecutionScheduleMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>
|
||||
>;
|
||||
|
||||
export type DeleteV1DeleteExecutionScheduleMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Delete execution schedule
|
||||
*/
|
||||
export const useDeleteV1DeleteExecutionSchedule = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>,
|
||||
TError,
|
||||
{ scheduleId: string },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof deleteV1DeleteExecutionSchedule>>,
|
||||
TError,
|
||||
{ scheduleId: string },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions =
|
||||
getDeleteV1DeleteExecutionScheduleMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
2841
autogpt_platform/frontend/src/app/api/__generated__/endpoints/store/store.ts
generated
Normal file
2841
autogpt_platform/frontend/src/app/api/__generated__/endpoints/store/store.ts
generated
Normal file
File diff suppressed because it is too large
Load Diff
140
autogpt_platform/frontend/src/app/api/__generated__/endpoints/turnstile/turnstile.ts
generated
Normal file
140
autogpt_platform/frontend/src/app/api/__generated__/endpoints/turnstile/turnstile.ts
generated
Normal file
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type {
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
import type { HTTPValidationError } from "../../models/hTTPValidationError";
|
||||
|
||||
import type { TurnstileVerifyRequest } from "../../models/turnstileVerifyRequest";
|
||||
|
||||
import type { TurnstileVerifyResponse } from "../../models/turnstileVerifyResponse";
|
||||
|
||||
import { customMutator } from "../../../mutators/custom-mutator";
|
||||
|
||||
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
|
||||
|
||||
/**
|
||||
* Verify a Cloudflare Turnstile token.
|
||||
This endpoint verifies a token returned by the Cloudflare Turnstile challenge
|
||||
on the client side. It returns whether the verification was successful.
|
||||
* @summary Verify Turnstile Token
|
||||
*/
|
||||
export type postV2VerifyTurnstileTokenResponse200 = {
|
||||
data: TurnstileVerifyResponse;
|
||||
status: 200;
|
||||
};
|
||||
|
||||
export type postV2VerifyTurnstileTokenResponse422 = {
|
||||
data: HTTPValidationError;
|
||||
status: 422;
|
||||
};
|
||||
|
||||
export type postV2VerifyTurnstileTokenResponseComposite =
|
||||
| postV2VerifyTurnstileTokenResponse200
|
||||
| postV2VerifyTurnstileTokenResponse422;
|
||||
|
||||
export type postV2VerifyTurnstileTokenResponse =
|
||||
postV2VerifyTurnstileTokenResponseComposite & {
|
||||
headers: Headers;
|
||||
};
|
||||
|
||||
export const getPostV2VerifyTurnstileTokenUrl = () => {
|
||||
return `/api/turnstile/verify`;
|
||||
};
|
||||
|
||||
export const postV2VerifyTurnstileToken = async (
|
||||
turnstileVerifyRequest: TurnstileVerifyRequest,
|
||||
options?: RequestInit,
|
||||
): Promise<postV2VerifyTurnstileTokenResponse> => {
|
||||
return customMutator<postV2VerifyTurnstileTokenResponse>(
|
||||
getPostV2VerifyTurnstileTokenUrl(),
|
||||
{
|
||||
...options,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...options?.headers },
|
||||
body: JSON.stringify(turnstileVerifyRequest),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const getPostV2VerifyTurnstileTokenMutationOptions = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>,
|
||||
TError,
|
||||
{ data: TurnstileVerifyRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
}): UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>,
|
||||
TError,
|
||||
{ data: TurnstileVerifyRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationKey = ["postV2VerifyTurnstileToken"];
|
||||
const { mutation: mutationOptions, request: requestOptions } = options
|
||||
? options.mutation &&
|
||||
"mutationKey" in options.mutation &&
|
||||
options.mutation.mutationKey
|
||||
? options
|
||||
: { ...options, mutation: { ...options.mutation, mutationKey } }
|
||||
: { mutation: { mutationKey }, request: undefined };
|
||||
|
||||
const mutationFn: MutationFunction<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>,
|
||||
{ data: TurnstileVerifyRequest }
|
||||
> = (props) => {
|
||||
const { data } = props ?? {};
|
||||
|
||||
return postV2VerifyTurnstileToken(data, requestOptions);
|
||||
};
|
||||
|
||||
return { mutationFn, ...mutationOptions };
|
||||
};
|
||||
|
||||
export type PostV2VerifyTurnstileTokenMutationResult = NonNullable<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>
|
||||
>;
|
||||
export type PostV2VerifyTurnstileTokenMutationBody = TurnstileVerifyRequest;
|
||||
export type PostV2VerifyTurnstileTokenMutationError = HTTPValidationError;
|
||||
|
||||
/**
|
||||
* @summary Verify Turnstile Token
|
||||
*/
|
||||
export const usePostV2VerifyTurnstileToken = <
|
||||
TError = HTTPValidationError,
|
||||
TContext = unknown,
|
||||
>(
|
||||
options?: {
|
||||
mutation?: UseMutationOptions<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>,
|
||||
TError,
|
||||
{ data: TurnstileVerifyRequest },
|
||||
TContext
|
||||
>;
|
||||
request?: SecondParameter<typeof customMutator>;
|
||||
},
|
||||
queryClient?: QueryClient,
|
||||
): UseMutationResult<
|
||||
Awaited<ReturnType<typeof postV2VerifyTurnstileToken>>,
|
||||
TError,
|
||||
{ data: TurnstileVerifyRequest },
|
||||
TContext
|
||||
> => {
|
||||
const mutationOptions = getPostV2VerifyTurnstileTokenMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
};
|
||||
19
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentials.ts
generated
Normal file
19
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentials.ts
generated
Normal file
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { APIKeyCredentialsTitle } from "./aPIKeyCredentialsTitle";
|
||||
import type { APIKeyCredentialsExpiresAt } from "./aPIKeyCredentialsExpiresAt";
|
||||
|
||||
export interface APIKeyCredentials {
|
||||
id?: string;
|
||||
provider: string;
|
||||
title?: APIKeyCredentialsTitle;
|
||||
type?: "api_key";
|
||||
api_key: string;
|
||||
/** Unix timestamp (seconds) indicating when the API key expires (if at all) */
|
||||
expires_at?: APIKeyCredentialsExpiresAt;
|
||||
}
|
||||
12
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentialsExpiresAt.ts
generated
Normal file
12
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentialsExpiresAt.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
/**
|
||||
* Unix timestamp (seconds) indicating when the API key expires (if at all)
|
||||
*/
|
||||
export type APIKeyCredentialsExpiresAt = number | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentialsTitle.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyCredentialsTitle.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyCredentialsTitle = string | null;
|
||||
18
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyPermission.ts
generated
Normal file
18
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyPermission.ts
generated
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyPermission =
|
||||
(typeof APIKeyPermission)[keyof typeof APIKeyPermission];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
export const APIKeyPermission = {
|
||||
EXECUTE_GRAPH: "EXECUTE_GRAPH",
|
||||
READ_GRAPH: "READ_GRAPH",
|
||||
EXECUTE_BLOCK: "EXECUTE_BLOCK",
|
||||
READ_BLOCK: "READ_BLOCK",
|
||||
} as const;
|
||||
16
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyStatus.ts
generated
Normal file
16
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyStatus.ts
generated
Normal file
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyStatus = (typeof APIKeyStatus)[keyof typeof APIKeyStatus];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
export const APIKeyStatus = {
|
||||
ACTIVE: "ACTIVE",
|
||||
REVOKED: "REVOKED",
|
||||
SUSPENDED: "SUSPENDED",
|
||||
} as const;
|
||||
26
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHash.ts
generated
Normal file
26
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHash.ts
generated
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { APIKeyStatus } from "./aPIKeyStatus";
|
||||
import type { APIKeyPermission } from "./aPIKeyPermission";
|
||||
import type { APIKeyWithoutHashLastUsedAt } from "./aPIKeyWithoutHashLastUsedAt";
|
||||
import type { APIKeyWithoutHashRevokedAt } from "./aPIKeyWithoutHashRevokedAt";
|
||||
import type { APIKeyWithoutHashDescription } from "./aPIKeyWithoutHashDescription";
|
||||
|
||||
export interface APIKeyWithoutHash {
|
||||
id: string;
|
||||
name: string;
|
||||
prefix: string;
|
||||
postfix: string;
|
||||
status: APIKeyStatus;
|
||||
permissions: APIKeyPermission[];
|
||||
created_at: string;
|
||||
last_used_at: APIKeyWithoutHashLastUsedAt;
|
||||
revoked_at: APIKeyWithoutHashRevokedAt;
|
||||
description: APIKeyWithoutHashDescription;
|
||||
user_id: string;
|
||||
}
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashDescription.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashDescription.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyWithoutHashDescription = string | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashLastUsedAt.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashLastUsedAt.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyWithoutHashLastUsedAt = string | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashRevokedAt.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/aPIKeyWithoutHashRevokedAt.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type APIKeyWithoutHashRevokedAt = string | null;
|
||||
12
autogpt_platform/frontend/src/app/api/__generated__/models/addUserCreditsResponse.ts
generated
Normal file
12
autogpt_platform/frontend/src/app/api/__generated__/models/addUserCreditsResponse.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export interface AddUserCreditsResponse {
|
||||
new_balance: number;
|
||||
transaction_key: string;
|
||||
}
|
||||
20
autogpt_platform/frontend/src/app/api/__generated__/models/agentExecutionStatus.ts
generated
Normal file
20
autogpt_platform/frontend/src/app/api/__generated__/models/agentExecutionStatus.ts
generated
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type AgentExecutionStatus =
|
||||
(typeof AgentExecutionStatus)[keyof typeof AgentExecutionStatus];
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
export const AgentExecutionStatus = {
|
||||
INCOMPLETE: "INCOMPLETE",
|
||||
QUEUED: "QUEUED",
|
||||
RUNNING: "RUNNING",
|
||||
COMPLETED: "COMPLETED",
|
||||
TERMINATED: "TERMINATED",
|
||||
FAILED: "FAILED",
|
||||
} as const;
|
||||
14
autogpt_platform/frontend/src/app/api/__generated__/models/apiResponse.ts
generated
Normal file
14
autogpt_platform/frontend/src/app/api/__generated__/models/apiResponse.ts
generated
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { Document } from "./document";
|
||||
|
||||
export interface ApiResponse {
|
||||
answer: string;
|
||||
documents: Document[];
|
||||
success: boolean;
|
||||
}
|
||||
12
autogpt_platform/frontend/src/app/api/__generated__/models/autoTopUpConfig.ts
generated
Normal file
12
autogpt_platform/frontend/src/app/api/__generated__/models/autoTopUpConfig.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export interface AutoTopUpConfig {
|
||||
amount: number;
|
||||
threshold: number;
|
||||
}
|
||||
23
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInput.ts
generated
Normal file
23
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInput.ts
generated
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { Node } from "./node";
|
||||
import type { Link } from "./link";
|
||||
import type { BaseGraphInputForkedFromId } from "./baseGraphInputForkedFromId";
|
||||
import type { BaseGraphInputForkedFromVersion } from "./baseGraphInputForkedFromVersion";
|
||||
|
||||
export interface BaseGraphInput {
|
||||
id?: string;
|
||||
version?: number;
|
||||
is_active?: boolean;
|
||||
name: string;
|
||||
description: string;
|
||||
nodes?: Node[];
|
||||
links?: Link[];
|
||||
forked_from_id?: BaseGraphInputForkedFromId;
|
||||
forked_from_version?: BaseGraphInputForkedFromVersion;
|
||||
}
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInputForkedFromId.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInputForkedFromId.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphInputForkedFromId = string | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInputForkedFromVersion.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphInputForkedFromVersion.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphInputForkedFromVersion = number | null;
|
||||
27
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutput.ts
generated
Normal file
27
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutput.ts
generated
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { Node } from "./node";
|
||||
import type { Link } from "./link";
|
||||
import type { BaseGraphOutputForkedFromId } from "./baseGraphOutputForkedFromId";
|
||||
import type { BaseGraphOutputForkedFromVersion } from "./baseGraphOutputForkedFromVersion";
|
||||
import type { BaseGraphOutputInputSchema } from "./baseGraphOutputInputSchema";
|
||||
import type { BaseGraphOutputOutputSchema } from "./baseGraphOutputOutputSchema";
|
||||
|
||||
export interface BaseGraphOutput {
|
||||
id?: string;
|
||||
version?: number;
|
||||
is_active?: boolean;
|
||||
name: string;
|
||||
description: string;
|
||||
nodes?: Node[];
|
||||
links?: Link[];
|
||||
forked_from_id?: BaseGraphOutputForkedFromId;
|
||||
forked_from_version?: BaseGraphOutputForkedFromVersion;
|
||||
readonly input_schema: BaseGraphOutputInputSchema;
|
||||
readonly output_schema: BaseGraphOutputOutputSchema;
|
||||
}
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputForkedFromId.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputForkedFromId.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphOutputForkedFromId = string | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputForkedFromVersion.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputForkedFromVersion.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphOutputForkedFromVersion = number | null;
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputInputSchema.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputInputSchema.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphOutputInputSchema = { [key: string]: unknown };
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputOutputSchema.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/baseGraphOutputOutputSchema.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BaseGraphOutputOutputSchema = { [key: string]: unknown };
|
||||
12
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1Callback.ts
generated
Normal file
12
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1Callback.ts
generated
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export interface BodyPostV1Callback {
|
||||
code: string;
|
||||
state_token: string;
|
||||
}
|
||||
14
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1ExecuteGraphAgent.ts
generated
Normal file
14
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1ExecuteGraphAgent.ts
generated
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { BodyPostV1ExecuteGraphAgentInputs } from "./bodyPostV1ExecuteGraphAgentInputs";
|
||||
import type { BodyPostV1ExecuteGraphAgentCredentialsInputs } from "./bodyPostV1ExecuteGraphAgentCredentialsInputs";
|
||||
|
||||
export interface BodyPostV1ExecuteGraphAgent {
|
||||
inputs?: BodyPostV1ExecuteGraphAgentInputs;
|
||||
credentials_inputs?: BodyPostV1ExecuteGraphAgentCredentialsInputs;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
import type { CredentialsMetaInput } from "./credentialsMetaInput";
|
||||
|
||||
export type BodyPostV1ExecuteGraphAgentCredentialsInputs = {
|
||||
[key: string]: CredentialsMetaInput;
|
||||
};
|
||||
9
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1ExecuteGraphAgentInputs.ts
generated
Normal file
9
autogpt_platform/frontend/src/app/api/__generated__/models/bodyPostV1ExecuteGraphAgentInputs.ts
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Generated by orval v7.10.0 🍺
|
||||
* Do not edit manually.
|
||||
* AutoGPT Agent Server
|
||||
* This server is used to execute agents that are created by the AutoGPT system.
|
||||
* OpenAPI spec version: 0.1
|
||||
*/
|
||||
|
||||
export type BodyPostV1ExecuteGraphAgentInputs = { [key: string]: unknown };
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user