DraftReviewPublishedArchived

Build Your Own Agent from Scratch: One Agent-Driven Full-Stack Network Engineering Battle

Three VPSs, one Cloudflare Worker, full AI Agent collaboration

Complete record from buying the first VPS to steady sailing. After experiencing a series of problems such as IP sealing, worker speed limiting, and protocol recognition, the three-layer disaster recovery architecture of AWS Lightsail + Vultr + CF Worker was finally formed. Collaborate on code writing, troubleshooting, and schema design from start to finish with AI Agent.

By Joker04/12/202615 min

QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARS```bash

安装 xray

bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install

生成 Reality 密钥对

xray x25519 Server configuration for Reality:json { "inbounds": [{ "port": 443, "protocol": "vless", "settings": { "clients": [{ "id": "your-uuid", "flow": "xtls-rprx-vision" }], "decryption": "none" }, "streamSettings": { "network": "tcp", "security": "reality", "realitySettings": { "dest": "www.amazon.co.jp:443", "serverNames": ["www.amazon.co.jp"], "privateKey": "your-private-key", "shortIds": ["abcdef"] } } }] } QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSbash

安装 Hysteria2

bash <(curl -fsSL https://get.hy2.sh/)

生成自签证书

openssl req -x509 -nodes -newkey ec:<(openssl ecparam -name prime256v1)
-keyout /etc/hysteria/server.key
-out /etc/hysteria/server.crt
-subj "/CN=www.bing.com" -days 3650

启动

systemctl enable --now hysteria-server QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARStoml

wrangler.toml

[routes] pattern = "your-domain.com" custom_domain = true


###  Pit 2: Worker is speed limited by Cloudflare (most outrageous)

Frequent `wrangler deploy`, deletion and reconstruction during the commissioning stage triggered the internal speed limit of CF.Worker started returning * * HTTP 1101 * * or * * 522 * * errors.

The most bizarre thing is: * * I waited all night and didn't recover * *.Even if the code is replaced with the smallest hello world, the same worker name will still report an error.```javascript
// 最小测试代码 -- 在被限速的 Worker 名称下依然返回 1101
export default {
  async fetch() {
    return new Response("hello");
  }
};
```After a lot of investigation, it was found that:

>  * * The speed limit for CF is for a specific worker name, not at the account level!* * Creating a new Worker with a different name under the same account is completely normal.Solution: Change `wrangler.toml` to `name`, redeploy, and delete the old Worker.

###  Pit 3: Free Plan CPU Limit (10ms/Request)

CF Worker Free Plan Only * * 10ms CPU time * * per request.

I initially stitched the HTML of the admin panel (about 37KB) dynamically in the Worker, more than 400 lines of `push()` calls, and directly timed out.More obscure issues: * * Strings longer than 6000 characters on a single line can cause the V8 engine to crash * *.

Solution: * * HTML pre-built, stored in KV * *.```javascript
// worker.js -- 从 KV 读取 HTML,CPU 时间 < 1ms
if (path === '/admin') {
  const html = await env.CONFIG.get("ADMIN_HTML");
  return new Response(html, {
    headers: { "Content-Type": "text/html;charset=utf-8" }
  });
}
```QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSChoosing a vendor is a hundred times more important than choosing an agreement.

AWS Lightsail $5/month plan: 0.5GB RAM, 2 vCPU, 20GB SSD, * * 1TB of data * *.

###  construction```bash
# 安装 Hysteria2
bash <(curl -fsSL https://get.hy2.sh/)

# 生成自签证书
openssl req -x509 -nodes -newkey ec:<(openssl ecparam -name prime256v1) \
  -keyout /etc/hysteria/server.key \
  -out /etc/hysteria/server.crt \
  -subj "/CN=www.bing.com" -days 3650

# 关键!调整内核 UDP 缓冲区
echo "net.core.rmem_max=16777216" >> /etc/sysctl.conf
echo "net.core.wmem_max=16777216" >> /etc/sysctl.conf
sysctl -p

# 启动
systemctl enable --now hysteria-server
```>  * * Note * *: AlmaLinux 9 * * no firewalld * * on Lightsail, ports to be managed via AWS own firewall:
> ```bash
> aws lightsail open-instance-public-ports \
>   --instance-name "your-instance" \
>   --port-info fromPort=443,toPort=443,protocol=UDP
> ```QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARS```bash
# 必须设置!默认 UDP 缓冲区太小,QUIC 吞吐量上不去
sysctl -w net.core.rmem_max=16777216   # 16MB 接收
sysctl -w net.core.wmem_max=16777216   # 16MB 发送
```If you don't change this, the download speed may be only one-tenth of the theoretical value.

---

##  VII. Self-built subscription system

Multiple VPS + multiple protocols, manual maintenance of client configuration is too cumbersome.Wrote a * * subscription distribution system * * with Cloudflare Worker: the client only needs to import one URL, and all node information is automatically issued.

Worker exposes two endpoints:
- `/clash?token=xxx` — Returns YAML configuration in Clash/mihomo format
- `/base64?token=xxx` — Returns Base64 encoded VLESS link

The IP address of the VPS is stored in KV and read dynamically.The IP has changed, just update the KV, no need to redeploy.```javascript
// 订阅入口
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const token = url.searchParams.get("token");
    if (token !== SECRET_TOKEN)
      return new Response("Not Found", { status: 404 });

    // 从 KV 动态获取 VPS IP
    const awsIP = await env.CONFIG.get("AWS_IP");
    const vultrIP = await env.CONFIG.get("VULTR_IP");

    if (url.pathname === "/clash")
      return generateClashYAML(awsIP, vultrIP);
    if (url.pathname === "/base64")
      return generateBase64Links(awsIP, vultrIP);
  }
};
```###  Shunt Rules

Subscription configurations have built-in full triage rules, based on community rule sets (Loyalsoldier, blackmatrix7):

-  * * AI Services * * (ChatGPT, Claude, Gemini→) Proxy
-  * * Streaming * * (YouTube, Netflix, Spotify→) Proxy
-  * * Social/Dev * * (Telegram, Twitter, GitHub)→ Routing
-  * * domestic website * * (WeChat, Taobao, B station)→ Direct connection
-  * * Microsoft/Apple * * is directly connected → by default and can be switched manually```yaml
rule-providers:
  OpenAI:
    type: http
    behavior: classical
    url: "https://raw.githubusercontent.com/blackmatrix7/ios_rule_script/master/rule/Clash/OpenAI/OpenAI.yaml"
    interval: 86400

