diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f98d51d..a1bc35f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,9 +13,17 @@ jobs: - uses: actions/checkout@v4 with: repository: lendevs/LenBot - ref: e62815a5cbbc2c4f8460450ad13f50359cf64f89 + ref: 078d91e0a69948755f6b81dec89aab15842a9fae path: host-source - run: uv python install 3.13 - run: uv venv --python 3.13 - run: uv pip install ./host-source pytest pytest-asyncio - - run: uv run --no-sync pytest -q plugin/tests + - name: Install declared plugin dependencies + run: | + uv run --no-project --python .venv/bin/python python -c 'import pathlib,tomllib; data=tomllib.loads(pathlib.Path("plugin/plugin.toml").read_text()); pathlib.Path("plugin-requirements.txt").write_text("\n".join(data.get("dependencies", [])))' + uv pip install --requirements plugin-requirements.txt + - run: uv run --no-project --python ../.venv/bin/python python -m pytest -q --confcutdir=tests + working-directory: plugin + - name: Check runtime ZIP resources + run: uv run --no-project --python ../.venv/bin/python python scripts/package.py "$RUNNER_TEMP/plugin.zip" + working-directory: plugin diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8a80e73..4fdff09 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,9 +9,13 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v5 + with: + version: "0.12.13" + - run: uv python install 3.13 - name: Package plugin - run: zip -r "counter-${GITHUB_REF_NAME}.zip" plugin.toml __init__.py README.md README.en.md LICENSE + run: uv run --no-project --python 3.13 python scripts/package.py "plugin-${GITHUB_REF_NAME}.zip" - name: Publish ZIP env: GH_TOKEN: ${{ github.token }} - run: gh release create "$GITHUB_REF_NAME" "counter-${GITHUB_REF_NAME}.zip" --verify-tag --generate-notes + run: gh release create "$GITHUB_REF_NAME" "plugin-${GITHUB_REF_NAME}.zip" --verify-tag --notes-file CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d5dd6f2 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 1.1.0 + +适配 LenBot 首版 0.2.0 的插件接口 1:显式工具简介、参数说明、按需共享指南与 JSON 结果。使用新增接口的版本需要包含插件生态改造的最终 0.2.0 基线;早期同版本开发提交不支持。 + +保留原插件名、配置和业务数据,无需数据迁移。与旧宿主共同回退时须使用原插件版本。当前为未发行开发版本;只提交源码,不创建版本标签或 Release。 + +模板保留查询和后台发送两个工具,增加按业务能力合并与严格 action 分支的作者说明;本次仍是开发改动,未创建标签或 Release。 diff --git a/README.en.md b/README.en.md index a6459c6..77adaa2 100644 --- a/README.en.md +++ b/README.en.md @@ -39,3 +39,7 @@ See `developer/plugins-v1.en.md` in the host repository for the interface, lifec ## License The template is [GPL-3.0-only](LICENSE). The LenBot host is AGPL-3.0-only and plugins run in the host process, so GPL-3.0 is the recommended plugin license; if you choose another license, check its compatibility with GPLv3 and AGPLv3. + +Tool interface 1 now uses explicit discovery summaries, shared `prompts/tools.md` instructions and native JSON results. `counter_read` returns data; `counter_card` starts background model generation and sends the completed text itself. Use `PluginTest.preview_tools()` to inspect the actual schemas. Tests do not call a model unless `models=` is explicitly provided. See CHANGELOG.md for the final 0.2.0 host baseline requirement. + +Group tools by user capability rather than HTTP endpoint. Keep data lookup and actual delivery separate. Use a discriminated request union for related search/detail operations, with strict models forbidding unrelated fields. Inspect both the discovery catalog and loaded schema: fewer names alone do not guarantee smaller context. This template retains two useful capabilities. diff --git a/README.md b/README.md index fb0a1a2..755a8f0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,8 @@ - `/计数`:读当前群的计数。 - `计数加一`:按配置里的 `step` 增加。 - `/计数清零`:清零。 -- 工具 `counter_read`:返回当前群的计数,不发消息。 +- 工具 `counter_read`:返回当前群的计数 JSON,不发消息。 +- 工具 `counter_card`:后台生成计数说明后自行发送;需要宿主配置模型。 计数按群分开存,更新插件源码不会清掉。 @@ -39,3 +40,19 @@ uv run --no-sync pytest -q tests ## 许可证 模板采用 [GPL-3.0-only](LICENSE)。LenBot 宿主采用 AGPL-3.0-only,插件和宿主运行在同一个进程里,推荐插件也使用 GPL-3.0;改用其他许可证前请确认它与 GPLv3/AGPLv3 兼容。 + +## 工具接口 + +工具采用接口 1 的显式简介、Field 参数说明与 `prompts/tools.md` 共享指南,返回原生 JSON 或文本。用 `PluginTest.preview_tools()` 查看模型说明、参数与可用性;模型服务默认关闭,真实发送仍单独核对。兼容和更新事项见 [CHANGELOG](CHANGELOG.md)。 + +CI 固定到包含当前插件接口的宿主开发提交;本次未创建版本标签或 Release。catalog-entry.json 只记录开发安装来源,未公开插件不加入主目录。 + +本机生成 ZIP:`uv run --no-project --python 3.13 python scripts/package.py /tmp/plugin.zip`。打包取 Git 已跟踪的运行源码和资源,新增文件需先加入 Git;不会收录本机环境、测试或配置。 + +## 工具数量与能力边界 + +本模板保留两个工具:counter_read 查询 JSON;counter_card 开始后台生成并自行发送。两种结果语义不同,所以分别暴露。不要为每个 HTTP 端点、列表页、详情页或随机选项再加一个工具。 + +同一能力需要多种操作时,可用 `request: Annotated[SearchRequest | ReadRequest, Field(discriminator="action")]`;各 Request 继承配置 `ConfigDict(strict=True, extra="forbid")` 的 BaseModel,并分别声明 `action: Literal["search"]`/`Literal["read"]` 和所需字段。列表、详情使用同一工具;查询和真实发送/账号写入保持清楚的边界。不要堆一组互斥可选参数。 + +用 PluginTest.preview_tools() 核对实际工具数、发现目录、共享指南与每个操作的 schema。工具数量减少不等于 schema 一定减少,检查目录和真实加载内容;已有生成 title 在模型参数中去掉,Field 的说明、示例和约束保留。 diff --git a/__init__.py b/__init__.py index eff130c..a80a8c8 100644 --- a/__init__.py +++ b/__init__.py @@ -1,7 +1,5 @@ """A copyable plugin using only the public interface.""" -import json - from len_bot.next.plugin import Invocation, Plugin, command, fullmatch, tool @@ -28,7 +26,18 @@ async def reset(self, ctx: Invocation, args: str) -> None: await ctx.delete_kv(ctx.scene) await self.show(ctx) - @tool('counter_read', '读取当前群计数,不修改计数、不发送消息') - async def read(self, ctx: Invocation) -> str: - return json.dumps({'label': ctx.config['label'], 'count': await ctx.get_kv(ctx.scene, 0)}, - ensure_ascii=False) + @tool('counter_read', '读取当前群计数,不修改计数、不发送消息', summary='查询本群当前计数') + async def read(self, ctx: Invocation) -> dict: + return {'label': ctx.config['label'], 'count': await ctx.get_kv(ctx.scene, 0)} + + @tool('counter_card', '在后台用模型生成本群计数的简短说明,完成后插件自行发到本群。' + '调用只表示开始,不能声称已经发送;不修改计数。', summary='后台生成并发送本群计数说明') + async def card(self, ctx: Invocation) -> dict: + count = await ctx.get_kv(ctx.scene, 0) + self.ctx.start_task('counter-card', self._card(ctx.scene, count)) + return {'status': 'started', 'delivery': 'plugin', 'count': count} + + async def _card(self, scene: str, count: int) -> None: + text = await self.ctx.generate(scene, f"用一句话说明本群计数为 {count}。") + sent = await self.ctx.send(scene, text) + await self.ctx.emit_event(scene, f"计数说明发送结果:{sent.status};{sent.report}") diff --git a/catalog-entry.json b/catalog-entry.json new file mode 100644 index 0000000..6014f9c --- /dev/null +++ b/catalog-entry.json @@ -0,0 +1,25 @@ +{ + "name": "counter", + "title": "插件模板", + "description": "每群独立计数:命令直接回复、只读 JSON 查询、按需后台模型说明与自行发送。", + "authors": [ + "LEN5010" + ], + "license": "GPL-3.0-only", + "version": "1.1.0", + "interface": 1, + "requires_lenbot": ">=0.2,<1", + "category": "开发示例", + "capabilities": [ + "JSON 查询", + "后台生成与发送" + ], + "usage": [ + "配置后选择启用的群;模型工具需要当前角色许可。", + "参数、共享指南与实际发送语义可在群聊工具页预览。", + "最低宿主基线和来源参数变更见 CHANGELOG.md。" + ], + "install": "git", + "repository": "https://github.com/lendevs/lenbot-plugin-template", + "ref": "main" +} diff --git a/plugin.toml b/plugin.toml index 12ed94c..ba98bd4 100644 --- a/plugin.toml +++ b/plugin.toml @@ -1,13 +1,16 @@ name = "counter" -version = "1.0.0" +version = "1.1.0" interface = 1 -requires_lenbot = ">=0.1,<1" +requires_lenbot = ">=0.2,<1" requires_python = ">=3.13" platforms = ["linux", "darwin", "win32"] reload = "plugin" authors = ["LEN5010"] license = "GPL-3.0-only" -description = "每群独立计数:命令和全文规则直接回复,另提供只读工具,不主动调用模型。" +description = "每群独立计数:命令直接回复、只读 JSON 查询、按需后台模型说明与自行发送。" + +[model] +instructions = "prompts/tools.md" [config.label] type = "string" diff --git a/prompts/tools.md b/prompts/tools.md new file mode 100644 index 0000000..74e7f4e --- /dev/null +++ b/prompts/tools.md @@ -0,0 +1 @@ +counter_read 查询当前群计数,返回 JSON 数据,不发送。counter_card 启动后台模型生成,完成后插件自行发到本群;返回 started 不是已送达,不重复发送。计数加一和清零使用明确命令;各群业务数据独立。 diff --git a/scripts/package.py b/scripts/package.py new file mode 100644 index 0000000..bfc1b41 --- /dev/null +++ b/scripts/package.py @@ -0,0 +1,24 @@ +"""Build a plugin ZIP from tracked runtime files without publishing it.""" +from pathlib import Path +import subprocess +import sys +import tomllib +from zipfile import ZIP_DEFLATED, ZipFile + +root = Path(__file__).resolve().parents[1] +manifest = tomllib.loads((root / 'plugin.toml').read_text()) +output = Path(sys.argv[1]).resolve() +output.parent.mkdir(parents=True, exist_ok=True) +files = subprocess.check_output(['git', 'ls-files', '-z'], cwd=root).decode().split('\0') +with ZipFile(output, 'w', ZIP_DEFLATED) as archive: + for name in sorted(filter(None, files)): + path = Path(name) + if path.parts[0] in {'prompts', 'skills', 'assets', 'fonts'} or len(path.parts) == 1 and ( + path.suffix in {'.py', '.toml', '.md'} or path.name in {'LICENSE', 'NOTICE'}): + if path.name not in {'pyproject.toml', 'AGENTS.md'}: + archive.write(root / path, name) +with ZipFile(output) as archive: + instructions = manifest.get('model', {}).get('instructions') + if instructions is not None and instructions not in archive.namelist(): + raise ValueError(f'model.instructions resource is not tracked: {instructions}') +print(output) diff --git a/tests/test_counter.py b/tests/test_counter.py index 6865dc8..f6dd07c 100644 --- a/tests/test_counter.py +++ b/tests/test_counter.py @@ -18,3 +18,43 @@ async def test_counter_keeps_scenes_separate_and_uses_saved_step(): assert json.loads(await bot.tool('counter_read', {}, scene=scenes[1]))['count'] == 0 assert await bot.message('/计数清零', scene=scenes[0]) assert json.loads(await bot.tool('counter_read', {}, scene=scenes[0]))['count'] == 0 + + +@pytest.mark.asyncio +async def test_background_generation_uses_explicit_model_protocol_and_simulated_send(): + import asyncio + import re + calls = [] + + async def respond(reader, writer): + headers = await reader.readuntil(b'\r\n\r\n') + length = int(re.search(rb'content-length:\s*(\d+)', headers, re.I)[1]) + request = json.loads(await reader.readexactly(length)) + calls.append(request) + body = json.dumps({'id': 'synthetic', 'object': 'chat.completion', 'created': 1234567890, + 'model': 'local', 'choices': [{'index': 0, 'message': {'role': 'assistant', + 'content': '当前计数为 2。'}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': 20, 'completion_tokens': 10, 'total_tokens': 30}}).encode() + writer.write(b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: ' + + str(len(body)).encode() + b'\r\nConnection: close\r\n\r\n' + body) + await writer.drain() + writer.close() + await writer.wait_closed() + + server = await asyncio.start_server(respond, '127.0.0.1', 0) + url = f'http://127.0.0.1:{server.sockets[0].getsockname()[1]}/v1' + models = {'providers': {'local': {'api': 'openai-chat', 'base_url': url, 'api_key': 'synthetic'}}, + 'roles': {'mind': {'provider': 'local', 'model': 'local', 'context_window_tokens': 8192}}} + async with server, PluginTest(Path(__file__).parents[1], config={'step': 2}, + now=lambda: 1234567890, models=models) as bot: + preview = {item['name']: item for item in bot.preview_tools()} + assert {'counter_read', 'counter_card'} == preview.keys() + assert all(item['summary'] and item['instructions'] for item in preview.values()) + await bot.message('计数加一') + result = json.loads(await bot.tool('counter_card', {})) + assert result == {'status': 'started', 'delivery': 'plugin', 'count': 2} + await bot.wait_tasks('counter-card') + assert len(calls) == 1 and '2' in calls[0]['messages'][-1]['content'] + assert bot.deliveries[-1].text == '当前计数为 2。' + assert bot.deliveries[-1].status == 'simulated' + assert bot.events()