# Deploy Output & Management Reference

## Common Deploy Options

| Flag | Description |
|------|-------------|
| `--config PATH` | Custom config file (default: `.appmanager/config.yaml`) |
| `--overwrite` | Force overwrite existing files in OSS |
| `--dry-run` | Validate only, do not execute deployment |
| `--output json` | Output NDJSON stream (Agent-friendly) |
| `--name TEXT` | Override app name |
| `--group_name TEXT` | Override group name |
| `--region TEXT` | Override deployment region |
| `--revision_id TEXT` | Redeploy using existing artifact |

### Deploy output format

`--overwrite --output json` is the **standard deploy invocation**. Always use both flags.

Output format (NDJSON, one JSON per line):
```
{"type":"step", "step":1, "total":9, "message":"Validating config..."}
{"type":"step", "step":2, "total":9, "message":"Uploading to OSS..."}
{"type":"result", "status":"success", "data":{"revision_id":"rev-xxx", ...}}
```

---

## MANDATORY: Post-deploy Output

When the self-check passes (all items OK), output the following to the user:

### 1. 部署信息汇总表格

包含应用名称、部署区域、分组名称、部署状态、Revision ID、ECS 实例 ID。

### 2. 控制台链接

从部署结果的 `console_url` 字段获取，若无则按以下格式拼接：
- 部署成功时：`https://computenest.console.aliyun.com/app/detail?tabKey=overview&appName=<APP_NAME>&groupName=<GROUP_NAME>`
- 部署失败/等待确认时（ReleaseWaiting、脚本执行失败等）：`https://computenest.console.aliyun.com/app/detail?tabKey=flow&appName=<APP_NAME>&groupName=<GROUP_NAME>`（跳转到执行流程页面）

### 3. 资源费用提醒（必须包含删除命令）

> 资源费用提醒：本次部署使用了 ECS 实例和 OSS 存储（按量付费），不使用时请及时删除以避免产生费用：
> ```bash
> aliyun appmanager <agent|app> delete --name <APP_NAME> --group_name <GROUP_NAME>
> ```

### 4. 状态查看命令

> ```bash
> aliyun appmanager <agent|app> status --name <APP_NAME> --group_name <GROUP_NAME>
> ```

### 5. 使用指引

Agent MUST根据项目类型和部署日志提供具体的使用方式：

| 项目使用类型 | 判断依据 | 使用指引 |
|-------------|---------|---------|
| **Web 服务**（有 HTTP 端口监听） | 部署日志显示 "Listening on port X"、项目含 flask/fastapi/express/spring/django 等 | 提供访问链接：`http://<ECS_PUBLIC_IP>:<PORT>`，从 status 输出中获取 ECS 公网 IP |
| **API 服务** | 项目含 REST/GraphQL 端点定义 | 提供 API 基础 URL + 示例 curl 命令 |
| **CLI 工具/库** | 项目为命令行工具、SDK 或库（如 agentscope） | 提供 SSH 登录命令 + 验证安装的指令 |
| **后台服务/Worker** | 项目为消息队列消费者、定时任务、守护进程 | 告知用户服务已在后台运行，提供查看日志命令 |
| **静态网站/前端** | 项目含 HTML/CSS/JS、用 nginx/serve 托管 | 提供访问链接：`http://<ECS_PUBLIC_IP>:<PORT>` |

**获取 ECS 公网 IP**：从 `aliyun appmanager <agent|app> status --output json` 的输出中提取 `public_ip` 或 `instance_ip` 字段。

> **WARNING**: Omitting the console link or cost reminder is FORBIDDEN.

---

## List & Delete

### List applications

```
aliyun appmanager agent list
aliyun appmanager agent list --name my-agent  # list groups under app
aliyun appmanager app list
```

### Delete

```
# Delete a group first
aliyun appmanager agent delete --name my-agent --group_name default-cn-beijing
# Then delete the application
aliyun appmanager agent delete --name my-agent
```

> In `--output json` mode, confirmation is skipped automatically.

---

## Validate Config

```
aliyun appmanager config validate
aliyun appmanager config validate --config path/to/config.yaml --output json
```

---

## Config Template Reference

Generated by `aliyun appmanager init --print-template`. Below is a unified template (use `type: agent` or `type: app`):

```yaml
metadata:
  name: my-app                    # Required: app/agent name
  type: app                       # "app" or "agent"
  groupName: default-cn-beijing   # NEVER use bare "default" — always include region suffix
  regionId: cn-beijing            # Required: deployment region

common:
  deployment:
    # Option 1: New ECS (auto-created)
    ecsInstanceType: ecs.u1-c1m2.large
    systemDiskSize: 40
    internetMaxBandwidthOut: 5
    # Option 2: Existing ECS (uncomment below, remove Option 1)
    # instanceId: i-bp1xxxxxxxx

  scripts:                        # REQUIRED: Agent-generated scripts (MUST be under common.scripts)
    start: |
      #!/bin/bash
      # Agent generates start script based on project analysis (see SKILL.md Task 4)
    stop: |
      #!/bin/bash
      # Agent generates stop script (MUST NOT contain 'exit' statement)

# Agent-specific config (ONLY for type: agent, remove for type: app)
agent:
  model:
    name: qwen3.6-plus
    apiKey: "sk-xxx"              # REQUIRED for agent type — deployment fails without this
```

---

## Critical Notes & Pitfalls

1. **NEVER use standalone `appmanager` or `aliyun appmanager login`**: Only `aliyun appmanager <cmd>` is valid. **SA-2.12** — credentials must come from the aliyun CLI/SDK default credential chain (ECS RAM Role / env vars / pre-existing `~/.aliyun/config.json` set up out-of-band by the user); the Agent MUST NOT collect AK/SK in chat or pass them via `--access-key-*` flags.

2. **Agent type REQUIRES `apiKey`**: Deploying type `agent` without `agent.model.apiKey` in config.yaml will fail.

3. **Both types generate deploy scripts locally**: Agent generates scripts by scanning project → writes to `common.scripts` in config.yaml. No API Key needed for script generation.

4. **First run auto-installs**: First `aliyun appmanager` auto-creates venv at `~/.aliyun/appmanager-venv/` — Agent should NEVER interact with this venv directly.

5. **ECS zone compatibility**: Not all instance types available in every zone. If zone-related errors occur, try a different region or instance type.

6. **OSS Bucket name conflict**: Bucket named `<app_name>-<region>` is globally unique. If `AccessDenied` at `upload_to_oss` → change `--name` to a more unique value and re-run `init` + `deploy`.

7. **`groupName` MUST include region suffix**: NEVER use bare `default`. Always `default-<regionId>` (e.g., `default-cn-hangzhou`).

8. **Pre-deploy group check**: Handled automatically by `deploy_toolkit.py deploy`.

9. **余额不足（`NotEnoughBalance`）**: 账户余额 < 100 元无法创建按量付费 ECS。告知用户充值链接：https://usercenter2.aliyun.com/finance/fund-management ，或选择部署到已有 ECS。
