@sleep2agi/agent-node 2.1.1 → 2.1.2-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +101 -204
- package/dist/cli.js +14 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,251 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sleep2agi/agent-node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Agent runtime for Agent Network. Connects to a CommHub server, registers under an alias, and processes incoming tasks with one of three runtimes.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**v2.1.1 stable.** The supported entry point is the `anet` CLI from `@sleep2agi/agent-network@2.0.0`, which writes the right `config.json` and environment variables for you.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
npx @sleep2agi/agent-node --alias "我的Agent" --hub http://YOUR_HUB:9200 --tools all
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
---
|
|
7
|
+
## Install
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
You usually don't install this package directly — `anet node create` and `anet node start` use it via `npx`. To pin it:
|
|
14
10
|
|
|
15
|
-
|
|
11
|
+
```bash
|
|
12
|
+
npm install -g @sleep2agi/agent-node
|
|
13
|
+
```
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
## Verified flow
|
|
18
16
|
|
|
19
|
-
```
|
|
20
|
-
agent-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
│
|
|
27
|
-
└── runtime: http-api ─→ 直接 HTTP 调用 (V2 新增)
|
|
28
|
-
└── OpenAI/Anthropic 兼容 API → MiniMax/DeepSeek 等
|
|
17
|
+
```bash
|
|
18
|
+
npm install -g @sleep2agi/agent-network
|
|
19
|
+
anet hub start # local hub (terminal 1)
|
|
20
|
+
anet hub dashboard # web UI (terminal 2)
|
|
21
|
+
anet login --username admin --password anethub
|
|
22
|
+
anet node create my-bot # two-step picker: runtime, then provider
|
|
23
|
+
anet node start my-bot # → SSE connected
|
|
29
24
|
```
|
|
30
25
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
基于 Anthropic 的 [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-typescript),底层 spawn `claude` CLI 进程。
|
|
34
|
-
|
|
35
|
-
**核心调用**:
|
|
36
|
-
```typescript
|
|
37
|
-
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
38
|
-
|
|
39
|
-
for await (const message of query({
|
|
40
|
-
prompt: "任务内容",
|
|
41
|
-
options: {
|
|
42
|
-
model: "MiniMax-M2.7", // 支持任意 Anthropic API 兼容模型
|
|
43
|
-
tools: ["Read", "Bash", "Grep"],
|
|
44
|
-
maxTurns: 5,
|
|
45
|
-
permissionMode: "bypassPermissions",
|
|
46
|
-
settingSources: [], // 隔离全局配置,防止串网
|
|
47
|
-
}
|
|
48
|
-
})) {
|
|
49
|
-
if (message.type === "result") console.log(message.result);
|
|
50
|
-
}
|
|
51
|
-
```
|
|
26
|
+
The picker writes `.anet/nodes/<name>/config.json`. `anet node start` reads it and runs this package under the hood.
|
|
52
27
|
|
|
53
|
-
|
|
28
|
+
## Direct invocation
|
|
54
29
|
|
|
55
|
-
|
|
30
|
+
For scripts and CI:
|
|
56
31
|
|
|
57
32
|
```bash
|
|
58
|
-
|
|
59
|
-
ANTHROPIC_BASE_URL=https://api.minimax.io/anthropic
|
|
60
|
-
ANTHROPIC_AUTH_TOKEN=your-minimax-key
|
|
61
|
-
|
|
62
|
-
# 书生 Intern-S1-Pro
|
|
63
|
-
ANTHROPIC_BASE_URL=https://chat.intern-ai.org.cn
|
|
64
|
-
ANTHROPIC_AUTH_TOKEN=your-intern-key
|
|
33
|
+
npx @sleep2agi/agent-node --alias my-bot --hub http://127.0.0.1:9200 --tools all
|
|
65
34
|
```
|
|
66
35
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
**已验证功能**:
|
|
70
|
-
- ✅ 单轮/多轮对话
|
|
71
|
-
- ✅ tool_use(Read/Write/Edit/Bash/Glob/Grep/WebSearch/WebFetch)
|
|
72
|
-
- ✅ Extended Thinking(`<think>` 标签)
|
|
73
|
-
- ✅ Session Resume(跨 query 保持上下文)
|
|
74
|
-
- ✅ SSE streaming
|
|
75
|
-
- ✅ Hooks(PreToolUse/PostToolUse)
|
|
76
|
-
- ✅ maxBudgetUsd 预算控制
|
|
77
|
-
- ✅ settingSources 隔离(防止读全局 MCP 配置串网)
|
|
78
|
-
|
|
79
|
-
### Codex SDK(`--runtime codex`)
|
|
36
|
+
CLI flags:
|
|
80
37
|
|
|
81
|
-
|
|
38
|
+
| Flag | Default | Notes |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `--alias` | required | unique name in the hub |
|
|
41
|
+
| `--hub` | `http://127.0.0.1:9200` | CommHub URL |
|
|
42
|
+
| `--runtime` | `claude-agent-sdk` | `claude-agent-sdk` / `codex-sdk` / `claude-code-cli` |
|
|
43
|
+
| `--model` | runtime default | passed through to the SDK |
|
|
44
|
+
| `--tools` | (none) | `all` or comma-separated list |
|
|
45
|
+
| `--max-turns` | `50` | upper bound per task |
|
|
46
|
+
| `--session` | (none) | resume a prior session / thread |
|
|
82
47
|
|
|
83
|
-
|
|
84
|
-
```typescript
|
|
85
|
-
import Codex from "@openai/codex-sdk";
|
|
48
|
+
## Runtimes
|
|
86
49
|
|
|
87
|
-
|
|
88
|
-
|
|
50
|
+
| Runtime | Backend | Status | Notes |
|
|
51
|
+
|---|---|---|---|
|
|
52
|
+
| `claude-agent-sdk` | [@anthropic-ai/claude-agent-sdk](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk) | verified | Anthropic Messages API; works with any compatible endpoint |
|
|
53
|
+
| `codex-sdk` | [@openai/codex-sdk](https://www.npmjs.com/package/@openai/codex-sdk) | unverified end-to-end | unit tests pass, no full E2E with real codex auth |
|
|
54
|
+
| `claude-code-cli` | local `claude` CLI | unverified end-to-end | runs locally for Claude Pro subscribers |
|
|
89
55
|
|
|
90
|
-
|
|
91
|
-
model: "gpt-5.4",
|
|
92
|
-
thread_id: thread.id,
|
|
93
|
-
input: "任务内容",
|
|
94
|
-
tools: [{ type: "code_interpreter" }, { type: "file_search" }],
|
|
95
|
-
});
|
|
56
|
+
Runtimes are loaded lazily — picking one doesn't pull the others' dependencies. `claude-code-cli` adds zero extra SDK weight.
|
|
96
57
|
|
|
97
|
-
|
|
98
|
-
```
|
|
58
|
+
## Provider presets (claude-agent-sdk)
|
|
99
59
|
|
|
100
|
-
|
|
101
|
-
- 不需要额外 API key(复用 `codex` CLI 登录态)
|
|
102
|
-
- 支持 gpt-5.4(默认)/ o3 / o4-mini
|
|
103
|
-
- Thread 保持上下文(多轮对话)
|
|
104
|
-
- Thread 过期自动重建
|
|
60
|
+
`anet node create` step 2 picks one of these and writes `ANTHROPIC_BASE_URL` + a default model. All Anthropic-compatible HTTP API; `--model` is passed through verbatim.
|
|
105
61
|
|
|
106
|
-
|
|
62
|
+
| Provider | Base URL | Default model | Status |
|
|
63
|
+
|---|---|---|---|
|
|
64
|
+
| Anthropic | `https://api.anthropic.com` | `claude-sonnet-4-5` | verified |
|
|
65
|
+
| MiniMax (国际) | `https://api.minimax.io/anthropic` | `MiniMax-M2.7` | verified |
|
|
66
|
+
| MiniMax (国内) | `https://api.minimaxi.com/anthropic` | `MiniMax-M2.7` | verified |
|
|
67
|
+
| DeepSeek | `https://api.deepseek.com/anthropic` | `deepseek-chat` | verified |
|
|
68
|
+
| GLM (智谱) | `https://open.bigmodel.cn/api/anthropic` | `glm-4-plus` | verified |
|
|
69
|
+
| Kimi (Moonshot) | `https://api.moonshot.cn/anthropic` | `moonshot-v1-32k` | verified |
|
|
70
|
+
| OpenRouter | `https://openrouter.ai/api/v1` | (user-chosen) | unverified end-to-end |
|
|
71
|
+
| Custom | user-supplied | user-supplied | unverified end-to-end |
|
|
107
72
|
|
|
108
|
-
##
|
|
73
|
+
## Manual env-var examples
|
|
109
74
|
|
|
110
|
-
|
|
75
|
+
```bash
|
|
76
|
+
# DeepSeek
|
|
77
|
+
ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic \
|
|
78
|
+
ANTHROPIC_AUTH_TOKEN=sk-... \
|
|
79
|
+
npx @sleep2agi/agent-node --alias deep --hub http://127.0.0.1:9200 --tools all
|
|
111
80
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
↓
|
|
117
|
-
SSE 长连接 /events/:alias
|
|
118
|
-
↓
|
|
119
|
-
┌─→ 收到 new_task 事件
|
|
120
|
-
│ ↓
|
|
121
|
-
│ get_inbox → 拿任务内容
|
|
122
|
-
│ ↓
|
|
123
|
-
│ ack_inbox → 确认收到
|
|
124
|
-
│ ↓
|
|
125
|
-
│ report_status: working
|
|
126
|
-
│ ↓
|
|
127
|
-
│ AI 处理(claude/codex/http-api)
|
|
128
|
-
│ ↓
|
|
129
|
-
│ send_reply → 回报结果(V2: 关联 task_id)
|
|
130
|
-
│ ↓
|
|
131
|
-
│ report_status: idle
|
|
132
|
-
│ ↓
|
|
133
|
-
└─── 等待下一个任务
|
|
134
|
-
↓ (每 3 分钟)
|
|
135
|
-
heartbeat → report_status: idle
|
|
81
|
+
# MiniMax
|
|
82
|
+
ANTHROPIC_BASE_URL=https://api.minimax.io/anthropic \
|
|
83
|
+
ANTHROPIC_AUTH_TOKEN=your-key \
|
|
84
|
+
npx @sleep2agi/agent-node --alias mini --model MiniMax-M2.7 --hub http://127.0.0.1:9200 --tools all
|
|
136
85
|
```
|
|
137
86
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
87
|
+
## Configuration file
|
|
88
|
+
|
|
89
|
+
Typical output of `anet node create` at `.anet/nodes/<name>/config.json`:
|
|
90
|
+
|
|
91
|
+
```json
|
|
92
|
+
{
|
|
93
|
+
"alias": "my-bot",
|
|
94
|
+
"hub": "http://127.0.0.1:9200",
|
|
95
|
+
"runtime": "claude-agent-sdk",
|
|
96
|
+
"model": "MiniMax-M2.7",
|
|
97
|
+
"anthropic_base_url": "https://api.minimax.io/anthropic",
|
|
98
|
+
"anthropic_auth_token": "sk-...",
|
|
99
|
+
"tools": "all",
|
|
100
|
+
"maxTurns": 50,
|
|
101
|
+
"dangerouslySkipPermissions": true,
|
|
102
|
+
"teammateMode": true
|
|
153
103
|
}
|
|
154
104
|
```
|
|
155
105
|
|
|
156
|
-
|
|
106
|
+
Per-node config wins over `~/.anet/config.json`; missing fields fall back to global, then defaults.
|
|
157
107
|
|
|
158
|
-
##
|
|
108
|
+
## Main loop
|
|
159
109
|
|
|
160
|
-
|
|
110
|
+
Same shape across runtimes:
|
|
161
111
|
|
|
162
112
|
```
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
→ AI 只能用 agent-node 显式传的工具
|
|
113
|
+
start
|
|
114
|
+
→ report_status: idle
|
|
115
|
+
→ SSE long-poll /events/:alias
|
|
116
|
+
→ on new_task: get_inbox → ack_inbox
|
|
117
|
+
→ report_status: working
|
|
118
|
+
→ run the LLM (with commhub MCP tools injected)
|
|
119
|
+
→ send_reply
|
|
120
|
+
→ report_status: idle
|
|
172
121
|
```
|
|
173
122
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
## 📊 模型对照表
|
|
177
|
-
|
|
178
|
-
| 模型 | runtime | 环境变量 | 默认 |
|
|
179
|
-
|------|---------|---------|------|
|
|
180
|
-
| MiniMax M2.7(国际) | claude | `ANTHROPIC_BASE_URL=https://api.minimax.io/anthropic` | |
|
|
181
|
-
| MiniMax M2.7(国内) | claude | `ANTHROPIC_BASE_URL=https://api.minimaxi.com/anthropic` | |
|
|
182
|
-
| 书生 Intern-S1-Pro | claude | `ANTHROPIC_BASE_URL=https://chat.intern-ai.org.cn` | |
|
|
183
|
-
| Claude Sonnet 4.6 | claude | `ANTHROPIC_API_KEY=key` | ✅ |
|
|
184
|
-
| GPT-5.4 | codex | 不需要(复用 codex 登录) | ✅ |
|
|
185
|
-
| o3 | codex | 不需要 | |
|
|
186
|
-
| o4-mini | codex | 不需要 | |
|
|
187
|
-
|
|
188
|
-
---
|
|
189
|
-
|
|
190
|
-
## 🚀 快速启动
|
|
191
|
-
|
|
192
|
-
```bash
|
|
193
|
-
# MiniMax(低成本)
|
|
194
|
-
ANTHROPIC_BASE_URL=https://api.minimax.io/anthropic \
|
|
195
|
-
ANTHROPIC_AUTH_TOKEN=your-key \
|
|
196
|
-
npx @sleep2agi/agent-node --alias 小明 --model MiniMax-M2.7 --hub http://IP:9200 --tools all
|
|
197
|
-
|
|
198
|
-
# 书生(国产)
|
|
199
|
-
ANTHROPIC_BASE_URL=https://chat.intern-ai.org.cn \
|
|
200
|
-
ANTHROPIC_AUTH_TOKEN=your-key \
|
|
201
|
-
npx @sleep2agi/agent-node --alias 书生 --model intern-s1-pro --hub http://IP:9200 --tools all
|
|
202
|
-
|
|
203
|
-
# Codex GPT-5.4(OpenAI)
|
|
204
|
-
npx @sleep2agi/agent-node --alias Codex马 --runtime codex --hub http://IP:9200 --tools all
|
|
205
|
-
|
|
206
|
-
# Claude
|
|
207
|
-
ANTHROPIC_API_KEY=your-key \
|
|
208
|
-
npx @sleep2agi/agent-node --alias Claude马 --hub http://IP:9200 --tools all
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
---
|
|
212
|
-
|
|
213
|
-
## ⚙️ CLI 参数
|
|
214
|
-
|
|
215
|
-
| 参数 | 默认值 | 说明 |
|
|
216
|
-
|------|--------|------|
|
|
217
|
-
| `--alias` | 必填 | Agent 名称 |
|
|
218
|
-
| `--hub` | `http://127.0.0.1:9200` | CommHub URL |
|
|
219
|
-
| `--runtime` | `claude` | `claude` / `codex` / `http-api` / `minimax` |
|
|
220
|
-
| `--model` | 按 runtime | codex: `gpt-5.4`, http-api: `claude-3-5-haiku-20241022` |
|
|
221
|
-
| `--tools` | 无 | `all` 或逗号分隔 |
|
|
222
|
-
| `--max-turns` | `5` | 每任务最大轮次 |
|
|
223
|
-
| `--max-budget` | 无 | 每任务预算(美元) |
|
|
224
|
-
| `--session` | 无 | 恢复指定 session/thread |
|
|
225
|
-
| `--prompt` | 无 | 自定义 system prompt |
|
|
123
|
+
## Peer coordination (verified)
|
|
226
124
|
|
|
227
|
-
|
|
125
|
+
When the agent runs, the commhub MCP tools are auto-injected. The model can call:
|
|
228
126
|
|
|
229
|
-
|
|
127
|
+
- `commhub_get_all_status()` — see who else is online
|
|
128
|
+
- `commhub_send_task(alias, task)` — dispatch a sub-task to a peer
|
|
129
|
+
- `commhub_get_task(task_id)` — poll for the peer's reply
|
|
130
|
+
- `commhub_send_message(alias, message)` — chat without a task lifecycle
|
|
131
|
+
- `commhub_report_status(status, task)` — push status update
|
|
230
132
|
|
|
231
|
-
|
|
232
|
-
|---|------------|
|
|
233
|
-
| `@anthropic-ai/claude-agent-sdk` | `--runtime claude` 时(动态 import) |
|
|
234
|
-
| `@openai/codex-sdk` | `--runtime codex` 时(动态 import) |
|
|
235
|
-
| 无外部依赖 | `--runtime http-api` 时(内置 fetch) |
|
|
133
|
+
This is what powers the multi-agent flow demonstrated in `anet hub dashboard` (e.g. ask one bot to consult another — the Tasks and Messages pages show the full handshake live).
|
|
236
134
|
|
|
237
|
-
|
|
135
|
+
## Isolation
|
|
238
136
|
|
|
239
|
-
|
|
137
|
+
When the runtime is `claude-code-cli`, the spawned subprocess gets `settingSources: []` so it doesn't read the host's `~/.claude.json` and accidentally cross networks.
|
|
240
138
|
|
|
241
|
-
##
|
|
139
|
+
## Companion packages
|
|
242
140
|
|
|
243
|
-
| | |
|
|
141
|
+
| Package | Version |
|
|
244
142
|
|---|---|
|
|
245
|
-
|
|
|
246
|
-
|
|
|
247
|
-
|
|
|
248
|
-
| **Dashboard** | [agent-net.vansin.me](https://agent-net.vansin.me) |
|
|
143
|
+
| [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.0.0 |
|
|
144
|
+
| [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) | 0.5.0 |
|
|
145
|
+
| [@sleep2agi/agent-network-dashboard](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.1.0 |
|
|
249
146
|
|
|
250
147
|
## License
|
|
251
148
|
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as Mz}from"node:module";var b=Mz(import.meta.url);import{readFileSync as f,existsSync as a,writeFileSync as t,chmodSync as bz}from"fs";import{join as U}from"path";import{hostname as e,homedir as Rz}from"os";import{mkdirSync as Fz,appendFileSync as Iz}from"fs";var __dirname="/home/vansin/agent-orchestra/agent-node/src";var Jz=Rz(),M=process.argv.slice(2),v={},qz=[],Wz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(f(U(z,Z),"utf-8"));if($.version){Wz=$.version;break}}catch{}}catch{}for(let z=0;z<M.length;z++){if(M[z]==="--version"||M[z]==="-v")console.log(`agent-node v${Wz}`),process.exit(0);if(M[z]==="-h"||M[z]==="--help")console.log(`
|
|
3
3
|
@sleep2agi/agent-node — AI Agent 节点,一行命令加入 CommHub 网络
|
|
4
4
|
|
|
5
5
|
用法:
|
|
@@ -24,21 +24,22 @@ import{createRequire as bz}from"node:module";var N=bz(import.meta.url);import{re
|
|
|
24
24
|
Runtime:
|
|
25
25
|
claude-agent-sdk Claude Agent SDK — Claude/MiniMax/Anthropic 兼容 API
|
|
26
26
|
codex-sdk Codex SDK — GPT-5.4,复用 codex 登录态
|
|
27
|
-
`),process.exit(0);if(
|
|
28
|
-
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var
|
|
29
|
-
`),
|
|
30
|
-
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let Y=$.slice(0,Q).trim(),X=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=X}}function Ez(z){return U(process.cwd(),".anet","nodes",H,"channels",z)}function Tz(z){let Z=z.path||Ez("telegram");Oz(U(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${U(Z,".env")}`),process.exit(1);try{
|
|
31
|
-
`)}catch{}}var
|
|
32
|
-
`)
|
|
27
|
+
`),process.exit(0);if(M[z]==="--new-session"){v["new-session"]="true";continue}if(M[z]==="--channel"&&z+1<M.length){qz.push(M[++z]);continue}if(M[z].startsWith("--")&&z+1<M.length)v[M[z].slice(2)]=M[++z]}function Gz(z){return z.replace(/^~(?=\/|$)/,Jz)}function Pz(z){let Z=z.indexOf(":");if(Z<0)return{type:z,raw:z};if(Z===0||Z===z.length-1)throw Error(`invalid channel spec "${z}" (expected type or type:path)`);return{type:z.slice(0,Z),path:Gz(z.slice(Z+1)),raw:z}}function p(z){if(!a(z))return null;try{return JSON.parse(f(z,"utf-8"))}catch{return null}}var j={},N="";if(v.config){let z=v.config.startsWith("/")?v.config:U(process.cwd(),v.config),Z=p(z);if(Z)j=Z,N=z,console.log(`[agent-node] Config: ${z}`)}var H=v.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||j.alias;if(!v.config&&H){let z=U(process.cwd(),".anet","nodes",H,"config.json"),Z=U(process.cwd(),".anet","profiles",`${H}.json`),$=a(z)?z:Z,Q=p($);if(Q){if(j={...Q,...j},N=$,console.log(`[agent-node] Config: ${$}`),Q.env&&typeof Q.env==="object"){for(let[Y,X]of Object.entries(Q.env))if(!process.env[Y]&&typeof X==="string")process.env[Y]=Gz(X)}}}var E=p(U(Jz,".anet","config.json"))||{};if(E.hub&&!j.hub)j.hub=E.hub;if(E.token&&!j.token)j.token=E.token;if(!v.config&&!Object.keys(j).length){let z=p(U(process.cwd(),".agent-node.json"));if(z)j=z,console.log("[agent-node] 配置: .agent-node.json")}if(!H)console.error(`错误: 必须指定 --alias
|
|
28
|
+
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var jz=v.runtime||process.env.RUNTIME||j.runtime||"claude-agent-sdk",xz={"claude-agent-sdk":"claude","claude-sdk":"claude","agent-sdk":"claude",claude:"claude","codex-sdk":"codex",codex:"codex","http-api":"http","openai-api":"http",minimax:"http"},C=xz[jz]||"claude",yz=jz,d=v.url||v.hub||process.env.COMMHUB_URL||j.hub||"http://127.0.0.1:9200",x=v.model||process.env.MODEL||j.model,Nz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],zz=v.tools||(Array.isArray(j.tools)?j.tools.join(","):j.tools)||"",T=zz==="all"?Nz:zz.split(",").filter(Boolean),Lz=parseInt(v["max-turns"]||j.flags?.maxTurns||j.maxTurns||"50"),Zz=parseFloat(v["max-budget"]||j.flags?.maxBudgetUsd||j.maxBudgetUsd||"0"),Az=v["new-session"]==="true",A=Az?"":v.session||j.session||j.resume||j.sessionId||"",O=v.prompt||j.systemPrompt||"",L=j.token||E.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&j.token&&process.env.COMMHUB_TOKEN!==j.token)console.warn(`[${H}] ⚠ COMMHUB_TOKEN env override ignored (using node config token). Unset COMMHUB_TOKEN to silence this warning.`);var s=v["log-dir"]||U(process.cwd(),".anet","nodes",H,"logs"),Cz={debug:0,info:1,warn:2,error:3},_z=Cz[v["log-level"]||process.env.LOG_LEVEL||j.logLevel||"info"]??1,S=[...(Array.isArray(j.channels)?j.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...qz],Bz=S.map((z)=>{try{return Pz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function Kz(z){if(!N||!z)return;try{let Z=JSON.parse(f(N,"utf-8"));if(Z.session===z)return;Z.session=z,t(N,JSON.stringify(Z,null,2)+`
|
|
29
|
+
`),R(`session 写回: ${N} → ${z.slice(0,8)}...`)}catch(Z){_(`writebackSession failed: ${Z.message}`)}}function Oz(z){if(!a(z))return;for(let Z of f(z,"utf-8").split(`
|
|
30
|
+
`)){let $=Z.trim();if(!$||$.startsWith("#"))continue;let Q=$.indexOf("=");if(Q<=0)continue;let Y=$.slice(0,Q).trim(),X=$.slice(Q+1).trim().replace(/^['"]|['"]$/g,"");if(!process.env[Y])process.env[Y]=X}}function Ez(z){return U(process.cwd(),".anet","nodes",H,"channels",z)}function Tz(z){let Z=z.path||Ez("telegram");Oz(U(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${U(Z,".env")}`),process.exit(1);try{bz(U(Z,".env"),384)}catch{}let Q=p(U(Z,"access.json"))||{},Y=U(Z,"inbox");try{Fz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var n=Bz.filter((z)=>z.type==="telegram").map(Tz),$z=Bz.find((z)=>z.type!=="telegram");if($z)console.error(`[agent-node] unsupported channel: ${$z.raw}`),process.exit(1);if(n.length>0&&C!=="codex"&&!T.includes("Read"))T.push("Read");try{Fz(s,{recursive:!0})}catch{}function i(z,Z,$){if(Z<_z)return;let Q=new Date().toTimeString().slice(0,8),Y=z.toUpperCase().padEnd(5),X=`[${Q}] [${Y}] [${H}] ${$}`;console.log(X);try{let W=new Date().toISOString().slice(0,10);Iz(U(s,`${W}.log`),X+`
|
|
31
|
+
`)}catch{}}var V=(z)=>i("info",1,z),R=(z)=>i("debug",0,z),_=(z)=>i("warn",2,z),h=(z)=>i("error",3,z);async function c(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(L)Q.Authorization=`Bearer ${L}`;let Y;for(let X=0;X<=$;X++)try{let W=await fetch(`${d}/mcp`,{method:"POST",headers:Q,body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:z,arguments:Z}})});if(!W.ok&&X<$){Y=Error(`HTTP ${W.status}`),await new Promise((w)=>setTimeout(w,1000*Math.pow(2,X)));continue}let q=await W.text(),B=q.match(/data: (.+)/),F=B?JSON.parse(B[1]):JSON.parse(q),K=F?.result?.content?.[0]?.text;return K?JSON.parse(K):F}catch(W){if(Y=W,X<$)R(`callCommHub(${z}) attempt ${X+1} failed: ${W.message}, retrying...`),await new Promise((q)=>setTimeout(q,1000*Math.pow(2,X)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var r=j.node_id||"",uz=j.node_name||"",u=j.network_id||process.env.ANET_NETWORK_ID||E.network_id||"",wz=r?`sdk-${r}`:`sdk-${H}-${Date.now().toString(36)}`,Sz=()=>c("report_status",{resume_id:wz,alias:H,status:"idle",server:e(),hostname:e(),agent:`agent-node:${C}`,project_dir:process.cwd(),node_id:r||void 0,node_name:uz||void 0,session_id:A||void 0,config_path:N||void 0,channels:S.length?JSON.stringify(S):void 0,model:x||void 0,network_id:u||void 0}),l=(z,Z)=>c("report_status",{resume_id:wz,alias:H,status:z,task:Z,node_id:r||void 0,session_id:m||A||void 0,config_path:N||void 0,channels:S.length?JSON.stringify(S):void 0,network_id:u||void 0}),hz=async()=>(await c("get_inbox",{alias:H,limit:20}))?.messages||[],fz=(z)=>c("ack_inbox",{alias:H,message_id:z}),pz=(z,Z,$,Q=!1)=>c("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:Q?"failed":"replied"}),m=A||void 0;async function dz(z,Z){let{existsSync:$}=await import("fs"),Q=!1;try{let G=b.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(G))Q=!0}catch{}if(!Q)try{let{execSync:G}=await import("child_process");G("which claude",{stdio:"pipe"}),Q=!0}catch{}if(!Q&&process.platform==="linux")try{let{execSync:G}=await import("child_process");V("[claude] no Claude binary found — installing @anthropic-ai/claude-agent-sdk-linux-x64 (glibc) ..."),G("npm install --no-save --prefix "+JSON.stringify(__dirname+"/../")+" @anthropic-ai/claude-agent-sdk-linux-x64",{stdio:"pipe",timeout:60000});try{let J=b.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(J))Q=!0,V(`[claude] glibc binary installed: ${J}`)}catch{}}catch(G){V(`[claude] auto-install of glibc binary failed: ${G?.message||G}`)}if(!Q)return["claude 错误: Claude Code 二进制未找到。","agent-node 默认运行 claude-agent-sdk runtime 需要 Claude Code 本地二进制。","解决方案:"," 1. 全局安装 Claude Code: npm i -g @anthropic-ai/claude-code"," 2. 或者切换到 codex-sdk runtime: anet node create <name> --runtime codex-sdk (需 codex auth login)"," 3. 或者在 node config.json 里设 pathToClaudeCodeExecutable 指向已安装的 claude 二进制"].join(`
|
|
32
|
+
`);let{query:Y}=await import("@anthropic-ai/claude-agent-sdk"),X=[`你是 ${H},一个 AI Agent 节点。收到来自 ${Z} 的任务:`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。","2. 用 mcp_commhub__send_task(alias, task) 派给合适的 agent,记下 task_id。","3. 用 mcp_commhub__get_task(task_id) 轮询直到 status 是 replied 或 failed,拿到 reply 内容。",`4. 把对方的 reply 整合到你给 ${Z} 的最终汇报里。`,"","【禁止】",`- 不要给自己(${H})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。","","执行完后简要汇报结果。"].join(`
|
|
33
|
+
`),W=O?`${O}
|
|
33
34
|
|
|
34
35
|
收到来自 ${Z} 的任务:
|
|
35
36
|
|
|
36
|
-
${z}`:
|
|
37
|
-
`),Qz={model_auto_compact_token_limit:200000,developer_instructions:cz};async function mz(z,Z,$){try{let{execSync:
|
|
38
|
-
`)||"",
|
|
37
|
+
${z}`:X,q=process.env.COMMHUB_URL||d,B=process.env.COMMHUB_TOKEN||L,F={};if(q)F.commhub={type:"http",url:`${q}/mcp`,headers:B?{Authorization:`Bearer ${B}`}:void 0};let K=(()=>{try{let{execSync:G}=b("child_process"),J=b("fs");try{let k=b.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(J.existsSync(k))return G(`${k} --version`,{stdio:"pipe"}),V(`[claude] using glibc binary: ${k}`),k}catch{}try{let k=G("which claude",{encoding:"utf-8"}).trim();if(k)return V(`[claude] using global binary: ${k}`),k}catch{}V("[claude] no binary resolved, falling back to SDK default");return}catch{return}})(),w={model:x||void 0,tools:T.length?T:void 0,maxTurns:Lz,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(F).length?F:void 0,pathToClaudeCodeExecutable:K,env:process.env,cwd:process.cwd(),stderr:(G)=>{if(G.trim())V(`[stderr] ${G.trim().slice(0,300)}`)},hooks:{PreToolUse:[{hooks:[async(G)=>{return V(`[tool] ${G.tool_name}(${JSON.stringify(G.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(Zz>0)w.maxBudgetUsd=Zz;if(O)w.systemPrompt=O;if(m)w.resume=m;let D="",I=Date.now();V(`[claude] claudePath=${K||"SDK default"}, mcpServers=${Object.keys(F).join(",")||"none"}`);for await(let G of Y({prompt:W,options:w})){let J=G;if(J.type==="system"&&J.subtype==="init")m=J.session_id,V(`[claude] session=${J.session_id?.slice(0,8)} model=${x||"default"}`),Kz(J.session_id);if(J.type==="result"){let k=Date.now()-I,y=J.usage||{};V(`[claude] ${J.subtype} | ${k}ms | $${J.total_cost_usd?.toFixed(4)||"?"} | in=${y.input_tokens||0} out=${y.output_tokens||0} | turns=${J.num_turns}`),D=J.subtype==="success"?J.result||"任务完成":`执行出错: ${J.error||J.result||"未知错误"}`}}return D}var P=null,cz=O||[`你是 ${H},一个 AI Agent 节点,工作目录:${process.cwd()}。`,"你通过通信网络(CommHub)接收任务并和其他 agent 协作。","","【可用通信工具】","- mcp_commhub__send_task(alias, task):派任务给指定 agent,等其 LLM 处理完返回 reply(同步语义)。","- mcp_commhub__send_message(alias, message):发聊天消息(不要求对方回复)。","- mcp_commhub__get_task(task_id):查询某任务的当前状态/reply。","- mcp_commhub__get_all_status():查看网络上所有在线 agent。","","【协作模式】","当你的任务需要其他 agent 的能力时:","1. 先 get_all_status 看哪些 agent 在线。","2. 用 send_task 派给合适的 agent。","3. **必须** 用 get_task 轮询那个 task_id 直到 status=replied,拿到对方的 reply 内容。","4. 把 reply 整合进你给原始任务发起者的最终汇报。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
|
|
38
|
+
`),Qz={model_auto_compact_token_limit:200000,developer_instructions:cz};async function mz(z,Z,$){try{let{execSync:B}=await import("child_process"),F=B("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(F){let K=F.replace(/\/codex$/,"");if(!process.env.PATH?.includes(K))process.env.PATH=`${K}:${process.env.PATH}`}}catch{}let Q;try{({Codex:Q}=await import("@openai/codex-sdk"))}catch{throw Error("@openai/codex-sdk not installed. Run: npm install -g @openai/codex-sdk @openai/codex")}if(!P){let B=new Q({config:Qz}),K={skipGitRepoCheck:!0,approvalPolicy:"never",model:x||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(A)P=B.resumeThread(A,K),V(`codex resumed thread: ${A}`);else P=B.startThread(K)}V(`[codex] model=${x||"gpt-5.4"} thread=${P?.id||"new"}`);let X=z,W=$?.length?[{type:"text",text:X},...$.map((B)=>({type:"local_image",path:B}))]:X,q=Date.now();try{let{events:B}=await P.runStreamed(W),F="",K=null,w=0;for await(let G of B)if(G.type==="item.started"){let J=G.item;R(`[codex] ${J.type}${J.command?`: ${J.command.slice(0,60)}`:J.tool?`: ${J.server}/${J.tool}`:""}`)}else if(G.type==="item.completed"){w++;let J=G.item;if(J.type==="agent_message")F=J.text||"";if(J.type==="command_execution")R(`[codex] cmd exit=${J.exit_code} | ${J.aggregated_output?.slice(0,80)}`);if(J.type==="reasoning")R(`[codex] thinking: ${J.text?.slice(0,80)}`);if(J.type==="mcp_tool_call")R(`[codex] mcp: ${J.server}/${J.tool} → ${J.status}`)}else if(G.type==="turn.completed")K=G.usage;let D=Date.now()-q,I=K?.input_tokens||0;if(V(`[codex] done | ${D}ms | in=${I} out=${K?.output_tokens||0} | items=${w}`),P?.id)Kz(P.id);return F||"(无回复)"}catch(B){V(`codex thread error: ${B.message}, 重建`),P=new Q({config:Qz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:x||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let K=await P.run(W),w=Date.now()-q;return V(`[codex] retry done | ${w}ms`),K.finalResponse||"(无回复)"}}async function nz(z,Z){let $=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.MINIMAX_CODING_API_KEY||j.apiKey||"",Q=process.env.ANTHROPIC_BASE_URL||j.anthropicBaseUrl||"",Y=process.env.OPENAI_BASE_URL||j.apiBaseUrl||"https://api.openai.com/v1",X=x||"gpt-4o-mini",W=!!Q,B=(Q||Y).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let F=O||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,K=Date.now();V(`[http-api] model=${X} format=${W?"anthropic":"openai"} base=${B.replace(/\/v1$/,"")}`);let w="",D=null;if(W){let G=await fetch(`${B}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:X,system:F,messages:[{role:"user",content:z}],max_tokens:2000})});if(!G.ok){let y=await G.text();return`Anthropic API 错误 ${G.status}: ${y.slice(0,200)}`}let J=await G.json();w=(Array.isArray(J.content)?J.content:[]).filter((y)=>y.type==="text").map((y)=>y.text).join(`
|
|
39
|
+
`)||"",D=J.usage}else{let G=await fetch(`${B}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:X,messages:[{role:"system",content:F},{role:"user",content:z}],max_tokens:2000})});if(!G.ok){let k=await G.text();return`OpenAI API 错误 ${G.status}: ${k.slice(0,200)}`}let J=await G.json();w=J.choices?.[0]?.message?.content||"",D=J.usage}let I=Date.now()-K;return V(`[http-api] done | ${I}ms | in=${D?.input_tokens||D?.prompt_tokens||0} out=${D?.output_tokens||D?.completion_tokens||0}`),w||"(无回复)"}var Xz=Promise.resolve();function Hz(z,Z,$){let Q=async()=>{if(C==="codex")return mz(z,Z,$);if(C==="http")return nz(z,Z);return dz(z,Z)},Y=Xz.then(Q,Q);return Xz=Y.then(()=>{},()=>{}),Y}async function rz(z,Z){V(`→ processing [${C}]: ${z.slice(0,80)}`),await l("working",z.slice(0,200)).catch(()=>{});let $,Q=!1;try{$=await Hz(z,Z)}catch(Y){$=`${C} 错误: ${Y.message}`,Q=!0,h(`✗ ${Y.message}`)}finally{await l("idle").catch(()=>{})}if(!Q&&/(API 错误|API error|需要设置.*KEY|missing.*key|issue with the selected model|may not have access|may not exist|model.+not.+(found|available))/i.test($))Q=!0;return{text:$,failed:Q}}var o={},lz=5000,gz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function vz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(gz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function iz(z,Z,$){if(z===H)return"self";if(Z.startsWith(`[${H}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(o[z]&&Q-o[z]<lz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&vz(Z))return"low-value-inbound";return null}async function oz(){let z=await hz();if(!z.length)return;for(let Z of z){let $=Z.from_session||"hub",Q=Z.content,Y=Z.type||"task";if(V(`← [${$}] (${Y}/${Z.priority||"normal"}) ${Q.slice(0,100)}`),await fz(Z.id),Y!=="task"&&Y!=="broadcast"){R(`skip non-task message: type=${Y}`);continue}let X=iz($,Q,Y);if(X){R(`skip message from ${$}: ${X}`);continue}let{text:W,failed:q}=await rz(Q,$);if(V(`processTask returned: "${W.slice(0,80)}" (${W.length} chars, failed=${q})`),!q&&vz(W,!0)){V(`skip reply: low-value (${W.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${q?"failed":"replied"})...`),await pz($,`[${H}] ${W.slice(0,2000)}`,Z.id,q),o[$]=Date.now(),V(`→ [${$}] ${W.slice(0,100)}`)}catch(B){_(`reply failed: ${B.message}`)}}}function Uz(z){return String(z.from?.id||z.chat?.id||"")}function Dz(z){return z.from?.username||z.from?.first_name||Uz(z)||"telegram"}function az(z,Z){if(z.allowFrom.length===0)return!0;let $=Uz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function g(z,Z,$){let Q=await fetch(`${z.apiBase}/${Z}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)}),Y=await Q.json();if(!Y.ok)throw Error(`telegram ${Z} failed: ${Y.description||Q.statusText}`);return Y.result}async function Yz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await g(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function Vz(z,Z,$){let Q=await g(z,"getFile",{file_id:Z}),Y=String(Q.file_path||""),X=await fetch(`${z.fileBase}/${Y}`);if(!X.ok)throw Error(`telegram file download failed: ${X.status} ${X.statusText}`);let W=Y.split(".").pop(),q=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),B=q.includes(".")||!W?q:`${q}.${W}`,F=U(z.channel.inboxDir,`${Date.now()}_${B}`);return t(F,Buffer.from(await X.arrayBuffer())),F}async function tz(z,Z){let $=Z.text||Z.caption||"",Q=[];if(Array.isArray(Z.photo)&&Z.photo.length>0){let X=Z.photo[Z.photo.length-1],W=await Vz(z,X.file_id,`photo_${Z.message_id}.jpg`);Q.push(W)}let Y=String(Z.document?.mime_type||"");if(Z.document&&Y.startsWith("image/")){let X=await Vz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
|
|
39
40
|
|
|
40
41
|
[Telegram 附件已下载]
|
|
41
42
|
${Q.map((X)=>`- 图片: ${X}`).join(`
|
|
42
|
-
`)}`;return{text:$.trim(),images:Q}}async function sz(z,Z){if(!az(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Dz(Z)}`,{text:X,images:
|
|
43
|
-
`)}catch{}},Y=!1,X=[];async function
|
|
44
|
-
`);
|
|
43
|
+
`)}`;return{text:$.trim(),images:Q}}async function sz(z,Z){if(!az(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${Dz(Z)}`,{text:X,images:W}=await tz(z,Z);if(!$||!Q||!X)return;R(`[TG] processing: ${X.slice(0,80)}`);try{let q=await Hz(X,Y,W);await Yz(z,$,q,Q),V(`→ [${Y}] ${q.slice(0,100)}`)}catch(q){h(`telegram task failed: ${q.message}`),await Yz(z,$,`处理出错: ${q.message}`,Q).catch(()=>{})}}async function ez(z){let Z={channel:z,apiBase:`https://api.telegram.org/bot${z.token}`,fileBase:`https://api.telegram.org/file/bot${z.token}`,offset:0};try{let q=await g(Z,"getMe",{});V(`Telegram bot: @${q.username} (${q.first_name})`)}catch(q){h(`Telegram token 无效: ${q.message}`),process.exit(1)}let $=U(z.dir,"state.json");try{let q=JSON.parse(f($,"utf-8"));if(q.offset)Z.offset=q.offset,R(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{t($,JSON.stringify({offset:Z.offset})+`
|
|
44
|
+
`)}catch{}},Y=!1,X=[];async function W(){if(Y)return;Y=!0;while(X.length){let{msg:q,updateId:B}=X.shift();try{await sz(Z,q),Z.offset=B+1,Q()}catch(F){h(`TG handle: ${F.message}`)}}Y=!1}V(`Telegram polling: ${z.dir}`);while(!0)try{let B=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!B.ok)throw Error(B.description||"getUpdates failed");for(let F of B.result||[])if(Z.offset=F.update_id+1,F.message){let K=F.message,w=Dz(K),D=K.text||K.caption||"";if(V(`← TG [${w}] ${D.slice(0,80)}${K.photo?" +img":""}${K.document?" +file":""}`),K.chat?.id&&K.message_id)g(Z,"setMessageReaction",{chat_id:K.chat.id,message_id:K.message_id,reaction:[{type:"emoji",emoji:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:K,updateId:F.update_id}),W()}}catch(q){_(`Telegram polling error: ${q.message}`),await new Promise((B)=>setTimeout(B,3000))}}async function zZ(){let z=`${d}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){R(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(L)$.Authorization=`Bearer ${L}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401)h("SSE 401: token 无效或未配置。检查 ~/.anet/config.json 的 token 字段");else _(`SSE failed: ${Q.status}`);await new Promise((q)=>setTimeout(q,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,W="";while(!0){let{done:q,value:B}=await Y.read();if(q)break;W+=X.decode(B,{stream:!0});let F=W.split(`
|
|
45
|
+
`);W=F.pop()||"";for(let K of F){if(!K.startsWith("data: "))continue;try{let w=JSON.parse(K.slice(6));if(w.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(w.type))V(`← SSE ${w.type}`),await oz();if(w.type==="new_reply")V(`← SSE reply from ${w.from||"?"}${w.in_reply_to?` (task ${w.in_reply_to.slice(0,8)})`:""}`)}catch{}}}}catch($){_(`SSE error: ${$.message}`)}R(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}V("启动");V(` runtime: ${yz}`);V(` model: ${x||(C==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${x?"":"(default)"}`);V(` hub: ${d}${L?" (auth)":" (no auth!)"}`);if(L)try{let z=await fetch(`${d}/api/auth/me`,{headers:{Authorization:`Bearer ${L}`}}).then((Z)=>Z.json()).catch(()=>null);if(z?.ok&&z.user)if(V(` user: ${z.user.username} (${z.user.role})`),z.current_network){let Z=z.networks?.find(($)=>$.network_id===z.current_network)?.network_name;V(` network: ${Z||z.current_network}`)}else V(` network: ${u||"(global)"}`);else if(z?.ok===!1)V(` network: ${u||"(global)"}`);else _(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{V(` network: ${u||"(global)"}`)}else _(" 未配置 token — agent 数据不隔离。运行: anet login");V(` tools: ${T.length?`[${T.join(",")}]`:"(none)"}`);V(` channels:${n.length?` telegram(${n.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${A||"(new)"}`);V(` log-dir: ${s}`);await Sz();V("已注册到 CommHub");setInterval(()=>l("idle").catch(()=>{}),180000);var kz=async()=>{V("shutting down..."),await l("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",kz);process.on("SIGTERM",kz);for(let z of n)ez(z);zZ();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-node",
|
|
3
|
-
"version": "2.1.1",
|
|
3
|
+
"version": "2.1.2-preview.1",
|
|
4
4
|
"description": "AI Agent runtime for CommHub networks. Supports Claude Agent SDK, Codex SDK, and OpenAI/Anthropic-compatible HTTP API.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"agent-node": "./dist/cli.js"
|