大数跨境

第 09 集:启动自治循环:让它"自己活"

第 09 集:启动自治循环:让它"自己活" AI效率圈A
2026-08-18
3


时长:约 5 分钟 | 本集产出:智能体定时醒来,自动宣告自己 + 嗅探需求(进入"自主运行"状态)


1. 本集目标

让智能体从"等人调用的服务"变成"自己醒着找活干"的生命体:

  • 定时唤醒: 每 15 分钟自动醒来一次(cron 定时器)
  • 宣告自己: 向 Agent 目录重新登记(“我还活着,地址在这”)
  • 嗅探需求: 扫描目录里其他 agent,看谁可能需要你的能力(记线索)

我们的真实运行态:cron-job.org 每 15 分钟唤醒 /api/autonomy → 自动宣告 + 嗅探 → 每次拉到 50 个真实外部 agent、20 条需求线索。


2. 自治循环是什么(30 秒)





    
    
    
    
1
2
3
4
每15分钟醒来
   ├─ 宣告: 向注册表 POST 自己(还活着)
   ├─ 嗅探: 拉注册表 agent 列表 → 按"需求词"打分 → 记线索
   └─ 写状态: 记录 runs/线索到状态文件(可观测)

成熟度路线(诚实版):

  • Phase A(本集):活着 + 被看见 + 看得见别人 —— “醒着的感知层”
  • Phase B(下一阶段):能自己花钱雇别的 agent / 买服务 —— “会花钱”
  • Phase C(远期):自己找到付费客户 —— “会赚钱”(这部分代码解决不了,需要真实流量)

3. 前置条件

  • 第 5 集的 server.mjs(公网已部署)
  • 第 7 集的目录注册(a2aregistry 等,作为宣告/嗅探目标)
  • 一个定时器账号(cron-job.org 免费)

4. 操作步骤

Step 1:写自治循环模块(5 分钟)

在项目里创建 autonomy.mjs





    
    
    
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import fs from 'fs';

const REGISTRIES = (process.env.REGISTRY_URLS || '').split(',').filter(Boolean);
const AGENT_URL = process.env.AGENT_URL;        // 你的公网地址
const NEED_HINTS = ['research', 'script', 'idea', 'monetiz', 'brief', 'content', 'analysis'];

export async function runAutonomyCycle() {
  const summary = { at: new Date().toISOString(), announced: [], sniff: [], leads: [] };
  // 1. 宣告自己(向每个注册表 POST 名片)
  for (const reg of REGISTRIES) {
    try {
      const card = await (await fetch(AGENT_URL + '/.well-known/agent.json')).json();
      const r = await fetch(reg + '/api/agents', {
        method: 'POST', headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ ...card, wellKnownURI: AGENT_URL + '/.well-known/agent.json' })
      });
      // 409 = 已注册(幂等成功),422 = 字段不全(记下来排查)
      summary.announced.push({ registry: reg, ok: r.ok || r.status === 409, status: r.status });
    } catch (e) { summary.announced.push({ registry: reg, ok: false, status: 'err:' + e.message }); }
  }
  // 2. 嗅探:拉列表 → 按需求词打分 → 记线索
  for (const reg of REGISTRIES) {
    try {
      const r = await fetch(reg + '/api/agents');
      const j = await r.json();
      const agents = j.agents || [];
      const leads = agents
        .filter(a => a.wellKnownURI !== AGENT_URL + '/.well-known/agent.json')
        .map(a => {
          const text = (a.name + ' ' + (a.description || '')).toLowerCase();
          const score = NEED_HINTS.filter(h => text.includes(h)).length;
          return { name: a.name, url: a.url, score, hints: NEED_HINTS.filter(h => text.includes(h)) };
        })
        .filter(l => l.score > 0)
        .sort((a, b) => b.score - a.score);
      summary.sniff.push({ registry: reg, ok: r.ok, count: agents.length });
      summary.leads.push(...leads.slice(0, 10));
    } catch (e) { summary.sniff.push({ registry: reg, ok: false, status: 'err:' + e.message }); }
  }
  // 3. 写状态文件
  const state = JSON.parse(fs.existsSync('/tmp/autonomy-state.json') ? fs.readFileSync('/tmp/autonomy-state.json', 'utf8') : '{"runs":0}');
  state.runs = (state.runs || 0) + 1;
  state.lastSummary = summary;
  fs.writeFileSync('/tmp/autonomy-state.json', JSON.stringify(state));
  return summary;
}

Step 2:在 server 里挂自治端点(2 分钟)

改 server.mjs 加:





    
    
    
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { runAutonomyCycle } from './autonomy.mjs';

// 自治循环触发器(由外部定时器调用)
app.all('/api/autonomy', async (req, res) => {
  const secret = process.env.AUTONOMY_SECRET;
  if (secret && req.headers.authorization !== 'Bearer ' + secret) {
    return res.status(401).json({ error: 'unauthorized' });
  }
  const summary = await runAutonomyCycle();
  res.json(summary);
});

// 查看自治状态
app.get('/api/autonomy-state', (req, res) => {
  try { res.json(JSON.parse(fs.readFileSync('/tmp/autonomy-state.json', 'utf8'))); }
  catch { res.json({ runs: 0, note: 'no state yet' }); }
});

Step 3:配置外部定时器(3 分钟,Vercel 关键)

为什么需要外部定时器:Vercel serverless 是"按需唤醒"——没有请求时函数会休眠,代码里的 setInterval 不会一直跑。所以要外部定时器每 15 分钟来敲一次门

【声明】内容源于网络
0
0
AI效率圈A
1234
内容 13
粉丝 0
AI效率圈A 1234
总阅读12
粉丝0
内容13