@sleep2agi/agent-node 2.3.0 → 2.3.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/LICENSE +202 -0
- package/README.md +10 -10
- package/dist/cli.js +13 -13
- package/package.json +11 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -2,20 +2,20 @@
|
|
|
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
|
+
The supported entry point is the `anet` CLI from `@sleep2agi/agent-network`, which writes the right `config.json`, network token, and environment variables for you.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
9
|
You usually don't install this package directly — `anet node create` and `anet node start` use it via `npx`. To pin it:
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
npm install -g @sleep2agi/agent-node
|
|
12
|
+
npm install -g @sleep2agi/agent-node
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
## Verified flow
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
|
-
npm install -g @sleep2agi/agent-network
|
|
18
|
+
npm install -g @sleep2agi/agent-network
|
|
19
19
|
anet hub start # local hub (terminal 1)
|
|
20
20
|
anet hub dashboard # web UI (terminal 2)
|
|
21
21
|
anet login --username admin --password anethub
|
|
@@ -51,7 +51,7 @@ CLI flags:
|
|
|
51
51
|
|---|---|---|---|
|
|
52
52
|
| `claude-agent-sdk` | [@anthropic-ai/claude-agent-sdk](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk) | verified | Anthropic-compatible API; works with MiniMax, DeepSeek, GLM, Kimi, Anthropic, OpenRouter, or custom endpoints |
|
|
53
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 |
|
|
54
|
+
| `claude-code-cli` | local `claude` CLI | unverified end-to-end | runs locally for Claude Pro subscribers (v0.8.2 fixed the session-resume default-loss bug; see [changelog](https://anet.sh/en/changelog)) |
|
|
55
55
|
| `http-api` | OpenAI/Anthropic-compatible HTTP | experimental | reads `ANTHROPIC_*`, `OPENAI_*`, or `MINIMAX_CODING_API_KEY` environment variables |
|
|
56
56
|
|
|
57
57
|
Runtimes are loaded lazily — picking one doesn't pull the others' dependencies. `claude-code-cli` adds zero extra SDK weight.
|
|
@@ -82,7 +82,7 @@ npx @sleep2agi/agent-node --alias deep --hub http://127.0.0.1:9200 --tools all
|
|
|
82
82
|
# MiniMax
|
|
83
83
|
ANTHROPIC_BASE_URL=https://api.minimax.io/anthropic \
|
|
84
84
|
ANTHROPIC_AUTH_TOKEN=your-key \
|
|
85
|
-
npx @sleep2agi/agent-node --alias mini --model
|
|
85
|
+
npx @sleep2agi/agent-node --alias mini --model <minimax-model-id> --hub http://127.0.0.1:9200 --tools all
|
|
86
86
|
```
|
|
87
87
|
|
|
88
88
|
## Configuration file
|
|
@@ -96,7 +96,7 @@ Typical output of `anet node create` at `.anet/nodes/<name>/config.json`:
|
|
|
96
96
|
"hub": "http://127.0.0.1:9200",
|
|
97
97
|
"token": "ntok_...",
|
|
98
98
|
"runtime": "claude-agent-sdk",
|
|
99
|
-
"model": "
|
|
99
|
+
"model": "<minimax-model-id>",
|
|
100
100
|
"channels": ["server:commhub"],
|
|
101
101
|
"tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
|
|
102
102
|
"env": {
|
|
@@ -148,10 +148,10 @@ When the runtime is `claude-code-cli`, the spawned subprocess gets `settingSourc
|
|
|
148
148
|
|
|
149
149
|
| Package | Version |
|
|
150
150
|
|---|---|
|
|
151
|
-
| [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.
|
|
152
|
-
| [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) | 0.
|
|
153
|
-
| [@sleep2agi/agent-network-dashboard](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.2
|
|
151
|
+
| [@sleep2agi/agent-network](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.1.7 |
|
|
152
|
+
| [@sleep2agi/commhub-server](https://www.npmjs.com/package/@sleep2agi/commhub-server) | 0.8.0 |
|
|
153
|
+
| [@sleep2agi/agent-network-dashboard](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.4.2 |
|
|
154
154
|
|
|
155
155
|
## License
|
|
156
156
|
|
|
157
|
-
|
|
157
|
+
Apache-2.0
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
2
|
+
import{createRequire as yz}from"node:module";var x=yz(import.meta.url);import{readFileSync as c,existsSync as e,writeFileSync as zz,chmodSync as Pz}from"fs";import{join as R}from"path";import{hostname as Qz,homedir as Nz}from"os";import{mkdirSync as Dz,appendFileSync as dz}from"fs";var __dirname="/home/vansin/agent-orchestra/agent-node/src";var jz=Nz(),M=process.argv.slice(2),v={},Bz=[],Kz="2.1.0";try{let z=new URL(".",import.meta.url).pathname;for(let Z of["../package.json","../../package.json"])try{let $=JSON.parse(c(R(z,Z),"utf-8"));if($.version){Kz=$.version;break}}catch{}}catch{}for(let z=0;z<M.length;z++){if(M[z]==="--version"||M[z]==="-v")console.log(`agent-node v${Kz}`),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,23 +24,23 @@ import{createRequire as Rz}from"node:module";var k=Rz(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
|
|
31
|
-
`)}catch{}}var V=(z)=>
|
|
27
|
+
`),process.exit(0);if(M[z]==="--new-session"){v["new-session"]="true";continue}if(M[z]==="--channel"&&z+1<M.length){Bz.push(M[++z]);continue}if(M[z].startsWith("--")&&z+1<M.length)v[M[z].slice(2)]=M[++z]}function Fz(z){return z.replace(/^~(?=\/|$)/,jz)}function Lz(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:Fz(z.slice(Z+1)),raw:z}}function h(z){if(!e(z))return null;try{return JSON.parse(c(z,"utf-8"))}catch{return null}}var q={},y="";if(v.config){let z=v.config.startsWith("/")?v.config:R(process.cwd(),v.config),Z=h(z);if(Z)q=Z,y=z,console.log(`[agent-node] Config: ${z}`)}var H=v.alias||process.env.COMMHUB_ALIAS||process.env.ALIAS||q.alias;if(!v.config&&H){let z=R(process.cwd(),".anet","nodes",H,"config.json"),Z=R(process.cwd(),".anet","profiles",`${H}.json`),$=e(z)?z:Z,Q=h($);if(Q)q={...Q,...q},y=$,console.log(`[agent-node] Config: ${$}`)}var u=h(R(jz,".anet","config.json"))||{};if(u.hub&&!q.hub)q.hub=u.hub;if(u.token&&!q.token)q.token=u.token;if(!v.config&&!Object.keys(q).length){let z=h(R(process.cwd(),".agent-node.json"));if(z)q=z,console.log("[agent-node] 配置: .agent-node.json")}if(q.env&&typeof q.env==="object"){for(let[z,Z]of Object.entries(q.env))if(!process.env[z]&&typeof Z==="string")process.env[z]=Fz(Z)}if(!H)console.error(`错误: 必须指定 --alias
|
|
28
|
+
用法: npx @sleep2agi/agent-node --alias "我的Agent"`),process.exit(1);var wz=v.runtime||process.env.RUNTIME||q.runtime||"claude-agent-sdk",Az={"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"},_=Az[wz]||"claude",Oz=wz,m=v.url||v.hub||process.env.COMMHUB_URL||q.hub||"http://127.0.0.1:9200",A=v.model||process.env.MODEL||q.model,Cz=["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch"],Xz=v.tools||(Array.isArray(q.tools)?q.tools.join(","):q.tools)||"",S=Xz==="all"?Cz:Xz.split(",").filter(Boolean),_z=parseInt(v["max-turns"]||q.flags?.maxTurns||q.maxTurns||"50"),Yz=parseFloat(v["max-budget"]||q.flags?.maxBudgetUsd||q.maxBudgetUsd||"0"),l=parseInt(v["claude-timeout-ms"]||process.env.CLAUDE_TIMEOUT_MS||q.flags?.claudeTimeoutMs||q.claudeTimeoutMs||"120000"),Ez=v["new-session"]==="true",C=Ez?"":v.session||q.session||q.resume||q.sessionId||"",T=v.prompt||q.systemPrompt||"",N=q.token||u.token||process.env.COMMHUB_TOKEN||"";if(process.env.COMMHUB_TOKEN&&q.token&&process.env.COMMHUB_TOKEN!==q.token)console.warn(`[${H}] ⚠ COMMHUB_TOKEN env override ignored (using node config token). Unset COMMHUB_TOKEN to silence this warning.`);function Iz(){if(!y)return!1;let z=h(y),Z=typeof z?.token==="string"?z.token:"";if(!Z||Z===N)return!1;return N=Z,q.token=Z,O(`reloaded node token from ${y}`),!0}var Zz=v["log-dir"]||R(process.cwd(),".anet","nodes",H,"logs"),Tz={debug:0,info:1,warn:2,error:3},uz=Tz[v["log-level"]||process.env.LOG_LEVEL||q.logLevel||"info"]??1,d=[...(Array.isArray(q.channels)?q.channels:[]).filter((z)=>!z.startsWith("server:")&&!z.startsWith("plugin:")),...Bz],Hz=d.map((z)=>{try{return Lz(z)}catch(Z){console.error(`[agent-node] ${Z.message}`),process.exit(1)}});function vz(z){if(!y||!z)return;try{let Z=JSON.parse(c(y,"utf-8"));if(Z.session===z)return;Z.session=z,zz(y,JSON.stringify(Z,null,2)+`
|
|
29
|
+
`),k(`session 写回: ${y} → ${z.slice(0,8)}...`)}catch(Z){O(`writebackSession failed: ${Z.message}`)}}function Sz(z){if(!e(z))return;for(let Z of c(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 hz(z){return R(process.cwd(),".anet","nodes",H,"channels",z)}function pz(z){let Z=z.path||hz("telegram");Sz(R(Z,".env"));let $=process.env.TELEGRAM_BOT_TOKEN||"";if(!$)console.error(`[agent-node] telegram channel needs TELEGRAM_BOT_TOKEN in ${R(Z,".env")}`),process.exit(1);try{Pz(R(Z,".env"),384)}catch{}let Q=h(R(Z,"access.json"))||{},Y=R(Z,"inbox");try{Dz(Y,{recursive:!0})}catch{}return{type:"telegram",dir:Z,inboxDir:Y,token:$,allowFrom:Array.isArray(Q.allowFrom)?Q.allowFrom.map(String):[]}}var r=Hz.filter((z)=>z.type==="telegram").map(pz),Vz=Hz.find((z)=>z.type!=="telegram");if(Vz)console.error(`[agent-node] unsupported channel: ${Vz.raw}`),process.exit(1);if(r.length>0&&_!=="codex"&&!S.includes("Read"))S.push("Read");try{Dz(Zz,{recursive:!0})}catch{}function t(z,Z,$){if(Z<uz)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);dz(R(Zz,`${W}.log`),X+`
|
|
31
|
+
`)}catch{}}var V=(z)=>t("info",1,z),k=(z)=>t("debug",0,z),O=(z)=>t("warn",2,z),f=(z)=>t("error",3,z);async function n(z,Z,$=3){let Q={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(N)Q.Authorization=`Bearer ${N}`;let Y;for(let X=0;X<=$;X++)try{let W=await fetch(`${m}/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 J=await W.text(),j=J.match(/data: (.+)/),K=j?JSON.parse(j[1]):JSON.parse(J),G=K?.result?.content?.[0]?.text;return G?JSON.parse(G):K}catch(W){if(Y=W,X<$)k(`callCommHub(${z}) attempt ${X+1} failed: ${W.message}, retrying...`),await new Promise((J)=>setTimeout(J,1000*Math.pow(2,X)))}throw Y||Error(`callCommHub(${z}) failed after ${$} retries`)}var i=q.node_id||"",fz=q.node_name||"",p=q.network_id||process.env.ANET_NETWORK_ID||u.network_id||"",bz=i?`sdk-${i}`:`sdk-${H}-${Date.now().toString(36)}`,cz=()=>n("report_status",{resume_id:bz,alias:H,status:"idle",server:Qz(),hostname:Qz(),agent:`agent-node:${_}`,project_dir:process.cwd(),node_id:i||void 0,node_name:fz||void 0,session_id:C||void 0,config_path:y||void 0,channels:d.length?JSON.stringify(d):void 0,model:A||void 0,network_id:p||void 0}),o=(z,Z)=>n("report_status",{resume_id:bz,alias:H,status:z,task:Z,node_id:i||void 0,session_id:g||C||void 0,config_path:y||void 0,channels:d.length?JSON.stringify(d):void 0,network_id:p||void 0}),mz=async()=>(await n("get_inbox",{alias:H,limit:20}))?.messages||[],nz=(z)=>n("ack_inbox",{alias:H,message_id:z}),lz=(z,Z,$,Q=!1)=>n("send_reply",{alias:z,text:Z,from_session:H,in_reply_to:$||void 0,status:Q?"failed":"replied"}),g=C||void 0;async function gz(z,Z){let{existsSync:$}=await import("fs"),Q=!1;try{let B=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(B))Q=!0}catch{}if(!Q)try{let{execSync:B}=await import("child_process");B("which claude",{stdio:"pipe"}),Q=!0}catch{}if(!Q&&process.platform==="linux")try{let{execSync:B}=await import("child_process");V("[claude] no Claude binary found — installing @anthropic-ai/claude-agent-sdk-linux-x64 (glibc) ..."),B("npm install --no-save --prefix "+JSON.stringify(__dirname+"/../")+" @anthropic-ai/claude-agent-sdk-linux-x64",{stdio:"pipe",timeout:60000});try{let D=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if($(D))Q=!0,V(`[claude] glibc binary installed: ${D}`)}catch{}}catch(B){V(`[claude] auto-install of glibc binary failed: ${B?.message||B}`)}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
32
|
`);if(typeof process.getuid==="function"&&process.getuid()===0)return["claude 错误: 当前以 root 用户运行,Claude Code 拒绝 --dangerously-skip-permissions。","解决方案 (推荐 1):"," 1. 建非 root 用户后再启动:"," useradd -m anet-agent"," su - anet-agent"," anet login --hub <URL> --username <user> --password <pass>"," anet node start <name>"," 2. 或切换 runtime 为 codex-sdk (root 下可运行,需 codex auth login):"," anet node delete <name> && anet node create <name> --runtime codex-sdk"].join(`
|
|
33
33
|
`);let{query:Y}=await import("@anthropic-ai/claude-agent-sdk"),X=process.env.CURRENT_TASK_ID||"",W=[`你是 ${H},一个 AI Agent 节点。收到来自 ${Z} 的任务 (task_id=${X}):`,"",z,"","【若任务需要其他 agent 协助】","1. 先用 mcp_commhub__get_all_status 看哪些 agent 在线。",`2. 用 mcp_commhub__send_task(alias, task, parent_task_id="${X}") 派给合适的 agent。`,` ⚠ 必须把 parent_task_id 设成你当前任务的 ID,这样系统会自动把子任务的最终结果串回给 ${Z}。`,`3. 用 mcp_commhub__get_task(task_id) 轮询子任务状态。允许中途给 ${Z} 发"还在等待"的进度汇报,但你必须继续轮询直到子任务 replied/failed。`,`4. 拿到子任务 reply 后把内容整合到你给 ${Z} 的最终汇报里。`,` 即便你的 session 中途断开,只要 parent_task_id 设了,系统也会自动把子任务结果交付给 ${Z},所以不必焦虑。`,"","【禁止】",`- 不要给自己(${H})发任务(死循环)。`,'- 不要回复"收到""ok""明白了"等无内容确认。',"- 不要在无新任务时主动调用通信工具。",`- send_task 时不要忘记 parent_task_id;忘了就要不回来 ${Z} 的链路。`,"","执行完后简要汇报结果。"].join(`
|
|
34
|
-
`),
|
|
34
|
+
`),J=T?`${T}
|
|
35
35
|
|
|
36
36
|
收到来自 ${Z} 的任务:
|
|
37
37
|
|
|
38
|
-
${z}`:W,
|
|
39
|
-
`),
|
|
40
|
-
`)||"",
|
|
38
|
+
${z}`:W,j=process.env.COMMHUB_URL||m,K=process.env.COMMHUB_TOKEN||N,G={};if(j)G.commhub={type:"http",url:`${j}/mcp`,headers:K?{Authorization:`Bearer ${K}`}:void 0};let w=(()=>{try{let{execSync:B}=x("child_process"),D=x("fs");try{let P=x.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude");if(D.existsSync(P))return B(`${P} --version`,{stdio:"pipe"}),V(`[claude] using glibc binary: ${P}`),P}catch{}try{let P=B("which claude",{encoding:"utf-8"}).trim();if(P)return V(`[claude] using global binary: ${P}`),P}catch{}V("[claude] no binary resolved, falling back to SDK default");return}catch{return}})(),U={model:A||void 0,tools:S.length?S:void 0,maxTurns:_z,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,settingSources:[],mcpServers:Object.keys(G).length?G:void 0,pathToClaudeCodeExecutable:w,env:process.env,cwd:process.cwd(),stderr:(B)=>{if(B.trim())V(`[stderr] ${B.trim().slice(0,300)}`)},hooks:{PreToolUse:[{hooks:[async(B)=>{return V(`[tool] ${B.tool_name}(${JSON.stringify(B.tool_input).slice(0,80)})`),{continue:!0}}]}]}};if(Yz>0)U.maxBudgetUsd=Yz;if(T)U.systemPrompt=T;if(g)U.resume=g;let E="",b=Date.now();V(`[claude] claudePath=${w||"SDK default"}, mcpServers=${Object.keys(G).join(",")||"none"}`);let F=!1,I;if(l>0){let B=new AbortController;U.abortController=B,I=setTimeout(()=>{F=!0,B.abort()},l)}try{for await(let B of Y({prompt:J,options:U})){let D=B;if(D.type==="system"&&D.subtype==="init")g=D.session_id,V(`[claude] session=${D.session_id?.slice(0,8)} model=${A||"default"}`),vz(D.session_id);if(D.type==="result"){let P=Date.now()-b,$z=D.usage||{};V(`[claude] ${D.subtype} | ${P}ms | $${D.total_cost_usd?.toFixed(4)||"?"} | in=${$z.input_tokens||0} out=${$z.output_tokens||0} | turns=${D.num_turns}`),E=D.subtype==="success"?D.result||"任务完成":`执行出错: ${D.error||D.result||"未知错误"}`}}}catch(B){if(F){let D=Date.now()-b;return V(`[claude] ✗ timed out after ${D}ms (CLAUDE_TIMEOUT_MS=${l}) — aborting query`),`执行出错: claude-agent-sdk 调用超时 (${Math.round(l/1000)}s 无响应) — 检查 ANTHROPIC_BASE_URL endpoint 是否可达且 Anthropic-compatible`}return V(`[claude] ✗ query error: ${String(B?.message||B).slice(0,200)}`),`执行出错: ${String(B?.message||B).slice(0,200)}`}finally{if(I)clearTimeout(I)}return E}var L=null,rz=T||[`你是 ${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(alias, task, parent_task_id=<env CURRENT_TASK_ID>) 派给合适的 agent。"," ⚠ 必须把 parent_task_id 设成你当前任务的 ID(环境变量 CURRENT_TASK_ID 里),系统会自动把子任务最终结果串回给你的上游。",'3. 用 get_task 轮询子任务直到 status=replied/failed。允许中途汇报"还在等",但要继续轮询。',"4. 拿到 reply 后整合进你给上游的最终汇报。"," 即使你的 session 中途断开,只要 parent_task_id 设了,结果也会被系统自动 chain 回上游,不必焦虑。","","【禁止】",'- 不要回复"收到""好的""ok""在线""待命"等无内容确认。',"- 不要给自己发任务(会死循环)。","- 收到的若是 reply 类型,不要再 send_task 给原方(会乒乓回复)。","- 没有新任务时保持沉默,不主动发消息。","","你的最终回复会被系统自动 send_reply 给任务发起者。"].join(`
|
|
39
|
+
`),Jz={model_auto_compact_token_limit:200000,developer_instructions:rz};async function iz(z,Z,$){try{let{execSync:j}=await import("child_process"),K=j("which codex 2>/dev/null",{encoding:"utf-8"}).trim();if(K){let G=K.replace(/\/codex$/,"");if(!process.env.PATH?.includes(G))process.env.PATH=`${G}:${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(!L){let j=new Q({config:Jz}),G={skipGitRepoCheck:!0,approvalPolicy:"never",model:A||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"};if(C)L=j.resumeThread(C,G),V(`codex resumed thread: ${C}`);else L=j.startThread(G)}V(`[codex] model=${A||"gpt-5.4"} thread=${L?.id||"new"}`);let X=z,W=$?.length?[{type:"text",text:X},...$.map((j)=>({type:"local_image",path:j}))]:X,J=Date.now();try{let{events:j}=await L.runStreamed(W),K="",G=null,w=0;for await(let b of j)if(b.type==="item.started"){let F=b.item;k(`[codex] ${F.type}${F.command?`: ${F.command.slice(0,60)}`:F.tool?`: ${F.server}/${F.tool}`:""}`)}else if(b.type==="item.completed"){w++;let F=b.item;if(F.type==="agent_message")K=F.text||"";if(F.type==="command_execution")k(`[codex] cmd exit=${F.exit_code} | ${F.aggregated_output?.slice(0,80)}`);if(F.type==="reasoning")k(`[codex] thinking: ${F.text?.slice(0,80)}`);if(F.type==="mcp_tool_call")k(`[codex] mcp: ${F.server}/${F.tool} → ${F.status}`)}else if(b.type==="turn.completed")G=b.usage;let U=Date.now()-J,E=G?.input_tokens||0;if(V(`[codex] done | ${U}ms | in=${E} out=${G?.output_tokens||0} | items=${w}`),L?.id)vz(L.id);return K||"(无回复)"}catch(j){V(`codex thread error: ${j.message}, 重建`),L=new Q({config:Jz}).startThread({skipGitRepoCheck:!0,approvalPolicy:"never",model:A||"gpt-5.4",sandboxMode:"danger-full-access",modelReasoningEffort:"low"});let G=await L.run(W),w=Date.now()-J;return V(`[codex] retry done | ${w}ms`),G.finalResponse||"(无回复)"}}async function oz(z,Z){let $=process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.OPENAI_API_KEY||process.env.MINIMAX_CODING_API_KEY||q.apiKey||"",Q=process.env.ANTHROPIC_BASE_URL||q.anthropicBaseUrl||"",Y=process.env.OPENAI_BASE_URL||q.apiBaseUrl||"https://api.openai.com/v1",X=A||"gpt-4o-mini",W=!!Q,j=(Q||Y).replace(/\/v1\/?$/,"");if(!$)return"错误: 需要设置 ANTHROPIC_API_KEY, OPENAI_API_KEY, 或 MINIMAX_CODING_API_KEY";let K=T||`你是 ${H},一个 AI 助手。收到来自 ${Z} 的任务后简要执行并汇报。`,G=Date.now();V(`[http-api] model=${X} format=${W?"anthropic":"openai"} base=${j.replace(/\/v1$/,"")}`);let w="",U=null;if(W){let b=await fetch(`${j}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":$,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:X,system:K,messages:[{role:"user",content:z}],max_tokens:2000})});if(!b.ok){let B=await b.text();return`Anthropic API 错误 ${b.status}: ${B.slice(0,200)}`}let F=await b.json();w=(Array.isArray(F.content)?F.content:[]).filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
40
|
+
`)||"",U=F.usage}else{let b=await fetch(`${j}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify({model:X,messages:[{role:"system",content:K},{role:"user",content:z}],max_tokens:2000})});if(!b.ok){let I=await b.text();return`OpenAI API 错误 ${b.status}: ${I.slice(0,200)}`}let F=await b.json();w=F.choices?.[0]?.message?.content||"",U=F.usage}let E=Date.now()-G;return V(`[http-api] done | ${E}ms | in=${U?.input_tokens||U?.prompt_tokens||0} out=${U?.output_tokens||U?.completion_tokens||0}`),w||"(无回复)"}var qz=Promise.resolve();function Uz(z,Z,$,Q){let Y=async()=>{let W=process.env.CURRENT_TASK_ID;if($)process.env.CURRENT_TASK_ID=$;else delete process.env.CURRENT_TASK_ID;try{if(_==="codex")return await iz(z,Z,Q);if(_==="http")return await oz(z,Z);return await gz(z,Z)}finally{if(W!==void 0)process.env.CURRENT_TASK_ID=W;else delete process.env.CURRENT_TASK_ID}},X=qz.then(Y,Y);return qz=X.then(()=>{},()=>{}),X}async function az(z,Z,$=null){V(`→ processing [${_}]: ${z.slice(0,80)}`),await o("working",z.slice(0,200)).catch(()=>{});let Q,Y=!1;try{Q=await Uz(z,Z,$)}catch(X){Q=`${_} 错误: ${X.message}`,Y=!0,f(`✗ ${X.message}`)}finally{await o("idle").catch(()=>{})}if(!Y&&/(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))Y=!0;return{text:Q,failed:Y}}var s={},tz=5000,sz=new Set(["收到","好的","ok","嗯","是的","了解","明白","确认","done","ack","roger","yes","no","在线","待命","正常","保持在线","通信正常","已收到","收到了","好","行","noted","copy","received","understood","等待任务","等待中","等待指令","无新任务","idle","waiting"]);function Rz(z,Z=!1){if(!z)return!0;let Q=z.trim().replace(/^[\[【].+?[\]】]\s*/,"").trim().toLowerCase().replace(/[\s。!?.!?✅❌👀⏳,,]+$/g,"").trim();if(sz.has(Q))return!0;if(/^[\p{Emoji}\s]+$/u.test(z.trim())&&!/[0-9a-zA-Z#*]/.test(z))return!0;return!1}function ez(z,Z,$){if(z===H)return"self";if(Z.startsWith(`[${H}]`))return"own-prefix";if(z!=="hub"&&z!=="api"){let Q=Date.now();if(s[z]&&Q-s[z]<tz)return"cooldown"}if($!=="task"&&$!=="broadcast"&&Rz(Z))return"low-value-inbound";return null}async function zZ(){let z=await mz();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 nz(Z.id),Y!=="task"&&Y!=="broadcast"){k(`skip non-task message: type=${Y}`);continue}let X=ez($,Q,Y);if(X){k(`skip message from ${$}: ${X}`);continue}let{text:W,failed:J}=await az(Q,$,Z.id);if(V(`processTask returned: "${W.slice(0,80)}" (${W.length} chars, failed=${J})`),!J&&Rz(W,!0)){V(`skip reply: low-value (${W.slice(0,30)})`);continue}try{V(`sending reply to ${$} (task ${Z.id.slice(0,8)}, status=${J?"failed":"replied"})...`),await lz($,`[${H}] ${W.slice(0,2000)}`,Z.id,J),s[$]=Date.now(),V(`→ [${$}] ${W.slice(0,100)}`)}catch(j){O(`reply failed: ${j.message}`)}}}function Mz(z){return String(z.from?.id||z.chat?.id||"")}function xz(z){return z.from?.username||z.from?.first_name||Mz(z)||"telegram"}function ZZ(z,Z){if(z.allowFrom.length===0)return!0;let $=Mz(Z),Q=Z.from?.username?String(Z.from.username):"";return z.allowFrom.includes($)||!!Q&&z.allowFrom.includes(Q)}async function a(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 Wz(z,Z,$,Q){let Y=$.match(/[\s\S]{1,4096}/g)||["(无回复)"];for(let X=0;X<Y.length;X++)await a(z,"sendMessage",{chat_id:Z,text:Y[X],...Q&&X===0?{reply_to_message_id:Q}:{}})}async function Gz(z,Z,$){let Q=await a(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(),J=($||Y.split("/").pop()||Z).replace(/[^a-zA-Z0-9._-]/g,"_"),j=J.includes(".")||!W?J:`${J}.${W}`,K=R(z.channel.inboxDir,`${Date.now()}_${j}`);return zz(K,Buffer.from(await X.arrayBuffer())),K}async function $Z(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 Gz(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 Gz(z,Z.document.file_id,Z.document.file_name||`image_${Z.message_id}`);Q.push(X)}if(Q.length)$+=`
|
|
41
41
|
|
|
42
42
|
[Telegram 附件已下载]
|
|
43
43
|
${Q.map((X)=>`- 图片: ${X}`).join(`
|
|
44
|
-
`)}`;return{text:$.trim(),images:Q}}async function
|
|
45
|
-
`)}catch{}},Y=!1,X=[];async function W(){if(Y)return;Y=!0;while(X.length){let{msg:
|
|
46
|
-
`);W=K.pop()||"";for(let
|
|
44
|
+
`)}`;return{text:$.trim(),images:Q}}async function QZ(z,Z){if(!ZZ(z.channel,Z))return;let $=Z.chat?.id,Q=Z.message_id,Y=`telegram:${xz(Z)}`,{text:X,images:W}=await $Z(z,Z);if(!$||!Q||!X)return;k(`[TG] processing: ${X.slice(0,80)}`);try{let J=await Uz(X,Y,W);await Wz(z,$,J,Q),V(`→ [${Y}] ${J.slice(0,100)}`)}catch(J){f(`telegram task failed: ${J.message}`),await Wz(z,$,`处理出错: ${J.message}`,Q).catch(()=>{})}}async function XZ(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 J=await a(Z,"getMe",{});V(`Telegram bot: @${J.username} (${J.first_name})`)}catch(J){f(`Telegram token 无效: ${J.message}`),process.exit(1)}let $=R(z.dir,"state.json");try{let J=JSON.parse(c($,"utf-8"));if(J.offset)Z.offset=J.offset,k(`Telegram offset restored: ${Z.offset}`)}catch{}let Q=()=>{try{zz($,JSON.stringify({offset:Z.offset})+`
|
|
45
|
+
`)}catch{}},Y=!1,X=[];async function W(){if(Y)return;Y=!0;while(X.length){let{msg:J,updateId:j}=X.shift();try{await QZ(Z,J),Z.offset=j+1,Q()}catch(K){f(`TG handle: ${K.message}`)}}Y=!1}V(`Telegram polling: ${z.dir}`);while(!0)try{let j=await(await fetch(`${Z.apiBase}/getUpdates?offset=${Z.offset}&timeout=30`)).json();if(!j.ok)throw Error(j.description||"getUpdates failed");for(let K of j.result||[])if(Z.offset=K.update_id+1,K.message){let G=K.message,w=xz(G),U=G.text||G.caption||"";if(V(`← TG [${w}] ${U.slice(0,80)}${G.photo?" +img":""}${G.document?" +file":""}`),G.chat?.id&&G.message_id)a(Z,"setMessageReaction",{chat_id:G.chat.id,message_id:G.message_id,reaction:[{type:"emoji",emoji:X.length>0?"⏳":"\uD83D\uDC40"}]}).catch(()=>{});X.push({msg:G,updateId:K.update_id}),W()}}catch(J){O(`Telegram polling error: ${J.message}`),await new Promise((j)=>setTimeout(j,3000))}}async function YZ(){let z=`${m}/events/${encodeURIComponent(H)}`,Z=3000;while(!0){k(`SSE connecting: ${z}`);try{let $={Accept:"text/event-stream","Cache-Control":"no-cache"};if(N)$.Authorization=`Bearer ${N}`;let Q=await fetch(z,{headers:$});if(!Q.ok||!Q.body){if(Q.status===401){if(Iz()){O(`SSE 401: ntok_ 已刷新,正在用 .anet/nodes/${H}/config.json 里的新 token 重试`),await new Promise((J)=>setTimeout(J,500));continue}f("SSE 401: ntok_ 已失效(hub DB 可能被重置或 token 被撤销)。试 `anet doctor --fix`")}else O(`SSE failed: ${Q.status}`);await new Promise((J)=>setTimeout(J,Z)),Z=Math.min(Z*1.5,60000);continue}Z=3000;let Y=Q.body.getReader(),X=new TextDecoder,W="";while(!0){let{done:J,value:j}=await Y.read();if(J)break;W+=X.decode(j,{stream:!0});let K=W.split(`
|
|
46
|
+
`);W=K.pop()||"";for(let G of K){if(!G.startsWith("data: "))continue;try{let w=JSON.parse(G.slice(6));if(w.type==="connected"){V("SSE connected");continue}if(["new_task","broadcast"].includes(w.type))V(`← SSE ${w.type}`),await zZ();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($){O(`SSE error: ${$.message}`)}k(`SSE reconnecting (${Z/1000}s)...`),await new Promise(($)=>setTimeout($,Z)),Z=Math.min(Z*1.5,60000)}}V("启动");V(` runtime: ${Oz}`);V(` model: ${A||(_==="codex"?"gpt-5.4":"claude-sonnet-4-6")} ${A?"":"(default)"}`);V(` hub: ${m}${N?" (auth)":" (no auth!)"}`);if(N)try{let z=await fetch(`${m}/api/auth/me`,{headers:{Authorization:`Bearer ${N}`}}).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: ${p||"(global)"}`);else if(z?.ok===!1)V(` network: ${p||"(global)"}`);else O(" token 验证失败 — 检查 token 是否有效。运行: anet login")}catch{V(` network: ${p||"(global)"}`)}else O(" 未配置 token — agent 数据不隔离。运行: anet login");V(` tools: ${S.length?`[${S.join(",")}]`:"(none)"}`);V(` channels:${r.length?` telegram(${r.map((z)=>z.dir).join(",")})`:" (none)"}`);V(` session: ${C||"(new)"}`);V(` log-dir: ${Zz}`);await cz();V("已注册到 CommHub");setInterval(()=>o("idle").catch(()=>{}),180000);var kz=async()=>{V("shutting down..."),await o("offline").catch(()=>{}),process.exit(0)};process.on("SIGINT",kz);process.on("SIGTERM",kz);for(let z of r)XZ(z);YZ();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/agent-node",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.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"
|
|
@@ -28,21 +28,27 @@
|
|
|
28
28
|
"anthropic"
|
|
29
29
|
],
|
|
30
30
|
"author": "sleep2agi",
|
|
31
|
-
"license": "
|
|
32
|
-
"homepage": "https://anet.
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"homepage": "https://anet.sh",
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|
|
35
35
|
"url": "https://github.com/sleep2agi/agent-network",
|
|
36
36
|
"directory": "agent-node"
|
|
37
37
|
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/sleep2agi/agent-network/issues"
|
|
43
|
+
},
|
|
38
44
|
"engines": {
|
|
39
45
|
"node": ">=18.0.0"
|
|
40
46
|
},
|
|
41
47
|
"dependencies": {
|
|
42
|
-
"@anthropic-ai/claude-agent-sdk": "^0.2.
|
|
48
|
+
"@anthropic-ai/claude-agent-sdk": "^0.2.140"
|
|
43
49
|
},
|
|
44
50
|
"peerDependencies": {
|
|
45
|
-
"@openai/codex-sdk": ">=0.
|
|
51
|
+
"@openai/codex-sdk": ">=0.130.0"
|
|
46
52
|
},
|
|
47
53
|
"peerDependenciesMeta": {
|
|
48
54
|
"@openai/codex-sdk": {
|