fae-plugin-py 0.1.0__py3-none-any.whl

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/config.py ADDED
@@ -0,0 +1,93 @@
1
+ """Configuration is evaluated once in the candidate inspection process."""
2
+ from __future__ import annotations
3
+ import inspect
4
+ import json
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from .types import API_VERSION, RegistrationMode, json_value
9
+
10
+
11
+ def normalize(raw: Any, plugin_id: str, source: Path) -> dict[str, Any]:
12
+ if not isinstance(raw, dict):
13
+ raise TypeError("plugin_config must return a dictionary")
14
+ raw = json.loads(json.dumps(json_value(raw), allow_nan=False))
15
+ if not re.fullmatch(r"[a-z][a-z0-9_]{0,63}", plugin_id):
16
+ raise ValueError("Invalid plugin ID")
17
+ allowed = {"registration_mode", "plugin_version", "fae_plugin_api_version",
18
+ "description", "engine", "mounts"}
19
+ if set(raw) - allowed:
20
+ raise ValueError("Unknown configuration fields")
21
+ raw.setdefault("registration_mode", "direct")
22
+ raw.setdefault("fae_plugin_api_version", API_VERSION)
23
+ RegistrationMode(raw["registration_mode"])
24
+ if raw["fae_plugin_api_version"] != API_VERSION:
25
+ raise ValueError("Incompatible FAE plugin API")
26
+ version = raw.get("plugin_version")
27
+ if not isinstance(version, str) or not re.fullmatch(
28
+ r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
29
+ r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
30
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?", version
31
+ ):
32
+ raise ValueError("plugin_version must be SemVer")
33
+ if not isinstance(raw.get("description"), str) or not raw["description"].strip():
34
+ raise ValueError("description is required")
35
+ single = source.is_file()
36
+ engine = source.suffix[1:] if single else raw.get("engine")
37
+ if engine not in ("py", "js") or (single and raw.get("engine", engine) != engine):
38
+ raise ValueError("Invalid or mismatched engine")
39
+ raw["engine"] = engine
40
+ if engine != "py":
41
+ raise ValueError("JavaScript plugin engine is unavailable")
42
+ mounts = raw.get("mounts")
43
+ if not isinstance(mounts, list) or not mounts:
44
+ raise ValueError("mounts must be a nonempty list")
45
+ for mount in mounts:
46
+ if not isinstance(mount, dict):
47
+ raise TypeError("Mount must be an object")
48
+ point = mount.get("point")
49
+ if not isinstance(point, str):
50
+ raise ValueError("Invalid mount point")
51
+ locations = {"SingleAgentHook": "agent_id", "ToolsHook": "channel", "ModelHook": None}
52
+ location = locations.get(point)
53
+ allowed_mount = {"point", "implementation"} | ({location} if location else set())
54
+ if point not in locations or set(mount) - allowed_mount:
55
+ raise ValueError("Invalid mount point or location fields")
56
+ if point == "ToolsHook":
57
+ mount.setdefault("channel", f"fae_{plugin_id}")
58
+ if location is not None and location in mount and (not isinstance(mount[location], str) or not mount[location].strip()):
59
+ raise ValueError("Invalid mount location")
60
+ entry = mount.get("implementation")
61
+ if not isinstance(entry, str):
62
+ raise TypeError("implementation must name a class")
63
+ if single:
64
+ class_name = entry
65
+ else:
66
+ file, separator, class_name = entry.partition(":")
67
+ path = Path(file)
68
+ if not separator or path.is_absolute() or ".." in path.parts or path.suffix != ".py":
69
+ raise ValueError("Invalid implementation path")
70
+ resolved = (source / path).resolve()
71
+ if not resolved.is_relative_to(source.resolve()) or not resolved.is_file():
72
+ raise ValueError("Implementation is outside the source or missing")
73
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", class_name):
74
+ raise ValueError("implementation must name an exported class")
75
+ for i, left in enumerate(mounts):
76
+ location = {"SingleAgentHook": "agent_id", "ToolsHook": "channel", "ModelHook": None}[left["point"]]
77
+ for right in mounts[i + 1:]:
78
+ if (left["point"], left["implementation"]) != (right["point"], right["implementation"]):
79
+ continue
80
+ if location is None or left.get(location) == right.get(location) or (
81
+ location == "agent_id" and (location not in left or location not in right)
82
+ ):
83
+ raise ValueError("Overlapping duplicate class mount")
84
+ return raw
85
+
86
+
87
+ def inspect_config(module: Any, plugin_id: str, source: Path) -> dict[str, Any]:
88
+ function = getattr(module, "plugin_config", None)
89
+ if not inspect.isfunction(function) or inspect.iscoroutinefunction(function):
90
+ raise ValueError("A synchronous plugin_config function is required")
91
+ if inspect.signature(function).parameters:
92
+ raise ValueError("plugin_config must have no parameters")
93
+ return normalize(function(), plugin_id, source)
fae_plugin/context.py ADDED
@@ -0,0 +1,175 @@
1
+ """Capabilities are scoped to one host invocation, never to a global current call."""
2
+ from __future__ import annotations
3
+ import asyncio
4
+ from typing import Any
5
+ from .engine import Engine
6
+ from .errors import InvalidHookNext, StateViewClosed
7
+ from .session import Session
8
+ from .types import (
9
+ ContextChildSpec, ContextFailure, ContextOutput, ContextScope, ContextSession,
10
+ ContextStack, ContextStackDraft, ContextStackPhase, ContextStackQuery,
11
+ ContextState, ContextStateKind, ContextStateUpdate, ContextUser,
12
+ SingleAgentSource, TaskMeta, TaskType, TaskTypeKind, TimerExecutionBinding,
13
+ TimerOwner, TodoPlanScope, encode,
14
+ )
15
+
16
+
17
+ def decode_state(value: dict[str, Any], host: Any) -> ContextState:
18
+ kind = ContextStateKind(value["kind"])
19
+ if kind == ContextStateKind.SUCCEEDED:
20
+ out = value["output"]
21
+ output = ContextOutput(out.get("json"), _host=host, _handle=out.get("handle"))
22
+ return ContextState(kind, output=output)
23
+ if kind == ContextStateKind.FAILED:
24
+ return ContextState(kind, error=ContextFailure(**value["error"]))
25
+ if kind == ContextStateKind.CANCELLED:
26
+ return ContextState(kind, reason=value["reason"])
27
+ return ContextState(kind)
28
+
29
+
30
+ class ContextStateView:
31
+ def __init__(self, host: Any, handle: str):
32
+ self._host = host
33
+ self._registration = asyncio.create_task(host.call("state.subscribe", {"handle": handle}))
34
+ self._closed = False
35
+ self._changing = False
36
+
37
+ async def _params(self) -> dict[str, Any]:
38
+ if self._closed:
39
+ raise StateViewClosed("State view is closed")
40
+ return {"handle": (await self._registration)["handle"]}
41
+
42
+ async def current(self) -> ContextState:
43
+ return decode_state(await self._host.call("state.current", await self._params()), self._host)
44
+
45
+ async def changed(self) -> None:
46
+ if self._changing:
47
+ raise InvalidHookNext("Only one changed operation may be in flight")
48
+ self._changing = True
49
+ try:
50
+ await self._host.call("state.changed", await self._params())
51
+ finally:
52
+ self._changing = False
53
+
54
+ async def aclose(self) -> None:
55
+ if self._closed:
56
+ return
57
+ self._closed = True
58
+ registration = await self._registration
59
+ await self._host.call("state.close", {"handle": registration["handle"]})
60
+
61
+
62
+ class Context:
63
+ __slots__ = ("_host", "_handle", "_identity", "_session")
64
+
65
+ def __init__(self, *, _host: Any, _data: dict[str, Any]):
66
+ self._host = _host
67
+ self._handle = _data["handle"]
68
+ self._refresh(_data)
69
+
70
+ def _refresh(self, data: dict[str, Any]) -> None:
71
+ self._identity = dict(data.get("identity", {}))
72
+ session = data.get("session")
73
+ self._session = (Session(_host=self._host, _identity=session["identity"],
74
+ _handle=session["handle"]) if session else None)
75
+
76
+ @property
77
+ def agent_id(self) -> str | None:
78
+ return self._identity.get("agent_id")
79
+
80
+ @property
81
+ def user_id(self) -> str | None:
82
+ return self._identity.get("user_id")
83
+
84
+ @property
85
+ def plan_id(self) -> str | None:
86
+ return self._identity.get("plan_id")
87
+
88
+ @property
89
+ def task_id(self) -> str | None:
90
+ return self._identity.get("task_id")
91
+
92
+ @property
93
+ def turn_id(self) -> int | None:
94
+ return self._identity.get("turn_id")
95
+
96
+ @property
97
+ def scope_id(self) -> str | None:
98
+ return self._identity.get("scope_id")
99
+
100
+ @property
101
+ def run_id(self) -> str | None:
102
+ return self._identity.get("run_id")
103
+
104
+ @property
105
+ def session(self) -> Session | None:
106
+ return self._session
107
+
108
+ async def _call(self, method: str, **params: Any) -> Any:
109
+ return await self._host.call(method, {"handle": self._handle, **encode(params)})
110
+
111
+ async def get_engine(self) -> Engine:
112
+ data = await self._call("context.get_engine")
113
+ return Engine(_host=self._host, _engine_id=data["engine_id"])
114
+
115
+ async def get_session(self) -> Session | None:
116
+ data = await self._call("context.get_session")
117
+ return Session(_host=self._host, _identity=data["identity"], _handle=data["handle"]) if data else None
118
+
119
+ async def scope(self) -> ContextScope:
120
+ data = await self._call("context.scope")
121
+ data["user"] = ContextUser(**data["user"])
122
+ if data.get("session"):
123
+ item = data["session"]
124
+ proxy = Session(_host=self._host, _identity=item["identity"], _handle=item["handle"])
125
+ data["session"] = ContextSession(proxy.session_id, proxy)
126
+ if data.get("todo"):
127
+ item = dict(data["todo"])
128
+ item["_handle"] = item.pop("handle")
129
+ data["todo"] = TodoPlanScope(**item)
130
+ if data.get("timer_execution"):
131
+ timer = data["timer_execution"]
132
+ data["timer_execution"] = TimerExecutionBinding(
133
+ TimerOwner(**timer["owner"]), SingleAgentSource(**timer["source"]), timer["workspace"])
134
+ return ContextScope(**data)
135
+
136
+ async def bind_scope(self, scope: ContextScope) -> None:
137
+ if not isinstance(scope, ContextScope):
138
+ raise TypeError("scope must be ContextScope")
139
+ self._refresh(await self._call("context.bind_scope", scope=scope))
140
+
141
+ async def fork(self, spec: ContextChildSpec) -> Context:
142
+ if not isinstance(spec, ContextChildSpec):
143
+ raise TypeError("spec must be ContextChildSpec")
144
+ return Context(_host=self._host, _data=await self._call("context.fork", spec=spec))
145
+
146
+ def state(self) -> ContextStateView:
147
+ return ContextStateView(self._host, self._handle)
148
+
149
+ async def set_state(self, state: ContextState) -> ContextStateUpdate:
150
+ if not isinstance(state, ContextState):
151
+ raise TypeError("state must be ContextState")
152
+ return ContextStateUpdate(await self._call("context.set_state", state=state))
153
+
154
+ async def append_stack(self, entry: ContextStackDraft) -> int:
155
+ if not isinstance(entry, ContextStackDraft):
156
+ raise TypeError("entry must be ContextStackDraft")
157
+ return await self._call("context.append_stack", entry=entry)
158
+
159
+ async def stacks(self, query: ContextStackQuery) -> list[ContextStack]:
160
+ if not isinstance(query, ContextStackQuery):
161
+ raise TypeError("query must be ContextStackQuery")
162
+ result = []
163
+ for item in await self._call("context.stacks", query=query):
164
+ meta = item["task_meta"]
165
+ meta["ty"] = TaskType(TaskTypeKind(meta["ty"]["kind"]), meta["ty"].get("value"))
166
+ item["task_meta"] = TaskMeta(**meta)
167
+ item["phase"] = ContextStackPhase(item["phase"])
168
+ result.append(ContextStack(**item))
169
+ return result
170
+
171
+ async def cancel(self, reason: str = "Cancelled by plugin") -> None:
172
+ await self._call("context.cancel", reason=reason)
173
+
174
+ async def cancel_run(self, reason: str = "Cancelled by plugin") -> None:
175
+ await self._call("context.cancel_run", reason=reason)
fae_plugin/engine.py ADDED
@@ -0,0 +1,16 @@
1
+ from typing import Any
2
+
3
+
4
+ class Engine:
5
+ __slots__ = ("_engine_id", "_host")
6
+
7
+ def __init__(self, *, _host: Any, _engine_id: str):
8
+ self._host = _host
9
+ self._engine_id = _engine_id
10
+
11
+ @property
12
+ def engine_id(self) -> str:
13
+ return self._engine_id
14
+
15
+ def same_engine(self, other: "Engine") -> bool:
16
+ return isinstance(other, Engine) and self._engine_id == other._engine_id
fae_plugin/errors.py ADDED
@@ -0,0 +1,96 @@
1
+ """Stable errors returned by the host and the plugin dispatcher."""
2
+ from typing import Any
3
+
4
+
5
+ class PluginHostError(Exception):
6
+ code = "plugin_error"
7
+
8
+ def __init__(self, message: str, **details: Any) -> None:
9
+ super().__init__(message)
10
+ self.message = message
11
+ self.details = details
12
+
13
+
14
+ class ContextUnavailable(PluginHostError):
15
+ code = "context_unavailable"
16
+
17
+
18
+ class ContextFinished(PluginHostError):
19
+ code = "context_finished"
20
+
21
+
22
+ class InvalidStateTransition(PluginHostError):
23
+ code = "invalid_state_transition"
24
+
25
+
26
+ class ScopeAlreadyBound(PluginHostError):
27
+ code = "scope_already_bound"
28
+
29
+
30
+ class InvalidScope(PluginHostError):
31
+ code = "invalid_scope"
32
+
33
+
34
+ class InvalidHandle(PluginHostError):
35
+ code = "invalid_handle"
36
+
37
+
38
+ class HandleExpired(PluginHostError):
39
+ code = "handle_expired"
40
+
41
+
42
+ class StateViewClosed(PluginHostError):
43
+ code = "state_view_closed"
44
+
45
+
46
+ class UnsupportedOutputType(PluginHostError):
47
+ code = "unsupported_output_type"
48
+
49
+
50
+ class UnsupportedValueType(PluginHostError):
51
+ code = "unsupported_value_type"
52
+
53
+
54
+ class StackCapacityExceeded(PluginHostError):
55
+ code = "stack_capacity_exceeded"
56
+
57
+
58
+ class InvalidStackEntry(PluginHostError):
59
+ code = "invalid_stack_entry"
60
+
61
+
62
+ class SessionBusy(PluginHostError):
63
+ code = "session_busy"
64
+
65
+
66
+ class SessionUnavailable(PluginHostError):
67
+ code = "session_unavailable"
68
+
69
+
70
+ class InvalidMessage(PluginHostError):
71
+ code = "invalid_message"
72
+
73
+
74
+ class HostCallTimeout(PluginHostError):
75
+ code = "host_call_timeout"
76
+
77
+
78
+ class HookCancelled(PluginHostError):
79
+ code = "hook_cancelled"
80
+
81
+
82
+ class InvalidHookNext(PluginHostError):
83
+ code = "invalid_hook_next"
84
+
85
+
86
+ class MissingChainHandler(PluginHostError):
87
+ code = "missing_chain_handler"
88
+
89
+
90
+ def from_wire(error: dict[str, Any]) -> PluginHostError:
91
+ cls = next((c for c in PluginHostError.__subclasses__()
92
+ if c.code == error.get("code")), PluginHostError)
93
+ result = cls(error.get("message", "Plugin host error"),
94
+ **{k: v for k, v in error.items() if k not in ("code", "message")})
95
+ result.code = error.get("code", result.code)
96
+ return result
fae_plugin/hooks.py ADDED
@@ -0,0 +1,56 @@
1
+ """Direct hook defaults preserve their inputs."""
2
+ from typing import Any
3
+ from .context import Context
4
+ from .types import ModelRequest, ModelResponse, ToolRequest, ToolResponse, SessionMessage, UserMemory
5
+
6
+
7
+ class SingleAgentHook:
8
+ async def on_query(self, ctx: Context, query: str) -> str:
9
+ return query
10
+
11
+ async def on_prompt(self, ctx: Context, prompt: str) -> str:
12
+ return prompt
13
+
14
+ async def on_memory(self, ctx: Context, memories: list[UserMemory]) -> list[UserMemory]:
15
+ return memories
16
+
17
+ async def on_history(self, ctx: Context, history: list[SessionMessage]) -> list[SessionMessage]:
18
+ return history
19
+
20
+ async def on_compression(self, ctx: Context, request: ModelRequest) -> ModelRequest:
21
+ return request
22
+
23
+ async def on_model_req(self, ctx: Context, request: ModelRequest) -> ModelRequest:
24
+ return request
25
+
26
+ async def on_model_resp(self, ctx: Context, response: ModelResponse) -> ModelResponse:
27
+ return response
28
+
29
+ async def on_tools_req(self, ctx: Context, request: ToolRequest) -> ToolRequest:
30
+ return request
31
+
32
+ async def on_tools_resp(self, ctx: Context, response: ToolResponse) -> ToolResponse:
33
+ return response
34
+
35
+ async def on_save(self, ctx: Context, messages: list[SessionMessage]) -> list[SessionMessage]:
36
+ return messages
37
+
38
+
39
+ class ToolsHook:
40
+ _channel: str
41
+ def channel(self) -> str:
42
+ return self._channel
43
+
44
+ async def desc(self, ctx: Context, tool_name: str) -> dict[str, Any]:
45
+ raise NotImplementedError("ToolsHook.desc must be implemented")
46
+
47
+ async def exec(self, ctx: Context, request: ToolRequest) -> ToolResponse:
48
+ raise NotImplementedError("ToolsHook.exec must be implemented")
49
+
50
+
51
+ class ModelHook:
52
+ async def match_model(self, ctx: Context, model: str) -> bool:
53
+ raise NotImplementedError("ModelHook.match_model must be implemented")
54
+
55
+ async def exec(self, ctx: Context, request: ModelRequest) -> ModelResponse:
56
+ raise NotImplementedError("ModelHook.exec must be implemented")
fae_plugin/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,173 @@
1
+ """Construct immutable member records; chain members are not Rust execution nodes."""
2
+ from __future__ import annotations
3
+ import builtins
4
+ import importlib.util
5
+ import inspect
6
+ import sys
7
+ import types
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Any
11
+ from .chain import ChainModelHook, ChainSingleAgentHook, ChainToolsHook
12
+ from .hooks import ModelHook, SingleAgentHook, ToolsHook
13
+
14
+ AGENT_METHODS = ("on_query", "on_prompt", "on_memory", "on_history", "on_compression",
15
+ "on_model_req", "on_model_resp", "on_tools_req", "on_tools_resp", "on_save")
16
+
17
+
18
+ class ModuleLoader:
19
+ """Resolve local imports in a per-member namespace, including plain import helper."""
20
+ def __init__(self, plugin_id: str, root: Path):
21
+ self.root = root.resolve()
22
+ self.namespace = f"_fae_plugin_{plugin_id}"
23
+ package = types.ModuleType(self.namespace)
24
+ package.__path__ = [str(self.root)]
25
+ sys.modules[self.namespace] = package
26
+ self.modules: dict[Path, Any] = {}
27
+
28
+ def load(self, file: Path) -> Any:
29
+ file = file.resolve()
30
+ if file in self.modules:
31
+ return self.modules[file]
32
+ if not file.is_relative_to(self.root):
33
+ raise ValueError("Code entry escapes the plugin root")
34
+ relative = file.relative_to(self.root).with_suffix("")
35
+ is_package = file.name == "__init__.py"
36
+ pieces = relative.parts[:-1] if is_package else relative.parts
37
+ for n in range(1, len(pieces)):
38
+ name = self.namespace + "." + ".".join(pieces[:n])
39
+ if name not in sys.modules:
40
+ init = self.root.joinpath(*pieces[:n], "__init__.py")
41
+ if init.is_file():
42
+ self.load(init)
43
+ continue
44
+ package = types.ModuleType(name)
45
+ package.__path__ = [str(self.root.joinpath(*pieces[:n]))]
46
+ sys.modules[name] = package
47
+ name = self.namespace + ("." + ".".join(pieces) if pieces else "")
48
+ spec = importlib.util.spec_from_file_location(
49
+ name, file, submodule_search_locations=[str(file.parent)] if is_package else None)
50
+ if spec is None or spec.loader is None:
51
+ raise ValueError("Cannot load implementation module")
52
+ module = importlib.util.module_from_spec(spec)
53
+ module.__dict__["__builtins__"] = {**vars(builtins), "__import__": self._import}
54
+ self.modules[file] = module
55
+ sys.modules[name] = module
56
+ parent, _, child = name.rpartition(".")
57
+ if parent in sys.modules:
58
+ setattr(sys.modules[parent], child, module)
59
+ spec.loader.exec_module(module)
60
+ return module
61
+
62
+ def _import(self, name: str, globals: Any = None, locals: Any = None,
63
+ fromlist: Any = (), level: int = 0) -> Any:
64
+ local_name = name
65
+ if level:
66
+ resolved = importlib.util.resolve_name("." * level + name, globals["__package__"])
67
+ if resolved == self.namespace:
68
+ local_name = ""
69
+ elif resolved.startswith(self.namespace + "."):
70
+ local_name = resolved[len(self.namespace) + 1:]
71
+ else:
72
+ return builtins.__import__(name, globals, locals, fromlist, level)
73
+ path = self.root.joinpath(*local_name.split(".")) if local_name else self.root
74
+ file, package = path.with_suffix(".py"), path / "__init__.py"
75
+ module: Any = None
76
+ if local_name and file.is_file():
77
+ module = self.load(file)
78
+ elif package.is_file():
79
+ module = self.load(package)
80
+ elif path.is_dir():
81
+ key = self.namespace + ("." + local_name if local_name else "")
82
+ if key not in sys.modules:
83
+ module = types.ModuleType(key)
84
+ module.__path__ = [str(path)]
85
+ sys.modules[key] = module
86
+ module = sys.modules[key]
87
+ if module is not None:
88
+ if fromlist:
89
+ for item in fromlist:
90
+ if item != "*" and not hasattr(module, item):
91
+ child_file, child_package = path / f"{item}.py", path / item / "__init__.py"
92
+ if child_file.is_file() or child_package.is_file():
93
+ setattr(module, item, self.load(child_file if child_file.is_file() else child_package))
94
+ return module
95
+ return sys.modules[self.namespace + "." + local_name.split(".")[0]]
96
+ return builtins.__import__(name, globals, locals, fromlist, level)
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class Instance:
101
+ key: str
102
+ plugin_id: str
103
+ mount: dict[str, Any]
104
+ object: Any
105
+ base: type
106
+ mode: str
107
+
108
+ def matches(self, point: str, location: str | None) -> bool:
109
+ if self.mount["point"] != point:
110
+ return False
111
+ if point == "ModelHook":
112
+ return True
113
+ field = {"SingleAgentHook": "agent_id", "ToolsHook": "channel"}[point]
114
+ return self.mount.get(field) == location or (field == "agent_id" and field not in self.mount)
115
+
116
+
117
+ def register(members: list[dict[str, Any]]) -> list[Instance]:
118
+ records = []
119
+ for member in members:
120
+ source = Path(member["source"])
121
+ loader = ModuleLoader(member["id"], source.parent if source.is_file() else source)
122
+ config = member["declaration"]
123
+ mode = config["registration_mode"]
124
+ bases = {"direct": {"SingleAgentHook": SingleAgentHook, "ToolsHook": ToolsHook, "ModelHook": ModelHook},
125
+ "chain": {"SingleAgentHook": ChainSingleAgentHook, "ToolsHook": ChainToolsHook,
126
+ "ModelHook": ChainModelHook}}[mode]
127
+ for index, mount in enumerate(config["mounts"]):
128
+ if source.is_file():
129
+ module, class_name = loader.load(source), mount["implementation"]
130
+ else:
131
+ file, class_name = mount["implementation"].split(":")
132
+ module = loader.load(source / file)
133
+ cls = getattr(module, class_name, None)
134
+ base = bases[mount["point"]]
135
+ if not inspect.isclass(cls) or not issubclass(cls, base) or cls is base:
136
+ raise ValueError(f"{member['id']}:{class_name} must inherit {base.__name__}")
137
+ methods = AGENT_METHODS if mount["point"] == "SingleAgentHook" else (
138
+ ("desc", "exec") if mount["point"] == "ToolsHook" else ("match_model", "exec"))
139
+ for method in methods:
140
+ function = getattr(cls, method)
141
+ if mode == "chain" and not inspect.iscoroutinefunction(function):
142
+ raise ValueError("Chain hook methods must be async")
143
+ signature = inspect.signature(function)
144
+ params = list(signature.parameters.values())
145
+ chained = mode == "chain" and method != "match_model"
146
+ count = 4 if chained else 3
147
+ if len(params) != count or any(p.kind not in (
148
+ inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
149
+ for p in params[:3]):
150
+ raise ValueError(f"Invalid {class_name}.{method} signature")
151
+ if chained and (params[3].name != "next" or params[3].kind != inspect.Parameter.KEYWORD_ONLY
152
+ or params[3].default != inspect.Parameter.empty):
153
+ raise ValueError("Chain next must be a required keyword-only argument")
154
+ if (method == "match_model" or (mode == "direct" and mount["point"] != "SingleAgentHook")) and function is getattr(base, method):
155
+ raise ValueError(f"{class_name}.{method} must be implemented")
156
+ obj: Any = cls()
157
+ if not isinstance(obj, cls):
158
+ if inspect.iscoroutine(obj):
159
+ obj.close()
160
+ raise ValueError(f"{member['id']}:{class_name} did not construct a hook instance")
161
+ if mount["point"] == "ToolsHook":
162
+ setattr(obj, "_channel", mount["channel"])
163
+ records.append(Instance(f"{member['id']}:{index}", member["id"], mount, obj, base, mode))
164
+ for record in records:
165
+ if record.mode != "chain" or record.mount["point"] == "SingleAgentHook":
166
+ continue
167
+ point = record.mount["point"]
168
+ location = record.mount["channel"] if point == "ToolsHook" else None
169
+ for method in ("desc", "exec") if point == "ToolsHook" else ("exec",):
170
+ if not any(r.matches(point, location) and getattr(type(r.object), method) is not getattr(r.base, method)
171
+ for r in records):
172
+ raise ValueError(f"Chain {point} {location} has no {method} implementation")
173
+ return records
fae_plugin/session.py ADDED
@@ -0,0 +1,42 @@
1
+ from typing import Any
2
+ from .types import MessageReceipt
3
+
4
+
5
+ class Session:
6
+ __slots__ = ("_host", "_identity", "_handle")
7
+
8
+ def __init__(self, *, _host: Any, _identity: dict[str, Any], _handle: str):
9
+ self._host = _host
10
+ self._identity = dict(_identity)
11
+ self._handle = _handle
12
+
13
+ @property
14
+ def session_id(self) -> str:
15
+ return self._identity["session_id"]
16
+
17
+ @property
18
+ def user_id(self) -> str:
19
+ return self._identity["user_id"]
20
+
21
+ @property
22
+ def agent_id(self) -> str | None:
23
+ return self._identity.get("agent_id")
24
+
25
+ @property
26
+ def turn_id(self) -> int | None:
27
+ return self._identity.get("turn_id")
28
+
29
+ @property
30
+ def run_id(self) -> str | None:
31
+ return self._identity.get("run_id")
32
+
33
+ async def send(self, text: str) -> MessageReceipt:
34
+ if not isinstance(text, str):
35
+ raise TypeError("Session.send requires text")
36
+ if not text.strip():
37
+ raise ValueError("Session message must not be blank")
38
+ result = await self._host.call("session.send", {"handle": self._handle, "text": text})
39
+ return MessageReceipt(**result)
40
+
41
+ def _wire_reference(self) -> dict[str, str]:
42
+ return {"handle": self._handle}