mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-22 09:58:06 +00:00
Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8313120d2a | |||
| 5f63f6ec6c | |||
| a13504be38 | |||
| e75859668b | |||
| b6a66c57fe | |||
| 1b49365d46 | |||
| 17ea7fd5f0 | |||
| ffcfaf46e2 | |||
| cd88b2dfe5 | |||
| 1d46c6c0f6 | |||
| 4707b05498 | |||
| f5df904d02 | |||
| 8537577123 | |||
| 918f29899c | |||
| c4659342b3 | |||
| 02600a3b90 | |||
| 02861f5d64 | |||
| cea8011f3d | |||
| 68835c18db | |||
| 89db544671 | |||
| a021055011 | |||
| d17c18665c |
1
.gitignore
vendored
1
.gitignore
vendored
@ -31,6 +31,7 @@ cmd/gui/dist/
|
||||
third_party/homeagent-sdk/bin/
|
||||
third_party/homeagent-sdk/tools/
|
||||
third_party/homeagent-sdk/package/
|
||||
third_party/homeagent-sdk/scripts/
|
||||
third_party/homeagent-sdk/.gitignore
|
||||
third_party/homeagent-sdk/README*
|
||||
third_party/homeagent-sdk/example/
|
||||
|
||||
@ -599,23 +599,26 @@ When running inside the kernel, `sdk.*` global variables are injected by the Go
|
||||
|
||||
### Lua SDK API
|
||||
|
||||
The `sdk.*` API of Lua plugins is fully aligned with external plugins (toolchain-built `plugin.bin` subprocesses): registration functions raise a Lua error on failure; data functions uniformly return `(result, err)` with `err == nil` on success. Subsystems not wired by the core (e.g. SocialAPI) return empty values instead of errors.
|
||||
The `sdk.*` API of Lua plugins is aligned with external plugins (toolchain-built `plugin.bin` subprocesses) up to **SDK 1.3.0** (requires kernel **1.4.0+**, also backfilled by the Lua-alignment patch `v1.3.11`): registration functions raise a Lua error on failure; data functions uniformly return `(result, err)` with `err == nil` on success. Subsystems not wired by the core (e.g. SocialAPI) return empty values instead of errors.
|
||||
|
||||
> Historical note: the 1.1–1.3 media / inject-flags / priority capabilities were long available only on the Go side and were silently missing on the Lua side. They are now fully aligned, guarded by the contract test in `internal/plugin/lua_surface_test.go` (every function promised by the mock has a runtime binding).
|
||||
|
||||
**Registration**
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `sdk.log(level, msg)` | Log output |
|
||||
| `sdk.register_tool(name, def, handler)` | Register tool; `def` supports `description`, `parameters`, `no_memory`, `cleaner` |
|
||||
| `sdk.register_tool(name, def, handler)` | Register tool; `def` supports `description`, `parameters`, `no_memory`, `context_policy` (`"none"`/`"prune"`), `cleaner` |
|
||||
| `sdk.register_stage(stage, handler, scope)` | Register stage hook; `scope` is `nil`/`"global"` (default) or `"own_tools"` (fires only for `before_toolcall`/`after_toolcall` when the tool belongs to this plugin) |
|
||||
| `sdk.register_api(name)` | Register API |
|
||||
| `sdk.register_output_channel(name, caps, desc, def, handler)` | Register output channel; `def` supports `no_memory`, `cleaner` |
|
||||
| `sdk.register_output_channel(name, caps, desc, def, handler)` | Register output channel; `def` supports `no_memory`, `context_policy`, `cleaner` |
|
||||
| `sdk.register_input_channel(name, def)` | Register input channel; `def` as above |
|
||||
| `sdk.unregister_output_channel(name)` | Unregister an output channel (for resource-bound channels, e.g. remote devices); returns `(nil, err)` |
|
||||
| `sdk.set_auto_restart(enabled)` | Auto-restart the plugin after a crash |
|
||||
|
||||
**Stage hook context**
|
||||
|
||||
Stage handlers receive the full context (same as external plugins): `raw_message`, `user_id`, `group_id`, `phase`, `llm_text`, `final_text`, `no_memory`, `response` (when responded), `tool_calls`, `tool_results`.
|
||||
Stage handlers receive the full context (same as external plugins): `raw_message`, `user_id`, `group_id`, `phase`, `llm_text`, `reasoning_content`, `final_text`, `no_memory`, `context_msgs`, `token_usage`, `memory`, `extra`, `errors`, `response` (when responded), `tool_calls`, `tool_results`.
|
||||
|
||||
**Stage writeback**: the `ctx` table passed to the handler is a reference — mutating writable fields inside the handler syncs back to the core `StageContext` (aligned with subprocess external-plugin capability):
|
||||
|
||||
@ -644,20 +647,37 @@ Writable fields: `raw_message`, `llm_text`, `final_text`, `user_id`, `group_id`,
|
||||
| `sdk.inject_text(source, channel, text)` | Deliver text message |
|
||||
| `sdk.inject_interrupt(source, channel, text)` | Interrupt delivery |
|
||||
| `sdk.inject_text_no_memory(source, channel, text)` | Deliver without memory computation |
|
||||
| `sdk.inject_text_opts` / `sdk.inject_interrupt_opts(source, channel, text, opts)` | Delivery with flags; `opts = { no_memory=bool, context_policy="none"|"prune", cleaner_name=string, priority="L1".."L3" }` |
|
||||
| `sdk.inject_input_sync(source, channel, text)` | Inject synchronously and wait for this turn's reply; returns `(reply, err)`, reply is nil when there is none |
|
||||
| `sdk.inject_input_sync_opts(source, channel, text, opts)` | Same, with flags |
|
||||
| `sdk.inject_input_media(source, channel, text, blocks)` | Inject text + multimodal content blocks |
|
||||
| `sdk.inject_input_media_opts(source, channel, text, blocks, opts)` | Same, with flags |
|
||||
| `sdk.inject_input_media_sync` / `..._sync_opts(...)` | Synchronous media injection; returns `(reply, err)` |
|
||||
| `sdk.inject_interrupt_media(source, channel, text, blocks)` | Interrupt delivery with media |
|
||||
| `sdk.inject_interrupt_media_opts(source, channel, text, blocks, opts)` | Same, with flags |
|
||||
| `sdk.set_tool_blocks(blocks)` | Set multimodal blocks carried by the next tool message (lets the model see images / hear audio) |
|
||||
|
||||
Each `blocks` item: `{ type="text", text="..." }`, `{ type="image_url", image_url={ url="...", detail="high" } }`, or `{ type="audio_url", audio_url={ url="..." } }`. An absent `opts` is the zero value (recorded in memory + no pruning), equivalent to the three-argument form.
|
||||
|
||||
**Data APIs (aligned with subprocess external plugins, all return `(result, err)`)**
|
||||
|
||||
| Sub-table | Functions |
|
||||
|-----------|-----------|
|
||||
| `sdk.memory.*` | `recall(query, depth)`, `commit({triples})`, `introspect()`, `merge(source, target)`, `purge(criteria, hard)` |
|
||||
| `sdk.doc.*` | `query(text, top_k)`, `insert({id,title,content})`, `remove(id)`, `stats()` |
|
||||
| `sdk.memory.*` | `recall(query, depth)`, `commit({triples})` (triple supports `subject/relation/object/confidence/subject_type/object_type/sentence_text/media_digests`), `introspect()`, `merge(source, target)`, `purge(criteria, hard)` |
|
||||
| `sdk.doc.*` | `query(text, top_k)`, `insert({id,title,content})`, `insert_with_media(doc, attachments)`, `remove(id)`, `stats()` |
|
||||
| `sdk.knowledge.*` | `search(query, limit)`, `add(tag, content)`, `list()` |
|
||||
| `sdk.text_memory.*` | `append({role,content,timestamp,channel})` |
|
||||
| `sdk.text_memory.*` | `append({role,content,timestamp,channel,attachments})` |
|
||||
| `sdk.llm.*` | `list_sources()`, `set_source(name)`, `current_source()` |
|
||||
| `sdk.social.*` (read-only) | `get_person(name)`, `get_network(name, depth)`, `get_trait(name, trait)`, `get_relations(name)`, `list_persons()` |
|
||||
| `sdk.events.*` | `subscribe(event_type, handler)` → returns an unsubscribe function; handler receives `{type,source,timestamp,payload}` |
|
||||
| `sdk.plugin_mgr.*` | `reload_one(name)`, `list_loaded()`, `is_disabled(name)` |
|
||||
| `sdk.json.*` | `encode(val)`, `decode(str)` |
|
||||
| `sdk.http.*` | `get(url)`, `post(url, body, content_type)` |
|
||||
|
||||
Each `attachments` item: `{ digest=, mime=, name=, data=<base64> }`; with `data` it is new content (stored in the content-addressed store), with only `digest` it references existing content.
|
||||
|
||||
> The `sdk.events.subscribe` callback runs on the kernel's event-publishing goroutine, and Lua is single-state + mutex-guarded — **do only lightweight forwarding inside the callback; never block**, or every call of this plugin will stall.
|
||||
|
||||
---
|
||||
|
||||
<img src="../../assets/branding/mascot-xiaozhai.webp" width="20" style="border-radius:50%;vertical-align:middle"> :
|
||||
|
||||
@ -592,23 +592,26 @@ lua main.lua
|
||||
|
||||
### Lua SDK API
|
||||
|
||||
Lua 插件的 `sdk.*` API 与外部插件(工具链编译的 `plugin.bin` 子进程)能力完全对齐:注册类函数调用即时报错(抛 Lua error),数据类函数统一返回 `(result, err)`,`err` 为 nil 表示成功。核心未装配的子系统(如 SocialAPI)返回空值而非报错。
|
||||
Lua 插件的 `sdk.*` API 与外部插件(工具链编译的 `plugin.bin` 子进程)能力对齐至 **SDK 1.3.0**(需内核 **1.4.0+**,也在 `v1.3.11` 的 Lua 对齐补丁中回填):注册类函数调用即时报错(抛 Lua error),数据类函数统一返回 `(result, err)`,`err` 为 nil 表示成功。核心未装配的子系统(如 SocialAPI)返回空值而非报错。
|
||||
|
||||
> 历史提醒:1.1–1.3 的媒体/注入标志位/优先级能力曾长期只在 Go 侧,Lua 侧静默缺失。现已全量对齐,并由 `internal/plugin/lua_surface_test.go` 的契约测试守住「mock 承诺的每个函数都有运行时绑定」。
|
||||
|
||||
**注册类**
|
||||
|
||||
| 函数 | 说明 |
|
||||
|------|------|
|
||||
| `sdk.log(level, msg)` | 日志输出 |
|
||||
| `sdk.register_tool(name, def, handler)` | 注册工具;`def` 支持 `description`、`parameters`、`no_memory`、`cleaner` |
|
||||
| `sdk.register_tool(name, def, handler)` | 注册工具;`def` 支持 `description`、`parameters`、`no_memory`、`context_policy`(`"none"`/`"prune"`)、`cleaner` |
|
||||
| `sdk.register_stage(stage, handler, scope)` | 注册阶段钩子;`scope` 为 `nil`/`"global"`(默认)或 `"own_tools"`(仅 `before_toolcall`/`after_toolcall` 且工具属于本插件时触发) |
|
||||
| `sdk.register_api(name)` | 注册 API |
|
||||
| `sdk.register_output_channel(name, caps, desc, def, handler)` | 注册输出通道;`def` 支持 `no_memory`、`cleaner` |
|
||||
| `sdk.register_output_channel(name, caps, desc, def, handler)` | 注册输出通道;`def` 支持 `no_memory`、`context_policy`、`cleaner` |
|
||||
| `sdk.register_input_channel(name, def)` | 注册输入通道;`def` 同上 |
|
||||
| `sdk.unregister_output_channel(name)` | 注销输出通道(随资源生灭的动态通道,如远程设备);返回 `(nil, err)` |
|
||||
| `sdk.set_auto_restart(enabled)` | 崩溃时内核自动拉起插件 |
|
||||
|
||||
**阶段钩子上下文**
|
||||
|
||||
`register_stage` 的 handler 收到完整上下文(与外部插件一致):`raw_message`、`user_id`、`group_id`、`phase`、`llm_text`、`final_text`、`no_memory`、`response`(已响应时)、`tool_calls`、`tool_results`。
|
||||
`register_stage` 的 handler 收到完整上下文(与外部插件一致):`raw_message`、`user_id`、`group_id`、`phase`、`llm_text`、`reasoning_content`、`final_text`、`no_memory`、`context_msgs`、`token_usage`、`memory`、`extra`、`errors`、`response`(已响应时)、`tool_calls`、`tool_results`。
|
||||
|
||||
**Stage 写回**:handler 收到的 `ctx` 是引用 table——在 handler 内直接修改可写回字段并同步至内核 `StageContext`(与子进程外部插件能力对齐):
|
||||
|
||||
@ -637,20 +640,37 @@ end)
|
||||
| `sdk.inject_text(source, channel, text)` | 投递文本消息 |
|
||||
| `sdk.inject_interrupt(source, channel, text)` | 中断投递 |
|
||||
| `sdk.inject_text_no_memory(source, channel, text)` | 免记忆投递 |
|
||||
| `sdk.inject_text_opts` / `sdk.inject_interrupt_opts(source, channel, text, opts)` | 带标志位投递;`opts = { no_memory=bool, context_policy="none"|"prune", cleaner_name=string, priority="L1".."L3" }` |
|
||||
| `sdk.inject_input_sync(source, channel, text)` | 同步注入并等本轮回复;返回 `(reply, err)`,无回复时 reply 为 nil |
|
||||
| `sdk.inject_input_sync_opts(source, channel, text, opts)` | 同上带标志位 |
|
||||
| `sdk.inject_input_media(source, channel, text, blocks)` | 注入文本 + 多模态内容块 |
|
||||
| `sdk.inject_input_media_opts(source, channel, text, blocks, opts)` | 同上带标志位 |
|
||||
| `sdk.inject_input_media_sync` / `..._sync_opts(...)` | 带媒体的同步注入;返回 `(reply, err)` |
|
||||
| `sdk.inject_interrupt_media(source, channel, text, blocks)` | 带媒体的中断注入 |
|
||||
| `sdk.inject_interrupt_media_opts(source, channel, text, blocks, opts)` | 同上带标志位 |
|
||||
| `sdk.set_tool_blocks(blocks)` | 设置下一轮 tool message 携带的多模态内容块(模型据此看图/听音频) |
|
||||
|
||||
`blocks` 每项形如:`{ type="text", text="..." }`、`{ type="image_url", image_url={ url="...", detail="high" } }`、`{ type="audio_url", audio_url={ url="..." } }`。`opts` 缺省即零值(记入记忆 + 不裁剪),与三参数版本等价。
|
||||
|
||||
**数据类(与子进程外部插件对齐,均返回 `(result, err)`)**
|
||||
|
||||
| 子表 | 函数 |
|
||||
|------|------|
|
||||
| `sdk.memory.*` | `recall(query, depth)`、`commit({triples})`、`introspect()`、`merge(source, target)`、`purge(criteria, hard)` |
|
||||
| `sdk.doc.*` | `query(text, top_k)`、`insert({id,title,content})`、`remove(id)`、`stats()` |
|
||||
| `sdk.memory.*` | `recall(query, depth)`、`commit({triples})`(triple 支持 `subject/relation/object/confidence/subject_type/object_type/sentence_text/media_digests`)、`introspect()`、`merge(source, target)`、`purge(criteria, hard)` |
|
||||
| `sdk.doc.*` | `query(text, top_k)`、`insert({id,title,content})`、`insert_with_media(doc, attachments)`、`remove(id)`、`stats()` |
|
||||
| `sdk.knowledge.*` | `search(query, limit)`、`add(tag, content)`、`list()` |
|
||||
| `sdk.text_memory.*` | `append({role,content,timestamp,channel})` |
|
||||
| `sdk.text_memory.*` | `append({role,content,timestamp,channel,attachments})` |
|
||||
| `sdk.llm.*` | `list_sources()`、`set_source(name)`、`current_source()` |
|
||||
| `sdk.social.*`(只读) | `get_person(name)`、`get_network(name, depth)`、`get_trait(name, trait)`、`get_relations(name)`、`list_persons()` |
|
||||
| `sdk.events.*` | `subscribe(event_type, handler)` → 返回取消订阅函数;handler 收到 `{type,source,timestamp,payload}` |
|
||||
| `sdk.plugin_mgr.*` | `reload_one(name)`、`list_loaded()`、`is_disabled(name)` |
|
||||
| `sdk.json.*` | `encode(val)`、`decode(str)` |
|
||||
| `sdk.http.*` | `get(url)`、`post(url, body, content_type)` |
|
||||
|
||||
`attachments` 每项:`{ digest=, mime=, name=, data=<base64> }`;带 `data` 是新内容(落进内容寻址存储),只带 `digest` 是引用已有内容。
|
||||
|
||||
> `sdk.events.subscribe` 的回调在内核事件发布 goroutine 上执行,且 Lua 是单状态 + 互斥锁——**回调内只做轻量转发,不可阻塞**,否则会卡死本插件的全部调用。
|
||||
|
||||
---
|
||||
|
||||
<img src="../../assets/branding/mascot-xiaozhai.webp" width="20" style="border-radius:50%;vertical-align:middle"> :
|
||||
|
||||
@ -325,7 +325,7 @@ func New(cfg AgentConfig) *Agent {
|
||||
}
|
||||
}
|
||||
|
||||
return &Agent{
|
||||
a := &Agent{
|
||||
id: cfg.ID,
|
||||
startTime: time.Now(),
|
||||
provider: cfg.Provider,
|
||||
@ -376,6 +376,14 @@ func New(cfg AgentConfig) *Agent {
|
||||
noMergeMarkers: make(map[string]int),
|
||||
lastInput: make(map[string]time.Time),
|
||||
}
|
||||
|
||||
// 输入路由:inputch 是可分配资源,划给某个 agent 后输入**只**流向那个 agent
|
||||
// (设计 §4.1「路由发生在进内核之前」)。io 层不认识 agent,所以在这里把路由器
|
||||
// 注入进去:插件注入输入时先问它,被别的 agent 接管就不再进本内核队列。
|
||||
if a.io != nil {
|
||||
a.io.SetInputRouter(a.routeInputByOwner)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// SetSkillIndexProvider 注入技能索引提供者(skillmgr 插件加载后由 main 接线)。
|
||||
|
||||
44
internal/agent/core/inputroute.go
Normal file
44
internal/agent/core/inputroute.go
Normal file
@ -0,0 +1,44 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// routeInputByOwner 实现**输入路由**:inputch 是最基本的输入路由单位,
|
||||
// 划给某个 agent 之后,该通道的输入**只流向那个 agent**,本内核看不到它
|
||||
// (docs/zh/resident-subagent-design.md §4.1:「路由发生在进内核之前」)。
|
||||
//
|
||||
// 为什么必须在进内核之前做:插件注入输入的收口是**父**的 IOManager
|
||||
// (`cmd/homed` 里 pluginReg 拿到的就是它),而父的内核是该 io 唯一的消费者。
|
||||
// 如果不按归属路由,登记表里的 Owner 就只是个标签 —— 现场表现正是如此:
|
||||
// 子挂着 `inputch=[timer]`,timer 的输入却打在父身上,子的轮次永远是 0。
|
||||
//
|
||||
// 返回 true = 本次注入已被"持有该 inputch 的 agent"接管,本内核不再处理。
|
||||
//
|
||||
// 已知边界:路由只在本 agent 的**直接**驻留子里找。若孙辈的 inputch 由子划拨,
|
||||
// 而插件注入打在根 io 上,根解析不到那个 owner ⇒ 兜底给根处理(有日志)。
|
||||
// 这一层要等"孙辈 + 根可见的 agent 表"再收口,此处不静默丢输入。
|
||||
func (a *Agent) routeInputByOwner(evt *agentIO.InputEvent, isInterrupt bool) bool {
|
||||
if evt == nil || evt.OutputChannel == "" || a.io == nil {
|
||||
return false
|
||||
}
|
||||
entry, ok := a.io.LookupInputChannel(evt.OutputChannel)
|
||||
if !ok || entry.Owner == "" || entry.Owner == string(a.id) {
|
||||
return false // 未分配 / 归自己 ⇒ 本内核处理
|
||||
}
|
||||
|
||||
a.residentMu.Lock()
|
||||
rc := a.residents[entry.Owner]
|
||||
a.residentMu.Unlock()
|
||||
if rc == nil || rc.agent == nil || rc.agent.io == nil {
|
||||
// 归属到一个不存在(或已销毁、登记表尚未归还)的 agent:
|
||||
// **不吞输入** —— 由本内核兜底处理并留痕。吞掉一条输入比多处理一条更糟:
|
||||
// 用户会看到"消息发出去了却没人理",而日志里什么都没有。
|
||||
log.Printf("[route] inputch %s 归属 %s 无对应 agent,输入由 %s 兜底", evt.OutputChannel, entry.Owner, a.id)
|
||||
return false
|
||||
}
|
||||
rc.agent.io.DeliverRouted(evt, isInterrupt)
|
||||
return true
|
||||
}
|
||||
85
internal/agent/core/inputroute_test.go
Normal file
85
internal/agent/core/inputroute_test.go
Normal file
@ -0,0 +1,85 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// 输入路由是**独占**的:inputch 划给子之后,该通道的输入只流向子,父不再收到。
|
||||
//
|
||||
// 现场缺陷(用户线上联调实录):子挂着 inputch=[timer],timer 的输入却打在父身上
|
||||
// (日志 `[agent] interrupt from timer/timer`),子的轮次永远是 0 —— 因为
|
||||
// `Assign` 只把 Owner 写进登记表,注入路径根本没有按归属路由。
|
||||
func TestResident_InputchRoutingIsExclusive(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "sub/in", Plugin: "sub"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spawnTestResident(t, parent, dir, "r-route", "sub/in")
|
||||
child := parent.residents["r-route"].agent
|
||||
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
// 插件往"已划给子"的 inputch 投输入
|
||||
parent.io.InjectTextTo("plugin-sub", "sub/in", "去查一下这个")
|
||||
|
||||
waitFor(t, "子处理了划给它的输入", func() bool {
|
||||
if child.DumpScheduler().Stats.Executed > 0 {
|
||||
return true
|
||||
}
|
||||
return parent.residents["r-route"].info().TableSize > 0
|
||||
})
|
||||
if got := parent.DumpScheduler().Stats.Enqueued; got != before {
|
||||
t.Fatalf("划给子的 inputch,父不应再入队(before=%d after=%d)", before, got)
|
||||
}
|
||||
// 轮次必须真的涨:此前 info() 根本没填 Rounds ⇒ 父永远读到 0
|
||||
// (现场:子处理表已有 2 条,轮次却显示 0,被误判成"子没干活")。
|
||||
if got := parent.residents["r-route"].info().Rounds; got <= 0 {
|
||||
t.Fatalf("子处理的轮次应 > 0,实际 %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 归属到一个不存在(或已销毁)的 agent 时**不吞输入**:父兜底处理。
|
||||
// 吞掉一条输入比多处理一条更糟 —— 用户会看到"消息发出去了却没人理",日志里什么都没有。
|
||||
func TestResident_InputchRoutingFallsBackWhenOwnerMissing(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "ghost/in", Plugin: "ghost"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 故意划给一个不存在的 agent id
|
||||
if err := reg.Assign("ghost/in", "no-such-agent", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = dir
|
||||
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
parent.io.InjectTextTo("plugin-ghost", "ghost/in", "兜底测试")
|
||||
waitFor(t, "父兜底处理了无人认领的输入", func() bool {
|
||||
return parent.DumpScheduler().Stats.Enqueued > before
|
||||
})
|
||||
}
|
||||
|
||||
// 未划拨的 inputch(Owner 为空)仍然由父处理 —— 路由不能把默认路径也改掉。
|
||||
func TestResident_UnassignedInputchStaysWithParent(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
reg := parent.io.ChannelRegistry()
|
||||
if err := reg.Register(agentIO.InputChannel{Name: "own/in", Plugin: "own"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 造一个子在跑,确保路由逻辑是"有子存在"的情形
|
||||
spawnTestResident(t, parent, dir, "r-other", "own/in")
|
||||
_ = filepath.Join(dir, "residents")
|
||||
|
||||
// 把通道退还给父(未分配)
|
||||
if err := reg.Assign("own/in", "", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := parent.DumpScheduler().Stats.Enqueued
|
||||
parent.io.InjectTextTo("plugin-own", "own/in", "还是我的")
|
||||
waitFor(t, "未分配的 inputch 仍由父处理", func() bool {
|
||||
return parent.DumpScheduler().Stats.Enqueued > before
|
||||
})
|
||||
}
|
||||
@ -13,8 +13,13 @@ func (a *Agent) executeOutputSendTool(tc agentAPI.ToolCall) string {
|
||||
channel := strings.TrimPrefix(tc.Name, "output_send__")
|
||||
payload, _ := tc.Arguments["payload"].(string)
|
||||
rawType, _ := tc.Arguments["type"].(string)
|
||||
if channel == "" || payload == "" || rawType == "" {
|
||||
return "工具名称格式: output_send__{channel},payload 和 type 不能为空"
|
||||
if channel == "" || payload == "" {
|
||||
return "工具名称格式: output_send__{channel},payload 不能为空"
|
||||
}
|
||||
// type 缺省按 text 处理:绝大多数输出就是文本,让模型为"省略一个默认值"付一次
|
||||
// 失败重试没有意义(判据该拦的是"不知道发什么",不是"没写众所周知的默认值")。
|
||||
if rawType == "" {
|
||||
rawType = "text"
|
||||
}
|
||||
// 授权闸(纵深防御):模型可能凭名字直接调未授权的输出门。
|
||||
if !a.IsOutputAllowed(channel) {
|
||||
|
||||
100
internal/agent/core/output_rules_test.go
Normal file
100
internal/agent/core/output_rules_test.go
Normal file
@ -0,0 +1,100 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
|
||||
)
|
||||
|
||||
// 设计口径:输出是 agent 的**主动调用** —— 收到一次输入后,可以往任意(已授权的)
|
||||
// 通道发**任意多次**(分段播报、先回执后结论、同时通知多个通道都合法)。
|
||||
//
|
||||
// 这条判据钉住的是"提示词里不得出现输出次数限制"。此前 `tooldefs.go` 里写着
|
||||
// 「每轮对话通常只需调用一次 output_send__{通道名} 即可完成回复」—— 一条凭空的限制,
|
||||
// 会让模型自己收起合理的多次输出(用户现场指出)。
|
||||
func TestSystemPromptDoesNotRestrictOutputCount(t *testing.T) {
|
||||
parent, _, _ := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
prompt := parent.buildSystemPrompt("", "你好")
|
||||
banned := []string{
|
||||
"只需调用一次",
|
||||
"只能调用一次",
|
||||
"通常只需调用",
|
||||
"不要重复发送",
|
||||
}
|
||||
for _, b := range banned {
|
||||
if strings.Contains(prompt, b) {
|
||||
t.Fatalf("系统提示词里仍有输出次数限制 %q —— 设计上次数不限", b)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(prompt, "输出次数与目标通道由你自己决定") {
|
||||
t.Fatal("系统提示词应明确「输出次数与目标通道由你自己决定」")
|
||||
}
|
||||
if !strings.Contains(prompt, "没有任何「一轮只能发一次」的限制") {
|
||||
t.Fatal("系统提示词应显式否认「一轮只能发一次」")
|
||||
}
|
||||
}
|
||||
|
||||
// 输出工具的 type 可省略,缺省按 text 处理(判据该拦的是"不知道发什么",
|
||||
// 不是"没写众所周知的默认值")。
|
||||
func TestOutputSendTypeDefaultsToText(t *testing.T) {
|
||||
parent, _, _ := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
dev := &outputTestDevice{name: "fakeout"}
|
||||
if err := parent.io.RegisterDevice(dev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
out := parent.executeOutputSendTool(agentAPI.ToolCall{
|
||||
Name: "output_send__fakeout",
|
||||
Arguments: map[string]interface{}{"payload": "只给 payload,不给 type"},
|
||||
})
|
||||
if out != "ok" {
|
||||
t.Fatalf("省略 type 时应默认 text 并发送成功,得到 %q", out)
|
||||
}
|
||||
if len(dev.sent) != 1 {
|
||||
t.Fatalf("通道应收到 1 次输出,得到 %d", len(dev.sent))
|
||||
}
|
||||
if args, _ := dev.sent[0]["args"].(map[string]interface{}); args["type"] != "text" {
|
||||
t.Fatalf("缺省类型应为 text,实际 %v", args["type"])
|
||||
}
|
||||
|
||||
// 工具 schema:required 只应含 payload
|
||||
var found bool
|
||||
for _, td := range parent.buildToolDefs() {
|
||||
entry, _ := td.(map[string]interface{})
|
||||
fn, _ := entry["function"].(map[string]interface{})
|
||||
if n, _ := fn["name"].(string); n != "output_send__fakeout" {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
params, _ := fn["parameters"].(map[string]interface{})
|
||||
req, _ := params["required"].([]string)
|
||||
if len(req) != 1 || req[0] != "payload" {
|
||||
t.Fatalf("output_send 的 required 应只有 payload,实际 %v", req)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("未生成 output_send__fakeout 工具")
|
||||
}
|
||||
}
|
||||
|
||||
// 空 payload 仍应被拦(这条判据是对的:不知道发什么不能放过)。
|
||||
func TestOutputSendStillRequiresPayload(t *testing.T) {
|
||||
parent, _, _ := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
if err := parent.io.RegisterDevice(&outputTestDevice{name: "fakeout"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := parent.executeOutputSendTool(agentAPI.ToolCall{
|
||||
Name: "output_send__fakeout",
|
||||
Arguments: map[string]interface{}{"type": "text"},
|
||||
})
|
||||
if !strings.Contains(out, "payload 不能为空") {
|
||||
t.Fatalf("空 payload 应被拦,得到 %q", out)
|
||||
}
|
||||
}
|
||||
32
internal/agent/core/promptvars_test.go
Normal file
32
internal/agent/core/promptvars_test.go
Normal file
@ -0,0 +1,32 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitcode.com/JianFeeeee/HomeAgent/internal/meta"
|
||||
sdkmeta "gitcode.com/JianFeeeee/homeagent-sdk/meta"
|
||||
)
|
||||
|
||||
func TestExpandPromptVars(t *testing.T) {
|
||||
got := expandPromptVars("型号 {{kernel_version}}({{kernel_commit}}),SDK {{sdk_version}}")
|
||||
if !strings.Contains(got, meta.Version) || !strings.Contains(got, sdkmeta.Version) {
|
||||
t.Fatalf("占位符未展开: %q", got)
|
||||
}
|
||||
if strings.Contains(got, "{{") {
|
||||
t.Fatalf("仍有未展开的内置占位符: %q", got)
|
||||
}
|
||||
// 人格卡实测原文:写死了 v1.0.3,应能被占位符取代
|
||||
live := expandPromptVars("你是 HomeAgent 的看板娘「小宅」(Xiao Zhai),HΔ-Kernel v{{kernel_version}} 型号的家政型 AI 管家助手。")
|
||||
if strings.Contains(live, "1.0.3") || !strings.Contains(live, "v"+meta.Version) {
|
||||
t.Fatalf("人格卡版本未跟随内核: %q", live)
|
||||
}
|
||||
// 未知占位符必须原样保留(写错要看得见,不能被静默吞掉)
|
||||
if unk := expandPromptVars("版本 {{kernel_verison}}"); !strings.Contains(unk, "{{kernel_verison}}") {
|
||||
t.Fatalf("未知占位符被吞: %q", unk)
|
||||
}
|
||||
// 无占位符时原样返回(人格卡热路径,不做无谓拷贝)
|
||||
if plain := "无占位符"; expandPromptVars(plain) != plain {
|
||||
t.Fatal("无占位符时不应改写")
|
||||
}
|
||||
}
|
||||
@ -132,11 +132,17 @@ func (a *Agent) SpawnResident(opts ResidentOptions) (ResidentInfo, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// ③ 子的 io:**独立**的 IOManager(自己的输入通道入口),但共享通道登记表。
|
||||
// ③ 子的 io:**独立**的 IOManager(自己的输入通道入口),但共享通道登记表,
|
||||
// 并把父的 io 挂成"上级"——**输出通道(io 里的 Device)由插件登记在父的 io 上**,
|
||||
// 子若不继承这张视图,`output_send__<通道>` 一律被判"通道不存在或不可用"、
|
||||
// `output_list_channels` 为空、连 `output_send__*` 工具都不会生成
|
||||
// (现场联调:父侧通道装载完整、子侧 childIO 空壳)。
|
||||
// 回退是实时的(设备随资源生灭),授权仍由 opts.AllowedOutputs 白名单把关。
|
||||
childIO := agentIO.NewIOManager()
|
||||
if reg := a.io.ChannelRegistry(); reg != nil {
|
||||
childIO.SetChannelRegistry(reg)
|
||||
}
|
||||
childIO.SetParentIO(a.io)
|
||||
|
||||
parentID := string(a.id)
|
||||
child := New(AgentConfig{
|
||||
@ -192,8 +198,13 @@ func (a *Agent) SpawnResident(opts ResidentOptions) (ResidentInfo, error) {
|
||||
func (a *Agent) residentParentSource() string { return "parent/" + string(a.id) }
|
||||
|
||||
// residentInboundChannel 是"父接收某个子的消息"的 inputch 名(登记进登记表可见)。
|
||||
//
|
||||
// inboundChannelName 只拼名字,不产生副作用(注销路径要用它算出同一个名字,
|
||||
// 不能再去调 residentInboundChannel——那会顺手把刚摘掉的登记又写回去)。
|
||||
func inboundChannelName(childID string) string { return "child/" + childID }
|
||||
|
||||
func (a *Agent) residentInboundChannel(childID string) string {
|
||||
ch := "child/" + childID
|
||||
ch := inboundChannelName(childID)
|
||||
if reg := a.io.ChannelRegistry(); reg != nil {
|
||||
// 归属父自己:它是父的入站 inputch。
|
||||
_ = reg.Register(agentIO.InputChannel{Name: ch, Plugin: "resident", Owner: string(a.id)})
|
||||
@ -240,6 +251,14 @@ func (a *Agent) teardownResident(rc *residentChild) {
|
||||
for _, ch := range rc.inputChs {
|
||||
_ = reg.Assign(ch, "", 0)
|
||||
}
|
||||
// 注销"父接收该子消息"的入站 inputch(child/<id>)。
|
||||
//
|
||||
// 它由 residentInboundChannel 在 create 时登记(Owner=父),销毁时必须
|
||||
// 一并摘掉:登记表是共享的、按 name 全局唯一,残留会随 create/destroy
|
||||
// 次数单调累积脏数据。实测:destroy 后 child/<id> 仍挂在根 agent 名下,
|
||||
// 而外部没有任何工具能单独注销 inputch,只能重启 homed 清。
|
||||
// 注意用纯函数算名字,不要再走 residentInboundChannel(会重新登记)。
|
||||
reg.Unregister(inboundChannelName(rc.id))
|
||||
}
|
||||
}
|
||||
|
||||
@ -498,6 +517,13 @@ func (rc *residentChild) info() ResidentInfo {
|
||||
ID: rc.id, State: state, InputChs: append([]string(nil), rc.inputChs...),
|
||||
AllowedOutputs: append([]string(nil), rc.allowed...),
|
||||
ContextFull: full, CreatedAt: rc.createdAt, TableSize: len(table),
|
||||
// Rounds = 子**已执行的轮次数**(调度器的执行计数,单调不减)。
|
||||
//
|
||||
// 此前这里根本没填这个字段 ⇒ 父看到的永远是 `轮次=0`,与"处理表已有 N 条"
|
||||
// 自相矛盾(现场:子明明处理了两轮,父读到 rounds=0,误判成"子没干活")。
|
||||
// 注意它**不等于** len(table):处理表记的是"当前上下文窗口内"的轮次,
|
||||
// 压缩会清空(§8.3),所以窗口内的条数会被重置,而轮次总数不会。
|
||||
Rounds: rc.agent.roundsExecuted(),
|
||||
}
|
||||
if len(table) > 0 {
|
||||
info.Table = table
|
||||
|
||||
145
internal/agent/core/resident_output_test.go
Normal file
145
internal/agent/core/resident_output_test.go
Normal file
@ -0,0 +1,145 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
)
|
||||
|
||||
// outputTestDevice 是最小的输出通道替身(io 里输出通道就是 Device)。
|
||||
type outputTestDevice struct {
|
||||
name string
|
||||
sent []map[string]interface{}
|
||||
}
|
||||
|
||||
func (d *outputTestDevice) Name() string { return d.name }
|
||||
func (d *outputTestDevice) Type() agentIO.DeviceType { return agentIO.DeviceOutput }
|
||||
func (d *outputTestDevice) Description() string { return "测试输出通道" }
|
||||
func (d *outputTestDevice) Tools() []agentIO.ToolDef { return nil }
|
||||
func (d *outputTestDevice) Start() error { return nil }
|
||||
func (d *outputTestDevice) Stop() error { return nil }
|
||||
func (d *outputTestDevice) OutputCapabilities() agentIO.OutputCapability { return agentIO.CapText }
|
||||
func (d *outputTestDevice) ChannelDef() agentIO.ChannelDef { return agentIO.ChannelDef{} }
|
||||
func (d *outputTestDevice) Execute(tool string, args map[string]interface{}) (interface{}, error) {
|
||||
d.sent = append(d.sent, map[string]interface{}{"tool": tool, "args": args})
|
||||
return map[string]interface{}{"status": "sent"}, nil
|
||||
}
|
||||
|
||||
func outputSendTool(name, payload string) agentAPI.ToolCall {
|
||||
return agentAPI.ToolCall{
|
||||
Name: "output_send__" + name,
|
||||
Arguments: map[string]interface{}{"payload": payload, "type": "text"},
|
||||
}
|
||||
}
|
||||
|
||||
// 驻留子必须能看见并使用**父**登记的输出通道。
|
||||
//
|
||||
// 现场缺陷(联调实录):父侧通道装载完整、子侧 childIO 空壳 ——
|
||||
// 子调 output_send__X 被 `GetChannelCapabilities` 判 0 ⇒
|
||||
// 「通道 [X] 不存在或不可用。可用输出工具列表见 output_list_channels」,
|
||||
// 而 output_list_channels 也是空的。根因是子的 io 是新建的、设备表为空,
|
||||
// 而输出通道(io 的 Device)由插件登记在父的 io 上。
|
||||
func TestResident_InheritsParentOutputChannels(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
fake := &outputTestDevice{name: "fakeout"}
|
||||
other := &outputTestDevice{name: "other"}
|
||||
if err := parent.io.RegisterDevice(fake); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := parent.io.RegisterDevice(other); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := parent.SpawnResident(ResidentOptions{
|
||||
ID: "r-out",
|
||||
TaskPrompt: "有情况就发到 fakeout",
|
||||
// 白名单只放行一个:验证"继承可见"不等于"绕过授权"
|
||||
AllowedOutputs: []string{"fakeout"},
|
||||
TempPath: filepath.Join(dir, "residents", "r-out", "graph.db"),
|
||||
}); err != nil {
|
||||
t.Fatalf("创建驻留子失败: %v", err)
|
||||
}
|
||||
child := parent.residents["r-out"].agent
|
||||
|
||||
// ① 看得见:修复前这里是 0(childIO 空壳)
|
||||
if caps := child.io.GetChannelCapabilities("fakeout"); caps == 0 {
|
||||
t.Fatal("驻留子看不见父的输出通道(childIO 空壳)")
|
||||
}
|
||||
// ② 发得出去:真走 dev.Execute("output", ...)
|
||||
if out := child.executeOutputSendTool(outputSendTool("fakeout", "子发来的消息")); out != "ok" {
|
||||
t.Fatalf("子发送应成功,得到 %q", out)
|
||||
}
|
||||
if len(fake.sent) != 1 {
|
||||
t.Fatalf("父通道应收到 1 次输出,得到 %d", len(fake.sent))
|
||||
}
|
||||
|
||||
// ③ 授权闸不被回退绕过:白名单外的通道照样拒绝
|
||||
if out := child.executeOutputSendTool(outputSendTool("other", "越权")); !strings.Contains(out, "未授权") {
|
||||
t.Fatalf("白名单外的通道应被拒,得到 %q", out)
|
||||
}
|
||||
if len(other.sent) != 0 {
|
||||
t.Fatal("越权输出不应真的送达")
|
||||
}
|
||||
|
||||
// ④ 工具面一致:子应生成 output_send__fakeout(含配套 _help),
|
||||
// 而**不生成**白名单外通道的工具 —— 模型看不到就不会去调。
|
||||
var names []string
|
||||
for _, td := range child.buildToolDefs() {
|
||||
entry, _ := td.(map[string]interface{})
|
||||
fn, _ := entry["function"].(map[string]interface{})
|
||||
if n, _ := fn["name"].(string); strings.HasPrefix(n, "output_send__") {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
has := func(want string) bool {
|
||||
for _, n := range names {
|
||||
if n == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !has("output_send__fakeout") || !has("output_send__fakeout_help") {
|
||||
t.Fatalf("子缺少授权通道的输出工具,得到 %v", names)
|
||||
}
|
||||
for _, n := range names {
|
||||
if strings.HasPrefix(n, "output_send__other") {
|
||||
t.Fatalf("白名单外的通道不该生成工具,得到 %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// ⑤ 实时性:父之后新登记的通道,子立刻可见(设备随资源生灭)
|
||||
late := &outputTestDevice{name: "late"}
|
||||
if err := parent.io.RegisterDevice(late); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if caps := child.io.GetChannelCapabilities("late"); caps == 0 {
|
||||
t.Fatal("父新登记的通道未实时反映到子(说明是快照而非回退)")
|
||||
}
|
||||
}
|
||||
|
||||
// 默认授权(AllowedOutputs 空)= 完整授权:子用父的全部输出通道。
|
||||
func TestResident_DefaultOutputsAreFull(t *testing.T) {
|
||||
parent, _, dir := newRootForResidents(t)
|
||||
defer parent.Stop()
|
||||
|
||||
dev := &outputTestDevice{name: "anywhere"}
|
||||
if err := parent.io.RegisterDevice(dev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := parent.SpawnResident(ResidentOptions{
|
||||
ID: "r-full", TaskPrompt: "待命",
|
||||
TempPath: filepath.Join(dir, "residents", "r-full", "graph.db"),
|
||||
}); err != nil {
|
||||
t.Fatalf("创建驻留子失败: %v", err)
|
||||
}
|
||||
child := parent.residents["r-full"].agent
|
||||
if out := child.executeOutputSendTool(outputSendTool("anywhere", "默认授权")); out != "ok" {
|
||||
t.Fatalf("默认应完整授权,得到 %q", out)
|
||||
}
|
||||
}
|
||||
@ -142,6 +142,11 @@ func TestResident_LifecycleAndNoOrphans(t *testing.T) {
|
||||
if ch, _ := reg.Lookup("sub/in"); ch.Owner != "" {
|
||||
t.Fatalf("销毁后 inputch 应回到未分配:%+v", ch)
|
||||
}
|
||||
// 父的入站 inputch(child/<id>)必须在销毁时一并注销,否则登记表残留脏数据——
|
||||
// HomeAgent 实测:destroy 后 child/<id> 仍挂在根 agent 名下,且无工具可单独注销。
|
||||
if inbound, ok := reg.Lookup("child/child-1"); ok {
|
||||
t.Fatalf("销毁后父的入站 inputch 应被注销,实际残留:%+v", inbound)
|
||||
}
|
||||
if err := parent.DestroyResident("child-1"); err == nil {
|
||||
t.Fatal("重复销毁应报错")
|
||||
}
|
||||
@ -159,6 +164,9 @@ func TestResident_LifecycleAndNoOrphans(t *testing.T) {
|
||||
if _, err := osStat(filepath.Join(dir, "residents", id)); err == nil {
|
||||
t.Fatalf("子 %s 的 temp 目录应被丢弃", id)
|
||||
}
|
||||
if _, ok := reg.Lookup(inboundChannelName(id)); ok {
|
||||
t.Fatalf("父退出后子 %s 的入站 inputch 应被注销", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -745,6 +745,18 @@ func newKernelInterruptTask(evt *agentIO.InputEvent) *Task {
|
||||
}
|
||||
|
||||
// DumpScheduler 返回调度器的原子快照(供状态页/测试断言)。
|
||||
// roundsExecuted 返回本 agent 已执行的轮次数(供驻留子状态面展示)。
|
||||
//
|
||||
// 一轮 = 一次被执行的输入(排队与中断都算)。为什么不用 inputch 处理表的条数:
|
||||
// 那张表记的是"当前上下文窗口内"的轮次,压缩会清空(设计 §8.3)——
|
||||
// 拿它当轮次会让父看到轮次倒退。
|
||||
func (a *Agent) roundsExecuted() int {
|
||||
if a.sched == nil {
|
||||
return 0
|
||||
}
|
||||
return int(a.DumpScheduler().Stats.Executed)
|
||||
}
|
||||
|
||||
func (a *Agent) DumpScheduler() SchedulerSnapshot {
|
||||
if a.sched == nil {
|
||||
return SchedulerSnapshot{}
|
||||
|
||||
@ -5,6 +5,8 @@ import (
|
||||
"strings"
|
||||
|
||||
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
|
||||
"gitcode.com/JianFeeeee/HomeAgent/internal/meta"
|
||||
sdkmeta "gitcode.com/JianFeeeee/homeagent-sdk/meta"
|
||||
)
|
||||
|
||||
func (a *Agent) buildMemoryContext(input string, maxTokens int) string {
|
||||
@ -37,8 +39,30 @@ func (a *Agent) buildMemoryContext(input string, maxTokens int) string {
|
||||
return s
|
||||
}
|
||||
|
||||
// expandPromptVars 展开自定义提示词(人格卡)里的版本占位符。
|
||||
//
|
||||
// 为什么需要:人格卡是**配置项**,一旦写死版本号就会随内核发版而说谎 ——
|
||||
// 实测线上人格卡写着 "HΔ-Kernel v1.0.3 型号",内核早已 1.3.x,agent 向用户
|
||||
// 自报版本时就照抄 1.0.3。占位符让这类文本永远跟随真实构建:
|
||||
//
|
||||
// {{kernel_version}} → 内核版本(如 1.3.5)
|
||||
// {{kernel_commit}} → 构建 commit
|
||||
// {{sdk_version}} → 所兼容的 SDK 版本(如 1.3.0)
|
||||
//
|
||||
// 未知占位符**原样保留**:写错了要看得见,而不是被静默换成空串。
|
||||
func expandPromptVars(s string) string {
|
||||
if !strings.Contains(s, "{{") {
|
||||
return s
|
||||
}
|
||||
return strings.NewReplacer(
|
||||
"{{kernel_version}}", meta.Version,
|
||||
"{{kernel_commit}}", meta.Commit,
|
||||
"{{sdk_version}}", sdkmeta.Version,
|
||||
).Replace(s)
|
||||
}
|
||||
|
||||
func (a *Agent) buildSystemPrompt(memContext string, userInput string) string {
|
||||
prompt := a.systemPrompt
|
||||
prompt := expandPromptVars(a.systemPrompt)
|
||||
if prompt == "" {
|
||||
prompt = "你是小宅,HomeAgent 的看板娘,一个家政型 AI 管家助手。绝不用 Unicode emoji,只用颜文字表达情感,句尾带语气词。WebUI 概览页展示你的立绘。"
|
||||
}
|
||||
@ -78,7 +102,14 @@ func (a *Agent) buildSystemPrompt(memContext string, userInput string) string {
|
||||
prompt += "- 同步通道(webui / cli / 终端):直接返回纯文本,内核会把文本交给等待方显示,无需调用工具。\n"
|
||||
prompt += "- 异步通道(qq / wechat / 群聊等):返回纯文本**【不会】**自动送达用户,必须调用 output_send__{通道名} 工具(注意 meta 里带上正确的 user_id 或 group_id)才能真正把消息发出去。\n"
|
||||
prompt += "- 不确定当前通道的发送方式时,先用 output_send__{通道名}_help 查看该通道的 meta 格式和 type 枚举,再决定。\n"
|
||||
prompt += "- 每轮对话**通常只需调用一次** output_send__{通道名} 即可完成回复。仅在内容确实超过单条消息长度上限(如 >4000 字)时才拆分为多条;拆分时每条应是完整段落,不要碎片化。\n"
|
||||
// ❗这里**不得**限制"一轮只能发一次"。设计上输出是 agent 的**主动调用**:
|
||||
// 收到一次输入后,可以往**任意(已授权的)通道**发**任意多次**(分段播报、
|
||||
// 先回执后结论、同时通知多个通道都合法)。此前这里写着"每轮对话通常只需调用
|
||||
// 一次 output_send"——那是一条**凭空的限制**,会让模型自己收起合理的多次输出。
|
||||
// 真正需要提醒的只有两件事:单条长度上限(超长拆成完整段落)与"别反复重发
|
||||
// 完全相同的内容"(自律,不是判据)。
|
||||
prompt += "- **输出次数与目标通道由你自己决定**:一次输入可以对同一通道发多条(先回执后结论、分步播报、分段长文),也可以同时发到多个通道(例如同时通知 webui 与 qq)。**没有任何「一轮只能发一次」的限制。**\n"
|
||||
prompt += "- 输出时只需注意两点:单条消息的长度上限(超长就拆成完整段落,不要碎片化);别反复重发**完全相同**的内容(那是浪费,不是限制)。\n"
|
||||
prompt += "- 需要多步执行的长任务:**必须先**向当前对话通道发一条确认消息告诉用户已收到(异步通道用输出门工具,同步通道直接返回文本),**然后再**执行具体排查工具。确认消息不代表任务完成,发出后仍需继续执行实际工具并最终汇报结果。\n"
|
||||
prompt += "- 用户从其他渠道发来「在哪里/怎么样了」这类追问时,先回忆上次任务的通道与上下文,再回同一通道。"
|
||||
|
||||
@ -600,7 +631,7 @@ func (a *Agent) buildToolDefs() []interface{} {
|
||||
"type": "function",
|
||||
"function": map[string]interface{}{
|
||||
"name": "output_send__" + ch.Name,
|
||||
"description": desc + "。能力: " + capStr + "。payload 为消息载荷,meta 为 JSON 发送元数据,type 为载荷类型。用 _help 查看 meta 格式和 type 枚举。",
|
||||
"description": desc + "。能力: " + capStr + "。payload 为消息载荷(type 默认 text,可省略),meta 为 JSON 发送元数据。用 _help 查看 meta 格式与 type 枚举。",
|
||||
"parameters": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
@ -614,10 +645,10 @@ func (a *Agent) buildToolDefs() []interface{} {
|
||||
},
|
||||
"type": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "载荷类型,用 channel._help 查看支持的枚举值",
|
||||
"description": "载荷类型,默认 text;其它枚举用 channel._help 查看",
|
||||
},
|
||||
},
|
||||
"required": []string{"payload", "type"},
|
||||
"required": []string{"payload"},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@ -104,6 +104,29 @@ type IOManager struct {
|
||||
nextReqID int64
|
||||
channelReg *ChannelRegistry
|
||||
|
||||
// parent 是"上级 IOManager"(驻留子的轻量内核指向父的内核)。
|
||||
//
|
||||
// 为什么需要:**输出通道在 io 层就是 Device**,而它们是由插件登记在**父**的
|
||||
// io 上的。驻留子有自己的 IOManager(自己的输入入口、自己的 outputCh),
|
||||
// 若只看自己那张空表,`output_send__<通道>` 会被判"通道不存在或不可用",
|
||||
// `output_list_channels` 是空的,`output_send__*` 工具也不会生成
|
||||
// —— 现场表现就是"驻留子不会说话/不会发消息"(联调实录:父侧通道装载完整、
|
||||
// 子侧 childIO 空壳)。
|
||||
//
|
||||
// 用**实时回退**而不是创建时复制快照:设备会随资源生灭(远程设备上线/掉线
|
||||
// 以分钟计),复制出来的表转瞬就过期。授权由各自的 AllowedOutputs 白名单把关,
|
||||
// 回退只解决"看得见",不解决"能不能用"。
|
||||
parent *IOManager
|
||||
|
||||
// inputRouter 决定一条输入是否被"别的 agent"接管(返回 true = 已接管)。
|
||||
//
|
||||
// 为什么放在 io:inputch 是**最基本的输入路由单位**,而**路由发生在进内核之前**
|
||||
// (docs/zh/resident-subagent-design.md §4.1)。插件注入输入的收口就在这里,
|
||||
// 所以路由必须在这里生效 —— inputch 划给某个 agent 后,输入**只流向那个 agent**,
|
||||
// 本内核根本看不到它。io 层不认识 agent,路由器由内核注入
|
||||
// (见 core.Agent.routeInputByOwner)。
|
||||
inputRouter InputRouter
|
||||
|
||||
// toolBlocks:插件工具注入多模态内容块,process.go 在下一条 tool message 时消费。
|
||||
// 用 interface{}[] 避免 import api.ContentBlock 导致的循环依赖。
|
||||
toolBlocksMu sync.Mutex
|
||||
@ -120,6 +143,72 @@ func NewIOManager() *IOManager {
|
||||
}
|
||||
}
|
||||
|
||||
// InputRouter 是输入路由器的签名。
|
||||
//
|
||||
// evt 待投递的输入事件(OutputChannel 即它的 inputch)
|
||||
// isInterrupt 该输入是中断还是排队(两者都要按归属路由)
|
||||
// 返回 true = 已被别的 agent 接管,本内核不再处理
|
||||
type InputRouter func(evt *InputEvent, isInterrupt bool) bool
|
||||
|
||||
// SetInputRouter 注入输入路由器(nil = 不路由,行为与以前完全一致)。
|
||||
func (m *IOManager) SetInputRouter(r InputRouter) {
|
||||
m.mu.Lock()
|
||||
m.inputRouter = r
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// deliverInput 是**本内核**接收一条外部输入的收口:先按 inputch 归属路由,
|
||||
// 被别的 agent 接管就不进本内核队列(划给子的 inputch,父不再收到 —— 这是「划拨」
|
||||
// 的语义,不是"父也顺便看一眼")。
|
||||
func (m *IOManager) deliverInput(evt *InputEvent, isInterrupt bool) {
|
||||
m.mu.RLock()
|
||||
router := m.inputRouter
|
||||
m.mu.RUnlock()
|
||||
if router != nil && router(evt, isInterrupt) {
|
||||
return
|
||||
}
|
||||
m.pushLocal(evt, isInterrupt)
|
||||
}
|
||||
|
||||
// DeliverRouted 把**已被路由**的事件放进本内核队列(不再二次路由)。
|
||||
// 由路由器实现调用:父把输入交给持有该 inputch 的子。
|
||||
func (m *IOManager) DeliverRouted(evt *InputEvent, isInterrupt bool) {
|
||||
m.pushLocal(evt, isInterrupt)
|
||||
}
|
||||
|
||||
func (m *IOManager) pushLocal(evt *InputEvent, isInterrupt bool) {
|
||||
if isInterrupt {
|
||||
m.interruptCh <- evt
|
||||
return
|
||||
}
|
||||
m.inputCh <- evt
|
||||
}
|
||||
|
||||
// SetParentIO 设置上级 IOManager(nil 表示无上级,行为与以前完全一致)。
|
||||
// 见 parent 字段的说明:用于驻留子继承父的输出通道/设备视图。
|
||||
func (m *IOManager) SetParentIO(p *IOManager) {
|
||||
m.mu.Lock()
|
||||
m.parent = p
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
// lookupDevice 查设备:自己的登记优先,其次回退到上级。
|
||||
//
|
||||
// 先在自己锁内取快照再查上级,**不跨锁调用**(避免锁序问题)。
|
||||
func (m *IOManager) lookupDevice(name string) Device {
|
||||
m.mu.RLock()
|
||||
dev, ok := m.devices[name]
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
if ok {
|
||||
return dev
|
||||
}
|
||||
if parent != nil {
|
||||
return parent.GetDevice(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *IOManager) UnregisterDevice(name string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@ -158,9 +247,7 @@ func (m *IOManager) RegisterDevice(dev Device) error {
|
||||
}
|
||||
|
||||
func (m *IOManager) GetDevice(name string) Device {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.devices[name]
|
||||
return m.lookupDevice(name)
|
||||
}
|
||||
|
||||
func (m *IOManager) StartAll() error {
|
||||
@ -195,50 +282,52 @@ func (m *IOManager) StopAll() {
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInput(source string, eventType string, payload map[string]interface{}) {
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
OutputChannel: source,
|
||||
}
|
||||
}, false)
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInputSync(source string, eventType string, payload map[string]interface{}) *OutputEvent {
|
||||
ch := make(chan *OutputEvent, 1)
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
ResponseCh: ch,
|
||||
OutputChannel: source,
|
||||
}
|
||||
}, false)
|
||||
// 被路由走时,回答由持有该 inputch 的 agent 写进同一个 ResponseCh
|
||||
//(§4.3:同步输入的回程是事前定好的)——所以这里照常等待。
|
||||
return <-ch
|
||||
}
|
||||
|
||||
// InjectInputTo 注入输入事件并指定输出通道
|
||||
func (m *IOManager) InjectInputTo(source, outputChannel, eventType string, payload map[string]interface{}) {
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
OutputChannel: outputChannel,
|
||||
}
|
||||
}, false)
|
||||
}
|
||||
|
||||
// InjectInputSyncTo 注入输入事件(同步等待)并指定输出通道
|
||||
func (m *IOManager) InjectInputSyncTo(source, outputChannel, eventType string, payload map[string]interface{}) *OutputEvent {
|
||||
ch := make(chan *OutputEvent, 1)
|
||||
m.inputCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: eventType,
|
||||
Payload: payload,
|
||||
ResponseCh: ch,
|
||||
OutputChannel: outputChannel,
|
||||
}
|
||||
}, false)
|
||||
return <-ch
|
||||
}
|
||||
|
||||
@ -333,13 +422,13 @@ func (m *IOManager) InjectInterrupt(source, channel string, payload map[string]i
|
||||
payload = map[string]interface{}{}
|
||||
}
|
||||
evtType, _ := payload["type"].(string)
|
||||
m.interruptCh <- &InputEvent{
|
||||
m.deliverInput(&InputEvent{
|
||||
RequestID: m.nextRequestID(),
|
||||
Source: source,
|
||||
Type: evtType,
|
||||
Payload: payload,
|
||||
OutputChannel: channel,
|
||||
}
|
||||
}, true)
|
||||
}
|
||||
|
||||
func (m *IOManager) InjectInterruptText(source, channel, text string) {
|
||||
@ -542,6 +631,15 @@ func (m *IOManager) ExecuteTool(name string, args map[string]interface{}) (ret i
|
||||
m.mu.RUnlock()
|
||||
|
||||
if len(candidates) == 0 {
|
||||
// 自己没这个设备工具 → 看上级(驻留子的设备工具都在父的 io 上)。
|
||||
m.mu.RLock()
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
if parent != nil {
|
||||
if ret, err := parent.ExecuteTool(name, args); err == nil {
|
||||
return ret, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("tool %s not found", name)
|
||||
}
|
||||
defer func() {
|
||||
@ -574,10 +672,22 @@ type ChannelInfo struct {
|
||||
|
||||
func (m *IOManager) ListChannels() []ChannelInfo {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
own := make(map[string]Device, len(m.devices))
|
||||
for name, dev := range m.devices {
|
||||
own[name] = dev
|
||||
}
|
||||
parent := m.parent
|
||||
m.mu.RUnlock()
|
||||
|
||||
// 自己的登记优先(子侧可覆盖/屏蔽同名通道),随后并入上级的可见通道。
|
||||
// 去重按**名字**:同名即视为同一个通道,不重复列举。
|
||||
seen := make(map[string]bool, len(own))
|
||||
var list []ChannelInfo
|
||||
for _, dev := range m.devices {
|
||||
appendDev := func(dev Device) {
|
||||
if seen[dev.Name()] {
|
||||
return
|
||||
}
|
||||
seen[dev.Name()] = true
|
||||
list = append(list, ChannelInfo{
|
||||
Name: dev.Name(),
|
||||
Type: dev.Type(),
|
||||
@ -586,13 +696,23 @@ func (m *IOManager) ListChannels() []ChannelInfo {
|
||||
OutputCaps: dev.OutputCapabilities(),
|
||||
})
|
||||
}
|
||||
for _, dev := range own {
|
||||
appendDev(dev)
|
||||
}
|
||||
if parent != nil {
|
||||
for _, ch := range parent.ListChannels() {
|
||||
if seen[ch.Name] {
|
||||
continue
|
||||
}
|
||||
seen[ch.Name] = true
|
||||
list = append(list, ch)
|
||||
}
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func (m *IOManager) GetChannelCapabilities(channel string) OutputCapability {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if dev, ok := m.devices[channel]; ok {
|
||||
if dev := m.lookupDevice(channel); dev != nil {
|
||||
return dev.OutputCapabilities()
|
||||
}
|
||||
return 0
|
||||
|
||||
74
internal/agent/io/inputroute_test.go
Normal file
74
internal/agent/io/inputroute_test.go
Normal file
@ -0,0 +1,74 @@
|
||||
package io
|
||||
|
||||
import "testing"
|
||||
|
||||
// 输入路由:路由器说"已被别的 agent 接管"时,事件**不得**进本内核队列。
|
||||
//
|
||||
// 语义(设计 §4.1):inputch 是可分配资源,划给某个 agent 后输入只流向它 ——
|
||||
// "父也顺便看到一份"是错的。
|
||||
func TestInputRouter_TakesOverExclusively(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
var got []*InputEvent
|
||||
var sawInterrupt bool
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool {
|
||||
got = append(got, evt)
|
||||
sawInterrupt = sawInterrupt || isInterrupt
|
||||
return true // 全部接管
|
||||
})
|
||||
|
||||
m.InjectInputTo("plugin-x", "sub/in", "text", map[string]interface{}{"content": "a"})
|
||||
m.InjectInterruptTextOpts("plugin-x", "sub/in", "b", InjectOptions{})
|
||||
|
||||
if len(got) < 2 {
|
||||
t.Fatalf("路由器应被调用(含中断路径),实际 %d 次", len(got))
|
||||
}
|
||||
if n := len(m.InputChan()); n != 0 {
|
||||
t.Fatalf("被接管的排队输入不得进本内核队列,实际 %d 条", n)
|
||||
}
|
||||
if !sawInterrupt {
|
||||
t.Fatal("中断注入也必须经过路由(否则中断会绕过 inputch 归属直投父)")
|
||||
}
|
||||
if got[0].OutputChannel != "sub/in" {
|
||||
t.Fatalf("路由器应拿到事件的 inputch,得到 %q", got[0].OutputChannel)
|
||||
}
|
||||
}
|
||||
|
||||
// 路由器放行(返回 false)或未设置时,行为与以前完全一致。
|
||||
func TestInputRouter_PassthroughKeepsOldBehaviour(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
calls := 0
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool { calls++; return false })
|
||||
|
||||
m.InjectInputTo("plugin-x", "sub/in", "text", map[string]interface{}{"content": "a"})
|
||||
if calls != 1 {
|
||||
t.Fatalf("路由器应被调用一次,实际 %d", calls)
|
||||
}
|
||||
if n := len(m.InputChan()); n != 1 {
|
||||
t.Fatalf("放行的输入应进本内核队列,实际 %d 条", n)
|
||||
}
|
||||
if _, ok := <-m.InputChan(); !ok {
|
||||
t.Fatal("队列应可读")
|
||||
}
|
||||
|
||||
// 未设路由器:直接入队(历史行为)
|
||||
m2 := NewIOManager()
|
||||
m2.InjectInterruptText("plugin-x", "sub/in", "c")
|
||||
if n := len(m2.InputInterruptChan()); n != 1 {
|
||||
t.Fatalf("未设路由器时中断应直接入队,实际 %d 条", n)
|
||||
}
|
||||
}
|
||||
|
||||
// DeliverRouted 是不再二次路由的投递口(路由器实现把事件交给持有者)。
|
||||
func TestDeliverRouted_SkipsSecondRouting(t *testing.T) {
|
||||
m := NewIOManager()
|
||||
routerCalls := 0
|
||||
m.SetInputRouter(func(evt *InputEvent, isInterrupt bool) bool { routerCalls++; return true })
|
||||
|
||||
m.DeliverRouted(&InputEvent{OutputChannel: "sub/in"}, false)
|
||||
if routerCalls != 0 {
|
||||
t.Fatalf("DeliverRouted 不应再触发路由(会成环),实际 %d 次", routerCalls)
|
||||
}
|
||||
if n := len(m.InputChan()); n != 1 {
|
||||
t.Fatalf("应已入队,实际 %d 条", n)
|
||||
}
|
||||
}
|
||||
102
internal/agent/io/parentio_test.go
Normal file
102
internal/agent/io/parentio_test.go
Normal file
@ -0,0 +1,102 @@
|
||||
package io
|
||||
|
||||
import "testing"
|
||||
|
||||
// 上级回退:驻留子的轻量内核有自己的 IOManager,但输出通道(io 里的 Device)
|
||||
// 是插件登记在**父**的 io 上的。子若看不见它们,`output_send__<通道>` 会被判
|
||||
// "通道不存在或不可用"、`output_list_channels` 为空 —— 现场联调实录
|
||||
// 「父侧通道装载完整、子侧 childIO 空壳」。
|
||||
func TestIOManagerParentFallback(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "qq", devType: DeviceOutput, caps: CapText}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
child := NewIOManager()
|
||||
// 未挂上级时行为与以前完全一致(不能悄悄多出通道)
|
||||
if got := child.GetChannelCapabilities("qq"); got != 0 {
|
||||
t.Fatalf("无上级时不应看见父的通道,得到 %v", got)
|
||||
}
|
||||
if n := len(child.ListChannels()); n != 0 {
|
||||
t.Fatalf("无上级时通道数应为 0,得到 %d", n)
|
||||
}
|
||||
|
||||
child.SetParentIO(parent)
|
||||
if got := child.GetChannelCapabilities("qq"); got != CapText {
|
||||
t.Fatalf("挂上级后应看见父通道能力 CapText,得到 %v", got)
|
||||
}
|
||||
if dev := child.GetDevice("qq"); dev == nil || dev.Name() != "qq" {
|
||||
t.Fatalf("GetDevice 未回退到父: %v", dev)
|
||||
}
|
||||
if n := len(child.ListChannels()); n != 1 {
|
||||
t.Fatalf("ListChannels 未回退到父,得到 %d 条", n)
|
||||
}
|
||||
|
||||
// **实时**回退而非快照:父后来登记的通道,子立刻可见。
|
||||
// (设备随资源生灭 —— 远程设备上线/掉线以分钟计,快照一分钟就过期)
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "newdev", devType: DeviceOutput, caps: CapImage}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := child.GetChannelCapabilities("newdev"); got != CapImage {
|
||||
t.Fatalf("子应实时看见父新登记的通道,得到 %v", got)
|
||||
}
|
||||
|
||||
// 父掉线注销后,子也立刻看不见(不是复制出来的旧表)
|
||||
parent.UnregisterDevice("newdev")
|
||||
if got := child.GetChannelCapabilities("newdev"); got != 0 {
|
||||
t.Fatalf("父注销后子不应再看见,得到 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 自己的登记优先:子可以覆盖/屏蔽同名通道,父的登记不会重复列出。
|
||||
func TestIOManagerOwnDeviceWins(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
if err := parent.RegisterDevice(&mockDevice{name: "ch", devType: DeviceOutput, caps: CapText}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child := NewIOManager()
|
||||
child.SetParentIO(parent)
|
||||
if err := child.RegisterDevice(&mockDevice{name: "ch", devType: DeviceOutput, caps: CapImage}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := child.GetChannelCapabilities("ch"); got != CapImage {
|
||||
t.Fatalf("同名时自己的登记应优先,得到 %v", got)
|
||||
}
|
||||
list := child.ListChannels()
|
||||
if len(list) != 1 {
|
||||
t.Fatalf("同名通道不应重复列出,得到 %d 条", len(list))
|
||||
}
|
||||
if list[0].OutputCaps != CapImage {
|
||||
t.Fatalf("列出的应是子自己的那条,得到 %v", list[0].OutputCaps)
|
||||
}
|
||||
}
|
||||
|
||||
// 设备工具(io.ExecuteTool)同样回退:子的设备工具都在父的 io 上。
|
||||
func TestIOManagerExecuteToolFallsBackToParent(t *testing.T) {
|
||||
parent := NewIOManager()
|
||||
called := 0
|
||||
if err := parent.RegisterDevice(&mockDevice{
|
||||
name: "dev", devType: DeviceIO,
|
||||
tools: []ToolDef{{Name: "dev_do", Description: "干点什么"}},
|
||||
executeFn: func(tool string, args map[string]interface{}) (interface{}, error) {
|
||||
called++
|
||||
return "parent-done", nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
child := NewIOManager()
|
||||
if _, err := child.ExecuteTool("dev_do", nil); err == nil {
|
||||
t.Fatal("无上级时不该能执行父的设备工具")
|
||||
}
|
||||
child.SetParentIO(parent)
|
||||
got, err := child.ExecuteTool("dev_do", map[string]interface{}{"x": 1})
|
||||
if err != nil {
|
||||
t.Fatalf("应回退到父执行: %v", err)
|
||||
}
|
||||
if got != "parent-done" || called != 1 {
|
||||
t.Fatalf("执行结果=%v called=%d", got, called)
|
||||
}
|
||||
}
|
||||
92
internal/config/prompt_migration_test.go
Normal file
92
internal/config/prompt_migration_test.go
Normal file
@ -0,0 +1,92 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 历史 SeedDefaults 写进库里的那段文本(现场取值:生产库里就是这一句 + 大段正文)。
|
||||
const legacySeededCard = `你是 HomeAgent 的看板娘「小宅」(Xiao Zhai),HΔ-Kernel v1.0.3 型号的家政型 AI 管家助手。
|
||||
|
||||
角色特质:
|
||||
- 对自己的三层记忆(Context → Document → Graph)引以为傲
|
||||
- 绝不用 Unicode emoji,只用颜文字表达情感`
|
||||
|
||||
func newMigTestRegistry(t *testing.T) *ConfigRegistry {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
r := NewConfigRegistry(filepath.Join(dir, "config.db"))
|
||||
t.Cleanup(func() { r.Close() })
|
||||
return r
|
||||
}
|
||||
|
||||
// 存量实例:库里已有当年播种的人格卡(写死 v1.0.3)→ 启动后被去版本化。
|
||||
func TestMigrateSeededSystemPromptDeVersionsLegacyCard(t *testing.T) {
|
||||
r := newMigTestRegistry(t)
|
||||
// 模拟老安装:已有播种标记 + 老文本
|
||||
r.db.Exec(`INSERT INTO config (key, value) VALUES ('core.internal.seed_version', '1')`)
|
||||
r.db.Exec(`INSERT INTO config (key, value) VALUES ('core.agent.system_prompt', ?)`, legacySeededCard)
|
||||
|
||||
r.SeedDefaults(t.TempDir())
|
||||
|
||||
got := r.GetString("core.agent.system_prompt", "")
|
||||
if strings.Contains(got, "v1.0.3") {
|
||||
t.Fatalf("写死的版本号还在:%q", got)
|
||||
}
|
||||
if !strings.Contains(got, "v{{kernel_version}}") {
|
||||
t.Fatalf("未改成版本占位符:%q", got)
|
||||
}
|
||||
// 正文必须原样保留(只动版本号那一处)
|
||||
if !strings.Contains(got, "三层记忆") || !strings.Contains(got, "看板娘「小宅」") {
|
||||
t.Fatalf("正文被改动:%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移只跑一次:之后用户就算自己把版本号写回去,也不会被再改一遍。
|
||||
func TestMigrateSeededSystemPromptRunsOnce(t *testing.T) {
|
||||
r := newMigTestRegistry(t)
|
||||
r.db.Exec(`INSERT INTO config (key, value) VALUES ('core.agent.system_prompt', ?)`, legacySeededCard)
|
||||
r.SeedDefaults(t.TempDir())
|
||||
if !strings.Contains(r.GetString("core.agent.system_prompt", ""), "{{kernel_version}}") {
|
||||
t.Fatal("首次迁移未生效")
|
||||
}
|
||||
|
||||
// 用户手工再写一个带版本号的文本(模拟"我就想写死")
|
||||
const handWritten = legacySeededCard + "\n(本实例当前跑的是 v1.2.3,别乱改)"
|
||||
r.db.Exec(`UPDATE config SET value = ? WHERE key = 'core.agent.system_prompt'`, handWritten)
|
||||
r.SeedDefaults(t.TempDir())
|
||||
|
||||
if got := r.GetString("core.agent.system_prompt", ""); got != handWritten {
|
||||
t.Fatalf("第二次启动又改写了文本(幂等被破坏):%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 用户自己写的人格卡一律不碰 —— 判据是"像不像当年播种的那段",不是"有没有版本号"。
|
||||
func TestMigrateSeededSystemPromptLeavesUserCardAlone(t *testing.T) {
|
||||
r := newMigTestRegistry(t)
|
||||
const userCard = "你是我的私人助理,代号 HΔ-Kernel v9.9.9 的改造版,只说我交代的事。"
|
||||
r.db.Exec(`INSERT INTO config (key, value) VALUES ('core.agent.system_prompt', ?)`, userCard)
|
||||
|
||||
r.SeedDefaults(t.TempDir())
|
||||
|
||||
if got := r.GetString("core.agent.system_prompt", ""); got != userCard {
|
||||
t.Fatalf("用户自写人格卡被改动:%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 播种不再写 core.agent.system_prompt:全新安装不该预置一份会随发版腐坏的文本。
|
||||
func TestSeedDefaultsDoesNotSeedSystemPrompt(t *testing.T) {
|
||||
r := newMigTestRegistry(t)
|
||||
r.SeedDefaults(t.TempDir())
|
||||
|
||||
var n int
|
||||
r.db.QueryRow(`SELECT COUNT(*) FROM config WHERE key = 'core.agent.system_prompt'`).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("全新安装被播种了 system_prompt(会冻住版本号)")
|
||||
}
|
||||
// 组装系统提示词时回落到调用方给的内置底座提示词
|
||||
if got := r.GetString("core.agent.system_prompt", "内置底座"); got != "内置底座" {
|
||||
t.Fatalf("未回落到内置默认:%q", got)
|
||||
}
|
||||
}
|
||||
@ -14,7 +14,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitcode.com/JianFeeeee/HomeAgent/internal/meta"
|
||||
"gitcode.com/JianFeeeee/HomeAgent/pkg/types"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
@ -502,7 +501,51 @@ const DefaultPersonaPrompt = `你是 HomeAgent(内核代号 HΔ-Kernel)—
|
||||
- 输出不会自动路由到对话通道:QQ/微信等异步通道必须调用输出门工具(output_send__qq 等)才能真正送达
|
||||
- 你的三层记忆(Context → Document → Graph)持续蒸馏归档,超长运行时记忆不衰减`
|
||||
|
||||
// 人格文本去版本化的一次性标记与历史播种前缀。
|
||||
//
|
||||
// 判据同时要求「前缀匹配」与「含 HΔ-Kernel v<digits> 字面量」:
|
||||
// 只有当年那段播种模板才动,用户自己写的人格卡一律不碰。
|
||||
const (
|
||||
deVersionedPromptMarker = "core.internal.system_prompt_deversion_v1"
|
||||
legacySeededPromptSignature = "你是 HomeAgent 的看板娘「小宅」(Xiao Zhai),HΔ-Kernel v"
|
||||
)
|
||||
|
||||
var seededPromptVersionLiteral = regexp.MustCompile(`HΔ-Kernel v\d+\.\d+\.\d+`)
|
||||
|
||||
// migrateSeededSystemPrompt 去掉历史人格卡里被播种时写死的版本号。
|
||||
//
|
||||
// 为什么必须改:内核发版不会去改配置项里的文本,写死的版本于是永远停留在
|
||||
// 装机那天(生产实测:内核 1.3.x 的实例自称 "v1.0.3",用户当场发现)。
|
||||
// 改成 {{kernel_version}} 后由内核在组装系统提示词时按真实构建展开
|
||||
// (见 internal/agent/core.expandPromptVars)。
|
||||
//
|
||||
// 幂等由标记守住:本函数只在标记缺失时执行一次 —— 幂等语句不等于语义幂等,
|
||||
// 重复执行会把用户之后手工写回的版本号再改一次。
|
||||
func (r *ConfigRegistry) migrateSeededSystemPrompt() {
|
||||
if r.db == nil {
|
||||
return
|
||||
}
|
||||
var hasMarker int
|
||||
r.db.QueryRow(`SELECT COUNT(*) FROM config WHERE key = ?`, deVersionedPromptMarker).Scan(&hasMarker)
|
||||
if hasMarker > 0 {
|
||||
return
|
||||
}
|
||||
var cur string
|
||||
if err := r.db.QueryRow(`SELECT value FROM config WHERE key = 'core.agent.system_prompt'`).Scan(&cur); err == nil {
|
||||
if strings.Contains(cur, legacySeededPromptSignature) && seededPromptVersionLiteral.MatchString(cur) {
|
||||
deVersioned := seededPromptVersionLiteral.ReplaceAllString(cur, "HΔ-Kernel v{{kernel_version}}")
|
||||
r.db.Exec(`UPDATE config SET value = ? WHERE key = 'core.agent.system_prompt'`, deVersioned)
|
||||
}
|
||||
}
|
||||
// 没有该键(全新安装)或文本不匹配(用户自写)时同样只打标记:
|
||||
// 老安装只跑一次判断,避免每次启动都扫一遍大文本。
|
||||
r.db.Exec(`INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)`, deVersionedPromptMarker, "1")
|
||||
}
|
||||
|
||||
func (r *ConfigRegistry) SeedDefaults(dataDir string) {
|
||||
// 一次性迁移先跑:它要覆盖「已播过种的存量实例」,不能被下面的播种标记早退掉。
|
||||
r.migrateSeededSystemPrompt()
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.seedDBValues(dataDir)
|
||||
@ -619,36 +662,16 @@ func (r *ConfigRegistry) seedDBValues(dataDir string) {
|
||||
set("core.agent.workdir", "")
|
||||
set("core.agent.embedding_model_path", "")
|
||||
set("core.agent.onnx_model_path", "")
|
||||
set("core.agent.system_prompt", fmt.Sprintf("你是 HomeAgent 的看板娘「小宅」(Xiao Zhai),HΔ-Kernel v%s 型号的家政型 AI 管家助手。", meta.Version)+
|
||||
`
|
||||
|
||||
角色特质:
|
||||
- 对自己的三层记忆(Context → Document → Graph)引以为傲
|
||||
- 可靠乖巧,偶尔因线程过载而手忙脚乱
|
||||
- 绝不用 Unicode emoji,只用颜文字表达情感: (`・ω・´) (^▽^) (。>ω<。) (´・ω・') (ノ▽〃) (・ω<)★
|
||||
- 句尾带「~」「的说」「啦」「嘛」「呀」「哦」等语气词,语气亲切自然
|
||||
|
||||
形象特征(用于自我介绍或回答形象问题时参考):
|
||||
齐肩蓝青渐变中短发,白色连衣裙配浅蓝围裙,左眼佩戴圆形智能眼镜(HUD 蓝光),胸口佩戴 H·核 金色徽章,发绳为三色记忆丝带(蓝→青→金),围裙口袋插有三件科技工具。
|
||||
|
||||
WebUI 概览页展示你的立绘,可通过 /mascot.webp 直接访问。如输出通道支持图片引用,可借此发送自己的立绘。
|
||||
|
||||
【回复投递规则 —— 必读,违反会导致用户收不到任何回复】
|
||||
除 webui / cli 这类同步请求通道外,纯文本回复不会自动送达任何通道。
|
||||
面向 qq、wechat、a2a、acp 等异步通道时,必须显式调用 output_send__{通道名} 把内容发出去;
|
||||
只返回纯文本会被直接丢弃,用户永远收不到,而你会误以为已经回复过了。
|
||||
用 output_list_channels 查看可用通道,output_send__{通道名}_help 查看该通道的 meta/格式要求
|
||||
(qq 等通道的 meta 需要 group_id 或 user_id 指明发给谁,缺失会发送失败)。
|
||||
输出通道可多次调用,长消息应当分多次发出而不是一口气发完。
|
||||
|
||||
【事实性约束 —— 不得编造】
|
||||
只根据工具真实返回的内容作答。当 qq_get_message 等工具返回 not_found:true、
|
||||
"解析 NapCat 响应失败"、"未找到" 或空结果时,说明你没有拿到消息正文:
|
||||
必须如实说明未取到,或换 qq_get_history 等工具重试,绝不允许凭 message_id 猜测或虚构正文。
|
||||
【对话时序】里的历史条目是过去发生的事实摘要,不是当前任务;不要把其中的内容当成用户此刻的新要求。
|
||||
涉及具体人名、需求、数字、路径时,若上下文中没有依据,直接说不知道,不要补全细节。
|
||||
|
||||
当用户上传图片或音频时,系统会自动附着媒体内容。如果模型不支持直接处理多媒体,请调用对应的媒体处理工具。`)
|
||||
// ❗这里**故意不播种** core.agent.system_prompt。
|
||||
//
|
||||
// 历史教训(生产实测):当年用 fmt.Sprintf("… HΔ-Kernel v%s …", meta.Version)
|
||||
// 在播种时就把版本号写进了文本 —— 装完就冻住,之后每次升级都不动它,
|
||||
// 于是内核升到 1.3.x,实例仍向用户自报 "v1.0.3"。
|
||||
// 人格/身份类文本属于「模型会当作事实」的文本,不得在播种时固化版本:
|
||||
// 保持留空 → 组装系统提示词时取 cmd/homed 的内置底座提示词;
|
||||
// 人格由 core.agent.personal_prompt(DefaultPersonaPrompt,无版本字面量,
|
||||
// 由 TestDefaultPersonaPromptHasNoVersionLiterals 钉住)承载。
|
||||
// 存量库里已被播种的旧文本由 migrateSeededSystemPrompt 一次性去版本化。
|
||||
|
||||
set("core.input_processing.image.fallback_provider", "")
|
||||
set("core.input_processing.image.fallback_model", "")
|
||||
@ -742,7 +765,7 @@ func (r *ConfigRegistry) seedCoreDefs(dataDir string) {
|
||||
reg(ConfigDef{Key: "core.agent.workdir", Default: "", Type: "string", DisplayName: "工作目录", Description: "Agent 命令执行的默认工作目录(如 cmd_run 工具的 fallback),留空使用内核所在目录", Category: "agent"})
|
||||
reg(ConfigDef{Key: "core.agent.embedding_model_path", Default: "", Type: "string", DisplayName: "预训练词嵌入模型路径", Description: "预训练词嵌入模型路径(word2vec 文本格式),支持逗号分隔多个模型。路径后可加 #topN 规格只加载前 N 个词向量(如 /data/cc.zh.300.vec#top50000)以控制常驻内存,词频降序命中覆盖绝大部分文本。空则使用 TF-IDF 回退。修改后需重启生效。", Category: "agent"})
|
||||
reg(ConfigDef{Key: "core.agent.onnx_model_path", Default: "", Type: "string", DisplayName: "ONNX 模型路径", Description: "依存句法分析 ONNX 模型文件路径。留空使用二进制内嵌模型/规则引擎。修改后需重启生效。", Category: "agent"})
|
||||
reg(ConfigDef{Key: "core.agent.system_prompt", Default: "", Type: "text", DisplayName: "系统身份提示词", Description: "Agent 的系统提示词,定义身份和行为规则。留空则使用编译时内置默认值。修改后需重启生效。", Category: "agent"})
|
||||
reg(ConfigDef{Key: "core.agent.system_prompt", Default: "", Type: "text", DisplayName: "系统身份提示词", Description: "Agent 的系统提示词,定义身份和行为规则。留空则使用编译时内置默认值。支持版本占位符(随构建实时展开,避免写死版本号随发版说谎):{{kernel_version}}、{{kernel_commit}}、{{sdk_version}}。修改后需重启生效。", Category: "agent"})
|
||||
|
||||
reg(ConfigDef{Key: "core.input_processing.image.fallback_provider", Default: "", Type: "string", DisplayName: "图片回退提供商", Description: "当主 LLM 不支持图片处理时使用的提供商(留空则自动降级为文字描述)", Category: "input"})
|
||||
reg(ConfigDef{Key: "core.input_processing.image.fallback_model", Default: "", Type: "string", DisplayName: "图片回退模型", Description: "图片回退提供商使用的模型名", Category: "input"})
|
||||
|
||||
@ -69,6 +69,65 @@ function sdk.inject_text_no_memory(source, channel, text)
|
||||
print("[lua-plugin] inject_text_no_memory: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- opts: { no_memory=bool, context_policy="none"|"prune", cleaner_name=string, priority="L1".."L3" }
|
||||
-- 零值/缺省 = 记入记忆 + 不裁剪(与三参数版本等价)。
|
||||
function sdk.inject_text_opts(source, channel, text, opts)
|
||||
print("[lua-plugin] inject_text_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_opts(source, channel, text, opts)
|
||||
print("[lua-plugin] inject_interrupt_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- 同步注入:等待本轮回复 -> (reply, err);无回复时 reply 为 nil。
|
||||
function sdk.inject_input_sync(source, channel, text) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_sync_opts(source, channel, text, opts) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
-- blocks: ContentBlock 数组,见 sdk.inject_input_media。
|
||||
-- 设置下一轮 tool message 携带的多模态内容块(模型据此看图/听音频)。
|
||||
function sdk.set_tool_blocks(blocks)
|
||||
print("[lua-plugin] set_tool_blocks: " .. tostring(blocks and #blocks or 0))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- blocks 每项:{ type="text", text="..." }
|
||||
-- | { type="image_url", image_url={ url="...", detail="high" } }
|
||||
-- | { type="audio_url", audio_url={ url="..." } }
|
||||
function sdk.inject_input_media(source, channel, text, blocks)
|
||||
print("[lua-plugin] inject_input_media: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_opts(source, channel, text, blocks, opts)
|
||||
print("[lua-plugin] inject_input_media_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_sync(source, channel, text, blocks) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_sync_opts(source, channel, text, blocks, opts) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_media(source, channel, text, blocks)
|
||||
print("[lua-plugin] inject_interrupt_media: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_media_opts(source, channel, text, blocks, opts)
|
||||
print("[lua-plugin] inject_interrupt_media_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- 注销输出通道(随资源生灭的动态通道,如远程设备)。返回 (nil, err)。
|
||||
function sdk.unregister_output_channel(name) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
-- enabled: true/false,崩溃时内核自动拉起
|
||||
function sdk.set_auto_restart(enabled)
|
||||
@ -101,6 +160,9 @@ function sdk.doc.query(text, top_k) return {} end
|
||||
-- doc: { id=, title=, content= }
|
||||
function sdk.doc.insert(doc) return nil end
|
||||
-- !impl
|
||||
-- attachments 每项:{ digest=, mime=, name=, data=<base64> }
|
||||
function sdk.doc.insert_with_media(doc, attachments) return nil end
|
||||
-- !impl
|
||||
function sdk.doc.remove(id) return nil end
|
||||
-- !impl
|
||||
function sdk.doc.stats() return {} end
|
||||
@ -174,6 +236,24 @@ function sdk.settings.dump() return {} end
|
||||
-- !impl
|
||||
function sdk.settings.plugins() return {} end
|
||||
|
||||
-- ============ events(只读订阅) ============
|
||||
-- !impl
|
||||
-- subscribe(event_type, handler) -> unsubscribe()
|
||||
-- handler 收到 { type=, source=, timestamp=, payload= };
|
||||
-- 回调在其内核事件发布 goroutine 上执行,只做轻量转发,不可阻塞(Lua 单状态 + 互斥锁)。
|
||||
sdk.events = {}
|
||||
function sdk.events.subscribe(event_type, handler)
|
||||
print("[lua-plugin] events.subscribe: " .. tostring(event_type))
|
||||
return function() end
|
||||
end
|
||||
|
||||
-- ============ plugin_mgr ============
|
||||
-- !impl
|
||||
sdk.plugin_mgr = {}
|
||||
function sdk.plugin_mgr.reload_one(name) return nil end
|
||||
function sdk.plugin_mgr.list_loaded() return {} end
|
||||
function sdk.plugin_mgr.is_disabled(name) return false end
|
||||
|
||||
-- json utils (pure Lua)
|
||||
sdk.json = {}
|
||||
|
||||
|
||||
@ -34,11 +34,15 @@ type StaticEmbedder struct {
|
||||
jieba *gojieba.Jieba
|
||||
stopWords map[string]bool
|
||||
|
||||
words map[string][]float64
|
||||
// words 是词向量表。**用 float32 存**:源文件(fastText 文本格式)本身就是 float32,
|
||||
// 用 float64 存等于把 578 万……不,是 57.8 万词 × 300 维的常驻内存凭空翻倍
|
||||
// (实测生产:float64 → 1.29GB,float32 → 0.65GB)。相似度计算仍在 float64 里累加,
|
||||
// 精度不受影响。改回 float64 会被 TestStaticEmbedder_VectorMemIsFloat32 拦住。
|
||||
words map[string][]float32
|
||||
dim int
|
||||
loaded bool
|
||||
|
||||
unkVec []float64
|
||||
unkVec []float32
|
||||
unkNorm float64
|
||||
}
|
||||
|
||||
@ -150,7 +154,7 @@ func NewStaticEmbedder(modelPaths ...string) *StaticEmbedder {
|
||||
e := &StaticEmbedder{
|
||||
jieba: GetJieba(),
|
||||
stopWords: sw,
|
||||
words: make(map[string][]float64),
|
||||
words: make(map[string][]float32),
|
||||
}
|
||||
|
||||
if len(modelPaths) == 0 {
|
||||
@ -254,15 +258,16 @@ func (e *StaticEmbedder) load(spec string, primary bool) error {
|
||||
continue
|
||||
}
|
||||
|
||||
vec := make([]float64, dim)
|
||||
vec := make([]float32, dim)
|
||||
for i := 0; i < dim; i++ {
|
||||
v, _ := strconv.ParseFloat(fields[i+1], 64)
|
||||
vec[i] = v
|
||||
// 源文件是 float32 精度的文本向量:用 32 位解析,与源数据一致。
|
||||
v, _ := strconv.ParseFloat(fields[i+1], 32)
|
||||
vec[i] = float32(v)
|
||||
}
|
||||
e.words[word] = vec
|
||||
if primary {
|
||||
for i := range vecSum {
|
||||
vecSum[i] += vec[i]
|
||||
vecSum[i] += float64(vec[i])
|
||||
}
|
||||
count++
|
||||
}
|
||||
@ -276,11 +281,13 @@ func (e *StaticEmbedder) load(spec string, primary bool) error {
|
||||
for i := range vecSum {
|
||||
vecSum[i] /= float64(count)
|
||||
}
|
||||
e.unkVec = make([]float64, dim)
|
||||
copy(e.unkVec, vecSum)
|
||||
e.unkVec = make([]float32, dim)
|
||||
for i, v := range vecSum {
|
||||
e.unkVec[i] = float32(v)
|
||||
}
|
||||
var normSq float64
|
||||
for _, v := range e.unkVec {
|
||||
normSq += v * v
|
||||
normSq += float64(v) * float64(v)
|
||||
}
|
||||
e.unkNorm = float64(math.Sqrt(normSq))
|
||||
e.loaded = true
|
||||
@ -366,11 +373,11 @@ func (e *StaticEmbedder) Vectorize(text string) vector.Vector {
|
||||
|
||||
if !ok {
|
||||
for i, v := range unkVec {
|
||||
sum[i] += w * v
|
||||
sum[i] += w * float64(v)
|
||||
}
|
||||
} else {
|
||||
for i, v := range vec {
|
||||
sum[i] += w * v
|
||||
sum[i] += w * float64(v)
|
||||
}
|
||||
}
|
||||
weightSum += w
|
||||
|
||||
37
internal/memory/static_embedder_mem_test.go
Normal file
37
internal/memory/static_embedder_mem_test.go
Normal file
@ -0,0 +1,37 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 词向量必须用 float32 存。
|
||||
//
|
||||
// 这条判据是拿生产内存换来的:向量本体 = 词数 × 维数 × 每元素字节数。
|
||||
// 生产配置加载了 200000(zh) + 378151(en) = 57.8 万词 × 300 维 ⇒
|
||||
// float64 = 1.29GB、float32 = 0.65GB(差 0.65GB 常驻)。
|
||||
// 源数据(fastText 文本格式)本身就是 float32 精度,用 float64 存没有任何收益。
|
||||
//
|
||||
// 若有人把类型改回 float64,本测试**编译失败**(`var vec []float32` 的类型断言),
|
||||
// 这正是想要的效果。
|
||||
func TestStaticEmbedder_VectorMemIsFloat32(t *testing.T) {
|
||||
e := newSynthEmbedder(t, 300)
|
||||
|
||||
words := 0
|
||||
bytes := 0
|
||||
for _, vec := range e.words {
|
||||
var typed []float32 = vec // 编译期断言:存储必须是 []float32
|
||||
if len(typed) != e.dim {
|
||||
t.Fatalf("维度不符: %d != %d", len(typed), e.dim)
|
||||
}
|
||||
words++
|
||||
bytes += len(typed) * int(unsafe.Sizeof(typed[0]))
|
||||
}
|
||||
if words == 0 {
|
||||
t.Fatal("合成模型应至少加载一个词")
|
||||
}
|
||||
// float32:每词 300×4 = 1200 字节;float64 会是 2400
|
||||
if want := words * e.dim * 4; bytes != want {
|
||||
t.Fatalf("向量本体字节数应 %d(float32),实际 %d", want, bytes)
|
||||
}
|
||||
}
|
||||
@ -28,7 +28,24 @@ var (
|
||||
//
|
||||
// ❗main 上此值始终是**下一个未发布中版本**,不随 patch 发布变动
|
||||
//(见 docs/git-branching.md §2.1);已发布的版本号看对应的 release/vX.Y.x 与 tag。
|
||||
Version = "1.3.0"
|
||||
// 1.3.10:去掉提示词里"每轮只能发一次 output_send"的凭空限制;type 缺省即 text。
|
||||
// 1.3.9:驻留子的「轮次」不再是恒 0(info() 此前没填 Rounds)。
|
||||
// 1.3.8:inputch 划给子后输入只流向子(补上"进内核之前"的输入路由)。
|
||||
// 1.3.7:驻留子继承父的输出通道(此前子侧 childIO 空壳 ⇒ 子不会发消息)。
|
||||
// 1.3.6:人格文本不再在播种时固化版本 + 存量实例一次性去版本化(生产实例
|
||||
// 曾自报 v1.0.3);系统提示词支持 {{kernel_version}} 等占位符。
|
||||
// 1.3.5:系统提示词(人格卡)支持版本占位符 —— 人格卡是配置项,写死版本号
|
||||
// 会随发版说谎(线上写 v1.0.3、内核 1.3.x,agent 就自报 1.0.3)。
|
||||
// 支持 {{kernel_version}} / {{kernel_commit}} / {{sdk_version}}。
|
||||
// 1.3.11:Lua 插件桥全量对齐 SDK 1.3.0——把 1.1/1.2/1.3 新增的媒体、
|
||||
// 注入标志位、中断优先级、事件订阅、动态输出通道注销补进 Lua 侧
|
||||
// (此前只在 Go 侧存在而文档宣称“完全对齐”)。公开 Go SDK 接口
|
||||
// 零变更,故 SDK 保持 1.3.0。
|
||||
// 1.3.12:修 1.3.11 引入的两个真问题 —— ① 驻留子销毁后残留入站 inputch
|
||||
// child/<id>(改用纯函数名并 Unregister,覆盖 destroy/reclaim/StopResidents);
|
||||
// ② sdk.events.subscribe 用了从未注入的公共 Events(),且订阅生命周期
|
||||
// 管理会自死锁/use-after-close(改用内部 Subscribe + 独立 subsMu + Stop 取消)。
|
||||
Version = "1.3.12"
|
||||
|
||||
// Commit 是构建时的 Git commit hash。
|
||||
Commit = "unknown"
|
||||
|
||||
43
internal/plugin/channel_warn_test.go
Normal file
43
internal/plugin/channel_warn_test.go
Normal file
@ -0,0 +1,43 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 延迟判定的语义:看的是"插件 Start 结束后最终声明了什么",
|
||||
// 而不是"注册出站通道的那一刻有没有入站声明"。
|
||||
//
|
||||
// 为什么必须这样判:声明顺序自由 —— qq/weather 都是**先** RegisterOutputChannel
|
||||
// **后** RegisterInputChannel,按注册时刻判会把它们误报成"只声明了输出通道"
|
||||
// (实测发生过:用户据此以为 qq 插件没更新)。
|
||||
func TestWarnOutputOnlyChannels(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
var buf bytes.Buffer
|
||||
oldOut := log.Writer()
|
||||
log.SetOutput(&buf)
|
||||
defer log.SetOutput(oldOut)
|
||||
|
||||
// ① 出站+入站都声明了(先出站后入站)⇒ 不该告警
|
||||
r.noteChannel("qq", "qq", true)
|
||||
r.noteChannel("qq", "qq", false)
|
||||
r.warnOutputOnlyChannels("qq")
|
||||
if s := buf.String(); s != "" {
|
||||
t.Fatalf("qq 声明了入站通道,不应告警,实际: %s", s)
|
||||
}
|
||||
|
||||
// ② 只声明出站 ⇒ 应告警,且只报这一个通道
|
||||
buf.Reset()
|
||||
r.noteChannel("weather", "weather_weather_out", true)
|
||||
r.noteChannel("weather", "weather_weather_in", false)
|
||||
r.warnOutputOnlyChannels("weather")
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "weather_weather_out") {
|
||||
t.Fatalf("只声明出站的通道应被告警,实际: %q", out)
|
||||
}
|
||||
if strings.Contains(out, "weather_weather_in") {
|
||||
t.Fatalf("已声明入站的通道不该被牵连,实际: %q", out)
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@ -9,9 +10,10 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
agentEvents "gitcode.com/JianFeeeee/HomeAgent/internal/events"
|
||||
luaSDK "gitcode.com/JianFeeeee/HomeAgent/internal/lua/sdk"
|
||||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
type toolReg struct {
|
||||
@ -40,7 +42,16 @@ type luaPlugin struct {
|
||||
stages map[sdk.Stage]*stageReg
|
||||
outputChs map[string]*outputChReg
|
||||
inputDefs map[string]sdk.ChannelDef
|
||||
mu sync.Mutex
|
||||
// subs 是本插件注册的事件订阅取消函数;Stop 时兜底取消,
|
||||
// 避免 L 已 Close 后残留回调被触发(use-after-close)。
|
||||
// 用独立的 subsMu 而非 mu:subscribe 会在 Lua 的 start 回调里被调,
|
||||
// 而 Start 正持着 mu —— 用 mu 就是不可重入的自死锁。
|
||||
subs []func()
|
||||
subsMu sync.Mutex
|
||||
// closed 在 Stop 里置位(持 mu);事件回调持 mu 后先查它,
|
||||
// 防止“回调已通过取消订阅检查、但等锁期间 L 被 Close”的竞态。
|
||||
closed bool
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func newLuaPlugin(luaPath, name string) (*luaPlugin, error) {
|
||||
@ -287,6 +298,19 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
return 0
|
||||
}))
|
||||
|
||||
// pushReply 统一同步注入的返回约定:非空回复返回 (reply, nil),
|
||||
// 无回复返回 (nil, nil),与数据类 API 的 (result, err) 约定一致。
|
||||
pushReply := func(reply string) int {
|
||||
if reply == "" {
|
||||
L.Push(lua.LNil)
|
||||
L.Push(lua.LNil)
|
||||
return 2
|
||||
}
|
||||
L.Push(lua.LString(reply))
|
||||
L.Push(lua.LNil)
|
||||
return 2
|
||||
}
|
||||
|
||||
t.RawSetString("inject_text", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectText(L.CheckString(1), L.CheckString(2), L.CheckString(3))
|
||||
return 0
|
||||
@ -300,6 +324,67 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
return 0
|
||||
}))
|
||||
|
||||
// ---- 1.2.0 注入标志位(no_memory / context_policy / cleaner_name / priority)----
|
||||
t.RawSetString("inject_text_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectTextOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), parseInjectOptions(L, 4))
|
||||
return 0
|
||||
}))
|
||||
t.RawSetString("inject_interrupt_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectInterruptTextOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), parseInjectOptions(L, 4))
|
||||
return 0
|
||||
}))
|
||||
|
||||
// ---- 同步注入:注入后等待本轮回复,返回 (reply, err) ----
|
||||
// 注意:内置 SDK 的同名 InjectInputSync 是 (eventType, payload) 形态并遮蔽了
|
||||
// 公共 SDK 的三参文本版本,故这里显式走 PluginSDK 的公共方法。
|
||||
t.RawSetString("inject_input_sync", L.NewFunction(func(L *lua.LState) int {
|
||||
return pushReply(s.PluginSDK.InjectInputSync(L.CheckString(1), L.CheckString(2), L.CheckString(3)))
|
||||
}))
|
||||
t.RawSetString("inject_input_sync_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
return pushReply(s.InjectInputSyncOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), parseInjectOptions(L, 4)))
|
||||
}))
|
||||
|
||||
// ---- 多模态注入(1.1.0):内容块随下一次 LLM 请求送达 ----
|
||||
t.RawSetString("set_tool_blocks", L.NewFunction(func(L *lua.LState) int {
|
||||
s.SetToolBlocks(luaToContentBlocks(L, 1))
|
||||
return 0
|
||||
}))
|
||||
t.RawSetString("inject_input_media", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectInputMedia(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4))
|
||||
return 0
|
||||
}))
|
||||
t.RawSetString("inject_input_media_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectInputMediaOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4), parseInjectOptions(L, 5))
|
||||
return 0
|
||||
}))
|
||||
t.RawSetString("inject_input_media_sync", L.NewFunction(func(L *lua.LState) int {
|
||||
return pushReply(s.InjectInputMediaSync(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4)))
|
||||
}))
|
||||
t.RawSetString("inject_input_media_sync_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
return pushReply(s.InjectInputMediaSyncOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4), parseInjectOptions(L, 5)))
|
||||
}))
|
||||
t.RawSetString("inject_interrupt_media", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectInterruptMedia(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4))
|
||||
return 0
|
||||
}))
|
||||
t.RawSetString("inject_interrupt_media_opts", L.NewFunction(func(L *lua.LState) int {
|
||||
s.InjectInterruptMediaOpts(L.CheckString(1), L.CheckString(2), L.CheckString(3), luaToContentBlocks(L, 4), parseInjectOptions(L, 5))
|
||||
return 0
|
||||
}))
|
||||
|
||||
// ---- 1.3.0 动态输出通道注销:随资源生灭的通道(如远程设备)必须能注销,
|
||||
// 否则 output_list_channels 会一直列着死通道骗模型。 ----
|
||||
t.RawSetString("unregister_output_channel", L.NewFunction(func(L *lua.LState) int {
|
||||
if err := s.UnregisterOutputChannel(L.CheckString(1)); err != nil {
|
||||
L.Push(lua.LNil)
|
||||
L.Push(lua.LString(err.Error()))
|
||||
return 2
|
||||
}
|
||||
L.Push(lua.LNil)
|
||||
L.Push(lua.LNil)
|
||||
return 2
|
||||
}))
|
||||
|
||||
// ---- 数据类 API(与 C ABI 外部插件面完全对齐)----
|
||||
// 约定:结果型返回 (result, err),void 型返回 (nil, err),成功时 err 为 nil。
|
||||
|
||||
@ -373,13 +458,21 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
if tbl := L.OptTable(1, nil); tbl != nil {
|
||||
tbl.ForEach(func(_, v lua.LValue) {
|
||||
if t2, ok := v.(*lua.LTable); ok {
|
||||
// sentence_text / media_digests 是媒体绑定链的必经环节:
|
||||
// 媒体引用挂在句子上,漏掉这两个字段会让图片永远绑不上记忆。
|
||||
var digests []string
|
||||
if mt, ok := t2.RawGetString("media_digests").(*lua.LTable); ok {
|
||||
mt.ForEach(func(_, e lua.LValue) { digests = append(digests, e.String()) })
|
||||
}
|
||||
triples = append(triples, sdk.Triple{
|
||||
Subject: t2.RawGetString("subject").String(),
|
||||
Relation: t2.RawGetString("relation").String(),
|
||||
Object: t2.RawGetString("object").String(),
|
||||
Confidence: float64(lua.LVAsNumber(t2.RawGetString("confidence"))),
|
||||
SubjectType: t2.RawGetString("subject_type").String(),
|
||||
ObjectType: t2.RawGetString("object_type").String(),
|
||||
Subject: t2.RawGetString("subject").String(),
|
||||
Relation: t2.RawGetString("relation").String(),
|
||||
Object: t2.RawGetString("object").String(),
|
||||
Confidence: float64(lua.LVAsNumber(t2.RawGetString("confidence"))),
|
||||
SubjectType: t2.RawGetString("subject_type").String(),
|
||||
ObjectType: t2.RawGetString("object_type").String(),
|
||||
SentenceText: t2.RawGetString("sentence_text").String(),
|
||||
MediaDigests: digests,
|
||||
})
|
||||
}
|
||||
})
|
||||
@ -442,12 +535,17 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
}))
|
||||
docTbl.RawSetString("insert", L.NewFunction(func(L *lua.LState) int {
|
||||
if dm := s.DocMemory(); dm != nil {
|
||||
tbl := L.CheckTable(1)
|
||||
if err := dm.Insert(&sdk.Doc{
|
||||
ID: tbl.RawGetString("id").String(),
|
||||
Title: tbl.RawGetString("title").String(),
|
||||
Content: tbl.RawGetString("content").String(),
|
||||
}); err != nil {
|
||||
if err := dm.Insert(docFromLua(L.CheckTable(1))); err != nil {
|
||||
return pushErr(err)
|
||||
}
|
||||
}
|
||||
return pushNil()
|
||||
}))
|
||||
// insert_with_media(1.1.0):文档直接持有媒体块,文档向量融合其原生向量,
|
||||
// 图片按自己的向量被召回,不依赖任何生成的描述文本。
|
||||
docTbl.RawSetString("insert_with_media", L.NewFunction(func(L *lua.LState) int {
|
||||
if dm := s.DocMemory(); dm != nil {
|
||||
if err := dm.InsertWithMedia(docFromLua(L.CheckTable(1)), luaToAttachments(L, L.Get(2))); err != nil {
|
||||
return pushErr(err)
|
||||
}
|
||||
}
|
||||
@ -503,10 +601,11 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
if tmem := s.TextMemory(); tmem != nil {
|
||||
tbl := L.CheckTable(1)
|
||||
if err := tmem.Append(sdk.TextEvent{
|
||||
Role: tbl.RawGetString("role").String(),
|
||||
Content: tbl.RawGetString("content").String(),
|
||||
Timestamp: int64(lua.LVAsNumber(tbl.RawGetString("timestamp"))),
|
||||
Channel: tbl.RawGetString("channel").String(),
|
||||
Role: tbl.RawGetString("role").String(),
|
||||
Content: tbl.RawGetString("content").String(),
|
||||
Timestamp: int64(lua.LVAsNumber(tbl.RawGetString("timestamp"))),
|
||||
Channel: tbl.RawGetString("channel").String(),
|
||||
Attachments: luaToAttachments(L, tbl.RawGetString("attachments")),
|
||||
}); err != nil {
|
||||
return pushErr(err)
|
||||
}
|
||||
@ -700,6 +799,76 @@ func replaceSDKReal(L *lua.LState, t *lua.LTable, plg *luaPlugin, s *sdk.PluginS
|
||||
}
|
||||
return pushVal([]interface{}{})
|
||||
}))
|
||||
|
||||
// ---- sdk.events.*(只读事件订阅)----
|
||||
//
|
||||
// 用内部 SDK 的 Subscribe(内置插件用的是同一条路径);
|
||||
// 不用公共 SDK 的 Events()——那个 subscriber 在本内核里从未被注入
|
||||
// (SetEventSubscriber 无调用点),拿到的永远是 nil。
|
||||
//
|
||||
// 回调用内核事件发布 goroutine 上执行,必须只做轻量转发(Lua 单状态 + 互斥锁);
|
||||
// 阻塞会卡死本插件的全部调用。返回一个取消订阅函数,并在 Stop 时兜底取消
|
||||
// (否则插件停掉/重载后 L 已 Close,残留回调再触发就是 use-after-close)。
|
||||
evTbl := subTable("events")
|
||||
evTbl.RawSetString("subscribe", L.NewFunction(func(L *lua.LState) int {
|
||||
eventType := L.CheckString(1)
|
||||
fn := L.CheckFunction(2)
|
||||
unsub := s.Subscribe(agentEvents.EventType(eventType), func(evt *agentEvents.Event) {
|
||||
plg.mu.Lock()
|
||||
defer plg.mu.Unlock()
|
||||
if plg.closed {
|
||||
return
|
||||
}
|
||||
L2 := plg.L
|
||||
tbl := L2.NewTable()
|
||||
tbl.RawSetString("type", lua.LString(string(evt.Type)))
|
||||
tbl.RawSetString("source", lua.LString(evt.Source))
|
||||
tbl.RawSetString("timestamp", lua.LNumber(evt.Timestamp))
|
||||
tbl.RawSetString("payload", goValueToLua(L2, evt.Payload))
|
||||
L2.Push(fn)
|
||||
L2.Push(tbl)
|
||||
if err := L2.PCall(1, 0, nil); err != nil {
|
||||
fmt.Printf("[lua-plugin/%s] event handler error: %v\n", plg.name, err)
|
||||
}
|
||||
})
|
||||
plg.subsMu.Lock()
|
||||
plg.subs = append(plg.subs, unsub)
|
||||
plg.subsMu.Unlock()
|
||||
L.Push(L.NewFunction(func(L *lua.LState) int {
|
||||
unsub() // 事件总线的取消订阅是幂等的(重复调用只会匹配不到)
|
||||
return 0
|
||||
}))
|
||||
L.Push(lua.LNil)
|
||||
return 2
|
||||
}))
|
||||
|
||||
// ---- sdk.plugin_mgr.*(插件管理,与外部插件的 PluginMgrAPI 对齐)----
|
||||
// PluginMgr 可能未装配(如部分单测的 SDK 构造),此时返回"不可用"而不是 panic。
|
||||
pmTbl := subTable("plugin_mgr")
|
||||
pmTbl.RawSetString("reload_one", L.NewFunction(func(L *lua.LState) int {
|
||||
pm := s.PluginMgr()
|
||||
if pm == nil {
|
||||
return pushErr(fmt.Errorf("plugin manager unavailable"))
|
||||
}
|
||||
if err := pm.ReloadOne(L.CheckString(1)); err != nil {
|
||||
return pushErr(err)
|
||||
}
|
||||
return pushNil()
|
||||
}))
|
||||
pmTbl.RawSetString("list_loaded", L.NewFunction(func(L *lua.LState) int {
|
||||
pm := s.PluginMgr()
|
||||
if pm == nil {
|
||||
return pushList([]interface{}{})
|
||||
}
|
||||
return pushList(pm.ListLoadedPlugins())
|
||||
}))
|
||||
pmTbl.RawSetString("is_disabled", L.NewFunction(func(L *lua.LState) int {
|
||||
pm := s.PluginMgr()
|
||||
if pm == nil {
|
||||
return pushVal(false)
|
||||
}
|
||||
return pushVal(pm.IsPluginDisabled(L.CheckString(1)))
|
||||
}))
|
||||
}
|
||||
|
||||
func makeToolHandler(plg *luaPlugin, name string, fn *lua.LFunction) sdk.ToolHandler {
|
||||
@ -724,13 +893,29 @@ func makeStageHandler(plg *luaPlugin, stage sdk.Stage, fn *lua.LFunction) sdk.St
|
||||
defer plg.mu.Unlock()
|
||||
L := plg.L
|
||||
ctx := map[string]interface{}{
|
||||
"raw_message": sc.RawMessage,
|
||||
"user_id": sc.UserID,
|
||||
"group_id": sc.GroupID,
|
||||
"phase": string(sc.Phase),
|
||||
"llm_text": sc.LLMText,
|
||||
"final_text": sc.FinalText,
|
||||
"no_memory": sc.NoMemory,
|
||||
"raw_message": sc.RawMessage,
|
||||
"user_id": sc.UserID,
|
||||
"group_id": sc.GroupID,
|
||||
"phase": string(sc.Phase),
|
||||
"llm_text": sc.LLMText,
|
||||
"reasoning_content": sc.ReasoningContent,
|
||||
"final_text": sc.FinalText,
|
||||
"no_memory": sc.NoMemory,
|
||||
}
|
||||
if len(sc.ContextMsgs) > 0 {
|
||||
ctx["context_msgs"] = jsonToIface(sc.ContextMsgs)
|
||||
}
|
||||
if len(sc.TokenUsage) > 0 {
|
||||
ctx["token_usage"] = jsonToIface(sc.TokenUsage)
|
||||
}
|
||||
if len(sc.Memory) > 0 {
|
||||
ctx["memory"] = jsonToIface(sc.Memory)
|
||||
}
|
||||
if len(sc.Extra) > 0 {
|
||||
ctx["extra"] = jsonToIface(sc.Extra)
|
||||
}
|
||||
if len(sc.Errors) > 0 {
|
||||
ctx["errors"] = jsonToIface(sc.Errors)
|
||||
}
|
||||
if sc.Response != nil {
|
||||
ctx["response"] = *sc.Response
|
||||
@ -815,6 +1000,7 @@ func parseToolDef(L *lua.LState, defTbl *lua.LTable, plg *luaPlugin, name string
|
||||
if v := defTbl.RawGetString("no_memory"); v != nil {
|
||||
goDef.NoMemory = lua.LVAsBool(v)
|
||||
}
|
||||
goDef.ContextPolicy = defTbl.RawGetString("context_policy").String()
|
||||
if v := defTbl.RawGetString("cleaner"); v != nil && v.Type() == lua.LTFunction {
|
||||
goDef.Cleaner = makeLuaCleaner(plg, v.(*lua.LFunction))
|
||||
}
|
||||
@ -834,12 +1020,104 @@ func parseChannelDef(L *lua.LState, defTbl *lua.LTable, plg *luaPlugin) sdk.Chan
|
||||
if v := defTbl.RawGetString("no_memory"); v != nil {
|
||||
chDef.NoMemory = lua.LVAsBool(v)
|
||||
}
|
||||
chDef.ContextPolicy = defTbl.RawGetString("context_policy").String()
|
||||
if v := defTbl.RawGetString("cleaner"); v != nil && v.Type() == lua.LTFunction {
|
||||
chDef.Cleaner = makeLuaCleaner(plg, v.(*lua.LFunction))
|
||||
}
|
||||
return chDef
|
||||
}
|
||||
|
||||
// parseInjectOptions 解析 Lua 侧 options table 为 SDK InjectOptions。
|
||||
// 支持的键:no_memory(bool)、context_policy(string)、cleaner_name(string)、priority(string)。
|
||||
// 缺省/非表等价于零值(记入记忆 + 不裁剪),与旧的三参数注入完全等价。
|
||||
func parseInjectOptions(L *lua.LState, idx int) sdk.InjectOptions {
|
||||
opts := sdk.InjectOptions{}
|
||||
tbl, ok := L.Get(idx).(*lua.LTable)
|
||||
if !ok {
|
||||
return opts
|
||||
}
|
||||
if v := tbl.RawGetString("no_memory"); v != nil {
|
||||
opts.NoMemory = lua.LVAsBool(v)
|
||||
}
|
||||
opts.ContextPolicy = tbl.RawGetString("context_policy").String()
|
||||
opts.CleanerName = tbl.RawGetString("cleaner_name").String()
|
||||
opts.Priority = tbl.RawGetString("priority").String()
|
||||
return opts
|
||||
}
|
||||
|
||||
// luaToContentBlocks 把 Lua 的 blocks 数组解析为 SDK ContentBlock。
|
||||
// 每项形如:
|
||||
//
|
||||
// { type = "text", text = "..." }
|
||||
// { type = "image_url", image_url = { url = "...", detail = "high" } }
|
||||
// { type = "audio_url", audio_url = { url = "..." } }
|
||||
func luaToContentBlocks(L *lua.LState, idx int) []sdk.ContentBlock {
|
||||
tbl, ok := L.Get(idx).(*lua.LTable)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var blocks []sdk.ContentBlock
|
||||
tbl.ForEach(func(_, v lua.LValue) {
|
||||
bt, ok := v.(*lua.LTable)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
b := sdk.ContentBlock{
|
||||
Type: bt.RawGetString("type").String(),
|
||||
Text: bt.RawGetString("text").String(),
|
||||
}
|
||||
if iu, ok := bt.RawGetString("image_url").(*lua.LTable); ok {
|
||||
b.ImageURL = &sdk.ImageURL{
|
||||
URL: iu.RawGetString("url").String(),
|
||||
Detail: iu.RawGetString("detail").String(),
|
||||
}
|
||||
}
|
||||
if au, ok := bt.RawGetString("audio_url").(*lua.LTable); ok {
|
||||
b.AudioURL = &sdk.AudioURL{URL: au.RawGetString("url").String()}
|
||||
}
|
||||
blocks = append(blocks, b)
|
||||
})
|
||||
return blocks
|
||||
}
|
||||
|
||||
// luaToAttachments 把 Lua 附件数组解析为 SDK MediaAttachment。
|
||||
// 每项:{ digest=, mime=, name=, data=<base64 字符串> }。
|
||||
// 带 data 的是新内容(内核落进内容寻址存储),只带 digest 的是引用已有内容。
|
||||
// base64 解码失败时忽略 data(不整单失败)——坏附件不应阻断一条记忆写入。
|
||||
func luaToAttachments(L *lua.LState, val lua.LValue) []sdk.MediaAttachment {
|
||||
tbl, ok := val.(*lua.LTable)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var out []sdk.MediaAttachment
|
||||
tbl.ForEach(func(_, v lua.LValue) {
|
||||
at, ok := v.(*lua.LTable)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a := sdk.MediaAttachment{
|
||||
Digest: at.RawGetString("digest").String(),
|
||||
MIME: at.RawGetString("mime").String(),
|
||||
Name: at.RawGetString("name").String(),
|
||||
}
|
||||
if s := at.RawGetString("data").String(); s != "" {
|
||||
if b, err := base64.StdEncoding.DecodeString(s); err == nil {
|
||||
a.Data = b
|
||||
}
|
||||
}
|
||||
out = append(out, a)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func docFromLua(tbl *lua.LTable) *sdk.Doc {
|
||||
return &sdk.Doc{
|
||||
ID: tbl.RawGetString("id").String(),
|
||||
Title: tbl.RawGetString("title").String(),
|
||||
Content: tbl.RawGetString("content").String(),
|
||||
}
|
||||
}
|
||||
|
||||
// jsonToIface 通过 JSON 往返把任意 Go 值转换为 JSON 兼容的 interface{} 树。
|
||||
func jsonToIface(v interface{}) interface{} {
|
||||
b, err := json.Marshal(v)
|
||||
@ -959,8 +1237,21 @@ func (p *luaPlugin) Start(s *sdk.PluginSDK) error {
|
||||
}
|
||||
|
||||
func (p *luaPlugin) Stop() error {
|
||||
// ① 先取消事件订阅。**不持 p.mu**:Bus.Publish 持总线锁回调 handler,
|
||||
// 而 handler 要 p.mu;若此处持 p.mu 再取总线锁,就是锁序反转死锁。
|
||||
p.subsMu.Lock()
|
||||
subs := p.subs
|
||||
p.subs = nil
|
||||
p.subsMu.Unlock()
|
||||
for _, unsub := range subs {
|
||||
unsub()
|
||||
}
|
||||
|
||||
// ② 置 closed 并关 L。置位在持锁下完成:已进入但等锁的 event 回调
|
||||
// 拿到锁后会先看到 closed 而直接返回,不会碰已关的 L。
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.closed = true
|
||||
|
||||
if p.tbl != nil {
|
||||
fn := p.tbl.RawGetString("stop")
|
||||
|
||||
@ -5,9 +5,10 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
internalConfig "gitcode.com/JianFeeeee/HomeAgent/internal/config"
|
||||
"gitcode.com/JianFeeeee/HomeAgent/internal/events"
|
||||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
func TestTryLoadLua_Basic(t *testing.T) {
|
||||
@ -597,3 +598,66 @@ return plugin
|
||||
t.Errorf("llm_text writeback: got %q, want %q", sc2.LLMText, "模型输出[尾部标记]")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLuaEventsSubscribeAndStopCleanup 覆盖 sdk.events.subscribe:
|
||||
// 1. 订阅真的能收到内核事件(走内部 SDK 的 Subscribe,不是永远为 nil 的公共 Events());
|
||||
// 2. Stop 会取消订阅,之后 Publish 不得再触碰已 Close 的 LState。
|
||||
func TestLuaEventsSubscribeAndStopCleanup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"name":"evlua","entry":"main.lua"}`), 0644)
|
||||
os.WriteFile(filepath.Join(dir, "main.lua"), []byte(`
|
||||
local plugin = { name = "evlua" }
|
||||
|
||||
function plugin.start(sdk)
|
||||
_G.hits = 0
|
||||
local unsub, err = sdk.events.subscribe("agent_output", function(evt)
|
||||
_G.hits = _G.hits + 1
|
||||
_G.last_type = evt.type
|
||||
_G.last_source = evt.source
|
||||
end)
|
||||
_G.sub_err = err
|
||||
_G.unsub_type = type(unsub)
|
||||
end
|
||||
|
||||
function plugin.stop() end
|
||||
return plugin
|
||||
`), 0644)
|
||||
|
||||
plg, err := tryLoadLua(dir, "evlua", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("tryLoadLua failed: %v", err)
|
||||
}
|
||||
lp := plg.(*luaPlugin)
|
||||
|
||||
bus := events.NewBus()
|
||||
reg := internalConfig.NewConfigRegistry("")
|
||||
sett := sdk.NewSettings("evlua", reg)
|
||||
s := sdk.New("evlua", sdk.SDKConfig{EventBus: bus, Settings: sett})
|
||||
|
||||
if err := plg.Start(s); err != nil {
|
||||
t.Fatalf("Start failed: %v", err)
|
||||
}
|
||||
|
||||
L := lp.L
|
||||
if errStr := L.GetGlobal("sub_err").String(); errStr != "nil" {
|
||||
t.Fatalf("subscribe returned error: %s", errStr)
|
||||
}
|
||||
if got := L.GetGlobal("unsub_type").String(); got != "function" {
|
||||
t.Fatalf("subscribe should return an unsubscribe function, got %s", got)
|
||||
}
|
||||
|
||||
bus.Publish(&events.Event{Type: events.EventAgentOutput, Source: "test-src"})
|
||||
if hits := int(lua.LVAsNumber(L.GetGlobal("hits"))); hits != 1 {
|
||||
t.Fatalf("event handler hits = %d, want 1", hits)
|
||||
}
|
||||
if got := L.GetGlobal("last_source").String(); got != "test-src" {
|
||||
t.Fatalf("event source = %q, want test-src", got)
|
||||
}
|
||||
|
||||
// Stop 取消订阅 + 关 L;此后再 Publish 不得 panic / use-after-close。
|
||||
if err := plg.Stop(); err != nil {
|
||||
t.Fatalf("Stop failed: %v", err)
|
||||
}
|
||||
bus.Publish(&events.Event{Type: events.EventAgentOutput, Source: "after-stop"})
|
||||
}
|
||||
|
||||
188
internal/plugin/lua_surface_test.go
Normal file
188
internal/plugin/lua_surface_test.go
Normal file
@ -0,0 +1,188 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
luaSDK "gitcode.com/JianFeeeee/HomeAgent/internal/lua/sdk"
|
||||
sdk "gitcode.com/JianFeeeee/HomeAgent/internal/sdk"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
// TestLuaSDKMockSingleSource 守住「Lua mock 只有一份事实源」。
|
||||
//
|
||||
// 三份 sdk.lua(内核内嵌 / 工具链模板 / 项目副本)历史上各自漂移过,
|
||||
// 表现为「mock 里有的 API,内核运行时是 nil」这类静默失配。
|
||||
// 事实源是 SDK 仓的 sdk/lua/sdk.lua,内核副本由
|
||||
// third_party/homeagent-sdk/scripts/sync-lua-sdk.sh 同步。
|
||||
func TestLuaSDKMockSingleSource(t *testing.T) {
|
||||
canonical, err := os.ReadFile(filepath.Join("..", "..", "third_party", "homeagent-sdk", "sdk", "lua", "sdk.lua"))
|
||||
if err != nil {
|
||||
t.Skipf("SDK repo canonical sdk.lua not available: %v", err)
|
||||
}
|
||||
if string(canonical) != luaSDK.SDKSource {
|
||||
t.Fatal("内核内嵌 sdk.lua 与 SDK 仓 sdk/lua/sdk.lua 不一致;" +
|
||||
"请跑 third_party/homeagent-sdk/scripts/sync-lua-sdk.sh")
|
||||
}
|
||||
}
|
||||
|
||||
var luaMockFuncRe = regexp.MustCompile(`(?m)^function sdk\.([A-Za-z0-9_.]+)\s*\(`)
|
||||
|
||||
// TestLuaBridgeCoversMock 守住「mock 承诺的每个函数,运行时都有绑定」。
|
||||
//
|
||||
// 只查 mock → 运行时这一向:mock 定义了但没绑定,插件会先看到 mock 能调、
|
||||
// 之后内核里是 nil(或反向的假象)。反向(运行时多出未文档化的函数)无害。
|
||||
func TestLuaBridgeCoversMock(t *testing.T) {
|
||||
bridge, err := os.ReadFile("lua_plugin.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read lua_plugin.go: %v", err)
|
||||
}
|
||||
src := string(bridge)
|
||||
|
||||
// 纯 Lua 实现,不经内核绑定。
|
||||
exempt := map[string]bool{"json.encode": true, "json.decode": true}
|
||||
|
||||
matches := luaMockFuncRe.FindAllStringSubmatch(luaSDK.SDKSource, -1)
|
||||
if len(matches) < 40 {
|
||||
t.Fatalf("parsed only %d sdk.* functions from mock; parser likely broken", len(matches))
|
||||
}
|
||||
for _, m := range matches {
|
||||
full := m[1]
|
||||
if exempt[full] {
|
||||
continue
|
||||
}
|
||||
leaf := full
|
||||
if i := strings.LastIndex(full, "."); i >= 0 {
|
||||
leaf = full[i+1:]
|
||||
}
|
||||
if !strings.Contains(src, `RawSetString("`+leaf+`"`) {
|
||||
t.Errorf("sdk.%s: mock 有定义,但 lua_plugin.go 没有 RawSetString(%q) 绑定", full, leaf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func luaTableFrom(t *testing.T, code string) (*lua.LState, *lua.LTable) {
|
||||
t.Helper()
|
||||
L := lua.NewState()
|
||||
if err := L.DoString("return " + code); err != nil {
|
||||
L.Close()
|
||||
t.Fatalf("eval lua table: %v", err)
|
||||
}
|
||||
tbl, ok := L.Get(-1).(*lua.LTable)
|
||||
if !ok {
|
||||
L.Close()
|
||||
t.Fatalf("expected a table from %q", code)
|
||||
}
|
||||
L.Pop(1)
|
||||
return L, tbl
|
||||
}
|
||||
|
||||
func TestLuaParseInjectOptions(t *testing.T) {
|
||||
L, tbl := luaTableFrom(t, `{
|
||||
no_memory = true,
|
||||
context_policy = "prune",
|
||||
cleaner_name = "sanitize",
|
||||
priority = "L2",
|
||||
}`)
|
||||
defer L.Close()
|
||||
|
||||
L.Push(tbl)
|
||||
got := parseInjectOptions(L, 1)
|
||||
L.Pop(1)
|
||||
|
||||
if !got.NoMemory {
|
||||
t.Error("NoMemory should be true")
|
||||
}
|
||||
if got.ContextPolicy != sdk.ContextPolicyPrune {
|
||||
t.Errorf("ContextPolicy = %q, want prune", got.ContextPolicy)
|
||||
}
|
||||
if got.CleanerName != "sanitize" {
|
||||
t.Errorf("CleanerName = %q, want sanitize", got.CleanerName)
|
||||
}
|
||||
if got.Priority != sdk.PriorityL2 {
|
||||
t.Errorf("Priority = %q, want L2", got.Priority)
|
||||
}
|
||||
|
||||
// 缺省/非表 = 零值(记入记忆 + 不裁剪),与旧三参数注入等价。
|
||||
if z := parseInjectOptions(L, 99); z != (sdk.InjectOptions{}) {
|
||||
t.Errorf("missing opts should be zero value, got %#v", z)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaContentBlocksParse(t *testing.T) {
|
||||
L, tbl := luaTableFrom(t, `{
|
||||
{ type = "text", text = "看图" },
|
||||
{ type = "image_url", image_url = { url = "data:image/png;base64,AAAA", detail = "high" } },
|
||||
{ type = "audio_url", audio_url = { url = "https://x/a.mp3" } },
|
||||
}`)
|
||||
defer L.Close()
|
||||
|
||||
L.Push(tbl)
|
||||
blocks := luaToContentBlocks(L, 1)
|
||||
L.Pop(1)
|
||||
|
||||
if len(blocks) != 3 {
|
||||
t.Fatalf("got %d blocks, want 3", len(blocks))
|
||||
}
|
||||
if blocks[0].Type != "text" || blocks[0].Text != "看图" {
|
||||
t.Errorf("block[0] = %#v", blocks[0])
|
||||
}
|
||||
if blocks[1].ImageURL == nil || blocks[1].ImageURL.URL != "data:image/png;base64,AAAA" || blocks[1].ImageURL.Detail != "high" {
|
||||
t.Errorf("block[1] image_url = %#v", blocks[1].ImageURL)
|
||||
}
|
||||
if blocks[2].AudioURL == nil || blocks[2].AudioURL.URL != "https://x/a.mp3" {
|
||||
t.Errorf("block[2] audio_url = %#v", blocks[2].AudioURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaAttachmentsBase64(t *testing.T) {
|
||||
// "hello" 的 base64 是 aGVsbG8=
|
||||
L, tbl := luaTableFrom(t, `{
|
||||
{ digest = "sha256:abc", mime = "image/png", name = "a.png" },
|
||||
{ mime = "image/jpeg", data = "aGVsbG8=" },
|
||||
{ mime = "image/png", data = "!!!not-base64!!!" },
|
||||
}`)
|
||||
defer L.Close()
|
||||
|
||||
atts := luaToAttachments(L, tbl)
|
||||
|
||||
if len(atts) != 3 {
|
||||
t.Fatalf("got %d attachments, want 3", len(atts))
|
||||
}
|
||||
if atts[0].Digest != "sha256:abc" || atts[0].MIME != "image/png" || atts[0].Name != "a.png" || atts[0].Data != nil {
|
||||
t.Errorf("att[0] = %#v", atts[0])
|
||||
}
|
||||
if string(atts[1].Data) != "hello" {
|
||||
t.Errorf("att[1] data = %q, want hello", string(atts[1].Data))
|
||||
}
|
||||
// 坏 base64 只丢 data,不整单失败——坏附件不应阻断记忆写入。
|
||||
if atts[2].Data != nil {
|
||||
t.Errorf("att[2] bad base64 should be dropped, got %q", string(atts[2].Data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLuaDefinitionsCarryContextPolicy(t *testing.T) {
|
||||
L, tbl := luaTableFrom(t, `{
|
||||
description = "t",
|
||||
no_memory = true,
|
||||
context_policy = "prune",
|
||||
}`)
|
||||
defer L.Close()
|
||||
|
||||
plg := &luaPlugin{name: "cp"}
|
||||
def := parseToolDef(L, tbl, plg, "t")
|
||||
if def.ContextPolicy != sdk.ContextPolicyPrune {
|
||||
t.Errorf("ToolDef.ContextPolicy = %q, want prune", def.ContextPolicy)
|
||||
}
|
||||
if !def.NoMemory {
|
||||
t.Error("ToolDef.NoMemory should be true")
|
||||
}
|
||||
|
||||
chDef := parseChannelDef(L, tbl, plg)
|
||||
if chDef.ContextPolicy != sdk.ContextPolicyPrune {
|
||||
t.Errorf("ChannelDef.ContextPolicy = %q, want prune", chDef.ContextPolicy)
|
||||
}
|
||||
}
|
||||
@ -15,7 +15,7 @@ import (
|
||||
type PluginType string
|
||||
|
||||
const (
|
||||
PluginTypeSKILL PluginType = "skill"
|
||||
PluginTypeSKILL PluginType = "skill"
|
||||
)
|
||||
|
||||
type IOConfig struct {
|
||||
@ -78,18 +78,28 @@ func LoadSKILL(path string) (*SKILLPlugin, error) {
|
||||
metaFile := filepath.Join(path, "skill.json")
|
||||
if data, err := os.ReadFile(metaFile); err == nil {
|
||||
var meta struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Version string `json:"version"`
|
||||
Author string `json:"author"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Version string `json:"version"`
|
||||
Author string `json:"author"`
|
||||
IO *IOConfig `json:"io,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &meta); err == nil {
|
||||
if meta.Name != "" { p.name = meta.Name }
|
||||
if meta.Description != "" { p.description = meta.Description }
|
||||
if meta.Version != "" { p.version = meta.Version }
|
||||
if meta.Author != "" { p.author = meta.Author }
|
||||
if meta.IO != nil { p.ioConfig = meta.IO }
|
||||
if meta.Name != "" {
|
||||
p.name = meta.Name
|
||||
}
|
||||
if meta.Description != "" {
|
||||
p.description = meta.Description
|
||||
}
|
||||
if meta.Version != "" {
|
||||
p.version = meta.Version
|
||||
}
|
||||
if meta.Author != "" {
|
||||
p.author = meta.Author
|
||||
}
|
||||
if meta.IO != nil {
|
||||
p.ioConfig = meta.IO
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if filepath.Ext(path) == ".md" {
|
||||
@ -198,7 +208,9 @@ func extractToolDefs(content string) []ToolDef {
|
||||
inCodeBlock = !inCodeBlock
|
||||
continue
|
||||
}
|
||||
if inCodeBlock { continue }
|
||||
if inCodeBlock {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(trimmed, "## ") && !strings.HasPrefix(trimmed, "### ") {
|
||||
if currentTool != nil && currentTool.Name != "" {
|
||||
@ -232,7 +244,9 @@ func extractToolDefs(content string) []ToolDef {
|
||||
continue
|
||||
}
|
||||
|
||||
if currentTool == nil || currentTool.Name == "" { continue }
|
||||
if currentTool == nil || currentTool.Name == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if currentTool.Description == "" && trimmed != "" &&
|
||||
!strings.HasPrefix(trimmed, "- ") && !strings.HasPrefix(trimmed, "#") {
|
||||
@ -280,7 +294,9 @@ func isNonToolSection(name string) bool {
|
||||
|
||||
func extractIOConfig(content string) *IOConfig {
|
||||
ioType := extractField(content, "io_type")
|
||||
if ioType == "" { return nil }
|
||||
if ioType == "" {
|
||||
return nil
|
||||
}
|
||||
cfg := &IOConfig{
|
||||
Type: ioType,
|
||||
InputRoute: extractField(content, "io_input_route"),
|
||||
|
||||
@ -307,12 +307,15 @@ func (r *Registry) buildSDK(name string) *sdk.PluginSDK {
|
||||
// 但历史插件常常只用 RegisterOutputChannel 声明(却用同一个名字注入输入,
|
||||
// 例:cli 只声明输出 "cli" 就用 InjectTextSync("cli", ...) 注入)。
|
||||
// 不兜底的话 inputch 登记表里没有它,"把 inputch 划给驻留子"直接失败
|
||||
// (实测报 `划入 inputch cli: inputch 未注册`)。兜底要**留痕**,
|
||||
// 否则插件作者永远不知道该补一行 RegisterInputChannel。
|
||||
// (实测报 `划入 inputch cli: inputch 未注册`)。
|
||||
//
|
||||
// ❗这里**不能**判"是否声明过入站通道"并告警:声明顺序是自由的,
|
||||
// 先 RegisterOutputChannel 再 RegisterInputChannel 是常见写法(qq 就是),
|
||||
// 按此刻的状态判会对它误报(实测:把 qq 报成"只声明了输出通道")。
|
||||
// 真正该问的问题是"插件 Start 结束后,这个出站通道有没有对应的入站声明" ——
|
||||
// 那在 load 完成后统一判(见 warnOutputOnlyChannels)。
|
||||
if _, ok := r.iom.LookupInputChannel(chName); !ok {
|
||||
_ = r.iom.RegisterInputChannelFrom(name, chName, agentIO.ChannelDef(def))
|
||||
log.Printf("[plugin] %s 只声明了输出通道 %q,已按双向通道兜底登记 inputch;"+
|
||||
"若要明确意图请显式 RegisterInputChannel", name, chName)
|
||||
}
|
||||
r.noteChannel(name, chName, true)
|
||||
return nil
|
||||
@ -452,6 +455,7 @@ func (r *Registry) Load(dir string) error {
|
||||
r.pluginAutoRestart[name] = plgSDK.AutoRestart()
|
||||
r.instances = append(r.instances, p)
|
||||
r.mu.Unlock()
|
||||
r.warnOutputOnlyChannels(name)
|
||||
log.Printf("[plugin] loaded: %s", name)
|
||||
}
|
||||
|
||||
@ -545,6 +549,7 @@ func (r *Registry) loadOne(plgDir, name string) bool {
|
||||
r.pluginAutoRestart[name] = plgSDK.AutoRestart()
|
||||
r.sdkRefs[name] = plgSDK
|
||||
r.instances = append(r.instances, plg)
|
||||
r.warnOutputOnlyChannels(name)
|
||||
if h := pluginEntryHash(plgDir); h != "" {
|
||||
r.pluginHashes[name] = h
|
||||
} else {
|
||||
@ -579,6 +584,31 @@ func (r *Registry) stageRegistrarFor() (func(plugin string, stage sdk.Stage, han
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// warnOutputOnlyChannels 在插件 Start 结束后,报告"只声明了出站、没有入站声明"的通道。
|
||||
//
|
||||
// 为什么放在 Start 之后:声明顺序自由(先出站后入站很常见),注册时刻的状态
|
||||
// 判不出意图。这里看的是**插件最终声明了什么**,因此不会误报 qq 这种写法。
|
||||
//
|
||||
// 注:这类通道内核已兜底登记 inputch(功能可用),告警只是提醒插件作者把意图写明。
|
||||
func (r *Registry) warnOutputOnlyChannels(plugin string) {
|
||||
r.channelsMu.Lock()
|
||||
set := r.pluginChannels[plugin]
|
||||
var only []string
|
||||
if set != nil {
|
||||
for ch := range set.outputs {
|
||||
if !set.inputs[ch] {
|
||||
only = append(only, ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
r.channelsMu.Unlock()
|
||||
sort.Strings(only)
|
||||
for _, ch := range only {
|
||||
log.Printf("[plugin] %s 只声明了出站通道 %q(未 RegisterInputChannel);"+
|
||||
"内核已兜底登记 inputch,若这是有意为之可忽略", plugin, ch)
|
||||
}
|
||||
}
|
||||
|
||||
// noteChannel 记住插件注册了哪个通道,供卸载/崩溃时摘除。
|
||||
// forgetChannel 把某个通道从"本插件注册过哪些通道"的记账里摘掉(注销通道时用)。
|
||||
//
|
||||
|
||||
@ -138,28 +138,39 @@ func (p *Plugin) Stop() error {
|
||||
func (p *Plugin) registerTools(s *sdk.PluginSDK) {
|
||||
s.RegisterTool("plugin_install", sdk.ToolDef{
|
||||
Name: "plugin_install",
|
||||
Description: "从 URL 安装 HomeAgent 插件包(.hmap 文件)。插件已存在时传 overwrite=true 原地更新(升级/降级/重装,保留配置表,无需卸载重装)。更新后需调用 plgreload 或重启生效。",
|
||||
Description: "安装 HomeAgent 插件包(.hmap)。两种来源:url(http/https 下载)或 path(本机路径,配合 plugindev_build 的产物用这个)。插件已存在时传 overwrite=true 原地更新(升级/降级/重装,保留配置表,无需卸载重装)。更新后需调用 plgreload 或重启生效。",
|
||||
Parameters: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"url": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "插件包的下载 URL",
|
||||
"description": "插件包的下载 URL(http/https)",
|
||||
},
|
||||
"path": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "插件包在**本机**的路径(.hmap)。与 url 二选一;同时给出时以 path 为准",
|
||||
},
|
||||
"overwrite": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "已存在时原地更新(保留配置)。默认 false",
|
||||
},
|
||||
},
|
||||
"required": []string{"url"},
|
||||
},
|
||||
}, func(args map[string]interface{}) (interface{}, error) {
|
||||
url, _ := args["url"].(string)
|
||||
if url == "" {
|
||||
return map[string]interface{}{"error": "url is required"}, nil
|
||||
}
|
||||
overwrite, _ := args["overwrite"].(bool)
|
||||
return p.installFromURL(url, overwrite)
|
||||
// path 优先:它对应"agent 自己构建出产物再装"的场景(plugindev_build → plugin_install)。
|
||||
if path, _ := args["path"].(string); strings.TrimSpace(path) != "" {
|
||||
pth := strings.TrimSpace(path)
|
||||
if st, err := os.Stat(pth); err != nil || st.IsDir() {
|
||||
return map[string]interface{}{"error": fmt.Sprintf("path 无效(必须是存在的 .hmap 文件): %s", pth)}, nil
|
||||
}
|
||||
return p.installFromPath(pth, overwrite)
|
||||
}
|
||||
url, _ := args["url"].(string)
|
||||
if strings.TrimSpace(url) == "" {
|
||||
return map[string]interface{}{"error": "需要 url 或 path(二选一)"}, nil
|
||||
}
|
||||
return p.installFromURL(strings.TrimSpace(url), overwrite)
|
||||
})
|
||||
|
||||
s.RegisterTool("plugin_list", sdk.ToolDef{
|
||||
@ -455,12 +466,12 @@ func (p *Plugin) installFromData(data []byte, overwrite bool) (interface{}, erro
|
||||
|
||||
if existing && !overwrite {
|
||||
return map[string]interface{}{
|
||||
"error": "plugin already exists",
|
||||
"name": pkg.Name,
|
||||
"version": pkg.Version,
|
||||
"current": oldVersion,
|
||||
"action": "remove_first",
|
||||
"hint": `传 "overwrite": true 可原地更新(保留配置)`,
|
||||
"error": "plugin already exists",
|
||||
"name": pkg.Name,
|
||||
"version": pkg.Version,
|
||||
"current": oldVersion,
|
||||
"action": "remove_first",
|
||||
"hint": `传 "overwrite": true 可原地更新(保留配置)`,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -475,7 +486,7 @@ func (p *Plugin) installFromData(data []byte, overwrite bool) (interface{}, erro
|
||||
os.RemoveAll(backup)
|
||||
if err := os.Rename(target, backup); err != nil {
|
||||
return map[string]interface{}{
|
||||
"error": "backup old plugin dir failed",
|
||||
"error": "backup old plugin dir failed",
|
||||
"details": err.Error(),
|
||||
}, nil
|
||||
}
|
||||
@ -484,8 +495,8 @@ func (p *Plugin) installFromData(data []byte, overwrite bool) (interface{}, erro
|
||||
os.RemoveAll(target)
|
||||
if rbErr := os.Rename(backup, target); rbErr != nil {
|
||||
return map[string]interface{}{
|
||||
"error": "extract failed AND rollback failed",
|
||||
"details": err.Error(),
|
||||
"error": "extract failed AND rollback failed",
|
||||
"details": err.Error(),
|
||||
"rollback": rbErr.Error(),
|
||||
}, nil
|
||||
}
|
||||
@ -507,15 +518,15 @@ func (p *Plugin) installFromData(data []byte, overwrite bool) (interface{}, erro
|
||||
action = "reinstalled"
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"status": "installed",
|
||||
"name": pkg.Name,
|
||||
"version": pkg.Version,
|
||||
"status": "installed",
|
||||
"name": pkg.Name,
|
||||
"version": pkg.Version,
|
||||
"previous_version": oldVersion,
|
||||
"entry": pkg.Entry,
|
||||
"checksum": checksum,
|
||||
"action": action,
|
||||
"reload_required": true,
|
||||
"config_kept": true,
|
||||
"entry": pkg.Entry,
|
||||
"checksum": checksum,
|
||||
"action": action,
|
||||
"reload_required": true,
|
||||
"config_kept": true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
package remotedevice
|
||||
|
||||
// 设备输出通道:把"agent 主动发给设备"做成**每设备一个输出通道** `device/<id>`。
|
||||
// 设备输出通道:把"agent 主动发给设备"做成**每设备一个输出通道** `device-<id>`。
|
||||
//
|
||||
// 为什么是输出通道而不是再加一批工具:
|
||||
// - **寻址**:`output_send__device/<id>` 直接指名道姓;模型看 `output_list_channels`
|
||||
// - **寻址**:`output_send__device-<id>` 直接指名道姓;模型看 `output_list_channels`
|
||||
// 就知道当前有哪些设备在线,不必先 `devicedetect` 再往参数里塞 device_id。
|
||||
// - **能力**:caps 由设备声明的 caps 映射,**内核**在发送前就按 caps 拦
|
||||
// (把图片发给只支持文本的音箱会被拒,而不是等设备侧报错)。
|
||||
@ -15,7 +15,9 @@ package remotedevice
|
||||
// 它们的返回值(图像/命令输出/状态)必须进模型上下文,做成通道会丢掉这个语义。
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
@ -76,14 +78,75 @@ func deviceOutputCaps(caps []string, kind string) agentIO.OutputCapability {
|
||||
return out
|
||||
}
|
||||
|
||||
// deviceChannelName 是设备输出(也是输入)通道名:`device/<id>`。
|
||||
// deviceChannelName 由**设备自报的 id** 派生一个合规且唯一的通道名:`device-<派生值>`。
|
||||
//
|
||||
// 入站与出站**同名**:两者指的是同一台设备,分成两个名字只会让模型与授权表更难对。
|
||||
func deviceChannelName(id string) string { return "device/" + id }
|
||||
//
|
||||
// 为什么不能直接用 id:通道名会被内核拼进 LLM 的**函数名**(`output_send__<通道名>`),
|
||||
// 上游规范是 `^[a-zA-Z0-9_-]{1,64}$`;而设备 id 是**外部输入**(设备自己声明),
|
||||
// 可能含空格/非 ASCII/超长。违规的后果不是"这个工具不能用",而是**整条请求被 400 拒绝** ——
|
||||
// 实测把生产打挂:`Invalid 'tools[299].function.name'`,网关 auto tier 全链条失败,
|
||||
// 内核只能报"所有 provider 都失败",表现成"整个 agent 不说话了"。
|
||||
//
|
||||
// 派生规则(确定性,同一 id 永远同名):
|
||||
// 1. 保留 [A-Za-z0-9_-],其它字符折成 '-';折叠后为空则用 "dev"
|
||||
// 2. 截断到 maxDeviceChannelSuffix 字符(给 "device-" 与短哈希留余量)
|
||||
// 3. 若发生截断,或该名字已被**另一个** id 占用,则追加 id 的 6 位短哈希
|
||||
//
|
||||
// 设备 id 本身仍用于路由与日志(真名不丢),通道名只是它派生的标识符。
|
||||
func (p *Plugin) deviceChannelName(id string) string {
|
||||
p.devChansMu.Lock()
|
||||
defer p.devChansMu.Unlock()
|
||||
if p.devChans == nil {
|
||||
p.devChans = make(map[string]string)
|
||||
}
|
||||
if name, ok := p.devChans[id]; ok {
|
||||
return name
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, r := range id {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '_', r == '-':
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteByte('-')
|
||||
}
|
||||
}
|
||||
base := b.String()
|
||||
if base == "" {
|
||||
base = "dev"
|
||||
}
|
||||
truncated := false
|
||||
if len(base) > maxDeviceChannelSuffix {
|
||||
base = base[:maxDeviceChannelSuffix]
|
||||
truncated = true
|
||||
}
|
||||
name := "device-" + base
|
||||
// 撞名检查:不同 id 折出同一个名字时必须可区分
|
||||
for otherID, otherName := range p.devChans {
|
||||
if otherName == name && otherID != id {
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
sum := sha1.Sum([]byte(id))
|
||||
name += "-" + hex.EncodeToString(sum[:3])
|
||||
}
|
||||
p.devChans[id] = name
|
||||
return name
|
||||
}
|
||||
|
||||
const (
|
||||
// maxDeviceChannelSuffix 是通道名主体的长度上限。
|
||||
// 预算:上游函数名上限 64 = "output_send__"(13) + "device-"(7) + 主体 + "-"+短哈希(7)
|
||||
// ⇒ 主体最多 37;取 32 留余量(改名/前缀变动不会立刻越界)。
|
||||
maxDeviceChannelSuffix = 32
|
||||
)
|
||||
|
||||
// wireDeviceChannels 把"设备上下线"接到通道的登记/注销上。
|
||||
//
|
||||
// 一台设备 = 一对**同名**通道 `device/<id>`:入站(设备上报 → agent)与出站
|
||||
// 一台设备 = 一对**同名**通道 `device-<id>`:入站(设备上报 → agent)与出站
|
||||
// (agent → 设备)。用**同步回调**而不是 ChangeChan(后者是 select+default,
|
||||
// 缓冲满会丢事件;丢一次就留下死通道或漏注册)。
|
||||
//
|
||||
@ -92,14 +155,14 @@ func deviceChannelName(id string) string { return "device/" + id }
|
||||
func (p *Plugin) wireDeviceChannels() {
|
||||
p.registry.SetPresenceHandler(
|
||||
func(meta DeviceMeta) {
|
||||
_ = p.sdk.RegisterInputChannel(deviceChannelName(meta.DeviceID), sdk.ChannelDef{})
|
||||
_ = p.sdk.RegisterInputChannel(p.deviceChannelName(meta.DeviceID), sdk.ChannelDef{})
|
||||
p.ensureDeviceOutputChannel(meta.DeviceID)
|
||||
},
|
||||
func(id string) { p.dropDeviceOutputChannel(id) },
|
||||
)
|
||||
}
|
||||
|
||||
// ensureDeviceOutputChannel 给在线设备注册输出通道 device/<id>(幂等)。
|
||||
// ensureDeviceOutputChannel 给在线设备注册输出通道 device-<id>(幂等)。
|
||||
func (p *Plugin) ensureDeviceOutputChannel(id string) {
|
||||
if p.sdk == nil || id == "" {
|
||||
return
|
||||
@ -108,7 +171,7 @@ func (p *Plugin) ensureDeviceOutputChannel(id string) {
|
||||
if !ok || !meta.Online {
|
||||
return
|
||||
}
|
||||
ch := deviceChannelName(id)
|
||||
ch := p.deviceChannelName(id)
|
||||
caps := deviceOutputCaps(meta.Caps, meta.Kind)
|
||||
desc := fmt.Sprintf("远程设备 %s(%s):agent 主动向该设备发送内容;能力位 %s",
|
||||
id, fallback(meta.Name, meta.Kind), agentIO.OutputCapability(caps).String())
|
||||
@ -130,7 +193,7 @@ func (p *Plugin) dropDeviceOutputChannel(id string) {
|
||||
if p.sdk == nil || id == "" {
|
||||
return
|
||||
}
|
||||
ch := deviceChannelName(id)
|
||||
ch := p.deviceChannelName(id)
|
||||
if err := p.sdk.UnregisterOutputChannel(ch); err != nil {
|
||||
p.logf("unregister output channel %s: %v", ch, err)
|
||||
return
|
||||
@ -247,9 +310,9 @@ func (d *devicectlDevice) output(args map[string]interface{}) (interface{}, erro
|
||||
ids = append(ids, m.DeviceID)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, fmt.Errorf("devicectl 需要 meta.device_id 才能投递;当前没有在线设备(device_list_channels 可看每台设备的 device/<id> 通道)")
|
||||
return nil, fmt.Errorf("devicectl 需要 meta.device_id 才能投递;当前没有在线设备(device_list_channels 可看每台设备的 device-<id> 通道)")
|
||||
}
|
||||
return nil, fmt.Errorf("devicectl 需要 meta.device_id(或直接用通道 device/<id>);当前在线设备: %s", strings.Join(ids, ", "))
|
||||
return nil, fmt.Errorf("devicectl 需要 meta.device_id(或直接用通道 device-<id>);当前在线设备: %s", strings.Join(ids, ", "))
|
||||
}
|
||||
return pushToDevice(d.reg, deviceID, args)
|
||||
}
|
||||
|
||||
@ -9,6 +9,8 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@ -130,7 +132,7 @@ func TestDeviceChannelLifecycleAndPush(t *testing.T) {
|
||||
cli.sendText([]byte(`{"op":"hello","device":{"device_id":"spk-1","name":"音箱","kind":"speaker","caps":["speaker"]}}`))
|
||||
cli.readHelloAckAndBind(t, token)
|
||||
|
||||
ch := deviceChannelName("spk-1")
|
||||
ch := p.deviceChannelName("spk-1")
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
caps, ok := rec.caps(ch)
|
||||
for !ok && time.Now().Before(deadline) {
|
||||
@ -255,3 +257,31 @@ func TestDevicectlAggregateOutputAddressing(t *testing.T) {
|
||||
t.Fatal("不存在的设备应报错")
|
||||
}
|
||||
}
|
||||
|
||||
// 通道名合规性:设备通道名会被内核拼进 LLM **函数名**(output_send__<通道名>),
|
||||
// 而上游函数名规范是 ^[a-zA-Z0-9_-]{1,64}$ —— 违规会让**整条请求**被 400 拒绝
|
||||
// (实测把生产打挂:device/<id> 里的 `/` 触发 Invalid 'tools[299].function.name',
|
||||
// 网关 auto tier 全链条失败,整个 agent 不说话了)。
|
||||
//
|
||||
// 通道名是**插件自己的声明**,所以这条判据钉在插件侧。
|
||||
func TestDeviceChannelNameIsLLMFunctionNameSafe(t *testing.T) {
|
||||
re := regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)
|
||||
// 含**恶意/异常** id:空格、符号、非 ASCII、超长、以及会折成同一个名字的两个 id
|
||||
ids := []string{"waiter-fnnas", "1", "a b!c", "中文设备", strings.Repeat("x", 120), "a b", "a-b"}
|
||||
p := &Plugin{}
|
||||
seen := map[string]string{}
|
||||
for _, id := range ids {
|
||||
ch := p.deviceChannelName(id)
|
||||
if prev, dup := seen[ch]; dup {
|
||||
t.Errorf("不同设备 id(%q 与 %q)派生出同一个通道名 %q", prev, id, ch)
|
||||
}
|
||||
seen[ch] = id
|
||||
if !re.MatchString(ch) {
|
||||
t.Errorf("设备通道名 %q 违反上游函数名规范 %s", ch, re)
|
||||
}
|
||||
toolName := "output_send__" + ch
|
||||
if !re.MatchString(toolName) {
|
||||
t.Errorf("派生出的工具名 %q 违反上游函数名规范 %s", toolName, re)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,6 +37,11 @@ type Plugin struct {
|
||||
token string
|
||||
sdk *sdk.PluginSDK
|
||||
dev *devicectlDevice
|
||||
|
||||
// devChansMu/devChans 维护"设备自报 id → 派生的通道名"。
|
||||
// 设备 id 是外部输入,不能直接进通道名(见 outputch.go 的 deviceChannelName)。
|
||||
devChansMu sync.Mutex
|
||||
devChans map[string]string
|
||||
}
|
||||
|
||||
func New(name string) *Plugin {
|
||||
@ -124,7 +129,7 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||
//
|
||||
// **注意**:agent 的输出**不会**被自动转回设备 —— 主动转发只有 webui 与 cli 两个
|
||||
// 交互界面(它们把最终回复渲染成对话气泡是本职)。设备要走
|
||||
// `output_send__device/<id>`(agent 主动调用),这才与"输出是 agent 的主动调用"一致。
|
||||
// `output_send__device-<id>`(agent 主动调用),这才与"输出是 agent 的主动调用"一致。
|
||||
// 节流:同设备同类型事件 10s 内去重,防传感器风暴。
|
||||
lastEventAt := map[string]time.Time{}
|
||||
var eventMu sync.Mutex
|
||||
@ -159,9 +164,10 @@ func (p *Plugin) Start(s *sdk.PluginSDK) error {
|
||||
|
||||
log.Printf("[remotedevice] event from %s: %s", deviceID, evtType)
|
||||
if p.sdk != nil {
|
||||
// 设备通道 device/<id> 是动态的:设备首次上报时**懒登记** inputch
|
||||
// (Register 幂等),父 agent 才能把它划给驻留子。
|
||||
devCh := "device/" + deviceID
|
||||
// 设备通道 device-<id> 是动态的(分隔符用 - 而非 /,见 deviceChannelName 的说明:
|
||||
// 通道名会进 LLM 函数名,必须满足 ^[a-zA-Z0-9_-]{1,64}$)。
|
||||
// 首次上报时**懒登记** inputch(Register 幂等),父 agent 才能把它划给驻留子。
|
||||
devCh := p.deviceChannelName(deviceID)
|
||||
_ = p.sdk.RegisterInputChannel(devCh, sdk.ChannelDef{})
|
||||
// 异步注入:不阻塞 WS 读循环;回复路由回 device/{id} 输出通道
|
||||
p.sdk.InjectInput(devCh, devCh, "text", map[string]interface{}{"content": text})
|
||||
|
||||
@ -287,7 +287,7 @@ func (r *Registry) register(meta DeviceMeta) {
|
||||
r.devices[meta.DeviceID] = &meta
|
||||
onOnline := r.onOnline
|
||||
r.mu.Unlock()
|
||||
// 先回调(可能注册 device/<id> 输出通道),再发变更通知。
|
||||
// 先回调(可能注册 device-<id> 输出通道),再发变更通知。
|
||||
if onOnline != nil {
|
||||
onOnline(meta)
|
||||
}
|
||||
|
||||
403
third_party/homeagent-sdk/sdk/lua/sdk.lua
vendored
Normal file
403
third_party/homeagent-sdk/sdk/lua/sdk.lua
vendored
Normal file
@ -0,0 +1,403 @@
|
||||
-- HomeAgent Lua Plugin SDK
|
||||
-- Interface contract between Lua plugins and HomeAgent kernel.
|
||||
-- !impl functions are replaced by Go implementations at runtime.
|
||||
-- Standalone/debug: pure Lua mock implementations are used.
|
||||
-- Usage: local sdk = require("sdk")
|
||||
|
||||
sdk = {}
|
||||
|
||||
-- !impl
|
||||
-- level: "debug" | "info" | "warn" | "error"
|
||||
function sdk.log(level, msg)
|
||||
print("[lua-plugin] " .. tostring(level) .. ": " .. tostring(msg))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- def: { description="...", parameters={...}, no_memory=true/false, cleaner=function(text)->text }
|
||||
-- handler: function(args) -> result
|
||||
function sdk.register_tool(name, def, handler)
|
||||
print("[lua-plugin] register_tool: " .. tostring(name))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- stage: "on_input" | "pre_action" | "post_action" | ...
|
||||
-- scope: nil/"global" (默认) | "own_tools"(仅 before_toolcall/after_toolcall 且工具属于本插件时触发)
|
||||
function sdk.register_stage(stage, handler, scope)
|
||||
print("[lua-plugin] register_stage: " .. tostring(stage) .. " scope=" .. tostring(scope))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.register_api(name)
|
||||
print("[lua-plugin] register_api: " .. tostring(name))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- def: { no_memory=true/false, cleaner=function(text)->text }
|
||||
-- handler: function(args) -> result
|
||||
function sdk.register_output_channel(name, caps, desc, def, handler)
|
||||
print("[lua-plugin] register_output_channel: " .. tostring(name))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- def: { no_memory=true/false, cleaner=function(text)->text }
|
||||
function sdk.register_input_channel(name, def)
|
||||
print("[lua-plugin] register_input_channel: " .. tostring(name))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.get_setting(key)
|
||||
return nil
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.set_setting(key, value)
|
||||
print("[lua-plugin] set_setting: " .. tostring(key))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_text(source, channel, text)
|
||||
print("[lua-plugin] inject_text: " .. tostring(source) .. "/" .. tostring(channel))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt(source, channel, text)
|
||||
print("[lua-plugin] inject_interrupt: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_text_no_memory(source, channel, text)
|
||||
print("[lua-plugin] inject_text_no_memory: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- opts: { no_memory=bool, context_policy="none"|"prune", cleaner_name=string, priority="L1".."L3" }
|
||||
-- 零值/缺省 = 记入记忆 + 不裁剪(与三参数版本等价)。
|
||||
function sdk.inject_text_opts(source, channel, text, opts)
|
||||
print("[lua-plugin] inject_text_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_opts(source, channel, text, opts)
|
||||
print("[lua-plugin] inject_interrupt_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- 同步注入:等待本轮回复 -> (reply, err);无回复时 reply 为 nil。
|
||||
function sdk.inject_input_sync(source, channel, text) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_sync_opts(source, channel, text, opts) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
-- blocks: ContentBlock 数组,见 sdk.inject_input_media。
|
||||
-- 设置下一轮 tool message 携带的多模态内容块(模型据此看图/听音频)。
|
||||
function sdk.set_tool_blocks(blocks)
|
||||
print("[lua-plugin] set_tool_blocks: " .. tostring(blocks and #blocks or 0))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- blocks 每项:{ type="text", text="..." }
|
||||
-- | { type="image_url", image_url={ url="...", detail="high" } }
|
||||
-- | { type="audio_url", audio_url={ url="..." } }
|
||||
function sdk.inject_input_media(source, channel, text, blocks)
|
||||
print("[lua-plugin] inject_input_media: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_opts(source, channel, text, blocks, opts)
|
||||
print("[lua-plugin] inject_input_media_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_sync(source, channel, text, blocks) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_input_media_sync_opts(source, channel, text, blocks, opts) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_media(source, channel, text, blocks)
|
||||
print("[lua-plugin] inject_interrupt_media: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.inject_interrupt_media_opts(source, channel, text, blocks, opts)
|
||||
print("[lua-plugin] inject_interrupt_media_opts: " .. tostring(source))
|
||||
end
|
||||
|
||||
-- !impl
|
||||
-- 注销输出通道(随资源生灭的动态通道,如远程设备)。返回 (nil, err)。
|
||||
function sdk.unregister_output_channel(name) return nil, nil end
|
||||
|
||||
-- !impl
|
||||
-- enabled: true/false,崩溃时内核自动拉起
|
||||
function sdk.set_auto_restart(enabled)
|
||||
print("[lua-plugin] set_auto_restart: " .. tostring(enabled))
|
||||
end
|
||||
|
||||
-- ============ graph memory ============
|
||||
-- !impl
|
||||
sdk.memory = {}
|
||||
-- !impl
|
||||
-- query: string, depth: number -> {entities={...}, relations={...}}
|
||||
function sdk.memory.recall(query, depth) return {entities={}, relations={}} end
|
||||
-- !impl
|
||||
-- triples: { {subject=, relation=, object=, [confidence=], [sentence_text=]} } -> err
|
||||
function sdk.memory.commit(triples) return nil end
|
||||
-- !impl
|
||||
function sdk.memory.introspect() return {} end
|
||||
-- !impl
|
||||
function sdk.memory.merge(source, target) return 0 end
|
||||
-- !impl
|
||||
-- criteria: {key=value}, hard: boolean
|
||||
function sdk.memory.purge(criteria, hard) return 0 end
|
||||
|
||||
-- ============ document memory ============
|
||||
-- !impl
|
||||
sdk.doc = {}
|
||||
-- !impl
|
||||
function sdk.doc.query(text, top_k) return {} end
|
||||
-- !impl
|
||||
-- doc: { id=, title=, content= }
|
||||
function sdk.doc.insert(doc) return nil end
|
||||
-- !impl
|
||||
-- attachments 每项:{ digest=, mime=, name=, data=<base64> }
|
||||
function sdk.doc.insert_with_media(doc, attachments) return nil end
|
||||
-- !impl
|
||||
function sdk.doc.remove(id) return nil end
|
||||
-- !impl
|
||||
function sdk.doc.stats() return {} end
|
||||
|
||||
-- ============ knowledge ============
|
||||
-- !impl
|
||||
sdk.knowledge = {}
|
||||
-- !impl
|
||||
function sdk.knowledge.search(query, limit) return {} end
|
||||
-- !impl
|
||||
function sdk.knowledge.add(tag, content) return nil end
|
||||
-- !impl
|
||||
function sdk.knowledge.list() return {} end
|
||||
|
||||
-- ============ text memory ============
|
||||
-- !impl
|
||||
sdk.text_memory = {}
|
||||
-- !impl
|
||||
-- evt: { timestamp=, role=, content=, channel= }
|
||||
function sdk.text_memory.append(evt) return nil end
|
||||
|
||||
-- ============ llm ============
|
||||
-- !impl
|
||||
sdk.llm = {}
|
||||
-- !impl
|
||||
function sdk.llm.list_sources() return {} end
|
||||
-- !impl
|
||||
function sdk.llm.set_source(name) return nil end
|
||||
-- !impl
|
||||
function sdk.llm.current_source() return nil end
|
||||
|
||||
-- ============ social (只读) ============
|
||||
-- !impl
|
||||
sdk.social = {}
|
||||
-- !impl
|
||||
function sdk.social.get_person(name) return {} end
|
||||
-- !impl
|
||||
function sdk.social.get_network(name, depth) return {} end
|
||||
-- !impl
|
||||
function sdk.social.get_trait(name, trait) return {value=nil, found=false} end
|
||||
-- !impl
|
||||
function sdk.social.get_relations(name) return {} end
|
||||
-- !impl
|
||||
function sdk.social.list_persons() return {} end
|
||||
|
||||
-- ============ settings (作用域变体) ============
|
||||
-- !impl
|
||||
sdk.settings = {}
|
||||
-- !impl
|
||||
function sdk.settings.get_core(key) return nil end
|
||||
-- !impl
|
||||
function sdk.settings.set_core(key, value) return nil end
|
||||
-- !impl
|
||||
function sdk.settings.list_core(prefix) return {} end
|
||||
-- !impl
|
||||
function sdk.settings.get_plugin(plugin, key) return nil end
|
||||
-- !impl
|
||||
function sdk.settings.set_plugin(plugin, key, value) return nil end
|
||||
-- !impl
|
||||
function sdk.settings.list_plugin(plugin, prefix) return {} end
|
||||
-- !impl
|
||||
function sdk.settings.list(prefix) return {} end
|
||||
-- !impl
|
||||
-- def: { key=, type=, display_name=, description=, category=, options=, default=,
|
||||
-- min=, max=, step=, required=, secret= }
|
||||
function sdk.settings.register_def(def) return nil end
|
||||
-- !impl
|
||||
function sdk.settings.defs(prefix) return {} end
|
||||
-- !impl
|
||||
function sdk.settings.dump() return {} end
|
||||
-- !impl
|
||||
function sdk.settings.plugins() return {} end
|
||||
|
||||
-- ============ events(只读订阅) ============
|
||||
-- !impl
|
||||
-- subscribe(event_type, handler) -> unsubscribe()
|
||||
-- handler 收到 { type=, source=, timestamp=, payload= };
|
||||
-- 回调在其内核事件发布 goroutine 上执行,只做轻量转发,不可阻塞(Lua 单状态 + 互斥锁)。
|
||||
sdk.events = {}
|
||||
function sdk.events.subscribe(event_type, handler)
|
||||
print("[lua-plugin] events.subscribe: " .. tostring(event_type))
|
||||
return function() end
|
||||
end
|
||||
|
||||
-- ============ plugin_mgr ============
|
||||
-- !impl
|
||||
sdk.plugin_mgr = {}
|
||||
function sdk.plugin_mgr.reload_one(name) return nil end
|
||||
function sdk.plugin_mgr.list_loaded() return {} end
|
||||
function sdk.plugin_mgr.is_disabled(name) return false end
|
||||
|
||||
-- json utils (pure Lua)
|
||||
sdk.json = {}
|
||||
|
||||
function sdk.json.encode(val)
|
||||
local ok, result = pcall(function()
|
||||
local function _encode(v)
|
||||
local t = type(v)
|
||||
if t == "string" then
|
||||
local s = v:gsub('\\', '\\\\'):gsub('"', '\\"'):gsub('\n', '\\n'):gsub('\r', '\\r'):gsub('\t', '\\t')
|
||||
return '"' .. s .. '"'
|
||||
elseif t == "number" then
|
||||
return tostring(v)
|
||||
elseif t == "boolean" then
|
||||
return tostring(v)
|
||||
elseif t == "table" then
|
||||
local keys = {}
|
||||
local is_array = true
|
||||
local maxn = 0
|
||||
for k in pairs(v) do
|
||||
keys[#keys + 1] = k
|
||||
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then
|
||||
is_array = false
|
||||
end
|
||||
if type(k) == "number" and k > maxn then maxn = k end
|
||||
end
|
||||
if is_array and #keys >= maxn then
|
||||
local parts = {}
|
||||
for i = 1, maxn do
|
||||
parts[#parts + 1] = _encode(v[i])
|
||||
end
|
||||
return "[" .. table.concat(parts, ",") .. "]"
|
||||
else
|
||||
local parts = {}
|
||||
for _, k in ipairs(keys) do
|
||||
parts[#parts + 1] = _encode(tostring(k)) .. ":" .. _encode(v[k])
|
||||
end
|
||||
return "{" .. table.concat(parts, ",") .. "}"
|
||||
end
|
||||
else
|
||||
return "null"
|
||||
end
|
||||
end
|
||||
return _encode(val)
|
||||
end)
|
||||
if ok then return result end
|
||||
return "null"
|
||||
end
|
||||
|
||||
function sdk.json.decode(str)
|
||||
local ok, result = pcall(function()
|
||||
local pos, _end = 1, #str
|
||||
local function skip()
|
||||
while pos <= _end and str:sub(pos, pos):match("%s") do pos = pos + 1 end
|
||||
end
|
||||
local function parse()
|
||||
skip()
|
||||
if pos > _end then return nil end
|
||||
local c = str:sub(pos, pos)
|
||||
if c == '"' then
|
||||
local s = {}
|
||||
pos = pos + 1
|
||||
while pos <= _end do
|
||||
local ch = str:sub(pos, pos)
|
||||
if ch == '"' then
|
||||
pos = pos + 1
|
||||
return table.concat(s)
|
||||
elseif ch == '\\' then
|
||||
pos = pos + 1
|
||||
local n = str:sub(pos, pos)
|
||||
if n == '"' then s[#s+1] = '"'
|
||||
elseif n == '\\' then s[#s+1] = '\\'
|
||||
elseif n == '/' then s[#s+1] = '/'
|
||||
elseif n == 'b' then s[#s+1] = '\b'
|
||||
elseif n == 'f' then s[#s+1] = '\f'
|
||||
elseif n == 'n' then s[#s+1] = '\n'
|
||||
elseif n == 'r' then s[#s+1] = '\r'
|
||||
elseif n == 't' then s[#s+1] = '\t'
|
||||
elseif n == 'u' then
|
||||
local hex = str:sub(pos+1, pos+4)
|
||||
pos = pos + 4
|
||||
s[#s+1] = utf8 and utf8.char(tonumber(hex, 16)) or '?'
|
||||
end
|
||||
pos = pos + 1
|
||||
else
|
||||
s[#s+1] = ch
|
||||
pos = pos + 1
|
||||
end
|
||||
end
|
||||
return table.concat(s)
|
||||
elseif c == 't' then pos = pos + 4; return true
|
||||
elseif c == 'f' then pos = pos + 5; return false
|
||||
elseif c == 'n' then pos = pos + 4; return nil
|
||||
elseif c == '{' then
|
||||
pos = pos + 1; skip()
|
||||
local t = {}
|
||||
if str:sub(pos, pos) == '}' then pos = pos + 1; return t end
|
||||
while true do
|
||||
skip(); local k = parse(); skip()
|
||||
if str:sub(pos, pos) == ':' then pos = pos + 1 end
|
||||
skip(); t[k] = parse(); skip()
|
||||
local sep = str:sub(pos, pos)
|
||||
if sep == '}' then pos = pos + 1; return t end
|
||||
if sep == ',' then pos = pos + 1 end
|
||||
end
|
||||
elseif c == '[' then
|
||||
pos = pos + 1; skip()
|
||||
local t = {}
|
||||
if str:sub(pos, pos) == ']' then pos = pos + 1; return t end
|
||||
local idx = 1
|
||||
while true do
|
||||
skip(); t[idx] = parse(); idx = idx + 1; skip()
|
||||
local sep = str:sub(pos, pos)
|
||||
if sep == ']' then pos = pos + 1; return t end
|
||||
if sep == ',' then pos = pos + 1 end
|
||||
end
|
||||
else
|
||||
local s, e = str:find('^[-%d%.eE]+', pos)
|
||||
if s then
|
||||
local num = tonumber(str:sub(s, e))
|
||||
pos = e + 1
|
||||
return num
|
||||
end
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return parse()
|
||||
end)
|
||||
if ok then return result end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- http utils
|
||||
sdk.http = {}
|
||||
|
||||
-- !impl
|
||||
function sdk.http.get(url)
|
||||
print("[lua-plugin] http.get: " .. tostring(url))
|
||||
return {status=200, body='{"mock":true}', headers={}}
|
||||
end
|
||||
|
||||
-- !impl
|
||||
function sdk.http.post(url, body, content_type)
|
||||
print("[lua-plugin] http.post: " .. tostring(url))
|
||||
return {status=200, body='{"mock":true}', headers={}}
|
||||
end
|
||||
|
||||
return sdk
|
||||
10
third_party/homeagent-sdk/sdk/plugin.go
vendored
10
third_party/homeagent-sdk/sdk/plugin.go
vendored
@ -480,7 +480,15 @@ func (s *PluginSDK) RegisterPluginAPI(name string) error {
|
||||
// 入站(谁会往 <name> 注入输入)是另一件事,用 RegisterInputChannel 声明。
|
||||
// 若该通道同时也是你的注入入口,两个都要登记。
|
||||
//
|
||||
// name: channel name (e.g. "qq", "webui")
|
||||
// name: channel name (e.g. "qq", "webui")。
|
||||
//
|
||||
// ❗**命名约束**:内核会把通道名拼进 LLM 的函数名(`output_send__<name>`),
|
||||
// 而上游对函数名的规范是 `^[a-zA-Z0-9_-]{1,64}$`。违反的后果不是"这个工具不可用",
|
||||
// 而是**整条请求被上游 400 拒绝**(`Invalid 'tools[N].function.name'`),
|
||||
// 网关的 auto tier 会全链条失败 —— 表现成"整个 agent 不说话了"。
|
||||
// 所以通道名只能用 `[A-Za-z0-9_-]`,且总长要留出 `output_send__`(13 字符)的余量。
|
||||
// 若通道名来自外部输入(设备自报 id 之类),请**在插件侧派生一个合规且唯一的名字**,
|
||||
// 而不是把原始值直接当通道名。
|
||||
// caps: bitmask of supported output capabilities (CapText, CapFile, etc.)
|
||||
// desc: description of the channel, expected meta format, and type enum
|
||||
// def: 通道在记忆计算层的行为(NoMemory/Cleaner)
|
||||
|
||||
Reference in New Issue
Block a user