fae-plugin-py 0.1.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fae_plugin_py-0.3.0/PKG-INFO +102 -0
- fae_plugin_py-0.3.0/README.md +83 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/pyproject.toml +1 -1
- fae_plugin_py-0.3.0/src/fae_plugin/__init__.py +26 -0
- fae_plugin_py-0.3.0/src/fae_plugin/_host.py +64 -0
- fae_plugin_py-0.3.0/src/fae_plugin/_inspect.py +42 -0
- fae_plugin_py-0.3.0/src/fae_plugin/_protocol.py +257 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/_worker.py +150 -62
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/chain.py +4 -2
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/config.py +3 -1
- fae_plugin_py-0.3.0/src/fae_plugin/context.py +77 -0
- fae_plugin_py-0.3.0/src/fae_plugin/data.py +417 -0
- fae_plugin_py-0.3.0/src/fae_plugin/errors.py +75 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/registration.py +3 -1
- fae_plugin_py-0.3.0/src/fae_plugin/session.py +42 -0
- fae_plugin_py-0.3.0/src/fae_plugin/types.py +131 -0
- fae_plugin_py-0.3.0/src/fae_plugin_py.egg-info/PKG-INFO +102 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin_py.egg-info/SOURCES.txt +1 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/tests/test_sdk.py +176 -72
- fae_plugin_py-0.1.0/PKG-INFO +0 -300
- fae_plugin_py-0.1.0/README.md +0 -281
- fae_plugin_py-0.1.0/src/fae_plugin/__init__.py +0 -19
- fae_plugin_py-0.1.0/src/fae_plugin/_host.py +0 -55
- fae_plugin_py-0.1.0/src/fae_plugin/_inspect.py +0 -30
- fae_plugin_py-0.1.0/src/fae_plugin/_protocol.py +0 -57
- fae_plugin_py-0.1.0/src/fae_plugin/context.py +0 -175
- fae_plugin_py-0.1.0/src/fae_plugin/errors.py +0 -96
- fae_plugin_py-0.1.0/src/fae_plugin/session.py +0 -42
- fae_plugin_py-0.1.0/src/fae_plugin/types.py +0 -464
- fae_plugin_py-0.1.0/src/fae_plugin_py.egg-info/PKG-INFO +0 -300
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/LICENSE +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/setup.cfg +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/engine.py +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/hooks.py +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin/py.typed +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin_py.egg-info/dependency_links.txt +0 -0
- {fae_plugin_py-0.1.0 → fae_plugin_py-0.3.0}/src/fae_plugin_py.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fae-plugin-py
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Typed Python plugins for the FAE agent engine
|
|
5
|
+
Author-email: Teshin <1443965173@qq.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/woshihaoren4/free-agent-engine
|
|
8
|
+
Project-URL: Documentation, https://github.com/woshihaoren4/free-agent-engine/tree/v2-plugins/python/fae-plugin-py
|
|
9
|
+
Project-URL: Issues, https://github.com/woshihaoren4/free-agent-engine/issues
|
|
10
|
+
Keywords: fae,agent,plugins,sdk
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# fae-plugin-py
|
|
21
|
+
|
|
22
|
+
FAE Agent Engine 的类型化 Python 插件 SDK,支持 Agent、工具和模型钩子,
|
|
23
|
+
以及执行上下文读取、Session 输出和子调用。
|
|
24
|
+
|
|
25
|
+
需要 Python 3.10 或更新版本。SDK 的发行版本与插件 API 版本分别管理;
|
|
26
|
+
当前插件 API 为 `0.2.0`,使用公共 v4 协议,需要对应版本的 FAE 宿主。
|
|
27
|
+
|
|
28
|
+
## 安装
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python3 -m pip install fae-plugin-py
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
在仓库根目录进行本地开发:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
python3 -m pip install -e ./python/fae-plugin-py
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
将 SDK 安装到宿主使用的 Python 解释器中。若使用虚拟环境,在启动 FAE 服务前
|
|
41
|
+
设置 `FAE_PLUGIN_PYTHON` 为该环境的 Python 路径。
|
|
42
|
+
|
|
43
|
+
## 最小 Agent 插件
|
|
44
|
+
|
|
45
|
+
保存为 `project_context.py`:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from fae_plugin import Context, SingleAgentHook, TextContent
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def plugin_config() -> dict:
|
|
52
|
+
return {
|
|
53
|
+
"plugin_version": "1.0.0",
|
|
54
|
+
"fae_plugin_api_version": "0.2.0",
|
|
55
|
+
"description": "清理输入并补充项目规范",
|
|
56
|
+
"mounts": [{
|
|
57
|
+
"point": "SingleAgentHook",
|
|
58
|
+
"implementation": "ProjectContext",
|
|
59
|
+
"agent_id": "fae",
|
|
60
|
+
}],
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ProjectContext(SingleAgentHook):
|
|
65
|
+
async def on_query(self, ctx: Context, query: str) -> str:
|
|
66
|
+
if ctx.session is not None:
|
|
67
|
+
await ctx.session.send([TextContent("开始处理请求。")])
|
|
68
|
+
return query.strip()
|
|
69
|
+
|
|
70
|
+
async def on_prompt(self, ctx: Context, prompt: str) -> str:
|
|
71
|
+
return prompt + "\n遵守当前项目的代码规范。"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
安装插件并使用已配置的 `fae` Agent:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
fae plugin install ./project_context.py
|
|
78
|
+
fae agent --agent-id fae
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
目录插件通过 `plugin.config` 声明挂载点,`implementation` 使用
|
|
82
|
+
`plugin.py:ClassName` 格式;单文件插件通过同步的 `plugin_config()` 返回配置。
|
|
83
|
+
|
|
84
|
+
## 主要接口
|
|
85
|
+
|
|
86
|
+
- `SingleAgentHook`:处理输入、提示词、记忆、历史、模型请求与响应、工具请求与响应。
|
|
87
|
+
- `ToolsHook`:实现 `desc` 和 `exec`,提供工具描述和执行结果。
|
|
88
|
+
- `ModelHook`:实现 `match_model` 和 `exec`,提供模型响应。
|
|
89
|
+
- `ChainSingleAgentHook`、`ChainToolsHook`、`ChainModelHook`:通过 `HookNext`
|
|
90
|
+
将调用传给后续插件,配置 `registration_mode: "chain"`。
|
|
91
|
+
- `Context`:通过 `read_summary()` 和 `export_context()` 读取公共上下文;
|
|
92
|
+
`execution_id` 和 `invocation_id` 标识当前调用。
|
|
93
|
+
- `Session.send()`:发送由 `TextContent`、`JsonContent` 或 `ResourceContent`
|
|
94
|
+
组成的内容,并返回输出回执;Session 可能为空,使用前需检查。
|
|
95
|
+
- `Context.complete_query(text)`:在 `on_query` 的原始上下文中发送最终回答并结束执行;
|
|
96
|
+
此方法不返回,后续查询钩子和模型任务不会继续执行。
|
|
97
|
+
|
|
98
|
+
## 示例与源码
|
|
99
|
+
|
|
100
|
+
完整示例见 [插件示例](https://github.com/woshihaoren4/free-agent-engine/tree/v2-plugins/examples/plugin)
|
|
101
|
+
和 [SDK 示例](https://github.com/woshihaoren4/free-agent-engine/tree/v2-plugins/python/fae-plugin-py/examples)。
|
|
102
|
+
项目使用 Apache-2.0 许可证。
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# fae-plugin-py
|
|
2
|
+
|
|
3
|
+
FAE Agent Engine 的类型化 Python 插件 SDK,支持 Agent、工具和模型钩子,
|
|
4
|
+
以及执行上下文读取、Session 输出和子调用。
|
|
5
|
+
|
|
6
|
+
需要 Python 3.10 或更新版本。SDK 的发行版本与插件 API 版本分别管理;
|
|
7
|
+
当前插件 API 为 `0.2.0`,使用公共 v4 协议,需要对应版本的 FAE 宿主。
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
python3 -m pip install fae-plugin-py
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
在仓库根目录进行本地开发:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
python3 -m pip install -e ./python/fae-plugin-py
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
将 SDK 安装到宿主使用的 Python 解释器中。若使用虚拟环境,在启动 FAE 服务前
|
|
22
|
+
设置 `FAE_PLUGIN_PYTHON` 为该环境的 Python 路径。
|
|
23
|
+
|
|
24
|
+
## 最小 Agent 插件
|
|
25
|
+
|
|
26
|
+
保存为 `project_context.py`:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from fae_plugin import Context, SingleAgentHook, TextContent
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def plugin_config() -> dict:
|
|
33
|
+
return {
|
|
34
|
+
"plugin_version": "1.0.0",
|
|
35
|
+
"fae_plugin_api_version": "0.2.0",
|
|
36
|
+
"description": "清理输入并补充项目规范",
|
|
37
|
+
"mounts": [{
|
|
38
|
+
"point": "SingleAgentHook",
|
|
39
|
+
"implementation": "ProjectContext",
|
|
40
|
+
"agent_id": "fae",
|
|
41
|
+
}],
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ProjectContext(SingleAgentHook):
|
|
46
|
+
async def on_query(self, ctx: Context, query: str) -> str:
|
|
47
|
+
if ctx.session is not None:
|
|
48
|
+
await ctx.session.send([TextContent("开始处理请求。")])
|
|
49
|
+
return query.strip()
|
|
50
|
+
|
|
51
|
+
async def on_prompt(self, ctx: Context, prompt: str) -> str:
|
|
52
|
+
return prompt + "\n遵守当前项目的代码规范。"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
安装插件并使用已配置的 `fae` Agent:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
fae plugin install ./project_context.py
|
|
59
|
+
fae agent --agent-id fae
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
目录插件通过 `plugin.config` 声明挂载点,`implementation` 使用
|
|
63
|
+
`plugin.py:ClassName` 格式;单文件插件通过同步的 `plugin_config()` 返回配置。
|
|
64
|
+
|
|
65
|
+
## 主要接口
|
|
66
|
+
|
|
67
|
+
- `SingleAgentHook`:处理输入、提示词、记忆、历史、模型请求与响应、工具请求与响应。
|
|
68
|
+
- `ToolsHook`:实现 `desc` 和 `exec`,提供工具描述和执行结果。
|
|
69
|
+
- `ModelHook`:实现 `match_model` 和 `exec`,提供模型响应。
|
|
70
|
+
- `ChainSingleAgentHook`、`ChainToolsHook`、`ChainModelHook`:通过 `HookNext`
|
|
71
|
+
将调用传给后续插件,配置 `registration_mode: "chain"`。
|
|
72
|
+
- `Context`:通过 `read_summary()` 和 `export_context()` 读取公共上下文;
|
|
73
|
+
`execution_id` 和 `invocation_id` 标识当前调用。
|
|
74
|
+
- `Session.send()`:发送由 `TextContent`、`JsonContent` 或 `ResourceContent`
|
|
75
|
+
组成的内容,并返回输出回执;Session 可能为空,使用前需检查。
|
|
76
|
+
- `Context.complete_query(text)`:在 `on_query` 的原始上下文中发送最终回答并结束执行;
|
|
77
|
+
此方法不返回,后续查询钩子和模型任务不会继续执行。
|
|
78
|
+
|
|
79
|
+
## 示例与源码
|
|
80
|
+
|
|
81
|
+
完整示例见 [插件示例](https://github.com/woshihaoren4/free-agent-engine/tree/v2-plugins/examples/plugin)
|
|
82
|
+
和 [SDK 示例](https://github.com/woshihaoren4/free-agent-engine/tree/v2-plugins/python/fae-plugin-py/examples)。
|
|
83
|
+
项目使用 Apache-2.0 许可证。
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from .data import (
|
|
2
|
+
ContextData, ContextSummary, SessionSummary, UserInfo, SessionConfig, MemoryView,
|
|
3
|
+
MemorySummary, ExecutionView, ExecutionSummary, ExecutionSettings, ExecutionOptions,
|
|
4
|
+
ExecutionStatus, ExecutionOutcome, InvocationView, InvocationStatus, InputRecord,
|
|
5
|
+
InputStatus, ModelRef, DefinitionRef, WorkspaceBinding, WorkspaceFileView,
|
|
6
|
+
ContentBlock, TextContent, JsonContent, ResourceContent, ResourceRef, ErrorInfo,
|
|
7
|
+
AgentTarget, WorkflowTarget, Succeeded, Failed, Cancelled,
|
|
8
|
+
TuiBinding, LarkBinding, SdkBinding, ChannelBinding,
|
|
9
|
+
ContextStack, ContextStackQuery, ContextStackPhase, TaskMeta, AnyTaskType,
|
|
10
|
+
SessionMessageRole, UserMemoryCategory, UserMemoryConfidence,
|
|
11
|
+
)
|
|
12
|
+
from .types import (
|
|
13
|
+
API_VERSION, JsonValue, RegistrationMode, ContextChildSpec, OutputReceipt,
|
|
14
|
+
ModelRequest, ModelResponse, ToolRequest, ToolResponse, SessionMessage, UserMemory,
|
|
15
|
+
)
|
|
16
|
+
from .context import Context
|
|
17
|
+
from .session import Session
|
|
18
|
+
from .engine import Engine
|
|
19
|
+
from .hooks import SingleAgentHook, ToolsHook, ModelHook
|
|
20
|
+
from .chain import ChainSingleAgentHook, ChainToolsHook, ChainModelHook, HookNext
|
|
21
|
+
from .errors import (
|
|
22
|
+
PluginHostError, ContextUnavailable, ContextFinished, HandleExpired,
|
|
23
|
+
UnsupportedValueType, SessionBusy, SessionUnavailable, InvalidMessage,
|
|
24
|
+
HostCallTimeout, HookCancelled, InvalidHookNext, MissingChainHandler,
|
|
25
|
+
ResponseCode,
|
|
26
|
+
)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import itertools
|
|
3
|
+
from typing import Any
|
|
4
|
+
from ._protocol import request
|
|
5
|
+
from .errors import HandleExpired, HostCallTimeout, from_wire
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Host:
|
|
9
|
+
def __init__(self, writer: Any):
|
|
10
|
+
self.writer = writer
|
|
11
|
+
self.pending: dict[str, tuple[dict[str, Any], asyncio.Future[Any]]] = {}
|
|
12
|
+
self.ids = itertools.count()
|
|
13
|
+
|
|
14
|
+
async def call(self, call: Any, member: str, path: str, params: dict[str, Any],
|
|
15
|
+
request_id: str | None = None) -> Any:
|
|
16
|
+
call.check()
|
|
17
|
+
if len(self.pending) >= 256:
|
|
18
|
+
raise from_wire({"code": 409, "msg": "Host request capacity exceeded"})
|
|
19
|
+
request_id = request_id or f"host-{next(self.ids)}"
|
|
20
|
+
if request_id in self.pending:
|
|
21
|
+
raise ValueError("request_id already in flight")
|
|
22
|
+
reference = call.params["contexts"][member]
|
|
23
|
+
message = request(request_id, path, params, reference.get("session_id"))
|
|
24
|
+
future = asyncio.get_running_loop().create_future()
|
|
25
|
+
self.pending[request_id] = (message, future)
|
|
26
|
+
try:
|
|
27
|
+
await self.writer.send(message, control=True)
|
|
28
|
+
try:
|
|
29
|
+
return await asyncio.wait_for(future, call.remaining())
|
|
30
|
+
except asyncio.TimeoutError:
|
|
31
|
+
raise HostCallTimeout("Host request exceeded call deadline") from None
|
|
32
|
+
finally:
|
|
33
|
+
self.pending.pop(request_id, None)
|
|
34
|
+
|
|
35
|
+
def response(self, frame: dict[str, Any]) -> None:
|
|
36
|
+
pending = self.pending.get(frame["request_id"])
|
|
37
|
+
if pending is None:
|
|
38
|
+
return
|
|
39
|
+
message, future = pending
|
|
40
|
+
if future.done():
|
|
41
|
+
return
|
|
42
|
+
if frame["path"] != message["path"].replace("/request/", "/response/", 1) or frame.get("session_id") != message.get("session_id"):
|
|
43
|
+
future.set_exception(ValueError("Response binding mismatch"))
|
|
44
|
+
elif frame["payload"]["code"] != 0:
|
|
45
|
+
future.set_exception(from_wire(frame["payload"]))
|
|
46
|
+
else:
|
|
47
|
+
future.set_result(frame["payload"]["data"])
|
|
48
|
+
|
|
49
|
+
def close(self) -> None:
|
|
50
|
+
for _, future in self.pending.values():
|
|
51
|
+
if not future.done():
|
|
52
|
+
future.set_exception(HandleExpired("Host connection closed"))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BoundHost:
|
|
56
|
+
def __init__(self, host: Host, call: Any, member: str):
|
|
57
|
+
self.host, self.call_owner, self.member = host, call, member
|
|
58
|
+
|
|
59
|
+
async def call(self, path: str, params: dict[str, Any], request_id: str | None = None) -> Any:
|
|
60
|
+
return await self.host.call(self.call_owner, self.member, path, params, request_id)
|
|
61
|
+
|
|
62
|
+
def access(self, binding: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
63
|
+
return {"call_id": self.call_owner.id, "member": self.member,
|
|
64
|
+
"binding": binding or self.call_owner.params["contexts"][self.member]["binding"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Candidate-only helper using the shared v4 inspect request and response."""
|
|
2
|
+
import sys
|
|
3
|
+
import json
|
|
4
|
+
import struct
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from ._protocol import MAX_FRAME, validate, response, reject_constant
|
|
7
|
+
from .config import inspect_config, normalize
|
|
8
|
+
from .registration import ModuleLoader
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main() -> None:
|
|
12
|
+
output = sys.stdout.buffer
|
|
13
|
+
sys.stdout = sys.stderr
|
|
14
|
+
size = struct.unpack(">I", sys.stdin.buffer.read(4))[0]
|
|
15
|
+
if not 0 < size <= MAX_FRAME:
|
|
16
|
+
raise ValueError("Invalid inspect frame length")
|
|
17
|
+
message = validate(json.loads(sys.stdin.buffer.read(size), parse_constant=reject_constant))
|
|
18
|
+
if message["path"] != "/request/plugin/inspect" or message.get("session_id") is not None:
|
|
19
|
+
raise ValueError("Expected an execution-free inspect request")
|
|
20
|
+
payload = message["payload"]
|
|
21
|
+
if set(payload) != {"id", "source"} or payload["id"] != sys.argv[1] or payload["source"] != sys.argv[2]:
|
|
22
|
+
raise ValueError("Inspect source mismatch")
|
|
23
|
+
source = Path(payload["source"])
|
|
24
|
+
try:
|
|
25
|
+
if source.is_file():
|
|
26
|
+
loader = ModuleLoader(payload["id"], source.parent)
|
|
27
|
+
config = inspect_config(loader.load(source), payload["id"], source)
|
|
28
|
+
else:
|
|
29
|
+
config = normalize(json.loads((source / "plugin.config").read_text(encoding="utf-8")),
|
|
30
|
+
payload["id"], source)
|
|
31
|
+
result = response(message, config)
|
|
32
|
+
except Exception as error:
|
|
33
|
+
result = response(message, code=400, msg=str(error))
|
|
34
|
+
data = json.dumps(result, allow_nan=False).encode()
|
|
35
|
+
if len(data) > MAX_FRAME:
|
|
36
|
+
raise ValueError("Inspect response exceeds frame limit")
|
|
37
|
+
output.write(struct.pack(">I", len(data)) + data)
|
|
38
|
+
output.flush()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
if __name__ == "__main__":
|
|
42
|
+
main()
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Four-byte big-endian length followed by UTF-8 JSON."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import struct
|
|
5
|
+
from typing import Any, BinaryIO
|
|
6
|
+
|
|
7
|
+
MAX_FRAME = 4 * 1024 * 1024
|
|
8
|
+
PROTOCOL_VERSION = 4
|
|
9
|
+
|
|
10
|
+
PLUGIN_PATHS = {
|
|
11
|
+
"worker/hello", "inspect", "invoke", "next", "context/get", "context/export",
|
|
12
|
+
"context/fork", "context/cancel", "context/complete_query", "context/stacks", "output/send", "stream/next", "stream/close",
|
|
13
|
+
"call/release", "host/get_engine", "host/get_session",
|
|
14
|
+
}
|
|
15
|
+
SESSION_PATHS = {"execution/steer", "execution/stop", "execution/get"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _object(value: Any, required: set[str], optional: set[str] = frozenset()) -> None:
|
|
19
|
+
if not isinstance(value, dict) or required - set(value) or set(value) - required - optional:
|
|
20
|
+
raise ValueError("Payload fields do not match registered schema")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _access(value: Any) -> None:
|
|
24
|
+
_object(value, {"call_id", "member", "binding"})
|
|
25
|
+
_object(value["binding"], {"handle"}, {"execution_id", "invocation_id"})
|
|
26
|
+
if not all(isinstance(value[key], str) and value[key] for key in ("call_id", "member")):
|
|
27
|
+
raise ValueError("Invalid capability owner")
|
|
28
|
+
binding = value["binding"]
|
|
29
|
+
if not isinstance(binding["handle"], str) or not binding["handle"]:
|
|
30
|
+
raise ValueError("Invalid capability handle")
|
|
31
|
+
if (binding.get("execution_id") is None) != (binding.get("invocation_id") is None):
|
|
32
|
+
raise ValueError("Incomplete execution binding")
|
|
33
|
+
for key in ("execution_id", "invocation_id"):
|
|
34
|
+
identity = binding.get(key)
|
|
35
|
+
if identity is not None and (not isinstance(identity, str) or not identity or len(identity.encode()) > 256):
|
|
36
|
+
raise ValueError("Invalid execution identity")
|
|
37
|
+
|
|
38
|
+
def hook_value(point: str, method: str, value: Any, *, output: bool = False) -> None:
|
|
39
|
+
from .data import SessionMessage, UserMemory
|
|
40
|
+
methods = {"SingleAgentHook": {"on_query", "on_prompt", "on_memory", "on_history", "on_compression",
|
|
41
|
+
"on_model_req", "on_model_resp", "on_tools_req", "on_tools_resp", "on_save"},
|
|
42
|
+
"ToolsHook": {"desc", "exec"}, "ModelHook": {"match_model", "exec"}}
|
|
43
|
+
if method not in methods.get(point, set()):
|
|
44
|
+
raise ValueError("Unregistered hook method")
|
|
45
|
+
if method in {"on_query", "on_prompt"} or (method in {"match_model", "desc"} and not output):
|
|
46
|
+
if not isinstance(value, str):
|
|
47
|
+
raise ValueError("Hook requires text")
|
|
48
|
+
elif method == "match_model":
|
|
49
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
50
|
+
raise ValueError("Model selection requires member ids")
|
|
51
|
+
elif method in {"on_memory", "on_history", "on_save"}:
|
|
52
|
+
if not isinstance(value, list):
|
|
53
|
+
raise ValueError("Hook requires an array")
|
|
54
|
+
cls = UserMemory if method == "on_memory" else SessionMessage
|
|
55
|
+
for item in value:
|
|
56
|
+
cls.from_dict(item)
|
|
57
|
+
elif method == "on_model_resp" or (point == "ModelHook" and output):
|
|
58
|
+
if not isinstance(value, dict):
|
|
59
|
+
raise ValueError("Model result requires an object")
|
|
60
|
+
if value.get("kind") == "completed":
|
|
61
|
+
_object(value, {"kind", "response"})
|
|
62
|
+
completion = value["response"]
|
|
63
|
+
if (not isinstance(completion, dict) or not {"id", "object", "created", "model", "choices"} <= set(completion)
|
|
64
|
+
or not isinstance(completion["choices"], list)):
|
|
65
|
+
raise ValueError("Invalid model completion")
|
|
66
|
+
elif value.get("kind") in ({"streaming", "host_stream"} if output else {"streaming"}):
|
|
67
|
+
_object(value, {"kind", "stream_id"})
|
|
68
|
+
if not isinstance(value["stream_id"], str) or not value["stream_id"]:
|
|
69
|
+
raise ValueError("Invalid stream reference")
|
|
70
|
+
else:
|
|
71
|
+
raise ValueError("Invalid model response variant")
|
|
72
|
+
elif method == "on_tools_resp" or (point == "ToolsHook" and method == "exec" and output):
|
|
73
|
+
if not isinstance(value, dict) or set(value) not in ({"result"}, {"reference"}, {"result", "reference"}):
|
|
74
|
+
raise ValueError("Invalid tool result")
|
|
75
|
+
if "reference" in value:
|
|
76
|
+
if not isinstance(value["reference"], str) or not value["reference"]:
|
|
77
|
+
raise ValueError("Invalid tool reference")
|
|
78
|
+
if value.get("result") is not None and not isinstance(value["result"], str):
|
|
79
|
+
raise ValueError("Invalid tool input")
|
|
80
|
+
elif not isinstance(value["result"], str):
|
|
81
|
+
raise ValueError("Tool result requires text")
|
|
82
|
+
elif point == "ToolsHook" and method == "desc":
|
|
83
|
+
if not isinstance(value, dict):
|
|
84
|
+
raise ValueError("Tool description requires an object")
|
|
85
|
+
elif method == "on_tools_req" or point == "ToolsHook":
|
|
86
|
+
_object(value, {"tool_name", "arguments"})
|
|
87
|
+
if not all(isinstance(value[k], str) for k in ("tool_name", "arguments")):
|
|
88
|
+
raise ValueError("Invalid tool request")
|
|
89
|
+
else:
|
|
90
|
+
if (not isinstance(value, dict) or not isinstance(value.get("model"), str)
|
|
91
|
+
or not isinstance(value.get("messages"), list)):
|
|
92
|
+
raise ValueError("Invalid native model request")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _payload(suffix: str, payload: dict[str, Any]) -> None:
|
|
96
|
+
schemas = {
|
|
97
|
+
"plugin/worker/hello": ({"api_version", "instances"}, set()),
|
|
98
|
+
"plugin/inspect": ({"id", "source"}, set()),
|
|
99
|
+
"plugin/invoke": ({"point", "method", "contexts", "argument", "group", "timeout_ms"}, {"location", "model_members"}),
|
|
100
|
+
"plugin/next": ({"access", "point", "method", "argument"}, set()),
|
|
101
|
+
"plugin/context/stacks": ({"access", "query"}, set()),
|
|
102
|
+
"plugin/context/fork": ({"access", "spec"}, set()),
|
|
103
|
+
"plugin/context/cancel": ({"access"}, {"reason"}),
|
|
104
|
+
"plugin/context/complete_query": ({"access", "text"}, set()),
|
|
105
|
+
"plugin/output/send": ({"access", "content"}, set()),
|
|
106
|
+
"plugin/stream/next": ({"call_id", "stream_id"}, {"access"}),
|
|
107
|
+
"plugin/stream/close": ({"call_id", "stream_id"}, {"access"}),
|
|
108
|
+
"plugin/call/release": ({"call_id"}, set()),
|
|
109
|
+
"session/execution/steer": ({"execution_id", "input"}, set()),
|
|
110
|
+
"session/execution/stop": ({"execution_id"}, {"reason"}),
|
|
111
|
+
"session/execution/get": (set(), {"execution_id", "input_request_id"}),
|
|
112
|
+
}
|
|
113
|
+
if suffix in {"plugin/context/get", "plugin/context/export", "plugin/host/get_engine", "plugin/host/get_session"}:
|
|
114
|
+
_access(payload)
|
|
115
|
+
return
|
|
116
|
+
required, optional = schemas[suffix]
|
|
117
|
+
_object(payload, required, optional)
|
|
118
|
+
if payload.get("access") is not None:
|
|
119
|
+
_access(payload["access"])
|
|
120
|
+
if suffix == "plugin/context/fork":
|
|
121
|
+
_object(payload["spec"], {"operation"})
|
|
122
|
+
if suffix == "plugin/context/complete_query":
|
|
123
|
+
if not isinstance(payload["text"], str) or not payload["text"].strip():
|
|
124
|
+
raise ValueError("Query result must be nonempty text")
|
|
125
|
+
if suffix == "plugin/context/stacks":
|
|
126
|
+
from .data import ContextStackQuery
|
|
127
|
+
query = ContextStackQuery.from_dict(payload["query"])
|
|
128
|
+
if query.limit is not None and not 0 <= query.limit <= 256:
|
|
129
|
+
raise ValueError("Invalid stack limit")
|
|
130
|
+
if suffix == "plugin/next":
|
|
131
|
+
hook_value(payload["point"], payload["method"], payload["argument"])
|
|
132
|
+
if suffix == "plugin/invoke":
|
|
133
|
+
methods = {"SingleAgentHook": {"on_query", "on_prompt", "on_memory", "on_history", "on_compression",
|
|
134
|
+
"on_model_req", "on_model_resp", "on_tools_req", "on_tools_resp", "on_save"},
|
|
135
|
+
"ToolsHook": {"desc", "exec"}, "ModelHook": {"match_model", "exec"}}
|
|
136
|
+
if payload["method"] not in methods.get(payload["point"], set()):
|
|
137
|
+
raise ValueError("Unregistered hook method")
|
|
138
|
+
if type(payload["timeout_ms"]) is not int or not 0 < payload["timeout_ms"] <= 120000:
|
|
139
|
+
raise ValueError("Invalid call deadline")
|
|
140
|
+
if not isinstance(payload["contexts"], dict) or not payload["contexts"]:
|
|
141
|
+
raise ValueError("Call requires capabilities")
|
|
142
|
+
for member, reference in payload["contexts"].items():
|
|
143
|
+
_object(reference, {"binding"}, {"summary", "session_id"})
|
|
144
|
+
_access({"call_id": "validation", "member": member, "binding": reference["binding"]})
|
|
145
|
+
hook_value(payload["point"], payload["method"], payload["argument"])
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def validate(frame: dict[str, Any]) -> dict[str, Any]:
|
|
149
|
+
if frame.get("version") != PROTOCOL_VERSION:
|
|
150
|
+
raise ValueError("Only protocol v4 is supported")
|
|
151
|
+
path = frame.get("path", "")
|
|
152
|
+
if not isinstance(path, str) or not path.startswith(("/request/", "/response/")):
|
|
153
|
+
raise ValueError("Invalid plugin protocol path")
|
|
154
|
+
suffix = path.split("/", 2)[2]
|
|
155
|
+
if suffix not in {f"plugin/{p}" for p in PLUGIN_PATHS} | {f"session/{p}" for p in SESSION_PATHS}:
|
|
156
|
+
raise ValueError("Unregistered plugin protocol path")
|
|
157
|
+
if set(frame) - {"version", "request_id", "session_id", "path", "payload"}:
|
|
158
|
+
raise ValueError("Unknown envelope fields")
|
|
159
|
+
identifier = frame.get("request_id")
|
|
160
|
+
if not isinstance(identifier, str) or not identifier or len(identifier.encode()) > 256 or identifier.strip() != identifier or any(ord(c) < 32 or ord(c) == 127 for c in identifier):
|
|
161
|
+
raise ValueError("Invalid request_id")
|
|
162
|
+
sid = frame.get("session_id")
|
|
163
|
+
if sid is not None and (not isinstance(sid, str) or not sid or len(sid.encode()) > 256 or sid.strip() != sid):
|
|
164
|
+
raise ValueError("Invalid session_id")
|
|
165
|
+
if suffix.startswith("session/") and sid is None:
|
|
166
|
+
raise ValueError("Session operation requires session_id")
|
|
167
|
+
if not isinstance(frame.get("payload"), dict) and not path.startswith("/response/"):
|
|
168
|
+
raise ValueError("Request payload must be an object")
|
|
169
|
+
if path.startswith("/request/"):
|
|
170
|
+
_payload(suffix, frame["payload"])
|
|
171
|
+
if suffix in {"plugin/worker/hello", "plugin/inspect"} and sid is not None:
|
|
172
|
+
raise ValueError("Initialization cannot bind a session")
|
|
173
|
+
if suffix == "plugin/invoke":
|
|
174
|
+
for reference in frame["payload"]["contexts"].values():
|
|
175
|
+
if reference.get("session_id") != sid or (reference["binding"].get("execution_id") is None) != (sid is None):
|
|
176
|
+
raise ValueError("Invocation session binding mismatch")
|
|
177
|
+
if path.startswith("/response/"):
|
|
178
|
+
body = frame["payload"]
|
|
179
|
+
if not isinstance(body, dict) or set(body) != {"code", "msg", "data"}:
|
|
180
|
+
raise ValueError("Invalid response payload")
|
|
181
|
+
if type(body["code"]) is not int or body["code"] not in {0, 400, 403, 404, 409, 500, 503, 507}:
|
|
182
|
+
raise ValueError("Invalid response code")
|
|
183
|
+
if not isinstance(body["msg"], str) or (body["code"] != 0 and body["data"] is not None):
|
|
184
|
+
raise ValueError("Invalid error response")
|
|
185
|
+
return frame
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def request(request_id: str, path: str, payload: dict[str, Any], session_id: str | None = None) -> dict[str, Any]:
|
|
189
|
+
frame = {"version": PROTOCOL_VERSION, "request_id": request_id, "path": path, "payload": payload}
|
|
190
|
+
if session_id is not None:
|
|
191
|
+
frame["session_id"] = session_id
|
|
192
|
+
return validate(frame)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def response(message: dict[str, Any], data: Any = None, *, code: int = 0, msg: str = "ok") -> dict[str, Any]:
|
|
196
|
+
if code == 0 and message["path"] in {"/request/plugin/invoke", "/request/plugin/next"}:
|
|
197
|
+
hook_value(message["payload"]["point"], message["payload"]["method"], data, output=True)
|
|
198
|
+
frame = {"version": PROTOCOL_VERSION, "request_id": message["request_id"],
|
|
199
|
+
"path": message["path"].replace("/request/", "/response/", 1),
|
|
200
|
+
"payload": {"code": code, "msg": msg, "data": data if code == 0 else None}}
|
|
201
|
+
if message.get("session_id") is not None:
|
|
202
|
+
frame["session_id"] = message["session_id"]
|
|
203
|
+
return validate(frame)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def reader() -> asyncio.StreamReader:
|
|
207
|
+
import sys
|
|
208
|
+
stream = asyncio.StreamReader(limit=MAX_FRAME + 4)
|
|
209
|
+
await asyncio.get_running_loop().connect_read_pipe(
|
|
210
|
+
lambda: asyncio.StreamReaderProtocol(stream), sys.stdin.buffer)
|
|
211
|
+
return stream
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
async def read_frame(stream: asyncio.StreamReader) -> dict[str, Any]:
|
|
215
|
+
size = struct.unpack(">I", await stream.readexactly(4))[0]
|
|
216
|
+
if size == 0 or size > MAX_FRAME:
|
|
217
|
+
raise ValueError("Invalid plugin protocol frame length")
|
|
218
|
+
data = json.loads(await stream.readexactly(size), parse_constant=reject_constant)
|
|
219
|
+
if not isinstance(data, dict):
|
|
220
|
+
raise ValueError("Protocol frame must be an object")
|
|
221
|
+
return validate(data)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def reject_constant(value: str) -> Any:
|
|
225
|
+
raise ValueError(f"Invalid JSON constant {value}")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class Writer:
|
|
229
|
+
def __init__(self, output: BinaryIO):
|
|
230
|
+
self.output = output
|
|
231
|
+
self.control: asyncio.Queue[bytes] = asyncio.Queue(64)
|
|
232
|
+
self.business: asyncio.Queue[bytes] = asyncio.Queue(64)
|
|
233
|
+
self.ready = asyncio.Event()
|
|
234
|
+
|
|
235
|
+
async def send(self, frame: dict[str, Any], *, control: bool = False) -> None:
|
|
236
|
+
validate(frame)
|
|
237
|
+
data = json.dumps(frame, allow_nan=False, separators=(",", ":")).encode("utf-8")
|
|
238
|
+
if not data or len(data) > MAX_FRAME:
|
|
239
|
+
raise ValueError("Plugin protocol message exceeds 4 MiB")
|
|
240
|
+
await (self.control if control else self.business).put(struct.pack(">I", len(data)) + data)
|
|
241
|
+
self.ready.set()
|
|
242
|
+
|
|
243
|
+
def _write(self, data: bytes) -> None:
|
|
244
|
+
self.output.write(data)
|
|
245
|
+
self.output.flush()
|
|
246
|
+
|
|
247
|
+
async def run(self) -> None:
|
|
248
|
+
while True:
|
|
249
|
+
await self.ready.wait()
|
|
250
|
+
queue = self.control if not self.control.empty() else self.business
|
|
251
|
+
if queue.empty():
|
|
252
|
+
self.ready.clear()
|
|
253
|
+
continue
|
|
254
|
+
data = queue.get_nowait()
|
|
255
|
+
await asyncio.to_thread(self._write, data)
|
|
256
|
+
if self.control.empty() and self.business.empty():
|
|
257
|
+
self.ready.clear()
|