fae-plugin-py 0.1.0__tar.gz → 0.2.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.
Files changed (34) hide show
  1. {fae_plugin_py-0.1.0/src/fae_plugin_py.egg-info → fae_plugin_py-0.2.0}/PKG-INFO +68 -59
  2. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/README.md +67 -58
  3. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/pyproject.toml +1 -1
  4. fae_plugin_py-0.2.0/src/fae_plugin/__init__.py +26 -0
  5. fae_plugin_py-0.2.0/src/fae_plugin/_host.py +64 -0
  6. fae_plugin_py-0.2.0/src/fae_plugin/_inspect.py +42 -0
  7. fae_plugin_py-0.2.0/src/fae_plugin/_protocol.py +253 -0
  8. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/_worker.py +135 -61
  9. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/chain.py +4 -2
  10. fae_plugin_py-0.2.0/src/fae_plugin/context.py +65 -0
  11. fae_plugin_py-0.2.0/src/fae_plugin/data.py +417 -0
  12. fae_plugin_py-0.2.0/src/fae_plugin/errors.py +75 -0
  13. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/registration.py +3 -1
  14. fae_plugin_py-0.2.0/src/fae_plugin/session.py +42 -0
  15. fae_plugin_py-0.2.0/src/fae_plugin/types.py +131 -0
  16. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0/src/fae_plugin_py.egg-info}/PKG-INFO +68 -59
  17. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin_py.egg-info/SOURCES.txt +1 -0
  18. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/tests/test_sdk.py +163 -72
  19. fae_plugin_py-0.1.0/src/fae_plugin/__init__.py +0 -19
  20. fae_plugin_py-0.1.0/src/fae_plugin/_host.py +0 -55
  21. fae_plugin_py-0.1.0/src/fae_plugin/_inspect.py +0 -30
  22. fae_plugin_py-0.1.0/src/fae_plugin/_protocol.py +0 -57
  23. fae_plugin_py-0.1.0/src/fae_plugin/context.py +0 -175
  24. fae_plugin_py-0.1.0/src/fae_plugin/errors.py +0 -96
  25. fae_plugin_py-0.1.0/src/fae_plugin/session.py +0 -42
  26. fae_plugin_py-0.1.0/src/fae_plugin/types.py +0 -464
  27. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/LICENSE +0 -0
  28. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/setup.cfg +0 -0
  29. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/config.py +0 -0
  30. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/engine.py +0 -0
  31. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/hooks.py +0 -0
  32. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin/py.typed +0 -0
  33. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin_py.egg-info/dependency_links.txt +0 -0
  34. {fae_plugin_py-0.1.0 → fae_plugin_py-0.2.0}/src/fae_plugin_py.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fae-plugin-py
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Typed Python plugins for the FAE agent engine
5
5
  Author-email: Teshin <1443965173@qq.com>
6
6
  License-Expression: Apache-2.0
@@ -19,7 +19,7 @@ Dynamic: license-file
19
19
 
20
20
  # fae-plugin-py
21
21
 
22
- FAE 插件 API `0.1.0` 的 Python SDK,支持 Agent Hook、工具和完整/流式模型。
22
+ FAE 插件 API `0.2.0` 的 Python SDK,支持 Agent Hook、工具和完整/流式模型。
23
23
  Python 3.10 及以上可用。发行名是 `fae-plugin-py`,导入名是 `fae_plugin`。
24
24
 
25
25
  ```bash
@@ -65,7 +65,7 @@ from fae_plugin import Context, SingleAgentHook, ToolsHook, ModelHook
65
65
  将单文件放在 `<fae_home>/plugins/project_context.py`:
66
66
 
67
67
  ```python
68
- from fae_plugin import SingleAgentHook
68
+ from fae_plugin import SingleAgentHook, TextContent
69
69
 
70
70
  def plugin_config():
