@syengup/fridaynext-hermes-channel 0.1.0-beta.2 → 0.1.0-beta.4
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.
- package/README.md +2 -2
- package/install-config.js +67 -0
- package/install-runtime.js +18 -9
- package/install.js +6 -4
- package/package.json +2 -1
- package/plugin/README.md +2 -2
- package/plugin/fridaynext_plugin/__init__.py +10 -0
- package/plugin/fridaynext_plugin/adapter.py +231 -12
- package/plugin/fridaynext_plugin/agent_management.py +158 -0
- package/plugin/fridaynext_plugin/canonical_control.py +12 -4
- package/plugin/fridaynext_plugin/compat_v0225.py +1247 -4
- package/plugin/fridaynext_plugin/continuations.py +271 -0
- package/plugin/fridaynext_plugin/device-tools-v1.json +302 -0
- package/plugin/fridaynext_plugin/device_tools.py +144 -0
- package/plugin/fridaynext_plugin/history.py +25 -3
- package/plugin/fridaynext_plugin/host.py +7 -4
- package/plugin/fridaynext_plugin/media_input.py +56 -9
- package/plugin/fridaynext_plugin/message_speech.py +143 -0
- package/plugin/fridaynext_plugin/multi_agent.py +221 -0
- package/plugin/fridaynext_plugin/reply_context.py +39 -0
- package/plugin/fridaynext_plugin/runtime_port.py +23 -1
- package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
- package/plugin/fridaynext_plugin/settings.py +7 -3
- package/plugin/fridaynext_plugin/slash_commands.py +163 -0
- package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
- package/plugin/fridaynext_plugin/stream_projection.py +30 -6
- package/plugin/fridaynext_plugin/subagents.py +228 -0
- package/plugin/plugin.yaml +11 -0
- package/plugin/runtime/dist/commands-routes.js +94 -0
- package/plugin/runtime/dist/device-tools-v1.json +302 -0
- package/plugin/runtime/dist/hosted-backend.js +293 -25
- package/plugin/runtime/dist/hosted-continuations.js +41 -0
- package/plugin/runtime/dist/hosted-device-tools.js +82 -0
- package/plugin/runtime/dist/hosted-media.js +54 -13
- package/plugin/runtime/dist/hosted-stream.js +124 -14
- package/plugin/runtime/dist/hosted-subagents.js +78 -0
- package/plugin/runtime/dist/platform-service.js +4 -0
- package/plugin/runtime/dist/plugin-control.js +10 -6
- package/plugin/runtime/dist/scheduled-routes.js +63 -0
- package/plugin/runtime/dist/service-host.js +40 -5
- package/plugin/runtime/dist/speech-routes.js +111 -0
- package/plugin/runtime/dist/tool-presentation.js +399 -0
- package/plugin/runtime/node_modules/.package-lock.json +6 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
- package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
- package/plugin/runtime/node_modules/tslib/README.md +3 -8
- package/plugin/runtime/node_modules/tslib/package.json +1 -1
- package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
- package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
- package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
- package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
- package/plugin/runtime/package-lock.json +7 -7
- package/plugin/runtime/package.json +1 -1
- package/plugin/tools.py +3 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""将同一原生Gateway的正式Profile适配器映射到既有多Agent合同。"""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import copy
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from . import compat_v0225
|
|
9
|
+
from .canonical_control import NativeControlError
|
|
10
|
+
from .host import KitHost
|
|
11
|
+
from .state import private_json
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def profile_id(adapter, owner):
|
|
15
|
+
if adapter is owner:
|
|
16
|
+
return "hermes"
|
|
17
|
+
return "hermes-profile-" + hashlib.sha256(str(adapter.profile).encode()).hexdigest()[:24]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SharedKitHost:
|
|
21
|
+
"""子Profile保留自己的回调/lease,只共用原网关的受保护Kit连接。"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, owner, adapter):
|
|
24
|
+
self.owner = owner
|
|
25
|
+
self.adapter = adapter
|
|
26
|
+
self.transport = owner.host
|
|
27
|
+
|
|
28
|
+
def __getattr__(self, name):
|
|
29
|
+
return getattr(self.transport, name)
|
|
30
|
+
|
|
31
|
+
async def stop(self):
|
|
32
|
+
# 原生停用一个Profile只停止它自己的观察与runtime;不停止共享worker。
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
async def publish(self, params):
|
|
36
|
+
self._check(params)
|
|
37
|
+
return await self.transport.publish(params)
|
|
38
|
+
|
|
39
|
+
async def run_changed(self, params):
|
|
40
|
+
self._check(params)
|
|
41
|
+
return await self.transport.run_changed(params)
|
|
42
|
+
|
|
43
|
+
def _check(self, params):
|
|
44
|
+
if (self.owner.host is not self.transport or self.transport.stopping
|
|
45
|
+
or self.adapter.host is not self or not self.adapter.plugin_enabled
|
|
46
|
+
or params.get("serviceInstanceId") != self.owner.service_id
|
|
47
|
+
or self.adapter.bindings.read(params.get("runId", "")) is None):
|
|
48
|
+
raise NativeControlError("AGENT_SCOPE_CHANGED")
|
|
49
|
+
|
|
50
|
+
async def scheduled_publish(self, params):
|
|
51
|
+
return await self.transport.scheduled_publish({**params, "agentId": profile_id(self.adapter, self.owner)})
|
|
52
|
+
|
|
53
|
+
async def register_media(self, params, *, context):
|
|
54
|
+
return await KitHost._scoped_media_call(self, "media.register", params, context)
|
|
55
|
+
|
|
56
|
+
async def observe_media(self, params, *, context):
|
|
57
|
+
return await KitHost._scoped_media_call(self, "media.observe", params, context)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ProfileRouter:
|
|
61
|
+
def __init__(self, owner):
|
|
62
|
+
self.owner = owner
|
|
63
|
+
self.lock = asyncio.Lock()
|
|
64
|
+
self.file = Path(owner.bindings.root) / "multi-agent-sessions.json"
|
|
65
|
+
|
|
66
|
+
def adapters(self):
|
|
67
|
+
return compat_v0225.fridaynext_profile_adapters(self.owner)
|
|
68
|
+
|
|
69
|
+
def known_sessions(self):
|
|
70
|
+
if not self.file.exists():
|
|
71
|
+
return {}
|
|
72
|
+
value = json.loads(self.file.read_text())
|
|
73
|
+
if value.get("version") != 1 or not isinstance(value.get("sessions"), dict):
|
|
74
|
+
raise NativeControlError("AGENT_DIRECTORY_UNREADABLE")
|
|
75
|
+
return value["sessions"]
|
|
76
|
+
|
|
77
|
+
def remember(self, key, agent_id):
|
|
78
|
+
known = self.known_sessions()
|
|
79
|
+
if key in known and known[key] != agent_id:
|
|
80
|
+
raise NativeControlError("SESSION_AGENT_MISMATCH")
|
|
81
|
+
if known.get(key) != agent_id:
|
|
82
|
+
private_json(self.file, {"version": 1, "sessions": {**known, key: agent_id}})
|
|
83
|
+
|
|
84
|
+
async def local(self, target, method, params):
|
|
85
|
+
# 单Profile端口沿用内部局部hermes选择器;公共身份只在本适配层显式投影。
|
|
86
|
+
agent_id = profile_id(target, self.owner)
|
|
87
|
+
host = getattr(target, "host", None)
|
|
88
|
+
if target is not self.owner and getattr(host, "adapter", None) is target and hasattr(host, "transport"):
|
|
89
|
+
if host.owner is not self.owner or host.transport is not self.owner.host:
|
|
90
|
+
# 新worker只接续同一原生注册表中的原Profile;旧lease仍指旧host并被拒绝。
|
|
91
|
+
target.host = SharedKitHost(self.owner, target)
|
|
92
|
+
client = getattr(target.runtime, "client", None)
|
|
93
|
+
if client is not None:
|
|
94
|
+
client.control_profile = str(self.owner.profile)
|
|
95
|
+
for observer in (getattr(target, "subagent_observer", None), getattr(target, "continuation_observer", None)):
|
|
96
|
+
if observer is not None:
|
|
97
|
+
observer.rebind()
|
|
98
|
+
if method == "agent.scope":
|
|
99
|
+
return {"agentId": agent_id, "profileRoot": str(target.profile), "dataDir": str(target.data)}
|
|
100
|
+
normalized = copy.deepcopy(params)
|
|
101
|
+
if "agentId" in normalized:
|
|
102
|
+
normalized["agentId"] = "hermes"
|
|
103
|
+
for key in ("context", "input", "run"):
|
|
104
|
+
if isinstance(normalized.get(key), dict) and "agentId" in normalized[key]:
|
|
105
|
+
normalized[key]["agentId"] = "hermes"
|
|
106
|
+
target.service_id = self.owner.service_id
|
|
107
|
+
host, runtime = target.host, target.runtime
|
|
108
|
+
reply = await target._host_request(method, normalized)
|
|
109
|
+
if target.host is not host or target.runtime is not runtime or not target.plugin_enabled:
|
|
110
|
+
raise NativeControlError("AGENT_SCOPE_CHANGED")
|
|
111
|
+
if target is self.owner:
|
|
112
|
+
return reply
|
|
113
|
+
reply = copy.deepcopy(reply)
|
|
114
|
+
if method in ("agents", "catalog"):
|
|
115
|
+
for row in reply.get("agents", []):
|
|
116
|
+
row["id"] = agent_id
|
|
117
|
+
row["isDefault"] = False
|
|
118
|
+
if row.get("name") in (None, "", "HERMES", "Hermes Agent", "hermes"):
|
|
119
|
+
row["name"] = getattr(target, "_owner_profile", None) or target.profile.name
|
|
120
|
+
if method == "sessions":
|
|
121
|
+
for row in reply.get("sessions", []):
|
|
122
|
+
row["agentId"] = agent_id
|
|
123
|
+
if method == "agent.operation" and reply.get("id") == "hermes":
|
|
124
|
+
reply["id"] = agent_id
|
|
125
|
+
if isinstance(reply.get("management"), dict) and reply["management"].get("name") in (None, "", "HERMES", "Hermes Agent"):
|
|
126
|
+
reply["management"]["name"] = getattr(target, "_owner_profile", None) or target.profile.name
|
|
127
|
+
containers = [reply, reply.get("page"), reply.get("snapshot")]
|
|
128
|
+
if isinstance(reply.get("result"), dict):
|
|
129
|
+
containers.append(reply["result"].get("snapshot"))
|
|
130
|
+
for container in containers:
|
|
131
|
+
if not isinstance(container, dict):
|
|
132
|
+
continue
|
|
133
|
+
if container.get("agentId") == "hermes":
|
|
134
|
+
container["agentId"] = agent_id
|
|
135
|
+
if isinstance(container.get("session"), dict):
|
|
136
|
+
container["session"]["agentId"] = agent_id
|
|
137
|
+
return reply
|
|
138
|
+
|
|
139
|
+
def target(self, params, adapters):
|
|
140
|
+
declared = [value.get("agentId") for value in [params, params.get("run", {}),
|
|
141
|
+
params.get("context", {}), params.get("input", {})] if isinstance(value, dict)
|
|
142
|
+
and value.get("agentId") is not None]
|
|
143
|
+
if any(not isinstance(value, str) or not value for value in declared) or len(set(declared)) > 1:
|
|
144
|
+
raise NativeControlError("AGENT_SCOPE_CHANGED")
|
|
145
|
+
run = params.get("run", {})
|
|
146
|
+
key = params.get("sessionKey") or run.get("sessionKey")
|
|
147
|
+
saved = self.known_sessions().get(key) if isinstance(key, str) else None
|
|
148
|
+
owners = set()
|
|
149
|
+
if saved:
|
|
150
|
+
owners.add(saved)
|
|
151
|
+
for adapter in adapters:
|
|
152
|
+
identity = profile_id(adapter, self.owner)
|
|
153
|
+
if isinstance(key, str) and (adapter.bindings.session_id(key)
|
|
154
|
+
or adapter._catalog().directory.get(key)):
|
|
155
|
+
owners.add(identity)
|
|
156
|
+
run_id = params.get("runId") or run.get("runId")
|
|
157
|
+
if isinstance(run_id, str) and adapter.bindings.read(run_id):
|
|
158
|
+
owners.add(identity)
|
|
159
|
+
control_id = params.get("requestId")
|
|
160
|
+
if isinstance(control_id, str) and any(
|
|
161
|
+
record.get("service_id") == self.owner.service_id
|
|
162
|
+
and (control_id in record.get("ordinary_controls", {})
|
|
163
|
+
or record.get("recovery_control", {}).get("id") == control_id)
|
|
164
|
+
for record in adapter.bindings.all()):
|
|
165
|
+
owners.add(identity)
|
|
166
|
+
if len(owners) > 1 or declared and owners and declared[0] not in owners:
|
|
167
|
+
raise NativeControlError("SESSION_AGENT_MISMATCH")
|
|
168
|
+
identity = declared[0] if declared else next(iter(owners), "hermes")
|
|
169
|
+
target = next((adapter for adapter in adapters if profile_id(adapter, self.owner) == identity), None)
|
|
170
|
+
if target is None:
|
|
171
|
+
raise NativeControlError("AGENT_NOT_FOUND")
|
|
172
|
+
return target, key, identity
|
|
173
|
+
|
|
174
|
+
async def request(self, method, params):
|
|
175
|
+
if method == "describe":
|
|
176
|
+
return await self.owner._host_request(method, params)
|
|
177
|
+
if params.get("serviceInstanceId", self.owner.service_id) != self.owner.service_id:
|
|
178
|
+
raise NativeControlError("SERVICE_MISMATCH")
|
|
179
|
+
adapters = self.adapters()
|
|
180
|
+
if method in ("agents", "catalog", "sessions") and not params.get("agentId"):
|
|
181
|
+
replies = []
|
|
182
|
+
for target in adapters:
|
|
183
|
+
try:
|
|
184
|
+
replies.append(await self.local(target, method, params))
|
|
185
|
+
except Exception:
|
|
186
|
+
if method != "catalog" or target is self.owner:
|
|
187
|
+
raise
|
|
188
|
+
# 独立Profile的模型暂不可读时仍公布真实身份,不发布猜测的可写设置。
|
|
189
|
+
replies.append(await self.local(target, "agents", params))
|
|
190
|
+
field = "sessions" if method == "sessions" else "agents"
|
|
191
|
+
rows = [row for reply in replies for row in reply[field]]
|
|
192
|
+
if field == "sessions":
|
|
193
|
+
async with self.lock:
|
|
194
|
+
for row in rows:
|
|
195
|
+
self.remember(row["sessionKey"], row["agentId"])
|
|
196
|
+
return {**replies[0], field: rows}
|
|
197
|
+
try:
|
|
198
|
+
target, key, identity = self.target(params, adapters)
|
|
199
|
+
except NativeControlError as error:
|
|
200
|
+
if method == "validate":
|
|
201
|
+
return {"allowed": False, "reason": error.code, "status": 404 if error.code == "AGENT_NOT_FOUND" else 409}
|
|
202
|
+
if method == "inspect":
|
|
203
|
+
return {"inspection": {"state": "unknown", "reason": error.code}}
|
|
204
|
+
raise
|
|
205
|
+
reply = await self.local(target, method, params)
|
|
206
|
+
if method == "validate" and reply.get("allowed") is True and isinstance(key, str):
|
|
207
|
+
async with self.lock:
|
|
208
|
+
try:
|
|
209
|
+
self.remember(key, identity)
|
|
210
|
+
except NativeControlError as error:
|
|
211
|
+
return {"allowed": False, "reason": error.code, "status": 409}
|
|
212
|
+
return reply
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
async def route(adapter, method, params):
|
|
216
|
+
# 既有单Profile台架/旧实例没有正式Gateway注册表,保留原局部合同。
|
|
217
|
+
if not getattr(adapter, "bindings", None) or not getattr(adapter, "gateway_runner", None):
|
|
218
|
+
return await adapter._host_request(method, params)
|
|
219
|
+
if getattr(adapter, "profile_router", None) is None:
|
|
220
|
+
adapter.profile_router = ProfileRouter(adapter)
|
|
221
|
+
return await adapter.profile_router.request(method, params)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""版本化中立回复选项;不从正文、作者显示名或宿主消息ID猜测语义。"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
FIELDS = frozenset({"version", "messageId", "text", "authorName", "isAssistant"})
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def checked(value):
|
|
8
|
+
def bounded(text, maximum, *, nonempty=False):
|
|
9
|
+
if not isinstance(text, str) or nonempty and not text.strip():
|
|
10
|
+
return False
|
|
11
|
+
try:
|
|
12
|
+
return len(text.encode("utf-16-le")) // 2 <= maximum
|
|
13
|
+
except UnicodeError:
|
|
14
|
+
return False
|
|
15
|
+
|
|
16
|
+
if (not isinstance(value, dict) or set(value) != FIELDS
|
|
17
|
+
or type(value.get("version")) is not int or value["version"] != 1
|
|
18
|
+
or not bounded(value.get("messageId"), 1024, nonempty=True)
|
|
19
|
+
or not bounded(value.get("text"), 500, nonempty=True)
|
|
20
|
+
or not bounded(value.get("authorName"), 256)
|
|
21
|
+
or type(value.get("isAssistant")) is not bool):
|
|
22
|
+
raise ValueError("REPLY_CONTEXT_INVALID")
|
|
23
|
+
return dict(value)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def split_options(options):
|
|
27
|
+
if not isinstance(options, dict):
|
|
28
|
+
raise ValueError("SESSION_OPTIONS_UNSUPPORTED")
|
|
29
|
+
settings = dict(options)
|
|
30
|
+
context = checked(settings.pop("replyContext")) if "replyContext" in settings else None
|
|
31
|
+
return context, settings
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def native_fields(context):
|
|
35
|
+
if context is None:
|
|
36
|
+
return {}
|
|
37
|
+
context = checked(context)
|
|
38
|
+
return {"reply_to_message_id": context["messageId"], "reply_to_text": context["text"],
|
|
39
|
+
"reply_to_author_name": context["authorName"], "reply_to_is_own_message": context["isAssistant"]}
|
|
@@ -59,6 +59,7 @@ class HermesRuntimePort(Protocol):
|
|
|
59
59
|
async def result(
|
|
60
60
|
self, *, conversation_id: str, admission_id: str, input_id: str
|
|
61
61
|
) -> dict | None: ...
|
|
62
|
+
async def continuation_receipt(self, scope: dict) -> tuple[dict, dict | None]: ...
|
|
62
63
|
async def snapshot(self, *, conversation_id: str) -> dict: ...
|
|
63
64
|
async def session_liveness(self, *, conversation_id: str) -> dict | None: ...
|
|
64
65
|
async def cancel(
|
|
@@ -231,9 +232,14 @@ class PublicCanonicalRuntime:
|
|
|
231
232
|
attachments.append(await media_input.selected_reference(self.adapter, staged, image))
|
|
232
233
|
self.adapter._recovery().check(lease)
|
|
233
234
|
self.client.calls["prompt.submit.shared"] += 1
|
|
235
|
+
reply_options = {}
|
|
236
|
+
if record.get("reply_context"):
|
|
237
|
+
from .compat_v0225 import native_reply_text
|
|
238
|
+
reply_options["api_text"] = native_reply_text(record["reply_context"], record["text"])
|
|
234
239
|
reply = await self.client.submit_selected(
|
|
235
240
|
record["native_id"], record["input_id"], record["text"],
|
|
236
|
-
**({"attachments": attachments, "expected_connection_id": connection} if images else {})
|
|
241
|
+
**({"attachments": attachments, "expected_connection_id": connection} if images else {}),
|
|
242
|
+
**reply_options,
|
|
237
243
|
)
|
|
238
244
|
if reply.get("ref") != {
|
|
239
245
|
"profile_id": self.profile_home,
|
|
@@ -395,6 +401,22 @@ class PublicCanonicalRuntime:
|
|
|
395
401
|
)
|
|
396
402
|
)[0]
|
|
397
403
|
|
|
404
|
+
async def continuation_receipt(self, scope):
|
|
405
|
+
"""观察已存在的自动准入;不新增普通绑定,也不调用prompt执行或重试。"""
|
|
406
|
+
if not self.locator.continuation_matches(scope):
|
|
407
|
+
raise NativeControlError("CONTINUATION_ADMISSION_MISMATCH")
|
|
408
|
+
key = (scope["native_id"], scope["admission_id"], scope["input_id"])
|
|
409
|
+
self.claims[key] = scope
|
|
410
|
+
try:
|
|
411
|
+
receipt, result = await self._read_receipt(
|
|
412
|
+
conversation_id=scope["native_id"], admission_id=scope["admission_id"], input_id=scope["input_id"])
|
|
413
|
+
if (receipt.get("generation") != scope["generation"]
|
|
414
|
+
or receipt.get("authority_epoch") != scope["authority_epoch"]):
|
|
415
|
+
raise NativeControlError("CONTINUATION_EXECUTION_CHANGED")
|
|
416
|
+
return receipt, result
|
|
417
|
+
finally:
|
|
418
|
+
self.claims.pop(key, None)
|
|
419
|
+
|
|
398
420
|
async def result(self, *, conversation_id, admission_id, input_id):
|
|
399
421
|
return (
|
|
400
422
|
await self._read_receipt(
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Hermes原生计划任务适配:原命令留证、固定Profile,不持有另一个调度器。"""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from . import compat_v0225
|
|
8
|
+
from .canonical_control import NativeControlError
|
|
9
|
+
from .settings import encoded
|
|
10
|
+
from .state import private_json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ScheduledTasksPort:
|
|
14
|
+
writes = {"schedule.create", "schedule.update", "schedule.delete", "schedule.run", "inbox.delete"}
|
|
15
|
+
|
|
16
|
+
def __init__(self, adapter):
|
|
17
|
+
self.adapter = adapter
|
|
18
|
+
self.profile = adapter.profile.resolve()
|
|
19
|
+
stat = self.profile.stat()
|
|
20
|
+
self.identity = (stat.st_dev, stat.st_ino)
|
|
21
|
+
self.root = adapter.bindings.root / "scheduled-commands"
|
|
22
|
+
self.root.mkdir(exist_ok=True, mode=0o700)
|
|
23
|
+
self.lock = asyncio.Lock()
|
|
24
|
+
self.observed = self.root / "observed"
|
|
25
|
+
self.observed.mkdir(exist_ok=True, mode=0o700)
|
|
26
|
+
self.inbox_state = self.root / "inbox-state.json"
|
|
27
|
+
|
|
28
|
+
def index(self):
|
|
29
|
+
return json.loads(self.inbox_state.read_text()) if self.inbox_state.exists() else {"cursor": 0, "deleted": []}
|
|
30
|
+
|
|
31
|
+
def check(self, context):
|
|
32
|
+
stat = self.profile.stat()
|
|
33
|
+
if (context.get("serviceInstanceId") != self.adapter.service_id or not self.adapter.plugin_enabled
|
|
34
|
+
or self.adapter.profile.resolve() != self.profile or (stat.st_dev, stat.st_ino) != self.identity):
|
|
35
|
+
raise NativeControlError("SCHEDULE_SCOPE_CHANGED")
|
|
36
|
+
|
|
37
|
+
async def call(self, operation, context, value, inspect=False):
|
|
38
|
+
self.check(context)
|
|
39
|
+
if operation == "inbox.list":
|
|
40
|
+
return await self.inbox(context.get("deviceId"))
|
|
41
|
+
if operation not in self.writes:
|
|
42
|
+
result = await asyncio.to_thread(compat_v0225.profile_scheduled_operation, self.profile, operation, value)
|
|
43
|
+
self.check(context)
|
|
44
|
+
return result
|
|
45
|
+
command, device = context.get("commandId"), context.get("deviceId")
|
|
46
|
+
if not isinstance(command, str) or not command.strip() or len(command) > 200:
|
|
47
|
+
raise NativeControlError("INVALID_SCHEDULE_COMMAND")
|
|
48
|
+
if not isinstance(device, str) or not device.strip() or len(device) > 200:
|
|
49
|
+
raise NativeControlError("INVALID_SCHEDULE_DEVICE")
|
|
50
|
+
path = self.root / (hashlib.sha256(command.encode()).hexdigest() + ".json")
|
|
51
|
+
intent = {"operation": operation, "context": context, "input": value}
|
|
52
|
+
async with self.lock:
|
|
53
|
+
self.check(context)
|
|
54
|
+
if path.exists():
|
|
55
|
+
saved = json.loads(path.read_text())
|
|
56
|
+
if encoded(saved.get("intent")) != encoded(intent):
|
|
57
|
+
return {"status": "conflict", "code": "SCHEDULE_COMMAND_CONFLICT"}
|
|
58
|
+
return saved.get("result", {"status": "unknown", "code": "SCHEDULE_WRITE_UNCONFIRMED"})
|
|
59
|
+
if inspect:
|
|
60
|
+
return {"status": "unknown", "code": "SCHEDULE_COMMAND_NOT_FOUND"}
|
|
61
|
+
prepared = False
|
|
62
|
+
|
|
63
|
+
def prepare():
|
|
64
|
+
nonlocal prepared
|
|
65
|
+
self.check(context)
|
|
66
|
+
private_json(path, {"intent": intent})
|
|
67
|
+
prepared = True
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
value = json.loads(json.dumps(value))
|
|
71
|
+
patch = value.get("job" if operation == "schedule.create" else "patch", {})
|
|
72
|
+
if not isinstance(patch, dict) or {"nativeModel", "nativeProvider"} & patch.keys():
|
|
73
|
+
raise NativeControlError("SCHEDULE_INPUT_INVALID")
|
|
74
|
+
selected_model = patch.get("model")
|
|
75
|
+
if selected_model is not None and not isinstance(selected_model, str):
|
|
76
|
+
raise NativeControlError("SCHEDULE_INPUT_INVALID")
|
|
77
|
+
if selected_model:
|
|
78
|
+
models = (await self.adapter._settings().models())["models"]
|
|
79
|
+
selected = next((row for row in models if row["id"] == selected_model), None)
|
|
80
|
+
if selected is None:
|
|
81
|
+
raise NativeControlError("SCHEDULE_MODEL_UNAVAILABLE")
|
|
82
|
+
patch["nativeModel"] = selected["modelId"]
|
|
83
|
+
patch["nativeProvider"] = selected["provider"]
|
|
84
|
+
if operation == "inbox.delete":
|
|
85
|
+
cursor = value.get("cursor")
|
|
86
|
+
if type(cursor) is not int or cursor < 1:
|
|
87
|
+
raise NativeControlError("INBOX_CURSOR_INVALID")
|
|
88
|
+
index = self.index()
|
|
89
|
+
key = encoded([device, cursor])
|
|
90
|
+
prepare()
|
|
91
|
+
index["deleted"] = sorted(set(index["deleted"]) | {key})
|
|
92
|
+
private_json(self.inbox_state, index)
|
|
93
|
+
result = {"status": "applied", "value": {"ok": True}}
|
|
94
|
+
else:
|
|
95
|
+
result = await asyncio.to_thread(compat_v0225.profile_scheduled_operation, self.profile,
|
|
96
|
+
operation, value, device=device, prepare=prepare)
|
|
97
|
+
self.check(context)
|
|
98
|
+
private_json(path, {"intent": intent, "result": result})
|
|
99
|
+
return result
|
|
100
|
+
except Exception as error:
|
|
101
|
+
if prepared:
|
|
102
|
+
return {"status": "unknown", "code": "SCHEDULE_WRITE_UNCONFIRMED"}
|
|
103
|
+
# 已证明尚未调用宿主写入,保留明确拒绝回执,让用户修正草稿后显式再提交。
|
|
104
|
+
self.check(context)
|
|
105
|
+
code = str(error)
|
|
106
|
+
if not code.startswith("SCHEDULE_") or not all(char.isupper() or char == "_" for char in code) or len(code) > 100:
|
|
107
|
+
code = "SCHEDULE_INPUT_INVALID"
|
|
108
|
+
result = {"status": "conflict", "code": code}
|
|
109
|
+
private_json(path, {"intent": intent, "result": result})
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
def observation_path(self, run_id):
|
|
113
|
+
return self.observed / (hashlib.sha256(str(run_id).encode()).hexdigest() + ".json")
|
|
114
|
+
|
|
115
|
+
def observations(self):
|
|
116
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
117
|
+
rows = []
|
|
118
|
+
for path in self.observed.glob("*.json"):
|
|
119
|
+
if path.is_symlink() or path.stat().st_size > 512 * 1024:
|
|
120
|
+
continue
|
|
121
|
+
row = json.loads(path.read_text())
|
|
122
|
+
if row.get("profile") == str(self.profile) and row.get("serviceInstanceId") == self.adapter.service_id:
|
|
123
|
+
rows.append(row)
|
|
124
|
+
return sorted(rows, key=lambda row: (row["occurredAt"], row["runId"]))
|
|
125
|
+
|
|
126
|
+
async def deliver(self, chat_id, content, metadata):
|
|
127
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
128
|
+
if not isinstance(metadata, dict) or not isinstance(metadata.get("job_id"), str) or not isinstance(content, str):
|
|
129
|
+
return None
|
|
130
|
+
if not content or len(content.encode()) > 256 * 1024:
|
|
131
|
+
return None
|
|
132
|
+
source = await asyncio.to_thread(compat_v0225.profile_scheduled_delivery, self.profile, metadata["job_id"], str(chat_id))
|
|
133
|
+
if source is None:
|
|
134
|
+
return None
|
|
135
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
136
|
+
run_id = "scheduled:" + hashlib.sha256(encoded([self.adapter.service_id, source["jobId"], source["executionId"]]).encode()).hexdigest()
|
|
137
|
+
session = "scheduled:" + hashlib.sha256(encoded([self.adapter.service_id, source["jobId"]]).encode()).hexdigest()
|
|
138
|
+
async with self.lock:
|
|
139
|
+
path = self.observation_path(run_id)
|
|
140
|
+
previous = json.loads(path.read_text()) if path.exists() else None
|
|
141
|
+
if previous and any(previous.get(key) != expected for key, expected in (
|
|
142
|
+
("profile", str(self.profile)), ("serviceInstanceId", self.adapter.service_id), ("text", content))):
|
|
143
|
+
return None
|
|
144
|
+
index = self.index()
|
|
145
|
+
cursor = previous["cursor"] if previous else index["cursor"] + 1
|
|
146
|
+
if not previous:
|
|
147
|
+
index["cursor"] = cursor
|
|
148
|
+
private_json(self.inbox_state, index)
|
|
149
|
+
devices = sorted(set(previous.get("deviceIds", [previous["deviceId"]]) if previous else []) | {str(chat_id)})
|
|
150
|
+
row = {**source, "profile": str(self.profile), "serviceInstanceId": self.adapter.service_id,
|
|
151
|
+
"runId": run_id, "sessionKey": session, "deviceId": str(chat_id), "deviceIds": devices,
|
|
152
|
+
"text": content, "cursor": cursor, "durable": (previous or {}).get("durable", False)}
|
|
153
|
+
private_json(path, row)
|
|
154
|
+
receipt = await self.adapter.host.scheduled_publish({key: value for key, value in row.items() if key != "profile"})
|
|
155
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
156
|
+
if receipt.get("durable") is not True:
|
|
157
|
+
return None
|
|
158
|
+
async with self.lock:
|
|
159
|
+
current = json.loads(path.read_text())
|
|
160
|
+
current["durable"] = True
|
|
161
|
+
private_json(path, current)
|
|
162
|
+
return run_id
|
|
163
|
+
|
|
164
|
+
def check_delivery(self, params):
|
|
165
|
+
self.check({"serviceInstanceId": params.get("serviceInstanceId")})
|
|
166
|
+
path = self.observation_path(params.get("runId"))
|
|
167
|
+
if not path.is_file() or path.is_symlink():
|
|
168
|
+
return {"allowed": False}
|
|
169
|
+
row = json.loads(path.read_text())
|
|
170
|
+
return {"allowed": row.get("profile") == str(self.profile)
|
|
171
|
+
and params.get("deviceId") in row.get("deviceIds", [row.get("deviceId")]) and all(
|
|
172
|
+
row.get(key) == params.get(key) for key in ("serviceInstanceId", "runId", "sessionKey", "jobId", "executionId", "text"))}
|
|
173
|
+
|
|
174
|
+
async def inbox(self, device):
|
|
175
|
+
if not isinstance(device, str) or not device.strip():
|
|
176
|
+
raise NativeControlError("INVALID_SCHEDULE_DEVICE")
|
|
177
|
+
deleted = set(self.index()["deleted"])
|
|
178
|
+
results = []
|
|
179
|
+
for row in self.observations():
|
|
180
|
+
if device not in row.get("deviceIds", [row.get("deviceId")]) or encoded([device, row["cursor"]]) in deleted:
|
|
181
|
+
continue
|
|
182
|
+
info = await self.inspect(row["runId"])
|
|
183
|
+
status = {"completed": "ok", "failed": "error"}.get(info["state"], info["state"])
|
|
184
|
+
results.append({"cursor": row["cursor"], "id": row["runId"], "category": "cronResults", "kind": "cronResult",
|
|
185
|
+
"lifecycle": "event", "occurredAtMs": row["occurredAt"], "deviceId": device,
|
|
186
|
+
"jobId": row["jobId"], "jobName": row["title"], "agentId": "hermes", "runId": row["runId"],
|
|
187
|
+
"sessionId": row["sessionKey"], "runAtMs": row["occurredAt"], "status": status,
|
|
188
|
+
"summary": row["text"], "error": info.get("error"), "delivered": True if row.get("durable") else None,
|
|
189
|
+
"deliveryStatus": "delivered" if row.get("durable") else "unknown"})
|
|
190
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
191
|
+
now = time.time_ns() // 1_000_000
|
|
192
|
+
return {"schemaVersion": 2, "serverInstanceId": self.adapter.service_id, "controlUiParityVersion": "2026.9.4",
|
|
193
|
+
"revision": now, "cursor": self.index()["cursor"], "cronResults": results,
|
|
194
|
+
"attention": {"approvals": [], "automations": [], "system": []},
|
|
195
|
+
"sources": {name: {"status": "fresh" if name == "cronResults" else "unsupported", "fetchedAtMs": now}
|
|
196
|
+
for name in ("cronResults", "execApprovals", "pluginApprovals", "systemAgentApprovals", "cronJobs", "cronStatus", "modelAuth", "update", "scopeUpgrade")}}
|
|
197
|
+
|
|
198
|
+
async def inspect(self, run_id):
|
|
199
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
200
|
+
path = self.observation_path(run_id)
|
|
201
|
+
if not path.is_file() or path.is_symlink():
|
|
202
|
+
return {"state": "unknown", "reason": "SCHEDULE_SOURCE_MISSING"}
|
|
203
|
+
row = json.loads(path.read_text())
|
|
204
|
+
if row.get("profile") != str(self.profile) or row.get("serviceInstanceId") != self.adapter.service_id:
|
|
205
|
+
raise NativeControlError("SCHEDULE_SCOPE_CHANGED")
|
|
206
|
+
result = await asyncio.to_thread(compat_v0225.profile_scheduled_inspection, self.profile, row["jobId"], row["executionId"])
|
|
207
|
+
self.check({"serviceInstanceId": self.adapter.service_id})
|
|
208
|
+
return result
|
|
209
|
+
|
|
210
|
+
def sessions(self):
|
|
211
|
+
rows = {}
|
|
212
|
+
for row in self.observations():
|
|
213
|
+
rows[row["sessionKey"]] = {"sessionKey": row["sessionKey"], "agentId": "hermes", "kind": "scheduled", "title": row["title"]}
|
|
214
|
+
return list(rows.values())
|
|
215
|
+
|
|
216
|
+
def history(self, key, limit=200, offset=0):
|
|
217
|
+
rows = [row for row in self.observations() if row["sessionKey"] == key]
|
|
218
|
+
if not rows:
|
|
219
|
+
raise NativeControlError("SCHEDULE_SESSION_NOT_FOUND")
|
|
220
|
+
limit, offset = max(1, min(int(limit), 200)), max(0, int(offset))
|
|
221
|
+
end = max(0, len(rows) - offset)
|
|
222
|
+
start = max(0, end - limit)
|
|
223
|
+
messages = [{"id": "answer:" + row["runId"], "seq": index + 1, "role": "assistant", "format": "canonical-v1",
|
|
224
|
+
"text": row["text"], "content": row["text"], "ts": row["occurredAt"],
|
|
225
|
+
"runId": row["runId"], "clientRequestId": "observed:" + row["runId"]}
|
|
226
|
+
for index, row in enumerate(rows) if start <= index < end]
|
|
227
|
+
return {"sessionKey": key, "agentId": "hermes", "title": rows[-1]["title"], "messages": messages,
|
|
228
|
+
"totalMessages": len(rows), "pagination": {"offset": offset, "limit": limit, "totalRecords": len(rows),
|
|
229
|
+
"hasMore": start > 0, **({"nextOffset": offset + len(messages)} if start > 0 else {})}}
|
|
@@ -46,9 +46,11 @@ def resolved_default_id(model, profile=None):
|
|
|
46
46
|
def thinking_options(capabilities):
|
|
47
47
|
if capabilities.get("reasoning") is not True:
|
|
48
48
|
return []
|
|
49
|
-
levels =
|
|
49
|
+
levels = compat_v0225.reasoning_effort_levels()
|
|
50
|
+
if not levels:
|
|
51
|
+
return []
|
|
50
52
|
if capabilities.get("can_disable_reasoning") is True:
|
|
51
|
-
levels
|
|
53
|
+
levels = ["none", *levels]
|
|
52
54
|
return [{"id": value, "label": value, "scope": "session"} for value in levels]
|
|
53
55
|
|
|
54
56
|
|
|
@@ -182,6 +184,7 @@ class SettingsPort:
|
|
|
182
184
|
]}
|
|
183
185
|
|
|
184
186
|
async def catalog(self):
|
|
187
|
+
ui = await asyncio.to_thread(compat_v0225.profile_agent_presentation, self.adapter.profile)
|
|
185
188
|
catalog = await self.models()
|
|
186
189
|
options = [
|
|
187
190
|
{"id": row["id"], "label": row["name"], "scope": "session"}
|
|
@@ -191,7 +194,8 @@ class SettingsPort:
|
|
|
191
194
|
"agents": [
|
|
192
195
|
{
|
|
193
196
|
"id": "hermes",
|
|
194
|
-
"name": "
|
|
197
|
+
"name": ui["name"],
|
|
198
|
+
"greeting": ui["greeting"],
|
|
195
199
|
"isDefault": True,
|
|
196
200
|
"settings": [
|
|
197
201
|
{
|