mirror of
https://gitcode.com/JianFeeeee/homeagent-sdk.git
synced 2026-09-21 17:38:03 +00:00
Compare commits
85 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 140cd34b56 | |||
| b237787c90 | |||
| 69ff3089a4 | |||
| e839eb8220 | |||
| d893bfa76f | |||
| 93ab794a82 | |||
| 12cabcb290 | |||
| 44bd915fbf | |||
| ba49dfda44 | |||
| b2eafdf885 | |||
| 8c397ecf65 | |||
| 632f6743d3 | |||
| 9d930db4ea | |||
| 0a164fe4b9 | |||
| fd5a291df1 | |||
| 5175e7d6e0 | |||
| 71e3325439 | |||
| 18fec9b003 | |||
| fc236120e3 | |||
| a66739e59b | |||
| da01af1ad7 | |||
| 741e284cd4 | |||
| ce5bff9275 | |||
| e256023399 | |||
| 092d8f4ab0 | |||
| 5ed8d65479 | |||
| 9f844123fe | |||
| ef0e58ee23 | |||
| 09b64dcb53 | |||
| 56485194df | |||
| 61f307be1a | |||
| 59c6e1844c | |||
| 5c1574be25 | |||
| 68497b4092 | |||
| 130f805b6e | |||
| cd1984e26e | |||
| 6184736fd4 | |||
| 81bfdfce1d | |||
| e3f93e254b | |||
| d57c5eaf3e | |||
| 16b4a56ee8 | |||
| 2e6d037bb9 | |||
| cf77bf389e | |||
| fc876c5554 | |||
| 5c5df9cfb9 | |||
| c91739d670 | |||
| 6527a40539 | |||
| 392f391f68 | |||
| cca9fdce9c | |||
| b6e30f9279 | |||
| 8e5610c494 | |||
| 1796395668 | |||
| f3d87ec35f | |||
| aee63a4f98 | |||
| fb07081929 | |||
| db5d3133ea | |||
| 12a8e99892 | |||
| 62447e3952 | |||
| bc1a005885 | |||
| 2b54814037 | |||
| 429fe9e1b9 | |||
| 87136057b1 | |||
| 84bf100a12 | |||
| 78ef7998c2 | |||
| b166697dd7 | |||
| 4d01e75282 | |||
| c5bcae9404 | |||
| c7c66b8d39 | |||
| 04837f237d | |||
| 1fa3c843ab | |||
| cb7999ca71 | |||
| 34f91ebd1a | |||
| 5e0c8d5a40 | |||
| e182b89983 | |||
| e030a9b9f9 | |||
| 7705e4eb3b | |||
| ab3c0bfd2d | |||
| 1a3e72e899 | |||
| 52dc22f86f | |||
| 75ae2b4692 | |||
| 95dad649a8 | |||
| 1bdec9507d | |||
| 1834a66bff | |||
| 348a1447c8 | |||
| 4f9e064721 |
25
.gitignore
vendored
25
.gitignore
vendored
@ -1,6 +1,8 @@
|
|||||||
# Build artifacts
|
# Build artifacts
|
||||||
*.so
|
*.so
|
||||||
*.dll
|
*.dll
|
||||||
|
*.o
|
||||||
|
*.exe
|
||||||
*.hmap
|
*.hmap
|
||||||
plugin.json
|
plugin.json
|
||||||
|
|
||||||
@ -8,15 +10,28 @@ plugin.json
|
|||||||
build/
|
build/
|
||||||
dist/
|
dist/
|
||||||
|
|
||||||
# Binaries
|
# plugindev 预编译二进制:只作为 release 附件分发,不进仓库历史。
|
||||||
*.exe
|
# 此前 5 个平台各 26-28MB 被 git 跟踪(约 137MB),每次重编都在历史里
|
||||||
|
# 再叠一份,而它们本质是可从源码复现的产物。
|
||||||
|
bin/
|
||||||
|
|
||||||
# Test artifacts
|
# Test artifacts
|
||||||
testdist/
|
testdist/
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
*.logz_bridge_gen.go\nz_entry.c\nbuild/\ndist/
|
*.log
|
||||||
|
|
||||||
|
# Generated bridge files
|
||||||
z_bridge_gen.go
|
z_bridge_gen.go
|
||||||
z_entry.c
|
z_entry.c
|
||||||
build/
|
|
||||||
dist/
|
# Binaries (except pre-built distributions in bin/)
|
||||||
|
/plugindev
|
||||||
|
*_debug*
|
||||||
|
|
||||||
|
# Pre-built plugindev binaries in bin/ should be tracked
|
||||||
|
!bin/plugindev*
|
||||||
|
!bin/*.exe
|
||||||
|
|
||||||
|
# plugindev binary in tools/
|
||||||
|
tools/plugindev/plugindev
|
||||||
|
|||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
720
README.md
720
README.md
@ -2,6 +2,70 @@
|
|||||||
|
|
||||||
HomeAgent 插件开发 SDK,用于构建与 HomeAgent 平台交互的智能插件。
|
HomeAgent 插件开发 SDK,用于构建与 HomeAgent 平台交互的智能插件。
|
||||||
|
|
||||||
|
## 版本与兼容性
|
||||||
|
|
||||||
|
当前:**SDK 1.2.0**(需内核 **1.2.0+**)。
|
||||||
|
|
||||||
|
**版本号跟随内核的中版本,patch 位恒为 `.0`**:
|
||||||
|
|
||||||
|
| 内核版本 | 对应 SDK |
|
||||||
|
|---|---|
|
||||||
|
| 1.0.0 / 1.0.1 / … / 1.0.4 | 1.0.0 |
|
||||||
|
| 1.1.0 / 1.1.1 / … / 1.1.N | **1.1.0** |
|
||||||
|
| 1.2.0 起 | 1.2.0 |
|
||||||
|
|
||||||
|
内核的 patch 位专用于 bugfix 与漏洞修复,不碰公开接口,所以 SDK 版本号不跟着动——
|
||||||
|
否则你要么被迫跟版、要么怀疑自己版本过时,而接口其实一个字都没变。
|
||||||
|
|
||||||
|
**1.0.x 插件升到 1.1.x:不需要改代码,也不需要重编。** 1.1.0 的新增全部是
|
||||||
|
「插件调用、内核实现」方向,不调就不受影响(已用 SDK 0.9.2 编的旧 `plugin.bin`
|
||||||
|
实测验证:在新内核上直接建链通过,因为握手校验的是 `ProtocolVersion`、不是 SDK 版本)。
|
||||||
|
想用新字段时重编即可。
|
||||||
|
|
||||||
|
**1.1.x 插件升到 1.2.x:接口纯追加,但必须重编。** 公开接口没有签名变更(新增
|
||||||
|
`InjectOptions` 与六个 `*Opts` 变体、`ChannelDef.ContextPolicy`),不调新能力就不受影响;
|
||||||
|
但内核的**插件运行协议升到了 2**(统一共享内存区的 fd3 布局改变,**不支持滚动升级**),
|
||||||
|
所以 `plugin.bin` 必须用配套的 `hmapdev` 重编后与内核**同批**安装——否则握手时协议版本
|
||||||
|
不匹配会被拒绝(错误信息会明确提示用配套 hmapdev 重编,不会静默降级)。
|
||||||
|
|
||||||
|
## 注入行为与上下文裁剪(1.2.0)
|
||||||
|
|
||||||
|
「记不记入记忆」与「要不要据此裁剪上下文」这两件事,原先只有 `ToolDef` 能声明;
|
||||||
|
1.2.0 起**注入侧也能声明**,并且二者共用同一套语义与取值。
|
||||||
|
|
||||||
|
```go
|
||||||
|
type InjectOptions struct {
|
||||||
|
NoMemory bool // true = 不参与记忆计算(向量化/关键词提取/蒸馏),原文仍留在上下文
|
||||||
|
ContextPolicy string // ""/none = 不裁剪(默认);prune = 据此裁剪上下文
|
||||||
|
CleanerName string // 计算层过滤函数名:先经 Cleaner 得到实际有效内容,再计算/裁剪
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ContextPolicyNone = "none"
|
||||||
|
ContextPolicyPrune = "prune"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 六个变体,与旧的三参数方法一一对应,只多一个 opts
|
||||||
|
InjectTextOpts(source, channel, text string, opts InjectOptions)
|
||||||
|
InjectInterruptTextOpts(source, channel, text string, opts InjectOptions)
|
||||||
|
InjectInputSyncOpts(source, channel, text string, opts InjectOptions) string
|
||||||
|
InjectInputMediaOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions)
|
||||||
|
InjectInputMediaSyncOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions) string
|
||||||
|
InjectInterruptMediaOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions)
|
||||||
|
```
|
||||||
|
|
||||||
|
要点:
|
||||||
|
|
||||||
|
- **零值 `InjectOptions{}` 与旧的三参数方法逐键等价**(记入记忆 + 不裁剪)。旧方法保留为
|
||||||
|
零值糖(`InjectText` / `InjectInterruptText` / `InjectTextNoMemory` …),存量插件不改一行、
|
||||||
|
不需重编即可继续调用。
|
||||||
|
- **裁剪(`prune`)必须显式声明**:它会归档丢弃低相关事件,是有副作用的行为,故默认关闭。
|
||||||
|
内核只放行 `""` / `none` / `prune`(`ValidContextPolicy`),未声明的取值会被拒。
|
||||||
|
- 裁剪前先经该插件注册的 **`Cleaner`**(由 `CleanerName` 指定)拿到实际有效内容,
|
||||||
|
避开「按原文裁剪、按清洗后计算」这种不一致。
|
||||||
|
- `ChannelDef` 也有同名 `context_policy`(并且 1.2.0 给它补上了 JSON tag——通道定义要跨进程
|
||||||
|
传给内核,而 `Cleaner` 是函数必须忽略;无 tag 时新增字段会被静默丢掉)。
|
||||||
|
|
||||||
## SDK API 接口
|
## SDK API 接口
|
||||||
|
|
||||||
### Plugin 接口
|
### Plugin 接口
|
||||||
@ -23,7 +87,8 @@ type Plugin interface {
|
|||||||
| 分类 | 方法 | 说明 |
|
| 分类 | 方法 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| 阶段钩子 | `RegisterStage(stage, handler, scope...)` | 注册阶段回调,scope 可选:`StageScopeGlobal`(全局,默认)或 `StageScopeOwnTools`(仅自己工具) |
|
| 阶段钩子 | `RegisterStage(stage, handler, scope...)` | 注册阶段回调,scope 可选:`StageScopeGlobal`(全局,默认)或 `StageScopeOwnTools`(仅自己工具) |
|
||||||
| 输出通道 | `RegisterOutputChannel(name, caps, desc, handler)` | 注册输出通道,caps 为能力位掩码 |
|
| 输入通道 | `RegisterInputChannel(name, def)` | 注册输入通道,def 为 `ChannelDef`(NoMemory/Cleaner) |
|
||||||
|
| 输出通道 | `RegisterOutputChannel(name, caps, desc, def, handler)` | 注册输出通道,def 为 `ChannelDef`,caps 为能力位掩码 |
|
||||||
| 工具注册 | `RegisterTool(name, def, handler)` | 注册工具供 LLM 调用 |
|
| 工具注册 | `RegisterTool(name, def, handler)` | 注册工具供 LLM 调用 |
|
||||||
| 插件 API | `RegisterPluginAPI(name)` | 注册插件 API 供其他插件访问 |
|
| 插件 API | `RegisterPluginAPI(name)` | 注册插件 API 供其他插件访问 |
|
||||||
| 图记忆 | `Memory()` | 访问图记忆 API(实体-关系存储) |
|
| 图记忆 | `Memory()` | 访问图记忆 API(实体-关系存储) |
|
||||||
@ -35,6 +100,7 @@ type Plugin interface {
|
|||||||
| 设置 | `Settings()` | 访问设置 API |
|
| 设置 | `Settings()` | 访问设置 API |
|
||||||
| 事件 | `Events()` | 访问事件订阅器(外部插件仅订阅) |
|
| 事件 | `Events()` | 访问事件订阅器(外部插件仅订阅) |
|
||||||
| 注入 | `InjectText(source, channel, text)` / `InjectInterruptText(source, channel, text)` / `InjectTextNoMemory(source, channel, text)` | 向管道注入文本 |
|
| 注入 | `InjectText(source, channel, text)` / `InjectInterruptText(source, channel, text)` / `InjectTextNoMemory(source, channel, text)` | 向管道注入文本 |
|
||||||
|
| 多模态注入 | `InjectInputMedia(source, channel, text, blocks)` / `InjectInputMediaSync(...)` / `InjectInterruptMedia(...)` | 注入带图片/音频的输入(1.1.0 新增) |
|
||||||
| 自动重启 | `SetAutoRestart(enabled)` / `AutoRestart()` | 控制崩溃自动重启 |
|
| 自动重启 | `SetAutoRestart(enabled)` / `AutoRestart()` | 控制崩溃自动重启 |
|
||||||
|
|
||||||
### 阶段钩子
|
### 阶段钩子
|
||||||
@ -47,10 +113,30 @@ sdk.RegisterStage(StagePreAction, func(ctx *StageContext) error { return nil })
|
|||||||
sdk.RegisterStage(StageBeforeToolcall, myHandler, StageScopeOwnTools)
|
sdk.RegisterStage(StageBeforeToolcall, myHandler, StageScopeOwnTools)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ChannelDef
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ChannelDef struct {
|
||||||
|
NoMemory bool // 通道输入/输出不参与记忆计算(向量/关键词/蒸馏),原文保留
|
||||||
|
Cleaner func(string) string // 可选:计算层过滤函数(不改原文)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`ChannelDef` 控制通道在记忆计算层的行为,与 `ToolDef` 的 `NoMemory`/`Cleaner` 语义一致。
|
||||||
|
|
||||||
|
### 输入通道
|
||||||
|
|
||||||
|
```go
|
||||||
|
sdk.RegisterInputChannel("qq", ChannelDef{
|
||||||
|
NoMemory: true,
|
||||||
|
Cleaner: func(text string) string { return strings.TrimSpace(text) },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
### 输出通道
|
### 输出通道
|
||||||
|
|
||||||
```go
|
```go
|
||||||
sdk.RegisterOutputChannel("my-channel", CapText|CapFile, "通道描述", handler)
|
sdk.RegisterOutputChannel("my-channel", CapText|CapFile, "通道描述", ChannelDef{}, handler)
|
||||||
```
|
```
|
||||||
|
|
||||||
handler 接收三个参数:
|
handler 接收三个参数:
|
||||||
@ -85,6 +171,30 @@ type 枚举值:
|
|||||||
| `InjectInterruptText(source, channel, text)` | 注入中断文本,打断当前处理,路由到指定通道 |
|
| `InjectInterruptText(source, channel, text)` | 注入中断文本,打断当前处理,路由到指定通道 |
|
||||||
| `InjectTextNoMemory(source, channel, text)` | 注入文本,不记入内存,路由到指定通道 |
|
| `InjectTextNoMemory(source, channel, text)` | 注入文本,不记入内存,路由到指定通道 |
|
||||||
|
|
||||||
|
### 多模态注入(1.1.0 新增)
|
||||||
|
|
||||||
|
| 方法 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `InjectInputMedia(source, channel, text, blocks)` | 注入带媒体的输入,异步 |
|
||||||
|
| `InjectInputMediaSync(source, channel, text, blocks)` | 注入带媒体的输入并同步等待回复文本 |
|
||||||
|
| `InjectInterruptMedia(source, channel, text, blocks)` | 注入带媒体的中断,可抢占当前处理 |
|
||||||
|
|
||||||
|
`blocks` 是 `[]sdk.ContentBlock`,与 `SetToolBlocks` 用同一类型:
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.InjectInputMedia("myplugin", "webui", "帮我看看这张图", []sdk.ContentBlock{{
|
||||||
|
Type: "image_url",
|
||||||
|
ImageURL: &sdk.ImageURL{URL: "data:image/png;base64," + b64, Detail: "auto"},
|
||||||
|
}})
|
||||||
|
```
|
||||||
|
|
||||||
|
与 `SetToolBlocks` 的区别:`SetToolBlocks` 只能在工具处理函数内部调用,媒体要等到
|
||||||
|
下一条 tool message 才到模型手上;这三个方法是插件**主动发起一轮带媒体的对话**,
|
||||||
|
媒体在本轮就随消息发给模型,并自动落进媒体存储、挂上媒体记忆引用。
|
||||||
|
|
||||||
|
媒体块里的 `data:` URL 会被内核落盘去重;`http(s)` URL 只透传给模型,不入库
|
||||||
|
(入库需要内核发起网络请求,涉及超时、鉴权与 SSRF)。
|
||||||
|
|
||||||
`source` 标识来源,`channel` 指定目标输出通道。
|
`source` 标识来源,`channel` 指定目标输出通道。
|
||||||
|
|
||||||
### Triple 扩展字段
|
### Triple 扩展字段
|
||||||
@ -94,6 +204,75 @@ Triple 数据结构新增字段:
|
|||||||
- `Confidence` — 置信度(0.0~1.0)
|
- `Confidence` — 置信度(0.0~1.0)
|
||||||
- `SubjectType` — 主体类型
|
- `SubjectType` — 主体类型
|
||||||
- `ObjectType` — 客体类型
|
- `ObjectType` — 客体类型
|
||||||
|
- `SentenceText` — 原始句子文本(1.1.0 新增),写入 `sentences` 表;媒体引用挂在句子上
|
||||||
|
- `MediaDigests` — 关联的媒体 digest 列表(1.1.0 新增)
|
||||||
|
|
||||||
|
### 记忆里的媒体(1.1.0 新增)
|
||||||
|
|
||||||
|
媒体在纯文本记忆里以**标记**形式存在,格式 `[<mime> <短digest>] <描述>`:
|
||||||
|
|
||||||
|
```
|
||||||
|
[image/png a1b2c3d4e5f6] 一张紫蓝红三色带图
|
||||||
|
```
|
||||||
|
|
||||||
|
描述文本是持久的语义记忆(检索靠它),digest 是回到字节的钥匙(反查靠它)。
|
||||||
|
标记由内核生成,插件不必自己拼——**填 digest 就够**。
|
||||||
|
|
||||||
|
#### 图记忆
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.Memory().Commit([]sdk.Triple{{
|
||||||
|
Subject: "配色图", Relation: "包含", Object: "三色带",
|
||||||
|
MediaDigests: []string{"a1b2c3d4e5f6"}, // 短 digest 即可,内核补全
|
||||||
|
}})
|
||||||
|
```
|
||||||
|
|
||||||
|
没给 `SentenceText` 时内核会用标记本身充当句子——媒体必须有句子落点,
|
||||||
|
否则引用无从挂起。
|
||||||
|
|
||||||
|
#### 知识库
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.DocMemory().InsertWithMedia(&sdk.Doc{
|
||||||
|
Title: "带图笔记",
|
||||||
|
Content: "正文",
|
||||||
|
}, []sdk.MediaAttachment{
|
||||||
|
{MIME: "image/png", Data: pngBytes, Name: "chart.png"}, // 新内容,落盘去重
|
||||||
|
{Digest: "a1b2c3d4e5f6"}, // 引用已有内容
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`Insert` 保持原签名不变,正文里已有的标记同样会被挂成文档级引用。
|
||||||
|
`Query` 返回的 `Doc` 带 `MediaDigests` 与 `Attachments`(mime + 描述,
|
||||||
|
**不含字节**——一次检索可能命中几十份媒体)。删除文档时引用自动释放。
|
||||||
|
|
||||||
|
#### 文本记忆
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.TextMemory().Append(sdk.TextEvent{
|
||||||
|
Role: "user", Content: "看这张图",
|
||||||
|
Attachments: []sdk.MediaAttachment{{MIME: "image/png", Data: pngBytes}},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`RecentEvents` 读回时正文里的标记会被反解成 `Attachments`。
|
||||||
|
|
||||||
|
媒体存储可在内核侧关闭(`core.memory.media.enabled=false`),此时以上接口
|
||||||
|
全部退化为纯文本行为:不报错、不 panic,与本特性上线前一致。
|
||||||
|
|
||||||
|
### ToolDef 字段说明
|
||||||
|
|
||||||
|
`RegisterTool` 的 `def` 参数类型为 `sdk.ToolDef`,包含以下字段:
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `Name` | `string` | 工具名,建议插件名前缀避免冲突 |
|
||||||
|
| `Description` | `string` | 工具描述,LLM 据此选择调用 |
|
||||||
|
| `Parameters` | `map[string]interface{}` | JSON Schema 格式参数定义 |
|
||||||
|
| `NoMemory` | `bool` | 默认为 `false`;设为 `true` 时输出不参与向量/jieba/蒸馏计算(原文保留) |
|
||||||
|
| `Cleaner` | `func(string) string` | 可选,输出进入计算层前的清洗函数(如 JSON 提取 `.content`) |
|
||||||
|
|
||||||
|
`NoMemory` 和 `Cleaner` 的详细设计意图参见核心仓 `docs/zh/PLUGIN_DEV.md`。
|
||||||
|
|
||||||
### New 构造函数
|
### New 构造函数
|
||||||
|
|
||||||
@ -103,50 +282,150 @@ Triple 数据结构新增字段:
|
|||||||
func New(name string, sett SettingsAPI, regTool ToolRegistrar, regStage StageRegistrar, regAPI APIRegistrar, regOutput OutputChannelRegistrar) *PluginSDK
|
func New(name string, sett SettingsAPI, regTool ToolRegistrar, regStage StageRegistrar, regAPI APIRegistrar, regOutput OutputChannelRegistrar) *PluginSDK
|
||||||
```
|
```
|
||||||
|
|
||||||
插件开发者只需实现 `Plugin` 接口并导出 `NewPlugin()` 入口函数。
|
插件开发者只需实现 `Plugin` 接口并导出 `NewPluginFactory()` 入口函数。
|
||||||
|
|
||||||
## plugindev 工具链
|
## hmapdev 工具链
|
||||||
|
|
||||||
`plugindev` 提供插件开发全流程支持:
|
`hmapdev` 提供插件开发全流程支持,最终产出 `.hmap` 插件包(工具名即来自该包格式)。
|
||||||
|
预编译二进制作为 **release 附件**分发(linux/darwin/windows × amd64/arm64),从
|
||||||
|
[Releases](https://gitcode.com/JianFeeeee/homeagent-sdk/releases) 下载后加入 PATH 即可:
|
||||||
|
|
||||||
|
> 改名说明:工具链原名 `plugindev`,自 1.2.0 起更名 `hmapdev`。
|
||||||
|
> SDK 存储目录同时由 `~/.homeagent/plugindev/sdk` 迁到 `~/.homeagent/hmapdev/sdk`
|
||||||
|
> (旧目录会被自动沿用,不会丢已装版本)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 从 release 附件下载(以最新 SDK 发布 / linux amd64 为例)
|
||||||
|
curl -Lo hmapdev https://gitcode.com/JianFeeeee/homeagent-sdk/releases/download/<版本>/hmapdev_linux_amd64
|
||||||
|
chmod +x hmapdev
|
||||||
|
|
||||||
|
# 或从源码自己编
|
||||||
|
cd tools/hmapdev && go build -o hmapdev .
|
||||||
|
```
|
||||||
|
|
||||||
|
> 二进制不再随仓库分发(旧的 `bin/` 目录已停用):5 个平台各 26-28MB,
|
||||||
|
> 每次重编都在 git 历史里再叠一份,而它们本质是可从源码复现的产物。
|
||||||
|
|
||||||
| 命令 | 说明 |
|
| 命令 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `plugindev init` | 初始化插件项目(生成 plg.json、入口模板) |
|
| `hmapdev init <name> [--lua]` | 初始化插件项目(生成 plg.json、plugin.go 或 main.lua、go.mod、README.md) |
|
||||||
| `plugindev build` | 构建插件,输出 .hmap 包 |
|
| `hmapdev build [flags]` | 编译并打包为 `.hmap` 包(支持跨平台编译和 bundle 模式) |
|
||||||
| `plugindev clean` | 清理构建产物 |
|
| `hmapdev clean` | 清理 `build/`、`dist/` 目录及生成文件(plugin.json、z_bridge_gen.go) |
|
||||||
| `plugindev debug` | 本地调试模式运行插件 |
|
| `hmapdev debug [dir]` | 通过 Yaegi Go 解释器加载插件源码,启动交互式 REPL 调试 |
|
||||||
|
| `hmapdev sdk <command>` | SDK 版本管理(子命令:list/install/use/path/current/latest) |
|
||||||
|
|
||||||
支持 **Go** 和 **Lua** 两种插件语言。
|
支持 **Go** 和 **Lua** 两种插件语言。
|
||||||
|
|
||||||
|
### build 命令 flags
|
||||||
|
|
||||||
|
| Flag | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `--outdir <dir>` | 输出目录(默认 `dist`,可覆盖 plg.json 中的 `outdir`) |
|
||||||
|
| `--target <os/arch>` | 构建目标(如 `linux/amd64`),可重复指定(追加到 plg.json 中的 targets) |
|
||||||
|
| `--bundle` | 强制 bundle 模式(同时编译 linux/amd64, darwin/amd64, windows/amd64) |
|
||||||
|
| `--no-bundle` | 关闭 bundle 模式,仅按 targets 逐个编译 |
|
||||||
|
| `--sdk-path <path>` | 指定 SDK 源码路径(覆盖 plg.json 中的 `sdk_path`) |
|
||||||
|
| `--replace <from=to>` / `-R` | Go 模块替换(追加到 plg.json 中的 replaces),`from` 为模块路径,`to` 为本地路径 |
|
||||||
|
|
||||||
### plg.json 清单格式
|
### plg.json 清单格式
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"name": "my-plugin",
|
"name": "weather",
|
||||||
|
"name_zh": "天气查询",
|
||||||
|
"name_en": "Weather",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"lang": "go",
|
"description": "天气查询插件",
|
||||||
"entry": "main.go",
|
"author": "HomeAgent",
|
||||||
"description": "插件描述",
|
"entry": "plugin.bin",
|
||||||
"channels": ["my-channel"],
|
"tags": ["weather", "forecast"],
|
||||||
"dependencies": {}
|
"targets": "linux/amd64,windows/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {
|
||||||
|
"github.com/example/pkg": "../local/pkg"
|
||||||
|
},
|
||||||
|
"source_dirs": [
|
||||||
|
"../shared-lib"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `name` | string | 插件标识名 |
|
||||||
|
| `name_zh` | string | 中文名 |
|
||||||
|
| `name_en` | string | 英文名 |
|
||||||
|
| `version` | string | 版本号 |
|
||||||
|
| `description` | string | 插件描述 |
|
||||||
|
| `author` | string | 作者 |
|
||||||
|
| `entry` | string | 入口文件(`plugin.bin` / `main.lua`)。v1.0.0 起 Go 插件统一为 `plugin.bin`,不再区分平台后缀 |
|
||||||
|
| `tags` | string[] | 标签 |
|
||||||
|
| `targets` | string | 构建目标,逗号分隔(如 `linux/amd64,windows/amd64`,Lua 插件为 `lua`) |
|
||||||
|
| `outdir` | string | 输出目录(默认 `dist`) |
|
||||||
|
| `bundle` | bool | 是否 bundle 模式(同时编译多平台,默认 `true`) |
|
||||||
|
| `sdk_path` | string | SDK 源码路径(覆盖自动检测的 SDK 路径) |
|
||||||
|
| `go_version` | string | Go 版本(如 `1.21`,默认从 SDK 的 go.mod 读取) |
|
||||||
|
| `replaces` | object | Go 模块替换,key=模块路径,value=本地路径 |
|
||||||
|
| `source_dirs` | string[] | 额外源码搜索路径(编译时自动导入,用于引入 `thirdpart/` 外部的共享代码) |
|
||||||
|
|
||||||
### .hmap 包格式
|
### .hmap 包格式
|
||||||
|
|
||||||
`.hmap` 为 ZIP 归档,包含:
|
`.hmap` 为 ZIP 归档,包含:
|
||||||
|
|
||||||
- `plugin.json` — 插件元数据
|
- `plugin.json` — 插件元数据
|
||||||
- `plugin.so` — Go 编译产物(Linux)
|
- `plugin.bin` — Go 编译产物(单平台构建)
|
||||||
- `plugin.dll` — Go 编译产物(Windows)
|
- `plugin.bin.<goos>.<goarch>` — 多平台 bundle 模式下每平台一份,
|
||||||
|
安装时 pluginmgr 挑当前平台那份重命名为 `plugin.bin`
|
||||||
- `main.lua` — Lua 插件入口(Lua 插件时)
|
- `main.lua` — Lua 插件入口(Lua 插件时)
|
||||||
|
|
||||||
|
> v1.0.0 起不再使用 `plugin.so`/`plugin.dll`/`plugin.dylib`——进程边界即 ABI 边界,
|
||||||
|
> 不存在平台特定的动态库区分。旧产物新内核不会加载,会给出明确的重编提示。
|
||||||
|
|
||||||
## 插件生命周期
|
## 插件生命周期
|
||||||
|
|
||||||
|
### 入口函数
|
||||||
|
|
||||||
|
插件必须导出 `NewPluginFactory` 入口函数(Go)或 `start()` 函数(Lua):
|
||||||
|
|
||||||
|
**Go 插件** — 实现 `Plugin` 接口并导出工厂函数:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
该函数由内核在加载插件时调用,`name` 为插件名,`config` 为 `skill.json` 中的配置(如有)。
|
||||||
|
|
||||||
|
**Lua 插件** — 返回包含 `start(sdk)` 和 `stop()` 方法的 table:
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local plugin = { name = "my-plugin" }
|
||||||
|
function plugin.start(sdk) -- 注册工具等 end
|
||||||
|
function plugin.stop() end
|
||||||
|
return plugin
|
||||||
|
```
|
||||||
|
|
||||||
### 启动与停止
|
### 启动与停止
|
||||||
|
|
||||||
- `Start(sdk *PluginSDK) error` — 插件启动,接收 SDK 实例
|
- `Start(sdk *PluginSDK) error` — 插件启动,接收 SDK 实例
|
||||||
- `Stop() error` — 插件停止,释放资源
|
- `Stop() error` — 插件停止,释放资源
|
||||||
|
- `sdk.RegisterStopHandler(fn func())` — 注册停止清理回调。内核(内置插件)或 z_bridge(外部插件)会在调用插件 `Stop()` **之前**统一执行已注册的 handler(后注册先执行,执行后清空、幂等)。适合做持久化落盘、取消后台任务等清理:此时插件内存状态仍然新鲜,避免在 `Stop()` 阶段以陈旧状态写回导致数据复活。
|
||||||
|
|
||||||
|
### 删除清理(onRemove)
|
||||||
|
|
||||||
|
`Stop`/`RegisterStopHandler` 在插件**停止**(含重载、禁用)时执行;`RegisterOnRemoveHandler` 仅在插件被**卸载(删除)**时执行一次,重载/禁用不触发:
|
||||||
|
|
||||||
|
- `sdk.RegisterOnRemoveHandler(fn func())` — 注册删除清理回调。内核在 `RemovePlugin` 流程中、插件 `Stop()` **之后**执行(后注册先执行,执行后清空、幂等)。用于删除插件自身创建的持久化文件(数据/缓存/状态文件)。
|
||||||
|
- 内核卸载时一并清理:工具注册、`disabled_plugins` 记录、插件配置项定义(`plugin.<name>.*`)与插件配置表(`config_<name>`),卸载后插件配置区完全消失。
|
||||||
|
- 示例:`example/calendar`(删 events.json)、`example/memo`(删 memos.json)、`example/rss`(删订阅数据目录)、`example/weather`(删缓存目录);`hmapdev` 模板含 onRemove 演示。
|
||||||
|
|
||||||
|
```go
|
||||||
|
sdk.RegisterOnRemoveHandler(func() {
|
||||||
|
os.Remove(filepath.Join(dataDir, "events.json"))
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
### 自动重启
|
### 自动重启
|
||||||
|
|
||||||
@ -158,6 +437,31 @@ enabled := sdk.AutoRestart()
|
|||||||
|
|
||||||
插件崩溃时平台自动拉起,保障服务可用性。
|
插件崩溃时平台自动拉起,保障服务可用性。
|
||||||
|
|
||||||
|
> ⚠️ `SetAutoRestart` 的典型用法是「外部连接建好后再判定能否自动重启」,而连接建立
|
||||||
|
> 通常在后台 goroutine 里,内核又在另一个 goroutine 读它——这对读写天然并发。
|
||||||
|
> **SDK 1.1.0 已给这个标志与全部 API 字段加锁**(`-race` 实测 11 处竞态,
|
||||||
|
> 生产表现是插件重载瞬间偶发 nil 解引用崩溃)。早于 1.1.0 的版本建议升级。
|
||||||
|
|
||||||
|
## 插件开发者的并发约定
|
||||||
|
|
||||||
|
`PluginSDK` 是**被多个 goroutine 同时使用的共享对象**:你在 `Start()` 里起的轮询、
|
||||||
|
监听、定时器都拿着同一份 `*PluginSDK` 往里注消息,而内核会在加载/重载时写它的
|
||||||
|
API 字段。因此:
|
||||||
|
|
||||||
|
- **SDK 侧已保证的**:全部 API 访问器(`Memory()`/`DocMemory()`/…)、全部注入方法、
|
||||||
|
`SetAutoRestart`/`AutoRestart`、`RegisterTool`/`RegisterStage`、
|
||||||
|
`RunStopHandlers`/`RunOnRemoveHandlers`(幂等,并发调也只执行一次)。
|
||||||
|
- **你需要自己保证的**:`StageContext` 的字段全部导出,并发读写必须自己持
|
||||||
|
`ctx.Lock()`/`ctx.RLock()`。尤其是 `ctx.Extra`——**map 的并发写在 Go 里是直接 fatal,
|
||||||
|
`recover` 接不住**。
|
||||||
|
|
||||||
|
```go
|
||||||
|
ctx.Lock()
|
||||||
|
ctx.Extra["mykey"] = value
|
||||||
|
ctx.FinalText += "补充说明"
|
||||||
|
ctx.Unlock()
|
||||||
|
```
|
||||||
|
|
||||||
## 受限 SDK vs 完整 SDK
|
## 受限 SDK vs 完整 SDK
|
||||||
|
|
||||||
外部插件(第三方分发)使用**受限 SDK**,仅暴露安全子集:
|
外部插件(第三方分发)使用**受限 SDK**,仅暴露安全子集:
|
||||||
@ -171,35 +475,383 @@ enabled := sdk.AutoRestart()
|
|||||||
|
|
||||||
## 示例插件
|
## 示例插件
|
||||||
|
|
||||||
| 插件 | 说明 |
|
| 插件 | 类型 | 说明 |
|
||||||
|------|------|
|
|------|------|------|
|
||||||
| a2a | Agent-to-Agent 协议通信 |
|
| [weather](example/weather) | Go | 天气查询(wttr.in),演示 NoMemory/Cleaner/阶段钩子/通道/文本记忆 |
|
||||||
| bili | Bilibili 视频下载 |
|
| [luademo](example/luademo) | Lua | Lua 全功能示例,覆盖 v0.8.0 Lua SDK 全部 API 面 |
|
||||||
| browser | 网络搜索、网页抓取、浏览器渲染(合并自 web/webfetch) |
|
| [qq](example/qq) | Go | QQ 消息集成(NapCat),17 个工具,输入/输出通道完整对接 |
|
||||||
| editdoc | 文档编辑 |
|
| [a2a](example/a2a) | Go | Agent-to-Agent 协议通信 |
|
||||||
| files | 文件管理 |
|
| [ai_image](example/ai_image) | Go | AI 图片生成 |
|
||||||
| memo | 备忘录/记忆 |
|
| [bili](example/bili) | Go | Bilibili 视频下载 |
|
||||||
| ocr | 光学字符识别 |
|
| [browser](example/browser) | Go | 网络搜索、网页抓取、浏览器渲染 |
|
||||||
| qq | QQ 消息集成 |
|
| [calendar](example/calendar) | Go | 日历管理 |
|
||||||
| sanitizer | 内容清洗/安全过滤 |
|
| [editdoc](example/editdoc) | Go | 文档编辑 |
|
||||||
|
| [files](example/files) | Go | 文件管理 |
|
||||||
|
| [memo](example/memo) | Go | 备忘录(PreAction 注入 + 定时提醒) |
|
||||||
|
| [music](example/music) | Go | 音乐播放 |
|
||||||
|
| [ocr](example/ocr) | Go | 光学字符识别 |
|
||||||
|
| [rss](example/rss) | Go | RSS 订阅 |
|
||||||
|
| [sanitizer](example/sanitizer) | Go | 内容清洗/安全过滤 |
|
||||||
|
|
||||||
|
**发版时附带预编译示例产物**:SDK 的 release 除 5 平台 `hmapdev` 外,还包含各示例插件的
|
||||||
|
`.hmap` 与 `SHA256SUMS`/`MANIFEST.txt`。原因是插件二进制与内核**协议绑定**(`ProtocolVersion`
|
||||||
|
+ 共享内存区魔数),只发工具链不发示例产物,很容易拿旧产物去装而握手失败——那看起来像
|
||||||
|
「插件坏了」而不是「版本不配套」。
|
||||||
|
|
||||||
|
## Remote Device SDK
|
||||||
|
|
||||||
|
用于开发**远程设备接入适配器**的 C 语言 SDK,零外部依赖,兼容嵌入式平台。
|
||||||
|
|
||||||
|
### 架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ ha_remotedevice (C SDK) │
|
||||||
|
│ 协议引擎 │ WS 帧 │ JSON │ 状态机 │ 传输抽象 │
|
||||||
|
└──────────┬──────────────────────────────────────┘
|
||||||
|
│ 同一份 C 代码,设备端和 App 端共用
|
||||||
|
┌──────┴──────────────────┐
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────┐ ┌──────────────────────────┐
|
||||||
|
│ ESP32 裸机 │ │ Linux 设备上的 App │
|
||||||
|
│ 纯 C 直调 │ │ (Python ctypes / Go CGo / │
|
||||||
|
│ 简单命令处理 │ │ Node addon / C# P/Invoke) │
|
||||||
|
└──────────────┘ └──────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 声明式 API 设计
|
||||||
|
|
||||||
|
设备在代码中声明**自己是什么**、**能做什么**、**支持哪些命令**,每个命令对应独立处理函数,SDK 自动分发并回执结果:
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
|
||||||
|
/* 声明能力 */
|
||||||
|
const char *caps[] = {"camera", "status", NULL};
|
||||||
|
|
||||||
|
/* 声明式命令处理表:每个命令绑定独立处理函数 */
|
||||||
|
static ha_status_t handle_camerasue(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata) {
|
||||||
|
(void)req_id; (void)userdata;
|
||||||
|
int duration = args[0] ? atoi(args) : 0;
|
||||||
|
// 拍照/录像...
|
||||||
|
result->status = 0;
|
||||||
|
result->output = "data:image/jpeg;base64,..."; // SDK 自动回执
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_cmd_handler_def_t handlers[] = {
|
||||||
|
{.command = "shell", .handler = handle_shell},
|
||||||
|
{.command = "camerasue", .handler = handle_camerasue},
|
||||||
|
{.command = "screensee", .handler = handle_screensee},
|
||||||
|
{.command = "speakeruse", .handler = handle_speakeruse},
|
||||||
|
{.command = NULL}, /* 标记结束 */
|
||||||
|
};
|
||||||
|
|
||||||
|
ha_config_t config = {
|
||||||
|
.transport = my_transport, // 用户实现 4 个函数
|
||||||
|
.server = "192.168.1.100:9890",
|
||||||
|
.token = "my-token",
|
||||||
|
.device = {
|
||||||
|
.device_id = "esp32-cam-1",
|
||||||
|
.name = "门口摄像头",
|
||||||
|
.kind = "camera",
|
||||||
|
.caps = caps,
|
||||||
|
},
|
||||||
|
.handlers = handlers, // 声明式命令处理表
|
||||||
|
.on_state = my_state_handler,
|
||||||
|
};
|
||||||
|
|
||||||
|
ha_client_t *client = ha_client_new(&config);
|
||||||
|
ha_client_start(client);
|
||||||
|
while (1) {
|
||||||
|
ha_client_process(client); // 主循环处理
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 传输层抽象
|
||||||
|
|
||||||
|
用户只需实现 4 个函数,适配不同平台:
|
||||||
|
|
||||||
|
```c
|
||||||
|
ha_transport_t my_transport = {
|
||||||
|
.connect = my_tcp_connect, // 建立 TCP 连接
|
||||||
|
.send = my_tcp_send, // 发送数据
|
||||||
|
.recv = my_tcp_recv, // 接收数据(阻塞)
|
||||||
|
.close = my_tcp_close, // 关闭连接
|
||||||
|
.ctx = &my_platform_ctx,
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 支持的协议
|
||||||
|
|
||||||
|
| 功能 | API |
|
||||||
|
|------|-----|
|
||||||
|
| WS 连接 + 握手 | `ha_client_start` 自动完成 |
|
||||||
|
| 设备注册 (hello/bind) | 启动时自动发送 |
|
||||||
|
| 命令接收 (shell/homeagent) | `handlers` 表声明式注册,SDK 自动分发 |
|
||||||
|
| 命令回执 | `ha_client_send_result` |
|
||||||
|
| 二进制分块(录像等) | `ha_client_send_data_chunked` |
|
||||||
|
| TTS 音频接收 | `on_binary` 回调 |
|
||||||
|
| 事件上报 | `ha_client_send_event` |
|
||||||
|
| 状态上报 | `ha_client_send_status` |
|
||||||
|
| 心跳保持 | 自动 ping/pong |
|
||||||
|
|
||||||
|
### 使用方式
|
||||||
|
|
||||||
|
通过 `hmapdev` 工具链初始化项目:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev init my-adapter --type remotedevice
|
||||||
|
```
|
||||||
|
|
||||||
|
生成 `main.c` + `CMakeLists.txt`,可直接编译或作为三方库引入:
|
||||||
|
|
||||||
|
```cmake
|
||||||
|
add_subdirectory(path/to/ha_remotedevice)
|
||||||
|
target_link_libraries(my_app ha_remotedevice)
|
||||||
|
target_include_directories(my_app PRIVATE ${HA_REMOTEDEVICE_INCLUDE_DIR})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 快速接入指南
|
||||||
|
|
||||||
|
以下是从零到设备成功接入 HomeAgent 的完整步骤。
|
||||||
|
|
||||||
|
#### 1. 准备工作
|
||||||
|
|
||||||
|
在 HomeAgent 平台上创建接入令牌:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在 HomeAgent 服务端创建一个设备接入令牌
|
||||||
|
curl -X POST http://<homeagent-server>:8080/api/v1/device/token \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"device_id":"esp32-cam-1","name":"门口摄像头","kind":"camera"}'
|
||||||
|
# 返回: {"token":"ha-dev-token-xxxxx"}
|
||||||
|
```
|
||||||
|
|
||||||
|
记录下返回的 `token`,设备端配置时使用。
|
||||||
|
|
||||||
|
#### 2. 实现传输层(4 个函数)
|
||||||
|
|
||||||
|
根据你的平台实现 `ha_transport_t` 的 4 个函数指针。以下是几种常见场景:
|
||||||
|
|
||||||
|
**场景 A:带 TCP/IP 栈的嵌入式设备(如 ESP32 + lwIP)**
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
static int esp_connect(void *ctx, const char *host, uint16_t port) {
|
||||||
|
struct sockaddr_in addr;
|
||||||
|
int sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (sock < 0) return -1;
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(port);
|
||||||
|
inet_pton(AF_INET, host, &addr.sin_addr);
|
||||||
|
int ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
|
||||||
|
if (ret < 0) { closesocket(sock); return -1; }
|
||||||
|
*(int *)ctx = sock;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int esp_send(void *ctx, const uint8_t *data, int len) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
return send(sock, (const char *)data, len, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int esp_recv(void *ctx, uint8_t *buf, int len) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
return recv(sock, (char *)buf, len, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void esp_close(void *ctx) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
closesocket(sock);
|
||||||
|
}
|
||||||
|
|
||||||
|
int esp_ctx = -1;
|
||||||
|
ha_transport_t transport = {
|
||||||
|
.connect = esp_connect,
|
||||||
|
.send = esp_send,
|
||||||
|
.recv = esp_recv,
|
||||||
|
.close = esp_close,
|
||||||
|
.ctx = &esp_ctx,
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**场景 B:通过串口(UART)连接透传模块**
|
||||||
|
|
||||||
|
```c
|
||||||
|
static int uart_connect(void *ctx, const char *host, uint16_t port) {
|
||||||
|
(void)host; (void)port;
|
||||||
|
// 初始化 UART,波特率 115200
|
||||||
|
return uart_init((uart_ctx_t *)ctx, 115200);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int uart_send(void *ctx, const uint8_t *data, int len) {
|
||||||
|
return uart_write((uart_ctx_t *)ctx, data, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int uart_recv(void *ctx, uint8_t *buf, int len) {
|
||||||
|
return uart_read((uart_ctx_t *)ctx, buf, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void uart_close(void *ctx) {
|
||||||
|
uart_deinit((uart_ctx_t *)ctx);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 注意:UART 透传时,另一端需运行一个 TCP 桥接程序,将串口数据转发到 HomeAgent 的 WebSocket 端口。
|
||||||
|
|
||||||
|
#### 3. 声明设备能力和命令处理
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
|
||||||
|
/* 声明设备能力 */
|
||||||
|
const char *caps[] = {"camera", "speaker", "status", NULL};
|
||||||
|
|
||||||
|
/* 处理 camerasue 命令(拍照) */
|
||||||
|
static ha_status_t handle_camera(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata) {
|
||||||
|
(void)req_id; (void)userdata;
|
||||||
|
int duration = args[0] ? atoi(args) : 0; // 参数:录像时长
|
||||||
|
|
||||||
|
// 拍照或录像,将结果填入 result
|
||||||
|
result->status = 0;
|
||||||
|
result->output = "data:image/jpeg;base64,/9j/4AAQ..."; // base64 图像数据
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 处理 shell 命令 */
|
||||||
|
static ha_status_t handle_shell(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata) {
|
||||||
|
(void)req_id; (void)userdata;
|
||||||
|
// 执行 shell 命令,args 为完整命令字符串
|
||||||
|
result->status = 0;
|
||||||
|
result->output = "command executed";
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 声明式命令处理表 */
|
||||||
|
ha_cmd_handler_def_t handlers[] = {
|
||||||
|
{.command = "shell", .handler = handle_shell},
|
||||||
|
{.command = "camerasue", .handler = handle_camera},
|
||||||
|
{.command = "screensee", .handler = handle_camera},
|
||||||
|
{.command = "speakeruse", .handler = handle_speaker},
|
||||||
|
{.command = NULL}, /* 标记结束 */
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. 配置并启动客户端
|
||||||
|
|
||||||
|
```c
|
||||||
|
ha_config_t config = {
|
||||||
|
.transport = transport, // 传输层实现
|
||||||
|
.server = "192.168.1.100:9890", // HomeAgent 服务端地址
|
||||||
|
.token = "ha-dev-token-xxxxx", // 第 1 步获取的令牌
|
||||||
|
.device = {
|
||||||
|
.device_id = "esp32-cam-1",
|
||||||
|
.name = "门口摄像头",
|
||||||
|
.kind = "camera",
|
||||||
|
.caps = caps,
|
||||||
|
.info_json = "{\"chip\":\"ESP32-S3\",\"firmware\":\"v1.0\"}",
|
||||||
|
},
|
||||||
|
.handlers = handlers, // 命令处理表
|
||||||
|
.on_binary = on_binary_data, // 接收 TTS 音频等二进制数据
|
||||||
|
.on_state = on_state_change, // 连接状态变化回调
|
||||||
|
.ping_interval = 30, // 心跳间隔秒数
|
||||||
|
};
|
||||||
|
|
||||||
|
ha_client_t *client = ha_client_new(&config);
|
||||||
|
ha_status_t ret = ha_client_start(client);
|
||||||
|
if (ret != HA_OK) {
|
||||||
|
printf("设备接入失败: %d\n", ret);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 主循环 */
|
||||||
|
while (1) {
|
||||||
|
ha_client_process(client); // 处理协议帧、心跳、命令分发
|
||||||
|
|
||||||
|
/* 可选:设备主动上报事件 */
|
||||||
|
ha_client_send_event(client, "motion_detected",
|
||||||
|
"{\"zone\":\"front_door\",\"confidence\":0.95}");
|
||||||
|
|
||||||
|
/* 可选:上报设备状态 */
|
||||||
|
ha_client_send_status(client, "online");
|
||||||
|
|
||||||
|
vTaskDelay(100 / portTICK_PERIOD_MS); // 嵌入式 RTOS 风格延时
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 5. 验证连接
|
||||||
|
|
||||||
|
在 HomeAgent 服务端检查设备是否在线:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看已注册设备列表
|
||||||
|
curl http://<homeagent-server>:8080/api/v1/device/list
|
||||||
|
# 预期输出包含: {"device_id":"esp32-cam-1","status":"online",...}
|
||||||
|
|
||||||
|
# 向设备发送命令(测试 camerasue)
|
||||||
|
curl -X POST http://<homeagent-server>:8080/api/v1/device/esp32-cam-1/cmd \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"cmd":"camerasue","args":"3"}'
|
||||||
|
# 预期返回: {"status":"ok","result":"data:image/jpeg;base64,..."}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 6. 调试技巧
|
||||||
|
|
||||||
|
| 问题 | 检查点 |
|
||||||
|
|------|--------|
|
||||||
|
| 连接失败 | 确认 `server` 地址和端口可通;检查 `token` 是否正确 |
|
||||||
|
| WS 握手失败 | 确认 HomeAgent 服务端已开启 WebSocket 支持 |
|
||||||
|
| 命令无响应 | 确认 `handlers` 表中注册了对应命令名;检查 `on_binary` 是否配置 |
|
||||||
|
| 断线重连 | `max_reconnect` 控制重连次数,-1 为无限重连 |
|
||||||
|
| 内存不足(嵌入式) | 定义 `HA_NO_ALLOC` 宏禁用动态内存分配 |
|
||||||
|
|
||||||
|
### 位置
|
||||||
|
|
||||||
|
- **SDK 源码**: `remotedevice/`
|
||||||
|
- **hmapdev 模板**: `hmapdev init --type remotedevice`
|
||||||
|
|
||||||
## 构建与安装
|
## 构建与安装
|
||||||
|
|
||||||
### 构建
|
### 构建
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
plugindev build
|
hmapdev build
|
||||||
```
|
```
|
||||||
|
|
||||||
输出 `.hmap` 包到项目目录。
|
输出 `.hmap` 包到 `dist/` 目录(默认 bundle 多平台合集;单平台构建使用 `hmapdev build --no-bundle`)。
|
||||||
|
|
||||||
### 安装
|
### 安装
|
||||||
|
|
||||||
通过 pluginmgr HTTP API 安装:
|
通过 pluginmgr HTTP API 安装(端口默认 9876,仅监听 127.0.0.1,无鉴权):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -X POST http://<host>:<port>/api/plugins/install \
|
# 本地路径
|
||||||
-F "package=@my-plugin.hmap"
|
curl -X POST http://127.0.0.1:9876/plugins \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"path": "/path/to/my-plugin.hmap"}'
|
||||||
|
|
||||||
|
# 直接上传二进制
|
||||||
|
curl -X POST http://127.0.0.1:9876/plugins \
|
||||||
|
--data-binary @dist/my-plugin.hmap
|
||||||
```
|
```
|
||||||
|
|
||||||
或手动将 `.hmap` 放入插件目录后重启平台。
|
或通过 WebUI 插件管理页面上传,也可手动将 `.hmap` 放入插件目录后重启平台。
|
||||||
|
|
||||||
|
## 许可
|
||||||
|
|
||||||
|
SDK 以 **AGPL-3.0-only** 发布,全文见 [LICENSE](LICENSE)。
|
||||||
|
|
||||||
|
**这对插件开发者是实质性约束**:SDK 会随插件一起**静态链接**(其源码进入插件二进制),
|
||||||
|
插件因此是本 SDK 的衍生作品,**必须以相同许可(AGPL-3.0-only)发布**;并且因为 AGPL §13
|
||||||
|
覆盖网络交互,通过 HTTP/WebSocket 等向用户提供服务的插件同样要向使用者提供源码。
|
||||||
|
若你的插件需要闭源,唯一合规路径是另行取得本项目的例外/商业授权——目前不提供。
|
||||||
|
|
||||||
|
第三方组件(Go 依赖:go-sqlite3、gojieba、bubbletea 等,均为 MIT / BSD-3 / Apache-2.0)
|
||||||
|
保持各自原有许可。平台侧的模型与推理运行时(Chinese-CLIP Apache-2.0、ONNX Runtime MIT)
|
||||||
|
不属于本 SDK,其许可全文随发行包放在 `/usr/share/doc/homeagent/licenses/`。
|
||||||
|
|||||||
693
README_EN.md
693
README_EN.md
@ -2,6 +2,83 @@
|
|||||||
|
|
||||||
Plugin development SDK for building intelligent plugins that interact with the HomeAgent platform.
|
Plugin development SDK for building intelligent plugins that interact with the HomeAgent platform.
|
||||||
|
|
||||||
|
## Version and Compatibility
|
||||||
|
|
||||||
|
Current: **SDK 1.2.0** (requires kernel **1.2.0+**).
|
||||||
|
|
||||||
|
**The version tracks the kernel's minor version, with the patch position pinned at `.0`**:
|
||||||
|
|
||||||
|
| Kernel version | Matching SDK |
|
||||||
|
|---|---|
|
||||||
|
| 1.0.0 / 1.0.1 / … / 1.0.4 | 1.0.0 |
|
||||||
|
| 1.1.0 / 1.1.1 / … / 1.1.N | **1.1.0** |
|
||||||
|
| 1.2.0 onward | 1.2.0 |
|
||||||
|
|
||||||
|
The kernel's patch position is reserved for bugfixes and vulnerability fixes, which never touch the
|
||||||
|
public interface, so the SDK version has no reason to move with it — otherwise you would either be
|
||||||
|
forced to chase releases or suspect your version is stale, when not one character of the interface
|
||||||
|
has changed.
|
||||||
|
|
||||||
|
**Upgrading a 1.0.x plugin to 1.1.x: no code changes, no rebuild.** Everything added in 1.1.0 is
|
||||||
|
in the "plugin calls, kernel implements" direction, so not calling it means not being affected
|
||||||
|
(verified with an old `plugin.bin` built against SDK 0.9.2: it handshakes fine on the new kernel,
|
||||||
|
because the handshake validates `ProtocolVersion`, not the SDK version). Rebuild only when you want
|
||||||
|
the new fields.
|
||||||
|
|
||||||
|
**Upgrading a 1.1.x plugin to 1.2.x: the interface is purely additive, but a rebuild is required.**
|
||||||
|
No public signature changed (the SDK adds `InjectOptions`, six `*Opts` variants and
|
||||||
|
`ChannelDef.ContextPolicy`), so not calling the new capabilities means not being affected — but the
|
||||||
|
kernel's **plugin protocol went to 2** (the fd3 layout of the unified shared-memory region changed,
|
||||||
|
and **rolling upgrades are not supported**). `plugin.bin` must therefore be rebuilt with the matching
|
||||||
|
`hmapdev` and installed **together with** the kernel; otherwise the handshake fails on protocol
|
||||||
|
version mismatch (the error says explicitly to rebuild with the matching hmapdev — it never
|
||||||
|
degrades silently).
|
||||||
|
|
||||||
|
## Injection Behaviour and Context Pruning (1.2.0)
|
||||||
|
|
||||||
|
"Should this go into memory" and "should the context be pruned based on this" used to be
|
||||||
|
something only `ToolDef` could declare. Since 1.2.0 **injections can declare them too**, sharing
|
||||||
|
the same semantics and values.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type InjectOptions struct {
|
||||||
|
NoMemory bool // true = excluded from memory computation (vectorize/keywords/distill); the
|
||||||
|
// original text still stays in context
|
||||||
|
ContextPolicy string // ""/none = do not prune (default); prune = prune context based on this
|
||||||
|
CleanerName string // name of the compute-layer cleaner: run it first to get the effective
|
||||||
|
// content, then compute/prune on that
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ContextPolicyNone = "none"
|
||||||
|
ContextPolicyPrune = "prune"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Six variants, one-to-one with the older three-argument methods, plus opts
|
||||||
|
InjectTextOpts(source, channel, text string, opts InjectOptions)
|
||||||
|
InjectInterruptTextOpts(source, channel, text string, opts InjectOptions)
|
||||||
|
InjectInputSyncOpts(source, channel, text string, opts InjectOptions) string
|
||||||
|
InjectInputMediaOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions)
|
||||||
|
InjectInputMediaSyncOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions) string
|
||||||
|
InjectInterruptMediaOpts(source, channel, text string, blocks []ContentBlock, opts InjectOptions)
|
||||||
|
```
|
||||||
|
|
||||||
|
Key points:
|
||||||
|
|
||||||
|
- **A zero-valued `InjectOptions{}` is key-for-key equivalent to the older three-argument methods**
|
||||||
|
(recorded in memory, not pruned). The old methods remain as zero-value sugar (`InjectText`,
|
||||||
|
`InjectInterruptText`, `InjectTextNoMemory`, …), so existing plugins keep working without a single
|
||||||
|
line changed *or* a rebuild.
|
||||||
|
- **Pruning (`prune`) must be declared explicitly**: it archives/drops low-relevance events, which
|
||||||
|
is a side effect, so it is off by default. The kernel only accepts `""` / `none` / `prune`
|
||||||
|
(`ValidContextPolicy`); anything else is rejected.
|
||||||
|
- Pruning first goes through the plugin's registered **`Cleaner`** (named by `CleanerName`) to get
|
||||||
|
the effective content, avoiding the inconsistency of "prune on the raw text, compute on the
|
||||||
|
cleaned text".
|
||||||
|
- `ChannelDef` carries the same `context_policy` (1.2.0 also gave `ChannelDef` JSON tags — the
|
||||||
|
definition crosses the process boundary, while `Cleaner` is a function that must be ignored; with
|
||||||
|
no tags, newly added fields would be silently dropped).
|
||||||
|
|
||||||
## SDK API Surface
|
## SDK API Surface
|
||||||
|
|
||||||
### Plugin Interface
|
### Plugin Interface
|
||||||
@ -23,7 +100,8 @@ The SDK instance injected via `Start(sdk *PluginSDK)` provides:
|
|||||||
| Category | Method | Description |
|
| Category | Method | Description |
|
||||||
|----------|--------|-------------|
|
|----------|--------|-------------|
|
||||||
| Stage Hooks | `RegisterStage(stage, handler, scope...)` | Register stage callback; scope: `StageScopeGlobal` (all, default) or `StageScopeOwnTools` (own tools only) |
|
| Stage Hooks | `RegisterStage(stage, handler, scope...)` | Register stage callback; scope: `StageScopeGlobal` (all, default) or `StageScopeOwnTools` (own tools only) |
|
||||||
| Output Channel | `RegisterOutputChannel(name, caps, desc, handler)` | Register output channel with capability bitmask |
|
| Input Channel | `RegisterInputChannel(name, def)` | Register input channel with `ChannelDef` (NoMemory/Cleaner) |
|
||||||
|
| Output Channel | `RegisterOutputChannel(name, caps, desc, def, handler)` | Register output channel with `ChannelDef` and capability bitmask |
|
||||||
| Tool Registration | `RegisterTool(name, def, handler)` | Register a tool for LLM invocation |
|
| Tool Registration | `RegisterTool(name, def, handler)` | Register a tool for LLM invocation |
|
||||||
| Plugin API | `RegisterPluginAPI(name)` | Register plugin API for inter-plugin access |
|
| Plugin API | `RegisterPluginAPI(name)` | Register plugin API for inter-plugin access |
|
||||||
| Graph Memory | `Memory()` | Access graph memory API (entity-relation store) |
|
| Graph Memory | `Memory()` | Access graph memory API (entity-relation store) |
|
||||||
@ -35,6 +113,7 @@ The SDK instance injected via `Start(sdk *PluginSDK)` provides:
|
|||||||
| Settings | `Settings()` | Access settings API |
|
| Settings | `Settings()` | Access settings API |
|
||||||
| Events | `Events()` | Access event subscriber (subscribe-only for external plugins) |
|
| Events | `Events()` | Access event subscriber (subscribe-only for external plugins) |
|
||||||
| Inject | `InjectText(source, channel, text)` / `InjectInterruptText(source, channel, text)` / `InjectTextNoMemory(source, channel, text)` | Inject text into the agent pipeline |
|
| Inject | `InjectText(source, channel, text)` / `InjectInterruptText(source, channel, text)` / `InjectTextNoMemory(source, channel, text)` | Inject text into the agent pipeline |
|
||||||
|
| Media inject | `InjectInputMedia(source, channel, text, blocks)` / `InjectInputMediaSync(...)` / `InjectInterruptMedia(...)` | Inject input carrying images/audio (added in 1.1.0) |
|
||||||
| Auto-Restart | `SetAutoRestart(enabled)` / `AutoRestart()` | Control automatic restart on crash |
|
| Auto-Restart | `SetAutoRestart(enabled)` / `AutoRestart()` | Control automatic restart on crash |
|
||||||
|
|
||||||
### Stage Hooks
|
### Stage Hooks
|
||||||
@ -47,10 +126,30 @@ sdk.RegisterStage(StagePreAction, func(ctx *StageContext) error { return nil })
|
|||||||
sdk.RegisterStage(StageBeforeToolcall, myHandler, StageScopeOwnTools)
|
sdk.RegisterStage(StageBeforeToolcall, myHandler, StageScopeOwnTools)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ChannelDef
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ChannelDef struct {
|
||||||
|
NoMemory bool // Channel input/output skips memory computation (vector/keyword/distill), original text preserved
|
||||||
|
Cleaner func(string) string // Optional: computation layer filter (does not modify original text)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`ChannelDef` controls channel behavior in the memory computation layer, with the same semantics as `ToolDef.NoMemory`/`Cleaner`.
|
||||||
|
|
||||||
|
### Input Channels
|
||||||
|
|
||||||
|
```go
|
||||||
|
sdk.RegisterInputChannel("qq", ChannelDef{
|
||||||
|
NoMemory: true,
|
||||||
|
Cleaner: func(text string) string { return strings.TrimSpace(text) },
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
### Output Channels
|
### Output Channels
|
||||||
|
|
||||||
```go
|
```go
|
||||||
sdk.RegisterOutputChannel("my-channel", CapText|CapFile, "channel description", handler)
|
sdk.RegisterOutputChannel("my-channel", CapText|CapFile, "channel description", ChannelDef{}, handler)
|
||||||
```
|
```
|
||||||
|
|
||||||
The handler receives three arguments:
|
The handler receives three arguments:
|
||||||
@ -85,6 +184,32 @@ Type enum values:
|
|||||||
| `InjectInterruptText(source, channel, text)` | Inject interrupt text, interrupt current processing, route to specified channel |
|
| `InjectInterruptText(source, channel, text)` | Inject interrupt text, interrupt current processing, route to specified channel |
|
||||||
| `InjectTextNoMemory(source, channel, text)` | Inject text without memory recording, route to specified channel |
|
| `InjectTextNoMemory(source, channel, text)` | Inject text without memory recording, route to specified channel |
|
||||||
|
|
||||||
|
### Multimodal Injection (added in 1.1.0)
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `InjectInputMedia(source, channel, text, blocks)` | Inject media-bearing input, asynchronous |
|
||||||
|
| `InjectInputMediaSync(source, channel, text, blocks)` | Inject media-bearing input and wait for the reply text |
|
||||||
|
| `InjectInterruptMedia(source, channel, text, blocks)` | Inject a media-bearing interrupt that can preempt current processing |
|
||||||
|
|
||||||
|
`blocks` is `[]sdk.ContentBlock`, the same type `SetToolBlocks` takes:
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.InjectInputMedia("myplugin", "webui", "take a look at this", []sdk.ContentBlock{{
|
||||||
|
Type: "image_url",
|
||||||
|
ImageURL: &sdk.ImageURL{URL: "data:image/png;base64," + b64, Detail: "auto"},
|
||||||
|
}})
|
||||||
|
```
|
||||||
|
|
||||||
|
How this differs from `SetToolBlocks`: that one is only callable inside a tool handler and
|
||||||
|
its media reaches the model with the *next* tool message. These three let a plugin
|
||||||
|
**initiate a turn that carries media** — the media goes out with this turn's message and is
|
||||||
|
automatically stored in the media store with a memory reference attached.
|
||||||
|
|
||||||
|
`data:` URLs in the blocks are stored and deduplicated by the kernel; `http(s)` URLs are
|
||||||
|
passed to the model only and never stored (storing them would require the kernel to make
|
||||||
|
network requests, bringing timeouts, auth and SSRF into scope).
|
||||||
|
|
||||||
`source` identifies the origin, `channel` specifies the target output channel.
|
`source` identifies the origin, `channel` specifies the target output channel.
|
||||||
|
|
||||||
### Triple Extended Fields
|
### Triple Extended Fields
|
||||||
@ -94,6 +219,79 @@ The Triple data structure includes additional fields:
|
|||||||
- `Confidence` — confidence score (0.0–1.0)
|
- `Confidence` — confidence score (0.0–1.0)
|
||||||
- `SubjectType` — subject type
|
- `SubjectType` — subject type
|
||||||
- `ObjectType` — object type
|
- `ObjectType` — object type
|
||||||
|
- `SentenceText` — the original sentence (added in 1.1.0), written to the `sentences` table; media references hang off the sentence
|
||||||
|
- `MediaDigests` — associated media digests (added in 1.1.0)
|
||||||
|
|
||||||
|
### Media in Memory (added in 1.1.0)
|
||||||
|
|
||||||
|
Inside plain-text memory, media is represented as a **marker** of the form
|
||||||
|
`[<mime> <short digest>] <description>`:
|
||||||
|
|
||||||
|
```
|
||||||
|
[image/png a1b2c3d4e5f6] a purple-blue-red three-band chart
|
||||||
|
```
|
||||||
|
|
||||||
|
The description is the durable semantic memory (retrieval uses it); the digest is the key
|
||||||
|
back to the bytes (reverse lookup uses it). Markers are generated by the kernel — a plugin
|
||||||
|
never has to assemble one, it just **supplies the digest**.
|
||||||
|
|
||||||
|
#### Graph memory
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.Memory().Commit([]sdk.Triple{{
|
||||||
|
Subject: "palette", Relation: "contains", Object: "three-band",
|
||||||
|
MediaDigests: []string{"a1b2c3d4e5f6"}, // short digest is fine, the kernel resolves it
|
||||||
|
}})
|
||||||
|
```
|
||||||
|
|
||||||
|
With no `SentenceText`, the kernel uses the marker itself as the sentence — media must have
|
||||||
|
a sentence to hang off, otherwise the reference has nowhere to attach.
|
||||||
|
|
||||||
|
#### Knowledge base
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.DocMemory().InsertWithMedia(&sdk.Doc{
|
||||||
|
Title: "illustrated note",
|
||||||
|
Content: "body",
|
||||||
|
}, []sdk.MediaAttachment{
|
||||||
|
{MIME: "image/png", Data: pngBytes, Name: "chart.png"}, // new content, stored and deduped
|
||||||
|
{Digest: "a1b2c3d4e5f6"}, // reference existing content
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`Insert` keeps its original signature; markers already present in the body are bound as
|
||||||
|
document-level references too. `Query` fills `MediaDigests` and `Attachments` (mime plus
|
||||||
|
description, **no bytes** — one query can match dozens of media items). Removing a document
|
||||||
|
releases its references.
|
||||||
|
|
||||||
|
#### Text memory
|
||||||
|
|
||||||
|
```go
|
||||||
|
s.TextMemory().Append(sdk.TextEvent{
|
||||||
|
Role: "user", Content: "look at this",
|
||||||
|
Attachments: []sdk.MediaAttachment{{MIME: "image/png", Data: pngBytes}},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`RecentEvents` decodes markers in the body back into `Attachments`.
|
||||||
|
|
||||||
|
The media store can be disabled kernel-side (`core.memory.media.enabled=false`); all of the
|
||||||
|
above then degrades to plain-text behaviour — no errors, no panics, identical to how it
|
||||||
|
behaved before this feature shipped.
|
||||||
|
|
||||||
|
### ToolDef Field Reference
|
||||||
|
|
||||||
|
The `def` parameter of `RegisterTool` is of type `sdk.ToolDef`, with the following fields:
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `Name` | `string` | Tool name, use plugin name prefix to avoid conflicts |
|
||||||
|
| `Description` | `string` | Tool description, LLM uses this for tool selection |
|
||||||
|
| `Parameters` | `map[string]interface{}` | JSON Schema parameter definition |
|
||||||
|
| `NoMemory` | `bool` | Default `false`; when `true`, output skips vector/jieba/distill computation (original text preserved) |
|
||||||
|
| `Cleaner` | `func(string) string` | Optional, filters output before computation layer (e.g., extract `.content` from JSON) |
|
||||||
|
|
||||||
|
For detailed design rationale of `NoMemory` and `Cleaner`, see `docs/en/PLUGIN_DEV.md` in the core repository.
|
||||||
|
|
||||||
### New Constructor
|
### New Constructor
|
||||||
|
|
||||||
@ -105,16 +303,37 @@ func New(name string, sett SettingsAPI, regTool ToolRegistrar, regStage StageReg
|
|||||||
|
|
||||||
Plugin developers only need to implement the `Plugin` interface and export a `NewPlugin()` entry function.
|
Plugin developers only need to implement the `Plugin` interface and export a `NewPlugin()` entry function.
|
||||||
|
|
||||||
## plugindev Toolchain
|
## hmapdev Toolchain
|
||||||
|
|
||||||
`plugindev` provides full development workflow support:
|
`hmapdev` provides full development workflow support and produces `.hmap` plugin bundles (the tool is
|
||||||
|
named after that package format). Prebuilt binaries ship as **release assets**
|
||||||
|
(linux/darwin/windows × amd64/arm64); download from
|
||||||
|
[Releases](https://gitcode.com/JianFeeeee/homeagent-sdk/releases) and put it on your PATH:
|
||||||
|
|
||||||
|
> Rename note: the toolchain was called `plugindev` and is `hmapdev` since 1.2.0.
|
||||||
|
> The SDK store moved from `~/.homeagent/plugindev/sdk` to `~/.homeagent/hmapdev/sdk`
|
||||||
|
> (the old directory is still honored, so installed versions are not lost).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# From release assets (latest SDK release / linux amd64 shown)
|
||||||
|
curl -Lo hmapdev https://gitcode.com/JianFeeeee/homeagent-sdk/releases/download/<version>/hmapdev_linux_amd64
|
||||||
|
chmod +x hmapdev
|
||||||
|
|
||||||
|
# Or build from source
|
||||||
|
cd tools/hmapdev && go build -o hmapdev .
|
||||||
|
```
|
||||||
|
|
||||||
|
> Binaries no longer ship inside the repository (the old `bin/` directory is retired): five
|
||||||
|
> platforms at 26-28MB each piled another copy into git history on every rebuild, and they are
|
||||||
|
> reproducible from source anyway.
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| `plugindev init` | Initialize plugin project (generates plg.json, entry template) |
|
| `hmapdev init <name> [--lua]` | Initialize plugin project (generates plg.json, plugin.go or main.lua, go.mod, README.md) |
|
||||||
| `plugindev build` | Build plugin, output .hmap package |
|
| `hmapdev build [flags]` | Build and package into a `.hmap` (supports cross-compilation and bundle mode) |
|
||||||
| `plugindev clean` | Clean build artifacts |
|
| `hmapdev clean` | Clean `build/` and `dist/` plus generated files |
|
||||||
| `plugindev debug` | Run plugin in local debug mode |
|
| `hmapdev debug [dir]` | Load plugin source through the Yaegi Go interpreter and start an interactive REPL |
|
||||||
|
| `hmapdev sdk <command>` | SDK version management (list/install/use/path/current/latest) |
|
||||||
|
|
||||||
Supports both **Go** and **Lua** plugin languages.
|
Supports both **Go** and **Lua** plugin languages.
|
||||||
|
|
||||||
@ -122,31 +341,77 @@ Supports both **Go** and **Lua** plugin languages.
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"name": "my-plugin",
|
"name": "weather",
|
||||||
|
"name_zh": "天气查询",
|
||||||
|
"name_en": "Weather",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"lang": "go",
|
"description": "Weather plugin",
|
||||||
"entry": "main.go",
|
"author": "HomeAgent",
|
||||||
"description": "Plugin description",
|
"entry": "plugin.bin",
|
||||||
"channels": ["my-channel"],
|
"tags": ["weather", "forecast"],
|
||||||
"dependencies": {}
|
"targets": "linux/amd64,windows/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {
|
||||||
|
"github.com/example/pkg": "../local/pkg"
|
||||||
|
},
|
||||||
|
"source_dirs": [
|
||||||
|
"../shared-lib"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `name` | string | Plugin identifier |
|
||||||
|
| `name_zh` | string | Chinese name |
|
||||||
|
| `name_en` | string | English name |
|
||||||
|
| `version` | string | Version |
|
||||||
|
| `description` | string | Plugin description |
|
||||||
|
| `author` | string | Author |
|
||||||
|
| `entry` | string | Entry file (`plugin.bin` / `main.lua`). Since v1.0.0 Go plugins uniformly build to `plugin.bin`—no per-platform suffix |
|
||||||
|
| `tags` | string[] | Tags |
|
||||||
|
| `targets` | string | Build targets, comma-separated (e.g. `linux/amd64,windows/amd64`) |
|
||||||
|
| `outdir` | string | Output directory (default `dist`) |
|
||||||
|
| `bundle` | bool | Bundle mode (build all platforms at once) |
|
||||||
|
| `replaces` | object | Go module replacements, key=module path, value=local path |
|
||||||
|
| `source_dirs` | string[] | Additional source search paths (auto-imported at build time) |
|
||||||
|
|
||||||
### .hmap Package Format
|
### .hmap Package Format
|
||||||
|
|
||||||
`.hmap` is a ZIP archive containing:
|
`.hmap` is a ZIP archive containing:
|
||||||
|
|
||||||
- `plugin.json` — plugin metadata
|
- `plugin.json` — plugin metadata
|
||||||
- `plugin.so` — Go compiled artifact (Linux)
|
- `plugin.bin` — Go compiled artifact (single-platform build)
|
||||||
- `plugin.dll` — Go compiled artifact (Windows)
|
- `plugin.bin.<goos>.<goarch>` — one per platform in bundle mode; on install pluginmgr picks
|
||||||
|
the one matching the current platform and renames it to `plugin.bin`
|
||||||
- `main.lua` — Lua plugin entry (for Lua plugins)
|
- `main.lua` — Lua plugin entry (for Lua plugins)
|
||||||
|
|
||||||
|
> Since v1.0.0 `plugin.so`/`plugin.dll`/`plugin.dylib` are no longer used—the process boundary
|
||||||
|
> *is* the ABI boundary, so there is no platform-specific shared-library distinction. The new
|
||||||
|
> kernel will not load old artifacts; it emits an explicit rebuild hint instead.
|
||||||
|
|
||||||
## Plugin Lifecycle
|
## Plugin Lifecycle
|
||||||
|
|
||||||
### Start & Stop
|
### Start & Stop
|
||||||
|
|
||||||
- `Start(sdk *PluginSDK) error` — Plugin startup, receives SDK instance
|
- `Start(sdk *PluginSDK) error` — Plugin startup, receives SDK instance
|
||||||
- `Stop() error` — Plugin shutdown, release resources
|
- `Stop() error` — Plugin shutdown, release resources
|
||||||
|
- `sdk.RegisterStopHandler(fn func())` — Register a shutdown cleanup callback. The kernel (for built-in plugins) or z_bridge (for external plugins) runs all registered handlers **before** calling the plugin's `Stop()` (LIFO order, cleared after running — idempotent). Use it for persistence and cancelling background work: plugin memory is still fresh at that point, avoiding stale-state write-backs that resurrect deleted data.
|
||||||
|
|
||||||
|
### Remove Cleanup (onRemove)
|
||||||
|
|
||||||
|
`Stop` / `RegisterStopHandler` run whenever the plugin **stops** (including reload and disable); `RegisterOnRemoveHandler` runs **only once when the plugin is uninstalled (removed)** — never on reload or disable:
|
||||||
|
|
||||||
|
- `sdk.RegisterOnRemoveHandler(fn func())` — Register a remove cleanup callback. The kernel runs it **after** the plugin's `Stop()` in the `RemovePlugin` flow (LIFO order, cleared after running — idempotent). Use it to delete persistent files the plugin created itself (data/cache/state files).
|
||||||
|
- The kernel also cleans up on uninstall: tool registrations, the `disabled_plugins` record, the plugin's config definitions (`plugin.<name>.*`) and its config table (`config_<name>`) — the plugin's config section disappears completely after removal.
|
||||||
|
- Examples: `example/calendar` (removes events.json), `example/memo` (removes memos.json), `example/rss` (removes the subscription data dir), `example/weather` (removes the cache dir); the `hmapdev` template includes an onRemove demo.
|
||||||
|
|
||||||
|
```go
|
||||||
|
sdk.RegisterOnRemoveHandler(func() {
|
||||||
|
os.Remove(filepath.Join(dataDir, "events.json"))
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
### Auto-Restart
|
### Auto-Restart
|
||||||
|
|
||||||
@ -158,6 +423,33 @@ enabled := sdk.AutoRestart()
|
|||||||
|
|
||||||
The platform automatically restarts the plugin on crash, ensuring service availability.
|
The platform automatically restarts the plugin on crash, ensuring service availability.
|
||||||
|
|
||||||
|
> ⚠️ `SetAutoRestart` is typically used to decide whether auto-restart is safe *after* an
|
||||||
|
> external connection has been established, and that connection setup usually happens in a
|
||||||
|
> background goroutine while the kernel reads the flag from another one — which is inherently
|
||||||
|
> concurrent. **SDK 1.1.0 locks this flag and all API fields** (`-race` reported 11 data races;
|
||||||
|
> in production this showed up as sporadic nil-dereference crashes during plugin reload). Upgrade
|
||||||
|
> if you are on anything earlier.
|
||||||
|
|
||||||
|
## Concurrency Contract for Plugin Developers
|
||||||
|
|
||||||
|
`PluginSDK` is a **shared object used by multiple goroutines**: the polling, listening and timer
|
||||||
|
callbacks you start in `Start()` all hold the same `*PluginSDK` and push messages into it, while
|
||||||
|
the kernel writes its API fields during load/reload. So:
|
||||||
|
|
||||||
|
- **Guaranteed by the SDK**: all API accessors (`Memory()`/`DocMemory()`/…), all injection methods,
|
||||||
|
`SetAutoRestart`/`AutoRestart`, `RegisterTool`/`RegisterStage`, and
|
||||||
|
`RunStopHandlers`/`RunOnRemoveHandlers` (idempotent; concurrent calls still run it once).
|
||||||
|
- **Your responsibility**: every field of `StageContext` is exported, and concurrent read/write
|
||||||
|
must hold `ctx.Lock()`/`ctx.RLock()`. Especially `ctx.Extra` — **concurrent map writes are a
|
||||||
|
fatal in Go, and `recover` cannot catch it**.
|
||||||
|
|
||||||
|
```go
|
||||||
|
ctx.Lock()
|
||||||
|
ctx.Extra["mykey"] = value
|
||||||
|
ctx.FinalText += "supplementary note"
|
||||||
|
ctx.Unlock()
|
||||||
|
```
|
||||||
|
|
||||||
## Restricted SDK vs Full SDK
|
## Restricted SDK vs Full SDK
|
||||||
|
|
||||||
External plugins (third-party distribution) use a **restricted SDK** that only exposes a safe subset:
|
External plugins (third-party distribution) use a **restricted SDK** that only exposes a safe subset:
|
||||||
@ -171,36 +463,369 @@ Internal plugins (platform built-in) have full SDK access including SocialAPI wr
|
|||||||
|
|
||||||
## Example Plugins
|
## Example Plugins
|
||||||
|
|
||||||
| Plugin | Description |
|
| Plugin | Type | Description |
|
||||||
|--------|-------------|
|
|--------|------|-------------|
|
||||||
| a2a | Agent-to-Agent protocol communication |
|
| [weather](example/weather) | Go | Weather queries (wttr.in); demonstrates NoMemory/Cleaner/stage hooks/channels/text memory |
|
||||||
| bili | Bilibili data fetching |
|
| [luademo](example/luademo) | Lua | Full-featured Lua example covering the whole v0.8.0 Lua SDK surface |
|
||||||
| editdoc | Document editing |
|
| [qq](example/qq) | Go | QQ messaging integration (NapCat), 17 tools, full input/output channel wiring |
|
||||||
| files | File management |
|
| [a2a](example/a2a) | Go | Agent-to-Agent protocol communication |
|
||||||
| memo | Memo/notes |
|
| [ai_image](example/ai_image) | Go | AI image generation |
|
||||||
| ocr | Optical character recognition |
|
| [bili](example/bili) | Go | Bilibili video downloading |
|
||||||
| qq | QQ messaging integration |
|
| [browser](example/browser) | Go | Web search, page fetching, browser rendering |
|
||||||
| sanitizer | Content sanitization/safety filtering |
|
| [calendar](example/calendar) | Go | Calendar management |
|
||||||
| web | Web browsing and interaction |
|
| [editdoc](example/editdoc) | Go | Document editing |
|
||||||
| webfetch | Web content fetching |
|
| [files](example/files) | Go | File management |
|
||||||
|
| [memo](example/memo) | Go | Memos (PreAction injection + scheduled reminders) |
|
||||||
|
| [music](example/music) | Go | Music playback |
|
||||||
|
| [ocr](example/ocr) | Go | Optical character recognition |
|
||||||
|
| [rss](example/rss) | Go | RSS subscriptions |
|
||||||
|
| [sanitizer](example/sanitizer) | Go | Content sanitization / safety filtering |
|
||||||
|
|
||||||
|
**Prebuilt example artifacts ship with every release**: besides the 5-platform `hmapdev`, an SDK
|
||||||
|
release contains the example plugins' `.hmap` files plus `SHA256SUMS`/`MANIFEST.txt`. The reason is
|
||||||
|
that plugin binaries are **protocol-bound** to the kernel (`ProtocolVersion` + the shared-memory
|
||||||
|
magic), so shipping the toolchain without matching artifacts invites installing an old artifact —
|
||||||
|
which fails the handshake and looks like "the plugin is broken" rather than "the versions don't
|
||||||
|
match".
|
||||||
|
|
||||||
|
## Remote Device SDK
|
||||||
|
|
||||||
|
A C language SDK for developing **remote device access adapters** with zero external dependencies, compatible with embedded platforms.
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ ha_remotedevice (C SDK) │
|
||||||
|
│ Protocol Engine │ WS Frames │ JSON │ State │
|
||||||
|
│ Machine │ Transport Abstraction │
|
||||||
|
└──────────┬──────────────────────────────────────┘
|
||||||
|
│ Same C code, shared by device & app
|
||||||
|
┌──────┴──────────────────┐
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────┐ ┌──────────────────────────┐
|
||||||
|
│ ESP32 Bare │ │ Linux App │
|
||||||
|
│ Pure C │ │ (Python ctypes / Go CGo /│
|
||||||
|
│ Simple Cmd │ │ Node addon / C# P/Invoke)│
|
||||||
|
└──────────────┘ └──────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Declarative API Design
|
||||||
|
|
||||||
|
The device declares **what it is** and **what it can do** in code. The SDK handles all protocol details automatically:
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
|
||||||
|
/* Declare capabilities */
|
||||||
|
const char *caps[] = {"camera", "status", NULL};
|
||||||
|
|
||||||
|
ha_config_t config = {
|
||||||
|
.transport = my_transport, // User implements 4 functions
|
||||||
|
.server = "192.168.1.100:9890",
|
||||||
|
.token = "my-token",
|
||||||
|
.device = {
|
||||||
|
.device_id = "esp32-cam-1",
|
||||||
|
.name = "Front Door Camera",
|
||||||
|
.kind = "camera",
|
||||||
|
.caps = caps,
|
||||||
|
},
|
||||||
|
.on_cmd = my_cmd_handler, // Called when receiving commands
|
||||||
|
.on_binary = my_data_handler, // Called on binary data (TTS audio, etc.)
|
||||||
|
.on_state = my_state_handler, // Connection state changes
|
||||||
|
};
|
||||||
|
|
||||||
|
ha_client_t *client = ha_client_new(&config);
|
||||||
|
ha_client_start(client);
|
||||||
|
while (1) {
|
||||||
|
ha_client_process(client); // Main loop processing
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Transport Layer Abstraction
|
||||||
|
|
||||||
|
Users only need to implement 4 functions to adapt to different platforms:
|
||||||
|
|
||||||
|
```c
|
||||||
|
ha_transport_t my_transport = {
|
||||||
|
.connect = my_tcp_connect, // Establish TCP connection
|
||||||
|
.send = my_tcp_send, // Send data
|
||||||
|
.recv = my_tcp_recv, // Receive data (blocking)
|
||||||
|
.close = my_tcp_close, // Close connection
|
||||||
|
.ctx = &my_platform_ctx,
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Protocol Support
|
||||||
|
|
||||||
|
| Feature | API |
|
||||||
|
|---------|-----|
|
||||||
|
| WS connection + handshake | Automatic via `ha_client_start` |
|
||||||
|
| Device registration (hello/bind) | Automatic on startup |
|
||||||
|
| Command receive (shell/homeagent) | `on_cmd` callback |
|
||||||
|
| Command result | `ha_client_send_result` |
|
||||||
|
| Binary chunked transfer (video) | `ha_client_send_data_chunked` |
|
||||||
|
| TTS audio receive | `on_binary` callback |
|
||||||
|
| Event reporting | `ha_client_send_event` |
|
||||||
|
| Status reporting | `ha_client_send_status` |
|
||||||
|
| Heartbeat keepalive | Automatic ping/pong |
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
Initialize a project via the `hmapdev` toolchain:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev init my-adapter --type remotedevice
|
||||||
|
```
|
||||||
|
|
||||||
|
Generates `main.c` + `CMakeLists.txt`, can be built directly or used as a third-party library:
|
||||||
|
|
||||||
|
```cmake
|
||||||
|
add_subdirectory(path/to/ha_remotedevice)
|
||||||
|
target_link_libraries(my_app ha_remotedevice)
|
||||||
|
target_include_directories(my_app PRIVATE ${HA_REMOTEDEVICE_INCLUDE_DIR})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Quick Start Guide
|
||||||
|
|
||||||
|
A complete step-by-step guide from zero to a device successfully connected to HomeAgent.
|
||||||
|
|
||||||
|
#### Step 1: Preparation
|
||||||
|
|
||||||
|
Create an access token on the HomeAgent platform:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create a device access token on the HomeAgent server
|
||||||
|
curl -X POST http://<homeagent-server>:8080/api/v1/device/token \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"device_id":"esp32-cam-1","name":"Front Door Camera","kind":"camera"}'
|
||||||
|
# Returns: {"token":"ha-dev-token-xxxxx"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Save the returned `token` — you'll need it in the device configuration.
|
||||||
|
|
||||||
|
#### Step 2: Implement the Transport Layer (4 functions)
|
||||||
|
|
||||||
|
Implement the 4 function pointers of `ha_transport_t` for your platform. Here are common scenarios:
|
||||||
|
|
||||||
|
**Scenario A: Embedded device with TCP/IP stack (e.g., ESP32 + lwIP)**
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
static int esp_connect(void *ctx, const char *host, uint16_t port) {
|
||||||
|
struct sockaddr_in addr;
|
||||||
|
int sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
if (sock < 0) return -1;
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(port);
|
||||||
|
inet_pton(AF_INET, host, &addr.sin_addr);
|
||||||
|
int ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
|
||||||
|
if (ret < 0) { closesocket(sock); return -1; }
|
||||||
|
*(int *)ctx = sock;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int esp_send(void *ctx, const uint8_t *data, int len) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
return send(sock, (const char *)data, len, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int esp_recv(void *ctx, uint8_t *buf, int len) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
return recv(sock, (char *)buf, len, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void esp_close(void *ctx) {
|
||||||
|
int sock = *(int *)ctx;
|
||||||
|
closesocket(sock);
|
||||||
|
}
|
||||||
|
|
||||||
|
int esp_ctx = -1;
|
||||||
|
ha_transport_t transport = {
|
||||||
|
.connect = esp_connect,
|
||||||
|
.send = esp_send,
|
||||||
|
.recv = esp_recv,
|
||||||
|
.close = esp_close,
|
||||||
|
.ctx = &esp_ctx,
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**Scenario B: Serial (UART) passthrough module**
|
||||||
|
|
||||||
|
```c
|
||||||
|
static int uart_connect(void *ctx, const char *host, uint16_t port) {
|
||||||
|
(void)host; (void)port;
|
||||||
|
return uart_init((uart_ctx_t *)ctx, 115200);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int uart_send(void *ctx, const uint8_t *data, int len) {
|
||||||
|
return uart_write((uart_ctx_t *)ctx, data, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int uart_recv(void *ctx, uint8_t *buf, int len) {
|
||||||
|
return uart_read((uart_ctx_t *)ctx, buf, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void uart_close(void *ctx) {
|
||||||
|
uart_deinit((uart_ctx_t *)ctx);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> Note: For UART passthrough, a TCP bridge program must run on the other end to forward serial data to the HomeAgent WebSocket port.
|
||||||
|
|
||||||
|
#### Step 3: Declare Device Capabilities and Command Handlers
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include "ha_remotedevice.h"
|
||||||
|
|
||||||
|
/* Declare device capabilities */
|
||||||
|
const char *caps[] = {"camera", "speaker", "status", NULL};
|
||||||
|
|
||||||
|
/* Handle camerasue command (take photo) */
|
||||||
|
static ha_status_t handle_camera(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata) {
|
||||||
|
(void)req_id; (void)userdata;
|
||||||
|
int duration = args[0] ? atoi(args) : 0;
|
||||||
|
|
||||||
|
// Capture image, fill the result
|
||||||
|
result->status = 0;
|
||||||
|
result->output = "data:image/jpeg;base64,/9j/4AAQ..."; // base64 image data
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Handle shell command */
|
||||||
|
static ha_status_t handle_shell(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata) {
|
||||||
|
(void)req_id; (void)userdata;
|
||||||
|
result->status = 0;
|
||||||
|
result->output = "command executed";
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Declarative command handler table */
|
||||||
|
ha_cmd_handler_def_t handlers[] = {
|
||||||
|
{.command = "shell", .handler = handle_shell},
|
||||||
|
{.command = "camerasue", .handler = handle_camera},
|
||||||
|
{.command = "screensee", .handler = handle_camera},
|
||||||
|
{.command = "speakeruse", .handler = handle_speaker},
|
||||||
|
{.command = NULL}, /* terminator */
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 4: Configure and Start the Client
|
||||||
|
|
||||||
|
```c
|
||||||
|
ha_config_t config = {
|
||||||
|
.transport = transport, // Transport layer implementation
|
||||||
|
.server = "192.168.1.100:9890", // HomeAgent server address
|
||||||
|
.token = "ha-dev-token-xxxxx", // Token from Step 1
|
||||||
|
.device = {
|
||||||
|
.device_id = "esp32-cam-1",
|
||||||
|
.name = "Front Door Camera",
|
||||||
|
.kind = "camera",
|
||||||
|
.caps = caps,
|
||||||
|
.info_json = "{\"chip\":\"ESP32-S3\",\"firmware\":\"v1.0\"}",
|
||||||
|
},
|
||||||
|
.handlers = handlers, // Command handler table
|
||||||
|
.on_binary = on_binary_data, // Receive TTS audio etc.
|
||||||
|
.on_state = on_state_change, // Connection state callback
|
||||||
|
.ping_interval = 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
ha_client_t *client = ha_client_new(&config);
|
||||||
|
ha_status_t ret = ha_client_start(client);
|
||||||
|
if (ret != HA_OK) {
|
||||||
|
printf("Device connection failed: %d\n", ret);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Main loop */
|
||||||
|
while (1) {
|
||||||
|
ha_client_process(client); // Process protocol frames, heartbeats, commands
|
||||||
|
|
||||||
|
/* Optional: device-initiated event reporting */
|
||||||
|
ha_client_send_event(client, "motion_detected",
|
||||||
|
"{\"zone\":\"front_door\",\"confidence\":0.95}");
|
||||||
|
|
||||||
|
/* Optional: report device status */
|
||||||
|
ha_client_send_status(client, "online");
|
||||||
|
|
||||||
|
vTaskDelay(100 / portTICK_PERIOD_MS); // RTOS-style delay
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 5: Verify the Connection
|
||||||
|
|
||||||
|
Check if the device is online on the HomeAgent server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List registered devices
|
||||||
|
curl http://<homeagent-server>:8080/api/v1/device/list
|
||||||
|
# Expected output includes: {"device_id":"esp32-cam-1","status":"online",...}
|
||||||
|
|
||||||
|
# Send a command to the device (test camerasue)
|
||||||
|
curl -X POST http://<homeagent-server>:8080/api/v1/device/esp32-cam-1/cmd \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"cmd":"camerasue","args":"3"}'
|
||||||
|
# Expected: {"status":"ok","result":"data:image/jpeg;base64,..."}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step 6: Debugging Tips
|
||||||
|
|
||||||
|
| Issue | Check |
|
||||||
|
|-------|-------|
|
||||||
|
| Connection failed | Verify `server` address and port are reachable; check `token` |
|
||||||
|
| WS handshake failed | Verify HomeAgent server WebSocket support is enabled |
|
||||||
|
| Command not responding | Confirm the command name is registered in `handlers` table; check `on_binary` |
|
||||||
|
| Reconnection issues | `max_reconnect` controls retry count; -1 = infinite |
|
||||||
|
| Low memory (embedded) | Define `HA_NO_ALLOC` to disable dynamic memory allocation |
|
||||||
|
|
||||||
|
### Location
|
||||||
|
|
||||||
|
- **SDK Source**: `remotedevice/`
|
||||||
|
- **hmapdev template**: `hmapdev init --type remotedevice`
|
||||||
|
|
||||||
## Building & Installing
|
## Building & Installing
|
||||||
|
|
||||||
### Build
|
### Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
plugindev build
|
hmapdev build
|
||||||
```
|
```
|
||||||
|
|
||||||
Outputs a `.hmap` package to the project directory.
|
Outputs a `.hmap` package to the `dist/` directory (default is the multi-platform bundle; use `hmapdev build --no-bundle` for a single-target build).
|
||||||
|
|
||||||
### Install
|
### Install
|
||||||
|
|
||||||
Via pluginmgr HTTP API:
|
Via the pluginmgr HTTP API (default port 9876, listening on 127.0.0.1 only, no auth):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -X POST http://<host>:<port>/api/plugins/install \
|
# Local path
|
||||||
-F "package=@my-plugin.hmap"
|
curl -X POST http://127.0.0.1:9876/plugins \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"path": "/path/to/my-plugin.hmap"}'
|
||||||
|
|
||||||
|
# Upload binary directly
|
||||||
|
curl -X POST http://127.0.0.1:9876/plugins \
|
||||||
|
--data-binary @dist/my-plugin.hmap
|
||||||
```
|
```
|
||||||
|
|
||||||
Or manually place the `.hmap` in the plugin directory and restart the platform.
|
Or upload via the WebUI plugin management page, or manually place the `.hmap` in the plugin directory and restart the platform.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
The SDK is released under **AGPL-3.0-only** — see [LICENSE](LICENSE).
|
||||||
|
|
||||||
|
**This is a substantive constraint for plugin developers**: the SDK is **statically linked** into
|
||||||
|
your plugin (its source ends up in the plugin binary), so the plugin is a derivative work of
|
||||||
|
this SDK and **must be released under the same license**. Because AGPL §13 covers network
|
||||||
|
interaction, a plugin that serves users over HTTP/WebSocket must also offer them the source.
|
||||||
|
If you need a closed-source plugin, the only compliant route is a separate exception/commercial
|
||||||
|
license from this project — none is offered today.
|
||||||
|
|
||||||
|
Third-party components (Go dependencies: go-sqlite3, gojieba, bubbletea, … — MIT / BSD-3 /
|
||||||
|
Apache-2.0) keep their own licenses. The platform-side model and inference runtime
|
||||||
|
(Chinese-CLIP Apache-2.0, ONNX Runtime MIT) are not part of this SDK; their full license texts
|
||||||
|
ship with the release packages under `/usr/share/doc/homeagent/licenses/`.
|
||||||
|
|||||||
@ -2,6 +2,6 @@ module a2a
|
|||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0-20260708004841-e9bdcf9304b0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
2
example/a2a/go.sum
Normal file
2
example/a2a/go.sum
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
gitcode.com/JianFeeeee/homeagent-sdk v0.7.1 h1:2XEtUgV200uOqbGGEiKT5QyBmZ5aIfNiwm/Ozrm9AOg=
|
||||||
|
gitcode.com/JianFeeeee/homeagent-sdk v0.7.1/go.mod h1:G48Rgpw9ReTkCf0qBHf50jb5CSeNR2c4OWcgcEm0plo=
|
||||||
@ -3,7 +3,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
@ -2,10 +2,18 @@
|
|||||||
"name": "a2a",
|
"name": "a2a",
|
||||||
"name_zh": "A2A 代理通信",
|
"name_zh": "A2A 代理通信",
|
||||||
"name_en": "A2A Agent Communication",
|
"name_en": "A2A Agent Communication",
|
||||||
"version": "1.0.0",
|
"version": "1.3.0",
|
||||||
"description": "Agent-to-Agent 协议通信插件,支持双向 A2A 通信:可查询其他 Agent 并回复其请求。提供 HTTP 服务端暴露本 Agent 能力。",
|
"description": "Agent-to-Agent 协议通信插件,支持双向 A2A 通信:可查询其他 Agent 并回复其请求。提供 HTTP 服务端暴露本 Agent 能力。",
|
||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["a2a", "agent", "interop"],
|
"tags": [
|
||||||
"targets": "linux/amd64"
|
"a2a",
|
||||||
}
|
"agent",
|
||||||
|
"interop"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
@ -9,26 +9,61 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
name string
|
name string
|
||||||
sdk *sdk.PluginSDK
|
sdk *sdk.PluginSDK
|
||||||
server *http.Server
|
srvMu sync.Mutex
|
||||||
|
server *http.Server
|
||||||
|
serverAddr string
|
||||||
|
|
||||||
|
// 会话表:session_id → 上下文前缀。A2A 无状态协议下由插件侧维护
|
||||||
|
// 多轮上下文:同 session 的后续请求会把之前的对话拼进注入文本。
|
||||||
|
sessMu sync.Mutex
|
||||||
|
sessions map[string]*a2aSession
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a2aSession 记录一个会话的轮次历史,用于延续上下文。
|
||||||
|
type a2aSession struct {
|
||||||
|
ID string
|
||||||
|
History []string // 轮次文本 [user1, agent1, user2, agent2, ...]
|
||||||
|
LastUsed time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxSessionTurns 单会话保留的最大轮次对数(防上下文无限膨胀)。
|
||||||
|
const maxSessionTurns = 10
|
||||||
|
|
||||||
|
// sessionGCPeriod 会话过期清理周期;超过 2 小时未用的会话回收。
|
||||||
|
const sessionGCPeriod = 30 * time.Minute
|
||||||
|
|
||||||
func (p *Plugin) Name() string { return p.name }
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
s.SetAutoRestart(true)
|
s.SetAutoRestart(true)
|
||||||
p.sdk = s
|
p.sdk = s
|
||||||
|
p.sessions = make(map[string]*a2aSession)
|
||||||
tp := p.name + "_"
|
tp := p.name + "_"
|
||||||
|
|
||||||
|
// 注册自身为输出通道:agent 回复 emit 到本通道时有落点,
|
||||||
|
// 且 output_list_channels 可见(agent 能主动向 a2a 会话推送消息)。
|
||||||
|
if err := s.RegisterOutputChannel(p.name, 1, "A2A Agent 互联通道(外部 agent 查询的回复由此返回)", sdk.ChannelDef{}, func(args map[string]interface{}) (interface{}, error) {
|
||||||
|
payload, _ := args["payload"].(string)
|
||||||
|
log.Printf("[%s] channel output: %s", p.name, truncateRunes(payload, 120))
|
||||||
|
return map[string]interface{}{"status": "ok"}, nil
|
||||||
|
}); err != nil {
|
||||||
|
log.Printf("[%s] register output channel: %v", p.name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 会话 GC:后台周期回收长期不用的会话
|
||||||
|
go p.sessionGCLoop()
|
||||||
|
|
||||||
s.Settings().RegisterDef(sdk.ConfigDef{
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
Key: "plugin." + p.name + ".listen", Default: "127.0.0.1:12000",
|
Key: "listen", Default: "127.0.0.1:12000",
|
||||||
Type: "string", DisplayName: "监听地址",
|
Type: "string", DisplayName: "监听地址",
|
||||||
Description: "A2A 服务端监听地址,设为空可禁用 HTTP 服务",
|
Description: "A2A 服务端监听地址,设为空可禁用 HTTP 服务",
|
||||||
Category: p.name,
|
Category: p.name,
|
||||||
@ -42,10 +77,18 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
"properties": map[string]interface{}{
|
"properties": map[string]interface{}{
|
||||||
"agent_url": map[string]interface{}{"type": "string", "description": "目标 Agent 的 A2A 端点 URL"},
|
"agent_url": map[string]interface{}{"type": "string", "description": "目标 Agent 的 A2A 端点 URL"},
|
||||||
"query": map[string]interface{}{"type": "string", "description": "发送给目标 Agent 的文本查询"},
|
"query": map[string]interface{}{"type": "string", "description": "发送给目标 Agent 的文本查询"},
|
||||||
|
"session_id": map[string]interface{}{"type": "string", "description": "可选。上次调用返回的 session_id,传入可延续与该 agent 的多轮对话上下文"},
|
||||||
"timeout": map[string]interface{}{"type": "integer", "description": "超时时间(秒),默认 60"},
|
"timeout": map[string]interface{}{"type": "integer", "description": "超时时间(秒),默认 60"},
|
||||||
},
|
},
|
||||||
"required": []string{"agent_url", "query"},
|
"required": []string{"agent_url", "query"},
|
||||||
},
|
},
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct{ Content string }
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Content != "" {
|
||||||
|
return r.Content
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
}, p.handleA2AQuery)
|
}, p.handleA2AQuery)
|
||||||
|
|
||||||
s.RegisterTool(tp+"a2a_discover", sdk.ToolDef{
|
s.RegisterTool(tp+"a2a_discover", sdk.ToolDef{
|
||||||
@ -59,10 +102,39 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
},
|
},
|
||||||
}, p.handleA2ADiscover)
|
}, p.handleA2ADiscover)
|
||||||
|
|
||||||
|
// Management tools
|
||||||
|
s.RegisterTool(tp+"a2a_configure", sdk.ToolDef{
|
||||||
|
Name: tp + "a2a_configure", Description: "修改 A2A 插件配置并自动重启服务。支持动态更改监听地址等参数。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"listen": map[string]interface{}{"type": "string", "description": "监听地址(如 0.0.0.0:12000,设为空字符串禁用 HTTP 服务)"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, p.handleConfigure)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"a2a_restart", sdk.ToolDef{
|
||||||
|
Name: tp + "a2a_restart", Description: "重启 A2A HTTP 服务端。当连接异常或配置变更后需要重新加载时使用。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleRestart)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"a2a_status", sdk.ToolDef{
|
||||||
|
Name: tp + "a2a_status", Description: "查看 A2A 插件的运行状态,包括监听地址和当前配置。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleStatus)
|
||||||
|
|
||||||
// Inbound HTTP server
|
// Inbound HTTP server
|
||||||
if addr, _ := s.Settings().Get("plugin." + p.name + ".listen"); addr != nil {
|
if addr, _ := s.Settings().Get("listen"); addr != nil {
|
||||||
if addrStr, ok := addr.(string); ok && addrStr != "" {
|
if addrStr, ok := addr.(string); ok && addrStr != "" {
|
||||||
p.startServer(addrStr)
|
if err := p.startServer(addrStr); err != nil {
|
||||||
|
log.Printf("[%s] start A2A server: %v", p.name, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,15 +143,83 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Stop() error {
|
func (p *Plugin) Stop() error {
|
||||||
|
p.stopServer()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sessionGCLoop 周期清理超时会话。
|
||||||
|
func (p *Plugin) sessionGCLoop() {
|
||||||
|
ticker := time.NewTicker(sessionGCPeriod)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for range ticker.C {
|
||||||
|
p.sessMu.Lock()
|
||||||
|
for id, sess := range p.sessions {
|
||||||
|
if time.Since(sess.LastUsed) > 2*time.Hour {
|
||||||
|
delete(p.sessions, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.sessMu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncateRunes(s string, n int) string {
|
||||||
|
r := []rune(s)
|
||||||
|
if len(r) <= n {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string(r[:n]) + "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
// sessionMessages 返回指定会话的近 limit 条消息(时间正序),
|
||||||
|
// 会话不存在返回 nil。消息格式 [{role, text, ts}]。
|
||||||
|
func (p *Plugin) sessionMessages(sessionID string, limit int) []map[string]interface{} {
|
||||||
|
p.sessMu.Lock()
|
||||||
|
sess := p.sessions[sessionID]
|
||||||
|
var hist []string
|
||||||
|
var lastUsed time.Time
|
||||||
|
if sess != nil {
|
||||||
|
hist = append([]string{}, sess.History...)
|
||||||
|
lastUsed = sess.LastUsed
|
||||||
|
}
|
||||||
|
p.sessMu.Unlock()
|
||||||
|
if sess == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_ = lastUsed
|
||||||
|
// History 交替 [user, agent, user, agent...],取末尾 limit 条,保持时间正序
|
||||||
|
start := 0
|
||||||
|
if len(hist) > limit {
|
||||||
|
start = len(hist) - limit
|
||||||
|
}
|
||||||
|
msgs := make([]map[string]interface{}, 0, len(hist)-start)
|
||||||
|
for i := start; i < len(hist); i++ {
|
||||||
|
role, text := "user", hist[i]
|
||||||
|
if after, ok := strings.CutPrefix(text, "用户: "); ok {
|
||||||
|
role, text = "user", after
|
||||||
|
} else if after, ok := strings.CutPrefix(text, "助手: "); ok {
|
||||||
|
role, text = "agent", after
|
||||||
|
}
|
||||||
|
msgs = append(msgs, map[string]interface{}{
|
||||||
|
"role": role,
|
||||||
|
"text": text,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return msgs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) stopServer() {
|
||||||
|
p.srvMu.Lock()
|
||||||
|
defer p.srvMu.Unlock()
|
||||||
if p.server != nil {
|
if p.server != nil {
|
||||||
p.server.Close()
|
p.server.Close()
|
||||||
|
p.server = nil
|
||||||
|
p.serverAddr = ""
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Inbound HTTP Server ----
|
// ---- Inbound HTTP Server ----
|
||||||
|
|
||||||
func (p *Plugin) startServer(addr string) {
|
func (p *Plugin) startServer(addr string) error {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/agent-card", p.handleAgentCard)
|
mux.HandleFunc("/agent-card", p.handleAgentCard)
|
||||||
mux.HandleFunc("/task", p.handleIncomingTask)
|
mux.HandleFunc("/task", p.handleIncomingTask)
|
||||||
@ -87,17 +227,32 @@ func (p *Plugin) startServer(addr string) {
|
|||||||
|
|
||||||
listener, err := net.Listen("tcp", addr)
|
listener, err := net.Listen("tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[%s] listen %s: %v", p.name, addr, err)
|
return fmt.Errorf("listen %s: %v", addr, err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
p.server = &http.Server{Handler: mux}
|
srv := &http.Server{
|
||||||
|
Handler: mux,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 120 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
addrStr := listener.Addr().String()
|
||||||
|
|
||||||
|
p.srvMu.Lock()
|
||||||
|
if p.server != nil {
|
||||||
|
p.server.Close()
|
||||||
|
}
|
||||||
|
p.server = srv
|
||||||
|
p.serverAddr = addrStr
|
||||||
|
p.srvMu.Unlock()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Printf("[%s] A2A server on %s", p.name, listener.Addr())
|
log.Printf("[%s] A2A server on %s", p.name, addrStr)
|
||||||
if err := p.server.Serve(listener); err != nil && err != http.ErrServerClosed {
|
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
log.Printf("[%s] serve: %v", p.name, err)
|
log.Printf("[%s] serve: %v", p.name, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) handleAgentCard(w http.ResponseWriter, r *http.Request) {
|
func (p *Plugin) handleAgentCard(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -129,7 +284,9 @@ func (p *Plugin) handleIncomingA2A(w http.ResponseWriter, r *http.Request) {
|
|||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Method string `json:"method"`
|
Method string `json:"method"`
|
||||||
Params struct {
|
Params struct {
|
||||||
Query string `json:"query,omitempty"`
|
Query string `json:"query,omitempty"`
|
||||||
|
SessionID string `json:"session_id,omitempty"`
|
||||||
|
Limit int `json:"limit,omitempty"`
|
||||||
Message *struct {
|
Message *struct {
|
||||||
Role string `json:"role"`
|
Role string `json:"role"`
|
||||||
Parts []struct {
|
Parts []struct {
|
||||||
@ -153,29 +310,96 @@ func (p *Plugin) handleIncomingA2A(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
queryText = strings.TrimSpace(queryText)
|
queryText = strings.TrimSpace(queryText)
|
||||||
}
|
}
|
||||||
|
if queryText == "" {
|
||||||
// Inject into agent pipeline via interrupt (preempt current processing) or direct input
|
http.Error(w, "query/message.text required", http.StatusBadRequest)
|
||||||
if queryText != "" {
|
return
|
||||||
p.sdk.InjectInterruptText("a2a", "webui", fmt.Sprintf("[来自A2A Agent的查询]\n%s", queryText))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Respond with task accepted
|
// 会话:调用方可指定 session_id 延续多轮上下文;不指定则新建。
|
||||||
|
sessionID := strings.TrimSpace(req.Params.SessionID)
|
||||||
|
injectText := queryText
|
||||||
|
p.sessMu.Lock()
|
||||||
|
if sessionID != "" {
|
||||||
|
sess := p.sessions[sessionID]
|
||||||
|
if sess == nil {
|
||||||
|
sess = &a2aSession{ID: sessionID, LastUsed: time.Now()}
|
||||||
|
p.sessions[sessionID] = sess
|
||||||
|
}
|
||||||
|
sess.LastUsed = time.Now()
|
||||||
|
// 有历史则把上下文拼在前面(截尾防爆量)
|
||||||
|
if len(sess.History) > 0 {
|
||||||
|
ctxText := strings.Join(sess.History, "\n")
|
||||||
|
injectText = "[对话上下文]\n" + ctxText + "\n[本轮输入]\n" + queryText
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sessionID = fmt.Sprintf("a2a_%d", time.Now().UnixNano())
|
||||||
|
p.sessions[sessionID] = &a2aSession{ID: sessionID, LastUsed: time.Now()}
|
||||||
|
}
|
||||||
|
p.sessMu.Unlock()
|
||||||
|
|
||||||
|
// 同步注入:阻塞等待 agent 处理完成拿回复(不再抢占打断、
|
||||||
|
// 也不再回 202 让请求方永远等不到结果)。HTTP 超时由调用方控制。
|
||||||
|
reply := p.sdk.InjectInputSync(p.name, p.name,
|
||||||
|
fmt.Sprintf("[来自A2A Agent的查询 session=%s]\n%s\n[注意] 请直接以文本回复本查询,不要调用 output_send__%s——你的最终文本回复会被系统自动返回给请求方。", sessionID, injectText, p.name))
|
||||||
|
|
||||||
|
// 回复写回会话历史(下一轮作为上下文)
|
||||||
|
p.sessMu.Lock()
|
||||||
|
if sess := p.sessions[sessionID]; sess != nil {
|
||||||
|
sess.History = append(sess.History, "用户: "+queryText, "助手: "+reply)
|
||||||
|
if len(sess.History) > maxSessionTurns*2 {
|
||||||
|
sess.History = sess.History[len(sess.History)-maxSessionTurns*2 :]
|
||||||
|
}
|
||||||
|
sess.LastUsed = time.Now()
|
||||||
|
}
|
||||||
|
p.sessMu.Unlock()
|
||||||
|
|
||||||
resp := map[string]interface{}{
|
resp := map[string]interface{}{
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"id": req.ID,
|
"id": req.ID,
|
||||||
"result": map[string]interface{}{
|
"result": map[string]interface{}{
|
||||||
"id": fmt.Sprintf("task_%d", time.Now().UnixNano()),
|
"id": fmt.Sprintf("task_%d", time.Now().UnixNano()),
|
||||||
"status": "submitted",
|
"status": "completed",
|
||||||
|
"session_id": sessionID,
|
||||||
|
"message": map[string]interface{}{
|
||||||
|
"role": "agent",
|
||||||
|
"parts": []map[string]string{{"type": "text", "text": reply}},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(resp)
|
json.NewEncoder(w).Encode(resp)
|
||||||
|
|
||||||
case "tasks.get":
|
case "tasks.get", "session.get":
|
||||||
|
// 按 session_id 返回会话内近 N 条消息(默认 10 条)。
|
||||||
|
sessionID := strings.TrimSpace(req.Params.SessionID)
|
||||||
|
if sessionID == "" {
|
||||||
|
sessionID = strings.TrimSpace(req.Params.Query)
|
||||||
|
}
|
||||||
|
limit := 10
|
||||||
|
if req.Params.Limit > 0 && req.Params.Limit <= 100 {
|
||||||
|
limit = req.Params.Limit
|
||||||
|
}
|
||||||
|
msgs := p.sessionMessages(sessionID, limit)
|
||||||
|
if msgs == nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{
|
||||||
|
"session_id": sessionID,
|
||||||
|
"status": "not_found",
|
||||||
|
"messages": []interface{}{},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
"jsonrpc": "2.0", "id": req.ID,
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
"result": map[string]interface{}{"id": req.Params.Query, "status": "unknown"},
|
"result": map[string]interface{}{
|
||||||
|
"session_id": sessionID,
|
||||||
|
"status": "completed",
|
||||||
|
"messages": msgs,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@ -219,9 +443,10 @@ type A2ARequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type A2AParams struct {
|
type A2AParams struct {
|
||||||
Query string `json:"query,omitempty"`
|
Query string `json:"query,omitempty"`
|
||||||
Message *A2AMessage `json:"message,omitempty"`
|
SessionID string `json:"session_id,omitempty"`
|
||||||
TaskID string `json:"id,omitempty"`
|
Message *A2AMessage `json:"message,omitempty"`
|
||||||
|
TaskID string `json:"id,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type A2AResponse struct {
|
type A2AResponse struct {
|
||||||
@ -234,6 +459,7 @@ type A2AResponse struct {
|
|||||||
type A2AResult struct {
|
type A2AResult struct {
|
||||||
TaskID string `json:"id,omitempty"`
|
TaskID string `json:"id,omitempty"`
|
||||||
Status string `json:"status,omitempty"`
|
Status string `json:"status,omitempty"`
|
||||||
|
SessionID string `json:"session_id,omitempty"`
|
||||||
Message *A2AMessage `json:"message,omitempty"`
|
Message *A2AMessage `json:"message,omitempty"`
|
||||||
AgentCard *A2AAgentCard `json:"agent_card,omitempty"`
|
AgentCard *A2AAgentCard `json:"agent_card,omitempty"`
|
||||||
}
|
}
|
||||||
@ -299,6 +525,7 @@ func (p *Plugin) handleA2ADiscover(args map[string]interface{}) (interface{}, er
|
|||||||
func (p *Plugin) handleA2AQuery(args map[string]interface{}) (interface{}, error) {
|
func (p *Plugin) handleA2AQuery(args map[string]interface{}) (interface{}, error) {
|
||||||
agentURL, _ := args["agent_url"].(string)
|
agentURL, _ := args["agent_url"].(string)
|
||||||
query, _ := args["query"].(string)
|
query, _ := args["query"].(string)
|
||||||
|
sessionID, _ := args["session_id"].(string) // 可选:延续对方会话
|
||||||
timeoutSec := 60
|
timeoutSec := 60
|
||||||
if v, ok := args["timeout"].(float64); ok && v > 0 {
|
if v, ok := args["timeout"].(float64); ok && v > 0 {
|
||||||
timeoutSec = int(v)
|
timeoutSec = int(v)
|
||||||
@ -320,7 +547,8 @@ func (p *Plugin) handleA2AQuery(args map[string]interface{}) (interface{}, error
|
|||||||
ID: fmt.Sprintf("a2a_%d", time.Now().UnixNano()),
|
ID: fmt.Sprintf("a2a_%d", time.Now().UnixNano()),
|
||||||
Method: "tasks.send",
|
Method: "tasks.send",
|
||||||
Params: A2AParams{
|
Params: A2AParams{
|
||||||
Message: &A2AMessage{Role: "user", Parts: []A2APart{{Text: query, Type: "text"}}},
|
SessionID: sessionID,
|
||||||
|
Message: &A2AMessage{Role: "user", Parts: []A2APart{{Text: query, Type: "text"}}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -359,12 +587,76 @@ func (p *Plugin) handleA2AQuery(args map[string]interface{}) (interface{}, error
|
|||||||
replyText = strings.TrimSpace(replyText)
|
replyText = strings.TrimSpace(replyText)
|
||||||
}
|
}
|
||||||
|
|
||||||
return map[string]interface{}{
|
result := map[string]interface{}{
|
||||||
"task_id": a2aResp.Result.TaskID, "status": a2aResp.Result.Status,
|
"task_id": a2aResp.Result.TaskID, "status": a2aResp.Result.Status,
|
||||||
"response": replyText,
|
"response": replyText,
|
||||||
}, nil
|
}
|
||||||
|
if a2aResp.Result.SessionID != "" || sessionID != "" {
|
||||||
|
result["session_id"] = a2aResp.Result.SessionID
|
||||||
|
if result["session_id"] == "" {
|
||||||
|
result["session_id"] = sessionID
|
||||||
|
}
|
||||||
|
result["note"] = "延续会话:下次调用传此 session_id 可保持上下文"
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
// ---- Management Handlers ----
|
||||||
|
|
||||||
|
func (p *Plugin) handleConfigure(args map[string]interface{}) (interface{}, error) {
|
||||||
|
listen, _ := args["listen"].(string)
|
||||||
|
listen = strings.TrimSpace(listen)
|
||||||
|
|
||||||
|
if err := p.sdk.Settings().Set("listen", listen); err != nil {
|
||||||
|
return fmt.Sprintf("保存配置失败: %v", err), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if listen == "" || listen == "off" || listen == "disabled" {
|
||||||
|
p.stopServer()
|
||||||
|
return "A2A HTTP 服务已禁用(listen 设为空)", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := p.startServer(listen); err != nil {
|
||||||
|
return fmt.Sprintf("A2A 配置已保存,但服务启动失败: %v", err), nil
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("A2A 配置已更新。监听地址: %s (已启动)", listen), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleRestart(args map[string]interface{}) (interface{}, error) {
|
||||||
|
p.stopServer()
|
||||||
|
|
||||||
|
addr, _ := p.sdk.Settings().Get("listen")
|
||||||
|
addrStr, _ := addr.(string)
|
||||||
|
if addrStr == "" || addrStr == "off" || addrStr == "disabled" {
|
||||||
|
return "A2A 服务未配置监听地址(listen 为空),无法启动", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := p.startServer(addrStr); err != nil {
|
||||||
|
return fmt.Sprintf("A2A 服务启动失败: %v", err), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.srvMu.Lock()
|
||||||
|
listening := p.serverAddr
|
||||||
|
p.srvMu.Unlock()
|
||||||
|
return fmt.Sprintf("A2A 服务已重启,监听: %s", listening), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleStatus(args map[string]interface{}) (interface{}, error) {
|
||||||
|
addr, _ := p.sdk.Settings().Get("listen")
|
||||||
|
addrStr, _ := addr.(string)
|
||||||
|
|
||||||
|
p.srvMu.Lock()
|
||||||
|
serverRunning := p.server != nil
|
||||||
|
listening := p.serverAddr
|
||||||
|
p.srvMu.Unlock()
|
||||||
|
if !serverRunning {
|
||||||
|
listening = "未运行"
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("配置监听地址: %s\n当前监听: %s\n服务状态: %s",
|
||||||
|
addrStr, listening, map[bool]string{true: "运行中", false: "已停止"}[serverRunning]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
7
example/acp/go.mod
Normal file
7
example/acp/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module acp
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/acp/main.go
Normal file
11
example/acp/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
19
example/acp/plg.json
Normal file
19
example/acp/plg.json
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "acp",
|
||||||
|
"name_zh": "ACP 代理通信",
|
||||||
|
"name_en": "ACP Agent Client Protocol",
|
||||||
|
"version": "1.2.0",
|
||||||
|
"description": "Agent Client Protocol 通信插件:充当 ACP 服务端接受其他 Agent 的任务请求,同时提供客户端工具向远程 ACP Agent(如 opencode)发起会话并读取回复",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": [
|
||||||
|
"acp",
|
||||||
|
"agent",
|
||||||
|
"interop"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
642
example/acp/plugin.go
Normal file
642
example/acp/plugin.go
Normal file
@ -0,0 +1,642 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
// acpPlugin 实现 Agent Client Protocol (ACP) 0.0.x 子集:
|
||||||
|
// - 服务端:POST /api/session (JSON-RPC:session/new / session/update),
|
||||||
|
// 请求注入本 Agent,另提供 GET /api/session?id=xxx SSE 事件流。
|
||||||
|
// - 客户端:向远程 ACP 服务端发 session/new 并读取 SSE session/reply。
|
||||||
|
type Plugin struct {
|
||||||
|
name string
|
||||||
|
sdk *sdk.PluginSDK
|
||||||
|
srvMu sync.Mutex
|
||||||
|
server *http.Server
|
||||||
|
serverID string
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
sessions map[string]*sessionState
|
||||||
|
}
|
||||||
|
|
||||||
|
type sessionState struct {
|
||||||
|
ID string
|
||||||
|
Replying []map[string]interface{}
|
||||||
|
History []string // 轮次历史 [user, agent, user, agent...],延续上下文用
|
||||||
|
LastUsed time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxSessionTurns 单会话保留的最大轮次对数。
|
||||||
|
const maxSessionTurns = 10
|
||||||
|
|
||||||
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
|
s.SetAutoRestart(true)
|
||||||
|
p.sdk = s
|
||||||
|
p.sessions = make(map[string]*sessionState)
|
||||||
|
tp := p.name + "_"
|
||||||
|
|
||||||
|
// 注册自身为输出通道:agent 回复 emit 到本通道时有落点。
|
||||||
|
// (回复主要走同步注入返回,此通道用于 agent 主动 output_send__acp)
|
||||||
|
s.RegisterOutputChannel(p.name, 1, "ACP Agent 互联通道(外部 agent 会话的回复由此返回)", sdk.ChannelDef{}, func(args map[string]interface{}) (interface{}, error) {
|
||||||
|
payload, _ := args["payload"].(string)
|
||||||
|
log.Printf("[%s] channel output: %s", p.name, truncateStr(payload, 120))
|
||||||
|
return map[string]interface{}{"status": "ok"}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "listen", Default: "127.0.0.1:12001",
|
||||||
|
Type: "string", DisplayName: "监听地址",
|
||||||
|
Description: "ACP 服务端监听地址,设为空可禁用 HTTP 服务",
|
||||||
|
Category: p.name,
|
||||||
|
})
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"acp_query", sdk.ToolDef{
|
||||||
|
Name: tp + "acp_query", Description: "向远程 ACP Agent(如 opencode http://127.0.0.1:13000、pi bridge http://127.0.0.1:12011 或回环到自身 12001)发起一个会话请求并等待回复,返回其最终回答文本,兼容 SSE 型与同步 JSON 型 ACP 服务端",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"server_url": map[string]interface{}{"type": "string", "description": "目标 ACP 服务端地址(如 http://127.0.0.1:13000)"},
|
||||||
|
"prompt": map[string]interface{}{"type": "string", "description": "发送给目标 Agent 的任务描述"},
|
||||||
|
"session_id": map[string]interface{}{"type": "string", "description": "可选。上次调用返回的 session_id,传入可延续与该 agent 的多轮对话上下文"},
|
||||||
|
"timeout": map[string]interface{}{"type": "integer", "description": "等待回复超时(秒),默认 120"},
|
||||||
|
},
|
||||||
|
"required": []string{"server_url", "prompt"},
|
||||||
|
},
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct {
|
||||||
|
Reply string `json:"reply"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Reply != "" {
|
||||||
|
return r.Reply
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
|
}, p.handleAcpQuery)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"acp_configure", sdk.ToolDef{
|
||||||
|
Name: tp + "acp_configure", Description: "修改 ACP 插件的监听配置并生效(重启 HTTP 服务)",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"listen": map[string]interface{}{"type": "string", "description": "监听地址(如 0.0.0.0:12001,设为空禁用)"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, p.handleConfigure)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"acp_status", sdk.ToolDef{
|
||||||
|
Name: tp + "acp_status", Description: "查看 ACP 插件运行状态与当前活跃会话数",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleStatus)
|
||||||
|
|
||||||
|
addr, _ := s.Settings().Get("listen")
|
||||||
|
if addrStr, ok := addr.(string); ok && addrStr != "" {
|
||||||
|
if err := p.startServer(addrStr); err != nil {
|
||||||
|
log.Printf("[%s] start ACP server: %v", p.name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[%s] started", p.name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Stop() error {
|
||||||
|
p.stopServer()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) stopServer() {
|
||||||
|
p.srvMu.Lock()
|
||||||
|
defer p.srvMu.Unlock()
|
||||||
|
if p.server != nil {
|
||||||
|
p.server.Close()
|
||||||
|
p.server = nil
|
||||||
|
p.serverID = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Inbound HTTP Server ----
|
||||||
|
|
||||||
|
func (p *Plugin) startServer(addr string) error {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/api/session", p.handleSession)
|
||||||
|
|
||||||
|
listener, err := net.Listen("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listen %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srv := &http.Server{Handler: mux}
|
||||||
|
addrStr := listener.Addr().String()
|
||||||
|
|
||||||
|
p.srvMu.Lock()
|
||||||
|
if p.server != nil {
|
||||||
|
p.server.Close()
|
||||||
|
}
|
||||||
|
p.server = srv
|
||||||
|
p.serverID = addrStr
|
||||||
|
p.srvMu.Unlock()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
log.Printf("[%s] ACP server on %s", p.name, addrStr)
|
||||||
|
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Printf("[%s] serve: %v", p.name, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleSession(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case "POST":
|
||||||
|
p.handleSessionPost(w, r)
|
||||||
|
case "GET":
|
||||||
|
p.handleSessionSSE(w, r)
|
||||||
|
default:
|
||||||
|
http.Error(w, "", http.StatusMethodNotAllowed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleSessionPost 处理 JSON-RPC:session/new 与 session/update
|
||||||
|
func (p *Plugin) handleSessionPost(w http.ResponseWriter, r *http.Request) {
|
||||||
|
body, _ := io.ReadAll(r.Body)
|
||||||
|
var req struct {
|
||||||
|
JSONRPC string `json:"jsonrpc"`
|
||||||
|
ID interface{} `json:"id"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
Params struct {
|
||||||
|
Request *struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
} `json:"request,omitempty"`
|
||||||
|
SessionID string `json:"session_id,omitempty"`
|
||||||
|
Limit int `json:"limit,omitempty"`
|
||||||
|
Final bool `json:"final,omitempty"`
|
||||||
|
} `json:"params,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &req); err != nil {
|
||||||
|
http.Error(w, "invalid json-rpc", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch req.Method {
|
||||||
|
case "session/new":
|
||||||
|
text := ""
|
||||||
|
if req.Params.Request != nil {
|
||||||
|
text = strings.TrimSpace(req.Params.Request.Text)
|
||||||
|
}
|
||||||
|
if text == "" {
|
||||||
|
http.Error(w, "request.text required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 会话:调用方可指定 session_id 延续多轮;不指定则新建。
|
||||||
|
sid := strings.TrimSpace(req.Params.SessionID)
|
||||||
|
p.mu.Lock()
|
||||||
|
if sid != "" {
|
||||||
|
if _, exists := p.sessions[sid]; !exists {
|
||||||
|
p.sessions[sid] = &sessionState{ID: sid, LastUsed: time.Now()}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sid = fmt.Sprintf("session_%d", time.Now().UnixNano())
|
||||||
|
p.sessions[sid] = &sessionState{ID: sid, LastUsed: time.Now()}
|
||||||
|
}
|
||||||
|
st := p.sessions[sid]
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
// 延续上下文
|
||||||
|
injectText := text
|
||||||
|
p.mu.Lock()
|
||||||
|
if len(st.History) > 0 {
|
||||||
|
ctxText := strings.Join(st.History, "\n")
|
||||||
|
injectText = "[对话上下文]\n" + ctxText + "\n[本轮输入]\n" + text
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
// 同步注入等待回复:不抢占打断,完整闭环返回文本。
|
||||||
|
reply := ""
|
||||||
|
if p.sdk != nil {
|
||||||
|
reply = p.sdk.InjectInputSync(p.name, p.name,
|
||||||
|
fmt.Sprintf("[来自ACP Agent的请求 session %s]\n%s\n[注意] 请直接以文本回复本请求,不要调用 output_send__%s——你的最终文本回复会被系统自动返回给请求方。", sid, injectText, p.name))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写回历史 + 填充 Replying 供 SSE 消费
|
||||||
|
p.mu.Lock()
|
||||||
|
st.History = append(st.History, "用户: "+text, "助手: "+reply)
|
||||||
|
if len(st.History) > maxSessionTurns*2 {
|
||||||
|
st.History = st.History[len(st.History)-maxSessionTurns*2:]
|
||||||
|
}
|
||||||
|
st.LastUsed = time.Now()
|
||||||
|
if reply != "" {
|
||||||
|
st.Replying = append(st.Replying, map[string]interface{}{
|
||||||
|
"type": "reply", "text": reply,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{
|
||||||
|
"session": map[string]interface{}{"id": sid},
|
||||||
|
"reply": reply,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
case "session/get":
|
||||||
|
// 按 session_id 返回会话内近 N 条消息(默认 10 条,时间正序)
|
||||||
|
sid := req.Params.SessionID
|
||||||
|
p.mu.RLock()
|
||||||
|
st := p.sessions[sid]
|
||||||
|
var hist []string
|
||||||
|
if st != nil {
|
||||||
|
hist = append([]string{}, st.History...)
|
||||||
|
}
|
||||||
|
p.mu.RUnlock()
|
||||||
|
if st == nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{
|
||||||
|
"session_id": sid,
|
||||||
|
"status": "not_found",
|
||||||
|
"messages": []interface{}{},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limit := 10
|
||||||
|
if req.Params.Limit > 0 && req.Params.Limit <= 100 {
|
||||||
|
limit = req.Params.Limit
|
||||||
|
}
|
||||||
|
start := 0
|
||||||
|
if len(hist) > limit {
|
||||||
|
start = len(hist) - limit
|
||||||
|
}
|
||||||
|
msgs := make([]map[string]interface{}, 0, len(hist)-start)
|
||||||
|
for i := start; i < len(hist); i++ {
|
||||||
|
role, text := "user", hist[i]
|
||||||
|
if after, ok := strings.CutPrefix(text, "用户: "); ok {
|
||||||
|
role, text = "user", after
|
||||||
|
} else if after, ok := strings.CutPrefix(text, "助手: "); ok {
|
||||||
|
role, text = "agent", after
|
||||||
|
}
|
||||||
|
msgs = append(msgs, map[string]interface{}{
|
||||||
|
"role": role,
|
||||||
|
"text": text,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{
|
||||||
|
"session_id": sid,
|
||||||
|
"status": "completed",
|
||||||
|
"messages": msgs,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
case "session/update":
|
||||||
|
sid := req.Params.SessionID
|
||||||
|
p.mu.Lock()
|
||||||
|
st := p.sessions[sid]
|
||||||
|
p.mu.Unlock()
|
||||||
|
if st == nil {
|
||||||
|
http.Error(w, "session not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if req.Params.Final {
|
||||||
|
// 客户端结束会话:标记并保留历史(后续可再 session/new 续)
|
||||||
|
p.mu.Lock()
|
||||||
|
st.LastUsed = time.Now()
|
||||||
|
p.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{"final": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
case "session/cancel":
|
||||||
|
p.mu.Lock()
|
||||||
|
delete(p.sessions, req.Params.SessionID)
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": req.ID,
|
||||||
|
"result": map[string]interface{}{"canceled": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
default:
|
||||||
|
http.Error(w, fmt.Sprintf("unknown method %q", req.Method), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleSessionSSE 提供 SSE 事件流订阅
|
||||||
|
func (p *Plugin) handleSessionSSE(w http.ResponseWriter, r *http.Request) {
|
||||||
|
sid := r.URL.Query().Get("id")
|
||||||
|
if sid == "" {
|
||||||
|
http.Error(w, "id query param required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.RLock()
|
||||||
|
st := p.sessions[sid]
|
||||||
|
p.mu.RUnlock()
|
||||||
|
if st == nil {
|
||||||
|
http.Error(w, "session not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fl, ok := w.(http.Flusher)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
|
||||||
|
ticker := time.NewTicker(15 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
p.mu.RLock()
|
||||||
|
replies := append([]map[string]interface{}{}, st.Replying...)
|
||||||
|
p.mu.RUnlock()
|
||||||
|
for _, rep := range replies {
|
||||||
|
data, _ := json.Marshal(rep)
|
||||||
|
fmt.Fprintf(w, "event: session/reply\ndata: %s\n\n", data)
|
||||||
|
fl.Flush()
|
||||||
|
}
|
||||||
|
p.mu.Lock()
|
||||||
|
st.Replying = nil
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-r.Context().Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Outbound:ACP 客户端 ----
|
||||||
|
|
||||||
|
// parseRPCBody 兼容 JSON 与 SSE 两种响应体
|
||||||
|
func parseRPCBody(ct string, body []byte) (*json.RawMessage, error) {
|
||||||
|
if strings.Contains(ct, "text/event-stream") {
|
||||||
|
sc := bufio.NewScanner(bytes.NewReader(body))
|
||||||
|
var last string
|
||||||
|
for sc.Scan() {
|
||||||
|
line := strings.TrimRight(sc.Text(), "\r")
|
||||||
|
if strings.HasPrefix(line, "data:") {
|
||||||
|
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||||
|
if data != "" && data != "[DONE]" {
|
||||||
|
last = data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last == "" {
|
||||||
|
return nil, fmt.Errorf("SSE body 中无 data 帧: %s", truncateStr(string(body), 200))
|
||||||
|
}
|
||||||
|
body = []byte(last)
|
||||||
|
}
|
||||||
|
var raw json.RawMessage
|
||||||
|
if err := json.Unmarshal(body, &raw); err != nil {
|
||||||
|
return nil, fmt.Errorf("解析响应失败: %v: %s", err, truncateStr(string(body), 300))
|
||||||
|
}
|
||||||
|
return &raw, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func truncateStr(s string, n int) string {
|
||||||
|
if len(s) > n {
|
||||||
|
return s[:n] + "..."
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleAcpQuery(args map[string]interface{}) (interface{}, error) {
|
||||||
|
serverURL, _ := args["server_url"].(string)
|
||||||
|
serverURL = strings.TrimRight(strings.TrimSpace(serverURL), "/")
|
||||||
|
if serverURL == "" {
|
||||||
|
return map[string]interface{}{"error": "server_url 不能为空"}, nil
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(serverURL, "http://") && !strings.HasPrefix(serverURL, "https://") {
|
||||||
|
serverURL = "http://" + serverURL
|
||||||
|
}
|
||||||
|
prompt, _ := args["prompt"].(string)
|
||||||
|
prompt = strings.TrimSpace(prompt)
|
||||||
|
if prompt == "" {
|
||||||
|
return map[string]interface{}{"error": "prompt 不能为空"}, nil
|
||||||
|
}
|
||||||
|
sessionID, _ := args["session_id"].(string) // 可选:延续对方会话
|
||||||
|
timeoutSec := 120
|
||||||
|
if v, ok := args["timeout"].(float64); ok && v > 0 {
|
||||||
|
timeoutSec = int(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
endpoint := serverURL + "/api/session"
|
||||||
|
client := &http.Client{Timeout: time.Duration(timeoutSec) * time.Second}
|
||||||
|
|
||||||
|
params := map[string]interface{}{
|
||||||
|
"request": map[string]interface{}{"text": prompt},
|
||||||
|
}
|
||||||
|
if sessionID != "" {
|
||||||
|
params["session_id"] = sessionID
|
||||||
|
}
|
||||||
|
newBody, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"jsonrpc": "2.0", "id": "acp-" + fmt.Sprintf("%d", time.Now().UnixNano()),
|
||||||
|
"method": "session/new",
|
||||||
|
"params": params,
|
||||||
|
})
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint, bytes.NewReader(newBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"error": fmt.Sprintf("请求失败(超时%d秒): %v", timeoutSec, err)}, nil
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 && resp.StatusCode != 202 {
|
||||||
|
return map[string]interface{}{"error": fmt.Sprintf("状态码 %d", resp.StatusCode), "raw_body": truncateStr(string(body), 300)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := parseRPCBody(resp.Header.Get("Content-Type"), body)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"error": err.Error()}, nil
|
||||||
|
}
|
||||||
|
var rpcResp struct {
|
||||||
|
Result *struct {
|
||||||
|
Session *struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
} `json:"session,omitempty"`
|
||||||
|
SessionID string `json:"sessionId,omitempty"`
|
||||||
|
Reply string `json:"reply,omitempty"`
|
||||||
|
} `json:"result,omitempty"`
|
||||||
|
Error *struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
} `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(*raw, &rpcResp); err != nil {
|
||||||
|
return map[string]interface{}{"error": fmt.Sprintf("JSON-RPC 解析失败: %v", err), "raw_body": truncateStr(string(*raw), 300)}, nil
|
||||||
|
}
|
||||||
|
if rpcResp.Error != nil {
|
||||||
|
return map[string]interface{}{"error": fmt.Sprintf("ACP 错误 [%d]: %s", rpcResp.Error.Code, rpcResp.Error.Message)}, nil
|
||||||
|
}
|
||||||
|
if rpcResp.Result == nil {
|
||||||
|
return map[string]interface{}{"error": "响应中没有 result", "raw_body": truncateStr(string(*raw), 300)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兼容两种协议:
|
||||||
|
// A) 标准/SSE 型(opencode、本插件服务端):result.session.id,回复经 SSE 事件流
|
||||||
|
// B) 同步 JSON 型(pi bridge):result.sessionId + result.reply
|
||||||
|
if rpcResp.Result.Reply != "" {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"session_id": rpcResp.Result.SessionID,
|
||||||
|
"status": "completed",
|
||||||
|
"reply": rpcResp.Result.Reply,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
if rpcResp.Result.Session == nil || rpcResp.Result.Session.ID == "" {
|
||||||
|
return map[string]interface{}{"error": "响应中没有 session.id", "raw_body": truncateStr(string(*raw), 300)}, nil
|
||||||
|
}
|
||||||
|
sid := rpcResp.Result.Session.ID
|
||||||
|
|
||||||
|
replyText := p.readSSEReply(endpoint, sid, client, timeoutSec)
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"session_id": sid,
|
||||||
|
"status": "completed",
|
||||||
|
"reply": replyText,
|
||||||
|
"note": "延续会话:下次调用传此 session_id 可保持上下文",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readSSEReply 通过 SSE 读取 session/reply 事件并拼接回复文本
|
||||||
|
func (p *Plugin) readSSEReply(endpoint, sid string, client *http.Client, timeoutSec int) string {
|
||||||
|
sseURL := fmt.Sprintf("%s?id=%s", endpoint, sid)
|
||||||
|
req, _ := http.NewRequest("GET", sseURL, nil)
|
||||||
|
req.Header.Set("Accept", "text/event-stream")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("(SSE 读取失败: %v)", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
bb, _ := io.ReadAll(resp.Body)
|
||||||
|
return fmt.Sprintf("(SSE 状态码 %d: %s)", resp.StatusCode, truncateStr(string(bb), 200))
|
||||||
|
}
|
||||||
|
|
||||||
|
var sb strings.Builder
|
||||||
|
sc := bufio.NewScanner(resp.Body)
|
||||||
|
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||||
|
|
||||||
|
deadline := time.Now().Add(time.Duration(timeoutSec) * time.Second)
|
||||||
|
for sc.Scan() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
line := strings.TrimRight(sc.Text(), "\r")
|
||||||
|
if strings.HasPrefix(line, "event: ") && strings.TrimSpace(strings.TrimPrefix(line, "event: ")) == "session/error" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "data:") {
|
||||||
|
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
|
||||||
|
if data == "" || data == "[DONE]" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var evt struct {
|
||||||
|
SessionID string `json:"session_id,omitempty"`
|
||||||
|
Type string `json:"type,omitempty"`
|
||||||
|
Text string `json:"text,omitempty"`
|
||||||
|
Message *struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
} `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal([]byte(data), &evt) == nil {
|
||||||
|
text := evt.Text
|
||||||
|
if evt.Message != nil && evt.Message.Text != "" {
|
||||||
|
text = evt.Message.Text
|
||||||
|
}
|
||||||
|
if text != "" {
|
||||||
|
if sb.Len() > 0 {
|
||||||
|
sb.WriteString("\n")
|
||||||
|
}
|
||||||
|
sb.WriteString(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sb.Len() == 0 {
|
||||||
|
return "(未收到回复)"
|
||||||
|
}
|
||||||
|
return sb.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Management ----
|
||||||
|
|
||||||
|
func (p *Plugin) handleConfigure(args map[string]interface{}) (interface{}, error) {
|
||||||
|
listen, _ := args["listen"].(string)
|
||||||
|
listen = strings.TrimSpace(listen)
|
||||||
|
|
||||||
|
if err := p.sdk.Settings().Set("listen", listen); err != nil {
|
||||||
|
return fmt.Sprintf("保存配置失败: %v", err), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if listen == "" || listen == "off" || listen == "disabled" {
|
||||||
|
p.stopServer()
|
||||||
|
return "ACP HTTP 服务已禁用", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := p.startServer(listen); err != nil {
|
||||||
|
return fmt.Sprintf("ACP 配置已保存,但服务启动失败: %v", err), nil
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("ACP 配置已更新,监听: %s", listen), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleStatus(args map[string]interface{}) (interface{}, error) {
|
||||||
|
addr, _ := p.sdk.Settings().Get("listen")
|
||||||
|
addrStr, _ := addr.(string)
|
||||||
|
|
||||||
|
p.srvMu.Lock()
|
||||||
|
serverRunning := p.server != nil
|
||||||
|
listening := p.serverID
|
||||||
|
p.srvMu.Unlock()
|
||||||
|
|
||||||
|
p.mu.RLock()
|
||||||
|
n := len(p.sessions)
|
||||||
|
p.mu.RUnlock()
|
||||||
|
|
||||||
|
if !serverRunning {
|
||||||
|
listening = "未运行"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("配置监听地址: %s\n当前监听: %s\n服务状态: %s\n活跃会话: %d",
|
||||||
|
addrStr, listening, map[bool]string{true: "运行中", false: "已停止"}[serverRunning], n), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
@ -1,11 +1,11 @@
|
|||||||
# testplugin
|
# ai_image
|
||||||
|
|
||||||
testplugin plugin
|
ai_image plugin
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
plugindev build
|
hmapdev build
|
||||||
```
|
```
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
7
example/ai_image/go.mod
Normal file
7
example/ai_image/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module ai_image
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/ai_image/main.go
Normal file
11
example/ai_image/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
20
example/ai_image/plg.json
Normal file
20
example/ai_image/plg.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "ai_image",
|
||||||
|
"name_zh": "AI绘图",
|
||||||
|
"name_en": "AI Image",
|
||||||
|
"version": "1.3.0",
|
||||||
|
"description": "AI 图像生成插件,支持 OpenAI DALL·E / Stable Diffusion",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": [
|
||||||
|
"ai",
|
||||||
|
"image",
|
||||||
|
"draw",
|
||||||
|
"generate"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
434
example/ai_image/plugin.go
Normal file
434
example/ai_image/plugin.go
Normal file
@ -0,0 +1,434 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Plugin struct {
|
||||||
|
name string
|
||||||
|
sdk *sdk.PluginSDK
|
||||||
|
client *http.Client
|
||||||
|
apiKey string
|
||||||
|
provider string
|
||||||
|
model string
|
||||||
|
size string
|
||||||
|
baseURL string
|
||||||
|
dataDir string // <data>/ai_images:生成本地图片存放目录
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
|
func getSetting[T string | int64 | float64](s sdk.SettingsAPI, key string, def T) T {
|
||||||
|
v, err := s.Get(key)
|
||||||
|
if err != nil || v == nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
switch any(def).(type) {
|
||||||
|
case string:
|
||||||
|
if sv, ok := v.(string); ok {
|
||||||
|
return any(sv).(T)
|
||||||
|
}
|
||||||
|
case int64:
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(int64(n)).(T)
|
||||||
|
case int64:
|
||||||
|
return any(n).(T)
|
||||||
|
case string:
|
||||||
|
if i, err := strconv.ParseInt(n, 10, 64); err == nil {
|
||||||
|
return any(i).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case float64:
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(n).(T)
|
||||||
|
case int64:
|
||||||
|
return any(float64(n)).(T)
|
||||||
|
case string:
|
||||||
|
if f, err := strconv.ParseFloat(n, 64); err == nil {
|
||||||
|
return any(f).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
func getArg[T string | int64 | float64](args map[string]interface{}, key string, def T) T {
|
||||||
|
v, ok := args[key]
|
||||||
|
if !ok || v == nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
switch any(def).(type) {
|
||||||
|
case string:
|
||||||
|
if s, ok := v.(string); ok {
|
||||||
|
return any(s).(T)
|
||||||
|
}
|
||||||
|
case int64:
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(int64(n)).(T)
|
||||||
|
case int64:
|
||||||
|
return any(n).(T)
|
||||||
|
case string:
|
||||||
|
if i, err := strconv.ParseInt(n, 10, 64); err == nil {
|
||||||
|
return any(i).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case float64:
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(n).(T)
|
||||||
|
case int64:
|
||||||
|
return any(float64(n)).(T)
|
||||||
|
case string:
|
||||||
|
if f, err := strconv.ParseFloat(n, 64); err == nil {
|
||||||
|
return any(f).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
|
s.SetAutoRestart(true)
|
||||||
|
p.sdk = s
|
||||||
|
p.client = &http.Client{Timeout: 120 * time.Second}
|
||||||
|
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "api_key", Default: "", Type: "string",
|
||||||
|
DisplayName: "API Key", Description: "OpenAI / Stable Diffusion API Key",
|
||||||
|
Category: "ai_image", Secret: true,
|
||||||
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "base_url", Default: "", Type: "string",
|
||||||
|
DisplayName: "Base URL", Description: "自定义 OpenAI 兼容网关地址(不带 /v1 尾缀,如 http://127.0.0.1:8081);为空走官方 https://api.openai.com",
|
||||||
|
Category: "ai_image",
|
||||||
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "provider", Default: "openai", Type: "string",
|
||||||
|
DisplayName: "Provider", Description: "Image generation provider: openai / stability",
|
||||||
|
Category: "ai_image",
|
||||||
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "model", Default: "dall-e-3", Type: "string",
|
||||||
|
DisplayName: "Model", Description: "Model name (dall-e-3, sd-xl, etc.)",
|
||||||
|
Category: "ai_image",
|
||||||
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "size", Default: "1024x1024", Type: "string",
|
||||||
|
DisplayName: "Size", Description: "Default image size (1024x1024, 1024x1792, 1792x1024)",
|
||||||
|
Category: "ai_image",
|
||||||
|
})
|
||||||
|
|
||||||
|
p.apiKey = getSetting(s.Settings(), "api_key", "")
|
||||||
|
p.provider = getSetting(s.Settings(), "provider", "openai")
|
||||||
|
p.model = getSetting(s.Settings(), "model", "dall-e-3")
|
||||||
|
p.size = getSetting(s.Settings(), "size", "1024x1024")
|
||||||
|
p.baseURL = strings.TrimRight(strings.TrimSpace(getSetting(s.Settings(), "base_url", "")), "/")
|
||||||
|
|
||||||
|
// 生图本地存放目录:插件专属数据目录(SDK DataDir API,内核保证存在)。
|
||||||
|
if p.sdk != nil {
|
||||||
|
if dd := s.Settings().DataDir(); dd != "" {
|
||||||
|
p.dataDir = dd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.dataDir == "" {
|
||||||
|
// 旧版内核无 DataDir API 时退到 /tmp
|
||||||
|
p.dataDir = filepath.Join(os.TempDir(), "homeagent_ai_images")
|
||||||
|
}
|
||||||
|
os.MkdirAll(p.dataDir, 0755)
|
||||||
|
|
||||||
|
tp := p.name + "_"
|
||||||
|
s.RegisterTool(tp+"generate", sdk.ToolDef{
|
||||||
|
Name: tp + "generate", Description: "Generate image from text prompt using AI. Downloads the result locally and returns a local file path (permanent, no expiry). To show the user, send it via output_send with type=image and payload=the returned path.",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"prompt": map[string]interface{}{"type": "string", "description": "Text description of the image to generate"},
|
||||||
|
"size": map[string]interface{}{"type": "string", "description": "Image size (1024x1024, 1024x1792, 1792x1024), default from config"},
|
||||||
|
"model": map[string]interface{}{"type": "string", "description": "Model override (dall-e-3, dall-e-2)"},
|
||||||
|
"n": map[string]interface{}{"type": "integer", "description": "Number of images to generate (1-10), default 1"},
|
||||||
|
},
|
||||||
|
"required": []string{"prompt"},
|
||||||
|
},
|
||||||
|
}, p.handleGenerate)
|
||||||
|
|
||||||
|
fmt.Printf("[%s] started (provider=%s, model=%s)\n", p.name, p.provider, p.model)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Stop() error {
|
||||||
|
fmt.Printf("[%s] stopped\n", p.name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type openAIReq struct {
|
||||||
|
Model string `json:"model"`
|
||||||
|
Prompt string `json:"prompt"`
|
||||||
|
N int `json:"n"`
|
||||||
|
Size string `json:"size"`
|
||||||
|
ResponseFormat string `json:"response_format"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type openAIResp struct {
|
||||||
|
Created int64 `json:"created"`
|
||||||
|
Data []struct {
|
||||||
|
RevisedPrompt string `json:"revised_prompt"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
} `json:"data"`
|
||||||
|
Error *struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
} `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleGenerate(args map[string]interface{}) (interface{}, error) {
|
||||||
|
prompt := getArg(args, "prompt", "")
|
||||||
|
if prompt == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "prompt is required"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
key := getSetting(p.sdk.Settings(), "api_key", p.apiKey)
|
||||||
|
if key == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "API key not configured. Set plugin.ai_image.api_key via CLI."}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
provider := getSetting(p.sdk.Settings(), "provider", p.provider)
|
||||||
|
model := getArg(args, "model", getSetting(p.sdk.Settings(), "model", p.model))
|
||||||
|
size := getArg(args, "size", getSetting(p.sdk.Settings(), "size", p.size))
|
||||||
|
n := getArg(args, "n", int64(1))
|
||||||
|
if n < 1 {
|
||||||
|
n = 1
|
||||||
|
}
|
||||||
|
if n > 10 {
|
||||||
|
n = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
switch provider {
|
||||||
|
case "openai":
|
||||||
|
return p.generateOpenAI(prompt, model, size, int(n), key)
|
||||||
|
case "stability":
|
||||||
|
return p.generateStability(prompt, model, size, int(n), key)
|
||||||
|
default:
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Unknown provider: " + provider + ". Supported: openai, stability"}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) generateOpenAI(prompt, model, size string, n int, apiKey string) (interface{}, error) {
|
||||||
|
// 上游地址:base_url 非空时走自定义网关(如本机 llmsproxy),约定不带 /v1 尾缀;
|
||||||
|
// 为空保持官方直连。兼容误配了 /v1 尾缀的情况(去重)。
|
||||||
|
endpoint := "https://api.openai.com/v1/images/generations"
|
||||||
|
if p.baseURL != "" {
|
||||||
|
base := strings.TrimSuffix(p.baseURL, "/v1")
|
||||||
|
endpoint = base + "/v1/images/generations"
|
||||||
|
}
|
||||||
|
|
||||||
|
body := openAIReq{
|
||||||
|
Model: model,
|
||||||
|
Prompt: prompt,
|
||||||
|
N: n,
|
||||||
|
Size: size,
|
||||||
|
ResponseFormat: "url",
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("[ai_image] endpoint=%s baseURL=%q model=%q", endpoint, p.baseURL, model)
|
||||||
|
b, _ := json.Marshal(body)
|
||||||
|
req, _ := http.NewRequest("POST", endpoint, bytes.NewReader(b))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||||
|
|
||||||
|
resp, err := p.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Request failed: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
var result openAIResp
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Failed to parse response: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if result.Error != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "API error: " + result.Error.Message}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result.Data) == 0 {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "No images returned"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
urls := make([]string, len(result.Data))
|
||||||
|
for i, d := range result.Data {
|
||||||
|
urls[i] = d.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下载到本地 data 目录,返回本地文件路径(而非临时 S3 URL):
|
||||||
|
// - S3 临时 URL 约 1 小时过期,且对无浏览器 UA 的客户端拒绝访问
|
||||||
|
// - 本地路径可经 webui /files/ 永久下发给所有客户端(含 API key 客户端)
|
||||||
|
localPaths := make([]string, len(urls))
|
||||||
|
var errs []string
|
||||||
|
for i, u := range urls {
|
||||||
|
path, err := p.downloadImage(u, fmt.Sprintf("ai_%s_%d", model, time.Now().UnixNano()))
|
||||||
|
if err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("第%d张下载失败: %v", i+1, err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
localPaths[i] = path
|
||||||
|
}
|
||||||
|
|
||||||
|
content := fmt.Sprintf("Generated %d image(s) with model %s:", len(urls), model)
|
||||||
|
for _, pth := range localPaths {
|
||||||
|
if pth != "" {
|
||||||
|
content += "\n" + pth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(errs) > 0 {
|
||||||
|
content += "\n\n" + strings.Join(errs, "\n")
|
||||||
|
}
|
||||||
|
content += "\n\n已将图片保存到本地(不会过期)。如需展示请用 output_send__webui(payload=本地路径, type=image)。"
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": content,
|
||||||
|
"images": localPaths,
|
||||||
|
"prompt": prompt,
|
||||||
|
"model": model,
|
||||||
|
"local_paths": localPaths,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// downloadImage 把生图返回的临时 URL 下载为本地文件,返回本地路径。
|
||||||
|
// 带浏览器 UA 以规避图床对无 UA 客户端的拦截。
|
||||||
|
func (p *Plugin) downloadImage(url, baseName string) (string, error) {
|
||||||
|
dl := &http.Client{Timeout: 60 * time.Second}
|
||||||
|
req, err := http.NewRequest("GET", url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; HomeAgent/1.0)")
|
||||||
|
resp, err := dl.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
b, _ := io.ReadAll(resp.Body)
|
||||||
|
return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(b))[:200])
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
ext := ".png"
|
||||||
|
if ct := resp.Header.Get("Content-Type"); strings.Contains(ct, "jpeg") || strings.Contains(ct, "jpg") {
|
||||||
|
ext = ".jpg"
|
||||||
|
} else if strings.Contains(ct, "webp") {
|
||||||
|
ext = ".webp"
|
||||||
|
}
|
||||||
|
path := filepath.Join(p.dataDir, baseName+ext)
|
||||||
|
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type stabilityReq struct {
|
||||||
|
TextPrompts []stabilityPrompt `json:"text_prompts"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
Samples int `json:"samples"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type stabilityPrompt struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
Weight float64 `json:"weight,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type stabilityArtifact struct {
|
||||||
|
Base64 string `json:"base64"`
|
||||||
|
Seed int `json:"seed"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type stabilityResp struct {
|
||||||
|
Artifacts []stabilityArtifact `json:"artifacts"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) generateStability(prompt, model, size string, n int, apiKey string) (interface{}, error) {
|
||||||
|
width, height := 1024, 1024
|
||||||
|
if parts := strings.Split(size, "x"); len(parts) == 2 {
|
||||||
|
if w, err := strconv.Atoi(parts[0]); err == nil {
|
||||||
|
width = w
|
||||||
|
}
|
||||||
|
if h, err := strconv.Atoi(parts[1]); err == nil {
|
||||||
|
height = h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body := stabilityReq{
|
||||||
|
TextPrompts: []stabilityPrompt{{Text: prompt, Weight: 1.0}},
|
||||||
|
Width: width,
|
||||||
|
Height: height,
|
||||||
|
Samples: n,
|
||||||
|
}
|
||||||
|
|
||||||
|
apiURL := "https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image"
|
||||||
|
|
||||||
|
b, _ := json.Marshal(body)
|
||||||
|
req, _ := http.NewRequest("POST", apiURL, bytes.NewReader(b))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||||
|
req.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
|
resp, err := p.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Request failed: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
return map[string]interface{}{"isError": true, "content": fmt.Sprintf("API error (status %d): %s", resp.StatusCode, string(respBody))}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
var result stabilityResp
|
||||||
|
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Failed to parse response: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result.Artifacts) == 0 {
|
||||||
|
msg := result.Message
|
||||||
|
if msg == "" {
|
||||||
|
msg = "No images returned"
|
||||||
|
}
|
||||||
|
return map[string]interface{}{"isError": true, "content": msg}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
urls := make([]string, len(result.Artifacts))
|
||||||
|
for i, a := range result.Artifacts {
|
||||||
|
urls[i] = "data:image/png;base64," + a.Base64
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("Generated %d image(s) via Stability AI:\n%s\n\n图片已保存到本地,如需展示请用 output_send(type=image)。", len(urls), strings.Join(urls, "\n")),
|
||||||
|
"images": urls,
|
||||||
|
"prompt": prompt,
|
||||||
|
"model": model,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@ -4,4 +4,4 @@ go 1.25.0
|
|||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/bili/main.go
Normal file
11
example/bili/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -2,10 +2,18 @@
|
|||||||
"name": "bili",
|
"name": "bili",
|
||||||
"name_zh": "B站视频下载",
|
"name_zh": "B站视频下载",
|
||||||
"name_en": "Bilibili Video Downloader",
|
"name_en": "Bilibili Video Downloader",
|
||||||
"version": "1.1.0",
|
"version": "1.2.0",
|
||||||
"description": "B站视频下载工具,基于 yt-dlp 引擎。支持查看视频清晰度列表、指定格式下载、可配置下载目录。",
|
"description": "B站视频下载工具,基于 yt-dlp 引擎。支持查看视频清晰度列表、指定格式下载、可配置下载目录。",
|
||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["bili", "video", "download"],
|
"tags": [
|
||||||
"targets": "linux/amd64"
|
"bili",
|
||||||
}
|
"video",
|
||||||
|
"download"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
@ -8,13 +8,15 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
name string
|
name string
|
||||||
sdk *sdk.PluginSDK
|
sdk *sdk.PluginSDK
|
||||||
|
proxy string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Name() string { return p.name }
|
func (p *Plugin) Name() string { return p.name }
|
||||||
@ -25,11 +27,22 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
tp := p.name + "_"
|
tp := p.name + "_"
|
||||||
|
|
||||||
s.Settings().RegisterDef(sdk.ConfigDef{
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
Key: "plugin." + p.name + ".output_dir", Default: "/tmp/bili_videos",
|
Key: "output_dir", Default: "/tmp/bili_videos",
|
||||||
Type: "string", DisplayName: "下载目录",
|
Type: "string", DisplayName: "下载目录",
|
||||||
Description: "B站视频下载后的保存目录",
|
Description: "B站视频下载后的保存目录",
|
||||||
Category: p.name,
|
Category: p.name,
|
||||||
})
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "proxy", Default: "",
|
||||||
|
Type: "string", DisplayName: "HTTP 代理",
|
||||||
|
Description: "yt-dlp 下载使用的 HTTP 代理地址(如 http://127.0.0.1:7890),留空则不设置",
|
||||||
|
Category: p.name,
|
||||||
|
})
|
||||||
|
if v, _ := s.Settings().Get("proxy"); v != nil {
|
||||||
|
if str, ok := v.(string); ok {
|
||||||
|
p.proxy = str
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
s.RegisterTool(tp+"video", sdk.ToolDef{
|
s.RegisterTool(tp+"video", sdk.ToolDef{
|
||||||
Name: tp + "video",
|
Name: tp + "video",
|
||||||
@ -43,6 +56,13 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
},
|
},
|
||||||
"required": []string{"url"},
|
"required": []string{"url"},
|
||||||
},
|
},
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct{ Content string }
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Content != "" {
|
||||||
|
return r.Content
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
}, p.handleBiliVideo)
|
}, p.handleBiliVideo)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -81,12 +101,20 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
|
|
||||||
outputDir := "/tmp/bili_videos"
|
outputDir := "/tmp/bili_videos"
|
||||||
if p.sdk != nil {
|
if p.sdk != nil {
|
||||||
if v, _ := p.sdk.Settings().Get("plugin." + p.name + ".output_dir"); v != nil {
|
if v, _ := p.sdk.Settings().Get("output_dir"); v != nil {
|
||||||
if s, ok := v.(string); ok && s != "" {
|
if s, ok := v.(string); ok && s != "" {
|
||||||
outputDir = s
|
outputDir = s
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 安全校验:output_dir 是配置项,但避免被配成系统目录导致 yt-dlp 任意位置写。
|
||||||
|
// 禁止根/家目录本身,且规范化后必须落在明确子目录内。
|
||||||
|
outputDir = filepath.Clean(outputDir)
|
||||||
|
for _, forbidden := range []string{"/", "/etc", "/usr", "/bin", "/sbin", "/boot", "/dev", "/proc", "/sys", "/var"} {
|
||||||
|
if outputDir == forbidden {
|
||||||
|
return nil, fmt.Errorf("output_dir 不能是系统目录 %s", forbidden)
|
||||||
|
}
|
||||||
|
}
|
||||||
os.MkdirAll(outputDir, 0755)
|
os.MkdirAll(outputDir, 0755)
|
||||||
|
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
@ -94,7 +122,7 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
cmd := exec.Command("yt-dlp", ytdlpArgs...)
|
cmd := exec.Command("yt-dlp", ytdlpArgs...)
|
||||||
cmd.Stdout = &out
|
cmd.Stdout = &out
|
||||||
cmd.Stderr = &out
|
cmd.Stderr = &out
|
||||||
cmd.Env = append(os.Environ(), "HTTP_PROXY=http://127.0.0.1:7890", "HTTPS_PROXY=http://127.0.0.1:7890")
|
cmd.Env = proxyEnv(p.proxy)
|
||||||
if err := cmd.Run(); err != nil {
|
if err := cmd.Run(); err != nil {
|
||||||
return nil, fmt.Errorf("yt-dlp info: %w\n%s", err, strings.TrimSpace(out.String()))
|
return nil, fmt.Errorf("yt-dlp info: %w\n%s", err, strings.TrimSpace(out.String()))
|
||||||
}
|
}
|
||||||
@ -164,12 +192,17 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
return map[string]interface{}{"content": strings.Join(lines, "\n")}, nil
|
return map[string]interface{}{"content": strings.Join(lines, "\n")}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
taskDir := filepath.Join(outputDir, fmt.Sprintf("bili_%d", time.Now().UnixNano()))
|
||||||
|
if err := os.MkdirAll(taskDir, 0755); err != nil {
|
||||||
|
return nil, fmt.Errorf("mkdir task dir: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
dlArgs := []string{
|
dlArgs := []string{
|
||||||
"--no-warnings",
|
"--no-warnings",
|
||||||
"--socket-timeout", "30",
|
"--socket-timeout", "30",
|
||||||
"--retries", "3",
|
"--retries", "3",
|
||||||
"--fragment-retries", "3",
|
"--fragment-retries", "3",
|
||||||
"-o", filepath.Join(outputDir, "%(title)s.%(ext)s"),
|
"-o", filepath.Join(taskDir, "%(title)s.%(ext)s"),
|
||||||
"--no-overwrites",
|
"--no-overwrites",
|
||||||
}
|
}
|
||||||
if format != "" {
|
if format != "" {
|
||||||
@ -177,7 +210,7 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
}
|
}
|
||||||
dlArgs = append(dlArgs, url)
|
dlArgs = append(dlArgs, url)
|
||||||
cmd2 := exec.Command("yt-dlp", dlArgs...)
|
cmd2 := exec.Command("yt-dlp", dlArgs...)
|
||||||
cmd2.Env = append(os.Environ(), "HTTP_PROXY=http://127.0.0.1:7890", "HTTPS_PROXY=http://127.0.0.1:7890")
|
cmd2.Env = proxyEnv(p.proxy)
|
||||||
var dlOut bytes.Buffer
|
var dlOut bytes.Buffer
|
||||||
cmd2.Stdout = &dlOut
|
cmd2.Stdout = &dlOut
|
||||||
cmd2.Stderr = &dlOut
|
cmd2.Stderr = &dlOut
|
||||||
@ -185,9 +218,18 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
return nil, fmt.Errorf("yt-dlp download: %w\n%s", err, strings.TrimSpace(dlOut.String()))
|
return nil, fmt.Errorf("yt-dlp download: %w\n%s", err, strings.TrimSpace(dlOut.String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
entries, _ := os.ReadDir(outputDir)
|
parts, _ := filepath.Glob(filepath.Join(taskDir, "*.part"))
|
||||||
var newest string
|
for _, f := range parts {
|
||||||
var newestTime int64
|
os.Remove(f)
|
||||||
|
}
|
||||||
|
residuals, _ := filepath.Glob(filepath.Join(taskDir, "*.ytdl"))
|
||||||
|
for _, f := range residuals {
|
||||||
|
os.Remove(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
entries, _ := os.ReadDir(taskDir)
|
||||||
|
var mainFile string
|
||||||
|
var mainSize int64
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
if e.IsDir() {
|
if e.IsDir() {
|
||||||
continue
|
continue
|
||||||
@ -196,30 +238,32 @@ func (p *Plugin) handleBiliVideo(args map[string]interface{}) (interface{}, erro
|
|||||||
if fi == nil {
|
if fi == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
t := fi.ModTime().Unix()
|
if fi.Size() > mainSize {
|
||||||
if t > newestTime {
|
mainSize = fi.Size()
|
||||||
newestTime = t
|
mainFile = e.Name()
|
||||||
newest = e.Name()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if newest == "" {
|
if mainFile == "" {
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"content": "下载完成,但未找到视频文件",
|
"content": "下载完成,但未找到视频文件",
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
dlPath := filepath.Join(outputDir, newest)
|
dlPath := filepath.Join(taskDir, mainFile)
|
||||||
fi, _ := os.Stat(dlPath)
|
|
||||||
var fileSize int64
|
|
||||||
if fi != nil {
|
|
||||||
fileSize = fi.Size()
|
|
||||||
}
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"content": fmt.Sprintf("下载完成: %s (%.1f MB)\n路径: %s", newest, float64(fileSize)/1048576, dlPath),
|
"content": fmt.Sprintf("下载完成: %s (%.1f MB)\n路径: %s", mainFile, float64(mainSize)/1048576, dlPath),
|
||||||
"file": dlPath,
|
"file": dlPath,
|
||||||
"filename": newest,
|
"filename": mainFile,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func proxyEnv(proxy string) []string {
|
||||||
|
env := os.Environ()
|
||||||
|
if proxy != "" {
|
||||||
|
env = append(env, "HTTP_PROXY="+proxy, "HTTPS_PROXY="+proxy)
|
||||||
|
}
|
||||||
|
return env
|
||||||
|
}
|
||||||
|
|
||||||
func contains(slice []string, s string) bool {
|
func contains(slice []string, s string) bool {
|
||||||
for _, v := range slice {
|
for _, v := range slice {
|
||||||
if v == s {
|
if v == s {
|
||||||
@ -229,6 +273,6 @@ func contains(slice []string, s string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,101 +0,0 @@
|
|||||||
/* Code generated by cmd/cgo; DO NOT EDIT. */
|
|
||||||
|
|
||||||
/* package bili */
|
|
||||||
|
|
||||||
|
|
||||||
#line 1 "cgo-builtin-export-prolog"
|
|
||||||
|
|
||||||
#include <stddef.h>
|
|
||||||
|
|
||||||
#ifndef GO_CGO_EXPORT_PROLOGUE_H
|
|
||||||
#define GO_CGO_EXPORT_PROLOGUE_H
|
|
||||||
|
|
||||||
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
||||||
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
|
|
||||||
extern size_t _GoStringLen(_GoString_ s);
|
|
||||||
extern const char *_GoStringPtr(_GoString_ s);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Start of preamble from import "C" comments. */
|
|
||||||
|
|
||||||
|
|
||||||
#line 3 "z_bridge_gen.go"
|
|
||||||
|
|
||||||
#include <stdlib.h>
|
|
||||||
int ha_dispatch(int method_id, void* core_api, char* s1, char* s2, char* s3, int i1, int i2, char** result, char** error);
|
|
||||||
|
|
||||||
#line 1 "cgo-generated-wrapper"
|
|
||||||
|
|
||||||
|
|
||||||
/* End of preamble from import "C" comments. */
|
|
||||||
|
|
||||||
|
|
||||||
/* Start of boilerplate cgo prologue. */
|
|
||||||
#line 1 "cgo-gcc-export-header-prolog"
|
|
||||||
|
|
||||||
#ifndef GO_CGO_PROLOGUE_H
|
|
||||||
#define GO_CGO_PROLOGUE_H
|
|
||||||
|
|
||||||
typedef signed char GoInt8;
|
|
||||||
typedef unsigned char GoUint8;
|
|
||||||
typedef short GoInt16;
|
|
||||||
typedef unsigned short GoUint16;
|
|
||||||
typedef int GoInt32;
|
|
||||||
typedef unsigned int GoUint32;
|
|
||||||
typedef long long GoInt64;
|
|
||||||
typedef unsigned long long GoUint64;
|
|
||||||
typedef GoInt64 GoInt;
|
|
||||||
typedef GoUint64 GoUint;
|
|
||||||
typedef size_t GoUintptr;
|
|
||||||
typedef float GoFloat32;
|
|
||||||
typedef double GoFloat64;
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
|
|
||||||
#include <complex.h>
|
|
||||||
typedef _Fcomplex GoComplex64;
|
|
||||||
typedef _Dcomplex GoComplex128;
|
|
||||||
#else
|
|
||||||
#include <complex>
|
|
||||||
typedef std::complex<float> GoComplex64;
|
|
||||||
typedef std::complex<double> GoComplex128;
|
|
||||||
#endif
|
|
||||||
#else
|
|
||||||
typedef float _Complex GoComplex64;
|
|
||||||
typedef double _Complex GoComplex128;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
static assertion to make sure the file is being used on architecture
|
|
||||||
at least with matching size of GoInt.
|
|
||||||
*/
|
|
||||||
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
|
|
||||||
|
|
||||||
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
||||||
typedef _GoString_ GoString;
|
|
||||||
#endif
|
|
||||||
typedef void *GoMap;
|
|
||||||
typedef void *GoChan;
|
|
||||||
typedef struct { void *t; void *v; } GoInterface;
|
|
||||||
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* End of boilerplate cgo prologue. */
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
extern int go_init_plugin(char* name, char* configJSON, char** errorOut);
|
|
||||||
extern int go_start_plugin(void* coreAPIptr, int coreVersion, char** errorOut);
|
|
||||||
extern int go_stop_plugin(char** errorOut);
|
|
||||||
extern int go_invoke_tool(char* name, char* argsJSON, char** resultOut, char** errorOut);
|
|
||||||
extern int go_invoke_stage(char* stage, char* ctxJSON, char** errorOut);
|
|
||||||
extern int go_invoke_output(char* channel, char* msgType, char* payloadJSON, char** errorOut);
|
|
||||||
extern void go_free_string(char* ptr);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@ -2,6 +2,25 @@ module browser
|
|||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0-20260708004841-e9bdcf9304b0
|
require (
|
||||||
|
gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
github.com/chromedp/chromedp v0.9.5
|
||||||
|
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732
|
||||||
|
github.com/chromedp/sysutil v1.0.0
|
||||||
|
github.com/gobwas/httphead v0.1.0
|
||||||
|
github.com/gobwas/pool v0.2.1
|
||||||
|
github.com/gobwas/ws v1.3.2
|
||||||
|
github.com/josharian/intern v1.0.0
|
||||||
|
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80
|
||||||
|
github.com/mailru/easyjson v0.7.7
|
||||||
|
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde
|
||||||
|
golang.org/x/sys v0.16.0
|
||||||
|
)
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../.
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
23
example/browser/go.sum
Normal file
23
example/browser/go.sum
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732 h1:XYUCaZrW8ckGWlCRJKCSoh/iFwlpX316a8yY9IFEzv8=
|
||||||
|
github.com/chromedp/cdproto v0.0.0-20240202021202-6d0b6a386732/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
|
||||||
|
github.com/chromedp/chromedp v0.9.5 h1:viASzruPJOiThk7c5bueOUY91jGLJVximoEMGoH93rg=
|
||||||
|
github.com/chromedp/chromedp v0.9.5/go.mod h1:D4I2qONslauw/C7INoCir1BJkSwBYMyZgx8X276z3+Y=
|
||||||
|
github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
|
||||||
|
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
|
||||||
|
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||||
|
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||||
|
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||||
|
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||||
|
github.com/gobwas/ws v1.3.2 h1:zlnbNHxumkRvfPWgfXu8RBwyNR1x8wh9cf5PTOCqs9Q=
|
||||||
|
github.com/gobwas/ws v1.3.2/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY=
|
||||||
|
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||||
|
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||||
|
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||||
|
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||||
|
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||||
|
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||||
|
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||||
|
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
|
||||||
|
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
11
example/browser/main.go
Normal file
11
example/browser/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -1,11 +1,21 @@
|
|||||||
{
|
{
|
||||||
"name": "browser",
|
"name": "browser",
|
||||||
"name_zh": "浏览器",
|
"name_zh": "浏览器",
|
||||||
"name_en": "browser",
|
"name_en": "Browser",
|
||||||
"version": "1.0.0",
|
"version": "2.3.0",
|
||||||
"description": "网络资源搜索与获取:搜索引擎查询(browser_search)、网页抓取(browser_fetch,SSRF防护)、无头浏览器渲染(browser_render)",
|
"description": "统一浏览器插件:搜索、HTTP抓取(quick)、无头渲染(normal)、交互式浏览器(interactive/CDP)",
|
||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["web", "search", "fetch", "browser"],
|
"tags": [
|
||||||
"targets": "linux/amd64"
|
"web",
|
||||||
}
|
"search",
|
||||||
|
"fetch",
|
||||||
|
"browser",
|
||||||
|
"cdp"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
13
example/calendar/README.md
Normal file
13
example/calendar/README.md
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# calendar
|
||||||
|
|
||||||
|
calendar plugin
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Upload the .hmap file through the Plugin Manager API.
|
||||||
7
example/calendar/go.mod
Normal file
7
example/calendar/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module calendar
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/calendar/main.go
Normal file
11
example/calendar/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
20
example/calendar/plg.json
Normal file
20
example/calendar/plg.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "calendar",
|
||||||
|
"name_zh": "日历",
|
||||||
|
"name_en": "Calendar",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"description": "日历事件管理,支持提醒和重复事件",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": [
|
||||||
|
"calendar",
|
||||||
|
"event",
|
||||||
|
"reminder",
|
||||||
|
"schedule"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
1189
example/calendar/plugin.go
Normal file
1189
example/calendar/plugin.go
Normal file
File diff suppressed because it is too large
Load Diff
@ -4,4 +4,4 @@ go 1.25.0
|
|||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/editdoc/main.go
Normal file
11
example/editdoc/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -7,5 +7,9 @@
|
|||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["editdoc", "office", "document"],
|
"tags": ["editdoc", "office", "document"],
|
||||||
"targets": "linux/amd64"
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
}
|
}
|
||||||
|
|||||||
@ -4,15 +4,19 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
name string
|
name string
|
||||||
sdk *sdk.PluginSDK
|
sdk *sdk.PluginSDK
|
||||||
|
scriptPath string
|
||||||
|
venvPython string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Name() string { return p.name }
|
func (p *Plugin) Name() string { return p.name }
|
||||||
@ -20,9 +24,34 @@ func (p *Plugin) Name() string { return p.name }
|
|||||||
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
s.SetAutoRestart(true)
|
s.SetAutoRestart(true)
|
||||||
p.sdk = s
|
p.sdk = s
|
||||||
|
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "script_path", Default: "", Type: "string",
|
||||||
|
DisplayName: "编辑脚本路径",
|
||||||
|
Description: "edit_doc.py 的绝对路径;留空时使用插件可执行文件同目录下的 edit_doc.py",
|
||||||
|
Category: p.name,
|
||||||
|
})
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "venv_python", Default: "", Type: "string",
|
||||||
|
DisplayName: "venv Python 解释器",
|
||||||
|
Description: "执行 edit_doc.py 使用的 Python 解释器(建议用 venv 内的 python);必须配置,留空将报错",
|
||||||
|
Category: p.name,
|
||||||
|
})
|
||||||
|
|
||||||
|
if v, err := s.Settings().Get("script_path"); err == nil {
|
||||||
|
if str, ok := v.(string); ok {
|
||||||
|
p.scriptPath = str
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v, err := s.Settings().Get("venv_python"); err == nil {
|
||||||
|
if str, ok := v.(string); ok {
|
||||||
|
p.venvPython = str
|
||||||
|
}
|
||||||
|
}
|
||||||
s.RegisterTool("edit_document", sdk.ToolDef{
|
s.RegisterTool("edit_document", sdk.ToolDef{
|
||||||
Name: "edit_document",
|
Name: "edit_document",
|
||||||
Description: "编辑 Office 文档内容。支持替换文本、修改单元格等操作。编辑后原文件被覆盖。操作前建议先用 read_document 查看内容。支持 .docx / .xlsx / .pptx。",
|
Description: "编辑 Office 文档内容。支持替换文本、修改单元格等操作。编辑后原文件被覆盖。操作前建议先用 read_document 查看内容。支持 .docx / .xlsx / .pptx。",
|
||||||
|
NoMemory: true,
|
||||||
Parameters: map[string]interface{}{
|
Parameters: map[string]interface{}{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": map[string]interface{}{
|
"properties": map[string]interface{}{
|
||||||
@ -79,19 +108,24 @@ func (p *Plugin) handleEditDocument(args map[string]interface{}) (interface{}, e
|
|||||||
}
|
}
|
||||||
pyArgsJSON, _ := json.Marshal(pyArgs)
|
pyArgsJSON, _ := json.Marshal(pyArgs)
|
||||||
|
|
||||||
scriptPath := "/home/newqqagent/plugins/editdoc/edit_doc.py"
|
scriptPath := p.scriptPath
|
||||||
|
if scriptPath == "" {
|
||||||
|
scriptPath = filepath.Join(filepath.Dir(os.Args[0]), "edit_doc.py")
|
||||||
|
log.Printf("[%s] script_path 未配置,使用默认脚本路径: %s", p.name, scriptPath)
|
||||||
|
}
|
||||||
if _, err := os.Stat(scriptPath); os.IsNotExist(err) {
|
if _, err := os.Stat(scriptPath); os.IsNotExist(err) {
|
||||||
return nil, fmt.Errorf("edit_doc.py not found at %s", scriptPath)
|
return nil, fmt.Errorf("edit_doc.py not found at %s(请在插件配置 script_path 中指定脚本路径)", scriptPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
venvPython := "/home/program/qq-workspace/self-workplace/.venv/bin/python3"
|
if p.venvPython == "" {
|
||||||
pythonBin := "python3"
|
return nil, fmt.Errorf("venv_python 未配置,无法执行脚本;请在插件配置中设置 venv_python(venv 内 python 的绝对路径)")
|
||||||
if _, err := os.Stat(venvPython); err == nil {
|
}
|
||||||
pythonBin = venvPython
|
if _, err := os.Stat(p.venvPython); err != nil {
|
||||||
|
return nil, fmt.Errorf("venv python 不存在: %s(请检查 venv_python 配置)", p.venvPython)
|
||||||
}
|
}
|
||||||
|
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
cmd := exec.Command(pythonBin, scriptPath, file, operation, string(pyArgsJSON))
|
cmd := exec.Command(p.venvPython, scriptPath, file, operation, string(pyArgsJSON))
|
||||||
cmd.Stdout = &out
|
cmd.Stdout = &out
|
||||||
if err := cmd.Run(); err != nil {
|
if err := cmd.Run(); err != nil {
|
||||||
return nil, fmt.Errorf("edit document: %w", err)
|
return nil, fmt.Errorf("edit document: %w", err)
|
||||||
@ -124,6 +158,6 @@ func (p *Plugin) handleEditDocument(args map[string]interface{}) (interface{}, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
7
example/files/go.mod
Normal file
7
example/files/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module files
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/files/main.go
Normal file
11
example/files/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -7,5 +7,9 @@
|
|||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["files", "filesystem"],
|
"tags": ["files", "filesystem"],
|
||||||
"targets": "linux/amd64"
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
@ -25,25 +26,40 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
s.SetAutoRestart(true)
|
s.SetAutoRestart(true)
|
||||||
p.sdk = s
|
p.sdk = s
|
||||||
s.Settings().RegisterDef(sdk.ConfigDef{
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
Key: "plugin.files.dir",
|
Key: "dir",
|
||||||
Default: "/",
|
Default: "",
|
||||||
Type: "string",
|
Type: "string",
|
||||||
DisplayName: "文件系统根目录",
|
DisplayName: "文件系统根目录",
|
||||||
Description: "文件操作允许访问的根目录(设为 / 表示完整主机文件系统)",
|
Description: "文件操作允许访问的根目录;留空时使用默认沙箱目录(主数据目录/files_sandbox),不建议设为 /",
|
||||||
Category: "files",
|
Category: "files",
|
||||||
})
|
})
|
||||||
|
|
||||||
dir := getSetting[string](s.Settings(), "dir", "/")
|
dir := getSetting[string](s.Settings(), "dir", "")
|
||||||
if strings.HasPrefix(dir, "~/") {
|
if strings.HasPrefix(dir, "~/") {
|
||||||
home, _ := os.UserHomeDir()
|
home, _ := os.UserHomeDir()
|
||||||
dir = filepath.Join(home, dir[2:])
|
dir = filepath.Join(home, dir[2:])
|
||||||
}
|
}
|
||||||
|
if dir == "" {
|
||||||
|
dataDir, err := s.Settings().GetCore("core.daemon.data_dir")
|
||||||
|
base := "."
|
||||||
|
if err == nil {
|
||||||
|
if ds, ok := dataDir.(string); ok && ds != "" {
|
||||||
|
base = ds
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dir = filepath.Join(base, "files_sandbox")
|
||||||
|
}
|
||||||
abs, err := filepath.Abs(dir)
|
abs, err := filepath.Abs(dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("resolve files.dir: %w", err)
|
return fmt.Errorf("resolve files.dir: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := os.MkdirAll(abs, 0755); err != nil {
|
||||||
|
return fmt.Errorf("mkdir files.dir: %w", err)
|
||||||
|
}
|
||||||
|
if real, err := filepath.EvalSymlinks(abs); err == nil {
|
||||||
|
abs = real
|
||||||
|
}
|
||||||
p.filesDir = abs
|
p.filesDir = abs
|
||||||
os.MkdirAll(p.filesDir, 0755)
|
|
||||||
|
|
||||||
tp := p.name + "_"
|
tp := p.name + "_"
|
||||||
|
|
||||||
@ -59,6 +75,14 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
},
|
},
|
||||||
"required": []string{"path"},
|
"required": []string{"path"},
|
||||||
},
|
},
|
||||||
|
NoMemory: false,
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct{ Content string }
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Content != "" {
|
||||||
|
return r.Content
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
}, p.handleRead)
|
}, p.handleRead)
|
||||||
|
|
||||||
s.RegisterTool(tp+"write", sdk.ToolDef{
|
s.RegisterTool(tp+"write", sdk.ToolDef{
|
||||||
@ -134,10 +158,60 @@ func (p *Plugin) resolvePath(userPath string) (string, error) {
|
|||||||
return "", fmt.Errorf("resolve path: %w", err)
|
return "", fmt.Errorf("resolve path: %w", err)
|
||||||
}
|
}
|
||||||
base := filepath.Clean(p.filesDir)
|
base := filepath.Clean(p.filesDir)
|
||||||
if base != "/" && !strings.HasPrefix(abs, base+string(filepath.Separator)) && abs != base {
|
if !withinSandbox(base, abs) {
|
||||||
return "", fmt.Errorf("path outside sandbox: %s", userPath)
|
return "", fmt.Errorf("path outside sandbox: %s", userPath)
|
||||||
}
|
}
|
||||||
return abs, nil
|
real, err := evalReal(base, abs)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !withinSandbox(base, real) {
|
||||||
|
return "", fmt.Errorf("path escapes sandbox via symlink: %s", userPath)
|
||||||
|
}
|
||||||
|
return real, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func withinSandbox(base, abs string) bool {
|
||||||
|
if base == "/" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return abs == base || strings.HasPrefix(abs, base+string(filepath.Separator))
|
||||||
|
}
|
||||||
|
|
||||||
|
func evalReal(base, abs string) (string, error) {
|
||||||
|
existing := abs
|
||||||
|
var tail []string
|
||||||
|
for {
|
||||||
|
real, err := filepath.EvalSymlinks(existing)
|
||||||
|
if err == nil {
|
||||||
|
full := real
|
||||||
|
for i := len(tail) - 1; i >= 0; i-- {
|
||||||
|
full = filepath.Join(full, tail[i])
|
||||||
|
}
|
||||||
|
return full, nil
|
||||||
|
}
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
return "", fmt.Errorf("resolve path: %w", err)
|
||||||
|
}
|
||||||
|
if link, lerr := os.Readlink(existing); lerr == nil {
|
||||||
|
target := link
|
||||||
|
if !filepath.IsAbs(target) {
|
||||||
|
target = filepath.Join(filepath.Dir(existing), target)
|
||||||
|
}
|
||||||
|
if t, aerr := filepath.Abs(target); aerr == nil {
|
||||||
|
target = filepath.Clean(t)
|
||||||
|
}
|
||||||
|
if !withinSandbox(base, target) {
|
||||||
|
return "", fmt.Errorf("path escapes sandbox via symlink: %s", abs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parent := filepath.Dir(existing)
|
||||||
|
if parent == existing {
|
||||||
|
return "", fmt.Errorf("resolve path: %w", err)
|
||||||
|
}
|
||||||
|
tail = append(tail, filepath.Base(existing))
|
||||||
|
existing = parent
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleRead implements the read tool.
|
// handleRead implements the read tool.
|
||||||
@ -478,6 +552,6 @@ func getSetting[T any](s sdk.SettingsAPI, key string, def T) T {
|
|||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
25
example/luademo/README.md
Normal file
25
example/luademo/README.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# luademo
|
||||||
|
|
||||||
|
Lua 插件全功能示例,展示 v0.8.0 Lua SDK 的完整能力面:
|
||||||
|
|
||||||
|
- **工具注册**:`no_memory` + `cleaner`(记忆计算层过滤)
|
||||||
|
- **阶段钩子**:`register_stage(stage, handler, scope)`,`own_tools` 与全局作用域
|
||||||
|
- **通道**:`register_output_channel` / `register_input_channel`(def 支持 no_memory/cleaner)
|
||||||
|
- **数据类 API**:`sdk.memory.*`、`sdk.doc.*`、`sdk.knowledge.*`、`sdk.text_memory.*`、`sdk.llm.*`、`sdk.settings.*`、`sdk.social.*`
|
||||||
|
- **其他**:`register_api`、`set_auto_restart`
|
||||||
|
|
||||||
|
## 本地独立测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
lua main.lua # 使用 sdk.lua mock,不依赖内核
|
||||||
|
```
|
||||||
|
|
||||||
|
## 构建
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev build
|
||||||
|
```
|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
通过插件管理 HTTP API 上传 `.hmap` 包,或解压到 `<data>/plugins/luademo/` 后重启内核。
|
||||||
105
example/luademo/main.lua
Normal file
105
example/luademo/main.lua
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
-- luademo plugin — 展示 v0.8.0 Lua SDK 全部能力
|
||||||
|
-- 运行环境:内核注入真实实现;lua main.lua 可用 sdk.lua mock 独立测试
|
||||||
|
local plugin = { name = "luademo" }
|
||||||
|
|
||||||
|
function plugin.start(sdk)
|
||||||
|
sdk.log("info", "luademo starting...")
|
||||||
|
|
||||||
|
-- 注册配置项(WebUI 可展示)
|
||||||
|
sdk.settings.register_def({
|
||||||
|
key = "plugin.luademo.greeting",
|
||||||
|
default = "Hello",
|
||||||
|
type = "string",
|
||||||
|
display_name = "Greeting",
|
||||||
|
description = "Greeting prefix for the hello tool",
|
||||||
|
category = "luademo",
|
||||||
|
})
|
||||||
|
|
||||||
|
-- 注册工具:no_memory(输出跳过记忆计算)+ cleaner(计算层过滤函数)
|
||||||
|
sdk.register_tool("luademo_hello", {
|
||||||
|
description = "A hello world tool with no_memory and cleaner",
|
||||||
|
parameters = { type = "object", properties = {} },
|
||||||
|
no_memory = true,
|
||||||
|
cleaner = function(text) return "CLEANED:" .. text end,
|
||||||
|
}, function(args)
|
||||||
|
local prefix, err = sdk.settings.get_core("plugin.luademo.greeting")
|
||||||
|
if err ~= nil then prefix = "Hello" end
|
||||||
|
return { content = (prefix or "Hello") .. " from luademo plugin!" }
|
||||||
|
end)
|
||||||
|
|
||||||
|
-- 注册工具:数据类 API 巡检(memory/doc/knowledge/text_memory/llm/settings/social)
|
||||||
|
sdk.register_tool("luademo_probe", {
|
||||||
|
description = "Exercise every aligned data API and return combined results",
|
||||||
|
parameters = { type = "object", properties = {} },
|
||||||
|
no_memory = true,
|
||||||
|
}, function(args)
|
||||||
|
local res = {}
|
||||||
|
|
||||||
|
local ok, err = sdk.memory.commit({ { subject = "demo", relation = "uses", object = "lua" } })
|
||||||
|
res.memory_commit = { ok = ok, err = err }
|
||||||
|
local recalled, rerr = sdk.memory.recall("demo", 1)
|
||||||
|
res.memory_recall = { result = recalled, err = rerr }
|
||||||
|
|
||||||
|
ok, err = sdk.doc.insert({ id = "demo-1", title = "lua demo doc", content = "hello lua world" })
|
||||||
|
res.doc_insert = { ok = ok, err = err }
|
||||||
|
local docs, derr = sdk.doc.query("lua", 2)
|
||||||
|
res.doc_query = { result = docs, err = derr }
|
||||||
|
|
||||||
|
ok, err = sdk.knowledge.add("luademo", "lua knowledge entry")
|
||||||
|
res.knowledge_add = { ok = ok, err = err }
|
||||||
|
local entries, kerr = sdk.knowledge.search("luademo", 2)
|
||||||
|
res.knowledge_search = { result = entries, err = kerr }
|
||||||
|
|
||||||
|
ok, err = sdk.text_memory.append({ role = "tool", content = "luademo probe ran", channel = "luademo" })
|
||||||
|
res.text_memory = { ok = ok, err = err }
|
||||||
|
|
||||||
|
local sources, serr = sdk.llm.list_sources()
|
||||||
|
res.llm_sources = { result = sources, err = serr }
|
||||||
|
|
||||||
|
local v, verr = sdk.settings.get_core("agent.name")
|
||||||
|
res.settings_get_core = { result = v, err = verr }
|
||||||
|
local defs, defserr = sdk.settings.defs("plugin.luademo")
|
||||||
|
res.settings_defs = { result = defs, err = defserr }
|
||||||
|
|
||||||
|
local persons, perr = sdk.social.list_persons()
|
||||||
|
res.social_persons = { result = persons, err = perr }
|
||||||
|
|
||||||
|
return { content = res }
|
||||||
|
end)
|
||||||
|
|
||||||
|
-- 阶段钩子:own_tools 作用域(仅本插件工具被调用时触发)
|
||||||
|
sdk.register_stage("before_toolcall", function(ctx)
|
||||||
|
local calls = ctx.tool_calls or {}
|
||||||
|
if calls[1] then
|
||||||
|
sdk.log("info", "luademo stage before_toolcall: tool=" .. tostring(calls[1].name))
|
||||||
|
end
|
||||||
|
return nil
|
||||||
|
end, "own_tools")
|
||||||
|
|
||||||
|
-- 阶段钩子:全局作用域(修改 ctx 字段会写回内核,见 applyLuaStageResult)
|
||||||
|
sdk.register_stage("pre_action", function(ctx)
|
||||||
|
sdk.log("info", "luademo stage pre_action: user=" .. tostring(ctx.user_id))
|
||||||
|
-- 演示 stage 写回:给 llm_text 追加标记(内核会同步回 StageContext)
|
||||||
|
if ctx.llm_text then
|
||||||
|
ctx.llm_text = ctx.llm_text .. "[luademo]"
|
||||||
|
end
|
||||||
|
return nil
|
||||||
|
end)
|
||||||
|
|
||||||
|
-- 输出通道:路由输出到外部渠道(def 支持 no_memory/cleaner)
|
||||||
|
sdk.register_output_channel("luademo_out", 0, "luademo push channel",
|
||||||
|
{ no_memory = true, cleaner = function(t) return "OCLEANED:" .. t end },
|
||||||
|
function(args) return { content = "out-channel ack" } end)
|
||||||
|
|
||||||
|
-- 输入通道
|
||||||
|
sdk.register_input_channel("luademo_in", { no_memory = true })
|
||||||
|
|
||||||
|
-- 其他 API
|
||||||
|
sdk.register_api("luademo.ping")
|
||||||
|
sdk.set_auto_restart(true)
|
||||||
|
|
||||||
|
sdk.log("info", "luademo started")
|
||||||
|
end
|
||||||
|
|
||||||
|
function plugin.stop() sdk.log("info", "luademo stopped") end
|
||||||
|
return plugin
|
||||||
11
example/luademo/plg.json
Normal file
11
example/luademo/plg.json
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "luademo",
|
||||||
|
"name_zh": "Lua 全功能示例",
|
||||||
|
"name_en": "Lua Demo",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Lua 插件全功能示例:工具(no_memory/cleaner) + 阶段钩子 + 通道 + 数据类 API",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "main.lua",
|
||||||
|
"tags": ["luademo"],
|
||||||
|
"targets": "lua"
|
||||||
|
}
|
||||||
67
example/luademo/sdk.lua
Normal file
67
example/luademo/sdk.lua
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
-- HomeAgent Lua Plugin SDK (standalone mock)
|
||||||
|
sdk = {}
|
||||||
|
function sdk.log(level, msg) print("[lua-plugin] " .. tostring(level) .. ": " .. tostring(msg)) end
|
||||||
|
function sdk.register_tool(name, def, handler) print("[lua-plugin] register_tool: " .. tostring(name)) end
|
||||||
|
function sdk.register_stage(stage, handler, scope) print("[lua-plugin] register_stage: " .. tostring(stage) .. " scope=" .. tostring(scope)) end
|
||||||
|
function sdk.register_api(name) print("[lua-plugin] register_api: " .. tostring(name)) end
|
||||||
|
function sdk.register_output_channel(name, caps, desc, def, handler) print("[lua-plugin] register_output_channel: " .. tostring(name)) end
|
||||||
|
function sdk.register_input_channel(name, def) print("[lua-plugin] register_input_channel: " .. tostring(name)) end
|
||||||
|
function sdk.get_setting(key) return nil end
|
||||||
|
function sdk.set_setting(key, value) print("[lua-plugin] set_setting: " .. tostring(key)) end
|
||||||
|
function sdk.inject_text(source, channel, text) print("[lua-plugin] inject_text: " .. tostring(source)) end
|
||||||
|
function sdk.inject_interrupt(source, channel, text) print("[lua-plugin] inject_interrupt: " .. tostring(source)) end
|
||||||
|
function sdk.inject_text_no_memory(source, channel, text) print("[lua-plugin] inject_text_no_memory: " .. tostring(source)) end
|
||||||
|
function sdk.set_auto_restart(enabled) print("[lua-plugin] set_auto_restart: " .. tostring(enabled)) end
|
||||||
|
sdk.memory = {}
|
||||||
|
function sdk.memory.recall(query, depth) return {entities={}, relations={}} end
|
||||||
|
function sdk.memory.commit(triples) return nil end
|
||||||
|
function sdk.memory.introspect() return {} end
|
||||||
|
function sdk.memory.merge(source, target) return 0 end
|
||||||
|
function sdk.memory.purge(criteria, hard) return 0 end
|
||||||
|
sdk.doc = {}
|
||||||
|
function sdk.doc.query(text, top_k) return {} end
|
||||||
|
function sdk.doc.insert(doc) return nil end
|
||||||
|
function sdk.doc.remove(id) return nil end
|
||||||
|
function sdk.doc.stats() return {} end
|
||||||
|
sdk.knowledge = {}
|
||||||
|
function sdk.knowledge.search(query, limit) return {} end
|
||||||
|
function sdk.knowledge.add(tag, content) return nil end
|
||||||
|
function sdk.knowledge.list() return {} end
|
||||||
|
sdk.text_memory = {}
|
||||||
|
function sdk.text_memory.append(evt) return nil end
|
||||||
|
sdk.llm = {}
|
||||||
|
function sdk.llm.list_sources() return {} end
|
||||||
|
function sdk.llm.set_source(name) return nil end
|
||||||
|
function sdk.llm.current_source() return nil end
|
||||||
|
sdk.social = {}
|
||||||
|
function sdk.social.get_person(name) return {} end
|
||||||
|
function sdk.social.get_network(name, depth) return {} end
|
||||||
|
function sdk.social.get_trait(name, trait) return {value=nil, found=false} end
|
||||||
|
function sdk.social.get_relations(name) return {} end
|
||||||
|
function sdk.social.list_persons() return {} end
|
||||||
|
sdk.settings = {}
|
||||||
|
function sdk.settings.get_core(key) return nil end
|
||||||
|
function sdk.settings.set_core(key, value) return nil end
|
||||||
|
function sdk.settings.list_core(prefix) return {} end
|
||||||
|
function sdk.settings.get_plugin(plugin, key) return nil end
|
||||||
|
function sdk.settings.set_plugin(plugin, key, value) return nil end
|
||||||
|
function sdk.settings.list_plugin(plugin, prefix) return {} end
|
||||||
|
function sdk.settings.list(prefix) return {} end
|
||||||
|
function sdk.settings.register_def(def) return nil end
|
||||||
|
function sdk.settings.defs(prefix) return {} end
|
||||||
|
function sdk.settings.dump() return {} end
|
||||||
|
function sdk.settings.plugins() return {} end
|
||||||
|
sdk.json = {}
|
||||||
|
function sdk.json.encode(val)
|
||||||
|
if type(val) == "string" then return '"' .. val:gsub('"', '\\"'):gsub('\n', '\\n') .. '"'
|
||||||
|
elseif type(val) == "number" or type(val) == "boolean" then return tostring(val)
|
||||||
|
elseif type(val) == "table" then local parts, i = {}, 1
|
||||||
|
for k, v in pairs(val) do parts[i] = sdk.json.encode(k) .. ":" .. sdk.json.encode(v); i = i + 1 end
|
||||||
|
return "{" .. table.concat(parts, ",") .. "}" end
|
||||||
|
return "null"
|
||||||
|
end
|
||||||
|
function sdk.json.decode(str) local ok, fn = pcall(load, "return " .. str); if ok then return fn() end; return nil end
|
||||||
|
sdk.http = {}
|
||||||
|
function sdk.http.get(url) print("[lua-plugin] http.get: " .. tostring(url)); return {status=200, body='{"mock":true}', headers={}} end
|
||||||
|
function sdk.http.post(url, body, ct) print("[lua-plugin] http.post: " .. tostring(url)); return {status=200, body='{"mock":true}', headers={}} end
|
||||||
|
return sdk
|
||||||
@ -4,4 +4,4 @@ go 1.25.0
|
|||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/memo/main.go
Normal file
11
example/memo/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -1,11 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "memo",
|
"name": "memo",
|
||||||
"name_zh": "备忘录",
|
"name_zh": "备忘录",
|
||||||
"name_en": "Memo/Notes",
|
"name_en": "Memo",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"description": "待办事项与备忘录管理插件。支持创建、完成、列表查看。通过阶段钩子在每次对话前注入待办提醒。",
|
"description": "待办与备忘录插件。待办(todo_add/todo_complete/todo_list)会主动提醒;备忘录(memo_create/memo_list/memo_delete)纯记事不提醒。",
|
||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["memo", "todo", "notes"],
|
"tags": [
|
||||||
"targets": "linux/amd64"
|
"memo",
|
||||||
}
|
"todo",
|
||||||
|
"notes"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
@ -13,20 +13,31 @@ import (
|
|||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Memo struct {
|
// Todo 待办条目:会被主动提醒
|
||||||
|
type Todo struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
CreatedAt int64 `json:"created_at"`
|
CreatedAt int64 `json:"created_at"`
|
||||||
Done bool `json:"done"`
|
Done bool `json:"done"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Memo 备忘录条目:纯记事,不主动提醒
|
||||||
|
type Memo struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
name string
|
name string
|
||||||
sdk *sdk.PluginSDK
|
sdk *sdk.PluginSDK
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
|
todos []Todo
|
||||||
|
nextTID int64
|
||||||
memos []Memo
|
memos []Memo
|
||||||
nextID int64
|
nextMID int64
|
||||||
filePath string
|
todoPath string
|
||||||
|
memoPath string
|
||||||
stopCh chan struct{}
|
stopCh chan struct{}
|
||||||
tp string
|
tp string
|
||||||
}
|
}
|
||||||
@ -37,70 +48,154 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
s.SetAutoRestart(true)
|
s.SetAutoRestart(true)
|
||||||
p.sdk = s
|
p.sdk = s
|
||||||
p.tp = p.name + "_"
|
p.tp = p.name + "_"
|
||||||
p.stopCh = make(chan struct{})
|
|
||||||
|
|
||||||
dataDirVal, err := s.Settings().GetCore("core.daemon.data_dir")
|
dataDirVal, err := s.Settings().GetCore("core.daemon.data_dir")
|
||||||
if err != nil || dataDirVal == "" {
|
if err != nil || dataDirVal == "" {
|
||||||
dataDirVal = "."
|
dataDirVal = "."
|
||||||
}
|
}
|
||||||
p.filePath = filepath.Join(fmt.Sprint(dataDirVal), "memos.json")
|
dir := filepath.Join(fmt.Sprint(dataDirVal), p.name)
|
||||||
p.load()
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
log.Printf("[%s] mkdir data dir %s: %v", p.name, dir, err)
|
||||||
|
}
|
||||||
|
p.todoPath = filepath.Join(dir, "todos.json")
|
||||||
|
p.memoPath = filepath.Join(dir, "memos.json")
|
||||||
|
p.loadTodos()
|
||||||
|
p.loadMemos()
|
||||||
|
|
||||||
s.RegisterTool(p.tp+"create", sdk.ToolDef{
|
// 卸载(删除)时清理数据文件;重载不触发
|
||||||
Name: p.tp + "create",
|
s.RegisterOnRemoveHandler(p.cleanupData)
|
||||||
Description: "创建一条备忘条目。备忘内容应包含具体事项的完整描述。",
|
|
||||||
|
// ── 待办(会被主动提醒)──
|
||||||
|
s.RegisterTool(p.tp+"todo_add", sdk.ToolDef{
|
||||||
|
Name: p.tp + "todo_add",
|
||||||
|
Description: "添加一条待办事项。待办会被主动提醒,完成后请及时用 todo_complete 标记。",
|
||||||
Parameters: map[string]interface{}{
|
Parameters: map[string]interface{}{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": map[string]interface{}{
|
"properties": map[string]interface{}{
|
||||||
"content": map[string]interface{}{"type": "string", "description": "备忘内容"},
|
"content": map[string]interface{}{"type": "string", "description": "待办内容"},
|
||||||
},
|
},
|
||||||
"required": []string{"content"},
|
"required": []string{"content"},
|
||||||
},
|
},
|
||||||
}, p.handleCreate)
|
}, p.handleTodoAdd)
|
||||||
|
|
||||||
s.RegisterTool(p.tp+"complete", sdk.ToolDef{
|
s.RegisterTool(p.tp+"todo_complete", sdk.ToolDef{
|
||||||
Name: p.tp + "complete",
|
Name: p.tp + "todo_complete",
|
||||||
Description: "将指定ID的备忘标记为已完成。",
|
Description: "将指定ID的待办标记为已完成(不再提醒)。",
|
||||||
Parameters: map[string]interface{}{
|
Parameters: map[string]interface{}{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": map[string]interface{}{
|
"properties": map[string]interface{}{
|
||||||
"id": map[string]interface{}{"type": "integer", "description": "备忘ID"},
|
"id": map[string]interface{}{"type": "integer", "description": "待办ID"},
|
||||||
},
|
},
|
||||||
"required": []string{"id"},
|
"required": []string{"id"},
|
||||||
},
|
},
|
||||||
}, p.handleComplete)
|
}, p.handleTodoComplete)
|
||||||
|
|
||||||
s.RegisterTool(p.tp+"list", sdk.ToolDef{
|
s.RegisterTool(p.tp+"todo_list", sdk.ToolDef{
|
||||||
Name: p.tp + "list",
|
Name: p.tp + "todo_list",
|
||||||
Description: "列出所有未完成的备忘条目,包含ID、内容和创建时间。",
|
Description: "列出所有未完成的待办事项,包含ID、内容和创建时间。",
|
||||||
Parameters: map[string]interface{}{
|
Parameters: map[string]interface{}{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": map[string]interface{}{},
|
"properties": map[string]interface{}{},
|
||||||
},
|
},
|
||||||
}, p.handleList)
|
}, p.handleTodoList)
|
||||||
|
|
||||||
|
s.RegisterTool(p.tp+"todo_delete", sdk.ToolDef{
|
||||||
|
Name: p.tp + "todo_delete",
|
||||||
|
Description: "删除指定ID的待办事项(包括已完成的)。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"id": map[string]interface{}{"type": "integer", "description": "待办ID"},
|
||||||
|
},
|
||||||
|
"required": []string{"id"},
|
||||||
|
},
|
||||||
|
}, p.handleTodoDelete)
|
||||||
|
|
||||||
|
// ── 备忘(纯记事,不提醒)──
|
||||||
|
s.RegisterTool(p.tp+"memo_create", sdk.ToolDef{
|
||||||
|
Name: p.tp + "memo_create",
|
||||||
|
Description: "创建一条备忘录。备忘录是纯记事(备注)用途,不会主动提醒,内容应包含完整信息供后续查阅。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"content": map[string]interface{}{"type": "string", "description": "备忘录内容"},
|
||||||
|
},
|
||||||
|
"required": []string{"content"},
|
||||||
|
},
|
||||||
|
}, p.handleMemoCreate)
|
||||||
|
|
||||||
|
s.RegisterTool(p.tp+"memo_list", sdk.ToolDef{
|
||||||
|
Name: p.tp + "memo_list",
|
||||||
|
Description: "列出所有备忘录,包含ID、内容和创建时间。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleMemoList)
|
||||||
|
|
||||||
|
s.RegisterTool(p.tp+"memo_delete", sdk.ToolDef{
|
||||||
|
Name: p.tp + "memo_delete",
|
||||||
|
Description: "删除指定ID的备忘录。",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"id": map[string]interface{}{"type": "integer", "description": "备忘录ID"},
|
||||||
|
},
|
||||||
|
"required": []string{"id"},
|
||||||
|
},
|
||||||
|
}, p.handleMemoDelete)
|
||||||
|
|
||||||
|
// 待办提醒:预动作注入未完成条数 + 周期主动提醒(备忘录不参与)
|
||||||
s.RegisterStage(sdk.StagePreAction, p.stagePreAction)
|
s.RegisterStage(sdk.StagePreAction, p.stagePreAction)
|
||||||
|
|
||||||
go p.periodicCheck()
|
go p.periodicCheck()
|
||||||
|
|
||||||
log.Printf("[%s] started, path=%s", p.name, p.filePath)
|
log.Printf("[%s] started, todos=%s memos=%s", p.name, p.todoPath, p.memoPath)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Stop() error {
|
func (p *Plugin) Stop() error {
|
||||||
close(p.stopCh)
|
close(p.stopCh)
|
||||||
p.save()
|
p.saveTodos()
|
||||||
|
p.saveMemos()
|
||||||
log.Printf("[%s] stopped", p.name)
|
log.Printf("[%s] stopped", p.name)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) load() {
|
func (p *Plugin) loadTodos() {
|
||||||
p.mu.Lock()
|
p.mu.Lock()
|
||||||
defer p.mu.Unlock()
|
defer p.mu.Unlock()
|
||||||
data, err := os.ReadFile(p.filePath)
|
data, err := os.ReadFile(p.todoPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
p.memos = nil
|
p.todos = []Todo{}
|
||||||
p.nextID = 1
|
p.nextTID = 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var store struct {
|
||||||
|
Todos []Todo `json:"todos"`
|
||||||
|
NextID int64 `json:"next_id"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(data, &store) != nil {
|
||||||
|
p.todos = []Todo{}
|
||||||
|
p.nextTID = 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.todos = store.Todos
|
||||||
|
p.nextTID = store.NextID
|
||||||
|
if p.todos == nil {
|
||||||
|
p.todos = []Todo{}
|
||||||
|
}
|
||||||
|
if p.nextTID < 1 {
|
||||||
|
p.nextTID = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) loadMemos() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
data, err := os.ReadFile(p.memoPath)
|
||||||
|
if err != nil {
|
||||||
|
p.memos = []Memo{}
|
||||||
|
p.nextMID = 1
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var store struct {
|
var store struct {
|
||||||
@ -108,66 +203,82 @@ func (p *Plugin) load() {
|
|||||||
NextID int64 `json:"next_id"`
|
NextID int64 `json:"next_id"`
|
||||||
}
|
}
|
||||||
if json.Unmarshal(data, &store) != nil {
|
if json.Unmarshal(data, &store) != nil {
|
||||||
p.memos = nil
|
p.memos = []Memo{}
|
||||||
p.nextID = 1
|
p.nextMID = 1
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
p.memos = store.Memos
|
p.memos = store.Memos
|
||||||
p.nextID = store.NextID
|
p.nextMID = store.NextID
|
||||||
if p.memos == nil {
|
if p.memos == nil {
|
||||||
p.memos = []Memo{}
|
p.memos = []Memo{}
|
||||||
}
|
}
|
||||||
if p.nextID < 1 {
|
if p.nextMID < 1 {
|
||||||
p.nextID = 1
|
p.nextMID = 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) save() {
|
func (p *Plugin) saveTodos() {
|
||||||
|
p.mu.RLock()
|
||||||
data, _ := json.MarshalIndent(map[string]interface{}{
|
data, _ := json.MarshalIndent(map[string]interface{}{
|
||||||
"memos": p.memos,
|
"todos": p.todos,
|
||||||
"next_id": p.nextID,
|
"next_id": p.nextTID,
|
||||||
}, "", " ")
|
}, "", " ")
|
||||||
os.WriteFile(p.filePath, data, 0644)
|
p.mu.RUnlock()
|
||||||
|
atomicWriteJSON(p.todoPath, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) pendingCount() int {
|
func (p *Plugin) saveMemos() {
|
||||||
|
p.mu.RLock()
|
||||||
|
data, _ := json.MarshalIndent(map[string]interface{}{
|
||||||
|
"memos": p.memos,
|
||||||
|
"next_id": p.nextMID,
|
||||||
|
}, "", " ")
|
||||||
|
p.mu.RUnlock()
|
||||||
|
atomicWriteJSON(p.memoPath, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 待办:未完成计数与提醒 ──
|
||||||
|
|
||||||
|
func (p *Plugin) pendingTodoCount() int {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
defer p.mu.RUnlock()
|
||||||
n := 0
|
n := 0
|
||||||
for _, m := range p.memos {
|
for _, t := range p.todos {
|
||||||
if !m.Done {
|
if !t.Done {
|
||||||
n++
|
n++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) pendingMemos() []Memo {
|
func (p *Plugin) pendingTodos() []Todo {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
defer p.mu.RUnlock()
|
||||||
var out []Memo
|
var out []Todo
|
||||||
for _, m := range p.memos {
|
for _, t := range p.todos {
|
||||||
if !m.Done {
|
if !t.Done {
|
||||||
out = append(out, m)
|
out = append(out, t)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stagePreAction 仅在待办未完成时注入上下文提示(备忘录不提示)
|
||||||
func (p *Plugin) stagePreAction(ctx *sdk.StageContext) error {
|
func (p *Plugin) stagePreAction(ctx *sdk.StageContext) error {
|
||||||
n := p.pendingCount()
|
n := p.pendingTodoCount()
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
ctx.Lock()
|
ctx.Lock()
|
||||||
ctx.ContextMsgs = append(ctx.ContextMsgs, map[string]interface{}{
|
ctx.ContextMsgs = append(ctx.ContextMsgs, map[string]interface{}{
|
||||||
"role": "system",
|
"role": "system",
|
||||||
"content": fmt.Sprintf("目前有%d条备忘未完成,调用%slist工具读取具体内容", n, p.tp),
|
"content": fmt.Sprintf("目前有%d条待办未完成,调用%s todo_list 工具读取具体内容", n, p.tp),
|
||||||
})
|
})
|
||||||
ctx.Unlock()
|
ctx.Unlock()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// periodicCheck 周期主动提醒未完成待办(备忘录不提醒)
|
||||||
func (p *Plugin) periodicCheck() {
|
func (p *Plugin) periodicCheck() {
|
||||||
ticker := time.NewTicker(5 * time.Minute)
|
ticker := time.NewTicker(5 * time.Minute)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@ -176,19 +287,125 @@ func (p *Plugin) periodicCheck() {
|
|||||||
case <-p.stopCh:
|
case <-p.stopCh:
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
n := p.pendingCount()
|
n := p.pendingTodoCount()
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if p.sdk != nil {
|
if p.sdk != nil {
|
||||||
p.sdk.InjectInterruptText(p.name, p.name,
|
// NoMemory:这是定时提醒,不是记忆内容。
|
||||||
fmt.Sprintf("注意,你还有%d条备忘未标记完成,请检查", n))
|
p.sdk.InjectInterruptTextOpts(p.name, p.name,
|
||||||
|
fmt.Sprintf("注意,你还有%d条待办未完成,请检查", n), sdk.InjectOptions{NoMemory: true})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) handleCreate(args map[string]interface{}) (interface{}, error) {
|
// ── 待办工具 ──
|
||||||
|
|
||||||
|
func (p *Plugin) handleTodoAdd(args map[string]interface{}) (interface{}, error) {
|
||||||
|
content, _ := args["content"].(string)
|
||||||
|
if content == "" {
|
||||||
|
return errorResult("content is required"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
todo := Todo{
|
||||||
|
ID: p.nextTID,
|
||||||
|
Content: content,
|
||||||
|
CreatedAt: time.Now().Unix(),
|
||||||
|
Done: false,
|
||||||
|
}
|
||||||
|
p.nextTID++
|
||||||
|
p.todos = append(p.todos, todo)
|
||||||
|
p.mu.Unlock()
|
||||||
|
p.saveTodos()
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("待办已添加 (ID: %d)", todo.ID),
|
||||||
|
"id": todo.ID,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleTodoComplete(args map[string]interface{}) (interface{}, error) {
|
||||||
|
id, ok := args["id"].(float64)
|
||||||
|
if !ok {
|
||||||
|
return errorResult("id is required"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
found := false
|
||||||
|
for i := range p.todos {
|
||||||
|
if p.todos[i].ID == int64(id) && !p.todos[i].Done {
|
||||||
|
p.todos[i].Done = true
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
return errorResult(fmt.Sprintf("未找到未完成的待办 ID: %d", int64(id))), nil
|
||||||
|
}
|
||||||
|
p.saveTodos()
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("待办 %d 已标记为完成", int64(id)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleTodoList(args map[string]interface{}) (interface{}, error) {
|
||||||
|
todos := p.pendingTodos()
|
||||||
|
if len(todos) == 0 {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": "暂无未完成的待办",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var sb strings.Builder
|
||||||
|
for i, t := range todos {
|
||||||
|
ts := time.Unix(t.CreatedAt, 0).Format("01-02 15:04")
|
||||||
|
if i > 0 {
|
||||||
|
sb.WriteString("\n")
|
||||||
|
}
|
||||||
|
sb.WriteString(fmt.Sprintf("%d. [ID:%d] %s — %s", i+1, t.ID, t.Content, ts))
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": sb.String(),
|
||||||
|
"count": len(todos),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleTodoDelete(args map[string]interface{}) (interface{}, error) {
|
||||||
|
id, ok := args["id"].(float64)
|
||||||
|
if !ok {
|
||||||
|
return errorResult("id is required"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
found := false
|
||||||
|
for i := range p.todos {
|
||||||
|
if p.todos[i].ID == int64(id) {
|
||||||
|
p.todos = append(p.todos[:i], p.todos[i+1:]...)
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
return errorResult(fmt.Sprintf("未找到待办 ID: %d", int64(id))), nil
|
||||||
|
}
|
||||||
|
p.saveTodos()
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("待办 %d 已删除", int64(id)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 备忘工具 ──
|
||||||
|
|
||||||
|
func (p *Plugin) handleMemoCreate(args map[string]interface{}) (interface{}, error) {
|
||||||
content, _ := args["content"].(string)
|
content, _ := args["content"].(string)
|
||||||
if content == "" {
|
if content == "" {
|
||||||
return errorResult("content is required"), nil
|
return errorResult("content is required"), nil
|
||||||
@ -196,23 +413,22 @@ func (p *Plugin) handleCreate(args map[string]interface{}) (interface{}, error)
|
|||||||
|
|
||||||
p.mu.Lock()
|
p.mu.Lock()
|
||||||
memo := Memo{
|
memo := Memo{
|
||||||
ID: p.nextID,
|
ID: p.nextMID,
|
||||||
Content: content,
|
Content: content,
|
||||||
CreatedAt: time.Now().Unix(),
|
CreatedAt: time.Now().Unix(),
|
||||||
Done: false,
|
|
||||||
}
|
}
|
||||||
p.nextID++
|
p.nextMID++
|
||||||
p.memos = append(p.memos, memo)
|
p.memos = append(p.memos, memo)
|
||||||
p.mu.Unlock()
|
p.mu.Unlock()
|
||||||
p.save()
|
p.saveMemos()
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"content": fmt.Sprintf("备忘已创建 (ID: %d)", memo.ID),
|
"content": fmt.Sprintf("备忘录已创建 (ID: %d)", memo.ID),
|
||||||
"id": memo.ID,
|
"id": memo.ID,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) handleComplete(args map[string]interface{}) (interface{}, error) {
|
func (p *Plugin) handleMemoDelete(args map[string]interface{}) (interface{}, error) {
|
||||||
id, ok := args["id"].(float64)
|
id, ok := args["id"].(float64)
|
||||||
if !ok {
|
if !ok {
|
||||||
return errorResult("id is required"), nil
|
return errorResult("id is required"), nil
|
||||||
@ -221,8 +437,8 @@ func (p *Plugin) handleComplete(args map[string]interface{}) (interface{}, error
|
|||||||
p.mu.Lock()
|
p.mu.Lock()
|
||||||
found := false
|
found := false
|
||||||
for i := range p.memos {
|
for i := range p.memos {
|
||||||
if p.memos[i].ID == int64(id) && !p.memos[i].Done {
|
if p.memos[i].ID == int64(id) {
|
||||||
p.memos[i].Done = true
|
p.memos = append(p.memos[:i], p.memos[i+1:]...)
|
||||||
found = true
|
found = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -230,30 +446,33 @@ func (p *Plugin) handleComplete(args map[string]interface{}) (interface{}, error
|
|||||||
p.mu.Unlock()
|
p.mu.Unlock()
|
||||||
|
|
||||||
if !found {
|
if !found {
|
||||||
return errorResult(fmt.Sprintf("未找到未完成的备忘 ID: %d", int64(id))), nil
|
return errorResult(fmt.Sprintf("未找到备忘录 ID: %d", int64(id))), nil
|
||||||
}
|
}
|
||||||
p.save()
|
p.saveMemos()
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"content": fmt.Sprintf("备忘 %d 已标记为完成", int64(id)),
|
"content": fmt.Sprintf("备忘录 %d 已删除", int64(id)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) handleList(args map[string]interface{}) (interface{}, error) {
|
func (p *Plugin) handleMemoList(args map[string]interface{}) (interface{}, error) {
|
||||||
memos := p.pendingMemos()
|
p.mu.RLock()
|
||||||
|
memos := append([]Memo{}, p.memos...)
|
||||||
|
p.mu.RUnlock()
|
||||||
|
|
||||||
if len(memos) == 0 {
|
if len(memos) == 0 {
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"content": "暂无未完成的备忘",
|
"content": "暂无备忘录",
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
for i, m := range memos {
|
for i, m := range memos {
|
||||||
t := time.Unix(m.CreatedAt, 0).Format("01-02 15:04")
|
ts := time.Unix(m.CreatedAt, 0).Format("01-02 15:04")
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
}
|
}
|
||||||
sb.WriteString(fmt.Sprintf("%d. [ID:%d] %s — %s", i+1, m.ID, m.Content, t))
|
sb.WriteString(fmt.Sprintf("%d. [ID:%d] %s — %s", i+1, m.ID, m.Content, ts))
|
||||||
}
|
}
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
@ -269,6 +488,25 @@ func errorResult(msg string) map[string]interface{} {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name, stopCh: make(chan struct{})}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupData 卸载时清理数据文件(待办 + 备忘)
|
||||||
|
func (p *Plugin) cleanupData() {
|
||||||
|
if p.todoPath != "" {
|
||||||
|
os.Remove(p.todoPath)
|
||||||
|
}
|
||||||
|
if p.memoPath != "" {
|
||||||
|
os.Remove(p.memoPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// atomicWriteJSON 原子写 JSON:先写临时文件再 rename,避免进程崩溃截断数据文件。
|
||||||
|
func atomicWriteJSON(path string, data []byte) error {
|
||||||
|
tmp := path + ".tmp"
|
||||||
|
if err := os.WriteFile(tmp, data, 0644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, path)
|
||||||
}
|
}
|
||||||
|
|||||||
7
example/music/go.mod
Normal file
7
example/music/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module music
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/music/main.go
Normal file
11
example/music/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
15
example/music/plg.json
Normal file
15
example/music/plg.json
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "music",
|
||||||
|
"name_zh": "音乐搜索",
|
||||||
|
"name_en": "Music Search",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "音乐搜索插件,支持搜索歌曲和查看歌词(基于网易云音乐)",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": ["music", "song", "lyrics", "网易云"],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
327
example/music/plugin.go
Normal file
327
example/music/plugin.go
Normal file
@ -0,0 +1,327 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Plugin struct {
|
||||||
|
name string
|
||||||
|
sdk *sdk.PluginSDK
|
||||||
|
cli *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type searchResp struct {
|
||||||
|
Result *struct {
|
||||||
|
Songs []songItem `json:"songs"`
|
||||||
|
SongCount int `json:"songCount"`
|
||||||
|
} `json:"result"`
|
||||||
|
Code int `json:"code"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type songItem struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Artists []artist `json:"artists"`
|
||||||
|
Album albumInfo `json:"album"`
|
||||||
|
Duration int `json:"duration"`
|
||||||
|
Mvid int `json:"mvid"`
|
||||||
|
Fee int `json:"fee"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type artist struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type albumInfo struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type lyricResp struct {
|
||||||
|
Lrc *lyricData `json:"lrc"`
|
||||||
|
TLrc *lyricData `json:"tlyric"`
|
||||||
|
Code int `json:"code"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type lyricData struct {
|
||||||
|
Lyric string `json:"lyric"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
|
s.SetAutoRestart(true)
|
||||||
|
p.sdk = s
|
||||||
|
p.cli = &http.Client{Timeout: 15 * time.Second}
|
||||||
|
|
||||||
|
s.RegisterTool(p.name+"_search", sdk.ToolDef{
|
||||||
|
Name: p.name + "_search",
|
||||||
|
Description: "搜索歌曲,通过关键词查找音乐,返回歌曲列表",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"keyword": map[string]interface{}{
|
||||||
|
"type": "string",
|
||||||
|
"description": "搜索关键词,如歌曲名、歌手名",
|
||||||
|
},
|
||||||
|
"limit": map[string]interface{}{
|
||||||
|
"type": "integer",
|
||||||
|
"description": "返回结果数量(1-50),默认10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": []string{"keyword"},
|
||||||
|
},
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct{ Content string }
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Content != "" {
|
||||||
|
return r.Content
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
|
}, p.handleSearch)
|
||||||
|
|
||||||
|
s.RegisterTool(p.name+"_lyrics", sdk.ToolDef{
|
||||||
|
Name: p.name + "_lyrics",
|
||||||
|
Description: "获取歌曲歌词,通过歌曲ID查看歌词内容",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"song_id": map[string]interface{}{
|
||||||
|
"type": "integer",
|
||||||
|
"description": "歌曲ID(从搜索结果的 id 字段获取)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": []string{"song_id"},
|
||||||
|
},
|
||||||
|
}, p.handleLyrics)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Stop() error { return nil }
|
||||||
|
|
||||||
|
func (p *Plugin) neRequest(path string, params map[string]string) ([]byte, error) {
|
||||||
|
base := "https://music.163.com/api" + path
|
||||||
|
reqURL := base + "?" + urlValues(params).Encode()
|
||||||
|
req, err := http.NewRequest("GET", reqURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||||
|
req.Header.Set("Referer", "https://music.163.com/")
|
||||||
|
resp, err := p.cli.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
return io.ReadAll(resp.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlValues(m map[string]string) url.Values {
|
||||||
|
v := url.Values{}
|
||||||
|
for k, val := range m {
|
||||||
|
v.Set(k, val)
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleSearch(args map[string]interface{}) (interface{}, error) {
|
||||||
|
keyword, _ := args["keyword"].(string)
|
||||||
|
keyword = strings.TrimSpace(keyword)
|
||||||
|
if keyword == "" {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": "请输入搜索关键词",
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
limit := 10
|
||||||
|
if v, ok := args["limit"].(float64); ok {
|
||||||
|
limit = int(v)
|
||||||
|
if limit < 1 {
|
||||||
|
limit = 1
|
||||||
|
}
|
||||||
|
if limit > 50 {
|
||||||
|
limit = 50
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := p.neRequest("/search/get", map[string]string{
|
||||||
|
"s": keyword,
|
||||||
|
"type": "1",
|
||||||
|
"limit": fmt.Sprint(limit),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("搜索失败:%v", err),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp searchResp
|
||||||
|
if err := json.Unmarshal(body, &resp); err != nil {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("解析响应失败:%v", err),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.Code != 200 || resp.Result == nil {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("搜索失败,响应码:%d", resp.Code),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
songs := resp.Result.Songs
|
||||||
|
if len(songs) == 0 {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("未找到与「%s」相关的歌曲", keyword),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
lines = append(lines, fmt.Sprintf("找到 %d 首与「%s」相关的歌曲:\n", resp.Result.SongCount, keyword))
|
||||||
|
for i, s := range songs {
|
||||||
|
var artists []string
|
||||||
|
for _, a := range s.Artists {
|
||||||
|
artists = append(artists, a.Name)
|
||||||
|
}
|
||||||
|
dur := time.Duration(s.Duration) * time.Millisecond
|
||||||
|
minutes := int(dur.Minutes())
|
||||||
|
seconds := int(dur.Seconds()) % 60
|
||||||
|
lines = append(lines, fmt.Sprintf("%d. %s - %s [%02d:%02d] (ID: %d)",
|
||||||
|
i+1, s.Name, strings.Join(artists, "/"), minutes, seconds, s.ID))
|
||||||
|
}
|
||||||
|
|
||||||
|
type songResult struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Artists []string `json:"artists"`
|
||||||
|
Album string `json:"album"`
|
||||||
|
Duration int `json:"duration"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var results []songResult
|
||||||
|
for _, s := range songs {
|
||||||
|
var artists []string
|
||||||
|
for _, a := range s.Artists {
|
||||||
|
artists = append(artists, a.Name)
|
||||||
|
}
|
||||||
|
results = append(results, songResult{
|
||||||
|
ID: s.ID,
|
||||||
|
Name: s.Name,
|
||||||
|
Artists: artists,
|
||||||
|
Album: s.Album.Name,
|
||||||
|
Duration: s.Duration,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": strings.Join(lines, "\n"),
|
||||||
|
"songs": results,
|
||||||
|
"total": resp.Result.SongCount,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleLyrics(args map[string]interface{}) (interface{}, error) {
|
||||||
|
songID, ok := args["song_id"].(float64)
|
||||||
|
if !ok {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": "请提供有效的歌曲ID",
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
id := int64(songID)
|
||||||
|
body, err := p.neRequest("/song/lyric", map[string]string{
|
||||||
|
"id": fmt.Sprint(id),
|
||||||
|
"lv": "-1",
|
||||||
|
"kv": "-1",
|
||||||
|
"tv": "-1",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("获取歌词失败:%v", err),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp lyricResp
|
||||||
|
if err := json.Unmarshal(body, &resp); err != nil {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("解析歌词失败:%v", err),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.Code != 200 {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("获取歌词失败,响应码:%d", resp.Code),
|
||||||
|
"isError": true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
lyric := ""
|
||||||
|
if resp.Lrc != nil {
|
||||||
|
lyric = resp.Lrc.Lyric
|
||||||
|
}
|
||||||
|
|
||||||
|
if lyric == "" {
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("歌曲 %d 暂无歌词", id),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up lyrics metadata lines and limit length
|
||||||
|
lyric = cleanLyrics(lyric)
|
||||||
|
if len(lyric) > 3000 {
|
||||||
|
lyric = lyric[:3000] + "\n...(歌词过长已截断)"
|
||||||
|
}
|
||||||
|
|
||||||
|
tLyric := ""
|
||||||
|
if resp.TLrc != nil && resp.TLrc.Lyric != "" {
|
||||||
|
tLyric = cleanLyrics(resp.TLrc.Lyric)
|
||||||
|
if len(tLyric) > 1000 {
|
||||||
|
tLyric = tLyric[:1000] + "\n...(翻译过长已截断)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result := fmt.Sprintf("歌词:\n%s", lyric)
|
||||||
|
if tLyric != "" {
|
||||||
|
result += fmt.Sprintf("\n翻译:\n%s", tLyric)
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": result,
|
||||||
|
"lyric": lyric,
|
||||||
|
"tlyric": tLyric,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanLyrics(l string) string {
|
||||||
|
lines := strings.Split(l, "\n")
|
||||||
|
var cleaned []string
|
||||||
|
for _, line := range lines {
|
||||||
|
// Skip metadata lines like [ti:...], [ar:...], [al:...], [by:...], [offset:...]
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
if trimmed == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cleaned = append(cleaned, line)
|
||||||
|
}
|
||||||
|
return strings.Join(cleaned, "\n")
|
||||||
|
}
|
||||||
@ -2,6 +2,6 @@ module ocr
|
|||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0-20260708004841-e9bdcf9304b0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/ocr/main.go
Normal file
11
example/ocr/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -7,5 +7,9 @@
|
|||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["ocr", "image", "text"],
|
"tags": ["ocr", "image", "text"],
|
||||||
"targets": "linux/amd64"
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
@ -38,6 +39,17 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
"language": map[string]interface{}{"type": "string", "description": "识别语言,默认 chi_sim+eng(中文简体+英文),可选 chi_sim / eng / chi_sim+eng"},
|
"language": map[string]interface{}{"type": "string", "description": "识别语言,默认 chi_sim+eng(中文简体+英文),可选 chi_sim / eng / chi_sim+eng"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
var r struct{ Text string }
|
||||||
|
if json.Unmarshal([]byte(output), &r) == nil && r.Text != "" {
|
||||||
|
return r.Text
|
||||||
|
}
|
||||||
|
var r2 struct{ Content string }
|
||||||
|
if json.Unmarshal([]byte(output), &r2) == nil && r2.Content != "" {
|
||||||
|
return r2.Content
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
}, p.handleOcrImage)
|
}, p.handleOcrImage)
|
||||||
|
|
||||||
log.Printf("[%s] plugin started", p.name)
|
log.Printf("[%s] plugin started", p.name)
|
||||||
@ -128,7 +140,6 @@ func (p *Plugin) handleOcrImage(args map[string]interface{}) (interface{}, error
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
|
||||||
return &Plugin{name: name}, nil
|
return &Plugin{name: name}, nil
|
||||||
}
|
}
|
||||||
@ -2,6 +2,6 @@ module qq
|
|||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0-20260708004841-e9bdcf9304b0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/qq/main.go
Normal file
11
example/qq/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -2,10 +2,17 @@
|
|||||||
"name": "qq",
|
"name": "qq",
|
||||||
"name_zh": "QQ消息",
|
"name_zh": "QQ消息",
|
||||||
"name_en": "qq",
|
"name_en": "qq",
|
||||||
"version": "1.0.0",
|
"version": "1.4.0",
|
||||||
"description": "QQ 消息收发插件,通过 NapCat 协议桥接",
|
"description": "QQ 消息收发插件,通过 NapCat 协议桥接",
|
||||||
"author": "HomeAgent",
|
"author": "HomeAgent",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["qq", "messaging"],
|
"tags": [
|
||||||
"targets": "linux/amd64"
|
"qq",
|
||||||
}
|
"messaging"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": false,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
2152
example/qq/plugin.go
2152
example/qq/plugin.go
File diff suppressed because it is too large
Load Diff
@ -1,101 +0,0 @@
|
|||||||
/* Code generated by cmd/cgo; DO NOT EDIT. */
|
|
||||||
|
|
||||||
/* package qq */
|
|
||||||
|
|
||||||
|
|
||||||
#line 1 "cgo-builtin-export-prolog"
|
|
||||||
|
|
||||||
#include <stddef.h>
|
|
||||||
|
|
||||||
#ifndef GO_CGO_EXPORT_PROLOGUE_H
|
|
||||||
#define GO_CGO_EXPORT_PROLOGUE_H
|
|
||||||
|
|
||||||
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
||||||
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
|
|
||||||
extern size_t _GoStringLen(_GoString_ s);
|
|
||||||
extern const char *_GoStringPtr(_GoString_ s);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Start of preamble from import "C" comments. */
|
|
||||||
|
|
||||||
|
|
||||||
#line 3 "z_bridge_gen.go"
|
|
||||||
|
|
||||||
#include <stdlib.h>
|
|
||||||
int ha_dispatch(int method_id, void* core_api, char* s1, char* s2, char* s3, int i1, int i2, char** result, char** error);
|
|
||||||
|
|
||||||
#line 1 "cgo-generated-wrapper"
|
|
||||||
|
|
||||||
|
|
||||||
/* End of preamble from import "C" comments. */
|
|
||||||
|
|
||||||
|
|
||||||
/* Start of boilerplate cgo prologue. */
|
|
||||||
#line 1 "cgo-gcc-export-header-prolog"
|
|
||||||
|
|
||||||
#ifndef GO_CGO_PROLOGUE_H
|
|
||||||
#define GO_CGO_PROLOGUE_H
|
|
||||||
|
|
||||||
typedef signed char GoInt8;
|
|
||||||
typedef unsigned char GoUint8;
|
|
||||||
typedef short GoInt16;
|
|
||||||
typedef unsigned short GoUint16;
|
|
||||||
typedef int GoInt32;
|
|
||||||
typedef unsigned int GoUint32;
|
|
||||||
typedef long long GoInt64;
|
|
||||||
typedef unsigned long long GoUint64;
|
|
||||||
typedef GoInt64 GoInt;
|
|
||||||
typedef GoUint64 GoUint;
|
|
||||||
typedef size_t GoUintptr;
|
|
||||||
typedef float GoFloat32;
|
|
||||||
typedef double GoFloat64;
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
|
|
||||||
#include <complex.h>
|
|
||||||
typedef _Fcomplex GoComplex64;
|
|
||||||
typedef _Dcomplex GoComplex128;
|
|
||||||
#else
|
|
||||||
#include <complex>
|
|
||||||
typedef std::complex<float> GoComplex64;
|
|
||||||
typedef std::complex<double> GoComplex128;
|
|
||||||
#endif
|
|
||||||
#else
|
|
||||||
typedef float _Complex GoComplex64;
|
|
||||||
typedef double _Complex GoComplex128;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*
|
|
||||||
static assertion to make sure the file is being used on architecture
|
|
||||||
at least with matching size of GoInt.
|
|
||||||
*/
|
|
||||||
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
|
|
||||||
|
|
||||||
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
||||||
typedef _GoString_ GoString;
|
|
||||||
#endif
|
|
||||||
typedef void *GoMap;
|
|
||||||
typedef void *GoChan;
|
|
||||||
typedef struct { void *t; void *v; } GoInterface;
|
|
||||||
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* End of boilerplate cgo prologue. */
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
extern int go_init_plugin(char* name, char* configJSON, char** errorOut);
|
|
||||||
extern int go_start_plugin(void* coreAPIptr, int coreVersion, char** errorOut);
|
|
||||||
extern int go_stop_plugin(char** errorOut);
|
|
||||||
extern int go_invoke_tool(char* name, char* argsJSON, char** resultOut, char** errorOut);
|
|
||||||
extern int go_invoke_stage(char* stage, char* ctxJSON, char** errorOut);
|
|
||||||
extern int go_invoke_output(char* channel, char* msgType, char* payloadJSON, char** errorOut);
|
|
||||||
extern void go_free_string(char* ptr);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
204
example/qq/plugin_test.go
Normal file
204
example/qq/plugin_test.go
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newPermissionTestPlugin(t *testing.T) *Plugin {
|
||||||
|
t.Helper()
|
||||||
|
instance, err := NewPluginFactory("qq", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return instance.(*Plugin)
|
||||||
|
}
|
||||||
|
|
||||||
|
func toolCallContext(name string, args map[string]interface{}) *sdk.StageContext {
|
||||||
|
return &sdk.StageContext{ToolCalls: []sdk.ToolCall{{Name: name, Arguments: args}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOwnerBypassesQQPermissionBoundary(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
ctx := toolCallContext("calendar_list", nil)
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("owner call rejected: %s", *ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrivateResourceCannotBeAllowlisted(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.privateToolAllowlist = append(p.privateToolAllowlist, "calendar_*")
|
||||||
|
p.auth = qqAuthContext{active: true, userID: 10001}
|
||||||
|
ctx := toolCallContext("calendar_list", nil)
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response == nil || !strings.Contains(*ctx.Response, "私人资源工具") {
|
||||||
|
t.Fatalf("expected private-resource denial, got %#v", ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNonOwnerQQHistoryIsScopedToCurrentGroup(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.auth = qqAuthContext{active: true, messageID: 88, userID: 10001, groupID: 20002, isGroup: true}
|
||||||
|
|
||||||
|
ctx := toolCallContext("qq_get_history", map[string]interface{}{"group_id": int64(20003)})
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response == nil || !strings.Contains(*ctx.Response, "当前 QQ 会话") {
|
||||||
|
t.Fatalf("cross-group history not rejected: %#v", ctx.Response)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx = toolCallContext("qq_get_history", map[string]interface{}{"group_id": int64(20002)})
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("current-group history rejected: %s", *ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnmatchedQQInputIsDowngraded(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
ctx := &sdk.StageContext{
|
||||||
|
RawMessage: "来自未知事件(message_id=404)",
|
||||||
|
Extra: map[string]interface{}{"input_source": "qq"},
|
||||||
|
}
|
||||||
|
if err := p.onInputAuthContext(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !p.auth.active || p.auth.owner || p.auth.userID != 0 {
|
||||||
|
t.Fatalf("unmatched input reused prior privilege: %+v", p.auth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDuplicateQQOutputIsStopped(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.maxDuplicateSend = 1
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
args := map[string]interface{}{"payload": "same", "type": "text", "meta": `{"user_id":123}`}
|
||||||
|
|
||||||
|
ctx := toolCallContext("output_send__qq", args)
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("first send rejected: %s", *ctx.Response)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx = toolCallContext("output_send__qq", args)
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response == nil || !strings.Contains(*ctx.Response, "循环保险") {
|
||||||
|
t.Fatalf("duplicate send not stopped: %#v", ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupAndUserRouteAddsLeadingMention(t *testing.T) {
|
||||||
|
var path string
|
||||||
|
var request map[string]interface{}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path = r.URL.Path
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
t.Errorf("decode request: %v", err)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"status":"ok","retcode":0,"data":{"message_id":1}}`))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.napcatURL = server.URL
|
||||||
|
p.httpClient = server.Client()
|
||||||
|
_, err := p.handleChannelOutput(map[string]interface{}{
|
||||||
|
"payload": "hello",
|
||||||
|
"type": "text",
|
||||||
|
"meta": `{"group_id":20002,"user_id":10001}`,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if path != "/send_group_msg" {
|
||||||
|
t.Fatalf("path=%q, want /send_group_msg", path)
|
||||||
|
}
|
||||||
|
segments, ok := request["message"].([]interface{})
|
||||||
|
if !ok || len(segments) < 2 {
|
||||||
|
t.Fatalf("message is not a segment array: %#v", request["message"])
|
||||||
|
}
|
||||||
|
mention, _ := segments[0].(map[string]interface{})
|
||||||
|
data, _ := mention["data"].(map[string]interface{})
|
||||||
|
if mention["type"] != "at" || data["qq"] != "10001" {
|
||||||
|
t.Fatalf("leading mention=%#v", mention)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回归:循环保险曾按“总数”拦截,导致参数不同且必需的调用被误杀。
|
||||||
|
// 现在只拦参数完全相同的重复调用。
|
||||||
|
func TestDistinctQQOutputsAreNotTreatedAsDuplicates(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
// maxDuplicateSend 默认 1:同一条消息重复才会被拦,不同消息必须全部放行。
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
ctx := toolCallContext("output_send__qq", map[string]interface{}{
|
||||||
|
"payload": fmt.Sprintf("message-%d", i),
|
||||||
|
"type": "text",
|
||||||
|
"meta": `{"user_id":123}`,
|
||||||
|
})
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("distinct message %d was blocked: %s", i, *ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDistinctNecessaryToolCallsAreNotBlocked(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
// 旧实现 maxQQToolCalls=32 会在第 33 个不同参数的必需调用处误拦。
|
||||||
|
for i := 0; i < 50; i++ {
|
||||||
|
ctx := toolCallContext("cmd_run", map[string]interface{}{"command": fmt.Sprintf("cmd-%d", i)})
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("necessary tool call %d was blocked: %s", i, *ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestZeroLimitsMeanUnlimited(t *testing.T) {
|
||||||
|
p := newPermissionTestPlugin(t)
|
||||||
|
p.maxQQOutputCalls = 0
|
||||||
|
p.maxDuplicateSend = 0
|
||||||
|
p.maxQQToolCalls = 0
|
||||||
|
p.auth = qqAuthContext{active: true, owner: true, userID: 2198972886}
|
||||||
|
for i := 0; i < 30; i++ {
|
||||||
|
ctx := toolCallContext("output_send__qq", map[string]interface{}{
|
||||||
|
"payload": "same-content",
|
||||||
|
"type": "text",
|
||||||
|
"meta": `{"user_id":123}`,
|
||||||
|
})
|
||||||
|
if err := p.beforeToolcall(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ctx.Response != nil {
|
||||||
|
t.Fatalf("0 should mean unlimited, blocked at %d: %s", i, *ctx.Response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
153
example/recoverydiag/diag_test.go
Normal file
153
example/recoverydiag/diag_test.go
Normal file
@ -0,0 +1,153 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
var realCfg = "/home/newqqagent/config.db"
|
||||||
|
var realLog = "/home/newqqagent/log"
|
||||||
|
|
||||||
|
func TestDiagTriage(t *testing.T) {
|
||||||
|
p := &Plugin{name: "recoverydiag"}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
args map[string]interface{}
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"signal", map[string]interface{}{"exit_code": 0, "signal": "SIGSEGV"}, "process_death"},
|
||||||
|
{"oom", map[string]interface{}{"exit_code": 0, "signal": "SIGKILL", "crash_reason": "oom-kill"}, "process_starvation"},
|
||||||
|
{"nonzero", map[string]interface{}{"exit_code": 1}, "process_death"},
|
||||||
|
{"healthy", map[string]interface{}{"exit_code": 0}, "normal_stop"},
|
||||||
|
{"alive", map[string]interface{}{"still_alive": true, "signal": "SIGKILL"}, "config_unreachable"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
r, _ := p.handleTriage(c.args)
|
||||||
|
m, ok := r.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("%s: not a map", c.name)
|
||||||
|
}
|
||||||
|
if got, _ := m["class"].(string); got != c.want {
|
||||||
|
t.Errorf("%s: class = %q, want %q", c.name, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiagDB(t *testing.T) {
|
||||||
|
if _, err := os.Stat(realCfg); err != nil {
|
||||||
|
t.Skip("config.db not present, skipping")
|
||||||
|
}
|
||||||
|
p := &Plugin{name: "recoverydiag"}
|
||||||
|
r, err := p.handleDB(map[string]interface{}{"db_path": realCfg})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("handleDB: %v", err)
|
||||||
|
}
|
||||||
|
m := r.(map[string]interface{})
|
||||||
|
t.Logf("integrity=%v sources=%v verdict=%v summary=%v", m["integrity"], m["source_count"], m["verdict"], m["summary"])
|
||||||
|
if m["integrity"] != "ok" {
|
||||||
|
t.Errorf("integrity = %v, want ok", m["integrity"])
|
||||||
|
}
|
||||||
|
if m["source_count"] == 0 {
|
||||||
|
t.Errorf("source_count == 0, expected LLM sources")
|
||||||
|
}
|
||||||
|
if got, _ := m["source_failed"].(int); got != 0 {
|
||||||
|
t.Errorf("source_failed = %d, want 0 (all sources OK): %v", got, m["missing_fields"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiagLogScan(t *testing.T) {
|
||||||
|
if _, err := os.Stat(realLog); err != nil {
|
||||||
|
t.Skip("log dir not present, skipping")
|
||||||
|
}
|
||||||
|
p := &Plugin{name: "recoverydiag"}
|
||||||
|
r, err := p.handleLogScan(map[string]interface{}{
|
||||||
|
"log_dir": realLog,
|
||||||
|
"since_minutes": 60 * 24 * 3,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("handleLogScan: %v", err)
|
||||||
|
}
|
||||||
|
m := r.(map[string]interface{})
|
||||||
|
t.Logf("matched=%v counts=%v dominant=%v conclusion=%v", m["lines_matched"], m["counts"], m["dominant"], m["conclusion"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiagDelta(t *testing.T) {
|
||||||
|
base := t.TempDir()
|
||||||
|
cur := t.TempDir()
|
||||||
|
sub := filepath.Join(base, "sub")
|
||||||
|
os.MkdirAll(sub, 0755)
|
||||||
|
|
||||||
|
// modified: same path, different content
|
||||||
|
os.WriteFile(filepath.Join(base, "a.txt"), []byte("hello"), 0644)
|
||||||
|
os.WriteFile(filepath.Join(cur, "a.txt"), []byte("world!"), 0644)
|
||||||
|
// created
|
||||||
|
os.WriteFile(filepath.Join(cur, "b.txt"), []byte("new"), 0644)
|
||||||
|
// deleted
|
||||||
|
os.WriteFile(filepath.Join(base, "gone.txt"), []byte("bye"), 0644)
|
||||||
|
// unchanged
|
||||||
|
os.WriteFile(filepath.Join(base, "same.txt"), []byte("x"), 0644)
|
||||||
|
os.WriteFile(filepath.Join(cur, "same.txt"), []byte("x"), 0644)
|
||||||
|
|
||||||
|
p := &Plugin{name: "recoverydiag"}
|
||||||
|
r, err := p.handleDelta(map[string]interface{}{"baseline_dir": base, "current_dir": cur})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("handleDelta: %v", err)
|
||||||
|
}
|
||||||
|
m := r.(map[string]interface{})
|
||||||
|
sum := m["summary"].(map[string]int)
|
||||||
|
t.Logf("summary=%v total=%v", sum, m["total_diff"])
|
||||||
|
if sum["created"] != 1 || sum["deleted"] != 1 || sum["modified"] != 1 {
|
||||||
|
t.Errorf("summary = %v, want modified=1 created=1 deleted=1", sum)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiagLoc(t *testing.T) {
|
||||||
|
p := &Plugin{name: "recoverydiag"}
|
||||||
|
r, _ := p.handleLoc(map[string]interface{}{
|
||||||
|
"triage": map[string]interface{}{"class": "process_death", "verdict": "down"},
|
||||||
|
"db": map[string]interface{}{"verdict": "ok"},
|
||||||
|
"log_scan": map[string]interface{}{"dominant": "panic"},
|
||||||
|
"delta": map[string]interface{}{"summary": map[string]interface{}{"created": 0, "modified": 0, "deleted": 0}},
|
||||||
|
})
|
||||||
|
m := r.(map[string]interface{})
|
||||||
|
// 经 JSON 往返,模拟内核把子结论以 JSON 传给 diag_loc 的真实路径
|
||||||
|
raw, _ := json.Marshal(m)
|
||||||
|
var dec map[string]interface{}
|
||||||
|
json.Unmarshal(raw, &dec)
|
||||||
|
hs := dec["ranked_hypotheses"].([]interface{})
|
||||||
|
if len(hs) == 0 {
|
||||||
|
t.Fatal("no hypotheses")
|
||||||
|
}
|
||||||
|
top := hs[0].(map[string]interface{})
|
||||||
|
t.Logf("top cause=%v conf=%v rec=%v", top["cause"], top["confidence"], top["recommendation"])
|
||||||
|
if top["cause"] != "code_panic_loop" {
|
||||||
|
t.Errorf("expected code_panic_loop, got %v", top["cause"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiagLocPersist(t *testing.T) {
|
||||||
|
kb := filepath.Join(t.TempDir(), "recovery_kb")
|
||||||
|
p := &Plugin{name: "recoverydiag", dataDir: filepath.Dir(kb)}
|
||||||
|
args := map[string]interface{}{
|
||||||
|
"persist": true,
|
||||||
|
"triage": map[string]interface{}{"class": "process_death", "verdict": "down"},
|
||||||
|
"db": map[string]interface{}{"verdict": "ok"},
|
||||||
|
"log_scan": map[string]interface{}{"dominant": "panic"},
|
||||||
|
"delta": map[string]interface{}{"summary": map[string]interface{}{"created": 0, "modified": 0, "deleted": 0}},
|
||||||
|
}
|
||||||
|
if _, err := p.handleLoc(args); err != nil {
|
||||||
|
t.Fatalf("handleLoc: %v", err)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(kb)
|
||||||
|
if err != nil || len(entries) == 0 {
|
||||||
|
t.Fatalf("expected persisted diag json, got err=%v entries=%v", err, entries)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(filepath.Join(kb, entries[0].Name()))
|
||||||
|
if !strings.Contains(string(data), `"cause"`) {
|
||||||
|
t.Errorf("persisted file missing cause field: %s", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
7
example/recoverydiag/go.mod
Normal file
7
example/recoverydiag/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module recoverydiag
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/recoverydiag/main.go
Normal file
11
example/recoverydiag/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
21
example/recoverydiag/plg.json
Normal file
21
example/recoverydiag/plg.json
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "recoverydiag",
|
||||||
|
"name_zh": "恢复诊断",
|
||||||
|
"name_en": "Recovery Diagnostics",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"description": "快速检查/崩溃取证工具集:diag_triage(退出码/信号/存活粗分)、diag_db(config.db 完整性 + LLM 源解析校验)、diag_log_scan(日志签名命中)、diag_delta(last-good 快照 vs 现状 diff)、diag_loc(正交综合定位)。全部返回结论而非原文,确定性、不消耗 LLM token,供 guard / failback 恢复决策使用。",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": [
|
||||||
|
"diag",
|
||||||
|
"recovery",
|
||||||
|
"diagnostics",
|
||||||
|
"triage",
|
||||||
|
"failback"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
1023
example/recoverydiag/plugin.go
Normal file
1023
example/recoverydiag/plugin.go
Normal file
File diff suppressed because it is too large
Load Diff
13
example/rss/README.md
Normal file
13
example/rss/README.md
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# rss
|
||||||
|
|
||||||
|
rss plugin
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Upload the .hmap file through the Plugin Manager API.
|
||||||
17
example/rss/go.mod
Normal file
17
example/rss/go.mod
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
module rss
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
github.com/mmcdole/gofeed v1.4.0
|
||||||
|
github.com/mmcdole/goxpp/v2 v2.0.0
|
||||||
|
golang.org/x/net v0.56.0
|
||||||
|
golang.org/x/text v0.38.0
|
||||||
|
)
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
8
example/rss/go.sum
Normal file
8
example/rss/go.sum
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
github.com/mmcdole/gofeed v1.4.0 h1:+efDmI/yJXJgTfa8we5zg9GAKsU+2d7tnpt9QZwvjLQ=
|
||||||
|
github.com/mmcdole/gofeed v1.4.0/go.mod h1:ngV5MTB7UJko6fH3/fG5AkB/ABUGK1ZTePF9iRhzu/c=
|
||||||
|
github.com/mmcdole/goxpp/v2 v2.0.0 h1:HrSCflxerUEqZQNq3u7ldtmE/XkwnTx4Zpq2DW4i5rQ=
|
||||||
|
github.com/mmcdole/goxpp/v2 v2.0.0/go.mod h1:CUduYMnO9JB6Z/uqDn9Ormk/r8E9BsLQxHPWDZ961Os=
|
||||||
|
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||||
|
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||||
|
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||||
|
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||||
11
example/rss/main.go
Normal file
11
example/rss/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
20
example/rss/plg.json
Normal file
20
example/rss/plg.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "rss",
|
||||||
|
"name_zh": "RSS订阅",
|
||||||
|
"name_en": "RSS",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"description": "RSS/Atom 订阅监控插件,自动检测更新并推送通知",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": [
|
||||||
|
"rss",
|
||||||
|
"feed",
|
||||||
|
"subscription",
|
||||||
|
"monitor"
|
||||||
|
],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
500
example/rss/plugin.go
Normal file
500
example/rss/plugin.go
Normal file
@ -0,0 +1,500 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
"github.com/mmcdole/gofeed"
|
||||||
|
)
|
||||||
|
|
||||||
|
const injectDedupWindow = 5 * time.Minute
|
||||||
|
|
||||||
|
type FeedSub struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
AddedAt string `json:"added_at"`
|
||||||
|
Interval int `json:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Plugin struct {
|
||||||
|
name string
|
||||||
|
sdk *sdk.PluginSDK
|
||||||
|
client *http.Client
|
||||||
|
fp *gofeed.Parser
|
||||||
|
dataDir string
|
||||||
|
mu sync.RWMutex
|
||||||
|
feeds []FeedSub
|
||||||
|
seenGUIDs map[string]bool
|
||||||
|
injected map[string]time.Time
|
||||||
|
stopCh chan struct{}
|
||||||
|
stopOnce sync.Once
|
||||||
|
wg sync.WaitGroup
|
||||||
|
pollTicker *time.Ticker
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
|
func getSetting[T string | int64 | float64](s sdk.SettingsAPI, key string, fallback T) T {
|
||||||
|
v, err := s.Get(key)
|
||||||
|
if err != nil || v == nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
switch any(fallback).(type) {
|
||||||
|
case string:
|
||||||
|
if sv, ok := v.(string); ok {
|
||||||
|
return any(sv).(T)
|
||||||
|
}
|
||||||
|
case int64:
|
||||||
|
switch val := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(int64(val)).(T)
|
||||||
|
case string:
|
||||||
|
if n, err := strconv.ParseInt(val, 10, 64); err == nil {
|
||||||
|
return any(n).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case float64:
|
||||||
|
switch val := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return any(val).(T)
|
||||||
|
case string:
|
||||||
|
if n, err := strconv.ParseFloat(val, 64); err == nil {
|
||||||
|
return any(n).(T)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func readArg(args map[string]interface{}, key string) string {
|
||||||
|
if v, ok := args[key]; ok && v != nil {
|
||||||
|
if s, ok := v.(string); ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func readArgInt(args map[string]interface{}, key string, fallback int) int {
|
||||||
|
if v, ok := args[key]; ok && v != nil {
|
||||||
|
switch n := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return int(n)
|
||||||
|
case int64:
|
||||||
|
return int(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
|
s.SetAutoRestart(true)
|
||||||
|
p.sdk = s
|
||||||
|
p.client = &http.Client{Timeout: 30 * time.Second}
|
||||||
|
p.fp = gofeed.NewParser()
|
||||||
|
p.stopCh = make(chan struct{})
|
||||||
|
p.seenGUIDs = make(map[string]bool)
|
||||||
|
p.injected = make(map[string]time.Time)
|
||||||
|
p.feeds = []FeedSub{}
|
||||||
|
|
||||||
|
dataDirVal, err := s.Settings().GetCore("core.daemon.data_dir")
|
||||||
|
if err != nil || dataDirVal == "" {
|
||||||
|
dataDirVal = "."
|
||||||
|
}
|
||||||
|
p.dataDir = filepath.Join(fmt.Sprint(dataDirVal), "rss")
|
||||||
|
if err := os.MkdirAll(p.dataDir, 0755); err != nil {
|
||||||
|
fmt.Printf("[%s] mkdir %s: %v\n", p.name, p.dataDir, err)
|
||||||
|
}
|
||||||
|
p.loadData()
|
||||||
|
|
||||||
|
// 卸载(删除)时清理订阅数据目录;重载不触发
|
||||||
|
s.RegisterOnRemoveHandler(p.cleanupData)
|
||||||
|
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "poll_interval", Default: "30", Type: "string",
|
||||||
|
DisplayName: "Poll Interval", Description: "Default polling interval in minutes (default: 30)",
|
||||||
|
Category: "rss",
|
||||||
|
})
|
||||||
|
|
||||||
|
tp := p.name + "_"
|
||||||
|
s.RegisterTool(tp+"subscribe", sdk.ToolDef{
|
||||||
|
Name: tp + "subscribe", Description: "Subscribe to an RSS/Atom feed URL",
|
||||||
|
NoMemory: true,
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"url": map[string]interface{}{"type": "string", "description": "Feed URL"},
|
||||||
|
"interval": map[string]interface{}{"type": "integer", "description": "Poll interval in minutes (default: 30, minimum: 5)"},
|
||||||
|
},
|
||||||
|
"required": []string{"url"},
|
||||||
|
},
|
||||||
|
}, p.handleSubscribe)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"unsubscribe", sdk.ToolDef{
|
||||||
|
Name: tp + "unsubscribe", Description: "Unsubscribe from a feed",
|
||||||
|
NoMemory: true,
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"url": map[string]interface{}{"type": "string", "description": "Feed URL to unsubscribe"},
|
||||||
|
},
|
||||||
|
"required": []string{"url"},
|
||||||
|
},
|
||||||
|
}, p.handleUnsubscribe)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"list", sdk.ToolDef{
|
||||||
|
Name: tp + "list", Description: "List all subscribed feeds",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleList)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"check_now", sdk.ToolDef{
|
||||||
|
Name: tp + "check_now", Description: "Manually check all feeds for new articles now",
|
||||||
|
NoMemory: true,
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{},
|
||||||
|
},
|
||||||
|
}, p.handleCheckNow)
|
||||||
|
|
||||||
|
pollMin := int(getSetting(s.Settings(), "poll_interval", int64(30)))
|
||||||
|
if pollMin < 5 {
|
||||||
|
pollMin = 5
|
||||||
|
}
|
||||||
|
p.pollTicker = time.NewTicker(time.Duration(pollMin) * time.Minute)
|
||||||
|
|
||||||
|
p.wg.Add(1)
|
||||||
|
go p.pollLoop()
|
||||||
|
|
||||||
|
fmt.Printf("[%s] started (%d feeds, poll every %dm)\n", p.name, len(p.feeds), pollMin)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Stop() error {
|
||||||
|
p.stopOnce.Do(func() { close(p.stopCh) })
|
||||||
|
p.pollTicker.Stop()
|
||||||
|
p.wg.Wait()
|
||||||
|
p.saveData()
|
||||||
|
fmt.Printf("[%s] stopped\n", p.name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) pollLoop() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
|
||||||
|
p.checkAllFeeds()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-p.pollTicker.C:
|
||||||
|
p.checkAllFeeds()
|
||||||
|
case <-p.stopCh:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) checkAllFeeds() {
|
||||||
|
p.mu.RLock()
|
||||||
|
feeds := make([]FeedSub, len(p.feeds))
|
||||||
|
copy(feeds, p.feeds)
|
||||||
|
p.mu.RUnlock()
|
||||||
|
|
||||||
|
for _, feed := range feeds {
|
||||||
|
select {
|
||||||
|
case <-p.stopCh:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
p.checkFeed(feed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) checkFeed(sub FeedSub) {
|
||||||
|
parsed, err := p.fp.ParseURL(sub.URL)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
title := parsed.Title
|
||||||
|
if title == "" {
|
||||||
|
title = sub.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
var newArticles []*gofeed.Item
|
||||||
|
for _, item := range parsed.Items {
|
||||||
|
guid := item.GUID
|
||||||
|
if guid == "" {
|
||||||
|
guid = item.Link
|
||||||
|
}
|
||||||
|
if guid == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
guid = sub.URL + "|" + guid
|
||||||
|
p.mu.RLock()
|
||||||
|
seen := p.seenGUIDs[guid]
|
||||||
|
p.mu.RUnlock()
|
||||||
|
if !seen {
|
||||||
|
newArticles = append(newArticles, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(newArticles) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
toInject := make([]*gofeed.Item, 0, len(newArticles))
|
||||||
|
p.mu.Lock()
|
||||||
|
for _, item := range newArticles {
|
||||||
|
guid := item.GUID
|
||||||
|
if guid == "" {
|
||||||
|
guid = item.Link
|
||||||
|
}
|
||||||
|
if guid == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := sub.URL + "|" + guid
|
||||||
|
if t, ok := p.injected[key]; ok && now.Sub(t) < injectDedupWindow {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.injected[key] = now
|
||||||
|
p.seenGUIDs[key] = true
|
||||||
|
toInject = append(toInject, item)
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
if len(toInject) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
lines = append(lines, fmt.Sprintf("📡 %s (%s) — %d 篇新文章:", title, sub.URL, len(toInject)))
|
||||||
|
for _, item := range toInject {
|
||||||
|
pubDate := ""
|
||||||
|
if item.PublishedParsed != nil {
|
||||||
|
pubDate = item.PublishedParsed.Format("01-02 15:04")
|
||||||
|
}
|
||||||
|
line := fmt.Sprintf(" • %s", item.Title)
|
||||||
|
if pubDate != "" {
|
||||||
|
line += fmt.Sprintf(" [%s]", pubDate)
|
||||||
|
}
|
||||||
|
if item.Link != "" {
|
||||||
|
line += "\n " + item.Link
|
||||||
|
}
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 中断注入是「系统通知」,NoMemory 写明意图:这类提醒不参与记忆计算,
|
||||||
|
// 原文仍进上下文(模型当轮看得到)。
|
||||||
|
p.sdk.InjectInterruptTextOpts("rss", "rss", strings.Join(lines, "\n"),
|
||||||
|
sdk.InjectOptions{NoMemory: true})
|
||||||
|
p.saveData()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleSubscribe(args map[string]interface{}) (interface{}, error) {
|
||||||
|
url := readArg(args, "url")
|
||||||
|
if url == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "URL is required"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.RLock()
|
||||||
|
for _, f := range p.feeds {
|
||||||
|
if f.URL == url {
|
||||||
|
p.mu.RUnlock()
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Already subscribed to: " + url}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.RUnlock()
|
||||||
|
|
||||||
|
interval := readArgInt(args, "interval", 30)
|
||||||
|
if interval < 5 {
|
||||||
|
interval = 5
|
||||||
|
}
|
||||||
|
|
||||||
|
parsed, err := p.fp.ParseURL(url)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Failed to parse feed: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
feedTitle := parsed.Title
|
||||||
|
if feedTitle == "" {
|
||||||
|
feedTitle = url
|
||||||
|
}
|
||||||
|
|
||||||
|
sub := FeedSub{
|
||||||
|
URL: url,
|
||||||
|
Title: feedTitle,
|
||||||
|
AddedAt: time.Now().Format("2006-01-02 15:04"),
|
||||||
|
Interval: interval,
|
||||||
|
}
|
||||||
|
|
||||||
|
guidCount := 0
|
||||||
|
p.mu.Lock()
|
||||||
|
for _, item := range parsed.Items {
|
||||||
|
guid := item.GUID
|
||||||
|
if guid == "" {
|
||||||
|
guid = item.Link
|
||||||
|
}
|
||||||
|
if guid == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.seenGUIDs[url+"|"+guid] = true
|
||||||
|
guidCount++
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
p.feeds = append(p.feeds, sub)
|
||||||
|
p.mu.Unlock()
|
||||||
|
p.saveData()
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": fmt.Sprintf("Subscribed to: %s\nTitle: %s\nArticles found: %d\nPoll interval: %d min", url, feedTitle, guidCount, interval),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleUnsubscribe(args map[string]interface{}) (interface{}, error) {
|
||||||
|
url := readArg(args, "url")
|
||||||
|
if url == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "URL is required"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.mu.Lock()
|
||||||
|
found := false
|
||||||
|
for i, f := range p.feeds {
|
||||||
|
if f.URL == url {
|
||||||
|
p.feeds = append(p.feeds[:i], p.feeds[i+1:]...)
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Not subscribed to: " + url}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for guid := range p.seenGUIDs {
|
||||||
|
if strings.HasPrefix(guid, url+"|") {
|
||||||
|
delete(p.seenGUIDs, guid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
p.saveData()
|
||||||
|
|
||||||
|
return map[string]interface{}{"content": "Unsubscribed: " + url}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleList(args map[string]interface{}) (interface{}, error) {
|
||||||
|
p.mu.RLock()
|
||||||
|
defer p.mu.RUnlock()
|
||||||
|
|
||||||
|
if len(p.feeds) == 0 {
|
||||||
|
return map[string]interface{}{"content": "No subscriptions. Use rss_subscribe to add one."}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
sort.Slice(p.feeds, func(i, j int) bool {
|
||||||
|
return p.feeds[i].Title < p.feeds[j].Title
|
||||||
|
})
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
lines = append(lines, fmt.Sprintf("📡 Subscriptions (%d):", len(p.feeds)))
|
||||||
|
for _, f := range p.feeds {
|
||||||
|
lines = append(lines, fmt.Sprintf(" • %s\n %s (every %dm, added %s)", f.Title, f.URL, f.Interval, f.AddedAt))
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{"content": strings.Join(lines, "\n")}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleCheckNow(args map[string]interface{}) (interface{}, error) {
|
||||||
|
select {
|
||||||
|
case <-p.stopCh:
|
||||||
|
return map[string]interface{}{"isError": true, "content": "plugin is stopping"}, nil
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
p.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
p.checkAllFeeds()
|
||||||
|
}()
|
||||||
|
return map[string]interface{}{"content": "Checking all feeds for updates..."}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) dataFile() string {
|
||||||
|
return filepath.Join(p.dataDir, "feeds.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) loadData() {
|
||||||
|
b, err := os.ReadFile(p.dataFile())
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var data struct {
|
||||||
|
Feeds []FeedSub `json:"feeds"`
|
||||||
|
SeenGUIDs map[string]bool `json:"seen"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(b, &data) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.Feeds != nil {
|
||||||
|
p.feeds = data.Feeds
|
||||||
|
}
|
||||||
|
if data.SeenGUIDs != nil {
|
||||||
|
p.seenGUIDs = data.SeenGUIDs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) saveData() {
|
||||||
|
p.mu.RLock()
|
||||||
|
defer p.mu.RUnlock()
|
||||||
|
data := struct {
|
||||||
|
Feeds []FeedSub `json:"feeds"`
|
||||||
|
SeenGUIDs map[string]bool `json:"seen"`
|
||||||
|
}{
|
||||||
|
Feeds: p.feeds,
|
||||||
|
SeenGUIDs: p.seenGUIDs,
|
||||||
|
}
|
||||||
|
b, _ := json.MarshalIndent(data, "", " ")
|
||||||
|
atomicWriteJSON(p.dataFile(), b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupData 卸载时清理订阅数据目录(feeds.json 等)
|
||||||
|
func (p *Plugin) cleanupData() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if p.dataDir == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, f := range []string{"feeds.json"} {
|
||||||
|
path := filepath.Join(p.dataDir, f)
|
||||||
|
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||||
|
fmt.Printf("[%s] onRemove cleanup %s: %v\n", p.name, path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// atomicWriteJSON 原子写 JSON:先写临时文件再 rename,避免进程崩溃截断数据文件。
|
||||||
|
func atomicWriteJSON(path string, data []byte) error {
|
||||||
|
tmp := path + ".tmp"
|
||||||
|
if err := os.WriteFile(tmp, data, 0644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp, path)
|
||||||
|
}
|
||||||
@ -2,6 +2,6 @@ module sanitizer
|
|||||||
|
|
||||||
go 1.25.0
|
go 1.25.0
|
||||||
|
|
||||||
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0-20260708004841-e9bdcf9304b0
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
replace gitcode.com/JianFeeeee/homeagent-sdk => ../..
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|||||||
11
example/sanitizer/main.go
Normal file
11
example/sanitizer/main.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows || !cgo
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return NewPluginFactory(name, config)
|
||||||
|
}
|
||||||
@ -7,5 +7,9 @@
|
|||||||
"author": "HomeAgent SDK",
|
"author": "HomeAgent SDK",
|
||||||
"entry": "plugin.so",
|
"entry": "plugin.so",
|
||||||
"tags": ["sanitizer"],
|
"tags": ["sanitizer"],
|
||||||
"targets": "linux/amd64"
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,13 @@
|
|||||||
// Package main 是一个外部插件示例(编译为 .so 通过 -buildmode=plugin)。
|
// Package main 是一个外部插件示例(编译为 .so 通过 -buildmode=plugin)。
|
||||||
// 在 StagePostAction 阶段清洗 LLM 输出中的工具调用残留(思维泄漏)。
|
// 目标:在 Agent 全链路清洗文本,防止乱码(坏 UTF-8 / U+FFFD / ANSI 转义)污染上下文并被 LLM 复读,
|
||||||
|
// 同时保留原有"工具调用残留(思维泄漏)"清理。
|
||||||
|
//
|
||||||
|
// 挂载阶段:
|
||||||
|
// - StageOnInput : 清洗用户输入(RawMessage)
|
||||||
|
// - StageAfterToolcall : 清洗工具执行结果(ToolResults),坏字节不进 LLM 上下文
|
||||||
|
// - StagePostAction : 清洗 LLM 输出(LLMText),保留原有思维泄漏清理
|
||||||
|
//
|
||||||
|
// 依赖 ABI v2 的 stage 写回能力:插件对 StageContext 的修改会同步回内核。
|
||||||
//
|
//
|
||||||
// 编译:
|
// 编译:
|
||||||
//
|
//
|
||||||
@ -13,21 +21,24 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
"gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
toolCallTagRE = regexp.MustCompile(`(?s)<tool_call[^>]*>.*?</tool_call>`)
|
toolCallTagRE = regexp.MustCompile(`(?s)<tool_call[^>]*>.*?</tool_call>`)
|
||||||
invokeTagRE = regexp.MustCompile(`(?s)<invoke[^>]*>.*?</invoke>`)
|
invokeTagRE = regexp.MustCompile(`(?s)<invoke[^>]*>.*?</invoke>`)
|
||||||
toolTagRE = regexp.MustCompile(`(?s)<tool[^>]*>.*?</tool>`)
|
toolTagRE = regexp.MustCompile(`(?s)<tool[^>]*>.*?</tool>`)
|
||||||
functionTagRE = regexp.MustCompile(`(?s)<function[^>]*>.*?</function>`)
|
functionTagRE = regexp.MustCompile(`(?s)<function[^>]*>.*?</function>`)
|
||||||
toolCodeBlockRE = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<tool_call[^>]*>.*?</tool_call>\\s*```")
|
toolCodeBlockRE = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<tool_call[^>]*>.*?</tool_call>\\s*```")
|
||||||
invokeCodeBlockRE = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<invoke[^>]*>.*?</invoke>\\s*```")
|
invokeCodeBlockRE = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<invoke[^>]*>.*?</invoke>\\s*```")
|
||||||
toolCodeBlockRE2 = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<tool[^>]*>.*?</tool>\\s*```")
|
toolCodeBlockRE2 = regexp.MustCompile("(?s)```(?:xml|json)?\\s*<tool[^>]*>.*?</tool>\\s*```")
|
||||||
chineseMarkerRE = regexp.MustCompile(`(?s)【tool_call】.*?【/tool_call】`)
|
chineseMarkerRE = regexp.MustCompile(`(?s)【tool_call】.*?【/tool_call】`)
|
||||||
multiNewlineRE = regexp.MustCompile(`\n{3,}`)
|
multiNewlineRE = regexp.MustCompile(`\n{3,}`)
|
||||||
toolNameRE = regexp.MustCompile(`^(cmd_run|terminal_create|terminal_write|memory_|knowledge_|doc_|social_|output_send|output_set_channel|llm_|plgreload|spawn_child|child_result|describe_image|transcribe_audio|ocr_image|timer_set|plugin_install|plugin_remove|qq_|a2a_|mcp_|healthcheck|files_|web_)`)
|
toolNameRE = regexp.MustCompile(`^(cmd_run|terminal_create|terminal_write|memory_|knowledge_|doc_|social_|output_set_channel|output_send|llm_|plgreload|spawn_child|child_result|describe_image|transcribe_audio|ocr_image|timer_set|plugin_install|plugin_remove|qq_|a2a_|mcp_|healthcheck|files_|web_)`)
|
||||||
|
placeholderRE = regexp.MustCompile(`(?i)\{\{\s*tool\s*[::][^}]*\}\}`)
|
||||||
|
atToolRE = regexp.MustCompile(`(?i)^@\s*tool\b`)
|
||||||
)
|
)
|
||||||
|
|
||||||
type Plugin struct{}
|
type Plugin struct{}
|
||||||
@ -36,10 +47,41 @@ func (p *Plugin) Name() string { return "sanitizer" }
|
|||||||
|
|
||||||
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
s.SetAutoRestart(true)
|
s.SetAutoRestart(true)
|
||||||
|
|
||||||
|
// 1) 输入清洗
|
||||||
|
s.RegisterStage(sdk.StageOnInput, func(ctx *sdk.StageContext) error {
|
||||||
|
ctx.Lock()
|
||||||
|
before := ctx.RawMessage
|
||||||
|
ctx.RawMessage = cleanText(ctx.RawMessage)
|
||||||
|
if before != ctx.RawMessage {
|
||||||
|
log.Printf("[sanitizer] StageOnInput: cleaned %d bytes", len(before)-len(ctx.RawMessage))
|
||||||
|
}
|
||||||
|
ctx.Unlock()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2) 工具结果清洗(坏字节/ANSI 不得进 LLM 上下文)
|
||||||
|
s.RegisterStage(sdk.StageAfterToolcall, func(ctx *sdk.StageContext) error {
|
||||||
|
ctx.Lock()
|
||||||
|
defer ctx.Unlock()
|
||||||
|
for i, tr := range ctx.ToolResults {
|
||||||
|
if s, ok := tr.Result.(string); ok {
|
||||||
|
clean := cleanText(s)
|
||||||
|
if clean != s {
|
||||||
|
ctx.ToolResults[i].Result = clean
|
||||||
|
log.Printf("[sanitizer] StageAfterToolcall: tool=%s cleaned %d bytes", tr.Name, len(s)-len(clean))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// 3) LLM 输出清洗(保留原有思维泄漏清理 + 新增乱码清洗)
|
||||||
s.RegisterStage(sdk.StagePostAction, func(ctx *sdk.StageContext) error {
|
s.RegisterStage(sdk.StagePostAction, func(ctx *sdk.StageContext) error {
|
||||||
ctx.Lock()
|
ctx.Lock()
|
||||||
before := len(ctx.LLMText)
|
before := len(ctx.LLMText)
|
||||||
ctx.LLMText = cleanToolCallLeakage(ctx.LLMText)
|
ctx.LLMText = cleanToolCallLeakage(ctx.LLMText)
|
||||||
|
ctx.LLMText = cleanText(ctx.LLMText)
|
||||||
after := len(ctx.LLMText)
|
after := len(ctx.LLMText)
|
||||||
ctx.Unlock()
|
ctx.Unlock()
|
||||||
if before != after {
|
if before != after {
|
||||||
@ -47,16 +89,17 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
log.Printf("[sanitizer] stage PostAction registered")
|
log.Printf("[sanitizer] stage OnInput/AfterToolcall/PostAction registered")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) Stop() error { return nil }
|
func (p *Plugin) Stop() error { return nil }
|
||||||
|
|
||||||
func NewPlugin(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
return &Plugin{}, nil
|
return &Plugin{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanToolCallLeakage 清洗 LLM 输出中的工具调用残留(思维泄漏)。
|
||||||
func cleanToolCallLeakage(content string) string {
|
func cleanToolCallLeakage(content string) string {
|
||||||
if content == "" {
|
if content == "" {
|
||||||
return content
|
return content
|
||||||
@ -83,8 +126,12 @@ func cleanToolCallLeakage(content string) string {
|
|||||||
cleaned = append(cleaned, line)
|
cleaned = append(cleaned, line)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if toolNameRE.MatchString(trimmed) {
|
if placeholderRE.MatchString(trimmed) || atToolRE.MatchString(trimmed) {
|
||||||
if strings.Contains(trimmed, "(") || strings.Contains(trimmed, "\"") || strings.Contains(trimmed, ":") {
|
continue
|
||||||
|
}
|
||||||
|
if m := toolNameRE.FindStringIndex(trimmed); m != nil {
|
||||||
|
rest := trimmed[m[1]:]
|
||||||
|
if strings.HasPrefix(rest, "(") && strings.Contains(rest, ")") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -100,3 +147,72 @@ func cleanToolCallLeakage(content string) string {
|
|||||||
}
|
}
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cleanText 清洗可能污染 LLM 上下文/输出的文本:
|
||||||
|
// 1. 剥离 ANSI 转义序列(\x1b[...m 等,源自终端输出)
|
||||||
|
// 2. 剔除无效 UTF-8 字节(strings.ToValidUTF8 语义)与已解码的 U+FFFD 替换符,
|
||||||
|
// 避免模型复读坏字节/替换符造成乱码(把坏段落整体丢弃比留残字更干净)
|
||||||
|
func cleanText(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
// 先剥离 ANSI 转义:ESC [ 参数 m / ESC ] 标题 / 其他 CSI 序列
|
||||||
|
if strings.ContainsRune(s, 0x1b) {
|
||||||
|
var sb strings.Builder
|
||||||
|
sb.Grow(len(s))
|
||||||
|
i := 0
|
||||||
|
for i < len(s) {
|
||||||
|
c := s[i]
|
||||||
|
if c == 0x1b {
|
||||||
|
// 跳过完整转义序列
|
||||||
|
j := i + 1
|
||||||
|
if j < len(s) {
|
||||||
|
switch s[j] {
|
||||||
|
case '[': // CSI: ESC [ <params> <letter>
|
||||||
|
j++
|
||||||
|
for j < len(s) && !(s[j] >= 0x40 && s[j] <= 0x7e) {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
if j < len(s) {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
i = j
|
||||||
|
continue
|
||||||
|
case ']': // OSC: ESC ] ... BEL / ST
|
||||||
|
i = j + 1
|
||||||
|
for i < len(s) && s[i] != 0x07 {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
i++ // skip BEL
|
||||||
|
continue
|
||||||
|
default: // 单字符转义(ESC c ESC 7 等)
|
||||||
|
i = j + 1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sb.WriteByte(c)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
s = sb.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 剔除无效 UTF-8 与 U+FFFD 替换符
|
||||||
|
if !utf8.ValidString(s) {
|
||||||
|
s = strings.ToValidUTF8(s, "")
|
||||||
|
}
|
||||||
|
if strings.ContainsRune(s, utf8.RuneError) {
|
||||||
|
// 连 U+FFFD 也不留给模型复述
|
||||||
|
var b strings.Builder
|
||||||
|
b.Grow(len(s))
|
||||||
|
for _, r := range s {
|
||||||
|
if r != utf8.RuneError {
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s = b.String()
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
@ -2,6 +2,31 @@ package main
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
|
func TestCleanText(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name, input, want string
|
||||||
|
}{
|
||||||
|
{"empty", "", ""},
|
||||||
|
{"clean", "你好世界 hello", "你好世界 hello"},
|
||||||
|
{"invalid_utf8", "a\xff\xfe b", "a b"},
|
||||||
|
{"ufffd", "有乱码\ufffd字符", "有乱码字符"},
|
||||||
|
{"multiple_ufffd", "a\ufffd\ufffdb\ufffdc", "abc"},
|
||||||
|
{"ansi_color", "\x1b[31m红色\x1b[0m结束", "红色结束"},
|
||||||
|
{"ansi_cursor", "a\x1b[2K\r\nb", "a\r\nb"},
|
||||||
|
{"ansi_osc", "\x1b]0;title\x07文本", "文本"},
|
||||||
|
{"an_and_ufffd", "\x1b[31m\ufffd中文\x1b[0m", "中文"},
|
||||||
|
{"emoji_kept", "颜文字(・ω・´)和🍎", "颜文字(・ω・´)和🍎"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got := cleanText(tt.input)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("got %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCleanToolCallLeakage(t *testing.T) {
|
func TestCleanToolCallLeakage(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name, input, want string
|
name, input, want string
|
||||||
@ -28,4 +53,4 @@ func TestCleanToolCallLeakage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
7
example/vanblog/go.mod
Normal file
7
example/vanblog/go.mod
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module vanblog-plugin
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
11
example/vanblog/plg.json
Normal file
11
example/vanblog/plg.json
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "vanblog",
|
||||||
|
"name_zh": "VanBlog 博客管理",
|
||||||
|
"name_en": "VanBlog",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "管理 VanBlog 开源博客系统:文章的增删改查、分类标签管理、草稿发布、备份导出等",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": ["blog", "vanblog", "cms"],
|
||||||
|
"targets": "linux/amd64"
|
||||||
|
}
|
||||||
1334
example/vanblog/plugin.go
Normal file
1334
example/vanblog/plugin.go
Normal file
File diff suppressed because it is too large
Load Diff
13
example/weather/README.md
Normal file
13
example/weather/README.md
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
# weather
|
||||||
|
|
||||||
|
weather plugin
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hmapdev build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
Upload the .hmap file through the Plugin Manager API.
|
||||||
8
example/weather/go.mod
Normal file
8
example/weather/go.mod
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
module weather
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require gitcode.com/JianFeeeee/homeagent-sdk v0.0.0
|
||||||
|
|
||||||
|
replace gitcode.com/JianFeeeee/homeagent-sdk => ../../
|
||||||
|
|
||||||
16
example/weather/plg.json
Normal file
16
example/weather/plg.json
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"name": "weather",
|
||||||
|
"name_zh": "天气查询",
|
||||||
|
"name_en": "Weather",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "天气查询插件(基于 wttr.in),支持实时天气和未来预报",
|
||||||
|
"author": "HomeAgent",
|
||||||
|
"entry": "plugin.so",
|
||||||
|
"tags": ["weather", "forecast", "wttr"],
|
||||||
|
"targets": "linux/amd64",
|
||||||
|
"outdir": "dist",
|
||||||
|
"bundle": true,
|
||||||
|
"replaces": {},
|
||||||
|
"source_dirs": []
|
||||||
|
}
|
||||||
|
|
||||||
412
example/weather/plugin.go
Normal file
412
example/weather/plugin.go
Normal file
@ -0,0 +1,412 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
sdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Plugin struct {
|
||||||
|
name string
|
||||||
|
sdk *sdk.PluginSDK
|
||||||
|
client *http.Client
|
||||||
|
defaultLoc string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPluginFactory(name string, config map[string]interface{}) (sdk.Plugin, error) {
|
||||||
|
return &Plugin{name: name}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Name() string { return p.name }
|
||||||
|
|
||||||
|
func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||||
|
s.SetAutoRestart(true)
|
||||||
|
p.sdk = s
|
||||||
|
p.client = &http.Client{Timeout: 15 * time.Second}
|
||||||
|
|
||||||
|
s.Settings().RegisterDef(sdk.ConfigDef{
|
||||||
|
Key: "default_location", Default: "", Type: "string",
|
||||||
|
DisplayName: "Default Location", Description: "Default city name for weather queries, e.g. Beijing",
|
||||||
|
Category: "weather",
|
||||||
|
})
|
||||||
|
|
||||||
|
if v, _ := s.Settings().Get("default_location"); v != nil {
|
||||||
|
if vs, ok := v.(string); ok {
|
||||||
|
p.defaultLoc = vs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tp := p.name + "_"
|
||||||
|
s.RegisterTool(tp+"current", sdk.ToolDef{
|
||||||
|
Name: tp + "current", Description: "Get current weather for a city",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"location": map[string]interface{}{"type": "string", "description": "City name (e.g. Beijing, Shanghai, London). Uses default if omitted."},
|
||||||
|
"units": map[string]interface{}{"type": "string", "description": "Units: metric (celsius) or imperial (fahrenheit), default metric"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// NoMemory: 外部实时数据对记忆计算无长期价值,跳过向量化/关键词提取
|
||||||
|
NoMemory: true,
|
||||||
|
// Cleaner: 工具输出参与记忆计算前先过滤;这里演示用法(保留摘要行)
|
||||||
|
Cleaner: func(output string) string {
|
||||||
|
for _, line := range strings.Split(output, "\n") {
|
||||||
|
if strings.HasPrefix(line, "🌤") {
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
},
|
||||||
|
}, p.handleCurrent)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"forecast", sdk.ToolDef{
|
||||||
|
Name: tp + "forecast", Description: "Get weather forecast for next several days",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"location": map[string]interface{}{"type": "string", "description": "City name. Uses default if omitted."},
|
||||||
|
"days": map[string]interface{}{"type": "integer", "description": "Number of days (1-7), default 3"},
|
||||||
|
"units": map[string]interface{}{"type": "string", "description": "Units: metric or imperial, default metric"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
NoMemory: true,
|
||||||
|
}, p.handleForecast)
|
||||||
|
|
||||||
|
s.RegisterTool(tp+"set_location", sdk.ToolDef{
|
||||||
|
Name: tp + "set_location", Description: "Set default weather location",
|
||||||
|
Parameters: map[string]interface{}{
|
||||||
|
"type": "object",
|
||||||
|
"properties": map[string]interface{}{
|
||||||
|
"location": map[string]interface{}{"type": "string", "description": "City name to set as default"},
|
||||||
|
},
|
||||||
|
"required": []string{"location"},
|
||||||
|
},
|
||||||
|
NoMemory: true,
|
||||||
|
}, p.handleSetLocation)
|
||||||
|
|
||||||
|
// 阶段钩子:own_tools 作用域——仅在本插件的工具被调用时触发
|
||||||
|
s.RegisterStage(sdk.StageAfterToolcall, func(ctx *sdk.StageContext) error {
|
||||||
|
ctx.Lock()
|
||||||
|
defer ctx.Unlock()
|
||||||
|
if len(ctx.ToolResults) > 0 {
|
||||||
|
fmt.Printf("[%s] stage after_toolcall(own): %s\n", p.name, ctx.ToolResults[0].Name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}, sdk.StageScopeOwnTools)
|
||||||
|
|
||||||
|
// 输出通道:把天气结果主动推给用户(如 QQ/WebUI 渠道)
|
||||||
|
if err := s.RegisterOutputChannel(tp+"weather_out", 0, "push weather to user", sdk.ChannelDef{
|
||||||
|
NoMemory: true,
|
||||||
|
}, func(args map[string]interface{}) (interface{}, error) {
|
||||||
|
payload, _ := args["payload"].(string)
|
||||||
|
return map[string]interface{}{"content": "weather pushed: " + payload}, nil
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 输入通道:接收天气订阅请求(NoMemory: 通道输入不参与记忆计算)
|
||||||
|
if err := s.RegisterInputChannel(tp+"weather_in", sdk.ChannelDef{NoMemory: true}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("[%s] started\n", p.name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Stop() error {
|
||||||
|
fmt.Printf("[%s] stopped\n", p.name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type wttrResp struct {
|
||||||
|
CurrentCondition []struct {
|
||||||
|
TempC string `json:"temp_C"`
|
||||||
|
FeelsLikeC string `json:"FeelsLikeC"`
|
||||||
|
Humidity string `json:"humidity"`
|
||||||
|
WindspeedKmph string `json:"windspeedKmph"`
|
||||||
|
Winddir16Point string `json:"winddir16Point"`
|
||||||
|
Pressure string `json:"pressure"`
|
||||||
|
Visibility string `json:"visibility"`
|
||||||
|
WeatherDesc []struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
} `json:"weatherDesc"`
|
||||||
|
LocalObsDateTime string `json:"localObsDateTime"`
|
||||||
|
} `json:"current_condition"`
|
||||||
|
NearestArea []struct {
|
||||||
|
AreaName []struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
} `json:"areaName"`
|
||||||
|
Country []struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
} `json:"country"`
|
||||||
|
Region []struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
} `json:"region"`
|
||||||
|
} `json:"nearest_area"`
|
||||||
|
Weather []wttrDay `json:"weather"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type wttrDay struct {
|
||||||
|
Date string `json:"date"`
|
||||||
|
Astronomy []struct {
|
||||||
|
Sunrise string `json:"sunrise"`
|
||||||
|
Sunset string `json:"sunset"`
|
||||||
|
} `json:"astronomy"`
|
||||||
|
MaxtempC string `json:"maxtempC"`
|
||||||
|
MintempC string `json:"mintempC"`
|
||||||
|
Hourly []struct {
|
||||||
|
TempC string `json:"tempC"`
|
||||||
|
WeatherDesc []struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
} `json:"weatherDesc"`
|
||||||
|
WindspeedKmph string `json:"windspeedKmph"`
|
||||||
|
Winddir16Point string `json:"winddir16Point"`
|
||||||
|
Humidity string `json:"humidity"`
|
||||||
|
FeelsLikeC string `json:"FeelsLikeC"`
|
||||||
|
PrecipMM string `json:"precipMM"`
|
||||||
|
Visibility string `json:"visibility"`
|
||||||
|
} `json:"hourly"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) getLoc(args map[string]interface{}) string {
|
||||||
|
if v, ok := args["location"].(string); ok && v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return p.defaultLoc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) getUnits(args map[string]interface{}) string {
|
||||||
|
if v, ok := args["units"].(string); ok && (v == "imperial" || v == "metric") {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return "metric"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) fetchWttr(location string) (*wttrResp, error) {
|
||||||
|
url := fmt.Sprintf("https://wttr.in/%s?format=j1", strings.ReplaceAll(location, " ", "%20"))
|
||||||
|
resp, err := p.client.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
var data wttrResp
|
||||||
|
if err := json.Unmarshal(body, &data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(data.CurrentCondition) == 0 {
|
||||||
|
return nil, fmt.Errorf("no weather data for: %s", location)
|
||||||
|
}
|
||||||
|
return &data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) displayName(data *wttrResp) string {
|
||||||
|
if len(data.NearestArea) == 0 {
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
area := data.NearestArea[0]
|
||||||
|
name := ""
|
||||||
|
if len(area.AreaName) > 0 {
|
||||||
|
name = area.AreaName[0].Value
|
||||||
|
}
|
||||||
|
region := ""
|
||||||
|
if len(area.Region) > 0 {
|
||||||
|
region = area.Region[0].Value
|
||||||
|
}
|
||||||
|
country := ""
|
||||||
|
if len(area.Country) > 0 {
|
||||||
|
country = area.Country[0].Value
|
||||||
|
}
|
||||||
|
var parts []string
|
||||||
|
if name != "" {
|
||||||
|
parts = append(parts, name)
|
||||||
|
}
|
||||||
|
if region != "" && region != name {
|
||||||
|
parts = append(parts, region)
|
||||||
|
}
|
||||||
|
if country != "" {
|
||||||
|
parts = append(parts, country)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertCtoF(c string) string {
|
||||||
|
if v, err := strconv.ParseFloat(c, 64); err == nil {
|
||||||
|
return fmt.Sprintf("%.0f", v*9/5+32)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleCurrent(args map[string]interface{}) (interface{}, error) {
|
||||||
|
location := p.getLoc(args)
|
||||||
|
if location == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "No location specified. Provide a city name or set default_location."}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
units := p.getUnits(args)
|
||||||
|
|
||||||
|
data, err := p.fetchWttr(location)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Weather request failed: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cc := data.CurrentCondition[0]
|
||||||
|
place := p.displayName(data)
|
||||||
|
|
||||||
|
desc := ""
|
||||||
|
if len(cc.WeatherDesc) > 0 {
|
||||||
|
desc = cc.WeatherDesc[0].Value
|
||||||
|
}
|
||||||
|
|
||||||
|
unitStr := "°C"
|
||||||
|
windUnit := "km/h"
|
||||||
|
tempStr := cc.TempC
|
||||||
|
feelsStr := cc.FeelsLikeC
|
||||||
|
if units == "imperial" {
|
||||||
|
unitStr = "°F"
|
||||||
|
windUnit = "mph"
|
||||||
|
tempStr = convertCtoF(tempStr)
|
||||||
|
feelsStr = convertCtoF(feelsStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
obsTime := cc.LocalObsDateTime
|
||||||
|
if len(obsTime) > 16 {
|
||||||
|
obsTime = obsTime[:16]
|
||||||
|
}
|
||||||
|
|
||||||
|
result := fmt.Sprintf("🌤 %s — %s\n🌡 %s%s (体感 %s%s)\n💧 湿度 %s%% | 💨 风速 %s %s %s\n🕐 %s",
|
||||||
|
place, desc,
|
||||||
|
tempStr, unitStr, feelsStr, unitStr,
|
||||||
|
cc.Humidity, cc.WindspeedKmph, windUnit, cc.Winddir16Point,
|
||||||
|
obsTime)
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": result,
|
||||||
|
"location": place,
|
||||||
|
"temp": cc.TempC,
|
||||||
|
"feels_like": cc.FeelsLikeC,
|
||||||
|
"humidity": cc.Humidity,
|
||||||
|
"wind_speed": cc.WindspeedKmph,
|
||||||
|
"weather": desc,
|
||||||
|
"observed": obsTime,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleForecast(args map[string]interface{}) (interface{}, error) {
|
||||||
|
location := p.getLoc(args)
|
||||||
|
if location == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "No location specified."}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
days := 3
|
||||||
|
if v, ok := args["days"].(float64); ok {
|
||||||
|
d := int(v)
|
||||||
|
if d >= 1 && d <= 7 {
|
||||||
|
days = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
units := p.getUnits(args)
|
||||||
|
|
||||||
|
data, err := p.fetchWttr(location)
|
||||||
|
if err != nil {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Forecast request failed: " + err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
place := p.displayName(data)
|
||||||
|
|
||||||
|
unitStr := "°C"
|
||||||
|
if units == "imperial" {
|
||||||
|
unitStr = "°F"
|
||||||
|
}
|
||||||
|
|
||||||
|
dayCount := days
|
||||||
|
if dayCount > len(data.Weather) {
|
||||||
|
dayCount = len(data.Weather)
|
||||||
|
}
|
||||||
|
daysData := data.Weather[:dayCount]
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
lines = append(lines, fmt.Sprintf("📅 %d日天气预报 — %s", days, place))
|
||||||
|
for _, day := range daysData {
|
||||||
|
t, err := time.Parse("2006-01-02", day.Date)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
weekday := t.Weekday().String()[:3]
|
||||||
|
|
||||||
|
maxT := day.MaxtempC
|
||||||
|
minT := day.MintempC
|
||||||
|
desc := ""
|
||||||
|
precip := ""
|
||||||
|
|
||||||
|
if len(day.Hourly) > 0 {
|
||||||
|
mid := len(day.Hourly) / 2
|
||||||
|
if len(day.Hourly[mid].WeatherDesc) > 0 {
|
||||||
|
desc = day.Hourly[mid].WeatherDesc[0].Value
|
||||||
|
}
|
||||||
|
totalPrecip := 0.0
|
||||||
|
for _, h := range day.Hourly {
|
||||||
|
if pv, err := strconv.ParseFloat(h.PrecipMM, 64); err == nil {
|
||||||
|
totalPrecip += pv
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if totalPrecip > 0 {
|
||||||
|
precip = fmt.Sprintf(" 🌧%.1fmm", totalPrecip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if units == "imperial" {
|
||||||
|
maxT = convertCtoF(maxT)
|
||||||
|
minT = convertCtoF(minT)
|
||||||
|
}
|
||||||
|
|
||||||
|
sunrise, sunset := "", ""
|
||||||
|
if len(day.Astronomy) > 0 {
|
||||||
|
sunrise = day.Astronomy[0].Sunrise
|
||||||
|
sunset = day.Astronomy[0].Sunset
|
||||||
|
}
|
||||||
|
|
||||||
|
datePart := ""
|
||||||
|
if len(day.Date) >= 8 {
|
||||||
|
datePart = day.Date[5:7] + "/" + day.Date[8:]
|
||||||
|
}
|
||||||
|
line := fmt.Sprintf(" %s %s — %s~%s%s %s", weekday, datePart, minT, maxT, unitStr, desc)
|
||||||
|
if precip != "" {
|
||||||
|
line += precip
|
||||||
|
}
|
||||||
|
if sunrise != "" && sunset != "" {
|
||||||
|
line += fmt.Sprintf(" 🌅%s 🌇%s", sunrise, sunset)
|
||||||
|
}
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
cc := data.CurrentCondition[0]
|
||||||
|
nowDesc := ""
|
||||||
|
if len(cc.WeatherDesc) > 0 {
|
||||||
|
nowDesc = cc.WeatherDesc[0].Value
|
||||||
|
}
|
||||||
|
lines = append(lines, fmt.Sprintf("\n当前:%s %s°C", nowDesc, cc.TempC))
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"content": strings.Join(lines, "\n"),
|
||||||
|
"location": place,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) handleSetLocation(args map[string]interface{}) (interface{}, error) {
|
||||||
|
loc, _ := args["location"].(string)
|
||||||
|
if loc == "" {
|
||||||
|
return map[string]interface{}{"isError": true, "content": "Location is required"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p.sdk.Settings().Set("default_location", loc)
|
||||||
|
p.defaultLoc = loc
|
||||||
|
return map[string]interface{}{"content": fmt.Sprintf("Default location set to: %s", loc)}, nil
|
||||||
|
}
|
||||||
2
go.mod
2
go.mod
@ -1,3 +1,3 @@
|
|||||||
module gitcode.com/JianFeeeee/homeagent-sdk
|
module gitcode.com/JianFeeeee/homeagent-sdk
|
||||||
|
|
||||||
go 1.25.0
|
go 1.21.0
|
||||||
|
|||||||
78
meta/meta.go
78
meta/meta.go
@ -5,7 +5,52 @@ package meta
|
|||||||
var (
|
var (
|
||||||
// Version 是 HomeAgent SDK 版本号。
|
// Version 是 HomeAgent SDK 版本号。
|
||||||
// 通过 `-ldflags="-X gitcode.com/JianFeeeee/homeagent-sdk/meta.Version=vX.Y.Z"` 注入。
|
// 通过 `-ldflags="-X gitcode.com/JianFeeeee/homeagent-sdk/meta.Version=vX.Y.Z"` 注入。
|
||||||
Version = "0.7.1"
|
//
|
||||||
|
// 版本号语义:**SDK 版本跟随核心的中版本,patch 位恒为 .0**。
|
||||||
|
// 整条核心 1.1.x 线(1.1.0、1.1.1、1.1.7…)共用 SDK 1.1.0;
|
||||||
|
// 只有核心进入 1.2.0 这种中版本跃迁时 SDK 才升到 1.2.0。
|
||||||
|
// 这样插件开发者只需关心「我在为哪个中版本写插件」,
|
||||||
|
// 不必跟着核心的每个 bugfix 换 SDK 依赖(见 核心仓 docs/git-branching.md §七)。
|
||||||
|
//
|
||||||
|
// 1.0.0:插件运行模型从 C ABI 动态库改为子进程 + 共享内存。
|
||||||
|
// 公开 SDK 接口零改动,但产物形态变了(plugin.so → plugin.bin)。
|
||||||
|
// 1.1.0:多模态贯通插件边界。**全部是新增,无签名变更**:
|
||||||
|
// - Triple.SentenceText / Triple.MediaDigests
|
||||||
|
// - Doc.MediaDigests / Doc.Attachments、MediaAttachment
|
||||||
|
// - TextEvent.Attachments
|
||||||
|
// - DocMemoryAPI.InsertWithMedia
|
||||||
|
// - IOInjector 的 InjectInputMedia / InjectInputMediaSync /
|
||||||
|
// InjectInterruptMedia;PluginSDK 补上缺失的 SetToolBlocks 包装
|
||||||
|
// 同版修掉两处并发竞态(sdk/stress_test.go 的 -race 实证,不是理论风险):
|
||||||
|
// PluginSDK 的 API 字段与 autoRestart 标志此前无锁,而写方
|
||||||
|
// (内核注入 API、插件 SetAutoRestart)与读方(插件后台 goroutine
|
||||||
|
// 注入、内核 registry 读 AutoRestart)天然跨 goroutine。
|
||||||
|
// 存量插件不需要改一行也不需要重编:新增方法由**插件调用、内核实现**,
|
||||||
|
// 不调就不受影响。想用新字段的插件重编即可。
|
||||||
|
//
|
||||||
|
// 1.2.0:注入行为的记忆/裁剪标志位。**全部是新增,无签名变更**:
|
||||||
|
// - InjectOptions{NoMemory, ContextPolicy}
|
||||||
|
// - IOInjector 的六个 *Opts 变体(排队/中断/同步/带媒体各一对)
|
||||||
|
// - ChannelDef.ContextPolicy(顺带给 ChannelDef 补上 JSON tag:
|
||||||
|
// 它要跨进程传给内核,而 Cleaner 是函数必须忽略;无 tag 时只能
|
||||||
|
// 手写字段白名单,新增字段会被静默丢掉)
|
||||||
|
// 语义:零值 InjectOptions 与旧的三参数方法完全等价(记入记忆 +
|
||||||
|
// 不裁剪),因此存量插件不需要改一行也不需要重编。
|
||||||
|
// 裁剪(ContextPolicy=prune)必须显式声明——它会归档丢弃低相关事件。
|
||||||
|
//
|
||||||
|
// ❗main 分支上此值是**下一个未发布中版本**;已发布的值看对应的
|
||||||
|
// release/vX.Y.x 分支与 tag(见 核心仓 docs/git-branching.md §2.1 与 §七.1)。
|
||||||
|
//
|
||||||
|
// 现为 1.2.0:核心的 1.2.x 线正在发布中(release/v1.2.x 承载 1.2.0),
|
||||||
|
// 但 **SDK 不跟 beta 发版**(§七.2)——SDK 1.2.0 的定版与 tag 随核心的
|
||||||
|
// **正式** tag 一起做(§七.3)。在那之前 1.2.0 仍是 SDK 尚未发布的中版本,
|
||||||
|
// 所以 main 就停在 1.2.0。
|
||||||
|
//
|
||||||
|
// 注意:这里与核心 main **故意不对称**。核心一旦切出 release/v1.2.x,
|
||||||
|
// 1.2.0 就归发布线所有,main 立刻推进到 1.3.0;而 SDK 因为要等正式 tag,
|
||||||
|
// 它的 main 在 v1.2.0 打出来之前不得越过 1.2.0。
|
||||||
|
// (曾误按 §七.4 把这里推到 1.3.0,等于宣称 1.2.0 已发布。)
|
||||||
|
Version = "1.2.0"
|
||||||
|
|
||||||
// Commit 是构建时的 Git commit hash。
|
// Commit 是构建时的 Git commit hash。
|
||||||
Commit = "unknown"
|
Commit = "unknown"
|
||||||
@ -15,9 +60,40 @@ var (
|
|||||||
|
|
||||||
// SDKName 是 SDK 名称。
|
// SDKName 是 SDK 名称。
|
||||||
SDKName = "HomeAgent SDK"
|
SDKName = "HomeAgent SDK"
|
||||||
|
|
||||||
|
// CoreModule 是核心仓的 Go module path,供 hmapdev 生成 go.mod 时使用。
|
||||||
|
CoreModule = "gitcode.com/JianFeeeee/HomeAgent"
|
||||||
|
|
||||||
|
// CoreVersion 是此 SDK 所兼容的最低核心版本。
|
||||||
|
//
|
||||||
|
// 1.0.0 是硬下限而非建议值:0.9.x 内核只会 dlopen `.so`,
|
||||||
|
// 本版工具链产出的 `plugin.bin` 在旧内核上根本不会被识别。
|
||||||
|
//
|
||||||
|
// ⚠️ 1.1.0 新增的媒体接口需要核心 **1.1.1+**(更早的核心没有
|
||||||
|
// doc.insertWithMedia / io.injectMedia* 这些 RPC,调用会返回 unknown method)。
|
||||||
|
// 这里仍写 1.0.0,因为它是「SDK 能在其上运行」的下限;
|
||||||
|
// 媒体接口是可选能力,不用就不受影响。
|
||||||
|
//
|
||||||
|
// ⚠️ 1.2.0 新增的注入标志位同理需要核心 **1.2.0+**:内核在 1.2.0 之前会
|
||||||
|
// 忽略注入参数里的 no_memory/context_policy 字段(不会报错,但不生效)。
|
||||||
|
// 想用这些标志位的插件应当要求核心 1.2.0+;不用就不受影响。
|
||||||
|
CoreVersion = "1.0.0"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FullVersion 返回完整的版本字符串。
|
// FullVersion 返回完整的版本字符串。
|
||||||
func FullVersion() string {
|
func FullVersion() string {
|
||||||
return SDKName + " v" + Version + " (" + Commit + ")"
|
return SDKName + " v" + Version + " (" + Commit + ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 协议版本 ----
|
||||||
|
//
|
||||||
|
// 子进程 RPC 的协议版本是一个独立的小整数,与 SDK/内核语义版本解耦:
|
||||||
|
// 语义版本变动频繁(修 bug、加字段),而 wire 协议只在**帧格式或握手语义**
|
||||||
|
// 变化时才升。当前值见核心仓 internal/plugin/proc/protocol.go 的 ProtocolVersion。
|
||||||
|
//
|
||||||
|
// C ABI 时代的 ABIVersion / CABINum / 51 个 Core<Method> 整数 ID 已随
|
||||||
|
// Part 6.2 删除 internal/plugin/cabi/ 一并退场:
|
||||||
|
// - 整数 method id 平移为 method 名字符串(proc/protocol.go 的 Method* 常量)
|
||||||
|
// - 版本协商改为握手帧里的 protocol 字段
|
||||||
|
//
|
||||||
|
// 保留那些常量只会让人以为它们还在生效。
|
||||||
|
|||||||
150
package/build-examples.sh
Normal file
150
package/build-examples.sh
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 给 SDK 发版打包**示例插件**的 .hmap 产物。
|
||||||
|
#
|
||||||
|
# 为什么要在 SDK 仓库里发示例插件的 hmap:
|
||||||
|
# 插件二进制与内核是**协议绑定**的(internal/plugin/proc/protocol.go 的
|
||||||
|
# ProtocolVersion + 统一共享内存区魔数)。SDK 升版往往同时意味着协议变化,
|
||||||
|
# 而示例插件(qq/memo/browser/…)是使用者最常直接安装的东西。
|
||||||
|
# 如果 SDK 只发工具链不发示例产物,使用者要么自己重编、要么用到与本版 SDK
|
||||||
|
# 不匹配的旧产物——后者的表现是握手失败(协议/魔数不匹配),而且看起来像
|
||||||
|
# 「插件坏了」而不是「版本不配套」。
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# package/build-examples.sh [TARGET] [OUT_DIR]
|
||||||
|
# TARGET native(默认) | linux/amd64 | linux/arm64 | darwin/amd64 | darwin/arm64 | windows/amd64 | all
|
||||||
|
# OUT_DIR 产物目录(默认 build/examples)
|
||||||
|
#
|
||||||
|
# 产物:
|
||||||
|
# <OUT_DIR>/<name>_<goos>_<goarch>.hmap 每个示例插件一份
|
||||||
|
# <OUT_DIR>/SHA256SUMS 全部产物齐全**之后**才计算
|
||||||
|
# <OUT_DIR>/MANIFEST.txt 版本、协议版本、产自哪个 commit
|
||||||
|
#
|
||||||
|
# 纪律(与本项目其它构建脚本一致):
|
||||||
|
# 1. 判成功看**产物是否存在**,不看退出码——hmapdev 对部分错误只打印不退出。
|
||||||
|
# 2. SHA256SUMS 必须在全部产物生成完毕后一次算完,边打边算会漏掉后生成的包。
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
TARGET="${1:-native}"
|
||||||
|
OUT_DIR="${2:-$SDK_ROOT/build/examples}"
|
||||||
|
GO="${GO:-$(command -v go 2>/dev/null || echo go)}"
|
||||||
|
|
||||||
|
case "$TARGET" in
|
||||||
|
native) GOOS=""; GOARCH="" ;;
|
||||||
|
linux/amd64) GOOS=linux; GOARCH=amd64 ;;
|
||||||
|
linux/arm64) GOOS=linux; GOARCH=arm64 ;;
|
||||||
|
darwin/amd64) GOOS=darwin; GOARCH=amd64 ;;
|
||||||
|
darwin/arm64) GOOS=darwin; GOARCH=arm64 ;;
|
||||||
|
windows/amd64)
|
||||||
|
# 明确拒绝,而不是让调用方拿到一句深层 Go 编译错误。
|
||||||
|
# 协议 2 的统一共享内存区只移植到了 Unix:内核 internal/plugin/proc/
|
||||||
|
# shmpass_windows.go 仍是旧的 SHM_STAGE/SHM_EVTRING 两段布局,
|
||||||
|
# 插件模板 proc_shm_windows.go 也缺 attachUnifiedShm。
|
||||||
|
echo "windows 目标暂不支持:协议 2 的统一共享内存区未移植到 Windows(内核与插件模板均缺实现)。" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
all)
|
||||||
|
echo "本脚本一次只构建一个平台;请由 package/build.sh 传入具体目标。" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown target: $TARGET" >&2
|
||||||
|
echo "Usage: $0 [native|linux/amd64|linux/arm64|darwin/amd64|darwin/arm64|windows/amd64|all] [OUT_DIR]" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
export CGO_ENABLED=0
|
||||||
|
|
||||||
|
# 按平台逐个构建,**不用** bundle 模式:
|
||||||
|
# - bundle 会连 windows 一起编,而协议 2 的统一共享区尚未移植到 Windows
|
||||||
|
# (内核 shmpass_windows.go 仍是旧的两段布局),必然失败;
|
||||||
|
# - 逐平台构建每个目标都产出一份 .hmap,正是发版要附的产物。
|
||||||
|
# 平台名解析成本脚本后面用(校验和与 MANIFEST 都要写清楚是哪个平台)。
|
||||||
|
if [ -z "${GOOS:-}" ]; then
|
||||||
|
GOOS="$(go env GOOS)"; GOARCH="$(go env GOARCH)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 1) 先保证工具链可用:示例必须用**本仓当前源码**构建,否则产物协议与这一版 SDK 不符。
|
||||||
|
# 允许外部指定(发版脚本会在跨平台构建后把刚产出的工具链路径传进来)。
|
||||||
|
# 工具链二进制名由 plugindev 改为 hmapdev;旧变量名 PLUGINDEV 仍兼容。
|
||||||
|
HMAPDEV="${HMAPDEV:-${PLUGINDEV:-$SDK_ROOT/build/hmapdev}}"
|
||||||
|
if [ ! -x "$PLUGINDEV" ]; then
|
||||||
|
echo "[examples] 先构建 hmapdev ..."
|
||||||
|
( cd "$SDK_ROOT/tools/hmapdev" && "$GO" build -o "$HMAPDEV" . ) || {
|
||||||
|
echo "[examples] hmapdev 构建失败,无法继续" >&2; exit 1; }
|
||||||
|
fi
|
||||||
|
if [ ! -x "$PLUGINDEV" ]; then
|
||||||
|
echo "[examples] hmapdev 不存在或不可执行:$HMAPDEV" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== 协议 ==="
|
||||||
|
echo " ProtocolVersion = $(grep -m1 '^const ProtocolVersion' "$SDK_ROOT/../internal/plugin/proc/protocol.go" 2>/dev/null | grep -oE '[0-9]+' || echo '?(本仓非内核仓,跳过)')"
|
||||||
|
|
||||||
|
mkdir -p "$OUT_DIR"
|
||||||
|
# 清掉上一次的校验和:残留的 SHA256SUMS 会掩盖本次缺产物。
|
||||||
|
rm -f "$OUT_DIR"/SHA256SUMS "$OUT_DIR"/MANIFEST.txt
|
||||||
|
|
||||||
|
ok=0
|
||||||
|
fail=0
|
||||||
|
failed_names=""
|
||||||
|
|
||||||
|
for dir in "$SDK_ROOT"/example/*/; do
|
||||||
|
[ -f "$dir/plugin.go" ] || continue
|
||||||
|
name="$(basename "$dir")"
|
||||||
|
|
||||||
|
# 清掉旧产物:残留会让人(和本脚本)误判成功。
|
||||||
|
rm -rf "$dir/build" "$dir/dist"
|
||||||
|
|
||||||
|
out=$( cd "$dir" && "$PLUGINDEV" build --no-bundle --target "$GOOS/$GOARCH" 2>&1 )
|
||||||
|
rc=$?
|
||||||
|
|
||||||
|
# 判据是**退出码 + 产物存在**,两者都要。
|
||||||
|
# 只看退出码:hmapdev 曾经出错也退 0(已修,但脚本不该依赖它「现在」是对的)。
|
||||||
|
# 只看产物:部分平台失败时会留下上一次的产物,看起来像成功。
|
||||||
|
hmap="$(ls "$dir"/dist/*.hmap 2>/dev/null | head -1)"
|
||||||
|
if [ $rc -eq 0 ] && [ -n "$hmap" ]; then
|
||||||
|
# 保留插件自己声明的产物名(它用的是 plg.json 的 name_en,是插件的身份),
|
||||||
|
# 只在前面加平台前缀避免多平台互相覆盖。
|
||||||
|
dest="$OUT_DIR/${GOOS}_${GOARCH}_$(basename "$hmap")"
|
||||||
|
cp "$hmap" "$dest"
|
||||||
|
printf "✓ %-14s → %s (%s)\n" "$name" "$(basename "$dest")" "$(du -h "$dest" | cut -f1)"
|
||||||
|
ok=$((ok + 1))
|
||||||
|
else
|
||||||
|
printf "✗ %-14s 构建失败 (rc=%d)\n" "$name" "$rc"
|
||||||
|
echo "$out" | tail -6 | sed 's/^/ /'
|
||||||
|
fail=$((fail + 1))
|
||||||
|
failed_names="$failed_names $name"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "示例产物: 成功 $ok / 失败 $fail"
|
||||||
|
[ -n "$failed_names" ] && echo "失败:$failed_names"
|
||||||
|
|
||||||
|
# 有失败就不算发版闭环:宁可整个中断,也不要发出「少几个插件」的包。
|
||||||
|
if [ $fail -ne 0 ]; then
|
||||||
|
echo "[examples] 有示例构建失败,不生成 SHA256SUMS" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2) 全部产物齐了才算校验和。
|
||||||
|
( cd "$OUT_DIR" && sha256sum ./*.hmap > SHA256SUMS )
|
||||||
|
|
||||||
|
VERSION="${VERSION:-$(git -C "$SDK_ROOT" describe --tags --dirty 2>/dev/null || echo unknown)}"
|
||||||
|
COMMIT="${COMMIT:-$(git -C "$SDK_ROOT" rev-parse --short HEAD 2>/dev/null || echo unknown)}"
|
||||||
|
{
|
||||||
|
echo "sdk_version: $VERSION"
|
||||||
|
echo "sdk_commit: $COMMIT"
|
||||||
|
echo "target: $GOOS/$GOARCH"
|
||||||
|
echo "plugins: $ok"
|
||||||
|
echo "built_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
echo
|
||||||
|
echo "这些 .hmap 与本版 SDK 的插件协议绑定,必须与同版本内核配套安装。"
|
||||||
|
echo "校验:sha256sum -c SHA256SUMS"
|
||||||
|
} > "$OUT_DIR/MANIFEST.txt"
|
||||||
|
|
||||||
|
echo "[examples] 产物: $OUT_DIR"
|
||||||
|
echo "[examples] 清单: $OUT_DIR/MANIFEST.txt"
|
||||||
|
echo "[examples] 校验: $OUT_DIR/SHA256SUMS"
|
||||||
108
package/build.sh
Executable file
108
package/build.sh
Executable file
@ -0,0 +1,108 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
BUILD_DIR="${PROJECT_ROOT}/build"
|
||||||
|
VERSION="${VERSION:-$(git -C "$PROJECT_ROOT" describe --tags --dirty 2>/dev/null || echo "0.7.1")}"
|
||||||
|
GO="${GO:-$(command -v go 2>/dev/null || echo "/home/jianf/go1.26.5/go/bin/go")}"
|
||||||
|
# 宿主平台必须在**本脚本 export GOOS/GOARCH 之前**取定。
|
||||||
|
# 否则 `go env GOOS` 会返回被 export 的目标平台(此前 `build.sh all all`
|
||||||
|
# 就是因此拿 darwin 二进制在 linux 上跑,报 cannot execute binary file)。
|
||||||
|
NATIVE_GOOS="$(env -u GOOS -u GOARCH "$GO" env GOOS 2>/dev/null || uname -s | tr 'A-Z' 'a-z')"
|
||||||
|
NATIVE_GOARCH="$(env -u GOOS -u GOARCH "$GO" env GOARCH 2>/dev/null || uname -m)"
|
||||||
|
case "$NATIVE_GOARCH" in x86_64|amd64) NATIVE_GOARCH="amd64" ;; aarch64|arm64) NATIVE_GOARCH="arm64" ;; esac
|
||||||
|
case "$NATIVE_GOOS" in darwin|linux|windows) ;; *) NATIVE_GOOS="linux" ;; esac
|
||||||
|
GOCACHE="${GOCACHE:-}"
|
||||||
|
GOPATH="${GOPATH:-}"
|
||||||
|
|
||||||
|
TARGET="${1:-native}"
|
||||||
|
COMPONENT="${2:-all}"
|
||||||
|
|
||||||
|
case "$TARGET" in
|
||||||
|
native) GOOS="" GOARCH="" ;;
|
||||||
|
linux/amd64) GOOS=linux GOARCH=amd64 ;;
|
||||||
|
linux/arm64) GOOS=linux GOARCH=arm64 ;;
|
||||||
|
darwin/amd64) GOOS=darwin GOARCH=amd64 ;;
|
||||||
|
darwin/arm64) GOOS=darwin GOARCH=arm64 ;;
|
||||||
|
windows/amd64) GOOS=windows GOARCH=amd64 ;;
|
||||||
|
all)
|
||||||
|
"$0" linux/amd64 "$COMPONENT"
|
||||||
|
"$0" linux/arm64 "$COMPONENT"
|
||||||
|
"$0" darwin/amd64 "$COMPONENT"
|
||||||
|
"$0" darwin/arm64 "$COMPONENT"
|
||||||
|
"$0" windows/amd64 "$COMPONENT"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown target: $TARGET"
|
||||||
|
echo "Usage: $0 [native|linux/amd64|linux/arm64|darwin/amd64|darwin/arm64|windows/amd64|all] [all|hmapdev|examples]"
|
||||||
|
exit 1
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [ -n "${GOOS:-}" ]; then
|
||||||
|
SUFFIX="${GOOS}_${GOARCH}"
|
||||||
|
export GOOS GOARCH
|
||||||
|
fi
|
||||||
|
export CGO_ENABLED=0
|
||||||
|
[ -n "$GOCACHE" ] && export GOCACHE
|
||||||
|
[ -n "$GOPATH" ] && export GOPATH
|
||||||
|
|
||||||
|
mkdir -p "$BUILD_DIR"
|
||||||
|
|
||||||
|
build_hmapdev() {
|
||||||
|
local src="tools/hmapdev"
|
||||||
|
local out="$BUILD_DIR/hmapdev${SUFFIX:+_$SUFFIX}"
|
||||||
|
if [ "$GOOS" = "windows" ]; then out="${out}.exe"; fi
|
||||||
|
|
||||||
|
echo "[BUILD] hmapdev ${GOOS:-linux}/${GOARCH:-amd64} → $out"
|
||||||
|
cd "$PROJECT_ROOT/$src"
|
||||||
|
"$GO" build -trimpath -ldflags "-X gitcode.com/JianFeeeee/homeagent-sdk/meta.Version=${VERSION}" \
|
||||||
|
-o "$out" .
|
||||||
|
echo " OK ($(du -h "$out" | cut -f1))"
|
||||||
|
cd "$PROJECT_ROOT"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 示例插件产物随 SDK 一起发。
|
||||||
|
#
|
||||||
|
# 为什么必须发:插件二进制与内核是**协议绑定**的(ProtocolVersion + 统一共享
|
||||||
|
# 内存区魔数)。SDK 升版常伴随协议变化,只发工具链不发示例产物,使用者很可能
|
||||||
|
# 拿旧产物去装,表现是握手失败(魔数不匹配)——看起来像「插件坏了」而不是
|
||||||
|
# 「版本不配套」。
|
||||||
|
#
|
||||||
|
# 用**宿主可执行**的那把工具链(而非 PATH 里的),保证产物与本次发版同源。
|
||||||
|
#
|
||||||
|
# 为什么不能用目标平台的那把:示例的跨平台构建是由 hmapdev 的 `--target GOOS/GOARCH`
|
||||||
|
# 完成的,被执行的进程本身必須能在当前机器上跑。拿目标平台的二进制去跑只会得到
|
||||||
|
# “cannot execute binary file: Exec format error”(`build.sh all all` 在 darwin 处断过)。
|
||||||
|
build_examples() {
|
||||||
|
local dev
|
||||||
|
dev="$BUILD_DIR/hmapdev_${NATIVE_GOOS}_${NATIVE_GOARCH}"
|
||||||
|
[ "$NATIVE_GOOS" = "windows" ] && dev="${dev}.exe"
|
||||||
|
# 宿主工具链缺失时先补建(`all` 的第一个目标可能不是宿主平台)。
|
||||||
|
if [ ! -x "$dev" ]; then
|
||||||
|
echo "[BUILD] 先补建宿主工具链 ${NATIVE_GOOS}/${NATIVE_GOARCH}(示例的跨平台由 --target 完成)"
|
||||||
|
( unset GOOS GOARCH; bash "$0" "${NATIVE_GOOS}/${NATIVE_GOARCH}" hmapdev ) || return 1
|
||||||
|
fi
|
||||||
|
if [ ! -x "$dev" ]; then
|
||||||
|
echo "[BUILD] 无法构建示例:缺少宿主可执行的工具链 $dev" >&2
|
||||||
|
echo " 先跑: $0 ${NATIVE_GOOS}/${NATIVE_GOARCH} hmapdev" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "[BUILD] example plugins ${GOOS:-linux}/${GOARCH:-amd64} → $BUILD_DIR/examples(用 ${NATIVE_GOOS}/${NATIVE_GOARCH} 的工具链交叉构建)"
|
||||||
|
PLUGINDEV="$dev" VERSION="$VERSION" bash "$PROJECT_ROOT/package/build-examples.sh" "$TARGET" "$BUILD_DIR/examples"
|
||||||
|
echo " OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$COMPONENT" in
|
||||||
|
all)
|
||||||
|
# 工具链必须先建完:示例用它来构建(同源保证协议一致)。
|
||||||
|
build_hmapdev
|
||||||
|
build_examples
|
||||||
|
;;
|
||||||
|
hmapdev) build_hmapdev ;;
|
||||||
|
examples) build_examples ;;
|
||||||
|
*)
|
||||||
|
echo "Unknown component: $COMPONENT"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
137
package/toolchain.nsi
Normal file
137
package/toolchain.nsi
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
!include "MUI2.nsh"
|
||||||
|
!include "nsDialogs.nsh"
|
||||||
|
!include "LogicLib.nsh"
|
||||||
|
!include "x64.nsh"
|
||||||
|
!include "WinVer.nsh"
|
||||||
|
|
||||||
|
!define PRODUCT_NAME "HomeAgent Toolchain"
|
||||||
|
!define PRODUCT_PUBLISHER "HomeAgent Team"
|
||||||
|
!define PRODUCT_VERSION "0.7.1"
|
||||||
|
!define PRODUCT_DISPLAY_NAME "HomeAgent 工具链"
|
||||||
|
!define OUTPUT_FILE "HomeAgent_v${PRODUCT_VERSION}_Toolchain_win64.exe"
|
||||||
|
!define SDK_VERSION "v0.7.1"
|
||||||
|
|
||||||
|
Name "${PRODUCT_DISPLAY_NAME} v${PRODUCT_VERSION}"
|
||||||
|
OutFile "${OUTPUT_FILE}"
|
||||||
|
InstallDir "$PROGRAMFILES64\${PRODUCT_NAME}"
|
||||||
|
InstallDirRegKey HKLM "Software\${PRODUCT_NAME}" ""
|
||||||
|
RequestExecutionLevel admin
|
||||||
|
BrandingText "HomeAgent Toolchain Installer"
|
||||||
|
SetCompressor /SOLID lzma
|
||||||
|
ShowInstDetails show
|
||||||
|
ShowUninstDetails show
|
||||||
|
|
||||||
|
Var hasGit
|
||||||
|
Var sdkInstallOk
|
||||||
|
|
||||||
|
!insertmacro MUI_PAGE_WELCOME
|
||||||
|
!insertmacro MUI_PAGE_DIRECTORY
|
||||||
|
Page custom pageConfirm pageConfirmLeave
|
||||||
|
!insertmacro MUI_PAGE_INSTFILES
|
||||||
|
!insertmacro MUI_PAGE_FINISH
|
||||||
|
|
||||||
|
!insertmacro MUI_LANGUAGE "SimpChinese"
|
||||||
|
!insertmacro MUI_LANGUAGE "English"
|
||||||
|
|
||||||
|
Function .onInit
|
||||||
|
!insertmacro MUI_LANGDLL_DISPLAY
|
||||||
|
StrCpy $hasGit "0"
|
||||||
|
StrCpy $sdkInstallOk "0"
|
||||||
|
FunctionEnd
|
||||||
|
|
||||||
|
Function pageConfirm
|
||||||
|
!insertmacro MUI_HEADER_TEXT "确认安装" "将安装 HomeAgent 工具链并自动下载 SDK ${SDK_VERSION}"
|
||||||
|
nsDialogs::Create 1018
|
||||||
|
Pop $0
|
||||||
|
${If} $0 == error
|
||||||
|
Abort
|
||||||
|
${EndIf}
|
||||||
|
${NSD_CreateLabel} 0 5u 100% 12u "将安装以下组件:"
|
||||||
|
Pop $0
|
||||||
|
${NSD_CreateLabel} 15u 20u 100% 12u "• hmapdev.exe — 插件开发工具"
|
||||||
|
Pop $0
|
||||||
|
${NSD_CreateLabel} 15u 35u 100% 12u "• SDK ${SDK_VERSION} — 将从远程仓库自动下载"
|
||||||
|
Pop $0
|
||||||
|
${NSD_CreateLabel} 0 60u 100% 20u "SDK 需要 Git 客户端。如果未安装 Git,请先安装:$\r$\nhttps://git-scm.com/downloads"
|
||||||
|
Pop $0
|
||||||
|
nsDialogs::Show
|
||||||
|
FunctionEnd
|
||||||
|
|
||||||
|
Function pageConfirmLeave
|
||||||
|
FunctionEnd
|
||||||
|
|
||||||
|
Section "Install" SEC_INSTALL
|
||||||
|
SetOutPath "$INSTDIR"
|
||||||
|
|
||||||
|
DetailPrint "复制工具链文件..."
|
||||||
|
File "hmapdev.exe"
|
||||||
|
|
||||||
|
DetailPrint "创建快捷方式..."
|
||||||
|
CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"
|
||||||
|
CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\hmapdev.lnk" "$INSTDIR\hmapdev.exe" "" "$INSTDIR\hmapdev.exe" 0
|
||||||
|
|
||||||
|
DetailPrint "配置环境变量..."
|
||||||
|
; Add to system PATH
|
||||||
|
ReadRegStr $0 HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "PATH"
|
||||||
|
${If} $0 != ""
|
||||||
|
${If} $0 != "*$INSTDIR*"
|
||||||
|
StrCpy $0 "$0;$INSTDIR"
|
||||||
|
WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "PATH" $0
|
||||||
|
${EndIf}
|
||||||
|
${Else}
|
||||||
|
WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "PATH" "$INSTDIR"
|
||||||
|
${EndIf}
|
||||||
|
WriteRegStr HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "HOMEAGENT_SDK_DIR" "$INSTDIR\sdk"
|
||||||
|
WriteRegStr HKLM "Software\${PRODUCT_NAME}" "" "$INSTDIR"
|
||||||
|
|
||||||
|
DetailPrint "检测 Git 客户端..."
|
||||||
|
nsExec::ExecToStack '"git" --version'
|
||||||
|
Pop $0
|
||||||
|
Pop $1
|
||||||
|
${If} $0 == 0
|
||||||
|
StrCpy $hasGit "1"
|
||||||
|
DetailPrint "Git 已安装: $1"
|
||||||
|
${Else}
|
||||||
|
DetailPrint "未检测到 Git,将跳过 SDK 自动下载"
|
||||||
|
DetailPrint "安装完成后请手动运行: hmapdev sdk install ${SDK_VERSION}"
|
||||||
|
${EndIf}
|
||||||
|
|
||||||
|
${If} $hasGit == "1"
|
||||||
|
DetailPrint "正在下载 SDK ${SDK_VERSION}..."
|
||||||
|
nsExec::ExecToStack '"$INSTDIR\hmapdev.exe" sdk install ${SDK_VERSION}'
|
||||||
|
Pop $0
|
||||||
|
Pop $1
|
||||||
|
${If} $0 == 0
|
||||||
|
StrCpy $sdkInstallOk "1"
|
||||||
|
DetailPrint "SDK ${SDK_VERSION} 下载完成"
|
||||||
|
DetailPrint "正在激活 SDK ${SDK_VERSION}..."
|
||||||
|
nsExec::Exec '"$INSTDIR\hmapdev.exe" sdk use ${SDK_VERSION}'
|
||||||
|
Pop $0
|
||||||
|
${Else}
|
||||||
|
DetailPrint "SDK 下载失败 (错误码: $0)"
|
||||||
|
DetailPrint "请手动运行: hmapdev sdk install ${SDK_VERSION}"
|
||||||
|
${EndIf}
|
||||||
|
${EndIf}
|
||||||
|
|
||||||
|
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "DisplayName" "${PRODUCT_DISPLAY_NAME} v${PRODUCT_VERSION}"
|
||||||
|
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "UninstallString" "$INSTDIR\Uninstall.exe"
|
||||||
|
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "InstallLocation" "$INSTDIR"
|
||||||
|
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "Publisher" "${PRODUCT_PUBLISHER}"
|
||||||
|
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "DisplayVersion" "${PRODUCT_VERSION}"
|
||||||
|
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "NoModify" 1
|
||||||
|
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" "NoRepair" 1
|
||||||
|
|
||||||
|
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||||
|
SectionEnd
|
||||||
|
|
||||||
|
Section "Uninstall"
|
||||||
|
Delete "$INSTDIR\Uninstall.exe"
|
||||||
|
Delete "$INSTDIR\hmapdev.exe"
|
||||||
|
RMDir /r "$INSTDIR\sdk"
|
||||||
|
RMDir "$INSTDIR"
|
||||||
|
Delete "$SMPROGRAMS\${PRODUCT_NAME}\hmapdev.lnk"
|
||||||
|
RMDir "$SMPROGRAMS\${PRODUCT_NAME}"
|
||||||
|
DeleteRegValue HKLM "SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "HOMEAGENT_SDK_DIR"
|
||||||
|
DeleteRegKey HKLM "Software\Microsoft\CurrentVersion\Uninstall\${PRODUCT_NAME}"
|
||||||
|
DeleteRegKey HKLM "Software\${PRODUCT_NAME}"
|
||||||
|
SectionEnd
|
||||||
116
remotedevice/CMakeLists.txt
Normal file
116
remotedevice/CMakeLists.txt
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.10)
|
||||||
|
project(ha_remotedevice VERSION 0.1.0 LANGUAGES C)
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# ha_remotedevice — HomeAgent 远程设备接入 C SDK
|
||||||
|
# 零外部依赖,纯 C 实现,兼容嵌入式平台。
|
||||||
|
#
|
||||||
|
# 使用方式:
|
||||||
|
# add_subdirectory(path/to/ha_remotedevice)
|
||||||
|
# target_link_libraries(my_app ha_remotedevice)
|
||||||
|
# target_include_directories(my_app PRIVATE
|
||||||
|
# ${HA_REMOTEDEVICE_INCLUDE_DIR})
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
# 选项: 构建为静态库或动态库
|
||||||
|
option(BUILD_SHARED_LIBS "Build ha_remotedevice as shared library" OFF)
|
||||||
|
|
||||||
|
# 选项: 禁用 malloc/free(用于裸机环境,用户需提供 alloc 回调)
|
||||||
|
option(HA_NO_ALLOC "Disable dynamic memory allocation" OFF)
|
||||||
|
|
||||||
|
# 选项: 日志级别
|
||||||
|
set(HA_LOG_LEVEL 2 CACHE STRING "Log level: 0=none, 1=error, 2=info, 3=debug")
|
||||||
|
|
||||||
|
# 源文件
|
||||||
|
set(HA_REMOTEDEVICE_SRC
|
||||||
|
src/ha_remotedevice.c
|
||||||
|
src/ha_json.c
|
||||||
|
src/ha_ws.c
|
||||||
|
)
|
||||||
|
|
||||||
|
# 头文件
|
||||||
|
set(HA_REMOTEDEVICE_INCLUDE
|
||||||
|
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||||
|
)
|
||||||
|
|
||||||
|
# 编译选项
|
||||||
|
if(HA_NO_ALLOC)
|
||||||
|
add_definitions(-DHA_NO_ALLOC)
|
||||||
|
endif()
|
||||||
|
add_definitions(-DHA_LOG_LEVEL=${HA_LOG_LEVEL})
|
||||||
|
|
||||||
|
# 创建库
|
||||||
|
if(BUILD_SHARED_LIBS)
|
||||||
|
add_library(ha_remotedevice SHARED ${HA_REMOTEDEVICE_SRC})
|
||||||
|
if(WIN32)
|
||||||
|
# Windows 需要导出符号
|
||||||
|
set_target_properties(ha_remotedevice PROPERTIES
|
||||||
|
WINDOWS_EXPORT_ALL_SYMBOLS ON)
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
add_library(ha_remotedevice STATIC ${HA_REMOTEDEVICE_SRC})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# 包含目录
|
||||||
|
target_include_directories(ha_remotedevice
|
||||||
|
PUBLIC ${HA_REMOTEDEVICE_INCLUDE}
|
||||||
|
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
|
||||||
|
)
|
||||||
|
|
||||||
|
# 不链接任何外部库
|
||||||
|
target_link_libraries(ha_remotedevice PRIVATE)
|
||||||
|
|
||||||
|
# 导出包含目录供外部项目使用
|
||||||
|
set(HA_REMOTEDEVICE_INCLUDE_DIR
|
||||||
|
${HA_REMOTEDEVICE_INCLUDE}
|
||||||
|
CACHE INTERNAL "ha_remotedevice include directories")
|
||||||
|
|
||||||
|
# 安装规则
|
||||||
|
install(TARGETS ha_remotedevice
|
||||||
|
EXPORT ha_remotedevice-targets
|
||||||
|
LIBRARY DESTINATION lib
|
||||||
|
ARCHIVE DESTINATION lib
|
||||||
|
RUNTIME DESTINATION bin
|
||||||
|
INCLUDES DESTINATION include
|
||||||
|
)
|
||||||
|
|
||||||
|
install(DIRECTORY include/
|
||||||
|
DESTINATION include
|
||||||
|
)
|
||||||
|
|
||||||
|
install(EXPORT ha_remotedevice-targets
|
||||||
|
DESTINATION lib/cmake/ha_remotedevice
|
||||||
|
NAMESPACE ha_remotedevice::
|
||||||
|
)
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 测试(可选)
|
||||||
|
# ============================================================
|
||||||
|
option(BUILD_TESTS "Build ha_remotedevice tests" OFF)
|
||||||
|
|
||||||
|
if(BUILD_TESTS)
|
||||||
|
find_package(Threads REQUIRED)
|
||||||
|
|
||||||
|
add_executable(ha_remotedevice_test
|
||||||
|
test/test_ha_remotedevice.c
|
||||||
|
)
|
||||||
|
target_link_libraries(ha_remotedevice_test
|
||||||
|
PRIVATE ha_remotedevice Threads::Threads
|
||||||
|
)
|
||||||
|
target_include_directories(ha_remotedevice_test
|
||||||
|
PRIVATE ${HA_REMOTEDEVICE_INCLUDE_DIR}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 添加测试
|
||||||
|
add_test(NAME ha_remotedevice_test
|
||||||
|
COMMAND ha_remotedevice_test
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 编译信息
|
||||||
|
# ============================================================
|
||||||
|
message(STATUS "ha_remotedevice ${PROJECT_VERSION}")
|
||||||
|
message(STATUS " Build type: $<CONFIG>")
|
||||||
|
message(STATUS " Shared lib: ${BUILD_SHARED_LIBS}")
|
||||||
|
message(STATUS " No alloc: ${HA_NO_ALLOC}")
|
||||||
216
remotedevice/include/ha_remotedevice.h
Normal file
216
remotedevice/include/ha_remotedevice.h
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
#ifndef HA_REMOTEDEVICE_H
|
||||||
|
#define HA_REMOTEDEVICE_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ==================================================================
|
||||||
|
* ha_remotedevice — 远程设备接入 C SDK
|
||||||
|
*
|
||||||
|
* 零外部依赖,纯 C 实现,兼容嵌入式平台。
|
||||||
|
* 传输层由用户实现(4 个函数指针),SDK 处理所有协议细节。
|
||||||
|
*
|
||||||
|
* 声明式设计:
|
||||||
|
* 设备在代码中声明自己是什么(kind)和能做什么(caps),
|
||||||
|
* 声明支持哪些命令(shell/camerasue/screensee/...)并注册对应处理函数,
|
||||||
|
* SDK 自动处理协议握手、心跳、消息路由、结果回执。
|
||||||
|
*
|
||||||
|
* 协议流程:
|
||||||
|
* TCP 连接 → WS 升级 → hello(设备声明) → bind(令牌) → 就绪
|
||||||
|
* 就绪后循环:读帧 → 按 handlers 表分发命令 → 自动回执结果
|
||||||
|
* ================================================================== */
|
||||||
|
|
||||||
|
/* ======================== 状态码 ======================== */
|
||||||
|
typedef enum {
|
||||||
|
HA_OK = 0,
|
||||||
|
HA_ERR_GENERIC = -1,
|
||||||
|
HA_ERR_NOMEM = -2,
|
||||||
|
HA_ERR_INVALID = -3,
|
||||||
|
HA_ERR_TIMEOUT = -4,
|
||||||
|
HA_ERR_DISCONNECTED = -5,
|
||||||
|
HA_ERR_PROTOCOL = -6,
|
||||||
|
HA_ERR_TRANSPORT = -7,
|
||||||
|
HA_ERR_NOT_FOUND = -8,
|
||||||
|
} ha_status_t;
|
||||||
|
|
||||||
|
/* ======================== 传输层抽象 ========================
|
||||||
|
*
|
||||||
|
* 用户必须实现这 4 个函数,适配不同平台(FreeRTOS+lwIP、Zephyr、裸机等)。
|
||||||
|
*
|
||||||
|
* connect(ctx, host, port) → 建立 TCP 连接,返回 0 成功
|
||||||
|
* send(ctx, data, len) → 发送 len 字节,返回实际发送字节数,-1 失败
|
||||||
|
* recv(ctx, buf, len) → 接收最多 len 字节,返回实际接收字节数,0 断开,-1 失败
|
||||||
|
* close(ctx) → 关闭连接
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
int (*connect)(void *ctx, const char *host, uint16_t port);
|
||||||
|
int (*send)(void *ctx, const uint8_t *data, int len);
|
||||||
|
int (*recv)(void *ctx, uint8_t *buf, int len);
|
||||||
|
void (*close)(void *ctx);
|
||||||
|
void *ctx;
|
||||||
|
} ha_transport_t;
|
||||||
|
|
||||||
|
/* ======================== 设备声明 ========================
|
||||||
|
*
|
||||||
|
* 声明式配置:设备在代码中声明自己的类型和能力。
|
||||||
|
* 这些信息通过 hello 消息发送给网关。
|
||||||
|
*
|
||||||
|
* device_id — 唯一标识,如 "esp32-cam-1"
|
||||||
|
* name — 设备显示名,如 "门口摄像头"
|
||||||
|
* kind — 设备种类,如 "camera"、"computer"、"speaker"、"light"
|
||||||
|
* caps — 能力数组,以 NULL 结尾,如 {"camera","status",NULL}
|
||||||
|
* info_json — 额外信息(JSON 字符串),可选,如 '{"chip":"ESP32-S3","psram":8}'
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
const char *device_id;
|
||||||
|
const char *name;
|
||||||
|
const char *kind;
|
||||||
|
const char **caps; /* NULL 结尾 */
|
||||||
|
const char *info_json; /* 可选,NULL 或 JSON 字符串 */
|
||||||
|
} ha_device_info_t;
|
||||||
|
|
||||||
|
/* ======================== 命令结果 ========================
|
||||||
|
*
|
||||||
|
* 命令处理函数通过填写此结构体返回数据。
|
||||||
|
* SDK 收到结果后自动发送回执(文本或二进制分块)。
|
||||||
|
*
|
||||||
|
* 使用方式:
|
||||||
|
* 1. 简单文本:设置 status=0, output="结果文本"
|
||||||
|
* 2. 二进制数据:设置 has_binary=1, binary_data/binary_len/mime
|
||||||
|
* 3. 错误:设置 status=1, error="错误信息"
|
||||||
|
*
|
||||||
|
* 注意:output 字符串由 SDK 内部 strdup 后发送,handler 返回后即可释放。
|
||||||
|
* 我们约定 handler 不负责分配,由 SDK 在内部做好拷贝。
|
||||||
|
* 所以 handler 可以返回栈上或静态字符串。
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
int status; /* 0=ok, 非0=error */
|
||||||
|
const char *output; /* 输出文本(如 base64 图像数据),SDK 内部拷贝 */
|
||||||
|
const char *error; /* 错误信息 */
|
||||||
|
int has_binary; /* 1=通过二进制分块回传 */
|
||||||
|
const char *binary_mime; /* 二进制 MIME 类型 */
|
||||||
|
const uint8_t *binary_data; /* 二进制数据指针 */
|
||||||
|
int binary_len; /* 二进制数据长度 */
|
||||||
|
} ha_cmd_result_t;
|
||||||
|
|
||||||
|
/* ======================== 命令处理声明 ========================
|
||||||
|
*
|
||||||
|
* 声明式命令注册:设备在配置中声明支持哪些命令,并绑定处理函数。
|
||||||
|
*
|
||||||
|
* command 值说明:
|
||||||
|
* - "shell" → 处理 shell 类型命令,args 为完整命令字符串
|
||||||
|
* - "camerasue" → 处理 homeagent-camerasue 命令,args 为参数
|
||||||
|
* - "screensee" → 处理 homeagent-screensee 命令
|
||||||
|
* - "speakeruse" → 处理 homeagent-speakeruse 命令
|
||||||
|
* - "computeruse" → 处理 homeagent-computeruse 命令
|
||||||
|
* - "clipboardsee" → 处理 homeagent-clipboardsee 命令
|
||||||
|
* - "clipboardsue" → 处理 homeagent-clipboardsue 命令
|
||||||
|
* - "screensue" → 处理 homeagent-screensue 命令
|
||||||
|
* - "deviceinfo" → 处理设备信息查询
|
||||||
|
* - 其他自定义命令名 → 按字符串匹配分发
|
||||||
|
*
|
||||||
|
* handler 处理完毕后只需填写 result 结构体,SDK 自动回执。
|
||||||
|
*/
|
||||||
|
typedef ha_status_t (*ha_cmd_handler_t)(const char *req_id, const char *args,
|
||||||
|
ha_cmd_result_t *result, void *userdata);
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
const char *command; /* 命令名,如 "camerasue"、"shell" */
|
||||||
|
ha_cmd_handler_t handler; /* 处理函数 */
|
||||||
|
} ha_cmd_handler_def_t;
|
||||||
|
|
||||||
|
/* 二进制数据接收回调:收到服务端推送的二进制数据(如 TTS 音频)时调用。
|
||||||
|
* data 指针在回调返回后失效,如需保存请拷贝。 */
|
||||||
|
typedef void (*ha_binary_handler_t)(const char *req_id, const char *kind,
|
||||||
|
const char *mime, const uint8_t *data,
|
||||||
|
int len, void *userdata);
|
||||||
|
|
||||||
|
/* 连接状态变化回调 */
|
||||||
|
typedef void (*ha_state_callback_t)(int connected, void *userdata);
|
||||||
|
|
||||||
|
/* ======================== 客户端配置 ========================
|
||||||
|
*
|
||||||
|
* 所有配置在 ha_client_new() 时一次性声明。
|
||||||
|
* 声明式核心:handlers 表声明了设备支持的所有命令及其处理函数。
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
ha_transport_t transport; /* 传输层实现(必须) */
|
||||||
|
ha_device_info_t device; /* 设备声明(必须) */
|
||||||
|
const char *server; /* 服务端地址,如 "192.168.1.100:9890"(必须) */
|
||||||
|
const char *token; /* 接入令牌(必须) */
|
||||||
|
|
||||||
|
ha_cmd_handler_def_t *handlers; /* 声明式命令处理表,.command=NULL 标记结束 */
|
||||||
|
ha_binary_handler_t on_binary; /* 二进制数据接收回调(可选) */
|
||||||
|
ha_state_callback_t on_state; /* 状态变化回调(可选) */
|
||||||
|
void *userdata; /* 用户自定义数据,传给所有回调 */
|
||||||
|
|
||||||
|
int ping_interval; /* 心跳间隔秒数,0 则默认 30 */
|
||||||
|
int max_reconnect; /* 最大重连次数,-1 无限重连(默认),0 不重连 */
|
||||||
|
} ha_config_t;
|
||||||
|
|
||||||
|
/* ======================== 客户端 API ======================== */
|
||||||
|
|
||||||
|
typedef struct ha_client ha_client_t;
|
||||||
|
|
||||||
|
/* 创建客户端实例。config 数据会在内部拷贝,外部可释放。 */
|
||||||
|
ha_client_t *ha_client_new(const ha_config_t *config);
|
||||||
|
|
||||||
|
/* 启动连接:TCP 连接 → WS 升级 → hello → bind → 就绪。阻塞直到完成或失败。 */
|
||||||
|
ha_status_t ha_client_start(ha_client_t *client);
|
||||||
|
|
||||||
|
/* 主循环处理:必须在用户的主循环中周期性调用。
|
||||||
|
* - 读取 WS 帧并分发
|
||||||
|
* - 按 handlers 表查找命令处理函数,自动回执结果
|
||||||
|
* - 处理心跳 ping/pong
|
||||||
|
* - 处理断线重连
|
||||||
|
* 返回 HA_OK 表示正常,HA_ERR_DISCONNECTED 表示正在重连。 */
|
||||||
|
ha_status_t ha_client_process(ha_client_t *client);
|
||||||
|
|
||||||
|
/* ===== 主动上报(设备主动推送,非命令响应) ===== */
|
||||||
|
|
||||||
|
/* 发送设备主动上报事件。type 如 "motion_detected",detail 为 JSON 字符串。 */
|
||||||
|
void ha_client_send_event(ha_client_t *client, const char *type,
|
||||||
|
const char *detail);
|
||||||
|
|
||||||
|
/* 发送设备状态更新。status: "online"、"offline"、"busy" 等。 */
|
||||||
|
void ha_client_send_status(ha_client_t *client, const char *status);
|
||||||
|
|
||||||
|
/* ===== 生命周期 ===== */
|
||||||
|
|
||||||
|
/* 停止客户端,断开连接。 */
|
||||||
|
void ha_client_stop(ha_client_t *client);
|
||||||
|
|
||||||
|
/* 销毁客户端,释放所有资源。 */
|
||||||
|
void ha_client_destroy(ha_client_t *client);
|
||||||
|
|
||||||
|
/* ======================== 工具函数 ======================== */
|
||||||
|
|
||||||
|
/* 解析 homeagent-* 命令,返回能力名和参数。
|
||||||
|
* command = "camerasue 5" → cap="camerasue", args="5"
|
||||||
|
* command = "screensee" → cap="screensee", args=""
|
||||||
|
* command = "computeruse {...}" → cap="computeruse", args="..." */
|
||||||
|
void ha_cmd_parse_homeagent(const char *command, const char **cap,
|
||||||
|
const char **args);
|
||||||
|
|
||||||
|
/* 解析 JSON 格式的命令参数,提取 action 和 JSON 字符串。
|
||||||
|
* command = "computeruse {\"action\":\"click\",\"x\":100}"
|
||||||
|
* → action="computeruse", json_str="{\"action\":\"click\",...}" */
|
||||||
|
void ha_cmd_parse_json(const char *command, const char **action,
|
||||||
|
const char **json_str);
|
||||||
|
|
||||||
|
/* Base64 编码(用于将二进制数据编码为文本回传)。
|
||||||
|
* 返回写入 out 的字节数(不含 \0),out 不足时返回所需长度。 */
|
||||||
|
int ha_base64_encode(const uint8_t *data, int len, char *out, int out_len);
|
||||||
|
|
||||||
|
/* 获取版本号 */
|
||||||
|
const char *ha_version(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* HA_REMOTEDEVICE_H */
|
||||||
369
remotedevice/src/ha_json.c
Normal file
369
remotedevice/src/ha_json.c
Normal file
@ -0,0 +1,369 @@
|
|||||||
|
#include "ha_json.h"
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
/* ======================== 解析器 ======================== */
|
||||||
|
|
||||||
|
/* 前向声明 */
|
||||||
|
static ha_json_node_t *parse_value(const char **pp);
|
||||||
|
|
||||||
|
/* 跳过空白 */
|
||||||
|
static const char *skip_ws(const char *p) {
|
||||||
|
while (*p && (unsigned char)*p <= ' ') p++;
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析字符串("..."),返回新分配的字符串,p 更新到结束引号后 */
|
||||||
|
static char *parse_string(const char **pp) {
|
||||||
|
const char *p = skip_ws(*pp);
|
||||||
|
if (*p != '"') return NULL;
|
||||||
|
p++;
|
||||||
|
int len = 0;
|
||||||
|
const char *q = p;
|
||||||
|
while (*q && *q != '"') {
|
||||||
|
if (*q == '\\') { q++; if (*q) q++; }
|
||||||
|
else q++;
|
||||||
|
len++;
|
||||||
|
}
|
||||||
|
if (*q != '"') return NULL;
|
||||||
|
char *s = (char *)malloc(len + 1);
|
||||||
|
if (!s) return NULL;
|
||||||
|
q = p;
|
||||||
|
int i = 0;
|
||||||
|
while (*q && *q != '"') {
|
||||||
|
if (*q == '\\') {
|
||||||
|
q++;
|
||||||
|
switch (*q) {
|
||||||
|
case '"': s[i++] = '"'; break;
|
||||||
|
case '\\': s[i++] = '\\'; break;
|
||||||
|
case '/': s[i++] = '/'; break;
|
||||||
|
case 'b': s[i++] = '\b'; break;
|
||||||
|
case 'f': s[i++] = '\f'; break;
|
||||||
|
case 'n': s[i++] = '\n'; break;
|
||||||
|
case 'r': s[i++] = '\r'; break;
|
||||||
|
case 't': s[i++] = '\t'; break;
|
||||||
|
case 'u': q += 4; s[i++] = '?'; continue;
|
||||||
|
default: s[i++] = *q; break;
|
||||||
|
}
|
||||||
|
q++;
|
||||||
|
} else {
|
||||||
|
s[i++] = *q++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s[i] = '\0';
|
||||||
|
*pp = q + 1;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
static ha_json_node_t *new_node(ha_json_type_t type) {
|
||||||
|
ha_json_node_t *n = (ha_json_node_t *)calloc(1, sizeof(ha_json_node_t));
|
||||||
|
if (n) n->type = type;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析数字 */
|
||||||
|
static ha_json_node_t *parse_number(const char **pp) {
|
||||||
|
const char *p = *pp;
|
||||||
|
int neg = 0;
|
||||||
|
if (*p == '-') { neg = 1; p++; }
|
||||||
|
if (!isdigit((unsigned char)*p)) return NULL;
|
||||||
|
int val = 0;
|
||||||
|
while (isdigit((unsigned char)*p)) {
|
||||||
|
val = val * 10 + (*p - '0');
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
if (*p == '.') { p++; while (isdigit((unsigned char)*p)) p++; }
|
||||||
|
if (*p == 'e' || *p == 'E') {
|
||||||
|
p++;
|
||||||
|
if (*p == '+' || *p == '-') p++;
|
||||||
|
while (isdigit((unsigned char)*p)) p++;
|
||||||
|
}
|
||||||
|
*pp = p;
|
||||||
|
ha_json_node_t *n = new_node(HA_JSON_INT);
|
||||||
|
if (n) n->int_val = neg ? -val : val;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析 true/false/null */
|
||||||
|
static ha_json_node_t *parse_keyword(const char **pp) {
|
||||||
|
const char *p = *pp;
|
||||||
|
ha_json_node_t *n = NULL;
|
||||||
|
if (strncmp(p, "true", 4) == 0 && !isalnum((unsigned char)p[4])) {
|
||||||
|
n = new_node(HA_JSON_BOOL); if (n) n->bool_val = 1;
|
||||||
|
*pp = p + 4;
|
||||||
|
} else if (strncmp(p, "false", 5) == 0 && !isalnum((unsigned char)p[5])) {
|
||||||
|
n = new_node(HA_JSON_BOOL); if (n) n->bool_val = 0;
|
||||||
|
*pp = p + 5;
|
||||||
|
} else if (strncmp(p, "null", 4) == 0 && !isalnum((unsigned char)p[4])) {
|
||||||
|
n = new_node(HA_JSON_NULL);
|
||||||
|
*pp = p + 4;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析对象 */
|
||||||
|
static ha_json_node_t *parse_object(const char **pp) {
|
||||||
|
const char *p = skip_ws(*pp);
|
||||||
|
if (*p != '{') return NULL;
|
||||||
|
p++;
|
||||||
|
ha_json_node_t *obj = new_node(HA_JSON_OBJECT);
|
||||||
|
if (!obj) return NULL;
|
||||||
|
ha_json_node_t **tail = &obj->child;
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == '}') { *pp = p + 1; return obj; }
|
||||||
|
while (*p) {
|
||||||
|
p = skip_ws(p);
|
||||||
|
char *key = parse_string(&p);
|
||||||
|
if (!key) break;
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p != ':') { free(key); break; }
|
||||||
|
p++;
|
||||||
|
ha_json_node_t *val = parse_value(&p);
|
||||||
|
if (!val) { free(key); break; }
|
||||||
|
val->key = key;
|
||||||
|
*tail = val;
|
||||||
|
tail = &val->next;
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == ',') { p++; continue; }
|
||||||
|
if (*p == '}') break;
|
||||||
|
}
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == '}') { *pp = p + 1; return obj; }
|
||||||
|
ha_json_free(obj);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析数组 */
|
||||||
|
static ha_json_node_t *parse_array(const char **pp) {
|
||||||
|
const char *p = skip_ws(*pp);
|
||||||
|
if (*p != '[') return NULL;
|
||||||
|
p++;
|
||||||
|
ha_json_node_t *arr = new_node(HA_JSON_ARRAY);
|
||||||
|
if (!arr) return NULL;
|
||||||
|
ha_json_node_t **tail = &arr->child;
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == ']') { *pp = p + 1; return arr; }
|
||||||
|
while (*p) {
|
||||||
|
ha_json_node_t *val = parse_value(&p);
|
||||||
|
if (!val) break;
|
||||||
|
*tail = val;
|
||||||
|
tail = &val->next;
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == ',') { p++; continue; }
|
||||||
|
if (*p == ']') break;
|
||||||
|
}
|
||||||
|
p = skip_ws(p);
|
||||||
|
if (*p == ']') { *pp = p + 1; return arr; }
|
||||||
|
ha_json_free(arr);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 解析值(主入口) */
|
||||||
|
static ha_json_node_t *parse_value(const char **pp) {
|
||||||
|
const char *p = skip_ws(*pp);
|
||||||
|
if (*p == '{') return parse_object(pp);
|
||||||
|
if (*p == '[') return parse_array(pp);
|
||||||
|
if (*p == '"') {
|
||||||
|
char *s = parse_string(pp);
|
||||||
|
if (!s) return NULL;
|
||||||
|
ha_json_node_t *n = new_node(HA_JSON_STRING);
|
||||||
|
if (!n) { free(s); return NULL; }
|
||||||
|
n->str_val = s;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
if (*p == '-' || isdigit((unsigned char)*p)) return parse_number(pp);
|
||||||
|
return parse_keyword(pp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 公共 API ======================== */
|
||||||
|
|
||||||
|
ha_json_node_t *ha_json_parse(const char *str) {
|
||||||
|
if (!str) return NULL;
|
||||||
|
const char *p = str;
|
||||||
|
return parse_value(&p);
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *ha_json_get_string(const ha_json_node_t *obj, const char *key) {
|
||||||
|
ha_json_node_t *n = ha_json_get(obj, key);
|
||||||
|
if (!n || n->type != HA_JSON_STRING) return NULL;
|
||||||
|
return n->str_val;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_json_get_int(const ha_json_node_t *obj, const char *key, int def) {
|
||||||
|
ha_json_node_t *n = ha_json_get(obj, key);
|
||||||
|
if (!n || n->type != HA_JSON_INT) return def;
|
||||||
|
return n->int_val;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_json_node_t *ha_json_get(const ha_json_node_t *obj, const char *key) {
|
||||||
|
if (!obj || obj->type != HA_JSON_OBJECT) return NULL;
|
||||||
|
ha_json_node_t *c = obj->child;
|
||||||
|
while (c) {
|
||||||
|
if (c->key && strcmp(c->key, key) == 0) return c;
|
||||||
|
c = c->next;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_json_array_len(const ha_json_node_t *arr) {
|
||||||
|
if (!arr || arr->type != HA_JSON_ARRAY) return 0;
|
||||||
|
int n = 0;
|
||||||
|
ha_json_node_t *c = arr->child;
|
||||||
|
while (c) { n++; c = c->next; }
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_json_node_t *ha_json_array_get(const ha_json_node_t *arr, int index) {
|
||||||
|
if (!arr || arr->type != HA_JSON_ARRAY) return NULL;
|
||||||
|
ha_json_node_t *c = arr->child;
|
||||||
|
int i = 0;
|
||||||
|
while (c) {
|
||||||
|
if (i == index) return c;
|
||||||
|
i++; c = c->next;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_free(ha_json_node_t *root) {
|
||||||
|
if (!root) return;
|
||||||
|
ha_json_node_t *c = root->child;
|
||||||
|
while (c) {
|
||||||
|
ha_json_node_t *next = c->next;
|
||||||
|
free(c->key);
|
||||||
|
if (c->type == HA_JSON_STRING) free(c->str_val);
|
||||||
|
ha_json_free(c);
|
||||||
|
c = next;
|
||||||
|
}
|
||||||
|
free(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 构建器 ======================== */
|
||||||
|
|
||||||
|
static void json_escape(ha_json_builder_t *jb, const char *s) {
|
||||||
|
if (!s) { ha_json_builder_raw(jb, "null"); return; }
|
||||||
|
ha_json_builder_raw(jb, "\"");
|
||||||
|
for (const char *p = s; *p; p++) {
|
||||||
|
unsigned char c = (unsigned char)*p;
|
||||||
|
switch (c) {
|
||||||
|
case '"': ha_json_builder_raw(jb, "\\\""); break;
|
||||||
|
case '\\': ha_json_builder_raw(jb, "\\\\"); break;
|
||||||
|
case '\b': ha_json_builder_raw(jb, "\\b"); break;
|
||||||
|
case '\f': ha_json_builder_raw(jb, "\\f"); break;
|
||||||
|
case '\n': ha_json_builder_raw(jb, "\\n"); break;
|
||||||
|
case '\r': ha_json_builder_raw(jb, "\\r"); break;
|
||||||
|
case '\t': ha_json_builder_raw(jb, "\\t"); break;
|
||||||
|
default:
|
||||||
|
if (c < 0x20) {
|
||||||
|
char buf[8];
|
||||||
|
snprintf(buf, sizeof(buf), "\\u%04x", c);
|
||||||
|
ha_json_builder_raw(jb, buf);
|
||||||
|
} else {
|
||||||
|
char buf[2] = { (char)c, 0 };
|
||||||
|
ha_json_builder_raw(jb, buf);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ha_json_builder_raw(jb, "\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_init(ha_json_builder_t *jb, char *buf, int cap) {
|
||||||
|
jb->buf = buf;
|
||||||
|
jb->len = 0;
|
||||||
|
jb->cap = cap;
|
||||||
|
jb->depth = 0;
|
||||||
|
if (cap > 0) buf[0] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_reset(ha_json_builder_t *jb) {
|
||||||
|
jb->len = 0;
|
||||||
|
jb->depth = 0;
|
||||||
|
if (jb->cap > 0) jb->buf[0] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_raw(ha_json_builder_t *jb, const char *s) {
|
||||||
|
while (*s && jb->len < jb->cap - 1) {
|
||||||
|
jb->buf[jb->len++] = *s++;
|
||||||
|
}
|
||||||
|
jb->buf[jb->len] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_comma(ha_json_builder_t *jb) {
|
||||||
|
if (jb->depth > 0 && jb->item_count[jb->depth - 1] > 0) {
|
||||||
|
ha_json_builder_raw(jb, ",");
|
||||||
|
}
|
||||||
|
if (jb->depth > 0) jb->item_count[jb->depth - 1]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_begin_object(ha_json_builder_t *jb) {
|
||||||
|
ha_json_builder_comma(jb);
|
||||||
|
ha_json_builder_raw(jb, "{");
|
||||||
|
if (jb->depth < 16) jb->item_count[jb->depth] = 0;
|
||||||
|
jb->depth++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_end_object(ha_json_builder_t *jb) {
|
||||||
|
jb->depth--;
|
||||||
|
ha_json_builder_raw(jb, "}");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_begin_array(ha_json_builder_t *jb) {
|
||||||
|
ha_json_builder_comma(jb);
|
||||||
|
ha_json_builder_raw(jb, "[");
|
||||||
|
if (jb->depth < 16) jb->item_count[jb->depth] = 0;
|
||||||
|
jb->depth++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_end_array(ha_json_builder_t *jb) {
|
||||||
|
jb->depth--;
|
||||||
|
ha_json_builder_raw(jb, "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_key(ha_json_builder_t *jb, const char *key) {
|
||||||
|
ha_json_builder_comma(jb);
|
||||||
|
json_escape(jb, key);
|
||||||
|
ha_json_builder_raw(jb, ":");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_add_string(ha_json_builder_t *jb, const char *val) {
|
||||||
|
json_escape(jb, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_add_int(ha_json_builder_t *jb, int val) {
|
||||||
|
char buf[16];
|
||||||
|
snprintf(buf, sizeof(buf), "%d", val);
|
||||||
|
ha_json_builder_raw(jb, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_add_bool(ha_json_builder_t *jb, int val) {
|
||||||
|
ha_json_builder_raw(jb, val ? "true" : "false");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_add_null(ha_json_builder_t *jb) {
|
||||||
|
ha_json_builder_raw(jb, "null");
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_string(ha_json_builder_t *jb, const char *key, const char *val) {
|
||||||
|
ha_json_builder_key(jb, key);
|
||||||
|
json_escape(jb, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_int(ha_json_builder_t *jb, const char *key, int val) {
|
||||||
|
ha_json_builder_key(jb, key);
|
||||||
|
ha_json_builder_add_int(jb, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_json_builder_bool(ha_json_builder_t *jb, const char *key, int val) {
|
||||||
|
ha_json_builder_key(jb, key);
|
||||||
|
ha_json_builder_add_bool(jb, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *ha_json_builder_str(ha_json_builder_t *jb) {
|
||||||
|
return jb->buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_json_builder_len(ha_json_builder_t *jb) {
|
||||||
|
return jb->len;
|
||||||
|
}
|
||||||
107
remotedevice/src/ha_json.h
Normal file
107
remotedevice/src/ha_json.h
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
#ifndef HA_JSON_H
|
||||||
|
#define HA_JSON_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ======================== JSON 解析器(DOM 风格) ======================== */
|
||||||
|
typedef enum {
|
||||||
|
HA_JSON_NULL,
|
||||||
|
HA_JSON_BOOL,
|
||||||
|
HA_JSON_INT,
|
||||||
|
HA_JSON_STRING,
|
||||||
|
HA_JSON_ARRAY,
|
||||||
|
HA_JSON_OBJECT,
|
||||||
|
} ha_json_type_t;
|
||||||
|
|
||||||
|
typedef struct ha_json_node {
|
||||||
|
ha_json_type_t type;
|
||||||
|
union {
|
||||||
|
int bool_val;
|
||||||
|
int int_val;
|
||||||
|
char *str_val;
|
||||||
|
};
|
||||||
|
struct ha_json_node *next; /* linked list for array/object items */
|
||||||
|
struct ha_json_node *child; /* first child for array/object */
|
||||||
|
char *key; /* key for object members */
|
||||||
|
} ha_json_node_t;
|
||||||
|
|
||||||
|
/* 解析 JSON 字符串,返回根节点。失败返回 NULL。 */
|
||||||
|
ha_json_node_t *ha_json_parse(const char *str);
|
||||||
|
|
||||||
|
/* 从对象中按 key 获取字符串值,不存在返回 NULL */
|
||||||
|
const char *ha_json_get_string(const ha_json_node_t *obj, const char *key);
|
||||||
|
|
||||||
|
/* 从对象中按 key 获取 int 值,不存在返回 def */
|
||||||
|
int ha_json_get_int(const ha_json_node_t *obj, const char *key, int def);
|
||||||
|
|
||||||
|
/* 从对象中按 key 获取子节点,不存在返回 NULL */
|
||||||
|
ha_json_node_t *ha_json_get(const ha_json_node_t *obj, const char *key);
|
||||||
|
|
||||||
|
/* 获取数组长度 */
|
||||||
|
int ha_json_array_len(const ha_json_node_t *arr);
|
||||||
|
|
||||||
|
/* 获取数组第 index 个元素,越界返回 NULL */
|
||||||
|
ha_json_node_t *ha_json_array_get(const ha_json_node_t *arr, int index);
|
||||||
|
|
||||||
|
/* 释放整个 JSON 树 */
|
||||||
|
void ha_json_free(ha_json_node_t *root);
|
||||||
|
|
||||||
|
/* ======================== JSON 构建器(直接写缓冲区) ======================== */
|
||||||
|
typedef struct {
|
||||||
|
char *buf;
|
||||||
|
int len;
|
||||||
|
int cap;
|
||||||
|
int depth;
|
||||||
|
int item_count[16]; /* 每层已添加元素数,用于逗号判断 */
|
||||||
|
} ha_json_builder_t;
|
||||||
|
|
||||||
|
/* 初始化构建器 */
|
||||||
|
void ha_json_builder_init(ha_json_builder_t *jb, char *buf, int cap);
|
||||||
|
|
||||||
|
/* 清空构建器 */
|
||||||
|
void ha_json_builder_reset(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 基础写入 */
|
||||||
|
void ha_json_builder_raw(ha_json_builder_t *jb, const char *s);
|
||||||
|
|
||||||
|
/* 逗号(自动判断是否需要加) */
|
||||||
|
void ha_json_builder_comma(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 对象 */
|
||||||
|
void ha_json_builder_begin_object(ha_json_builder_t *jb);
|
||||||
|
void ha_json_builder_end_object(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 数组 */
|
||||||
|
void ha_json_builder_begin_array(ha_json_builder_t *jb);
|
||||||
|
void ha_json_builder_end_array(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 键名 */
|
||||||
|
void ha_json_builder_key(ha_json_builder_t *jb, const char *key);
|
||||||
|
|
||||||
|
/* 值 */
|
||||||
|
void ha_json_builder_add_string(ha_json_builder_t *jb, const char *val);
|
||||||
|
void ha_json_builder_add_int(ha_json_builder_t *jb, int val);
|
||||||
|
void ha_json_builder_add_bool(ha_json_builder_t *jb, int val);
|
||||||
|
void ha_json_builder_add_null(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 快捷方法:直接写 "key":"val" */
|
||||||
|
void ha_json_builder_string(ha_json_builder_t *jb, const char *key, const char *val);
|
||||||
|
void ha_json_builder_int(ha_json_builder_t *jb, const char *key, int val);
|
||||||
|
void ha_json_builder_bool(ha_json_builder_t *jb, const char *key, int val);
|
||||||
|
|
||||||
|
/* 获取当前构建的字符串指针 */
|
||||||
|
const char *ha_json_builder_str(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
/* 获取当前长度 */
|
||||||
|
int ha_json_builder_len(ha_json_builder_t *jb);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* HA_JSON_H */
|
||||||
628
remotedevice/src/ha_remotedevice.c
Normal file
628
remotedevice/src/ha_remotedevice.c
Normal file
@ -0,0 +1,628 @@
|
|||||||
|
#include "ha_remotedevice.h"
|
||||||
|
#include "ha_json.h"
|
||||||
|
#include "ha_ws.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#define HA_VERSION "0.1.0"
|
||||||
|
|
||||||
|
/* 前向声明(因 handle_cmd_msg 需要调用这些函数,而它们定义在后面) */
|
||||||
|
void ha_client_send_result(ha_client_t *client, const char *req_id,
|
||||||
|
const char *status, const char *output,
|
||||||
|
const char *error);
|
||||||
|
void ha_client_send_data_chunked(ha_client_t *client, const char *req_id,
|
||||||
|
const char *kind, const char *mime,
|
||||||
|
const uint8_t *data, int len);
|
||||||
|
|
||||||
|
/* ======================== 内部状态 ======================== */
|
||||||
|
typedef enum {
|
||||||
|
HA_STATE_INIT,
|
||||||
|
HA_STATE_DISCONNECTED,
|
||||||
|
HA_STATE_CONNECTING,
|
||||||
|
HA_STATE_WS_UPGRADING,
|
||||||
|
HA_STATE_HELLO_SENT,
|
||||||
|
HA_STATE_BIND_SENT,
|
||||||
|
HA_STATE_READY,
|
||||||
|
HA_STATE_STOPPING,
|
||||||
|
} ha_state_t;
|
||||||
|
|
||||||
|
/* 语音数据聚合缓冲区 */
|
||||||
|
typedef struct {
|
||||||
|
char req_id[128];
|
||||||
|
char kind[64];
|
||||||
|
char mime[64];
|
||||||
|
int total;
|
||||||
|
uint8_t *data;
|
||||||
|
int len;
|
||||||
|
int cap;
|
||||||
|
} ha_speech_accum_t;
|
||||||
|
|
||||||
|
struct ha_client {
|
||||||
|
ha_config_t config; /* 拷贝的配置 */
|
||||||
|
ha_state_t state;
|
||||||
|
int reconnect_cnt; /* 当前重连次数 */
|
||||||
|
ha_ws_t ws; /* WS 连接 */
|
||||||
|
|
||||||
|
/* JSON 构建缓冲区 */
|
||||||
|
char json_buf[4096];
|
||||||
|
ha_json_builder_t jb;
|
||||||
|
|
||||||
|
/* 语音数据聚合 */
|
||||||
|
ha_speech_accum_t speech;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ======================== 辅助函数 ======================== */
|
||||||
|
|
||||||
|
static void set_sockbuf(ha_client_t *c, int i) { (void)c; (void)i; }
|
||||||
|
|
||||||
|
/* Base64 编码表 */
|
||||||
|
static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
|
int ha_base64_encode(const uint8_t *data, int len, char *out, int out_len) {
|
||||||
|
int needed = ((len + 2) / 3) * 4 + 1;
|
||||||
|
if (out_len < needed) {
|
||||||
|
if (out_len > 0) out[0] = '\0';
|
||||||
|
return needed;
|
||||||
|
}
|
||||||
|
int i = 0, j = 0;
|
||||||
|
while (i < len) {
|
||||||
|
int rem = len - i;
|
||||||
|
uint8_t b0 = data[i++];
|
||||||
|
uint8_t b1 = (rem > 1) ? data[i++] : 0;
|
||||||
|
uint8_t b2 = (rem > 2) ? data[i++] : 0;
|
||||||
|
out[j++] = b64[b0 >> 2];
|
||||||
|
out[j++] = b64[((b0 & 0x03) << 4) | (b1 >> 4)];
|
||||||
|
out[j++] = (rem > 1) ? b64[((b1 & 0x0F) << 2) | (b2 >> 6)] : '=';
|
||||||
|
out[j++] = (rem > 2) ? b64[b2 & 0x3F] : '=';
|
||||||
|
}
|
||||||
|
out[j] = '\0';
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== JSON 构建辅助 ======================== */
|
||||||
|
static void json_init(ha_client_t *c) {
|
||||||
|
ha_json_builder_init(&c->jb, c->json_buf, sizeof(c->json_buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== WS 发送 JSON ======================== */
|
||||||
|
static int ws_send_json(ha_client_t *c) {
|
||||||
|
return ha_ws_send_text(&c->ws, c->json_buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 协议消息构造 ======================== */
|
||||||
|
|
||||||
|
/* 构建 hello 消息 */
|
||||||
|
static int send_hello(ha_client_t *c) {
|
||||||
|
json_init(c);
|
||||||
|
ha_json_builder_begin_object(&c->jb);
|
||||||
|
ha_json_builder_string(&c->jb, "op", "hello");
|
||||||
|
ha_json_builder_key(&c->jb, "device");
|
||||||
|
ha_json_builder_begin_object(&c->jb);
|
||||||
|
ha_json_builder_string(&c->jb, "device_id", c->config.device.device_id);
|
||||||
|
ha_json_builder_string(&c->jb, "name", c->config.device.name);
|
||||||
|
ha_json_builder_string(&c->jb, "kind", c->config.device.kind);
|
||||||
|
/* caps */
|
||||||
|
ha_json_builder_key(&c->jb, "caps");
|
||||||
|
ha_json_builder_begin_array(&c->jb);
|
||||||
|
if (c->config.device.caps) {
|
||||||
|
for (const char **p = c->config.device.caps; *p; p++) {
|
||||||
|
ha_json_builder_add_string(&c->jb, *p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ha_json_builder_end_array(&c->jb);
|
||||||
|
/* info 可选 */
|
||||||
|
if (c->config.device.info_json && c->config.device.info_json[0]) {
|
||||||
|
ha_json_builder_string(&c->jb, "info", c->config.device.info_json);
|
||||||
|
}
|
||||||
|
ha_json_builder_end_object(&c->jb); /* device */
|
||||||
|
ha_json_builder_end_object(&c->jb); /* root */
|
||||||
|
return ws_send_json(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 构建 bind 消息 */
|
||||||
|
static int send_bind(ha_client_t *c) {
|
||||||
|
json_init(c);
|
||||||
|
ha_json_builder_begin_object(&c->jb);
|
||||||
|
ha_json_builder_string(&c->jb, "op", "bind");
|
||||||
|
ha_json_builder_string(&c->jb, "device_id", c->config.device.device_id);
|
||||||
|
ha_json_builder_string(&c->jb, "token", c->config.token);
|
||||||
|
ha_json_builder_end_object(&c->jb);
|
||||||
|
return ws_send_json(c);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 消息处理 ======================== */
|
||||||
|
|
||||||
|
/* 在 handlers 表中查找命令处理函数 */
|
||||||
|
static ha_cmd_handler_def_t *find_handler(ha_client_t *c, const char *name) {
|
||||||
|
if (!name || !c->config.handlers) return NULL;
|
||||||
|
for (ha_cmd_handler_def_t *h = c->config.handlers; h->command; h++) {
|
||||||
|
if (strcmp(h->command, name) == 0) return h;
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 声明式命令分发:查找 handlers 表 → 调用 handler → 自动回执 */
|
||||||
|
static void handle_cmd_msg(ha_client_t *c, ha_json_node_t *msg) {
|
||||||
|
const char *req_id = ha_json_get_string(msg, "req_id");
|
||||||
|
const char *command = ha_json_get_string(msg, "command");
|
||||||
|
const char *cmd_type = ha_json_get_string(msg, "cmd_type");
|
||||||
|
if (!req_id || !command) return;
|
||||||
|
if (!cmd_type) cmd_type = "homeagent";
|
||||||
|
|
||||||
|
const char *handler_name = NULL;
|
||||||
|
const char *args = command;
|
||||||
|
|
||||||
|
if (strcmp(cmd_type, "shell") == 0) {
|
||||||
|
handler_name = "shell";
|
||||||
|
/* args 保持为完整命令字符串 */
|
||||||
|
} else {
|
||||||
|
/* homeagent-* 命令:提取能力名作为 handler 名 */
|
||||||
|
const char *cap = command;
|
||||||
|
const char *p = command;
|
||||||
|
if (strncmp(p, "homeagent-", 10) == 0) p += 10;
|
||||||
|
const char *space = strchr(p, ' ');
|
||||||
|
if (space) {
|
||||||
|
args = space + 1;
|
||||||
|
/* handler_name 用静态缓冲区 */
|
||||||
|
static char name_buf[128];
|
||||||
|
int n = (int)(space - p);
|
||||||
|
if (n > 127) n = 127;
|
||||||
|
strncpy(name_buf, p, n);
|
||||||
|
name_buf[n] = '\0';
|
||||||
|
handler_name = name_buf;
|
||||||
|
} else {
|
||||||
|
handler_name = p;
|
||||||
|
args = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_cmd_handler_def_t *def = find_handler(c, handler_name);
|
||||||
|
if (!def) {
|
||||||
|
ha_client_send_result(c, req_id, "error", NULL,
|
||||||
|
"unsupported command");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 调用 handler,填写 result */
|
||||||
|
ha_cmd_result_t result;
|
||||||
|
memset(&result, 0, sizeof(result));
|
||||||
|
ha_status_t st = def->handler(req_id, args, &result, c->config.userdata);
|
||||||
|
|
||||||
|
/* 自动回执 */
|
||||||
|
if (st != HA_OK) {
|
||||||
|
ha_client_send_result(c, req_id, "error", NULL,
|
||||||
|
result.error ? result.error : "handler failed");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.has_binary && result.binary_data && result.binary_len > 0) {
|
||||||
|
/* 二进制分块回传 */
|
||||||
|
ha_client_send_data_chunked(c, req_id,
|
||||||
|
handler_name, result.binary_mime ? result.binary_mime : "application/octet-stream",
|
||||||
|
result.binary_data, result.binary_len);
|
||||||
|
} else {
|
||||||
|
/* 文本回传 */
|
||||||
|
ha_client_send_result(c, req_id, result.status == 0 ? "ok" : "error",
|
||||||
|
result.output, result.error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handle_speech_start(ha_client_t *c, ha_json_node_t *msg) {
|
||||||
|
const char *req_id = ha_json_get_string(msg, "req_id");
|
||||||
|
const char *kind = ha_json_get_string(msg, "kind");
|
||||||
|
const char *mime = ha_json_get_string(msg, "mime");
|
||||||
|
if (!req_id) return;
|
||||||
|
|
||||||
|
/* 释放旧的聚合数据 */
|
||||||
|
free(c->speech.data);
|
||||||
|
memset(&c->speech, 0, sizeof(c->speech));
|
||||||
|
|
||||||
|
strncpy(c->speech.req_id, req_id, sizeof(c->speech.req_id) - 1);
|
||||||
|
if (kind) strncpy(c->speech.kind, kind, sizeof(c->speech.kind) - 1);
|
||||||
|
if (mime) strncpy(c->speech.mime, mime, sizeof(c->speech.mime) - 1);
|
||||||
|
c->speech.total = ha_json_get_int(msg, "total", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handle_speech_end(ha_client_t *c, ha_json_node_t *msg) {
|
||||||
|
const char *req_id = ha_json_get_string(msg, "req_id");
|
||||||
|
if (!req_id || strcmp(req_id, c->speech.req_id) != 0) return;
|
||||||
|
|
||||||
|
if (c->config.on_binary && c->speech.data && c->speech.len > 0) {
|
||||||
|
c->config.on_binary(c->speech.req_id, c->speech.kind,
|
||||||
|
c->speech.mime, c->speech.data,
|
||||||
|
c->speech.len, c->config.userdata);
|
||||||
|
}
|
||||||
|
|
||||||
|
free(c->speech.data);
|
||||||
|
memset(&c->speech, 0, sizeof(c->speech));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handle_text_message(ha_client_t *c, const uint8_t *payload, int len) {
|
||||||
|
/* 解析 JSON */
|
||||||
|
char *tmp = (char *)malloc(len + 1);
|
||||||
|
if (!tmp) return;
|
||||||
|
memcpy(tmp, payload, len);
|
||||||
|
tmp[len] = '\0';
|
||||||
|
|
||||||
|
ha_json_node_t *root = ha_json_parse(tmp);
|
||||||
|
if (!root) { free(tmp); return; }
|
||||||
|
|
||||||
|
const char *op = ha_json_get_string(root, "op");
|
||||||
|
if (!op) { ha_json_free(root); free(tmp); return; }
|
||||||
|
|
||||||
|
switch (c->state) {
|
||||||
|
case HA_STATE_HELLO_SENT:
|
||||||
|
if (strcmp(op, "hello_ack") == 0) {
|
||||||
|
c->state = HA_STATE_BIND_SENT;
|
||||||
|
send_bind(c);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case HA_STATE_BIND_SENT:
|
||||||
|
if (strcmp(op, "bind_ack") == 0) {
|
||||||
|
c->state = HA_STATE_READY;
|
||||||
|
if (c->config.on_state) {
|
||||||
|
c->config.on_state(1, c->config.userdata);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case HA_STATE_READY:
|
||||||
|
if (strcmp(op, "cmd") == 0) {
|
||||||
|
handle_cmd_msg(c, root);
|
||||||
|
} else if (strcmp(op, "cmd_speech_start") == 0) {
|
||||||
|
handle_speech_start(c, root);
|
||||||
|
} else if (strcmp(op, "cmd_speech_end") == 0) {
|
||||||
|
handle_speech_end(c, root);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_json_free(root);
|
||||||
|
free(tmp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 连接管理 ======================== */
|
||||||
|
|
||||||
|
static int do_connect(ha_client_t *c) {
|
||||||
|
c->state = HA_STATE_CONNECTING;
|
||||||
|
c->reconnect_cnt++;
|
||||||
|
|
||||||
|
/* 解析 server 地址 */
|
||||||
|
char host[256] = {0};
|
||||||
|
uint16_t port = 9890;
|
||||||
|
const char *p = c->config.server;
|
||||||
|
if (!p) return -1;
|
||||||
|
|
||||||
|
/* 去掉 ws:// 前缀 */
|
||||||
|
if (strncmp(p, "ws://", 5) == 0) p += 5;
|
||||||
|
else if (strncmp(p, "wss://", 6) == 0) p += 6;
|
||||||
|
|
||||||
|
/* 提取 host:port */
|
||||||
|
const char *colon = strchr(p, ':');
|
||||||
|
const char *slash = strchr(p, '/');
|
||||||
|
if (colon && (!slash || colon < slash)) {
|
||||||
|
int host_len = (int)(colon - p);
|
||||||
|
if (host_len > (int)sizeof(host) - 1) host_len = sizeof(host) - 1;
|
||||||
|
memcpy(host, p, host_len);
|
||||||
|
host[host_len] = '\0';
|
||||||
|
port = (uint16_t)atoi(colon + 1);
|
||||||
|
} else {
|
||||||
|
int host_len = (slash ? (int)(slash - p) : (int)strlen(p));
|
||||||
|
if (host_len > (int)sizeof(host) - 1) host_len = sizeof(host) - 1;
|
||||||
|
memcpy(host, p, host_len);
|
||||||
|
host[host_len] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
c->state = HA_STATE_WS_UPGRADING;
|
||||||
|
if (ha_ws_connect(&c->ws, &c->config.transport, host, port,
|
||||||
|
"/api/v1/device/ws", c->config.token) != 0) {
|
||||||
|
c->state = HA_STATE_DISCONNECTED;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 发送 hello */
|
||||||
|
c->state = HA_STATE_HELLO_SENT;
|
||||||
|
if (send_hello(c) != 0) {
|
||||||
|
ha_ws_close(&c->ws);
|
||||||
|
c->state = HA_STATE_DISCONNECTED;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 公共 API ======================== */
|
||||||
|
|
||||||
|
ha_client_t *ha_client_new(const ha_config_t *config) {
|
||||||
|
ha_client_t *c = (ha_client_t *)calloc(1, sizeof(ha_client_t));
|
||||||
|
if (!c) return NULL;
|
||||||
|
memcpy(&c->config, config, sizeof(ha_config_t));
|
||||||
|
c->state = HA_STATE_INIT;
|
||||||
|
c->reconnect_cnt = 0;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_status_t ha_client_start(ha_client_t *client) {
|
||||||
|
if (!client) return HA_ERR_INVALID;
|
||||||
|
if (client->state != HA_STATE_INIT) return HA_ERR_GENERIC;
|
||||||
|
|
||||||
|
/* 默认心跳间隔 30 秒 */
|
||||||
|
if (client->config.ping_interval <= 0) {
|
||||||
|
client->config.ping_interval = 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (do_connect(client) != 0) {
|
||||||
|
return HA_ERR_TRANSPORT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 等待 bind_ack(最多 5 秒) */
|
||||||
|
int wait_ms = 5000;
|
||||||
|
int step = 50;
|
||||||
|
while (wait_ms > 0 && client->state != HA_STATE_READY) {
|
||||||
|
/* 处理一帧 */
|
||||||
|
ha_status_t st = ha_client_process(client);
|
||||||
|
if (st != HA_OK && st != HA_ERR_DISCONNECTED) {
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
if (client->state == HA_STATE_READY) return HA_OK;
|
||||||
|
|
||||||
|
/* 简单延时:靠 process 中的 recv 阻塞 */
|
||||||
|
wait_ms -= step;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (client->state == HA_STATE_READY) ? HA_OK : HA_ERR_TIMEOUT;
|
||||||
|
}
|
||||||
|
|
||||||
|
ha_status_t ha_client_process(ha_client_t *client) {
|
||||||
|
if (!client) return HA_ERR_INVALID;
|
||||||
|
|
||||||
|
if (client->state == HA_STATE_STOPPING) {
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 断线重连 */
|
||||||
|
if (client->state == HA_STATE_DISCONNECTED ||
|
||||||
|
client->state == HA_STATE_INIT) {
|
||||||
|
if (client->config.max_reconnect >= 0 &&
|
||||||
|
client->reconnect_cnt > client->config.max_reconnect) {
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
/* 非阻塞模式:不在这里阻塞等待重连,返回 HA_ERR_DISCONNECTED */
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!client->ws.connected) {
|
||||||
|
client->state = HA_STATE_DISCONNECTED;
|
||||||
|
if (client->config.on_state) {
|
||||||
|
client->config.on_state(0, client->config.userdata);
|
||||||
|
}
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 尝试读取一帧 */
|
||||||
|
const uint8_t *payload = NULL;
|
||||||
|
int len = 0;
|
||||||
|
int ret = ha_ws_read_frame(&client->ws, &payload, &len);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
/* 连接断开 */
|
||||||
|
client->state = HA_STATE_DISCONNECTED;
|
||||||
|
if (client->config.on_state) {
|
||||||
|
client->config.on_state(0, client->config.userdata);
|
||||||
|
}
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (ret) {
|
||||||
|
case WS_OPCODE_TEXT:
|
||||||
|
handle_text_message(client, payload, len);
|
||||||
|
break;
|
||||||
|
case WS_OPCODE_BINARY:
|
||||||
|
/* 二进制帧:如果处于语音聚合状态,追加数据 */
|
||||||
|
if (client->speech.req_id[0] && payload) {
|
||||||
|
int new_len = client->speech.len + len;
|
||||||
|
if (new_len > client->speech.cap) {
|
||||||
|
int new_cap = client->speech.cap ? client->speech.cap * 2 : 4096;
|
||||||
|
while (new_cap < new_len) new_cap *= 2;
|
||||||
|
uint8_t *nd = (uint8_t *)realloc(client->speech.data, new_cap);
|
||||||
|
if (!nd) break;
|
||||||
|
client->speech.data = nd;
|
||||||
|
client->speech.cap = new_cap;
|
||||||
|
}
|
||||||
|
memcpy(client->speech.data + client->speech.len, payload, len);
|
||||||
|
client->speech.len = new_len;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case WS_OPCODE_PING:
|
||||||
|
/* 回复 pong */
|
||||||
|
ha_ws_send_frame(&client->ws, WS_OPCODE_PONG, NULL, 0);
|
||||||
|
break;
|
||||||
|
case WS_OPCODE_PONG:
|
||||||
|
/* 收到 pong,忽略 */
|
||||||
|
break;
|
||||||
|
case WS_OPCODE_CLOSE:
|
||||||
|
client->state = HA_STATE_DISCONNECTED;
|
||||||
|
if (client->config.on_state) {
|
||||||
|
client->config.on_state(0, client->config.userdata);
|
||||||
|
}
|
||||||
|
return HA_ERR_DISCONNECTED;
|
||||||
|
}
|
||||||
|
|
||||||
|
return HA_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_send_result(ha_client_t *client, const char *req_id,
|
||||||
|
const char *status, const char *output,
|
||||||
|
const char *error) {
|
||||||
|
if (!client || client->state != HA_STATE_READY) return;
|
||||||
|
json_init(client);
|
||||||
|
ha_json_builder_begin_object(&client->jb);
|
||||||
|
ha_json_builder_string(&client->jb, "op", "cmd_result");
|
||||||
|
ha_json_builder_string(&client->jb, "req_id", req_id);
|
||||||
|
ha_json_builder_string(&client->jb, "status", status ? status : "ok");
|
||||||
|
ha_json_builder_string(&client->jb, "device_id", client->config.device.device_id);
|
||||||
|
if (output && output[0]) {
|
||||||
|
ha_json_builder_string(&client->jb, "output", output);
|
||||||
|
}
|
||||||
|
if (error && error[0]) {
|
||||||
|
ha_json_builder_string(&client->jb, "error", error);
|
||||||
|
}
|
||||||
|
ha_json_builder_end_object(&client->jb);
|
||||||
|
ws_send_json(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_send_data_chunked(ha_client_t *client, const char *req_id,
|
||||||
|
const char *kind, const char *mime,
|
||||||
|
const uint8_t *data, int len) {
|
||||||
|
if (!client || client->state != HA_STATE_READY) return;
|
||||||
|
|
||||||
|
/* cmd_data_start */
|
||||||
|
json_init(client);
|
||||||
|
ha_json_builder_begin_object(&client->jb);
|
||||||
|
ha_json_builder_string(&client->jb, "op", "cmd_data_start");
|
||||||
|
ha_json_builder_string(&client->jb, "req_id", req_id);
|
||||||
|
ha_json_builder_string(&client->jb, "kind", kind ? kind : "data");
|
||||||
|
ha_json_builder_string(&client->jb, "mime", mime ? mime : "application/octet-stream");
|
||||||
|
ha_json_builder_int(&client->jb, "total", len);
|
||||||
|
ha_json_builder_int(&client->jb, "chunk_size", 8192);
|
||||||
|
ha_json_builder_end_object(&client->jb);
|
||||||
|
ws_send_json(client);
|
||||||
|
|
||||||
|
/* 二进制帧分块发送 */
|
||||||
|
int off = 0;
|
||||||
|
while (off < len) {
|
||||||
|
int chunk = len - off;
|
||||||
|
if (chunk > 8192) chunk = 8192;
|
||||||
|
if (ha_ws_send_binary(&client->ws, data + off, chunk) != 0) return;
|
||||||
|
off += chunk;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* cmd_data_end */
|
||||||
|
json_init(client);
|
||||||
|
ha_json_builder_begin_object(&client->jb);
|
||||||
|
ha_json_builder_string(&client->jb, "op", "cmd_data_end");
|
||||||
|
ha_json_builder_string(&client->jb, "req_id", req_id);
|
||||||
|
ha_json_builder_string(&client->jb, "status", "ok");
|
||||||
|
ha_json_builder_int(&client->jb, "total", len);
|
||||||
|
ha_json_builder_end_object(&client->jb);
|
||||||
|
ws_send_json(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_send_event(ha_client_t *client, const char *type,
|
||||||
|
const char *detail) {
|
||||||
|
if (!client || client->state != HA_STATE_READY) return;
|
||||||
|
json_init(client);
|
||||||
|
ha_json_builder_begin_object(&client->jb);
|
||||||
|
ha_json_builder_string(&client->jb, "op", "event");
|
||||||
|
ha_json_builder_string(&client->jb, "device_id", client->config.device.device_id);
|
||||||
|
ha_json_builder_string(&client->jb, "type", type ? type : "");
|
||||||
|
if (detail && detail[0]) {
|
||||||
|
ha_json_builder_string(&client->jb, "payload", detail);
|
||||||
|
}
|
||||||
|
ha_json_builder_end_object(&client->jb);
|
||||||
|
ws_send_json(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_send_status(ha_client_t *client, const char *status) {
|
||||||
|
if (!client || client->state != HA_STATE_READY) return;
|
||||||
|
json_init(client);
|
||||||
|
ha_json_builder_begin_object(&client->jb);
|
||||||
|
ha_json_builder_string(&client->jb, "op", "status");
|
||||||
|
ha_json_builder_string(&client->jb, "device_id", client->config.device.device_id);
|
||||||
|
ha_json_builder_string(&client->jb, "status", status ? status : "online");
|
||||||
|
ha_json_builder_end_object(&client->jb);
|
||||||
|
ws_send_json(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_stop(ha_client_t *client) {
|
||||||
|
if (!client) return;
|
||||||
|
client->state = HA_STATE_STOPPING;
|
||||||
|
if (client->ws.connected) {
|
||||||
|
ha_ws_close(&client->ws);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_client_destroy(ha_client_t *client) {
|
||||||
|
if (!client) return;
|
||||||
|
ha_client_stop(client);
|
||||||
|
free(client->speech.data);
|
||||||
|
free(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 工具函数 ======================== */
|
||||||
|
|
||||||
|
void ha_cmd_parse_homeagent(const char *command, const char **cap,
|
||||||
|
const char **args) {
|
||||||
|
*cap = command;
|
||||||
|
*args = "";
|
||||||
|
|
||||||
|
if (!command) {
|
||||||
|
*cap = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 去掉 homeagent- 前缀 */
|
||||||
|
const char *p = command;
|
||||||
|
if (strncmp(p, "homeagent-", 10) == 0) {
|
||||||
|
p += 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 按空格分割 */
|
||||||
|
const char *space = strchr(p, ' ');
|
||||||
|
if (space) {
|
||||||
|
/* cap 指向 p 但不包含空格,需要临时拷贝 */
|
||||||
|
/* 返回指针到原始字符串,调用方用 strncpy 取出 */
|
||||||
|
*cap = command; /* 调用方应使用 ha_cmd_parse_homeagent 的要小心 */
|
||||||
|
/* 实际上,最简单的方式是原地修改,但 const 不允许 */
|
||||||
|
/* 用静态缓冲区或让调用方自己处理 */
|
||||||
|
static char cap_buf[256];
|
||||||
|
int n = (int)(space - p);
|
||||||
|
if (n > 255) n = 255;
|
||||||
|
strncpy(cap_buf, p, n);
|
||||||
|
cap_buf[n] = '\0';
|
||||||
|
*cap = cap_buf;
|
||||||
|
*args = space + 1;
|
||||||
|
} else {
|
||||||
|
static char cap_buf[256];
|
||||||
|
strncpy(cap_buf, p, sizeof(cap_buf) - 1);
|
||||||
|
cap_buf[sizeof(cap_buf) - 1] = '\0';
|
||||||
|
*cap = cap_buf;
|
||||||
|
*args = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_cmd_parse_json(const char *command, const char **action,
|
||||||
|
const char **json_str) {
|
||||||
|
*action = "";
|
||||||
|
*json_str = "";
|
||||||
|
|
||||||
|
if (!command) return;
|
||||||
|
|
||||||
|
const char *p = command;
|
||||||
|
if (strncmp(p, "homeagent-", 10) == 0) {
|
||||||
|
p += 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *brace = strchr(p, '{');
|
||||||
|
if (brace) {
|
||||||
|
static char act_buf[256];
|
||||||
|
int n = (int)(brace - p);
|
||||||
|
while (n > 0 && (p[n - 1] == ' ' || p[n - 1] == '\t')) n--;
|
||||||
|
if (n > 255) n = 255;
|
||||||
|
strncpy(act_buf, p, n);
|
||||||
|
act_buf[n] = '\0';
|
||||||
|
*action = act_buf;
|
||||||
|
*json_str = brace;
|
||||||
|
} else {
|
||||||
|
static char act_buf[256];
|
||||||
|
strncpy(act_buf, p, sizeof(act_buf) - 1);
|
||||||
|
*action = act_buf;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *ha_version(void) {
|
||||||
|
return HA_VERSION;
|
||||||
|
}
|
||||||
|
|
||||||
325
remotedevice/src/ha_ws.c
Normal file
325
remotedevice/src/ha_ws.c
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
#include "ha_ws.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/* WS GUID 用于计算 Accept 值 */
|
||||||
|
#define WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||||
|
|
||||||
|
/* ======================== Base64 编码(用于 WS key) ======================== */
|
||||||
|
static const char b64t[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
|
static void base64_encode_bin(const uint8_t *in, int in_len, char *out) {
|
||||||
|
int i = 0, j = 0;
|
||||||
|
uint8_t b[3];
|
||||||
|
while (i < in_len) {
|
||||||
|
int rem = in_len - i;
|
||||||
|
if (rem >= 3) {
|
||||||
|
b[0] = in[i++]; b[1] = in[i++]; b[2] = in[i++];
|
||||||
|
out[j++] = b64t[b[0] >> 2];
|
||||||
|
out[j++] = b64t[((b[0] & 0x03) << 4) | (b[1] >> 4)];
|
||||||
|
out[j++] = b64t[((b[1] & 0x0F) << 2) | (b[2] >> 6)];
|
||||||
|
out[j++] = b64t[b[2] & 0x3F];
|
||||||
|
} else if (rem == 2) {
|
||||||
|
b[0] = in[i++]; b[1] = in[i++];
|
||||||
|
out[j++] = b64t[b[0] >> 2];
|
||||||
|
out[j++] = b64t[((b[0] & 0x03) << 4) | (b[1] >> 4)];
|
||||||
|
out[j++] = b64t[(b[1] & 0x0F) << 2];
|
||||||
|
out[j++] = '=';
|
||||||
|
} else {
|
||||||
|
b[0] = in[i++];
|
||||||
|
out[j++] = b64t[b[0] >> 2];
|
||||||
|
out[j++] = b64t[(b[0] & 0x03) << 4];
|
||||||
|
out[j++] = '=';
|
||||||
|
out[j++] = '=';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out[j] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 简单伪随机数生成器 */
|
||||||
|
static uint32_t ws_rand_state = 0;
|
||||||
|
static void ws_rand_seed(uint32_t seed) { ws_rand_state = seed; }
|
||||||
|
static uint32_t ws_rand(void) {
|
||||||
|
ws_rand_state = ws_rand_state * 1103515245 + 12345;
|
||||||
|
return ws_rand_state;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 生成 WS 握手 key */
|
||||||
|
static void ws_gen_key(char *out) {
|
||||||
|
uint8_t buf[16];
|
||||||
|
for (int i = 0; i < 16; i++) {
|
||||||
|
buf[i] = (uint8_t)(ws_rand() & 0xFF);
|
||||||
|
}
|
||||||
|
base64_encode_bin(buf, 16, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 从传输层接收指定字节数 ======================== */
|
||||||
|
static int recv_all(ha_ws_t *ws, uint8_t *buf, int len) {
|
||||||
|
int pos = 0;
|
||||||
|
while (pos < len) {
|
||||||
|
int n = ws->transport->recv(ws->transport->ctx, buf + pos, len - pos);
|
||||||
|
if (n <= 0) return -1;
|
||||||
|
pos += n;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 发送 WS 帧 ======================== */
|
||||||
|
int ha_ws_send_frame(ha_ws_t *ws, int opcode, const uint8_t *payload, int len) {
|
||||||
|
uint8_t hdr[14]; /* 最大帧头:2 + 8 + 4 = 14 */
|
||||||
|
int hdr_len = 0;
|
||||||
|
|
||||||
|
hdr[0] = 0x80 | opcode; /* FIN + opcode */
|
||||||
|
hdr_len = 2;
|
||||||
|
|
||||||
|
int ext_len = 0;
|
||||||
|
if (len < 126) {
|
||||||
|
hdr[1] = 0x80 | len; /* mask bit + length */
|
||||||
|
} else if (len < 65536) {
|
||||||
|
hdr[1] = 0x80 | 126;
|
||||||
|
hdr_len = 4;
|
||||||
|
hdr[2] = (uint8_t)(len >> 8);
|
||||||
|
hdr[3] = (uint8_t)(len & 0xFF);
|
||||||
|
ext_len = 2;
|
||||||
|
} else {
|
||||||
|
hdr[1] = 0x80 | 127;
|
||||||
|
hdr_len = 10;
|
||||||
|
uint64_t l = (uint64_t)len;
|
||||||
|
for (int i = 8; i > 0; i--) {
|
||||||
|
hdr[1 + i] = (uint8_t)(l & 0xFF);
|
||||||
|
l >>= 8;
|
||||||
|
}
|
||||||
|
ext_len = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* mask key */
|
||||||
|
uint8_t mask_key[4];
|
||||||
|
mask_key[0] = (uint8_t)(ws_rand() & 0xFF);
|
||||||
|
mask_key[1] = (uint8_t)(ws_rand() & 0xFF);
|
||||||
|
mask_key[2] = (uint8_t)(ws_rand() & 0xFF);
|
||||||
|
mask_key[3] = (uint8_t)(ws_rand() & 0xFF);
|
||||||
|
|
||||||
|
int mask_off = 2 + ext_len;
|
||||||
|
hdr[mask_off] = mask_key[0];
|
||||||
|
hdr[mask_off + 1] = mask_key[1];
|
||||||
|
hdr[mask_off + 2] = mask_key[2];
|
||||||
|
hdr[mask_off + 3] = mask_key[3];
|
||||||
|
hdr_len = mask_off + 4;
|
||||||
|
|
||||||
|
/* 发送帧头 */
|
||||||
|
if (ws->transport->send(ws->transport->ctx, hdr, hdr_len) != hdr_len) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 发送掩码后的 payload */
|
||||||
|
if (len > 0) {
|
||||||
|
/* 如果 payload 不大,用栈缓冲区 */
|
||||||
|
uint8_t stack_buf[2048];
|
||||||
|
uint8_t *masked = (len <= (int)sizeof(stack_buf)) ? stack_buf : (uint8_t *)malloc(len);
|
||||||
|
if (!masked) return -1;
|
||||||
|
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
masked[i] = payload[i] ^ mask_key[i & 3];
|
||||||
|
}
|
||||||
|
|
||||||
|
int ret = (ws->transport->send(ws->transport->ctx, masked, len) == len) ? 0 : -1;
|
||||||
|
|
||||||
|
if (masked != stack_buf) free(masked);
|
||||||
|
if (ret != 0) return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ======================== 公共 API ======================== */
|
||||||
|
|
||||||
|
int ha_ws_connect(ha_ws_t *ws, ha_transport_t *transport,
|
||||||
|
const char *host, uint16_t port,
|
||||||
|
const char *path, const char *token) {
|
||||||
|
memset(ws, 0, sizeof(ha_ws_t));
|
||||||
|
ws->transport = transport;
|
||||||
|
ws->connected = 0;
|
||||||
|
|
||||||
|
strncpy(ws->host, host, sizeof(ws->host) - 1);
|
||||||
|
ws->port = port;
|
||||||
|
strncpy(ws->path, path, sizeof(ws->path) - 1);
|
||||||
|
if (token) strncpy(ws->token, token, sizeof(ws->token) - 1);
|
||||||
|
|
||||||
|
/* 种子 */
|
||||||
|
ws_rand_seed((uint32_t)(uintptr_t)ws ^ (uint32_t)port);
|
||||||
|
|
||||||
|
/* 1. TCP 连接 */
|
||||||
|
if (transport->connect(transport->ctx, host, port) != 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 2. 发送 WS 升级请求 */
|
||||||
|
char key[32];
|
||||||
|
ws_gen_key(key);
|
||||||
|
|
||||||
|
char req[1024];
|
||||||
|
int n = snprintf(req, sizeof(req),
|
||||||
|
"GET %s HTTP/1.1\r\n"
|
||||||
|
"Host: %s:%u\r\n"
|
||||||
|
"Upgrade: websocket\r\n"
|
||||||
|
"Connection: Upgrade\r\n"
|
||||||
|
"Sec-WebSocket-Key: %s\r\n"
|
||||||
|
"Sec-WebSocket-Version: 13\r\n"
|
||||||
|
"\r\n",
|
||||||
|
path, host, (unsigned)port, key);
|
||||||
|
|
||||||
|
/* 如果 token 存在,加到路径参数中 */
|
||||||
|
if (token && token[0]) {
|
||||||
|
n = snprintf(req, sizeof(req),
|
||||||
|
"GET %s?token=%s HTTP/1.1\r\n"
|
||||||
|
"Host: %s:%u\r\n"
|
||||||
|
"Upgrade: websocket\r\n"
|
||||||
|
"Connection: Upgrade\r\n"
|
||||||
|
"Sec-WebSocket-Key: %s\r\n"
|
||||||
|
"Sec-WebSocket-Version: 13\r\n"
|
||||||
|
"\r\n",
|
||||||
|
path, token, host, (unsigned)port, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (transport->send(transport->ctx, (uint8_t *)req, n) != n) {
|
||||||
|
transport->close(transport->ctx);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 3. 读取响应头(直到 \r\n\r\n) */
|
||||||
|
char resp[1024];
|
||||||
|
int resp_len = 0;
|
||||||
|
int found = 0;
|
||||||
|
while (resp_len < (int)sizeof(resp) - 1) {
|
||||||
|
int n = transport->recv(transport->ctx, (uint8_t *)(resp + resp_len), 1);
|
||||||
|
if (n <= 0) {
|
||||||
|
transport->close(transport->ctx);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
resp_len += n;
|
||||||
|
resp[resp_len] = '\0';
|
||||||
|
if (resp_len >= 4 && strcmp(resp + resp_len - 4, "\r\n\r\n") == 0) {
|
||||||
|
found = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!found) {
|
||||||
|
transport->close(transport->ctx);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 4. 检查状态码 101 */
|
||||||
|
if (strstr(resp, " 101 ") == NULL) {
|
||||||
|
transport->close(transport->ctx);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ws->connected = 1;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_ws_send_text(ha_ws_t *ws, const char *text) {
|
||||||
|
if (!ws->connected) return -1;
|
||||||
|
return ha_ws_send_frame(ws, WS_OPCODE_TEXT, (const uint8_t *)text, (int)strlen(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_ws_send_binary(ha_ws_t *ws, const uint8_t *data, int len) {
|
||||||
|
if (!ws->connected) return -1;
|
||||||
|
return ha_ws_send_frame(ws, WS_OPCODE_BINARY, data, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_ws_send_ping(ha_ws_t *ws) {
|
||||||
|
if (!ws->connected) return -1;
|
||||||
|
return ha_ws_send_frame(ws, WS_OPCODE_PING, NULL, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
int ha_ws_read_frame(ha_ws_t *ws, const uint8_t **payload, int *len) {
|
||||||
|
if (!ws->connected) return -1;
|
||||||
|
|
||||||
|
*payload = NULL;
|
||||||
|
*len = 0;
|
||||||
|
|
||||||
|
/* 读取帧头:2 字节 */
|
||||||
|
uint8_t hdr[2];
|
||||||
|
if (recv_all(ws, hdr, 2) != 0) {
|
||||||
|
ws->connected = 0;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int opcode = hdr[0] & 0x0F;
|
||||||
|
int masked = (hdr[1] & 0x80) ? 1 : 0;
|
||||||
|
uint64_t frame_len = hdr[1] & 0x7F;
|
||||||
|
|
||||||
|
if (frame_len == 126) {
|
||||||
|
uint8_t ext[2];
|
||||||
|
if (recv_all(ws, ext, 2) != 0) { ws->connected = 0; return -1; }
|
||||||
|
frame_len = ((uint64_t)ext[0] << 8) | ext[1];
|
||||||
|
} else if (frame_len == 127) {
|
||||||
|
uint8_t ext[8];
|
||||||
|
if (recv_all(ws, ext, 8) != 0) { ws->connected = 0; return -1; }
|
||||||
|
frame_len = 0;
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
frame_len = (frame_len << 8) | ext[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 读取 mask key */
|
||||||
|
uint8_t mask_key[4] = {0, 0, 0, 0};
|
||||||
|
if (masked) {
|
||||||
|
if (recv_all(ws, mask_key, 4) != 0) { ws->connected = 0; return -1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 限制帧大小 */
|
||||||
|
if (frame_len > sizeof(ws->read_buf)) {
|
||||||
|
/* 帧太大,跳过 payload */
|
||||||
|
uint64_t skip = frame_len;
|
||||||
|
uint8_t tmp[256];
|
||||||
|
while (skip > 0) {
|
||||||
|
int to_skip = (skip > sizeof(tmp)) ? (int)sizeof(tmp) : (int)skip;
|
||||||
|
if (recv_all(ws, tmp, to_skip) != 0) { ws->connected = 0; return -1; }
|
||||||
|
skip -= to_skip;
|
||||||
|
}
|
||||||
|
return -1; /* 返回错误,帧太大 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 读取 payload */
|
||||||
|
if (frame_len > 0) {
|
||||||
|
if (recv_all(ws, ws->read_buf, (int)frame_len) != 0) {
|
||||||
|
ws->connected = 0;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
/* 如果有 mask,解掩码 */
|
||||||
|
if (masked) {
|
||||||
|
for (uint64_t i = 0; i < frame_len; i++) {
|
||||||
|
ws->read_buf[i] ^= mask_key[i & 3];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*payload = ws->read_buf;
|
||||||
|
*len = (int)frame_len;
|
||||||
|
|
||||||
|
switch (opcode) {
|
||||||
|
case WS_OPCODE_CLOSE:
|
||||||
|
ws->connected = 0;
|
||||||
|
return WS_OPCODE_CLOSE;
|
||||||
|
case WS_OPCODE_PING:
|
||||||
|
return WS_OPCODE_PING;
|
||||||
|
case WS_OPCODE_PONG:
|
||||||
|
return WS_OPCODE_PONG;
|
||||||
|
case WS_OPCODE_TEXT:
|
||||||
|
case WS_OPCODE_BINARY:
|
||||||
|
return opcode;
|
||||||
|
default:
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ha_ws_close(ha_ws_t *ws) {
|
||||||
|
if (ws->connected) {
|
||||||
|
ha_ws_send_frame(ws, WS_OPCODE_CLOSE, NULL, 0);
|
||||||
|
ws->connected = 0;
|
||||||
|
}
|
||||||
|
ws->transport->close(ws->transport->ctx);
|
||||||
|
}
|
||||||
62
remotedevice/src/ha_ws.h
Normal file
62
remotedevice/src/ha_ws.h
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
#ifndef HA_WS_H
|
||||||
|
#define HA_WS_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include "../include/ha_remotedevice.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ======================== WS 帧类型 ======================== */
|
||||||
|
#define WS_OPCODE_CONTINUATION 0x0
|
||||||
|
#define WS_OPCODE_TEXT 0x1
|
||||||
|
#define WS_OPCODE_BINARY 0x2
|
||||||
|
#define WS_OPCODE_CLOSE 0x8
|
||||||
|
#define WS_OPCODE_PING 0x9
|
||||||
|
#define WS_OPCODE_PONG 0xA
|
||||||
|
|
||||||
|
/* ======================== WS 连接 ======================== */
|
||||||
|
typedef struct {
|
||||||
|
ha_transport_t *transport; /* 用户实现的传输层 */
|
||||||
|
int connected; /* 是否已连接 */
|
||||||
|
uint8_t read_buf[8192]; /* 读缓冲区 */
|
||||||
|
int read_pos; /* 缓冲区中有效数据起始位置 */
|
||||||
|
int read_len; /* 缓冲区中有效数据长度 */
|
||||||
|
char host[256]; /* 缓存目标地址 */
|
||||||
|
uint16_t port;
|
||||||
|
char path[256];
|
||||||
|
char token[256];
|
||||||
|
} ha_ws_t;
|
||||||
|
|
||||||
|
/* 创建 WS 连接。返回 0 成功,非 0 失败。 */
|
||||||
|
int ha_ws_connect(ha_ws_t *ws, ha_transport_t *transport,
|
||||||
|
const char *host, uint16_t port,
|
||||||
|
const char *path, const char *token);
|
||||||
|
|
||||||
|
/* 发送文本帧。返回 0 成功。 */
|
||||||
|
int ha_ws_send_text(ha_ws_t *ws, const char *text);
|
||||||
|
|
||||||
|
/* 发送二进制帧。返回 0 成功。 */
|
||||||
|
int ha_ws_send_binary(ha_ws_t *ws, const uint8_t *data, int len);
|
||||||
|
|
||||||
|
/* 发送 ping。返回 0 成功。 */
|
||||||
|
int ha_ws_send_ping(ha_ws_t *ws);
|
||||||
|
|
||||||
|
/* 读取一帧。
|
||||||
|
* 返回 opcode (0x1/0x2/0x8/0x9/0xA),-1 表示关闭或错误。
|
||||||
|
* payload 和 len 指向内部缓冲区,在下次调用前有效。 */
|
||||||
|
int ha_ws_read_frame(ha_ws_t *ws, const uint8_t **payload, int *len);
|
||||||
|
|
||||||
|
/* 发送原始 WS 帧(内部使用,用于回复 ping) */
|
||||||
|
int ha_ws_send_frame(ha_ws_t *ws, int opcode, const uint8_t *payload, int len);
|
||||||
|
|
||||||
|
/* 关闭 WS 连接 */
|
||||||
|
void ha_ws_close(ha_ws_t *ws);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* HA_WS_H */
|
||||||
1509
remotedevice/test/test_ha_remotedevice.c
Normal file
1509
remotedevice/test/test_ha_remotedevice.c
Normal file
File diff suppressed because it is too large
Load Diff
@ -25,13 +25,18 @@ type Relation struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Triple represents a subject-relation-object triple for the knowledge graph.
|
// Triple represents a subject-relation-object triple for the knowledge graph.
|
||||||
|
//
|
||||||
|
// SentenceText 是这条三元组的原句,会写进 sentences 表;媒体引用挂在句子上,
|
||||||
|
// 所以 MediaDigests 非空时内核会保证句子存在(不给就自动合成一句)。
|
||||||
type Triple struct {
|
type Triple struct {
|
||||||
Subject string `json:"subject"`
|
Subject string `json:"subject"`
|
||||||
Relation string `json:"relation"`
|
Relation string `json:"relation"`
|
||||||
Object string `json:"object"`
|
Object string `json:"object"`
|
||||||
Confidence float64 `json:"confidence,omitempty"`
|
Confidence float64 `json:"confidence,omitempty"`
|
||||||
SubjectType string `json:"subject_type,omitempty"`
|
SubjectType string `json:"subject_type,omitempty"`
|
||||||
ObjectType string `json:"object_type,omitempty"`
|
ObjectType string `json:"object_type,omitempty"`
|
||||||
|
SentenceText string `json:"sentence_text,omitempty"`
|
||||||
|
MediaDigests []string `json:"media_digests,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TextMemoryAPI provides access to chronological text event storage.
|
// TextMemoryAPI provides access to chronological text event storage.
|
||||||
@ -40,27 +45,54 @@ type TextMemoryAPI interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TextEvent represents a single text memory event.
|
// TextEvent represents a single text memory event.
|
||||||
|
// MediaAttachment 描述一份与记忆关联的媒体。
|
||||||
|
//
|
||||||
|
// 两个方向共用一个类型:
|
||||||
|
// - 写入(InsertWithMedia):给 Data + MIME 就是新内容;只给 Digest 则是引用已有内容。
|
||||||
|
// - 读出(Query):内核只填 Digest/MIME,**不回 Data**——
|
||||||
|
// 一次检索可能命中几十张图,把字节全塞回插件会把 ABI 消息撑爆。
|
||||||
|
// 需要字节时拿 Digest 单独取。
|
||||||
|
//
|
||||||
|
// 刻意没有 Description 字段:媒体不作为文本被索引,也不带任何生成的描述。
|
||||||
|
// 它只按自己的原生向量被检索与召回;附加文字请写在文档 / 三元组的文本里。
|
||||||
|
type MediaAttachment struct {
|
||||||
|
Digest string `json:"digest,omitempty"`
|
||||||
|
MIME string `json:"mime,omitempty"`
|
||||||
|
Data []byte `json:"data,omitempty"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type TextEvent struct {
|
type TextEvent struct {
|
||||||
Role string `json:"role"`
|
Role string `json:"role"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Timestamp int64 `json:"timestamp"`
|
Timestamp int64 `json:"timestamp"`
|
||||||
Channel string `json:"channel,omitempty"`
|
Channel string `json:"channel,omitempty"`
|
||||||
|
Attachments []MediaAttachment `json:"attachments,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DocMemoryAPI provides access to the document vector store.
|
// DocMemoryAPI provides access to the document vector store.
|
||||||
type DocMemoryAPI interface {
|
type DocMemoryAPI interface {
|
||||||
Query(text string, topK int) []*Doc
|
Query(text string, topK int) []*Doc
|
||||||
Insert(doc *Doc) error
|
Insert(doc *Doc) error
|
||||||
|
// InsertWithMedia 写入文档并关联媒体。attachments 里带 Data 的会落进
|
||||||
|
// 内容寻址存储(相同字节只存一份),只带 Digest 的直接引用已有内容。
|
||||||
|
// 媒体成为文档直接持有的一等记忆块:文档向量会融合它们的原生向量,
|
||||||
|
// 因此图片按自己的向量被召回,不依赖任何生成的描述文本。
|
||||||
|
InsertWithMedia(doc *Doc, attachments []MediaAttachment) error
|
||||||
Remove(id string)
|
Remove(id string)
|
||||||
Stats() map[string]interface{}
|
Stats() map[string]interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Doc represents a document in the document store.
|
// Doc represents a document in the document store.
|
||||||
|
//
|
||||||
|
// MediaDigests / Attachments 在 Query 返回时由内核填充(仅元数据,不带字节)。
|
||||||
type Doc struct {
|
type Doc struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
Score float64 `json:"score,omitempty"`
|
Score float64 `json:"score,omitempty"`
|
||||||
|
MediaDigests []string `json:"media_digests,omitempty"`
|
||||||
|
Attachments []MediaAttachment `json:"attachments,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SocialAPI provides read-only access to the social graph (person profiles and relationships).
|
// SocialAPI provides read-only access to the social graph (person profiles and relationships).
|
||||||
@ -75,9 +107,9 @@ type SocialAPI interface {
|
|||||||
|
|
||||||
// PersonProfile represents a person's complete profile (traits + social relations).
|
// PersonProfile represents a person's complete profile (traits + social relations).
|
||||||
type PersonProfile struct {
|
type PersonProfile struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Traits map[string]string `json:"traits,omitempty"`
|
Traits map[string]string `json:"traits,omitempty"`
|
||||||
Relations []SocialRelation `json:"relations,omitempty"`
|
Relations []SocialRelation `json:"relations,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SocialRelation represents a social relationship between two persons.
|
// SocialRelation represents a social relationship between two persons.
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user