> ## Documentation Index
> Fetch the complete documentation index at: https://docs.profy.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Task lifecycle, agent dispatch, and paid results

> How Profy orchestrates user tasks from creation through agent dispatch to paid result delivery, including callbacks and the pay-to-view result model.

# Task Orchestration

The task system manages the full lifecycle of user-submitted work requests — from creation through agent dispatch to paid result delivery. Tasks bridge the gap between user intent and AI agent execution.

## Overview

```mermaid theme={null}
flowchart LR
    subgraph User
        Create[Create Task]
        Submit[Submit Task]
        Pay[Pay for Result]
        View[View Full Result]
    end

    subgraph Core["Core API"]
        TS[Task Service]
        Dispatch[Agent Dispatch]
        Callback[Callback Handler]
    end

    subgraph Agent["Agent Engine"]
        AI[AI Processing]
    end

    subgraph Finance
        Credits[Credit System]
    end

    Create --> TS
    Submit --> Dispatch
    Dispatch -->|"AGENT_INVOKE_URL"| AI
    AI -->|"POST /internal/task/callback"| Callback
    Callback --> TS
    Pay --> Credits
    Credits --> View
```

## Task Lifecycle

Every task progresses through a defined state machine:

```mermaid theme={null}
stateDiagram-v2
    [*] --> PENDING: create
    PENDING --> RUNNING: submit
    PENDING --> CANCELLED: delete
    RUNNING --> COMPLETED: agent callback (success)
    RUNNING --> FAILED: agent callback (error)
    COMPLETED --> PAID: pay (deduct credits)
    CANCELLED --> [*]
    FAILED --> [*]
    PAID --> [*]
```

### Task States

| State       | Description                                    |
| ----------- | ---------------------------------------------- |
| `PENDING`   | Task created, not yet submitted for processing |
| `RUNNING`   | Submitted to agent engine, awaiting result     |
| `COMPLETED` | Agent returned a result, available for viewing |
| `FAILED`    | Agent processing encountered an error          |
| `CANCELLED` | Task deleted by user before completion         |

### Payment States

| State      | Description                             |
| ---------- | --------------------------------------- |
| `UNPAID`   | Result available but not yet purchased  |
| `PAID`     | User paid credits to unlock full result |
| `REFUNDED` | Payment reversed                        |

## API Endpoints

| Method | Endpoint           | Description                         |
| ------ | ------------------ | ----------------------------------- |
| `POST` | `/api/task/create` | Create a new task                   |
| `POST` | `/api/task/submit` | Submit task to agent for processing |
| `POST` | `/api/task/list`   | List user's tasks with pagination   |
| `POST` | `/api/task/result` | Get task result (preview or full)   |
| `POST` | `/api/task/pay`    | Pay credits to unlock full result   |
| `POST` | `/api/task/rename` | Rename a task                       |
| `POST` | `/api/task/pin`    | Pin/unpin a task                    |
| `POST` | `/api/task/delete` | Delete (cancel) a task              |

All endpoints require JWT authentication.

## Agent Dispatch

When a task is submitted, the Core API dispatches it to the configured agent engine.

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant C as Core API
    participant R as Redis
    participant A as Agent Engine
    participant D as PostgreSQL

    U->>C: POST /api/task/submit {taskUuid}
    C->>D: Update status → RUNNING
    C->>A: POST {AGENT_INVOKE_URL} with task payload
    A->>A: Process task asynchronously

    Note over A: Agent completes work

    A->>C: POST /internal/task/callback
    C->>D: Store result, status → COMPLETED
    C-->>A: 200 OK
```

### Configuration

| Environment Variable | Description                                    |
| -------------------- | ---------------------------------------------- |
| `AGENT_INVOKE_URL`   | URL of the agent engine's task intake endpoint |

When `AGENT_INVOKE_URL` is not configured, the system enters **test mode** — tasks complete immediately with mock data, useful for development and testing.

### Agent Callback

The agent engine reports results asynchronously via:

```
POST /internal/task/callback
```

This is an internal-only route, accessible only from the private network. The callback payload includes the task identifier, result data, and success/failure status.

## Pay-to-View Model

Task results use a two-tier visibility model:

| Access Level | Content                                       | Auth Required       |
| ------------ | --------------------------------------------- | ------------------- |
| **Preview**  | `resultPreview` — summary or truncated result | JWT (task owner)    |
| **Full**     | `resultFull` — complete result data           | JWT + `PAID` status |

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant C as Core API
    participant F as Finance
    participant D as PostgreSQL

    U->>C: POST /api/task/result {taskUuid}
    C->>D: Fetch task
    alt PayStatus = PAID
        C-->>U: {resultPreview, resultFull}
    else PayStatus = UNPAID
        C-->>U: {resultPreview}
        U->>C: POST /api/task/pay {taskUuid}
        C->>F: Deduct credits
        F-->>C: Success
        C->>D: Update payStatus → PAID
        C-->>U: {resultPreview, resultFull}
    end
```

## Task Management

Beyond the core lifecycle, users can organize their tasks:

| Action     | Endpoint                | Description                      |
| ---------- | ----------------------- | -------------------------------- |
| **Rename** | `POST /api/task/rename` | Change task display name         |
| **Pin**    | `POST /api/task/pin`    | Pin/unpin for quick access       |
| **Delete** | `POST /api/task/delete` | Cancel and remove a pending task |
| **List**   | `POST /api/task/list`   | Paginated list with filters      |

## File Attachments

Tasks can reference files stored in S3. The file service provides:

| Method   | Endpoint                       | Description       |
| -------- | ------------------------------ | ----------------- |
| `POST`   | `/api/file/upload`             | Upload file to S3 |
| `GET`    | `/api/file/download/:fileUuid` | Download a file   |
| `DELETE` | `/api/file/:fileUuid`          | Delete a file     |

## Related Pages

<CardGroup cols={2}>
  <Card title="Finance & Payments" icon="credit-card" href="/en/documentation/finance">
    Credit consumption powers the pay-to-view model
  </Card>

  <Card title="Agent Platform" icon="robot" href="/en/documentation/agent">
    Profy agents process submitted tasks
  </Card>
</CardGroup>
