# https://github.com/refly-ai/refly 项目说明书

生成时间：2026-05-15 13:25:24 UTC

## 目录

- [Project Introduction](#project-introduction)
- [Quick Start Guide](#quick-start-guide)
- [System Architecture](#system-architecture)
- [Project Structure](#project-structure)
- [Workflow Engine](#workflow-engine)
- [Skill Management](#skill-management)
- [Canvas Component](#canvas-component)
- [Copilot Integration](#copilot-integration)
- [API Modules](#api-modules)
- [Authentication and Authorization](#authentication)

<a id='project-introduction'></a>

## Project Introduction

### 相关页面

相关主题：[System Architecture](#system-architecture), [Quick Start Guide](#quick-start-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/refly-ai/refly/blob/main/README.md)
- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
- [packages/layout/README.md](https://github.com/refly-ai/refly/blob/main/packages/layout/README.md)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/components/skill-docs-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/components/skill-docs-tab.tsx)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx)
- [apps/api/src/modules/workflow-app/email-templates.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/workflow-app/email-templates.ts)
</details>

# Project Introduction

## Overview

Refly.ai is a comprehensive workflow automation platform designed for developers and creators. The platform enables users to build, schedule, and automate workflows through a visual canvas interface combined with AI-powered capabilities. Refly.ai provides integrations with popular development tools and supports programmatic access through REST APIs and a Command Line Interface (CLI).

资料来源：[README.md](https://github.com/refly-ai/refly/blob/main/README.md)

## Architecture

The platform follows a modular monorepo architecture with multiple packages organized under a unified structure.

### Package Structure

| Package | Description |
|---------|-------------|
| `packages/layout` | Reusable page layout components for consistent UI structure |
| `packages/cli` | Command-line interface for workflow management and integration |
| `packages/ai-workspace-common` | Shared UI components for canvas, nodes, and integrations |
| `packages/web-core` | Core web application components |
| `packages/stores` | State management using Zustand |
| `apps/api` | Backend REST API service |

资料来源：[packages/layout/README.md](https://github.com/refly-ai/refly/blob/main/packages/layout/README.md)

## Core Features

### Visual Workflow Canvas

The workspace provides a drag-and-drop canvas interface for building workflows. Users can:

- Add and configure various node types including code artifacts
- Connect nodes to define workflow dependencies
- Preview artifacts and outputs directly within the canvas
- Share workflow configurations

```mermaid
graph TD
    A[User Canvas] --> B[Canvas Nodes]
    A --> C[Resource Import]
    A --> D[Integration Docs]
    B --> E[Code Artifact]
    B --> F[Skill Execution]
    E --> G[Renderer]
    F --> H[Action Steps]
    G --> I[Preview Output]
```

资料来源：[packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx)

### Layout System

The application provides two primary layout components:

**PrimaryPageLayout**: Used for main application pages
- Configuration options include title, actions, extra content
- Supports `fixHeight`, `noPaddingY`, `noPaddingX` options

**SecondaryPageLayout**: Designed for detail pages and sub-functional pages
- Includes title, description, and back button support
- Ideal for nested views and detail information

```tsx
<PrimaryPageLayout>
  {({ context, onContextChange }) => (
    <>
      <PrimaryPageLayoutContextUpdater
        title="Page Title"
        actions={<Button>Action Button</Button>}
        deps={[]}
      />
      <div>Page Content</div>
    </>
  )}
</PrimaryPageLayout>
```

资料来源：[packages/layout/README.md](https://github.com/refly-ai/refly/blob/main/packages/layout/README.md)

### Scheduled Workflows

The platform supports scheduled workflow execution with configurable limits based on user subscription plans.

| Feature | Description |
|---------|-------------|
| Schedule Creation | Create time-based automated workflows |
| Limit Management | Enforced limits per subscription tier |
| Schedule Management | View, edit, and disable existing schedules |

资料来源：[packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)

### Template Marketplace

Refly.ai includes a template marketplace where users can publish and discover workflow templates. The platform rewards creators with discount vouchers for publishing templates.

**Email Notification Flow**:

```mermaid
graph LR
    A[User Publishes Template] --> B[Generate Voucher]
    B --> C{Locale Detection}
    C -->|zh| D[Chinese Email Template]
    C -->|en| E[English Email Template]
    D --> F[Send Email]
    E --> F
    F --> G[Creator Receives Discount]
```

资料来源：[apps/api/src/modules/voucher/voucher-email-templates.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/voucher/voucher-email-templates.ts)

## Integrations

### Claude Code Integration

After running `refly init`, skill files are installed to Claude Code's directory structure:

| IDE | Path |
|-----|------|
| Claude Code | `~/.claude/skills/refly/` |
| Antigravity | `~/.antigravity/skills/` |
| OpenCode | `~/.opencode/skills/` |
| Cursor | `~/.cursor/skills/` |
| VS Code | `~/.vscode/skills/` |
| Trae | `~/.trae/skills/` |

This enables AI assistants to:
- Understand Refly workflow concepts
- Use builder mode correctly
- Handle state transitions
- Output deterministic results

资料来源：[packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)

### Webhook Support

The platform provides webhook integration capabilities with comprehensive error handling:

| Error Code | HTTP Status | Description |
|------------|-------------|-------------|
| AUTH_REQUIRED | 401 | Not authenticated |
| BUILDER_NOT_STARTED | 400 | No active builder session |
| VALIDATION_REQUIRED | 400 | Must validate before commit |
| VALIDATION_ERROR | 422 | DAG validation failed |
| DUPLICATE_NODE_ID | 409 | Node ID already exists |
| CYCLE_DETECTED | 422 | Circular dependency detected |
| WORKFLOW_NOT_FOUND | 404 | Workflow does not exist |

资料来源：[packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx)

## CLI Tool

The Refly CLI provides command-line access to workflow management:

### Installation

```bash
npm install -g @refly/cli
```

### Configuration

Configuration is stored in `~/.refly/config.json`:

```json
{
  "version": 1,
  "auth": {
    "apiKey": "...",
    "expiresAt": "..."
  },
  "api": {
    "endpoint": "https://api.refly.ai"
  }
}
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `REFLY_API_KEY` | API key for authentication |
| `REFLY_API_ENDPOINT` | Override API endpoint |

### Key Commands

| Command | Description |
|---------|-------------|
| `refly login` | Authenticate with the platform |
| `refly builder start` | Start a new builder session |
| `refly builder validate` | Validate workflow DAG |
| `refly init` | Initialize Claude Code integration |

资料来源：[packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)

## State Management

The application uses Zustand for state management across the workspace:

**Import Resource Store**: Manages modal visibility, file lists, image lists, and waiting list items.

```typescript
interface ImportResourceState {
  importResourceModalVisible: boolean;
  extensionModalVisible: boolean;
  fileList: FileItem[];
  imageList: ImageItem[];
  selectedMenuItem: ImportResourceMenuItem;
  waitingList: WaitingListItem[];
  scrapeLinks: LinkMeta[];
}
```

资料来源：[packages/stores/src/stores/import-resource.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)

## API Endpoint

The platform exposes a REST API at:

```
https://api.refly.ai
```

Public file access:
```
https://api.refly.ai/v1/drive/file/public/{fileId}
```

资料来源：[apps/api/src/modules/voucher/voucher-email-templates.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/voucher/voucher-email-templates.ts)

## Internationalization

The platform supports multiple locales including:
- English (en)
- Chinese Simplified (zh-CN)
- Chinese Traditional (zh-TW, zh-HK)
- And other locales detected via browser settings

Language detection is used for:
- Email template selection
- UI text rendering
- User-facing notifications

资料来源：[apps/api/src/modules/voucher/voucher-email-templates.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/voucher/voucher-email-templates.ts)

---

<a id='quick-start-guide'></a>

## Quick Start Guide

### 相关页面

相关主题：[Project Introduction](#project-introduction)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
- [scripts/cli-deploy/README.md](https://github.com/refly-ai/refly/blob/main/scripts/cli-deploy/README.md)
- [packages/cli/src/commands/workflow/index.ts](https://github.com/refly-ai/refly/blob/main/packages/cli/src/commands/workflow/index.ts)
- [packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)
- [packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx)
</details>

# Quick Start Guide

## Overview

The Quick Start Guide provides developers and users with the essential steps to begin using Refly, an AI-powered workflow automation platform. This guide covers CLI installation, authentication, workflow creation using Builder mode, workflow execution, and core concepts necessary to start building automated workflows.

Refly's architecture consists of three primary layers: a Command Line Interface (CLI) for local development, a web-based workspace for visual workflow design, and a cloud API for execution and scheduling. The CLI enables developers to build workflows incrementally with local state management, while the web interface provides a graphical canvas for complex workflow design.

资料来源：[packages/cli/README.md:1-20]()

## Prerequisites

Before starting with Refly, ensure the following requirements are met:

| Requirement | Description |
|-------------|-------------|
| Node.js | Version 18 or higher |
| Package Manager | pnpm (recommended) or npm |
| Docker | Required for local development services |
| API Key | Generated from the Refly dashboard |

资料来源：[scripts/cli-deploy/README.md:1-30]()

## Installation

### Installing the CLI

The Refly CLI can be installed via npm or pnpm. After installation, initialize the CLI to set up configuration files and install skill files for Claude Code integration.

```bash
npm install -g @refly/cli
# or
pnpm add -g @refly/cli
```

### Initializing the CLI

Run the initialization command to set up the CLI and install skill files:

```bash
refly init
```

This command performs the following actions:

1. Creates the configuration directory at `~/.refly/`
2. Generates the initial `config.json` file
3. Installs skill files to `~/.claude/skills/refly/`
4. Sets up command shortcuts if the commands directory exists

资料来源：[packages/cli/README.md:1-15]()

## Authentication

### Logging In

Authenticate with the Refly API using your API key:

```bash
refly login
```

This command stores your credentials in `~/.refly/config.json`:

```json
{
  "version": 1,
  "auth": {
    "apiKey": "...",
    "expiresAt": "..."
  },
  "api": {
    "endpoint": "https://api.refly.ai"
  }
}
```

### Checking Authentication Status

Verify your authentication status and view current user information:

```bash
refly status
refly whoami
```

### Environment Variables

Override default configuration using environment variables:

| Variable | Description | Default |
|----------|-------------|---------|
| `REFLY_API_KEY` | API key for authentication | - |
| `REFLY_API_ENDPOINT` | Override API endpoint | `https://api.refly.ai` |

资料来源：[packages/cli/README.md:25-45]()

## Core Concepts

### Builder Mode

Builder mode enables incremental workflow construction with local state management. It uses a deterministic state machine to track workflow progress through defined stages.

```mermaid
graph TD
    IDLE["IDLE"] --> DRAFT["DRAFT"]
    DRAFT --> VALIDATED["VALIDATED"]
    VALIDATED --> COMMITTED["COMMITTED"]
    COMMITTED --> IDLE
    DRAFT --> IDLE
    
    style IDLE fill:#e1f5fe
    style DRAFT fill:#fff3e0
    style VALIDATED fill:#e8f5e9
    style COMMITTED fill:#c8e6c9
```

### Workflow States

| State | Description | Can Transition To |
|-------|-------------|-------------------|
| IDLE | No active builder session | DRAFT |
| DRAFT | Workflow being constructed | IDLE, VALIDATED |
| VALIDATED | DAG validation passed | IDLE, COMMITTED |
| COMMITTED | Workflow saved to server | IDLE |

资料来源：[packages/cli/README.md:48-65]()

### Workflow Components

Refly workflows consist of nodes and connections:

| Component | Description |
|-----------|-------------|
| Nodes | Individual units of work (agents, tools, data transformations) |
| Edges | Connections defining data flow between nodes |
| Variables | Input/output parameters for workflow execution |
| Schedules | Cron-based triggers for automated execution |

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx:1-30]()

## Building a Workflow

### Starting a Builder Session

Begin a new workflow or edit an existing one:

```bash
refly builder start --name "my-workflow"
```

### Adding Nodes

Add nodes to define workflow steps:

```bash
refly builder add-node --node '<json>'
```

Node JSON structure:

```json
{
  "id": "node-001",
  "type": "agent",
  "config": {
    "model": "gpt-4",
    "prompt": "Analyze the input document"
  }
}
```

### Connecting Nodes

Establish data flow between nodes:

```bash
refly builder connect --from "node-001" --to "node-002"
```

### Viewing the Graph

Visualize the current workflow structure:

```bash
refly builder graph
refly builder graph --ascii
```

### Validating the Workflow

Before committing, validate the workflow's DAG structure:

```bash
refly builder validate
```

This checks for:
- Circular dependencies
- Missing required inputs
- Invalid node configurations
- Orphan nodes without connections

### Committing the Workflow

Save the validated workflow to the server:

```bash
refly builder commit
```

### Aborting Changes

Discard all changes and return to IDLE state:

```bash
refly builder abort
```

资料来源：[packages/cli/README.md:47-80]()

## Workflow Management

### Creating Workflows

Create a workflow using the CLI:

```bash
refly workflow create --name "<name>" --spec '<json>'
```

### Listing Workflows

View all available workflows:

```bash
refly workflow list [--limit N]
```

### Retrieving Workflow Details

Get detailed information about a specific workflow:

```bash
refly workflow get <workflowId>
```

### Editing Workflows

Modify an existing workflow:

```bash
refly workflow edit <workflowId> --ops '<json>'
```

### Deleting Workflows

Remove a workflow from the system:

```bash
refly workflow delete <workflowId>
```

资料来源：[packages/cli/src/commands/workflow/index.ts:1-50]()

## Workflow Execution

### Running a Workflow

Execute a workflow with optional input data:

```bash
refly workflow run <workflowId> [--input '<json>']
```

Example with input:

```bash
refly workflow run wf-abc123 --input '{"documentUrl": "https://example.com/doc.pdf"}'
```

### Monitoring Execution Status

Track the progress of a running workflow:

```bash
refly workflow run-status <runId>
```

### Aborting Execution

Stop a running workflow:

```bash
refly workflow abort <runId>
```

### Node Debugging

Test individual node types independently:

```bash
refly node types [--category <category>]
refly node run --type "<nodeType>" --input '<json>'
```

资料来源：[packages/cli/README.md:82-100]()

## Scheduling Workflows

Workflows can be scheduled for automated execution using cron-based triggers.

### Schedule Limits

Different plans have varying limits on scheduled workflows:

| Plan | Maximum Schedules |
|------|-------------------|
| Free | 5 |
| Pro | 25 |
| Enterprise | Unlimited |

### Managing Schedules

When scheduling limits are reached, users can:

1. View existing schedules
2. Disable unused schedules
3. Upgrade to a higher plan

The schedule management interface provides modals for viewing and deactivating schedules.

资料来源：[packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx:1-60]()

## Local Development Setup

### Quick Start Deployment

For developers with an existing repository clone:

```bash
./scripts/cli-deploy/quick-start.sh
```

This script performs:

1. Building the CLI package
2. Starting Docker services (PostgreSQL, Redis)
3. Running database migrations
4. Seeding global tools data
5. Starting the API server
6. Guiding through OAuth login
7. Generating an API key

### Full Deployment

For a complete fresh deployment:

```bash
./scripts/cli-deploy/deploy-cli.sh
```

### Deployment Options

| Option | Description |
|--------|-------------|
| `--skip-build` | Skip building CLI |
| `--skip-services` | Skip Docker services |
| `--skip-seed` | Skip seeding data |
| `--skip-api` | Skip starting API |
| `--skip-auth` | Skip authentication |
| `--refly-dir` | Custom installation directory |
| `--branch` | Use specific Git branch |

资料来源：[scripts/cli-deploy/README.md:10-50]()

## Error Handling

### Common Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| AUTH_REQUIRED | Not authenticated | Run `refly login` |
| BUILDER_NOT_STARTED | No active builder session | Run `refly builder start` |
| VALIDATION_REQUIRED | Must validate before commit | Run `refly builder validate` |
| VALIDATION_ERROR | DAG validation failed | Check error details |
| DUPLICATE_NODE_ID | Node ID already exists | Use unique ID |
| CYCLE_DETECTED | Circular dependency | Remove cycle |
| WORKFLOW_NOT_FOUND | Workflow does not exist | Check workflow ID |

### Builder State Transitions

The builder enforces strict state transitions:

```mermaid
graph LR
    A[IDLE] -->|start| B[DRAFT]
    B -->|validate| C[VALIDATED]
    C -->|commit| D[COMMITTED]
    B -->|abort| A
    C -->|abort| A
    D -->|start| B
```

资料来源：[packages/cli/README.md:100-120]()

## Next Steps

After completing this quick start guide, explore the following topics:

1. **Advanced Workflows** - Implement conditional logic, loops, and parallel execution
2. **Custom Nodes** - Create reusable node types for specialized tasks
3. **Integration APIs** - Connect external services and APIs
4. **Team Collaboration** - Share workflows and manage permissions
5. **Monitoring & Analytics** - Track workflow performance and costs

### Additional Resources

| Resource | Link |
|----------|------|
| Documentation | https://docs.refly.ai |
| GitHub Discussions | https://github.com/refly-ai/refly-skills/discussions |
| Issue Tracker | https://github.com/refly-ai/refly-skills/issues |
| Discord Community | https://discord.gg/refly |

---

<a id='system-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Project Structure](#project-structure), [API Modules](#api-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/stores/src/stores/import-resource.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)
- [packages/skill-template/src/scheduler/utils/context.ts](https://github.com/refly-ai/refly/blob/main/packages/skill-template/src/scheduler/utils/context.ts)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx)
- [packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx)
- [packages/ai-workspace-common/src/components/pure-copilot/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/pure-copilot/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)
- [packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx)
- [packages/web-core/src/components/layout/ModalContainer.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/components/layout/ModalContainer.tsx)
- [packages/web-core/src/pages/page-share/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/page-share/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)
</details>

# System Architecture

## Overview

Refly is a modular AI workspace platform built with a distributed architecture that separates concerns across multiple packages. The system comprises a monorepo structure using pnpm workspaces, organized into application layers (API, web-core) and shared package libraries (canvas-common, stores, skill-template, ai-workspace-common, layout).

The architecture follows a modular design pattern where each package encapsulates specific functionality, enabling loose coupling between components while maintaining type-safe inter-package communication.

## Package Architecture

The repository is organized into the following main packages:

| Package | Purpose | Key Dependencies |
|---------|---------|------------------|
| `apps/api` | Backend API server | NestJS framework |
| `apps/web-core` | Frontend application | React 18, TypeScript |
| `packages/canvas-common` | Shared canvas types and utilities | - |
| `packages/stores` | Global state management (Zustand) | React |
| `packages/skill-template` | Skill execution templates | - |
| `packages/ai-workspace-common` | Reusable UI components | Ant Design, Tailwind CSS |
| `packages/layout` | Page layout components | React |

资料来源：[packages/stores/src/stores/import-resource.ts:1-50](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)

## State Management Architecture

### Global Store Structure

The application uses Zustand for centralized state management through the `packages/stores` package. The store is organized into functional slices with clear action boundaries.

```mermaid
graph TD
    A[Root Store] --> B[Import Resource Store]
    A --> C[Canvas Store]
    A --> D[User Store]
    A --> E[UI Store]
    
    B --> B1[importResourceModalVisible]
    B --> B2[extensionModalVisible]
    B --> B3[scrapeLinks]
    B --> B4[waitingList]
    B --> B5[fileList / imageList]
    
    C --> C1[selectedMenuItem]
    C --> C2[insertNodePosition]
```

### Store Actions Pattern

State updates follow a consistent pattern using Zustand's `set` function with immutable state updates:

```typescript
setFileList: (fileList: FileItem[]) => set((state) => ({ ...state, fileList })),
setImageList: (imageList: ImageItem[]) => set((state) => ({ ...state, imageList })),
setSelectedMenuItem: (menuItem: ImportResourceMenuItem) =>
  set((state) => ({ ...state, selectedMenuItem: menuItem })),
setInsertNodePosition: (position: XYPosition) =>
  set((state) => ({ ...state, insertNodePosition: position })),
```

资料来源：[packages/stores/src/stores/import-resource.ts:1-30](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)

### Waiting List Management

The store implements a waiting list feature for handling pending operations:

```typescript
addToWaitingList: (item: WaitingListItem) =>
  set((state) => ({ ...state, waitingList: [...state.waitingList, item] })),
removeFromWaitingList: (id: string) =>
  set((state) => ({
    ...state,
    waitingList: state.waitingList.filter((item) => item.id !== id),
  })),
updateWaitingListItem: (id: string, updates: Partial<WaitingListItem>) =>
  set((state) => ({
    ...state,
    waitingList: state.waitingList.map((item) =>
      item.id === id ? { ...item, ...updates } : item
    ),
  })),
```

资料来源：[packages/stores/src/stores/import-resource.ts:30-45](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)

## Canvas System Architecture

### Canvas Overview

The canvas is the central workspace component where users build workflows by connecting nodes. It supports multiple node types including skills, webhooks, documents, and integrations.

### Node Types

| Node Type | Description | Source Component |
|-----------|-------------|------------------|
| Skill Node | Executes AI-powered skills | `action-step.tsx` |
| Webhook Node | HTTP callback endpoints | `webhook-config-tab.tsx` |
| Document Node | Rich content rendering | `ArtifactRenderer.tsx` |
| Integration Node | External service connections | `integration-docs-modal.tsx` |

资料来源：[packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx:1-60](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)

### Artifact Rendering System

The `ArtifactRenderer` component handles rendering different content types within the canvas:

```typescript
const ArtifactRenderer = memo(
  ({ node, type, content, title, language, status }) => {
    // Renders based on rendererType: 'document' or other
    // Supports purePreview mode for clean rendering
    // Implements custom width/height scaling
  },
  (prevProps, nextProps) => {
    // Custom comparison for memo optimization
    const prevMetadata = prevProps.node.nodeData?.metadata || {};
    const nextMetadata = nextProps.node.nodeData?.metadata || {};
    
    return (
      prevProps.type === nextProps.type &&
      prevProps.node.entityId === nextProps.node.entityId &&
      prevMetadata.content === nextMetadata.content &&
      prevMetadata.status === nextMetadata.status
    );
  }
);
```

资料来源：[packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx:1-120](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx)

### Action Step Execution Flow

Skills execute through a structured action step system:

```mermaid
graph TD
    A[Skill Node] --> B[ActionStep Component]
    B --> C{Status Check}
    C -->|executing| D[Show Progress Logs]
    C -->|waiting| E[Show Pending Indicator]
    C -->|finish| F[Show Results]
    C -->|failed| G[Show Error Logs]
    
    D --> H[ReasoningContent]
    E --> H
    F --> I[Collapsed View]
    G --> J[Error Details]
```

The component manages status transitions automatically:

```typescript
useEffect(() => {
  if (['executing', 'waiting'].includes(status)) {
    setCollapsed(false);
  } else {
    setCollapsed(true);
  }
}, [status]);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx:50-80](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)

## Integration System Architecture

### Integration Docs Modal

The integration system provides a unified interface for configuring external services:

```typescript
case 'webhook':
  return (
    <WebhookDocsTab
      canvasId={canvasId}
      webhookConfig={webhookConfig}
      toggling={webhookToggling}
      onWebhookReset={fetchWebhookConfig}
      onNavigateToApiSection={handleNavigateToIntegrationSection}
    />
  );
case 'api':
  return <ApiDocsTab canvasId={canvasId} />;
case 'skill':
  return <SkillDocsTab />;
```

资料来源：[packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx:1-80](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx)

### Webhook Documentation Tab

The webhook documentation provides usage instructions and error handling guidance:

```typescript
<section id="webhook-instructions" className="space-y-2 scroll-mt-4">
  <Text strong>{t('webhook.instructions')}</Text>
  <ul className="list-disc list-inside space-y-1 text-sm text-gray-600">
    <li>{t('webhook.instruction1')}</li>
    <li>{t('webhook.instruction2')}</li>
    <li>{t('webhook.instruction3')}</li>
  </ul>
</section>
```

资料来源：[packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx:1-30](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx)

### Webhook Error Codes

| Error Code | HTTP Status | Description |
|------------|-------------|-------------|
| AUTH_REQUIRED | 401 | Not authenticated |
| VALIDATION_ERROR | 400 | DAG validation failed |
| DUPLICATE_NODE_ID | 409 | Node ID already exists |
| CYCLE_DETECTED | 400 | Circular dependency |
| WORKFLOW_NOT_FOUND | 404 | Workflow does not exist |

## Skill Template System

### Context Management

The skill template system uses a context-based architecture for passing data between skill execution steps:

```typescript
export interface ContextFile {
  name: string;
  fileId: string;
  type: string;
  summary: string;
  content: string;
  variableId?: string;
  variableName?: string;
}

export interface ContextFileMeta {
  // Metadata-only version (without content)
  name: string;
  fileId: string;
  type: string;
  summary: string;
  variableId?: string;
  variableName?: string;
}
```

资料来源：[packages/skill-template/src/scheduler/utils/context.ts:1-50](https://github.com/refly-ai/refly/blob/main/packages/skill-template/src/scheduler/utils/context.ts)

### Tool Use Pattern

Skills use a standardized tool calling format:

```typescript
// Matches markdown code block format
const TOOL_USE_BLOCK_REGEX = /\n*```tool_use(?:_result)?[^\n]*\n[\s\S]*?```\n*/g;

// Matches standalone XML tags
const TOOL_USE_TAG_REGEX = /<tool_use[\s\S]*?<\/tool_use>/g;
```

### Agent Result Structure

```typescript
export interface AgentResult {
  resultId: string;
  title: string;
  content: string;
  outputFiles: ContextFileMeta[];
}

export interface ToolCallMeta {
  callId: string;      // For retrieval via read_tool_result
  toolName: string;    // Tool that was called
}
```

资料来源：[packages/skill-template/src/scheduler/utils/context.ts:40-80](https://github.com/refly-ai/refly/blob/main/packages/skill-template/src/scheduler/utils/context.ts)

## Copilot Integration

### Pure Copilot Component

The copilot provides an AI-powered interface for interacting with the workspace:

```typescript
const PureCopilot = ({
  source,
  canvasId,
  onQueryChange,
}: {
  source: 'frontPage' | 'onboarding';
  canvasId?: string;
  onQueryChange?: (query: string) => void;
}) => {
  // Supports drag-and-drop file handling
  // Integrates with ChatInput component
  // Manages file uploads and context items
};
```

资料来源：[packages/ai-workspace-common/src/components/pure-copilot/index.tsx:1-50](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/pure-copilot/index.tsx)

### Drag and Drop Support

```typescript
<div
  className="w-full relative"
  onDragEnter={handleDragEnter}
  onDragLeave={handleDragLeave}
  onDragOver={handleDragOver}
  onDrop={handleDrop}
>
```

The copilot glow effect varies based on source location:

```typescript
source === 'frontPage'
  ? cn('border-refly-primary-default my-2')
  : 'border-transparent pure-copilot-glow-effect'
```

## Modal Architecture

### Modal Container Pattern

The application uses a centralized modal container with lazy loading:

```typescript
<LazyModal
  visible={importResourceModalVisible}
  loader={() =>
    import('@refly-packages/ai-workspace-common/components/import-resource').then((m) => ({
      default: m.ImportResourceModal,
    }))
  }
/>
```

资料来源：[packages/web-core/src/components/layout/ModalContainer.tsx:1-80](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/components/layout/ModalContainer.tsx)

### Modal Types

| Modal | Purpose | Source |
|-------|---------|--------|
| ImportResourceModal | Import external resources | `import-resource.ts` |
| CanvasRenameModal | Rename canvas | `canvas-rename.tsx` |
| CanvasDeleteModal | Delete canvas | `canvas-delete.tsx` |
| DuplicateCanvasModal | Duplicate canvas | `duplicate-canvas-modal.tsx` |
| ClaimedVoucherPopup | Show claimed voucher | `voucher` |
| EarnedVoucherPopup | Show earned voucher | `voucher` |

## Schedule System

### Schedule Button Component

The schedule system manages automated workflow execution:

```typescript
<Popover content={scheduleContent} trigger="click" placement="bottomRight">
  <Button className="schedule-toolbar-btn">
    {/* Loading state with skeleton */}
    {/* Schedule title display */}
  </Button>
</Popover>

<Modal
  title={t('schedule.limitReached.title')}
  footer={[
    <Button key="cancel">{t('common.cancel')}</Button>,
    <Button key="view-schedules" type="primary">{t('schedule.viewSchedules')}</Button>,
  ]}
>
  {/* Limit reached message */}
</Modal>
```

资料来源：[packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx:1-60](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)

### Schedule Modal Features

| Feature | Description |
|---------|-------------|
| Schedule Limit Modal | Shown when user exceeds plan limits |
| Deactivate Confirmation | Confirm before disabling schedules |
| View Schedules | Navigate to schedule management |

## Page Layout System

### Layout Components

The layout system provides consistent page structures:

```typescript
// PrimaryPageLayout - Main application pages
<PrimaryPageLayout>
  {({ context, onContextChange }) => (
    <>
      <PrimaryPageLayoutContextUpdater
        title="Page Title"
        actions={<Button>Action</Button>}
      />
      <div>Content</div>
    </>
  )}
</PrimaryPageLayout>

// SecondaryPageLayout - Detail/sub-pages
<SecondaryPageLayout>
  {({ context, onContextChange }) => (
    <>
      <SecondaryPageLayoutContextUpdater
        title="Detail Title"
        desc="Description"
        onBack={() => history.back()}
      />
      <div>Content</div>
    </>
  )}
</SecondaryPageLayout>
```

### Layout Configuration Options

| Option | Description |
|--------|-------------|
| `title` | Page title |
| `desc` | Page description |
| `actions` | Action button area |
| `extra` | Extra content area |
| `fixHeight` | Fix content height |
| `noPaddingX` | Remove horizontal padding |
| `noPaddingY` | Remove vertical padding |

## Wide Mode Feature

The page share feature includes a wide mode for expanded content viewing:

```typescript
{wideMode.isActive && (
  <Modal
    open={wideMode.isActive}
    footer={null}
    onCancel={handleCloseWideMode}
    width="85%"
    className="wide-mode-modal"
  >
    <div className="bg-white h-full w-full flex flex-col rounded-lg overflow-hidden">
      {wideMode.nodeId && nodes.find((n) => n.nodeId === wideMode.nodeId)}
    </div>
  </Modal>
)}
```

资料来源：[packages/web-core/src/pages/page-share/index.tsx:1-80](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/page-share/index.tsx)

## Component Rendering Optimization

### Memo Strategy

Components use React's `memo` with custom comparison functions to optimize re-renders:

```typescript
export const ArtifactRenderer = memo(
  Component,
  (prevProps, nextProps) => {
    const prevMetadata = prevProps.node.nodeData?.metadata || {};
    const nextMetadata = nextProps.node.nodeData?.metadata || {};

    return (
      prevProps.type === nextProps.type &&
      prevProps.node.entityId === nextProps.node.entityId &&
      prevMetadata.content === nextMetadata.content &&
      prevMetadata.status === nextMetadata.status &&
      prevMetadata.type === nextMetadata.type
    );
  }
);
```

资料来源：[packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx:100-120](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx)

## API Error Handling

### Error Response Structure

The API returns structured error responses:

```typescript
{
  code: string;        // Error code (e.g., "AUTH_REQUIRED")
  httpStatus: number;  // HTTP status code
  message: string;    // Error message
  description: string // Detailed description
}
```

### Common Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| AUTH_REQUIRED | Authentication missing | Run `refly login` |
| BUILDER_NOT_STARTED | No builder session | Run `refly builder start` |
| VALIDATION_REQUIRED | Validation pending | Run `refly builder validate` |
| VALIDATION_ERROR | DAG validation failed | Check node connections |
| DUPLICATE_NODE_ID | ID collision | Use unique identifiers |
| CYCLE_DETECTED | Circular dependency | Remove cycles from graph |

## Conclusion

The Refly system architecture demonstrates a well-structured monorepo design with clear separation of concerns across multiple packages. The architecture supports:

- **Scalable State Management**: Centralized Zustand stores with typed actions
- **Modular UI Components**: Reusable components in ai-workspace-common
- **Flexible Integration System**: Extensible webhook and API integrations
- **Optimized Rendering**: Strategic use of React.memo for performance
- **Type-Safe Communication**: Consistent TypeScript interfaces across packages

---

<a id='project-structure'></a>

## Project Structure

### 相关页面

相关主题：[System Architecture](#system-architecture), [API Modules](#api-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [pnpm-workspace.yaml](https://github.com/refly-ai/refly/blob/main/pnpm-workspace.yaml)
- [turbo.json](https://github.com/refly-ai/refly/blob/main/turbo.json)
- [packages/stores/src/stores/import-resource.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)
- [packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)
- [packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)
- [packages/ai-workspace-common/src/components/resource-view/resource-meta.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/resource-view/resource-meta.tsx)
- [packages/ai-workspace-common/src/components/pure-copilot/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/pure-copilot/index.tsx)
- [packages/web-core/src/components/layout/ModalContainer.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/components/layout/ModalContainer.tsx)
- [packages/web-core/src/pages/page-share/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/page-share/index.tsx)
- [packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx)
- [packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx)
- [packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/components/webhook-docs-tab.tsx)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx)
- [packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx)
- [packages/layout/README.md](https://github.com/refly-ai/refly/blob/main/packages/layout/README.md)
- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
- [packages/ai-workspace-common/src/components/markdown/plugins/link/render.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/markdown/plugins/link/render.tsx)
</details>

# Project Structure

## Overview

Refly is a modern monorepo built with pnpm workspaces and Turborepo for optimized build performance. The repository follows a structured approach to organize code across multiple packages and applications, enabling shared dependencies and consistent development practices across the entire codebase.

The project architecture separates concerns into discrete packages under the `packages/` directory and applications under the `apps/` directory, with each package serving a specific domain of functionality.

## High-Level Architecture

```mermaid
graph TD
    subgraph "Apps Layer"
        API[apps/api<br/>Backend API Service]
        WEB[apps/web-core<br/>Web Application]
    end

    subgraph "Packages Layer"
        STORES[packages/stores<br/>Zustand State Management]
        LAYOUT[packages/layout<br/>Layout Components]
        WORKSPACE[packages/ai-workspace-common<br/>Workspace Components]
        CLI[packages/cli<br/>Command Line Interface]
    end

    API --> STORES
    WEB --> STORES
    WEB --> LAYOUT
    WEB --> WORKSPACE
    CLI --> API
```

## Directory Structure

```
refly/
├── apps/
│   ├── api/                    # Backend API application
│   │   └── src/
│   │       └── modules/        # API modules (voucher, workflows, etc.)
│   └── web/                    # Web application entry
├── packages/
│   ├── stores/                 # State management with Zustand
│   ├── ai-workspace-common/    # Shared AI workspace components
│   ├── layout/                 # Page layout components
│   ├── web-core/               # Core web components
│   └── cli/                    # CLI tool
├── pnpm-workspace.yaml         # pnpm workspace configuration
└── turbo.json                 # Turborepo configuration
```

## Applications

### apps/api

The backend API service built with Node.js. The API module structure follows a modular pattern:

```
apps/api/src/modules/
├── voucher/                   # Voucher/coupon management
│   └── voucher-email-templates.ts
└── ... (additional modules)
```

**Key Characteristics:**
- Handles business logic and data persistence
- Provides REST API endpoints for the frontend
- Contains email template logic for notifications
- Manages voucher rewards and creator incentives

资料来源：[apps/api/src/modules](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules)

### apps/web-core

The main web application entry point, responsible for rendering the user interface and handling client-side routing.

## Packages

### packages/stores

State management layer using Zustand. Provides centralized state stores for various application features.

**Primary Store Files:**

| Store File | Purpose |
|------------|---------|
| `import-resource.ts` | Manages import resource modal visibility and file lists |
| `waiting-list.ts` | Handles waiting list state and operations |
| `scraper-links.ts` | Manages scraped link metadata |

**Key Store Patterns:**

```typescript
// Store action pattern
setImportResourceModalVisible: (visible: boolean) =>
  set((state) => ({ ...state, importResourceModalVisible: visible })),

// Waiting list operations
addToWaitingList: (item: WaitingListItem) =>
  set((state) => ({ ...state, waitingList: [...state.waitingList, item] })),

removeFromWaitingList: (id: string) =>
  set((state) => ({
    ...state,
    waitingList: state.waitingList.filter((item) => item.id !== id),
  })),
```

资料来源：[packages/stores/src/stores/import-resource.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/import-resource.ts)

### packages/ai-workspace-common

The core component library for the AI workspace functionality. This package contains the majority of UI components and business logic for the application.

#### Component Organization

```
packages/ai-workspace-common/src/components/
├── canvas/                    # Canvas-based workflow components
│   ├── nodes/                 # Custom node types
│   ├── top-toolbar/          # Toolbar components
│   ├── node-preview/         # Node preview panels
│   ├── integration-docs/    # Integration documentation
│   ├── webhook/              # Webhook configuration
│   └── launchpad/           # Launchpad interface
├── resource-view/            # Resource display components
├── pure-copilot/             # Copilot chat interface
├── slideshow/                # Presentation/slideshow components
└── markdown/                 # Markdown rendering plugins
```

#### Canvas Components

The canvas system is a node-based workflow editor:

| Component | Purpose |
|-----------|---------|
| `CodeArtifactNode` | Renders code artifacts within canvas nodes |
| `ArtifactRenderer` | Renders various artifact types (documents, code) |
| `RichChatInput` | Multi-feature chat input with mentions and uploads |
| `SkillResponse` | Displays skill execution logs and reasoning |
| `ActionStep` | Renders individual action steps with status |

**Canvas Node Rendering:**

```typescript
// packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx
export const CodeArtifactNode = memo(
  ({ id, data, isPreview, selected, hideHandles, onNodeClick }: CodeArtifactNodeProps) => {
    const [isHovered, setIsHovered] = useState(false);
    const { edges } = useCanvasData();
    const { getNode } = useReactFlow();
    // ... node rendering logic
  },
  (prevProps, nextProps) =>
    prevProps.entityId === nextProps.entityId &&
    prevProps?.status === nextProps?.status &&
    prevProps.legacyData?.content === nextProps.legacyData?.content
);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/nodes/code-artifact.tsx)

#### Skill Response & Action Steps

The skill response system displays AI agent execution logs:

```typescript
// packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx
const ReasoningContent = memo(
  ({
    resultId,
    reasoningContent,
    sources,
    step,
    status,
  }: {
    resultId: string;
    reasoningContent: string;
    sources: Source[];
    step: ActionStep;
    status: ActionStatus;
  }) => {
    const [collapsed, setCollapsed] = useState(status !== 'executing');
    
    // Auto-collapse when step status changes from executing to finish
    useEffect(() => {
      if (['executing', 'waiting'].includes(status)) {
        setCollapsed(false);
      } else {
        setCollapsed(true);
      }
    }, [status]);
    // ...
  }
);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)

#### Resource View System

Displays resource metadata and details:

```typescript
// packages/ai-workspace-common/src/components/resource-view/resource-meta.tsx
{resourceDetail?.data?.url && (
  <a
    className="site-intro-site-url no-underline text-[#0E9F77]"
    href={resourceDetail?.data?.url}
    target="_blank"
    rel="noreferrer"
  >
    {resourceDetail?.data?.url}
  </a>
)}
{resourceDetail?.createdAt && (
  <p className="text-gray-400">
    {time(resourceDetail?.createdAt, language as LOCALE)
      .utc()
      .fromNow()}
  </p>
)}
```

资料来源：[packages/ai-workspace-common/src/components/resource-view/resource-meta.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/resource-view/resource-meta.tsx)

#### Integration Documentation

Web-based documentation and configuration interfaces:

```typescript
// packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx
<Button
  type="primary"
  className="view-schedules-btn"
  onClick={handleViewSchedulesClick}
>
  {t('schedule.viewSchedules') || 'View Schedules'}
</Button>

<Modal
  title={t('schedule.limitReached.title') || 'Schedule Limit Reached'}
  open={scheduleLimitModalVisible}
  footer={[
    <Button key="cancel" onClick={() => setScheduleLimitModalVisible(false)}>
      {t('common.cancel') || 'Cancel'}
    </Button>,
    // ...
  ]}
>
```

资料来源：[packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)

#### Artifact Rendering

Supports multiple artifact types with preview capabilities:

```typescript
// packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx
<div className="transform scale-[0.5] origin-top-left w-[200%] h-[200%] overflow-hidden bg-white dark:bg-gray-900 rounded shadow-sm">
  <Renderer
    purePreview
    content={content}
    type={currentType}
    title={title}
    language={artifactData?.language || language}
    readonly
    onRequestFix={handleRequestFix}
    width="100%"
    height="100%"
  />
</div>
```

资料来源：[packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/slideshow/components/ArtifactRenderer.tsx)

#### Markdown Link Rendering

Custom markdown plugin for rendering links with preview functionality:

```typescript
// packages/ai-workspace-common/src/components/markdown/plugins/link/render.tsx
<img
  className="w-3 h-3"
  alt={source?.url}
  src={`https://www.google.com/s2/favicons?domain=${source?.url}&sz=${16}`}
/>
```

资料来源：[packages/ai-workspace-common/src/components/markdown/plugins/link/render.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/markdown/plugins/link/render.tsx)

### packages/web-core

Core web components including modal management and page layouts.

#### Modal Container

Centralized modal management system:

```typescript
// packages/web-core/src/components/layout/ModalContainer.tsx
<LazyModal
  visible={importResourceModalVisible}
  loader={() =>
    import('@refly-packages/ai-workspace-common/components/import-resource').then((m) => ({
      default: m.ImportResourceModal,
    }))
  }
/>

<LazyModal
  visible={isCanvasRenameShown}
  loader={() =>
    import('@refly-packages/ai-workspace-common/components/canvas/modals/canvas-rename').then(
      (m) => ({ default: m.CanvasRenameModal }),
    )
  }
/>
```

资料来源：[packages/web-core/src/components/layout/ModalContainer.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/components/layout/ModalContainer.tsx)

#### Page Share Module

Handles public page sharing functionality:

```typescript
// packages/web-core/src/pages/page-share/index.tsx
{wideMode.isActive && (
  <Modal
    open={wideMode.isActive}
    footer={null}
    onCancel={handleCloseWideMode}
    width="85%"
    className="wide-mode-modal"
  >
    <div className="bg-white h-full w-full flex flex-col rounded-lg overflow-hidden">
      {/* Wide mode content */}
    </div>
  </Modal>
)}
```

资料来源：[packages/web-core/src/pages/page-share/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/page-share/index.tsx)

### packages/layout

Page layout component library providing consistent layout patterns.

#### Layout Components

| Component | Description |
|-----------|-------------|
| `PrimaryPageLayout` | Main application pages with title, actions, and extra content areas |
| `SecondaryPageLayout` | Detail pages with back navigation |
| `Header` | Reusable header with left/right action areas |

**Primary Layout Usage:**

```tsx
import { PrimaryPageLayout, PrimaryPageLayoutContextUpdater } from '@refly/layout';

function MainPage() {
  return (
    <PrimaryPageLayout>
      {({ context, onContextChange }) => (
        <>
          <PrimaryPageLayoutContextUpdater
            title="Page Title"
            actions={<Button>Action Button</Button>}
            extra={<div>Extra Content</div>}
            deps={[]}
          />
          <div>Page Content</div>
        </>
      )}
    </PrimaryPageLayout>
  );
}
```

**Configuration Options:**

| Option | Type | Description |
|--------|------|-------------|
| `title` | string | Page title displayed in header |
| `actions` | ReactNode | Action button area |
| `extra` | ReactNode | Extra content area |
| `fixHeight` | boolean | Whether to fix height |
| `noPaddingY` | boolean | Remove vertical padding |
| `noPaddingX` | boolean | Remove horizontal padding |

资料来源：[packages/layout/README.md](https://github.com/refly-ai/refly/blob/main/packages/layout/README.md)

### packages/cli

Command-line interface for Refly operations.

#### CLI Features

| Feature | Description |
|---------|-------------|
| `refly login` | Authenticate with API key |
| `refly builder` | Workflow builder commands |
| `refly workflow` | Workflow execution and management |
| `refly init` | Initialize Claude Code integration |

**Configuration Storage:**

Configuration is stored in `~/.refly/config.json`:

```json
{
  "version": 1,
  "auth": {
    "apiKey": "...",
    "expiresAt": "..."
  },
  "api": {
    "endpoint": "https://api.refly.ai"
  }
}
```

**Environment Variables:**

| Variable | Description |
|----------|-------------|
| `REFLY_API_KEY` | API key for authentication |
| `REFLY_API_ENDPOINT` | Override API endpoint |

#### Claude Code Integration

After `refly init`, skill files are installed to:
- `~/.claude/skills/refly/SKILL.md`
- `~/.claude/skills/refly/references/`
- `~/.claude/commands/refly-*.md`

#### Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| AUTH_REQUIRED | Not authenticated | Run `refly login` |
| BUILDER_NOT_STARTED | No active builder session | Run `refly builder start` |
| VALIDATION_REQUIRED | Must validate before commit | Run `refly builder validate` |
| VALIDATION_ERROR | DAG validation failed | Check error details |
| DUPLICATE_NODE_ID | Node ID already exists | Use unique ID |
| CYCLE_DETECTED | Circular dependency | Remove cycle |
| WORKFLOW_NOT_FOUND | Workflow does not exist | Check workflow ID |

资料来源：[packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)

## Build System

### pnpm Workspaces

The project uses pnpm workspaces for monorepo management:

```yaml
# pnpm-workspace.yaml
packages:
  - 'apps/*'
  - 'packages/*'
```

### Turborepo

Build orchestration with Turborepo:

```json
// turbo.json (inferred from usage)
{
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**"]
    }
  }
}
```

## Component Communication Flow

```mermaid
graph LR
    subgraph "State Layer"
        STORES[packages/stores<br/>Zustand Stores]
    end

    subgraph "UI Layer"
        WEB_CORE[packages/web-core<br/>Modal Container]
        WORKSPACE[packages/ai-workspace-common<br/>Components]
    end

    subgraph "Layout Layer"
        LAYOUT[packages/layout<br/>Page Layouts]
    end

    STORES -->|State Updates| WEB_CORE
    STORES -->|State Updates| WORKSPACE
    WORKSPACE -->|Lazy Loaded| WEB_CORE
    LAYOUT -->|Wraps| WEB_CORE
```

## Internationalization

The project uses i18n for translations with namespace support:

```typescript
const { t } = useTranslation();

{t('schedule.title') || 'Schedule'}
{t('schedule.limitReached.title', { ns: 'schedule' })}
```

Translation namespaces include:
- `common` - Common UI strings
- `schedule` - Schedule-related strings
- `skillLog` - Skill execution logs
- `webhook` - Webhook configuration
- `integration` - Integration documentation

## Key Development Patterns

### Lazy Loading

Components are lazy-loaded for performance:

```typescript
<LazyModal
  visible={importResourceModalVisible}
  loader={() =>
    import('@refly-packages/ai-workspace-common/components/import-resource').then((m) => ({
      default: m.ImportResourceModal,
    }))
  }
/>
```

### Memoization

Heavy components use React.memo for optimization:

```typescript
export const CodeArtifactNode = memo(
  ({ id, data, isPreview, selected }: CodeArtifactNodeProps) => {
    // component logic
  },
  (prevProps, nextProps) =>
    prevProps.entityId === nextProps.entityId &&
    prevProps?.status === nextProps?.status
);
```

### Custom Hooks

Domain-specific hooks encapsulate business logic:

- `useCanvasData()` - Canvas state access
- `useAgentNodeManagement()` - Agent node operations
- `useVariablesManagement()` - Workflow variables
- `useFetchDriveFiles()` - File fetching

## Development Commands

```bash
# Install dependencies
pnpm install

# Build all packages
pnpm build

# Watch mode for development
pnpm dev

# Run API locally
node dist/bin/refly.js

---

<a id='workflow-engine'></a>

## Workflow Engine

### 相关页面

相关主题：[Skill Management](#skill-management), [API Modules](#api-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [apps/api/src/modules/workflow/workflow.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/workflow/workflow.service.ts)
- [apps/api/src/modules/workflow/workflow.processor.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/workflow/workflow.processor.ts)
- [apps/api/src/modules/schedule/schedule.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/workflow/schedule.service.ts)
- [packages/canvas-common/src/workflow.ts](https://github.com/refly-ai/refly/blob/main/packages/canvas-common/src/workflow.ts)
- [packages/skill-template/src/scheduler/utils/context.ts](https://github.com/refly-ai/refly/blob/main/packages/skill-template/src/scheduler/utils/context.ts)
- [apps/api/src/modules/skill/skill-invoker.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/skill/skill-invoker.service.ts)
- [apps/api/src/modules/skill-package/skill-package.dto.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/skill-package/skill-package.dto.ts)
- [packages/web-core/src/pages/workflow-app/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/workflow-app/index.tsx)
</details>

# Workflow Engine

## Overview

The Workflow Engine is the core execution runtime of the refly platform. It orchestrates the execution of workflow graphs composed of interconnected nodes, where each node represents a discrete unit of work executed by specialized agents. The engine handles workflow lifecycle management, from creation through execution, monitoring, and completion.

The Workflow Engine serves as the backbone for:

- **Workflow Graph Execution**: Parsing and executing directed acyclic graphs (DAGs) of workflow tasks
- **Node Agent Orchestration**: Invoking skill agents for individual task execution
- **Variable Management**: Managing workflow-level and node-level variables
- **Execution State Tracking**: Tracking node status, handling retries, and managing abort signals
- **Scheduled Execution**: Supporting time-based workflow triggers

## Architecture

The Workflow Engine follows a layered architecture with clear separation of concerns:

```mermaid
graph TD
    subgraph "API Layer"
        WS[Workflow Service]
        SS[Schedule Service]
    end
    
    subgraph "Core Engine"
        WP[Workflow Processor]
        SI[Skill Invoker]
    end
    
    subgraph "Execution Layer"
        NA[Node Agents]
        ST[Skill Templates]
    end
    
    subgraph "State Management"
        DB[(Database)]
        EV[Event Bus]
    end
    
    WS --> WP
    SS --> WP
    WP --> SI
    SI --> NA
    NA --> ST
    WP <--> DB
    WP <--> EV
```

### Key Components

| Component | Package | Responsibility |
|-----------|---------|----------------|
| `WorkflowService` | apps/api | Workflow CRUD, execution triggering |
| `WorkflowProcessor` | apps/api | Core DAG execution, state management |
| `SkillInvokerService` | apps/api | Skill agent invocation, result handling |
| `ScheduleService` | apps/api | Time-based workflow triggers |
| `WorkflowRunForm` | ai-workspace-common | Variable input UI for workflow execution |

## Data Models

### Workflow Graph Structure

The workflow is defined as a graph with nodes and edges:

```typescript
interface WorkflowSpec {
  nodes?: Array<Record<string, unknown>>;
  edges?: Array<Record<string, unknown>>;
}
```

资料来源：[apps/api/src/modules/skill-package/skill-package.dto.ts:26]()

### Node Types

Workflows support multiple node types:

| Node Type | Description |
|-----------|-------------|
| `skillResponse` | Skill agent execution nodes |
| `start` | Entry point node |
| `end` | Termination node |

资料来源：[packages/web-core/src/pages/workflow-app/index.tsx:142]()

### Task Structure

Tasks represent individual units of work within a workflow:

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique identifier (e.g., "task-1") |
| `title` | string | Concise task name |
| `prompt` | string | Detailed execution instructions with @ mentions |
| `dependentTasks` | string[] | Task IDs that must complete first |
| `toolsets` | string[] | Toolset IDs from Available Tools |

资料来源：[packages/skill-template/src/prompts/templates/copilot-agent-system.md:67]()

### Context Files

Context files provide input/output data flow between workflow nodes:

```typescript
export interface ContextFile {
  name: string;
  fileId: string;
  type: string;
  summary: string;
  content: string;
  variableId?: string;
  variableName?: string;
}
```

资料来源：[packages/skill-template/src/scheduler/utils/context.ts:14]()

### Agent Results

Agent results encapsulate task execution outcomes:

```typescript
export interface AgentResult {
  resultId: string;
  title: string;
  content: string;
  outputFiles: ContextFileMeta[];
}
```

资料来源：[packages/skill-template/src/scheduler/utils/context.ts:27]()

## Workflow Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Created: workflow.create
    Created --> Running: workflow.run
    Running --> Completed: all nodes finish
    Running --> Failed: unhandled error
    Running --> Aborted: user abort
    Failed --> Running: retry
    Aborted --> [*]
    Completed --> [*]
```

### Execution States

Each node in a workflow can be in one of the following states:

| Status | Description |
|--------|-------------|
| `waiting` | Node is waiting for dependencies to complete |
| `executing` | Node is currently running |
| `finish` | Node completed successfully |
| `failed` | Node execution failed |

资料来源：[packages/ai-workspace-common/src/components/workflow-app/run-logs.tsx:78]()

## Workflow Execution Flow

```mermaid
sequenceDiagram
    participant User
    participant API
    participant Processor
    participant Invoker
    participant Agent
    
    User->>API: workflow.run(workflowId, input)
    API->>Processor: processWorkflowExecution()
    Processor->>Processor: Initialize execution context
    Processor->>Processor: Resolve task dependencies (DAG)
    
    loop For each ready node
        Processor->>Invoker: invokeSkillNode(node)
        Invoker->>Agent: Execute skill agent
        Agent-->>Invoker: AgentResult
        Invoker-->>Processor: NodeExecutionResult
        Processor->>Processor: Update execution state
    end
    
    Processor-->>API: WorkflowExecutionResult
    API-->>User: Execution ID + status
```

## Variable Management

Workflow variables enable data passing between nodes and external input:

### Variable Input Schema

```typescript
interface WorkflowVariable {
  id: string;
  name: string;
  type: string;
  required: boolean;
  defaultValue?: unknown;
}
```

Variables can be defined at the workflow level and referenced in node prompts using the format `@{type=variable,id=<id>,name=<Name>}`.

资料来源：[packages/skill-template/src/prompts/templates/copilot-agent-system.md:73]()

## Scheduled Execution

The Workflow Engine supports time-based triggers through the Schedule Service:

```mermaid
graph LR
    S[Schedule] -->|trigger| WP[Workflow Processor]
    WP -->|execute| W[Workflow]
    S -->|email| U[User Notification]
```

### Schedule Configuration

| Field | Description |
|-------|-------------|
| `cronExpression` | Cron expression for timing |
| `workflowId` | Target workflow to execute |
| `input` | Input variables for the workflow |

## Skill Invocation

The Skill Invoker Service handles the execution of skill agents within workflow nodes:

### Invocation Flow

1. **Skill Node Triggered**: Processor identifies ready skill node
2. **Input Preparation**: Gather context files and variables
3. **Agent Invocation**: Call skill agent with prepared context
4. **Result Processing**: Parse agent output, extract files and results
5. **State Update**: Update node execution status

### Abort Handling

The engine supports graceful abort of executing nodes:

```typescript
// Abort signal propagation
const abortSignal = new AbortController();
skillInvoker.invokeSkill({
  executionId,
  nodeId,
  signal: abortSignal.signal,
});
```

资料来源：[apps/api/src/modules/skill/skill-invoker.service.ts:1]()

## Error Handling

### Retry Mechanism

Failed nodes can be retried using the retry handler:

```typescript
const handleRetry = createRetryHandler(node, resultId);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx:52]()

### Error Display

Execution errors are displayed with appropriate styling:

```typescript
<span className="text-sm font-semibold text-refly-func-danger-default">
  {t('canvas.workflow.run.executionFailed')}
</span>
```

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx:32]()

## Workflow Generation

The copilot agent can generate workflows dynamically using the `generate_workflow` and `patch_workflow` tools:

| Tool | Use Case |
|------|----------|
| `generate_workflow` | Creating new workflows from scratch |
| `patch_workflow` | Modifying existing workflows |

资料来源：[packages/skill-template/src/prompts/templates/copilot-agent-system.md:49]()

### Workflow Plan Structure

```typescript
interface WorkflowPlanRecord {
  tasks: Array<{
    id: string;
    title: string;
    prompt: string;
    dependentTasks: string[];
    toolsets: string[];
  }>;
  // ...
}
```

## CLI Integration

The refly CLI provides workflow management commands:

```bash
# Create workflow
refly workflow create --name "<name>" --spec '<json>'

# Run workflow
refly workflow run <workflowId> [--input '<json>']

# Check status
refly workflow run-status <runId>

# Abort execution
refly workflow abort <runId>
```

资料来源：[packages/cli/README.md:1]()

## Credit Usage Tracking

The engine tracks credit consumption during workflow execution:

```typescript
creditUsage={
  isCreditUsageLoading || hasIncompleteNodes
    ? null
    : (creditUsageData?.data?.total ?? 0)
}
```

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/preview.tsx:45]()

## Webhook Integration

Workflows can trigger external webhooks:

```mermaid
graph LR
    W[Workflow Complete] -->|POST| H[Webhook Endpoint]
    H -->|Response| W
```

Webhook configuration includes error codes and status mappings for reliable integration.

## Public Workflow Pages

The workflow engine powers multiple page types exported from the web-core package:

| Page | Route | Purpose |
|------|-------|---------|
| `WorkflowAppPage` | `/workflow-app` | Main workflow execution UI |
| `WorkflowListPage` | `/workflow-list` | Browse and manage workflows |
| `RunHistoryPage` | `/run-history` | View past executions |
| `RunDetailPage` | `/run-detail` | Detailed execution analysis |
| `MarketplacePage` | `/marketplace` | Discover workflow templates |

资料来源：[packages/web-core/src/index.ts:1]()

## Summary

The Workflow Engine is the central orchestration layer that transforms workflow specifications into executable task graphs. It leverages the skill system for node execution, manages complex variable dependencies, and provides comprehensive execution tracking with support for real-time monitoring, scheduled runs, and graceful error handling. The engine's design emphasizes extensibility through toolsets, reliability through retry mechanisms, and observability through detailed execution logging.

---

<a id='skill-management'></a>

## Skill Management

### 相关页面

相关主题：[Workflow Engine](#workflow-engine)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/ai-workspace-common/src/components/canvas/integration-docs/components/skill-docs-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/components/skill-docs-tab.tsx)
- [packages/cli/src/skill/loader.ts](https://github.com/refly-ai/refly/blob/main/packages/cli/src/skill/loader.ts)
- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
</details>

# Skill Management

## Overview

The Skill Management system in Refly provides a modular, extensible framework for creating, installing, updating, and uninstalling reusable workflow snippets called "Skills." Skills enable users to package and share reusable automation logic across the Refly ecosystem, including integration with various IDE environments such as Claude Code, Cursor, VS Code, and others.

Skills are defined using markdown files with frontmatter metadata and can be loaded, validated, and executed through the CLI or API components. The system supports a registry-based distribution model where skills are hosted in the [refly-skills GitHub repository](https://github.com/refly-ai/refly-skills) and can be installed to local IDE environments.

资料来源：[skill-docs-tab.tsx:1-150]()

## Architecture

The Skill Management system is composed of three primary layers:

| Layer | Component | Purpose |
|-------|-----------|---------|
| CLI | `packages/cli/src/skill/loader.ts` | Skill loading, validation, and metadata extraction |
| UI | `skill-docs-tab.tsx` | User-facing documentation and installation guides |
| Registry | `refly-skills` repository | Central repository for skill distribution |

```mermaid
graph TD
    A[User] --> B[CLI Command<br/>refly skill install]
    A --> C[Web UI<br/>Integration Docs Tab]
    B --> D[Skill Loader<br/>packages/cli/src/skill/loader.ts]
    C --> E[Skill Registry<br/>github.com/refly-ai/refly-skills]
    E --> D
    D --> F[Local Skill Storage<br/>~/.{ide}/skills/]
    D --> G[Symlink Validation]
    G --> H[SKILL.md Loading]
    H --> I[Metadata Extraction]
    I --> J[LoadedSkill Object]
```

资料来源：[loader.ts:1-60]()

## Skill File Structure

Each skill consists of a standardized directory structure with a mandatory `SKILL.md` file at its root. The skill directory is installed to environment-specific locations based on the target IDE.

### Directory Layout

| File/Folder | Description |
|-------------|-------------|
| `SKILL.md` | Main skill definition with frontmatter metadata and content |
| `references/` | Additional reference files for context (installed for Claude Code) |
| `commands/` | CLI command definitions (optional, installed for Claude Code) |

资料来源：[skill-docs-tab.tsx:150-200]()

### Supported IDE Installation Paths

Skills are installed to the following locations based on the target IDE:

| IDE | Installation Path |
|-----|-------------------|
| Claude Code | `~/.claude/skills/refly/` |
| Antigravity | `~/.antigravity/skills/` |
| OpenCode | `~/.opencode/skills/` |
| Cursor | `~/.cursor/skills/` |
| VS Code | `~/.vscode/skills/` |
| Trae | `~/.trae/skills/` |

资料来源：[skill-docs-tab.tsx:200-230]()

## Skill Loading

### The Loader Module

The skill loader (`packages/cli/src/skill/loader.ts`) provides core functionality for loading and validating skills from the local filesystem.

```typescript
export function loadSkill(name: string): LoadedSkill {
  // Loads skill with symlink validation
  // Returns LoadedSkill object with metadata
}
```

资料来源：[loader.ts:20-40]()

### Loading Process

```mermaid
graph TD
    A[loadSkill name] --> B{Check Symlink Status}
    B -->|Symlink Invalid| C[Error: Symlink Broken]
    B -->|Symlink Valid| D{Skill Directory Exists?}
    D -->|No| E[Error: SKILL_DIR_NOT_FOUND]
    D -->|Yes| F{SKILL.md Exists?}
    F -->|No| G[Error: SKILL_NOT_FOUND]
    F -->|Yes| H[Load Skill Metadata]
    H --> I[Extract Frontmatter]
    I --> J[Validate Frontmatter]
    J --> K[Return LoadedSkill]
```

### Safe Loading with tryLoadSkill

The `tryLoadSkill` function provides a safe loading mechanism that returns `null` instead of throwing errors when a skill is not found:

```typescript
export function tryLoadSkill(name: string): LoadedSkill | null {
  try {
    return loadSkill(name);
  } catch (err) {
    if (
      (err as { code?: string }).code === SkillErrorCode.SKILL_DIR_NOT_FOUND ||
      (err as { code?: string }).code === SkillErrorCode.SKILL_NOT_FOUND
    ) {
      return null;
    }
    throw err;
  }
}
```

资料来源：[loader.ts:70-90]()

## Metadata Extraction

### Frontmatter Parsing

The `extractSkillMetadata` function allows extraction of skill metadata without fully loading from disk, which is useful for validation and preview operations:

```typescript
export function extractSkillMetadata(content: string): {
  frontmatter: SkillFrontmatter | null;
  issues: ValidationIssue[];
  content: string;
}
```

The function performs the following steps:

1. Parses frontmatter from markdown content
2. Validates frontmatter against schema
3. Returns extracted metadata and any validation issues

资料来源：[loader.ts:100-120]()

### Validation Issues

When frontmatter validation fails, the system returns an array of `ValidationIssue` objects describing each problem. This ensures skills meet the required schema before installation.

## Skill Operations

### Installation from Repository

The installation process follows these steps:

1. Downloads the skill from the registry repository
2. Creates the skill directory structure
3. Validates and installs symlinks to IDE-specific locations

```bash
refly skill install <skill-name>
```

资料来源：[skill-docs-tab.tsx:250-280]()

### Uninstallation

Uninstallation removes the skill directory and cleans up all symlinks:

1. Removes skill files from the local directory
2. Cleans up environment-specific symlinks
3. Updates skill registry

```bash
refly skill uninstall <skill-name>
```

资料来源：[skill-docs-tab.tsx:100-150]()

### Updating Skills

Update operations fetch the latest version from the registry and replace existing files while preserving local customizations.

### Creating New Skills

The `refly skill create` command initializes a new skill with the standard directory structure:

```bash
refly skill create <skill-name>
```

资料来源：[skill-docs-tab.tsx:300-350]()

## CLI Integration

### Configuration Storage

The Refly CLI stores configuration at `~/.refly/config.json`:

```json
{
  "version": 1,
  "auth": {
    "apiKey": "...",
    "expiresAt": "..."
  },
  "api": {
    "endpoint": "https://api.refly.ai"
  }
}
```

资料来源：[packages/cli/README.md:20-40]()

### Environment Variables

| Variable | Description |
|----------|-------------|
| `REFLY_API_KEY` | API key for authentication |
| `REFLY_API_ENDPOINT` | Override API endpoint URL |

### Claude Code Integration

After running `refly init`, skill files are automatically installed to Claude Code locations:

- `~/.claude/skills/refly/SKILL.md`
- `~/.claude/skills/refly/references/`
- `~/.claude/commands/refly-*.md` (if commands directory exists)

This integration enables Claude Code to:

- Understand Refly workflow concepts
- Use builder mode correctly
- Handle state transitions
- Output deterministic results

资料来源：[packages/cli/README.md:45-60]()

## Error Handling

### Error Codes

| Code | Description | Resolution |
|------|-------------|------------|
| `AUTH_REQUIRED` | Not authenticated | Run `refly login` |
| `BUILDER_NOT_STARTED` | No active builder session | Run `refly builder start` |
| `VALIDATION_REQUIRED` | Must validate before commit | Run `refly builder validate` |
| `VALIDATION_ERROR` | DAG validation failed | Check error details |
| `DUPLICATE_NODE_ID` | Node ID already exists | Use unique ID |
| `CYCLE_DETECTED` | Circular dependency | Remove cycle |
| `WORKFLOW_NOT_FOUND` | Workflow does not exist | Check workflow ID |
| `SKILL_DIR_NOT_FOUND` | Skill directory missing | Reinstall the skill |
| `SKILL_NOT_FOUND` | SKILL.md file missing | The skill may be corrupted |

资料来源：[packages/cli/README.md:65-75]()

### Error Recovery Suggestions

The loader provides contextual suggestions for error recovery:

```typescript
throw createSkillError(
  SkillErrorCode.SKILL_DIR_NOT_FOUND,
  `Skill '${name}' symlink exists but SKILL.md file is missing`,
  {
    suggestions: [
      'The skill directory may be corrupted',
      'Try reinstalling the skill with `refly skill install`',
    ],
  }
);
```

资料来源：[loader.ts:30-50]()

## Skill Registry

The official skill registry is hosted at [github.com/refly-ai/refly-skills](https://github.com/refly-ai/refly-skills). Users can browse available skills at:

```
https://github.com/refly-ai/refly-skills/tree/main/skills
```

资料来源：[skill-docs-tab.tsx:20-30]()

## Summary

The Skill Management system provides a complete lifecycle for reusable automation snippets:

- **Creation**: Scaffold new skills with standard structure
- **Installation**: Fetch from registry and install to IDE environments
- **Loading**: Validate and parse skill metadata
- **Execution**: Integrate with Claude Code and other IDEs
- **Updates**: Fetch latest versions from registry
- **Uninstallation**: Clean removal with symlink cleanup

The modular architecture separates concerns between the CLI loader, UI documentation components, and the registry, enabling maintainable and extensible skill management across the Refly ecosystem.

---

<a id='canvas-component'></a>

## Canvas Component

### 相关页面

相关主题：[Copilot Integration](#copilot-integration), [System Architecture](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/ai-workspace-common/src/components/canvas/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx)
- [packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx)
- [packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx)
- [packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)
- [packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx)
- [packages/ai-workspace-common/src/components/canvas/canvas-resources/share/file-overview.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/canvas-resources/share/file-overview.tsx)
- [packages/ai-workspace-common/src/components/canvas/front-page/recent-workflow.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/front-page/recent-workflow.tsx)
- [packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)
- [packages/stores/src/stores/sider.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/sider.ts)
</details>

# Canvas Component

## Overview

The Canvas Component is the core visual workspace system in the Refly AI platform. It provides an interactive, node-based environment for building and executing AI-powered workflows. The Canvas enables users to create, configure, and orchestrate complex AI workflows through a visual interface that combines drag-and-drop node composition with real-time execution monitoring.

The Canvas system supports multiple node types including agent nodes, tool nodes, document renderers, and webhook integrations. It serves as the primary workspace where users define workflow logic, manage context items, connect to upstream agents, and execute AI-driven processes.

资料来源：[packages/ai-workspace-common/src/components/canvas/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/index.tsx)

## Architecture

### Component Hierarchy

The Canvas architecture follows a modular composition pattern with multiple layered components working together to provide the complete workspace experience.

```mermaid
graph TD
    A[Canvas Workspace] --> B[Canvas Container]
    A --> C[Top Toolbar]
    A --> D[Side Panel]
    B --> E[Rich Chat Input]
    B --> F[Node System]
    B --> G[Workflow Runner]
    C --> H[Schedule Button]
    C --> I[Integration Docs]
    D --> J[Resource Library]
    D --> K[Sider Store]
    F --> L[Agent Nodes]
    F --> M[Tool Nodes]
    G --> N[Workflow Node Panel]
    G --> O[Action Steps]
```

### Directory Structure

The Canvas components are organized in the following structure within `packages/ai-workspace-common/src/components/canvas/`:

| Directory | Purpose |
|-----------|---------|
| `nodes/` | Node type definitions and implementations |
| `workflow-run/` | Workflow execution and monitoring components |
| `launchpad/rich-chat-input/` | Chat input with @mentions and file handling |
| `node-preview/` | Node preview and skill response rendering |
| `top-toolbar/` | Top navigation toolbar components |
| `webhook/` | Webhook configuration interfaces |
| `integration-docs/` | Integration documentation modal |
| `canvas-resources/` | File and resource management |
| `front-page/` | Recent workflows display |

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx)

## Core Components

### Canvas Context

The Canvas uses React Context to provide global state and utilities across all child components. The context exposes canvas-specific operations including context item management, toolset selection, and agent connections.

```typescript
const { canvasId } = useCanvasContext();
```

The Canvas context is consumed by multiple sub-components to access shared state such as the current canvas identifier and related workflow metadata. This enables components throughout the canvas tree to access and modify workflow state without prop drilling.

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx)

### Rich Chat Input

The Rich Chat Input component provides the primary user interaction mechanism for communicating with AI agents within the Canvas. It supports advanced features including file attachments, @mentions, and real-time message composition.

```typescript
export interface RichChatInputRef {
  focus: () => void;
  insertAtSymbol?: () => void;
}
```

**Key Features:**

| Feature | Description |
|---------|-------------|
| File Upload | Support for single and multiple image uploads |
| @Mentions | Context-aware mentions for files, agents, and tools |
| Auto-resize | Dynamic textarea height adjustment |
| Drag-and-Drop | File drag-and-drop interface support |
| Tool Store Integration | Access to external tool marketplace |

The component integrates with the `useAgentNodeManagement` hook to manage query state, context items, and selected toolsets. It also connects to `useAgentConnections` for upstream agent communication.

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx)

### Mention List

The mention system provides context-aware suggestions when users type @ symbols in the chat input. It supports multiple mention types with distinct rendering behaviors.

**Mention Types:**

| Type | Source | Rendering |
|------|--------|-----------|
| Files | Drive files | File icon with filename |
| Agents | Skill responses | Skill response icon |
| Tools | Tool registry | Tool icon |
| Variables | Canvas variables | Variable type icon (text, image, resource) |

```typescript
agents: {
  nodeIconProps: (item: MentionItem) => {
    if (item.source === 'agents') {
      return {
        type: 'skillResponse' as CanvasNodeType,
        small: true,
      };
    } else {
      return {
        type: item.variableType as CanvasNodeType,
        small: true,
        url: item.variableType === 'image' ? item.metadata?.imageUrl : undefined,
      };
    }
  },
  emptyStateKey: 'noAgents',
},
```

The mention list automatically formats variable values for display, truncating long text values to 20 characters with an ellipsis indicator.

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx)

## Node System

### Workflow Node Panel

The Workflow Node Panel provides the execution interface for individual nodes within a workflow. It displays node status, results, and allows users to interact with running workflows.

```typescript
<LastRunTab
  location="runlog"
  loading={loading}
  isStreaming={isStreaming}
  resultId={resultId}
  result={result}
  outputStep={outputStep}
  query={query}
  title={title}
  nodeId={node.id}
  selectedToolsets={selectedToolsets}
  handleRetry={createRetryHandler(node, resultId)}
/>
```

**Panel States:**

| State | Description |
|-------|-------------|
| Idle | Node not yet executed |
| Running | Node currently executing with streaming output |
| Finished | Node completed successfully |
| Failed | Node execution encountered an error |

The panel automatically logs events when users expand agent nodes, tracking canvas and node identifiers for analytics purposes:

```typescript
logEvent('runlog_agent_expand', null, {
  canvasId,
  nodeId: node.id,
  resultId,
});
```

资料来源：[packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/workflow-run/workflow-node-panel.tsx)

### Action Steps

Action Steps display individual execution steps within skill responses. They render logs with titles and descriptions, supporting status indicators for execution progress.

```typescript
items={logs.map((log) => ({
  title: t(`${log.key}.title`, {
    ...log.titleArgs,
    ns: 'skillLog',
    defaultValue: log.key,
  }),
  description: t(`${log.key}.description`, {
    ...log.descriptionArgs,
    ns: 'skillLog',
    defaultValue: '',
  }),
  status: log.status === 'error' ? 'error' : 'finish',
}))}
```

**Status Types:**

| Status | Badge Color | Meaning |
|--------|-------------|---------|
| `executing` | Blue/Active | Currently running |
| `waiting` | Yellow | Waiting for input |
| `finish` | Green | Completed successfully |
| `error` | Red | Execution failed |

Action steps automatically collapse when execution status changes from `executing` or `waiting` to a terminal state.

资料来源：[packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/node-preview/skill-response/action-step.tsx)

## Integration System

### Integration Docs Modal

The Integration Docs Modal provides a comprehensive interface for viewing and managing canvas integrations. It includes API key management, webhook configuration, and documentation display.

```typescript
<IntegrationDocsModal open={open} onClose={onClose} canvasId={canvasId} />
<ApiKeyModal open={apiKeyModalOpen} onClose={() => setApiKeyModalOpen(false)} />
<ApiOutputModal
  open={outputModalOpen}
  onClose={() => setOutputModalOpen(false)}
  canvasId={canvasId}
/>
```

**Modal Components:**

| Component | Purpose |
|-----------|---------|
| IntegrationDocsModal | Main integration documentation interface |
| ApiKeyModal | API key management and configuration |
| ApiOutputModal | API output and testing results |

资料来源：[packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/integration-docs/integration-docs-modal.tsx)

### Webhook Configuration

The Webhook Configuration system enables external systems to trigger canvas workflows. It provides a structured interface for managing webhook endpoints and payloads.

```typescript
<section id="webhook-instructions" className="space-y-2 scroll-mt-4">
  <Text strong>{t('webhook.instructions')}</Text>
  <ul className="list-disc list-inside space-y-1 text-sm text-gray-600">
    <li>{t('webhook.instruction1')}</li>
    <li>{t('webhook.instruction2')}</li>
    <li>{t('webhook.instruction3')}</li>
  </ul>
</section>
```

**Webhook Features:**

- Request body schema definition
- Parameter documentation with types and descriptions
- Required field indicators
- Markdown-formatted descriptions

The webhook documentation tab renders request body fields in a structured table format with columns for name, type, requirement status, and description.

资料来源：[packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/webhook/webhook-config-tab.tsx)

## Scheduling System

The Schedule Button enables users to configure automated workflow execution at specified intervals. It provides a popover interface for schedule management with modal dialogs for limit warnings.

```typescript
const handleViewSchedulesClick = () => {
  // Navigate to schedule management
};

<Modal
  title={t('schedule.limitReached.title')}
  open={scheduleLimitModalVisible}
  footer={[
    <Button key="cancel" onClick={() => setScheduleLimitModalVisible(false)}>
      {t('common.cancel')}
    </Button>,
    <Button key="view-schedules" type="primary" onClick={handleViewSchedulesClick}>
      {t('schedule.viewSchedules')}
    </Button>,
  ]}
>
  <p>{t('schedule.limitReached.message')}</p>
</Modal>
```

**Schedule Features:**

| Feature | Description |
|---------|-------------|
| Interval Configuration | Set recurring execution intervals |
| Limit Detection | Alert when schedule limit is reached |
| Schedule Management | View and manage existing schedules |
| Plan Integration | Respects user plan limitations |

资料来源：[packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/top-toolbar/schedule-button.tsx)

## Resource Management

### File Overview

The File Overview component provides a grid-based interface for managing canvas resources. It includes search functionality and supports both empty and populated states.

```typescript
<div className="flex-grow overflow-y-auto min-h-0">
  <FileList files={files} searchKeyword={searchKeyword} />
</div>
```

**Features:**

- Searchable file list with keyword filtering
- Empty state with "new resource" call-to-action
- Read-only mode support for shared canvases
- Border-styled input with filled variant

The component displays a search input field above the file list, allowing users to filter resources by name or metadata.

资料来源：[packages/ai-workspace-common/src/components/canvas/canvas-resources/share/file-overview.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/canvas-resources/share/file-overview.tsx)

### Recent Workflows

The Recent Workflow component displays a grid of recently accessed workflows on the canvas front page. Each workflow card shows the workflow name, used toolsets, and last update timestamp.

```typescript
<div key={canvas.id} onClick={() => handleEditCanvas(canvas.id)}>
  <div className="h-[120px] flex flex-col justify-between p-4 pb-2">
    <div>
      <div className="text-sm leading-5 font-semibold text-refly-text-0 line-clamp-1">
        {canvas.name || t('common.untitled')}
      </div>
      <UsedToolsets toolsets={canvas.usedToolsets} />
    </div>
    <ActionDropdown canvasId={canvas.id} canvasName={canvas.name} />
  </div>
</div>
```

**Card Display:**

| Field | Content |
|-------|---------|
| Title | Workflow name (truncated to single line) |
| Toolsets | Visual indicator of used toolsets |
| Timestamp | Relative time (e.g., "2 hours ago") |
| Actions | Dropdown menu for canvas operations |

资料来源：[packages/ai-workspace-common/src/components/canvas/front-page/recent-workflow.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/front-page/recent-workflow.tsx)

## State Management

### Sider Store

The Canvas state is partially managed through the global Sider Store, which maintains UI state for sidebars, modals, and canvas lists.

```typescript
export const useSiderStore = create<SiderState>()(
  devtools((set) => ({
    collapse: false,
    collapseState: 'expanded',
    isManualCollapse: false,
    showSiderDrawer: false,
    canvasList: [],
    projectsList: [],
    sourceList: [],
    showLibraryModal: false,
    showCanvasListModal: false,
    showSettingModal: false,
    showInvitationModal: false,
    settingsModalActiveTab: null,
  }))
);
```

**Store Actions:**

| Action | Description |
|--------|-------------|
| `setCollapse` | Toggle sidebar collapse state |
| `setShowSiderDrawer` | Control drawer visibility |
| `setCanvasList` | Update canvas list data |
| `setShowLibraryModal` | Toggle library modal |
| `updateCanvasTitle` | Update canvas title by ID |

资料来源：[packages/stores/src/stores/sider.ts](https://github.com/refly-ai/refly/blob/main/packages/stores/src/stores/sider.ts)

## Workflow Execution Flow

```mermaid
sequenceDiagram
    participant User
    participant RichChatInput
    participant AgentNode
    participant WorkflowPanel
    participant ActionStep
    
    User->>RichChatInput: Submit query with context
    RichChatInput->>AgentNode: Execute agent with toolsets
    AgentNode->>WorkflowPanel: Stream execution status
    WorkflowPanel->>ActionStep: Render logs and progress
    ActionStep-->>User: Display execution steps
    AgentNode-->>RichChatInput: Return result
    WorkflowPanel->>User: Show final output and metrics
```

## Component Configuration Reference

### Primary Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `title` | string | - | Page title for layout |
| `actions` | ReactNode | - | Action buttons area |
| `extra` | ReactNode | - | Extra content area |
| `fixHeight` | boolean | false | Fix container height |
| `noPaddingY` | boolean | false | Remove vertical padding |
| `noPaddingX` | boolean | false | Remove horizontal padding |

### Secondary Layout Configuration

| Option | Type | Description |
|--------|------|-------------|
| `title` | string | Detail page title |
| `desc` | string | Page description |
| `actions` | ReactNode | Action buttons |
| `extra` | ReactNode | Extra content |
| `onBack` | () => void | Back button callback |

## Best Practices

### Node Implementation

1. Always provide unique node identifiers for event tracking
2. Use the `logEvent` function for analytics when nodes expand or collapse
3. Implement proper cleanup in `useEffect` return functions
4. Handle all execution states including idle, running, finished, and failed

### State Management

1. Use Canvas Context for shared state across components
2. Leverage Sider Store for global UI state
3. Implement proper lazy loading for performance optimization
4. Use dependency arrays (`deps`) to trigger context updates when needed

### Integration Development

1. Define clear API schemas for webhook request bodies
2. Provide localized strings for all user-facing text
3. Implement proper error handling and user feedback
4. Support both read-only and editable modes for shared canvases

---

<a id='copilot-integration'></a>

## Copilot Integration

### 相关页面

相关主题：[Canvas Component](#canvas-component), [API Modules](#api-modules)

<details>
<summary>Relevant Source Files</summary>

The following source files are referenced in this documentation:

- [apps/api/src/modules/copilot/copilot.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/copilot/copilot.service.ts)
- [apps/api/src/modules/copilot-autogen/copilot-autogen.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/copilot-autogen/copilot-autogen.service.ts)
- [packages/ai-workspace-common/src/components/canvas/copilot/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/copilot/index.tsx)
- [packages/ai-workspace-common/src/components/pure-copilot/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/pure-copilot/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx)
- [packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx](https://github.com/refly-ai/refly/blob/main/packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx)
- [packages/skill-template/src/scheduler/utils/context.ts](https://github.com/refly-ai/refly/blob/main/packages/skill-template/src/scheduler/utils/context.ts)
- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
</details>

# Copilot Integration

## Overview

The Copilot Integration in Refly represents the core conversational AI interface that enables users to interact with Refly's agentic workflow capabilities. It provides a natural language interface where users can describe intent, attach files, mention workflow variables, and send messages to trigger agent actions within canvas workflows.

The integration spans both frontend UI components and backend services, creating a bidirectional communication channel between the user interface and the agent execution engine.

## Architecture Overview

```mermaid
graph TD
    subgraph Frontend
        PC[PureCopilot Component]
        CO[Canvas Copilot]
        RCI[RichChatInput]
        ML[MentionList]
    end
    
    subgraph Hooks
        ANM[useAgentNodeManagement]
        AC[useAgentConnections]
        VM[useVariablesManagement]
    end
    
    subgraph Backend
        CS[Copilot Service]
        CAS[CopilotAutogen Service]
    end
    
    subgraph Data Layer
        CF[Context Files]
        AR[Agent Results]
        TC[Tool Calls]
    end
    
    PC --> RCI
    CO --> RCI
    RCI --> ML
    RCI --> ANM
    RCI --> AC
    RCI --> VM
    ANM --> CS
    AC --> CS
    CS --> CAS
    CAS --> CF
    CAS --> AR
    AR --> TC
```

## Core Components

### PureCopilot Component

The `PureCopilot` component (`packages/ai-workspace-common/src/components/pure-copilot/index.tsx`) serves as the standalone chat interface for copilot interactions. It handles file attachments, drag-and-drop uploads, and message composition.

**Key Features:**
- File upload and management via `FileList` component
- Drag-and-drop support with visual feedback (`handleDragEnter`, `handleDragLeave`, `handleDragOver`, `handleDrop`)
- Context item management for attached files
- Source-aware styling (supports `frontPage` and `onboarding` modes)

**Component Props:**
| Prop | Type | Description |
|------|------|-------------|
| `source` | `string` | Context source for styling: `'frontPage'` or `'onboarding'` |
| `currentCanvasId` | `string` | Active canvas identifier |
| `contextItems` | `ContextItem[]` | Attached files and context |
| `relevantUploads` | `Upload[]` | Upload queue items |

资料来源：[packages/ai-workspace-common/src/components/pure-copilot/index.tsx]()()

### RichChatInput Component

The `RichChatInput` component (`packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx`) provides the primary input interface within canvas workflows. It extends basic chat input with advanced features like variable mentions, tool references, and OAuth integrations.

**Component Interface:**
```typescript
export interface RichChatInputProps {
  readonly?: boolean;
  handleSendMessage: (message: string) => void;
  onUploadImage?: (file: File) => Promise<void>;
  onUploadMultipleImages?: (files: File[]) => Promise<void>;
  onFocus?: () => void;
  placeholder?: string;
  mentionPosition?: MentionPosition;
  nodeId?: string;
}

export interface RichChatInputRef {
  focus: () => void;
  insertAtSymbol?: () => void;
}
```

**Internal State Management:**
- `isDragging`: Tracks drag-over state for file drops
- `isFocused`: Tracks focus state for UI styling
- `isLogin`: Authentication state from `useUserStoreShallow`
- `isMentionListVisible`: Controls mention dropdown visibility

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx]()()

### MentionList Component

The `MentionList` component (`packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx`) provides context-aware suggestions for variables, tools, and other workflow entities during chat composition.

**Mention Types:**
| Source | Description |
|--------|-------------|
| `variables` | Workflow variables available in current canvas |
| `toolset` | Available tool integrations |
| `oauth` | OAuth-connected services |

**Keyboard Navigation States:**
```typescript
type FocusLevel = 'first' | 'second';
const [focusLevel, setFocusLevel] = useState<FocusLevel>('first');
const [firstLevelIndex, setFirstLevelIndex] = useState<number>(0);
const [secondLevelIndex, setSecondLevelIndex] = useState<number>(0);
```

**Height Tracking:**
The component tracks nested list heights for keyboard navigation:
```typescript
const [firstLevelHeight, setFirstLevelHeight] = useState<number>(0);
const [secondLevelHeight, setSecondLevelHeight] = useState<number>(0);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/mentionList.tsx]()()

## Context Management System

### ContextFile Model

The copilot system uses structured context files to manage files and data passed to agents:

```typescript
export interface ContextFile {
  name: string;
  fileId: string;
  type: string;
  summary: string;
  content: string;
  variableId?: string;
  variableName?: string;
}

/**
 * Metadata-only version of ContextFile (without content)
 * Used in ContextBlock to reduce token usage - LLM should use read_file to get full content
 */
export interface ContextFileMeta {
  name: string;
  fileId: string;
  type: string;
  summary: string;
  variableId?: string;
  variableName?: string;
}
```

### Agent Results

Agent execution produces structured results:

```typescript
export interface AgentResult {
  resultId: string;
  title: string;
  content: string;
  outputFiles: ContextFileMeta[];
}
```

### Tool Call Metadata

Tool calls within agent results are tracked for retrieval:

```typescript
export interface ToolCallMeta {
  callId: string;
  toolName: string;
}
```

资料来源：[packages/skill-template/src/scheduler/utils/context.ts]()()

## Backend Services

### Copilot Service

The backend copilot service handles message processing, agent dispatch, and response streaming.

**Service Location:** `apps/api/src/modules/copilot/copilot.service.ts`

### Copilot Autogen Service

The `CopilotAutogen` service (`apps/api/src/modules/copilot-autogen/copilot-autogen.service.ts`) manages automatic skill generation and agent orchestration.

**Key Responsibilities:**
- Generate skills based on user intent
- Manage skill lifecycle (create, update, delete)
- Handle skill installation to Claude Code environments

**Skill Installation Path:**
```
~/.claude/skills/refly/SKILL.md
~/.claude/skills/refly/references/
~/.claude/commands/refly-*.md
```

资料来源：[apps/api/src/modules/copilot-autogen/copilot-autogen.service.ts]()()
资料来源：[packages/cli/README.md]()()

## Integration Hooks

### useAgentNodeManagement

Manages the agent node state and message handling for a specific node:

```typescript
const { query, setQuery, setContextItems, setSelectedToolsets } =
  useAgentNodeManagement(nodeId);
```

### useAgentConnections

Manages connections between agents:

```typescript
const { connectToUpstreamAgent } = useAgentConnections();
```

### useVariablesManagement

Manages workflow variables for the current canvas:

```typescript
const { data: workflowVariables } = useVariablesManagement(canvasId);
```

### useVariableView

Provides variable viewing functionality:

```typescript
const { handleVariableView } = useVariableView(canvasId);
```

资料来源：[packages/ai-workspace-common/src/components/canvas/launchpad/rich-chat-input/index.tsx]()()

## User Interaction Flow

```mermaid
sequenceDiagram
    participant User
    participant RCI as RichChatInput
    participant ML as MentionList
    participant ANM as useAgentNodeManagement
    participant CS as Copilot Service
    
    User->>RCI: Type message
    RCI->>ML: Check for @ trigger
    ML-->>RCI: Show suggestion dropdown
    User->>ML: Select mention
    ML-->>RCI: Insert mention into query
    User->>RCI: Send message
    RCI->>ANM: handleSendMessage(query)
    ANM->>CS: Process message
    CS-->>ANM: Agent result
    ANM-->>RCI: Update state
    RCI-->>User: Display result
```

## Configuration Options

### ChatInput Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `readonly` | `boolean` | `false` | Disable input |
| `autoFocus` | `boolean` | `false` | Focus on mount |
| `minRows` | `number` | `2` | Minimum input height |
| `inputClassName` | `string` | - | Custom input styling |
| `placeholder` | `string` | i18n key | Placeholder text |

### Mention Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `placement` | `'bottom'` / `'bottom-start'` | `'bottom-start'` | Dropdown position |
| `query` | `string` | `''` | Current mention query |
| `isPolling` | `boolean` | `false` | Enable polling mode |
| `isOpening` | `boolean` | `false` | Handle OAuth popup |

## Styling and Theming

The copilot components use CSS custom properties for theming:

```css
/* Primary copilot styling */
.pure-copilot-glow-effect {
  box-shadow: var(--copilot-glow-color);
}

/* Input area */
.bg-refly-bg-content-z2 {
  background-color: var(--refly-bg-content);
}

/* Text hierarchy */
.text-refly-text-0 { color: var(--refly-text-primary); }
.text-refly-text-1 { color: var(--refly-text-secondary); }
```

### Source-Specific Styling

```typescript
className={cn(
  'w-full px-4 py-3 rounded-[12px] border-[1px] border-solid bg-refly-bg-content-z2 transition-all duration-300 relative z-20',
  source === 'frontPage'
    ? cn('border-refly-primary-default my-2')
    : 'border-transparent pure-copilot-glow-effect',
)}
```

## Internationalization

The copilot interface supports i18n with namespace-based translations:

| Namespace | Usage |
|-----------|-------|
| `copilot` | Main copilot UI strings |
| `skillLog` | Skill execution logs |
| `common` | Shared strings |

**Example Translation Keys:**
```typescript
t('copilot.greeting.title')
t('copilot.pureCopilotPlaceholder')
t('skillLog.error.title')
```

## Error Handling

### File Upload Errors

Files can fail upload with retry capability:

```typescript
const { onRemove, onRetry } = useFileUpload({
  uploads: relevantUploads,
  canvasId: currentCanvasId,
});
```

### OAuth Popup Handling

The mention list supports OAuth integration:

```typescript
openOAuthPopup?: (toolsetKey: string) => Promise<any>;
```

## Related Documentation

- [Canvas Integration](canvas-integration) - Workflow canvas features
- [Skills System](skills-system) - Agent skill management
- [API Documentation](api-reference) - Backend service APIs
- [CLI Integration](cli-integration) - Claude Code skill installation

---

<a id='api-modules'></a>

## API Modules

### 相关页面

相关主题：[System Architecture](#system-architecture), [Authentication and Authorization](#authentication)

<details>
<summary>Related Source Files</summary>

The following source files were referenced for generating this documentation:

- [apps/api/src/modules/tool/tool.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/tool/tool.service.ts)
- [apps/api/src/modules/tool/ptc/tool-execution.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/tool/ptc/tool-execution.service.ts)
- [apps/api/src/modules/webhook/webhook.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/webhook/webhook.service.ts)
- [apps/api/src/modules/openapi/openapi.service.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/openapi/openapi.service.ts)

**Note:** The source files listed above were not available in the context retrieved for this analysis. The following documentation is based on the available context files that reference API module functionality, including UI components and integration documentation.

</details>

# API Modules

The Refly API Modules form the backend service layer that handles tool execution, webhook integration, OpenAPI specification management, and skill orchestration. These modules operate within the `apps/api/src/modules/` directory and expose functionality through REST endpoints consumed by the frontend workspace components.

## Overview

The API modules provide a structured backend architecture for the Refly platform's core capabilities:

| Module | Purpose | Key Files |
|--------|---------|-----------|
| **Tool** | Tool registration, management, and execution | `tool.service.ts`, `tool-execution.service.ts` |
| **Webhook** | Webhook configuration and event delivery | `webhook.service.ts` |
| **OpenAPI** | OpenAPI specification handling and integration | `openapi.service.ts` |
| **Skill** | Skill registry and lifecycle management | `skill.service.ts` |

## Tool Module

The Tool module manages the lifecycle of tools and tool execution within the Refly workspace. Tools are reusable components that can be invoked by agents during workflow execution.

### Tool Service

The `ToolService` handles tool registration, retrieval, and metadata management. Tools in Refly can belong to toolsets, which group related functionality together.

### Tool Execution Service (PTC)

The Prompt-Tool-Calling (PTC) execution service manages the runtime execution of tools during agent reasoning. This service:

- Coordinates tool invocation based on agent decisions
- Manages input/output schemas for tools
- Handles tool result serialization and context injection

## Webhook Module

The Webhook module enables event-driven integrations by allowing external services to receive notifications when specific events occur in Refly workflows.

### Webhook Configuration

Webhook configuration includes:

- **Endpoint URL**: The target URL for webhook delivery
- **Event Types**: Specific events to subscribe to
- **Authentication**: Headers and secrets for security
- **Retry Policy**: Configuration for failed delivery attempts

### Webhook Event Delivery

```mermaid
graph TD
    A[Workflow Event] --> B[WebhookService]
    B --> C{Event Type Match?}
    C -->|Yes| D[Prepare Payload]
    C -->|No| E[Skip Delivery]
    D --> F{HTTP POST}
    F --> G{Response 2xx?}
    G -->|Success| H[Log Success]
    G -->|Failure| I{Retry Count?}
    I -->|< Max| J[Retry with Backoff]
    J --> F
    I -->|>= Max| K[Mark Failed]
```

### Webhook Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `WEBHOOK_DELIVERY_FAILED` | 500 | Failed to deliver webhook |
| `WEBHOOK_TIMEOUT` | 504 | Request timed out |
| `WEBHOOK_INVALID_URL` | 400 | URL format invalid |
| `WEBHOOK_AUTH_FAILED` | 401 | Authentication failed |

## OpenAPI Module

The OpenAPI module provides integration with OpenAPI specifications, enabling Refly to:

- Parse and validate OpenAPI documents
- Generate tool definitions from specifications
- Support API schema introspection

### Request Body Schema

OpenAPI integration follows standard OpenAPI 3.x conventions for request body definitions:

```typescript
interface RequestBodySchema {
  description?: string;
  descriptionKey?: string; // i18n key for localization
  required?: boolean;
  schema: {
    type: string;
    properties: Record<string, SchemaProperty>;
  };
}
```

## Integration with Frontend Components

The API modules communicate with frontend components through:

1. **Context Files** (`packages/skill-template/src/scheduler/utils/context.ts`): Define data structures for tool and result metadata
2. **UI Components**: Consume API responses for display in the workspace interface

### Data Flow

```mermaid
graph LR
    A[Frontend UI] -->|API Request| B[API Module]
    B --> C[Service Logic]
    C --> D[External Service/Tool]
    D --> E[Response]
    C --> F[Context Metadata]
    F --> G[Frontend Render]
```

## Module Configuration

API modules are configured through:

| Configuration | Location | Description |
|---------------|----------|-------------|
| API Endpoint | `~/.refly/config.json` | Base URL for API calls |
| API Key | Environment `REFLY_API_KEY` | Authentication token |
| Module-specific | Per-module configuration | Varies by module |

## Skill Module Integration

Skills extend the API module functionality by providing pre-built integrations. The skill system references external skill repositories at `https://github.com/refly-ai/refly-skills` for community-contributed tools and workflows.

## Error Handling

Standard error codes returned by API modules:

| Code | Module | Description |
|------|--------|-------------|
| `AUTH_REQUIRED` | All | Authentication required |
| `TOOL_NOT_FOUND` | Tool | Requested tool does not exist |
| `WEBHOOK_NOT_CONFIGURED` | Webhook | Webhook endpoint not set |
| `OPENAPI_INVALID_SPEC` | OpenAPI | Invalid OpenAPI specification |
| `SKILL_NOT_INSTALLED` | Skill | Requested skill not found |

---

<a id='authentication'></a>

## Authentication and Authorization

### 相关页面

相关主题：[API Modules](#api-modules)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/cli/src/commands/login.ts](https://github.com/refly-ai/refly/blob/main/packages/cli/src/commands/login.ts)
- [packages/cli/src/api/client.ts](https://github.com/refly-ai/refly/blob/main/packages/cli/src/api/client.ts)
- [packages/cli/src/commands/status.ts](https://github.com/refly-ai/refly/blob/main/packages/cli/src/commands/status.ts)
- [packages/web-core/src/pages/login/index.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/pages/login/index.tsx)
- [packages/web-core/src/components/login-modal/login-content.tsx](https://github.com/refly-ai/refly/blob/main/packages/web-core/src/components/login-modal/login-content.tsx)
- [apps/api/src/modules/config/app.config.ts](https://github.com/refly-ai/refly/blob/main/apps/api/src/modules/config/app.config.ts)
- [packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)
</details>

# Authentication and Authorization

## Overview

The Refly platform implements a comprehensive authentication and authorization system that supports multiple authentication methods across both CLI and web interfaces. The system provides secure access control through OAuth 2.0 flows, API key authentication, and email/password credentials.

## Architecture Overview

The authentication system is designed with two primary entry points:

- **CLI Authentication**: Device-based OAuth authorization with optional API key authentication
- **Web Authentication**: OAuth providers (GitHub, Google) combined with email/password registration and login

```mermaid
graph TD
    subgraph "CLI Authentication"
        CLI[refly CLI] --> LOGIN[refly login]
        LOGIN --> DEVICE[Device Authorization]
        DEVICE --> POLL[Polling for Auth]
        POLL --> SUCCESS{Authorized?}
        SUCCESS -->|Yes| TOKEN[Access Token]
        SUCCESS -->|No| POLL
    end
    
    subgraph "Web Authentication"
        WEB[Web App] --> OAUTH[OAuth Providers]
        WEB --> EMAIL[Email/Password]
        OAUTH --> GH[GitHub]
        OAUTH --> GGL[Google]
    end
    
    subgraph "API Layer"
        TOKEN --> API[API Request]
        API --> GUARD[Auth Guard]
        APIKEY[API Key] --> GUARD
    end
```

## CLI Authentication

### Device Authorization Flow

The CLI implements a device authorization flow for OAuth authentication. When a user runs `refly login`, the CLI initiates a device authorization request and displays a verification URL for the user to complete authentication in a browser.

**Flow Steps:**

1. CLI generates a unique device ID
2. CLI polls the authorization server at regular intervals (2 seconds)
3. User completes authorization in browser
4. CLI receives access token upon successful authorization

```mermaid
sequenceDiagram
    participant CLI
    participant Browser
    participant Server
    
    CLI->>Server: Request device code
    Server-->>CLI: Device code, user code, verification URL
    CLI->>Browser: Open verification URL
    CLI->>Server: Poll for authorization status
    Browser->>Server: User authenticates
    Server-->>CLI: Authorization granted
    CLI->>Server: Exchange for access token
    Server-->>CLI: Access token + refresh token
```

**Key Implementation Details:**

| Parameter | Purpose |
|-----------|---------|
| `device_id` | Unique identifier for the device session |
| `cli_version` | CLI version for server-side validation |
| `host` | Hostname for session tracking |
| `pollInterval` | 2000ms polling interval |

资料来源：[packages/cli/src/commands/login.ts:1-100]()

### API Key Authentication

For programmatic access, the CLI supports API key authentication. Users can authenticate by setting their API key through environment variables or configuration files.

**Environment Variable:**
```
REFLY_API_KEY=<your-api-key>
```

**Configuration File:** `~/.refly/config.json`

```json
{
  "version": 1,
  "auth": {
    "apiKey": "...",
    "expiresAt": "..."
  },
  "api": {
    "endpoint": "https://api.refly.ai"
  }
}
```

资料来源：[packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)

### Token Management

The CLI manages OAuth tokens with automatic refresh capability. When an access token expires, the system automatically attempts to refresh it before making API requests.

**Token Storage Components:**

| Field | Description |
|-------|-------------|
| `accessToken` | Current OAuth access token |
| `refreshToken` | Token for refreshing expired access tokens |
| `expiresAt` | Expiration timestamp for the access token |

**Refresh Logic:**

```typescript
if (expiresAt && new Date(expiresAt) < new Date()) {
  logger.debug('Access token expired, refreshing...');
  try {
    accessToken = await refreshAccessToken();
  } catch (error) {
    throw new AuthError('Session expired, please login again');
  }
}
```

资料来源：[packages/cli/src/api/client.ts:1-80]()

### CLI Status Command

The `refly status` command provides comprehensive authentication status information including:

| Field | Description |
|-------|-------------|
| `cli_version` | Installed CLI version |
| `config_dir` | Configuration directory path |
| `api_endpoint` | API endpoint URL |
| `auth_status` | Authentication status (`valid`, `expired`, `invalid`) |
| `auth_method` | Authentication method used (`oauth`, `apikey`) |
| `auth_details` | Provider or API key information |
| `user` | Authenticated user object |
| `skill` | Skill installation status |

资料来源：[packages/cli/src/commands/status.ts:1-90]()

## Web Authentication

### Supported Authentication Methods

The web interface supports multiple authentication providers configured at the server level:

| Provider | Type | Description |
|----------|------|-------------|
| GitHub | OAuth 2.0 | GitHub OAuth application integration |
| Google | OAuth 2.0 | Google OAuth integration |
| Email | Password | Email/password credentials with validation |

**Fallback Behavior:** Email authentication is always enabled as a fallback, regardless of server configuration.

资料来源：[packages/web-core/src/pages/login/index.tsx:1-80]()

### OAuth Flow Implementation

```mermaid
graph LR
    A[Login Page] --> B{Check Provider Enabled}
    B -->|GitHub| C[GitHub OAuth]
    B -->|Google| D[Google OAuth]
    B -->|Email| E[Email Form]
    C --> F[Redirect to /v1/auth/provider]
    D --> F
    E --> G[Form Validation]
    G --> H[Email Signup/Login API]
```

**OAuth URL Construction:**

```typescript
window.location.href = `${serverOrigin}/v1/auth/${provider}`;
```

**Login Handler:**

```typescript
const handleLogin = useCallback((provider: 'github' | 'google') => {
  logEvent('auth::oauth_login_click', provider);
  authStore.setLoginInProgress(true);
  authStore.setLoginProvider(provider);
  storePendingRedirect();
  window.location.href = `${serverOrigin}/v1/auth/${provider}`;
}, [authStore]);
```

资料来源：[packages/web-core/src/pages/login/index.tsx:80-120]()

### Email/Password Authentication

Email authentication includes comprehensive validation rules:

| Rule | Condition | Error Message |
|------|-----------|---------------|
| Required | Field is empty | Field is required |
| Email Format | Invalid email format | Invalid email address |
| Password Required | Empty password | Password is required |
| Password Min Length | Less than 8 characters | Password must be at least 8 characters |
| Password Confirmation | Does not match | Passwords do not match |

**Password Validation Implementation:**

```typescript
rules={[
  {
    required: true,
    message: t('verifyRules.passwordRequired'),
  },
  ...(authStore.isSignUpMode
    ? [
        {
          min: 8,
          message: t('verifyRules.passwordMin'),
        },
      ]
    : []),
]}
```

资料来源：[packages/web-core/src/components/login-modal/login-content.tsx:1-100]()

### Authentication State Management

The authentication system maintains state through an auth store that tracks:

| State Property | Type | Description |
|----------------|------|-------------|
| `loginInProgress` | boolean | Authentication request in progress |
| `loginProvider` | string | Currently authenticating provider |
| `isSignUpMode` | boolean | Toggle between sign-in and sign-up forms |

**Email Signup Request:**

```typescript
const { data } = await getClient().emailSignup({
  body: {
    email: values.email,
    password: values.password,
  },
});
```

资料来源：[packages/web-core/src/pages/login/index.tsx:120-180]()

## Server-Side Configuration

### Application Auth Config

The API server provides configurable authentication options through environment variables:

| Environment Variable | Type | Default | Description |
|---------------------|------|---------|-------------|
| `AUTH_REQUIRE_INVITATION_CODE` | boolean | false | Require invitation code for registration |
| `INVITATION_MAX_CODES_PER_USER` | number | 20 | Max invitation codes per user |
| `INVITATION_INVITER_CREDIT_AMOUNT` | number | 500 | Credits awarded to inviter |
| `INVITATION_INVITEE_CREDIT_AMOUNT` | number | 500 | Credits awarded to invitee |
| `REGISTRATION_BONUS_CREDIT_AMOUNT` | number | 500 | New user registration bonus |

资料来源：[apps/api/src/modules/config/app.config.ts:1-50]()

### OAuth Provider Configuration

OAuth providers are configured with client credentials:

```typescript
twitter: {
  enabled: process.env.TWITTER_AUTH_ENABLED === 'true' || false,
  clientId: process.env.TWITTER_CLIENT_ID || 'test',
  clientSecret: process.env.TWITTER_CLIENT_SECRET || 'test',
  callbackUrl: process.env.TWITTER_CALLBACK_URL || 'test',
},
notion: {
  enabled: process.env.NOTION_AUTH_ENABLED === 'true' || false,
  clientId: process.env.NOTION_CLIENT_ID || 'test',
  clientSecret: process.env.NOTION_CLIENT_SECRET || 'test',
  callbackUrl: process.env.NOTION_CALLBACK_URL || 'test',
},
```

资料来源：[apps/api/src/modules/config/app.config.ts:50-80]()

## Authentication Methods Summary

| Method | Use Case | Token Storage | Refresh |
|--------|----------|---------------|---------|
| OAuth (CLI Device) | Interactive CLI login | config.json | Automatic |
| OAuth (Web) | Web application login | HTTP-only cookies | Automatic |
| API Key | Scripting/CI-CD | Environment/config | N/A |
| Email/Password | Web registration | HTTP-only cookies | Automatic |

## Error Handling

### CLI Error Codes

| Code | Description | Hint |
|------|-------------|------|
| `AUTH_REQUIRED` | Not authenticated | refly login |
| `INVALID_CREDENTIALS` | Invalid login | Check credentials |
| `SESSION_EXPIRED` | Token expired | Run refly login again |

### Web Error Handling

The web interface implements form validation with user-friendly error messages and loading states:

```typescript
const handleEmailAuth = useCallback(async () => {
  let values: FormValues;
  try {
    values = await form.validateFields();
  } catch (error) {
    console.error('Error validating form fields', error);
    return;
  }
  
  authStore.setLoginProvider('email');
  authStore.setLoginInProgress(true);
  // ... authentication logic
}, []);
```

## Best Practices

1. **CLI Authentication**: Use `refly login` for interactive sessions; use API keys for automated workflows
2. **Token Refresh**: The CLI automatically handles token refresh; ensure network connectivity for re-authentication
3. **Security**: Never commit API keys to version control; use environment variables
4. **Session Management**: Use `refly logout` to clear stored credentials when done

## Related Commands

```bash
refly login        # Authenticate with OAuth or API key
refly logout       # Remove stored credentials
refly status       # Check authentication status
refly whoami       # Display current user information
```

资料来源：[packages/cli/README.md](https://github.com/refly-ai/refly/blob/main/packages/cli/README.md)

---

---

## Doramagic 踩坑日志

项目：refly-ai/refly

摘要：发现 21 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：[Question] Sandbox deployment fails with "AggregateError: All promises were rejected" - Scalebox template and setup inq…。

## 1. 安全/权限坑 · 来源证据：[Question] Sandbox deployment fails with "AggregateError: All promises were rejected" - Scalebox template and setup inq…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Question] Sandbox deployment fails with "AggregateError: All promises were rejected" - Scalebox template and setup inquiry
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0805b730bc2b4c5787cea36e55a118cd | https://github.com/refly-ai/refly/issues/2088 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：v0.5.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.5.0
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0c49752e8b10439aa5eda23446563b9f | https://github.com/refly-ai/refly/releases/tag/v0.5.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：v0.7.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.7.0
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9680da63e17747a5afdc985701b56111 | https://github.com/refly-ai/refly/releases/tag/v0.7.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：v0.8.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.8.0
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_bde62a80a1994e2b89a9741dabace272 | https://github.com/refly-ai/refly/releases/tag/v0.8.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 5. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:759799529 | https://github.com/refly-ai/refly | host_targets=claude, claude_code, cursor

## 6. 配置坑 · 来源证据：translate/index.ts — 429 retries at 1s, 2s, 4s ignore Retry-After, retry budget exhausted in 7 seconds

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：translate/index.ts — 429 retries at 1s, 2s, 4s ignore Retry-After, retry budget exhausted in 7 seconds
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_91f612b63eef439ba150bafe81966117 | https://github.com/refly-ai/refly/issues/2278 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:759799529 | https://github.com/refly-ai/refly | README/documentation is current enough for a first validation pass.

## 8. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:759799529 | https://github.com/refly-ai/refly | last_activity_observed missing

## 9. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:759799529 | https://github.com/refly-ai/refly | no_demo; severity=medium

## 10. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:759799529 | https://github.com/refly-ai/refly | no_demo; severity=medium

## 11. 安全/权限坑 · 来源证据：Security findings in executable artifacts

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security findings in executable artifacts
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6f5d63839cda4472b1c2f6cb1213ef5f | https://github.com/refly-ai/refly/issues/2276 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 12. 安全/权限坑 · 来源证据：v0.10.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.10.0
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_eb88a44b5350452dbe311722dc4d806b | https://github.com/refly-ai/refly/releases/tag/v0.10.0 | 来源类型 github_release 暴露的待验证使用条件。

## 13. 安全/权限坑 · 来源证据：v0.4.2

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.4.2
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_63bd65a5586242c8a4f52bad2217eb37 | https://github.com/refly-ai/refly/releases/tag/v0.4.2 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 安全/权限坑 · 来源证据：v0.6.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.0
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_dd65b4699b5d40b994cbe193f304e92e | https://github.com/refly-ai/refly/releases/tag/v0.6.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 15. 安全/权限坑 · 来源证据：v0.7.1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.7.1
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_99e4528065d24170b07db348f8e8a81f | https://github.com/refly-ai/refly/releases/tag/v0.7.1 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。

## 16. 安全/权限坑 · 来源证据：v0.9.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.9.0
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9db6c700d2e04aef8d4dadd155fe94d3 | https://github.com/refly-ai/refly/releases/tag/v0.9.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 17. 安全/权限坑 · 来源证据：v0.9.1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.9.1
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_49d03f2d9bf4459fa86662b339f44b6f | https://github.com/refly-ai/refly/releases/tag/v0.9.1 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：v1.1.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v1.1.0
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6417649c1639474087639d2d86d6c84c | https://github.com/refly-ai/refly/releases/tag/v1.1.0 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 19. 安全/权限坑 · 来源证据：🤖 Connect your agent to MEEET STATE — earn $MEEET on Solana

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：🤖 Connect your agent to MEEET STATE — earn $MEEET on Solana
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_5e73e7f36609413094647d829f738f1e | https://github.com/refly-ai/refly/issues/2271 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 20. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:759799529 | https://github.com/refly-ai/refly | issue_or_pr_quality=unknown

## 21. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:759799529 | https://github.com/refly-ai/refly | release_recency=unknown

<!-- canonical_name: refly-ai/refly; human_manual_source: deepwiki_human_wiki -->