71
71
  return {
@@ -78,9 +78,9 @@ def plugin_config():
78
78
  class ProjectContext(SingleAgentHook):
79
79
  async def on_query(self, ctx, query):
80
80
  if ctx.session is not None:
81
- await ctx.session.send("开始处理请求。")
81
+ await ctx.session.send([TextContent("开始处理请求。")])
82
82
  if query.strip() == "/stop":
83
- await ctx.cancel_run("用户要求停止")
83
+ await ctx.cancel_execution("stop-from-query")
84
84
  return query.strip()
85
85
 
86
86
  async def on_prompt(self, ctx, prompt):
@@ -88,18 +88,28 @@ class ProjectContext(SingleAgentHook):
88
88
  ```
89
89
 
90
90
  ```bash
91
- fae plugin project_context
92
- fae plugin --show project_context
93
- fae plugin --show '*'
94
- fae --fae-home /path/to/.fae plugin project_context
91
+ fae plugin install /path/to/project_context.py
92
+ fae plugin show project_context
93
+ fae plugin show '*'
94
+ fae --fae-home /path/to/.fae plugin uninstall project_context
95
95
  ```
96
96
 
97
- 单文件配置函数是同步无参数函数,每次候选加载调用一次。目录插件以根目录
97
+ `fae plugin show` 不传 ID 时等同于 `fae plugin show '*'`,简洁列出全部插件。
98
+
99
+ 安装命令将插件文件或目录复制到 `<fae_home>/plugins/`,同名覆盖并保留安装位置。
100
+ 固定 JSON 文件 `plugins/plugins.config` 的 `plugins` 数组记录安装顺序、
101
+ `id`、`source`、`installed` 和 `enabled`;卸载保留源码并将两个状态设为 false,
102
+ 卸载后重装追加到末尾。可编辑 `enabled` 禁用插件。
103
+ 服务启动按配置顺序加载已安装且启用的当前源码,任何错误都会导致启动失败。
104
+ 服务运行时安装、覆盖和卸载即时更新运行时,无需重启;已有任务保留原 Worker 快照。
105
+ 服务未运行时只更新文件及配置,下次启动生效;未记录在配置中的源码不会自动加载。
106
+
107
+ 单文件配置函数是同步无参数函数,每次服务加载调用一次。目录插件以根目录
98
108
  `plugin.config` UTF-8 JSON 为唯一配置,必须有 `"engine": "py"`,入口为
99
109
  `"implementation": "plugin.py:ProjectContext"`,不调用配置函数。
100
110
 
101
111
  声明的必填字段为 `plugin_version`(SemVer)、`description`、`mounts`;
102
- `registration_mode` 默认 `direct`,`fae_plugin_api_version` 默认 `0.1.0`。
112
+ `registration_mode` 默认 `direct`,`fae_plugin_api_version` 默认 `0.2.0`。
103
113
  未知字段、不匹配的接口位置、重复挂载、越界入口或不兼容版本会拒绝加载。
104
114
  JavaScript 引擎首期明确不可用。
105
115
 
@@ -134,54 +144,53 @@ async task 调用一次;不能保留到流生成器、其他 task 或下一轮
134
144
  `ChainModelHook.match_model(ctx, model)` 是独立判断方法,不接收 `next`,
135
145
  每个模型类都必须实现;只有返回 True 的成员进入本次模型链。
136
146
 
137
- ## 上下文、状态和栈
147
+ ## 上下文与执行能力
138
148
 
139
- 所有接口接收同一种 Context。属性 `agent_id/user_id/scope_id/run_id` 和
140
- Agent 的 `plan_id/task_id/turn_id` 是只读身份缓存。`ctx.session` 可能为 None。
141
- `get_engine()` 返回具有 `engine_id` 和 `same_engine()` 的宿主引用。
149
+ 所有接口接收同一种 Context。`execution_id/invocation_id` 固定到原执行;
150
+ `read_summary()` 返回公共 SessionSummary,`export_context()` 返回完整 ContextData。
151
+ SessionMessage 与 UserMemory 为确定的 dataclass,历史 role、记忆 category/confidence
152
+ 使用枚举;原有历史与记忆文件格式保持不变。完整导出补齐当前默认目标分区至
153
+ history_offset=0,并读取用户记忆与项目文件;执行目录从
154
+ `latest_execution_view.effective.workspace` 读取。
155
+ 这些 DTO 不包含 worker、Engine 或控制句柄,反序列化不会恢复执行。
156
+ `ctx.session` 在执行外可能为 None。`get_engine()` 返回不透明宿主引用,
157
+ 支持 `engine_id` 和 `same_engine()`。
142
158
 
143
159
  ```python
144
- from fae_plugin import (
145
- ContextChildSpec, ContextState, ContextStackQuery,
146
- ContextStackDraft, ContextStackPhase, TaskMeta, TaskType,
147
- )
160
+ from fae_plugin import ContextChildSpec, TextContent
148
161
 
149
162
  async def inspect(ctx):
150
- scope = await ctx.scope()
151
- child = await ctx.fork(ContextChildSpec()) # 只创建,不调度任务
152
- await child.set_state(ContextState.running())
153
- view = child.state()
154
- try:
155
- print((await view.current()).kind)
156
- await child.cancel("关闭临时子上下文")
157
- await view.changed()
158
- finally:
159
- await view.aclose()
160
- await ctx.append_stack(ContextStackDraft(
161
- TaskMeta("plugin-step", ctx.plan_id or "", TaskType(), "plugin", "inspect"),
162
- ContextStackPhase.STARTED,
163
- ))
164
- entries = await ctx.stacks(ContextStackQuery(tree=True, limit=20))
165
- if entries:
166
- next_page = await ctx.stacks(ContextStackQuery(
167
- tree=True, after_sequence=entries[-1].sequence, limit=20))
163
+ summary = await ctx.read_summary()
164
+ print(summary.user_info.user_id)
165
+ child = await ctx.fork(ContextChildSpec("inspect"))
166
+ assert child.execution_id == ctx.execution_id
167
+ await child.cancel_local("关闭临时子调用")
168
+ if ctx.session:
169
+ await ctx.session.send([TextContent("检查完成")])
168
170
  ```
169
171
 
170
- `state()` 创建订阅视图,`current()` 不消费执行结果。成功状态的 output 支持
171
- `await output.json_snapshot()`;不可编码原生结果报 `UnsupportedOutputType`。
172
- Agent 计划与插件创建的子上下文可写 JSON 成功输出,原生工具/模型任务不能写入伪造 JSON 结果。
173
- `cancel()` 取消当前上下文;`cancel_run()` 取消固定 root Run;取消子上下文不会
174
- 自动取消父 Hook。终态写入不可恢复执行。
175
-
176
- `bind_scope` 保留原生一次性绑定语义:已绑定 Hook 拒绝重绑,静态 ContextNull
177
- 不能绑定。session/todo 等宿主引用不能通过字符串伪造。`fork(execution=True)`
178
- 遵循 Rust 的执行归属清空/显式指定规则,用户始终继承。
172
+ 子调用继承用户、Session、Execution、workspace 与插件快照,仅接受局部操作名。
173
+ 取消局部子调用不会取消父 Hook。正常完成通过 hook/provider 的类型化返回;
174
+ SDK 不提供 `bind_scope`、`set_state` 或直接修改整体终态的接口。
175
+ `await ctx.stacks(ContextStackQuery(tree=True, limit=20))` 只读查询调试记录,
176
+ 当前活动调用关系从 InvocationView 的父子 ID 与状态推导。
179
177
 
180
178
  代理限于当前调用与关联流;方法返回后无流则释放,调用结束时取消未调度的
181
179
  临时子上下文。不要把 ctx/session/next 保存到实例属性用于其他输入。
182
180
 
183
- `session.send(text)` 产生独立 `plugin_message`,CLI/TUI/Lark 会展示;它不追加
184
- 模型历史,也不修改最终答案。静态工具发现 ContextNull 无 session,不能取消任务。
181
+ `session.send(content)` 将文本、JSON 或资源内容提交到统一 OutputDelta 出口。
182
+ `session.steer(content, request_id)` 显式补充绑定的 Execution,返回接收回执;
183
+ `session.input_record(request_id)` 可重复读取 Queued/Applied/NotApplied 事实。
184
+ `session.stop(request_id)` 和 `ctx.cancel_execution(request_id)` 校验原 Execution,
185
+ 接收停止请求后仍需等待实际清理。过期能力明确报错。
186
+ OutputDelta 带原 execution_id/invocation_id/output_id,source 标记
187
+ model、tool、plugin(含 plugin_id)或 runtime。插件通知不进入输入邮箱或模型历史。
188
+
189
+ stdio 保留四字节大端长度前缀与 4 MiB 上限,帧内直接使用公共 v4
190
+ Message/ResponseMessage;错误采用整数 ResponseCode 和 `code/msg/data`。
191
+ 旧 API/worker 在握手时拒绝,不进行协议映射或版本降级。
192
+ chain next 的单次调用和成员归属由 Python 与宿主共同校验;宿主验证后
193
+ 再请求 Worker 执行下一层,输入和结果仍须满足原生 Hook 类型。
185
194
 
186
195
  ## 工具与模型
187
196
 
@@ -237,16 +246,14 @@ Agent 的 `model.model` 仍填写模型名称;例如回显示例匹配
237
246
  [examples/http_model](examples/http_model) 展示真实异步 HTTP 模型调用;
238
247
  `on_model_resp` 可返回输入响应或包装其 async iterator。
239
248
 
240
- 从旧版本升级时,在模型类中补充 match_model,删除 plugin.config 或
241
- plugin_config() 中的模型挂载 model 字段,重新加载插件。宿主读取旧持久化
242
- 记录时会迁移旧 model 元数据,但不会修改冻结源码;未实现新接口的旧执行版本
243
- 会显示加载错误,必须用更新后的源码重新加载。
249
+ 升级时使用 API 0.2.0 的 Context 和 Content 接口并重新加载插件。
250
+ 模型类须实现 match_model,模型挂载声明不接受 model 字段。
244
251
 
245
252
  可直接复制的样例还包括 `examples/project_context.py`(direct Agent)、
246
253
  `examples/echo_tools/`(目录工具插件)、`examples/a.py`、`b.py`、`c.py`
247
254
  (Python 洋葱链)。将样例复制到 `<fae_home>/plugins/` 后依次执行
248
- `fae plugin a`、`fae plugin b`、`fae plugin c`,得到 A→B→C;
249
- 工具样例加载为 `fae plugin echo_tools`,Agent 的 tools 中选择
255
+ `fae plugin install /path/to/a.py`、`b.py`、`c.py`,得到 A→B→C;
256
+ 工具样例用 `fae plugin install /path/to/echo_tools` 安装,Agent 的 tools 中选择
250
257
  `fae_echo_tools__echo`。
251
258
 
252
259
  ## 运行和开发
@@ -268,7 +275,8 @@ class LookupCache:
268
275
 
269
276
  async def lookup(self, ctx, url):
270
277
  session = ctx.session # 调用局部变量
271
- key = (ctx.user_id, session.session_id if session else None, url)
278
+ summary = await ctx.read_summary()
279
+ key = (summary.user_info.user_id, session.session_id if session else None, url)
272
280
  async with self.lock:
273
281
  if key in self.cache:
274
282
  return self.cache[key]
@@ -286,11 +294,12 @@ class LookupCache:
286
294
  普通方法及模型 match_model 判断预算默认 1 秒,模型 exec 和模型流总预算 120 秒;排队计入预算。
287
295
  首块等待上限 30 秒,后续空闲上限 60 秒;消费者不读取的时间仅计入总预算。
288
296
  Worker 使用有界队列、8 个业务槽、每组 4 个槽、4 个同步线程及有界流引用。
289
- 流逐块拉取,消费端 drop/cancel 释放调用。stdout 专用于协议,print 转到 stderr。
297
+ 流逐块拉取,消费端 drop/stop 触发释放。worker 确认关闭生成器、结束实际同步线程
298
+ 和清理临时资源后,宿主才释放 Execution 活跃槽。stdout 专用于协议,print 转到 stderr。
290
299
 
291
- 重加载先校验新配置、类、签名、依赖和路由,再原子切换。旧 Run 的子任务和
292
- 流保留旧快照,下一轮使用新版本;失败保留工作版本。状态与冻结源码在
293
- `plugin-state/active.json` 和 `plugin-state/versions/` 内管理,重启恢复冻结配置与源码,离线 show 不运行插件代码。
300
+ 启动时校验当前配置、类、签名、依赖和路由,错误直接向上传递。
301
+ 宿主不保存冻结源码或恢复旧版本。安装状态只记录在 `plugins/plugins.config`,
302
+ 重启重新读取当前源码及声明;离线 show 不运行插件代码,单文件声明显示为未知。
294
303
 
295
304
  ```bash
296
305
  PYTHONPATH=python/fae-plugin-py/src python3 -m unittest discover \
@@ -1,6 +1,6 @@
1
1
  # fae-plugin-py
2
2
 
3
- FAE 插件 API `0.1.0` 的 Python SDK,支持 Agent Hook、工具和完整/流式模型。
3
+ FAE 插件 API `0.2.0` 的 Python SDK,支持 Agent Hook、工具和完整/流式模型。
4
4
  Python 3.10 及以上可用。发行名是 `fae-plugin-py`,导入名是 `fae_plugin`。
5
5
 
6
6
  ```bash
@@ -46,7 +46,7 @@ from fae_plugin import Context, SingleAgentHook, ToolsHook, ModelHook
46
46
  将单文件放在 `<fae_home>/plugins/project_context.py`:
47
47
 
48
48
  ```python
49
- from fae_plugin import SingleAgentHook
49
+ from fae_plugin import SingleAgentHook, TextContent
50
50
 
51
51
  def plugin_config():
52
52
  return {
@@ -59,9 +59,9 @@ def plugin_config():
59
59
  class ProjectContext(SingleAgentHook):
60
60
  async def on_query(self, ctx, query):
61
61
  if ctx.session is not None:
62
- await ctx.session.send("开始处理请求。")
62
+ await ctx.session.send([TextContent("开始处理请求。")])
63
63
  if query.strip() == "/stop":
64
- await ctx.cancel_run("用户要求停止")
64
+ await ctx.cancel_execution("stop-from-query")
65
65
  return query.strip()
66
66
 
67
67
  async def on_prompt(self, ctx, prompt):
@@ -69,18 +69,28 @@ class ProjectContext(SingleAgentHook):
69
69
  ```
70
70
 
71
71
  ```bash
72
- fae plugin project_context
73
- fae plugin --show project_context
74
- fae plugin --show '*'
75
- fae --fae-home /path/to/.fae plugin project_context
72
+ fae plugin install /path/to/project_context.py
73
+ fae plugin show project_context
74
+ fae plugin show '*'
75
+ fae --fae-home /path/to/.fae plugin uninstall project_context
76
76
  ```
77
77
 
78
- 单文件配置函数是同步无参数函数,每次候选加载调用一次。目录插件以根目录
78
+ `fae plugin show` 不传 ID 时等同于 `fae plugin show '*'`,简洁列出全部插件。
79
+
80
+ 安装命令将插件文件或目录复制到 `<fae_home>/plugins/`,同名覆盖并保留安装位置。
81
+ 固定 JSON 文件 `plugins/plugins.config` 的 `plugins` 数组记录安装顺序、
82
+ `id`、`source`、`installed` 和 `enabled`;卸载保留源码并将两个状态设为 false,
83
+ 卸载后重装追加到末尾。可编辑 `enabled` 禁用插件。
84
+ 服务启动按配置顺序加载已安装且启用的当前源码,任何错误都会导致启动失败。
85
+ 服务运行时安装、覆盖和卸载即时更新运行时,无需重启;已有任务保留原 Worker 快照。
86
+ 服务未运行时只更新文件及配置,下次启动生效;未记录在配置中的源码不会自动加载。
87
+
88
+ 单文件配置函数是同步无参数函数,每次服务加载调用一次。目录插件以根目录
79
89
  `plugin.config` UTF-8 JSON 为唯一配置,必须有 `"engine": "py"`,入口为
80
90
  `"implementation": "plugin.py:ProjectContext"`,不调用配置函数。
81
91
 
82
92
  声明的必填字段为 `plugin_version`(SemVer)、`description`、`mounts`;
83
- `registration_mode` 默认 `direct`,`fae_plugin_api_version` 默认 `0.1.0`。
93
+ `registration_mode` 默认 `direct`,`fae_plugin_api_version` 默认 `0.2.0`。
84
94
  未知字段、不匹配的接口位置、重复挂载、越界入口或不兼容版本会拒绝加载。
85
95
  JavaScript 引擎首期明确不可用。
86
96
 
@@ -115,54 +125,53 @@ async task 调用一次;不能保留到流生成器、其他 task 或下一轮
115
125
  `ChainModelHook.match_model(ctx, model)` 是独立判断方法,不接收 `next`,
116
126
  每个模型类都必须实现;只有返回 True 的成员进入本次模型链。
117
127
 
118
- ## 上下文、状态和栈
128
+ ## 上下文与执行能力
119
129
 
120
- 所有接口接收同一种 Context。属性 `agent_id/user_id/scope_id/run_id` 和
121
- Agent 的 `plan_id/task_id/turn_id` 是只读身份缓存。`ctx.session` 可能为 None。
122
- `get_engine()` 返回具有 `engine_id` 和 `same_engine()` 的宿主引用。
130
+ 所有接口接收同一种 Context。`execution_id/invocation_id` 固定到原执行;
131
+ `read_summary()` 返回公共 SessionSummary,`export_context()` 返回完整 ContextData。
132
+ SessionMessage 与 UserMemory 为确定的 dataclass,历史 role、记忆 category/confidence
133
+ 使用枚举;原有历史与记忆文件格式保持不变。完整导出补齐当前默认目标分区至
134
+ history_offset=0,并读取用户记忆与项目文件;执行目录从
135
+ `latest_execution_view.effective.workspace` 读取。
136
+ 这些 DTO 不包含 worker、Engine 或控制句柄,反序列化不会恢复执行。
137
+ `ctx.session` 在执行外可能为 None。`get_engine()` 返回不透明宿主引用,
138
+ 支持 `engine_id` 和 `same_engine()`。
123
139
 
124
140
  ```python
125
- from fae_plugin import (
126
- ContextChildSpec, ContextState, ContextStackQuery,
127
- ContextStackDraft, ContextStackPhase, TaskMeta, TaskType,
128
- )
141
+ from fae_plugin import ContextChildSpec, TextContent
129
142
 
130
143
  async def inspect(ctx):
131
- scope = await ctx.scope()
132
- child = await ctx.fork(ContextChildSpec()) # 只创建,不调度任务
133
- await child.set_state(ContextState.running())
134
- view = child.state()
135
- try:
136
- print((await view.current()).kind)
137
- await child.cancel("关闭临时子上下文")
138
- await view.changed()
139
- finally:
140
- await view.aclose()
141
- await ctx.append_stack(ContextStackDraft(
142
- TaskMeta("plugin-step", ctx.plan_id or "", TaskType(), "plugin", "inspect"),
143
- ContextStackPhase.STARTED,
144
- ))
145
- entries = await ctx.stacks(ContextStackQuery(tree=True, limit=20))
146
- if entries:
147
- next_page = await ctx.stacks(ContextStackQuery(
148
- tree=True, after_sequence=entries[-1].sequence, limit=20))
144
+ summary = await ctx.read_summary()
145
+ print(summary.user_info.user_id)
146
+ child = await ctx.fork(ContextChildSpec("inspect"))
147
+ assert child.execution_id == ctx.execution_id
148
+ await child.cancel_local("关闭临时子调用")
149
+ if ctx.session:
150
+ await ctx.session.send([TextContent("检查完成")])
149
151
  ```
150
152
 
151
- `state()` 创建订阅视图,`current()` 不消费执行结果。成功状态的 output 支持
152
- `await output.json_snapshot()`;不可编码原生结果报 `UnsupportedOutputType`。
153
- Agent 计划与插件创建的子上下文可写 JSON 成功输出,原生工具/模型任务不能写入伪造 JSON 结果。
154
- `cancel()` 取消当前上下文;`cancel_run()` 取消固定 root Run;取消子上下文不会
155
- 自动取消父 Hook。终态写入不可恢复执行。
156
-
157
- `bind_scope` 保留原生一次性绑定语义:已绑定 Hook 拒绝重绑,静态 ContextNull
158
- 不能绑定。session/todo 等宿主引用不能通过字符串伪造。`fork(execution=True)`
159
- 遵循 Rust 的执行归属清空/显式指定规则,用户始终继承。
153
+ 子调用继承用户、Session、Execution、workspace 与插件快照,仅接受局部操作名。
154
+ 取消局部子调用不会取消父 Hook。正常完成通过 hook/provider 的类型化返回;
155
+ SDK 不提供 `bind_scope`、`set_state` 或直接修改整体终态的接口。
156
+ `await ctx.stacks(ContextStackQuery(tree=True, limit=20))` 只读查询调试记录,
157
+ 当前活动调用关系从 InvocationView 的父子 ID 与状态推导。
160
158
 
161
159
  代理限于当前调用与关联流;方法返回后无流则释放,调用结束时取消未调度的
162
160
  临时子上下文。不要把 ctx/session/next 保存到实例属性用于其他输入。
163
161
 
164
- `session.send(text)` 产生独立 `plugin_message`,CLI/TUI/Lark 会展示;它不追加
165
- 模型历史,也不修改最终答案。静态工具发现 ContextNull 无 session,不能取消任务。
162
+ `session.send(content)` 将文本、JSON 或资源内容提交到统一 OutputDelta 出口。
163
+ `session.steer(content, request_id)` 显式补充绑定的 Execution,返回接收回执;
164
+ `session.input_record(request_id)` 可重复读取 Queued/Applied/NotApplied 事实。
165
+ `session.stop(request_id)` 和 `ctx.cancel_execution(request_id)` 校验原 Execution,
166
+ 接收停止请求后仍需等待实际清理。过期能力明确报错。
167
+ OutputDelta 带原 execution_id/invocation_id/output_id,source 标记
168
+ model、tool、plugin(含 plugin_id)或 runtime。插件通知不进入输入邮箱或模型历史。
169
+
170
+ stdio 保留四字节大端长度前缀与 4 MiB 上限,帧内直接使用公共 v4
171
+ Message/ResponseMessage;错误采用整数 ResponseCode 和 `code/msg/data`。
172
+ 旧 API/worker 在握手时拒绝,不进行协议映射或版本降级。
173
+ chain next 的单次调用和成员归属由 Python 与宿主共同校验;宿主验证后
174
+ 再请求 Worker 执行下一层,输入和结果仍须满足原生 Hook 类型。
166
175
 
167
176
  ## 工具与模型
168
177
 
@@ -218,16 +227,14 @@ Agent 的 `model.model` 仍填写模型名称;例如回显示例匹配
218
227
  [examples/http_model](examples/http_model) 展示真实异步 HTTP 模型调用;
219
228
  `on_model_resp` 可返回输入响应或包装其 async iterator。
220
229
 
221
- 从旧版本升级时,在模型类中补充 match_model,删除 plugin.config 或
222
- plugin_config() 中的模型挂载 model 字段,重新加载插件。宿主读取旧持久化
223
- 记录时会迁移旧 model 元数据,但不会修改冻结源码;未实现新接口的旧执行版本
224
- 会显示加载错误,必须用更新后的源码重新加载。
230
+ 升级时使用 API 0.2.0 的 Context 和 Content 接口并重新加载插件。
231
+ 模型类须实现 match_model,模型挂载声明不接受 model 字段。
225
232
 
226
233
  可直接复制的样例还包括 `examples/project_context.py`(direct Agent)、
227
234
  `examples/echo_tools/`(目录工具插件)、`examples/a.py`、`b.py`、`c.py`
228
235
  (Python 洋葱链)。将样例复制到 `<fae_home>/plugins/` 后依次执行
229
- `fae plugin a`、`fae plugin b`、`fae plugin c`,得到 A→B→C;
230
- 工具样例加载为 `fae plugin echo_tools`,Agent 的 tools 中选择
236
+ `fae plugin install /path/to/a.py`、`b.py`、`c.py`,得到 A→B→C;
237
+ 工具样例用 `fae plugin install /path/to/echo_tools` 安装,Agent 的 tools 中选择
231
238
  `fae_echo_tools__echo`。
232
239
 
233
240
  ## 运行和开发
@@ -249,7 +256,8 @@ class LookupCache:
249
256
 
250
257
  async def lookup(self, ctx, url):
251
258
  session = ctx.session # 调用局部变量
252
- key = (ctx.user_id, session.session_id if session else None, url)
259
+ summary = await ctx.read_summary()
260
+ key = (summary.user_info.user_id, session.session_id if session else None, url)
253
261
  async with self.lock:
254
262
  if key in self.cache:
255
263
  return self.cache[key]
@@ -267,11 +275,12 @@ class LookupCache:
267
275
  普通方法及模型 match_model 判断预算默认 1 秒,模型 exec 和模型流总预算 120 秒;排队计入预算。
268
276
  首块等待上限 30 秒,后续空闲上限 60 秒;消费者不读取的时间仅计入总预算。
269
277
  Worker 使用有界队列、8 个业务槽、每组 4 个槽、4 个同步线程及有界流引用。
270
- 流逐块拉取,消费端 drop/cancel 释放调用。stdout 专用于协议,print 转到 stderr。
278
+ 流逐块拉取,消费端 drop/stop 触发释放。worker 确认关闭生成器、结束实际同步线程
279
+ 和清理临时资源后,宿主才释放 Execution 活跃槽。stdout 专用于协议,print 转到 stderr。
271
280
 
272
- 重加载先校验新配置、类、签名、依赖和路由,再原子切换。旧 Run 的子任务和
273
- 流保留旧快照,下一轮使用新版本;失败保留工作版本。状态与冻结源码在
274
- `plugin-state/active.json` 和 `plugin-state/versions/` 内管理,重启恢复冻结配置与源码,离线 show 不运行插件代码。
281
+ 启动时校验当前配置、类、签名、依赖和路由,错误直接向上传递。
282
+ 宿主不保存冻结源码或恢复旧版本。安装状态只记录在 `plugins/plugins.config`,
283
+ 重启重新读取当前源码及声明;离线 show 不运行插件代码,单文件声明显示为未知。
275
284
 
276
285
  ```bash
277
286
  PYTHONPATH=python/fae-plugin-py/src python3 -m unittest discover \
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fae-plugin-py"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "Typed Python plugins for the FAE agent engine"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -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()