open-source-alchemy-framework 1.0.1__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.
Files changed (51) hide show
  1. oaf/__init__.py +47 -0
  2. oaf/adapters/__init__.py +9 -0
  3. oaf/adapters/base.py +40 -0
  4. oaf/adapters/desktop_pet.py +254 -0
  5. oaf/adapters/local_chat.py +47 -0
  6. oaf/adapters/mock_environment.py +27 -0
  7. oaf/adapters/state.py +109 -0
  8. oaf/core/__init__.py +6 -0
  9. oaf/core/coordination.py +69 -0
  10. oaf/core/event_processing.py +51 -0
  11. oaf/core/lifecycle.py +15 -0
  12. oaf/core/soul_core.py +162 -0
  13. oaf/core/status.py +29 -0
  14. oaf/modules/__init__.py +10 -0
  15. oaf/modules/base.py +39 -0
  16. oaf/modules/llm.py +36 -0
  17. oaf/modules/memory.py +50 -0
  18. oaf/modules/personality.py +46 -0
  19. oaf/modules/wishes.py +52 -0
  20. oaf/protocols.py +445 -0
  21. oaf/resources.py +29 -0
  22. open_source_alchemy_framework-1.0.1.dist-info/METADATA +221 -0
  23. open_source_alchemy_framework-1.0.1.dist-info/RECORD +51 -0
  24. open_source_alchemy_framework-1.0.1.dist-info/WHEEL +5 -0
  25. open_source_alchemy_framework-1.0.1.dist-info/licenses/LICENSE +201 -0
  26. open_source_alchemy_framework-1.0.1.dist-info/top_level.txt +3 -0
  27. protocols/README.md +26 -0
  28. protocols/__init__.py +1 -0
  29. protocols/events/__init__.py +1 -0
  30. protocols/events/event-result.schema.json +15 -0
  31. protocols/events/event.schema.json +21 -0
  32. protocols/expressions/__init__.py +1 -0
  33. protocols/expressions/action-feedback.schema.json +16 -0
  34. protocols/expressions/action.schema.json +17 -0
  35. protocols/expressions/capability.schema.json +15 -0
  36. protocols/expressions/expression.schema.json +16 -0
  37. protocols/expressions/playback.schema.json +17 -0
  38. protocols/expressions/safety.schema.json +14 -0
  39. protocols/expressions/speech.schema.json +16 -0
  40. protocols/expressions/viseme.schema.json +17 -0
  41. protocols/memory/__init__.py +1 -0
  42. protocols/memory/memory.schema.json +19 -0
  43. protocols/state/__init__.py +1 -0
  44. protocols/state/adapter-status.schema.json +18 -0
  45. protocols/state/state.schema.json +28 -0
  46. protocols/wishes/__init__.py +1 -0
  47. protocols/wishes/wish.schema.json +20 -0
  48. templates/__init__.py +1 -0
  49. templates/blank_personality/README.md +15 -0
  50. templates/blank_personality/__init__.py +1 -0
  51. templates/blank_personality/personality.json +22 -0