rules:
  - RULE-SET,reject,REJECT
  - RULE-SET,OpenAI,AI服务
  - RULE-SET,YouTube,流媒体
  - RULE-SET,Google,代理
  - RULE-SET,direct-domain,DIRECT
  - MATCH,兜底
```QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSThe rear panel of the speed limit also hung up, and nothing was visible.

After separation:
-  * * CF Pages * *: Pure static hosting, not affected by Worker speed limits
-  * * VPS API * *: Python script running on the VPS, through the CF CDN proxy, the worker can hang up to see the status

### VPS Monitoring API

To run a lightweight Python HTTP service on a VPS:```python
# /opt/vps-api/api.py
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/status':
            data = {
                'cpu': get_cpu_usage(),
                'memory': get_memory(),
                'disk': get_disk(),
                'network': get_network_stats(),
                'hysteria2_users': get_hy2_online(),
            }
            self.send_json(data)

# 用 systemd 管理,开机自启
HTTPServer(('0.0.0.0', 2053), Handler).serve_forever()
```QUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSQUERY LENGTH LIMIT EXCEEDED. MAX ALLOWED QUERY : 500 CHARSLightsail + Hysteria2, probably in a day.But it is because of the detours that we have clarified the logic of the blockade, the line differences of each cloud manufacturer, and the various dark pits of the Cloudflare free package.

Self-built agents are not the most economical option, but it is the most transparent option.Where your traffic goes, who sees it, what logs are stored - the answers to these questions can only be determined when you are on your own.

With the blessing of the Agent, the threshold for this matter was greatly reduced.You don't need to be a network engineer, you don't need to be proficient in the details of every protocol - you need clarity of purpose, patience to solve problems, and a reliable AI partner.

---

* Just for study. Comply with local laws and regulations and use technology tools wisely. *
QUEST COMPLETEREWARD: +30 XP, +1 LEGENDARY ITEM
Build Progress100%