oaf/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """Open Source Alchemy Framework — 虚拟角色通用炼成阵。
2
+
3
+ 本包只包含公开架构、协议和 Mock 实现,不包含任何私有角色数据。
4
+ """
5
+
6
+ from .protocols import (
7
+ ActionFeedback,
8
+ ActionRequest,
9
+ AdapterStatus,
10
+ AudioPlaybackEvent,
11
+ CapabilityDescriptor,
12
+ ConnectionState,
13
+ Event,
14
+ EventResult,
15
+ ExpressionIntent,
16
+ MemoryRecord,
17
+ SafetyPolicy,
18
+ SpeechIntent,
19
+ StateSnapshot,
20
+ VisemeEvent,
21
+ WishRecord,
22
+ )
23
+ from .core.soul_core import MockSoulCore, SoulCore
24
+ from .modules.personality import BlankPersonalityModule
25
+ from .modules.memory import InMemoryMemoryModule
26
+ from .modules.wishes import SimpleWishModule
27
+ from .modules.llm import BaseLLMAdapter, EchoLLMAdapter
28
+ from .modules.base import Module
29
+ from .adapters.base import BaseEnvironmentAdapter
30
+ from .adapters.desktop_pet import DesktopPetAdapter, MockDesktopPetAdapter
31
+ from .adapters.local_chat import LocalChatAdapter
32
+ from .adapters.mock_environment import MockEnvironmentAdapter
33
+
34
+ __all__ = [
35
+ "ActionFeedback", "ActionRequest", "AdapterStatus", "AudioPlaybackEvent",
36
+ "CapabilityDescriptor", "ConnectionState", "Event", "EventResult",
37
+ "ExpressionIntent", "MemoryRecord", "SafetyPolicy", "SpeechIntent",
38
+ "StateSnapshot", "VisemeEvent", "WishRecord",
39
+ "SoulCore", "MockSoulCore",
40
+ "BlankPersonalityModule", "InMemoryMemoryModule", "SimpleWishModule",
41
+ "BaseLLMAdapter", "EchoLLMAdapter", "Module",
42
+ "BaseEnvironmentAdapter", "DesktopPetAdapter", "MockDesktopPetAdapter",
43
+ "LocalChatAdapter", "MockEnvironmentAdapter",
44
+ ]
45
+
46
+ __version__ = "1.0.1"
47
+ PROTOCOL_VERSION = "0.1"
@@ -0,0 +1,9 @@
1
+ """环境适配器。"""
2
+
3
+ from .base import BaseEnvironmentAdapter
4
+ from .desktop_pet import DesktopPetAdapter, MockDesktopPetAdapter
5
+ from .local_chat import LocalChatAdapter
6
+ from .mock_environment import MockEnvironmentAdapter
7
+
8
+ __all__ = ["BaseEnvironmentAdapter", "DesktopPetAdapter", "MockDesktopPetAdapter",
9
+ "LocalChatAdapter", "MockEnvironmentAdapter"]
oaf/adapters/base.py ADDED
@@ -0,0 +1,40 @@
1
+ """环境适配器基类:把环境差异挡在核心之外。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any
7
+
8
+ from ..protocols import Event, EventResult, ExpressionIntent
9
+
10
+
11
+ class BaseEnvironmentAdapter(ABC):
12
+ adapter_id = "environment"
13
+ capabilities: tuple[str, ...] = ("text_in", "text_out")
14
+
15
+ def __init__(self, core: Any = None) -> None:
16
+ self.core = core
17
+ self.started = False
18
+
19
+ def start(self, core: Any | None = None) -> None:
20
+ if core is not None:
21
+ self.core = core
22
+ if self.core is None:
23
+ raise RuntimeError("environment adapter needs a core")
24
+ self.started = True
25
+
26
+ def stop(self) -> None:
27
+ self.started = False
28
+
29
+ def health(self) -> dict[str, Any]:
30
+ return {"adapter_id": self.adapter_id, "started": self.started,
31
+ "capabilities": list(self.capabilities)}
32
+
33
+ @abstractmethod
34
+ def send(self, intent: ExpressionIntent) -> dict[str, Any]:
35
+ ...
36
+
37
+ def receive(self, event: Event) -> EventResult:
38
+ if self.core is None:
39
+ raise RuntimeError("environment adapter is not attached")
40
+ return self.core.receive_event(event)
@@ -0,0 +1,254 @@
1
+ """载体无关的桌面桌宠接口。
2
+
3
+ 这里只定义接入协议,不包含 Live2D/Godot 资产或具体动画实现。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from typing import Any
10
+
11
+ from ..protocols import (
12
+ ActionFeedback,
13
+ ActionRequest,
14
+ AdapterStatus,
15
+ AudioPlaybackEvent,
16
+ CapabilityDescriptor,
17
+ ConnectionState,
18
+ Event,
19
+ EventResult,
20
+ ExpressionIntent,
21
+ SpeechIntent,
22
+ VisemeEvent,
23
+ new_id,
24
+ utcnow,
25
+ )
26
+ from .base import BaseEnvironmentAdapter
27
+ from .state import AudioPlaybackTracker, ProtocolStateError, VisemeSequenceTracker
28
+
29
+ SUPPORTED_CAPABILITIES = (
30
+ "text", "expression", "action", "speech",
31
+ "audio_playback", "viseme", "status", "reconnect",
32
+ )
33
+
34
+
35
+ class DesktopPetAdapter(BaseEnvironmentAdapter):
36
+ """桌宠接入的公共层;具体载体继承它并映射自己的动画/TTS。"""
37
+
38
+ adapter_id = "desktop-pet"
39
+ capabilities = SUPPORTED_CAPABILITIES
40
+
41
+ def __init__(self, core: Any = None) -> None:
42
+ super().__init__(core)
43
+ self.connection_state = ConnectionState.DISCONNECTED
44
+ self.last_error = ""
45
+ self.unsupported_capabilities: tuple[str, ...] = ()
46
+ self.playback_tracker = AudioPlaybackTracker()
47
+ self.viseme_tracker = VisemeSequenceTracker()
48
+
49
+ def initialize(self, core: Any | None = None) -> None:
50
+ """Alias for the carrier lifecycle; starts the adapter and connects."""
51
+ self.start(core)
52
+
53
+ def start(self, core: Any | None = None) -> None:
54
+ super().start(core)
55
+ self.connect()
56
+
57
+ def stop(self) -> None:
58
+ self.disconnect()
59
+ super().stop()
60
+
61
+ def connect(self) -> None:
62
+ self.connection_state = ConnectionState.CONNECTED
63
+ self.last_error = ""
64
+
65
+ def disconnect(self) -> None:
66
+ self.connection_state = ConnectionState.DISCONNECTED
67
+
68
+ def reconnect(self) -> None:
69
+ self.connection_state = ConnectionState.CONNECTING
70
+ self.connect()
71
+
72
+ def supports(self, capability: str) -> bool:
73
+ return capability in self.capabilities and capability not in self.unsupported_capabilities
74
+
75
+ def capability_descriptors(self) -> list[CapabilityDescriptor]:
76
+ return [CapabilityDescriptor(
77
+ name=name,
78
+ supported=name not in self.unsupported_capabilities,
79
+ description=f"desktop pet capability: {name}",
80
+ ) for name in self.capabilities]
81
+
82
+ def _reject(self, capability: str, request: Any) -> dict[str, Any]:
83
+ payload = {"ok": False, "allowed": False,
84
+ "error": f"unsupported capability: {capability}",
85
+ "capability": capability}
86
+ for key in ("request_id", "speech_id", "playback_id", "viseme_id"):
87
+ value = getattr(request, key, "")
88
+ if value:
89
+ payload[key] = value
90
+ self.last_error = payload["error"]
91
+ return payload
92
+
93
+ def receive_text(self, text: str, session_id: str = "desktop") -> Any:
94
+ """Translate user text into the same Event protocol as other adapters."""
95
+ event = Event(
96
+ event_type="environment.message",
97
+ source=self.adapter_id,
98
+ target="soul",
99
+ session_id=session_id,
100
+ payload={"text": text},
101
+ )
102
+ if not self.supports("text"):
103
+ return EventResult(event_id=event.event_id, status="failed",
104
+ error="unsupported capability: text")
105
+ return self.receive(event)
106
+
107
+ def send_text(self, text: str, session_id: str = "desktop") -> dict[str, Any]:
108
+ return self.send(ExpressionIntent(text=text, session_id=session_id,
109
+ metadata={"adapter": self.adapter_id}))
110
+
111
+ def send(self, intent: ExpressionIntent | ActionRequest | SpeechIntent |
112
+ AudioPlaybackEvent | VisemeEvent) -> dict[str, Any]:
113
+ mapping = {
114
+ ExpressionIntent: "expression",
115
+ ActionRequest: "action",
116
+ SpeechIntent: "speech",
117
+ AudioPlaybackEvent: "audio_playback",
118
+ VisemeEvent: "viseme",
119
+ }
120
+ capability = mapping.get(type(intent))
121
+ if capability is None:
122
+ raise TypeError(f"unsupported desktop intent: {type(intent).__name__}")
123
+ if not self.supports(capability):
124
+ return self._reject(capability, intent)
125
+ if isinstance(intent, ExpressionIntent):
126
+ return self.on_expression(intent)
127
+ if isinstance(intent, ActionRequest):
128
+ return self.on_action(intent)
129
+ if isinstance(intent, SpeechIntent):
130
+ return self.on_speech(intent)
131
+ if isinstance(intent, AudioPlaybackEvent):
132
+ return self.on_playback(intent)
133
+ if isinstance(intent, VisemeEvent):
134
+ return self.on_viseme(intent)
135
+ raise TypeError(f"unsupported desktop intent: {type(intent).__name__}")
136
+
137
+ def on_expression(self, intent: ExpressionIntent) -> dict[str, Any]:
138
+ return {"ok": True, "type": "expression", "intent": intent.to_dict()}
139
+
140
+ def on_action(self, request: ActionRequest) -> dict[str, Any]:
141
+ policy = getattr(self.core, "policy", None)
142
+ if policy is not None:
143
+ allowed, _, reason = policy.check(request)
144
+ if not allowed:
145
+ return ActionFeedback(request_id=request.request_id,
146
+ status="denied", error=reason,
147
+ session_id=request.metadata.get("session_id", "desktop")).to_dict()
148
+ return ActionFeedback(request_id=request.request_id,
149
+ status="accepted").to_dict()
150
+
151
+ def on_speech(self, intent: SpeechIntent) -> dict[str, Any]:
152
+ return {"ok": True, "type": "speech", "intent": intent.to_dict()}
153
+
154
+ def on_playback(self, event: AudioPlaybackEvent) -> dict[str, Any]:
155
+ try:
156
+ result = self.playback_tracker.apply(event)
157
+ except ProtocolStateError as exc:
158
+ self.last_error = str(exc)
159
+ return {"ok": False, "type": "audio_playback",
160
+ "error": str(exc), "playback_id": event.playback_id}
161
+ return {"ok": True, "type": "audio_playback",
162
+ "event": event.to_dict(), **result}
163
+
164
+ def on_viseme(self, event: VisemeEvent) -> dict[str, Any]:
165
+ try:
166
+ result = self.viseme_tracker.apply(event)
167
+ except ProtocolStateError as exc:
168
+ self.last_error = str(exc)
169
+ return {"ok": False, "type": "viseme",
170
+ "error": str(exc), "viseme_id": event.viseme_id}
171
+ return {"ok": True, "type": "viseme",
172
+ "event": event.to_dict(), **result}
173
+
174
+ def status(self) -> AdapterStatus:
175
+ return AdapterStatus(
176
+ adapter_id=self.adapter_id,
177
+ lifecycle="started" if self.started else "stopped",
178
+ connection_state=self.connection_state.value,
179
+ healthy=self.started and self.connection_state is ConnectionState.CONNECTED,
180
+ capabilities=list(self.capabilities),
181
+ updated_at=utcnow(),
182
+ last_error=self.last_error,
183
+ metadata={"unsupported_capabilities": list(self.unsupported_capabilities)},
184
+ )
185
+
186
+ def health(self) -> dict[str, Any]:
187
+ payload = super().health()
188
+ payload.update({"connection_state": self.connection_state.value,
189
+ "last_error": self.last_error})
190
+ return payload
191
+
192
+
193
+ class MockDesktopPetAdapter(DesktopPetAdapter):
194
+ """只证明协议可用;不加载模型、不播放音频、不连接 TTS。"""
195
+
196
+ adapter_id = "mock-desktop-pet"
197
+
198
+ def __init__(self, core: Any = None) -> None:
199
+ super().__init__(core)
200
+ self.outbound: list[dict[str, Any]] = []
201
+ self.playback_events: list[dict[str, Any]] = []
202
+ self.viseme_events: list[dict[str, Any]] = []
203
+ self.action_feedback: list[dict[str, Any]] = []
204
+ self.received_text: list[str] = []
205
+
206
+ def receive_text(self, text: str, session_id: str = "desktop") -> Any:
207
+ self.received_text.append(text)
208
+ return super().receive_text(text, session_id)
209
+
210
+ def on_expression(self, intent: ExpressionIntent) -> dict[str, Any]:
211
+ payload = intent.to_dict()
212
+ self.outbound.append(payload)
213
+ return {"ok": True, "type": "expression", "intent": payload}
214
+
215
+ def on_action(self, request: ActionRequest) -> dict[str, Any]:
216
+ result = super().on_action(request)
217
+ if result.get("status") != "denied":
218
+ result = ActionFeedback(request_id=request.request_id,
219
+ status="completed",
220
+ result={"simulated": True}).to_dict()
221
+ self.action_feedback.append(result)
222
+ return result
223
+
224
+ def on_speech(self, intent: SpeechIntent) -> dict[str, Any]:
225
+ self.outbound.append({"type": "speech", **intent.to_dict()})
226
+ playback_id = new_id("play")
227
+ base_ms = int(time.time() * 1000)
228
+ for index, state in enumerate(("queued", "started", "completed")):
229
+ result = self.on_playback(AudioPlaybackEvent(
230
+ state=state, playback_id=playback_id, speech_id=intent.speech_id,
231
+ session_id=intent.session_id, timestamp_ms=base_ms + index))
232
+ if not result.get("ok"):
233
+ return result
234
+ for index, start in enumerate((0, 150, 300)):
235
+ result = self.on_viseme(VisemeEvent(
236
+ viseme_id=f"viseme-{index + 1}", start_ms=start,
237
+ duration_ms=120, sequence=index, speech_id=intent.speech_id,
238
+ session_id=intent.session_id))
239
+ if not result.get("ok"):
240
+ return result
241
+ return {"ok": True, "type": "speech", "intent": intent.to_dict(),
242
+ "simulated_playback": True, "playback_id": playback_id}
243
+
244
+ def on_playback(self, event: AudioPlaybackEvent) -> dict[str, Any]:
245
+ result = super().on_playback(event)
246
+ if result.get("ok") and not result.get("duplicate"):
247
+ self.playback_events.append(event.to_dict())
248
+ return result
249
+
250
+ def on_viseme(self, event: VisemeEvent) -> dict[str, Any]:
251
+ result = super().on_viseme(event)
252
+ if result.get("ok") and not result.get("duplicate"):
253
+ self.viseme_events.append(event.to_dict())
254
+ return result
@@ -0,0 +1,47 @@
1
+ """本地聊天适配器:无网络、无真实账号的示例。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ..protocols import Event, ExpressionIntent
8
+ from ..modules.llm import LLMAdapter
9
+ from .base import BaseEnvironmentAdapter
10
+
11
+
12
+ class LocalChatAdapter(BaseEnvironmentAdapter):
13
+ adapter_id = "local-chat"
14
+ capabilities = ("text_in", "text_out", "session")
15
+
16
+ def __init__(self, core: Any, llm: LLMAdapter) -> None:
17
+ super().__init__(core)
18
+ self.llm = llm
19
+ self.sent: list[dict[str, Any]] = []
20
+
21
+ def send_text(self, text: str, session_id: str = "local") -> ExpressionIntent:
22
+ if not self.started:
23
+ raise RuntimeError("call start() first")
24
+ event = Event(
25
+ event_type="environment.message",
26
+ source=self.adapter_id,
27
+ target="soul",
28
+ session_id=session_id,
29
+ payload={"text": text},
30
+ )
31
+ self.receive(event)
32
+ bundle = self.core.build_context(session_id, text)
33
+ messages = [
34
+ {"role": "system", "content": bundle.system_prompt()},
35
+ {"role": "user", "content": text},
36
+ ]
37
+ reply = self.llm.complete(messages)
38
+ intent = ExpressionIntent(text=reply, session_id=session_id,
39
+ metadata={"adapter": self.adapter_id})
40
+ self.core.deliver(intent)
41
+ self.send(intent)
42
+ return intent
43
+
44
+ def send(self, intent: ExpressionIntent) -> dict[str, Any]:
45
+ payload = intent.to_dict()
46
+ self.sent.append(payload)
47
+ return payload
@@ -0,0 +1,27 @@
1
+ """Mock 环境:只记录输入输出,方便测试和协议演示。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ..protocols import Event, ExpressionIntent
8
+ from .base import BaseEnvironmentAdapter
9
+
10
+
11
+ class MockEnvironmentAdapter(BaseEnvironmentAdapter):
12
+ adapter_id = "mock-environment"
13
+ capabilities = ("text_in", "text_out", "event_capture")
14
+
15
+ def __init__(self, core: Any = None) -> None:
16
+ super().__init__(core)
17
+ self.outbound: list[dict[str, Any]] = []
18
+
19
+ def emit(self, text: str, session_id: str = "mock") -> Any:
20
+ event = Event(event_type="environment.message", source=self.adapter_id,
21
+ session_id=session_id, payload={"text": text})
22
+ return self.receive(event)
23
+
24
+ def send(self, intent: ExpressionIntent) -> dict[str, Any]:
25
+ payload = intent.to_dict()
26
+ self.outbound.append(payload)
27
+ return payload
oaf/adapters/state.py ADDED
@@ -0,0 +1,109 @@
1
+ """Stateful protocol guards for playback and viseme streams.
2
+
3
+ Protocol records describe data. These small trackers validate event order
4
+ without turning a protocol dataclass into a scheduler.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from ..protocols import AudioPlaybackEvent, VisemeEvent
12
+
13
+
14
+ class ProtocolStateError(ValueError):
15
+ """A state transition or sequence is invalid."""
16
+
17
+
18
+ PLAYBACK_TRANSITIONS: dict[str, set[str]] = {
19
+ "queued": {"started", "stopped", "failed"},
20
+ "started": {"paused", "completed", "stopped", "failed"},
21
+ "paused": {"resumed", "stopped", "failed"},
22
+ "resumed": {"paused", "completed", "stopped", "failed"},
23
+ "completed": set(),
24
+ "stopped": set(),
25
+ "failed": set(),
26
+ }
27
+
28
+
29
+ class AudioPlaybackTracker:
30
+ """Validate one playback stream per playback_id.
31
+
32
+ A new playback must start with queued. Terminal states never reopen;
33
+ create a new playback_id for a new playback.
34
+ """
35
+
36
+ def __init__(self) -> None:
37
+ self._states: dict[str, dict[str, Any]] = {}
38
+
39
+ def apply(self, event: AudioPlaybackEvent) -> dict[str, Any]:
40
+ record = self._states.get(event.playback_id)
41
+ if record is None:
42
+ if event.state != "queued":
43
+ raise ProtocolStateError(
44
+ f"playback {event.playback_id} must start at queued")
45
+ self._states[event.playback_id] = {
46
+ "state": event.state,
47
+ "timestamp_ms": event.timestamp_ms,
48
+ "speech_id": event.speech_id,
49
+ "session_id": event.session_id,
50
+ }
51
+ return {"ok": True, "duplicate": False, "state": event.state}
52
+
53
+ if event.timestamp_ms < int(record["timestamp_ms"]):
54
+ raise ProtocolStateError("playback event is older than the last event")
55
+ if record["speech_id"] and event.speech_id and record["speech_id"] != event.speech_id:
56
+ raise ProtocolStateError("playback speech_id mismatch")
57
+ if record["session_id"] and event.session_id and record["session_id"] != event.session_id:
58
+ raise ProtocolStateError("playback session_id mismatch")
59
+
60
+ current = str(record["state"])
61
+ if event.state == current:
62
+ return {"ok": True, "duplicate": True, "state": current}
63
+ if event.state not in PLAYBACK_TRANSITIONS[current]:
64
+ raise ProtocolStateError(
65
+ f"illegal playback transition: {current} -> {event.state}")
66
+
67
+ record.update({
68
+ "state": event.state,
69
+ "timestamp_ms": event.timestamp_ms,
70
+ })
71
+ return {"ok": True, "duplicate": False, "state": event.state}
72
+
73
+ def state_of(self, playback_id: str) -> str | None:
74
+ record = self._states.get(playback_id)
75
+ return str(record["state"]) if record else None
76
+
77
+ def snapshot(self) -> dict[str, str]:
78
+ return {key: str(value["state"]) for key, value in self._states.items()}
79
+
80
+
81
+ class VisemeSequenceTracker:
82
+ """Enforce per-session/per-speech nondecreasing sequence ordering."""
83
+
84
+ def __init__(self) -> None:
85
+ self._last: dict[tuple[str, str], tuple[int, str]] = {}
86
+
87
+ def apply(self, event: VisemeEvent) -> dict[str, Any]:
88
+ key = (event.session_id, event.speech_id)
89
+ current = self._last.get(key)
90
+ if current is None:
91
+ self._last[key] = (event.sequence, event.viseme_id)
92
+ return {"ok": True, "duplicate": False, "sequence": event.sequence}
93
+
94
+ last_sequence, last_viseme = current
95
+ if event.sequence < last_sequence:
96
+ raise ProtocolStateError(
97
+ f"viseme sequence moved backwards: {event.sequence} < {last_sequence}")
98
+ if event.sequence == last_sequence:
99
+ if event.viseme_id == last_viseme:
100
+ return {"ok": True, "duplicate": True, "sequence": event.sequence}
101
+ raise ProtocolStateError(
102
+ "duplicate viseme sequence with a different viseme_id")
103
+
104
+ self._last[key] = (event.sequence, event.viseme_id)
105
+ return {"ok": True, "duplicate": False, "sequence": event.sequence}
106
+
107
+ def last_sequence(self, session_id: str, speech_id: str) -> int | None:
108
+ current = self._last.get((session_id, speech_id))
109
+ return current[0] if current else None
oaf/core/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """核心公开接口。"""
2
+
3
+ from .soul_core import MockSoulCore, SoulCore
4
+ from .lifecycle import LifecycleState
5
+
6
+ __all__ = ["MockSoulCore", "SoulCore", "LifecycleState"]
@@ -0,0 +1,69 @@
1
+ """模块注册与有序启动/停止。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ if TYPE_CHECKING:
8
+ from ..modules.base import Module
9
+ from .soul_core import MockSoulCore
10
+
11
+
12
+ class ModuleRegistry:
13
+ def __init__(self) -> None:
14
+ self._modules: dict[str, "Module"] = {}
15
+ self.errors: list[str] = []
16
+
17
+ def register(self, module: "Module") -> None:
18
+ module_id = getattr(module, "module_id", "")
19
+ if not module_id or not isinstance(module_id, str):
20
+ raise ValueError("module_id must be a non-empty string")
21
+ if module_id in self._modules:
22
+ raise ValueError(f"duplicate module_id: {module_id}")
23
+ for method in ("on_start", "on_stop", "on_event", "contribute_context", "status"):
24
+ if not callable(getattr(module, method, None)):
25
+ raise TypeError(f"module {module_id} missing {method}()")
26
+ self._modules[module_id] = module
27
+
28
+ def get(self, module_id: str) -> "Module | None":
29
+ return self._modules.get(module_id)
30
+
31
+ def all(self) -> tuple["Module", ...]:
32
+ return tuple(self._modules.values())
33
+
34
+ def start_all(self, core: "MockSoulCore") -> None:
35
+ for module in self.all():
36
+ try:
37
+ module.on_start(core)
38
+ except Exception as exc: # noqa: BLE001 - module isolation
39
+ self.errors.append(f"{module.module_id}.on_start: {exc}")
40
+
41
+ def stop_all(self, core: "MockSoulCore") -> None:
42
+ for module in reversed(self.all()):
43
+ try:
44
+ module.on_stop(core)
45
+ except Exception as exc: # noqa: BLE001 - module isolation
46
+ self.errors.append(f"{module.module_id}.on_stop: {exc}")
47
+
48
+ def tick_all(self, core: "MockSoulCore") -> list[str]:
49
+ errors: list[str] = []
50
+ for module in self.all():
51
+ try:
52
+ module.tick(core)
53
+ except Exception as exc: # noqa: BLE001 - module isolation
54
+ errors.append(f"{module.module_id}.tick: {exc}")
55
+ return errors
56
+
57
+ def statuses(self) -> list[dict[str, Any]]:
58
+ rows: list[dict[str, Any]] = []
59
+ for module in self.all():
60
+ try:
61
+ detail = module.status()
62
+ except Exception as exc: # noqa: BLE001
63
+ detail = {"state": "error", "error": str(exc)}
64
+ rows.append({
65
+ "module_id": module.module_id,
66
+ "capabilities": list(getattr(module, "capabilities", ())),
67
+ "detail": detail,
68
+ })
69
+ return rows
@@ -0,0 +1,51 @@
1
+ """同步事件处理:去重、分发、模块异常隔离。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from ..protocols import ActionRequest, Event, EventResult, ExpressionIntent
8
+
9
+ if TYPE_CHECKING:
10
+ from ..modules.base import Module
11
+ from .soul_core import MockSoulCore
12
+
13
+
14
+ class EventProcessor:
15
+ def __init__(self) -> None:
16
+ self.seen: set[str] = set()
17
+
18
+ def process(self, event: Event, modules: tuple["Module", ...],
19
+ core: "MockSoulCore") -> EventResult:
20
+ if event.event_id in self.seen:
21
+ return EventResult(event_id=event.event_id, status="duplicate",
22
+ duplicate=True)
23
+ self.seen.add(event.event_id)
24
+ event.status = "processing"
25
+ outputs: list[dict[str, Any]] = []
26
+ errors: list[str] = []
27
+ for module in modules:
28
+ accepts = getattr(module, "accepts_event", None)
29
+ if callable(accepts) and not accepts(event):
30
+ continue
31
+ try:
32
+ result = module.on_event(core, event)
33
+ except Exception as exc: # noqa: BLE001 - isolate module failure
34
+ errors.append(f"{module.module_id}: {exc}")
35
+ continue
36
+ if result is None:
37
+ continue
38
+ if isinstance(result, (ExpressionIntent, ActionRequest)):
39
+ outputs.append(result.to_dict())
40
+ elif isinstance(result, dict):
41
+ outputs.append(result)
42
+ elif isinstance(result, list):
43
+ outputs.extend(item.to_dict() if hasattr(item, "to_dict") else item
44
+ for item in result)
45
+ if errors:
46
+ event.status = "failed"
47
+ event.error = "; ".join(errors)
48
+ return EventResult(event_id=event.event_id, status="failed",
49
+ outputs=outputs, error=event.error)
50
+ event.status = "processed"
51
+ return EventResult(event_id=event.event_id, status="processed", outputs=outputs)
oaf/core/lifecycle.py ADDED
@@ -0,0 +1,15 @@
1
+ """公开生命周期状态。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+
7
+
8
+ class LifecycleState(str, Enum):
9
+ CREATED = "created"
10
+ INITIALIZED = "initialized"
11
+ STARTING = "starting"
12
+ RUNNING = "running"
13
+ STOPPING = "stopping"
14
+ STOPPED = "stopped"
15
+ FAILED = "failed"