@syengup/fridaynext-hermes-channel 0.1.0-beta.3 → 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.
Files changed (90) hide show
  1. package/README.md +2 -2
  2. package/install-config.js +67 -0
  3. package/install-runtime.js +17 -5
  4. package/install.js +6 -4
  5. package/package.json +2 -1
  6. package/plugin/README.md +2 -2
  7. package/plugin/fridaynext_plugin/__init__.py +10 -0
  8. package/plugin/fridaynext_plugin/adapter.py +221 -12
  9. package/plugin/fridaynext_plugin/agent_management.py +158 -0
  10. package/plugin/fridaynext_plugin/canonical_control.py +12 -4
  11. package/plugin/fridaynext_plugin/compat_v0225.py +1174 -4
  12. package/plugin/fridaynext_plugin/continuations.py +271 -0
  13. package/plugin/fridaynext_plugin/device-tools-v1.json +302 -0
  14. package/plugin/fridaynext_plugin/device_tools.py +144 -0
  15. package/plugin/fridaynext_plugin/history.py +25 -3
  16. package/plugin/fridaynext_plugin/host.py +7 -4
  17. package/plugin/fridaynext_plugin/media_input.py +56 -9
  18. package/plugin/fridaynext_plugin/multi_agent.py +221 -0
  19. package/plugin/fridaynext_plugin/reply_context.py +39 -0
  20. package/plugin/fridaynext_plugin/runtime_port.py +23 -1
  21. package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
  22. package/plugin/fridaynext_plugin/settings.py +7 -3
  23. package/plugin/fridaynext_plugin/slash_commands.py +163 -0
  24. package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
  25. package/plugin/fridaynext_plugin/stream_projection.py +30 -6
  26. package/plugin/fridaynext_plugin/subagents.py +228 -0
  27. package/plugin/plugin.yaml +11 -0
  28. package/plugin/runtime/dist/commands-routes.js +94 -0
  29. package/plugin/runtime/dist/device-tools-v1.json +302 -0
  30. package/plugin/runtime/dist/hosted-backend.js +250 -25
  31. package/plugin/runtime/dist/hosted-continuations.js +41 -0
  32. package/plugin/runtime/dist/hosted-device-tools.js +82 -0
  33. package/plugin/runtime/dist/hosted-media.js +54 -13
  34. package/plugin/runtime/dist/hosted-stream.js +124 -14
  35. package/plugin/runtime/dist/hosted-subagents.js +78 -0
  36. package/plugin/runtime/dist/platform-service.js +4 -0
  37. package/plugin/runtime/dist/plugin-control.js +10 -6
  38. package/plugin/runtime/dist/scheduled-routes.js +63 -0
  39. package/plugin/runtime/dist/service-host.js +27 -3
  40. package/plugin/runtime/dist/tool-presentation.js +399 -0
  41. package/plugin/runtime/node_modules/.package-lock.json +6 -6
  42. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
  43. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
  44. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
  45. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
  46. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
  47. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
  48. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
  49. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
  50. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
  51. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
  52. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
  53. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
  54. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
  55. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
  56. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
  57. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
  58. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
  59. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
  60. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
  61. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
  62. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
  63. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
  64. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
  65. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
  66. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
  67. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
  68. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
  69. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
  70. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
  71. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
  72. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
  73. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
  74. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
  75. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
  76. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
  77. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
  78. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
  79. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
  80. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
  81. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
  82. package/plugin/runtime/node_modules/tslib/README.md +3 -8
  83. package/plugin/runtime/node_modules/tslib/package.json +1 -1
  84. package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
  85. package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
  86. package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
  87. package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
  88. package/plugin/runtime/package-lock.json +7 -7
  89. package/plugin/runtime/package.json +1 -1
  90. package/plugin/tools.py +3 -0
@@ -1,12 +1,15 @@
1
1
  """固定版身份、平台授权/首次注册、已授权FIFO、默认配置与原控制观察;公开协议优先,必要配置写入固定封装,告警保持。"""
2
2
 
3
3
  import asyncio
4
+ from contextlib import contextmanager
5
+ import json
4
6
  import logging
5
7
  import os
6
8
  import subprocess
7
9
  import time
8
10
  import threading
9
11
  from collections import OrderedDict
12
+ from contextvars import ContextVar
10
13
  from pathlib import Path
11
14
  from gateway import config as gateway_config
12
15
  from .runtime_port import PublicRuntimeUnavailable, InputAdmissionRefused, InputAdmissionUnconfirmed
@@ -17,7 +20,444 @@ logger = logging.getLogger(__name__)
17
20
  _resolved_default_warning_emitted = False
18
21
  _model_names_warning_emitted = False
19
22
  _profile_defaults_warning_emitted = False
23
+ _multi_profile_warning_emitted = False
24
+ _device_execution = ContextVar("fridaynext_device_execution", default=None)
25
+
26
+
27
+ def _fridaynext_adapter(platforms):
28
+ if not isinstance(platforms, dict):
29
+ return None
30
+ return next((adapter for platform, adapter in platforms.items()
31
+ if getattr(platform, "value", platform) == "fridaynext"), None)
32
+
33
+
34
+ def fridaynext_listener_owner(adapter):
35
+ """固定版原生multiplex注册表;不扫描目录或自行创建Profile执行器。"""
36
+ runner = getattr(adapter, "gateway_runner", None)
37
+ primary = getattr(runner, "adapters", {})
38
+ owner = _fridaynext_adapter(primary)
39
+ if owner is adapter:
40
+ return None
41
+ candidates = [owner] if owner is not None else []
42
+ if owner is None:
43
+ registry = getattr(runner, "_profile_adapters", {})
44
+ if isinstance(registry, dict):
45
+ candidates = [_fridaynext_adapter(platforms) for _, platforms in sorted(registry.items())]
46
+ for candidate in candidates:
47
+ if candidate is None or candidate is adapter:
48
+ continue
49
+ # 默认Profile未启用本平台时,已有服务的命名Profile继续拥有原listener。
50
+ candidate = getattr(getattr(candidate, "host", None), "owner", candidate)
51
+ if candidate is adapter:
52
+ continue
53
+ if (not callable(getattr(candidate, "_host_request", None))
54
+ or getattr(candidate, "gateway_runner", None) is not runner):
55
+ continue
56
+ host = getattr(candidate, "host", None)
57
+ if not host or getattr(host, "stopping", False) or not getattr(candidate, "plugin_enabled", False):
58
+ raise RuntimeError("PRIMARY_PROFILE_UNAVAILABLE")
59
+ return candidate
60
+ return None
61
+
62
+
63
+ def fridaynext_profile_adapters(owner):
64
+ """只列同一Gateway已登记、已初始化且允许owner进入的正式适配器。"""
65
+ runner = getattr(owner, "gateway_runner", None)
66
+ registry = getattr(runner, "_profile_adapters", {})
67
+ peers = []
68
+ for name, platforms in sorted(registry.items()) if isinstance(registry, dict) else []:
69
+ adapter = _fridaynext_adapter(platforms)
70
+ if (adapter is None or adapter is owner or not callable(getattr(adapter, "_host_request", None))
71
+ or getattr(adapter, "gateway_runner", None) is not runner
72
+ or not getattr(adapter, "plugin_enabled", False) or not getattr(adapter, "host", None)
73
+ or not getattr(adapter, "runtime", None) or not getattr(adapter, "bindings", None)
74
+ or getattr(adapter, "_running", True) is not True
75
+ or adapter.profile == owner.profile):
76
+ continue
77
+ extra = getattr(getattr(adapter, "config", None), "extra", {})
78
+ allowed = extra.get("allowed_users", [])
79
+ if isinstance(allowed, str):
80
+ allowed = [value.strip() for value in allowed.split(",")]
81
+ if not isinstance(allowed, (list, tuple, set)):
82
+ allowed = []
83
+ if "owner" not in allowed and extra.get("allow_all_users") is not True:
84
+ continue
85
+ peers.append(adapter)
86
+ global _multi_profile_warning_emitted
87
+ if peers and not _multi_profile_warning_emitted:
88
+ _multi_profile_warning_emitted = True
89
+ logger.warning("hermes.compat.multi_profile_registry_v0_22_5:读取固定版原生Profile注册表,执行仍走标准平台入口")
90
+ return [owner, *peers]
20
91
  _message_speech_warning_emitted = False
92
+ _reasoning_options_warning_emitted = False
93
+ _scheduled_warning_emitted = False
94
+ _scheduled_lock = threading.RLock()
95
+
96
+
97
+ def _scheduled_version(job):
98
+ import hashlib
99
+ import json
100
+ # list_jobs 额外附上执行摘要,get_job 和写入回执只返回原任务。
101
+ # 统一版本输入,仍用原任务字段拦截实际改动。
102
+ record = {key: value for key, value in job.items() if key != "latest_execution"}
103
+ return hashlib.sha256(json.dumps(record, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
104
+
105
+
106
+ def _scheduled_time_zone():
107
+ """跟随Hermes生效时区;未配置时解析宿主本地时区,不把server-local误报成UTC。"""
108
+ from hermes_time import get_timezone
109
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
110
+ configured = get_timezone()
111
+ if configured is not None:
112
+ return str(configured)
113
+ environment = os.environ.get("TZ", "").lstrip(":")
114
+ candidates = [environment] if environment else []
115
+ if not environment:
116
+ local = Path("/etc/localtime").resolve()
117
+ if "zoneinfo" in local.parts:
118
+ candidates.append("/".join(local.parts[local.parts.index("zoneinfo") + 1:]))
119
+ timezone_file = Path("/etc/timezone")
120
+ if timezone_file.is_file():
121
+ candidates.append(timezone_file.read_text().strip())
122
+ for name in candidates:
123
+ try:
124
+ return str(ZoneInfo(name))
125
+ except (ValueError, ZoneInfoNotFoundError):
126
+ continue
127
+ # 无可验证IANA名时保持未知,周期仍由原生调度器解释,不能给客户端伪造时区。
128
+ return ""
129
+
130
+
131
+ def _scheduled_wire(job, zone):
132
+ from .settings import model_id
133
+ schedule = job.get("schedule") or {}
134
+ kind = schedule.get("kind")
135
+ wire = ({"kind": "at", "at": schedule.get("run_at")} if kind == "once" else
136
+ {"kind": "every", "everyMs": schedule.get("minutes", 0) * 60000} if kind == "interval" else
137
+ {"kind": "cron", "expr": schedule.get("expr"), "tz": zone} if kind == "cron" else {"kind": kind or "unknown"})
138
+ deliver = job.get("deliver") or "local"
139
+ origin = job.get("origin") or {}
140
+ if deliver == "origin":
141
+ channel, target = origin.get("platform"), origin.get("chat_id")
142
+ else:
143
+ channel, _, target = deliver.partition(":")
144
+ delivery = ({"mode": "none"} if deliver == "local" else
145
+ {"mode": "announce", "channel": "friday-next" if channel == "fridaynext" else channel,
146
+ **({"to": target} if target else {})})
147
+ def epoch(value):
148
+ from datetime import datetime
149
+ try:
150
+ return datetime.fromisoformat(value).timestamp() * 1000 if value else None
151
+ except (ValueError, TypeError):
152
+ return None
153
+ return {"id": job["id"], "name": job.get("name", job["id"]), "agentId": "hermes",
154
+ "version": _scheduled_version(job), "enabled": job.get("enabled", True), "schedule": wire,
155
+ "payload": {"kind": "native" if job.get("script") or job.get("no_agent") else "agentTurn",
156
+ "message": job.get("prompt", ""),
157
+ "model": model_id(job.get("provider") or "", job["model"]) if job.get("model") else None},
158
+ "delivery": delivery, "nextRunAtMs": epoch(job.get("next_run_at")), "lastRunAtMs": epoch(job.get("last_run_at")),
159
+ "lastRunStatus": {"success": "ok", "error": "error", "failed": "error"}.get(job.get("last_status")),
160
+ "lastRunError": job.get("last_error"), "deleteAfterRun": False}
161
+
162
+
163
+ def _scheduled_text(schedule, zone):
164
+ if not isinstance(schedule, dict):
165
+ raise ValueError("SCHEDULE_INVALID")
166
+ kind = schedule.get("kind")
167
+ if kind == "cron":
168
+ if schedule.get("tz") not in (None, "", zone):
169
+ # 固定Hermes版本按Profile时区调度;不假装支持单任务时区,也不静默换算。
170
+ raise ValueError("SCHEDULE_TIMEZONE_MISMATCH")
171
+ return str(schedule.get("expr") or "")
172
+ if kind == "every":
173
+ interval = schedule.get("everyMs")
174
+ if type(interval) not in (int, float) or interval < 60000 or interval % 60000:
175
+ raise ValueError("SCHEDULE_INTERVAL_INVALID")
176
+ return f"every {int(interval // 60000)}m"
177
+ if kind == "at":
178
+ from datetime import datetime
179
+ parsed = datetime.fromisoformat(schedule.get("at") or "")
180
+ if parsed.tzinfo is None:
181
+ raise ValueError("SCHEDULE_TIMEZONE_REQUIRED")
182
+ return parsed.isoformat()
183
+ raise ValueError("SCHEDULE_KIND_UNSUPPORTED")
184
+
185
+
186
+ def profile_scheduled_operation(profile, operation, value, *, device=None, prepare=None):
187
+ """复用固定版原生cron API及官方蓝图定义;只在owner作用域内调用,不扫描其他Profile。"""
188
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
189
+ from agent.secret_scope import set_secret_scope, reset_secret_scope
190
+ from tui_gateway.launch_profile_policy import owner_secret_scope
191
+ from cron import jobs
192
+ from cron.scheduler import create_job_with_scheduler_registration
193
+ from cron.scheduler_provider import resolve_cron_scheduler
194
+ from cron.blueprint_catalog import list_blueprints, get_blueprint, blueprint_form_schema, fill_blueprint
195
+
196
+ global _scheduled_warning_emitted
197
+ if not _scheduled_warning_emitted:
198
+ _scheduled_warning_emitted = True
199
+ logger.warning("hermes.compat.scheduled_tasks_v0_22_5:固定cron存储作用域、调度器注册与蓝图API;非稳定Platform管理SDK")
200
+ root = Path(profile).resolve()
201
+ home_token = set_hermes_home_override(str(root))
202
+ secret_token = None
203
+ try:
204
+ secret_token = set_secret_scope(owner_secret_scope(root), profile_home=str(root))
205
+ with _scheduled_lock, jobs.use_cron_store(root):
206
+ zone = _scheduled_time_zone()
207
+
208
+ def notify():
209
+ resolve_cron_scheduler().on_jobs_changed()
210
+
211
+ def missing_skills(entry):
212
+ from tools.skills_tool import find_all_skills
213
+ available = {row["name"] for row in find_all_skills()}
214
+ return [name for name in entry.skills if name not in available]
215
+
216
+ def blueprint(identifier, values, *, require_available=False):
217
+ entry = get_blueprint(identifier)
218
+ if entry is None:
219
+ raise ValueError("SCHEDULE_BLUEPRINT_NOT_FOUND")
220
+ if require_available and missing_skills(entry):
221
+ raise ValueError("SCHEDULE_BLUEPRINT_DEPENDENCY_UNAVAILABLE")
222
+ return fill_blueprint(entry, values)
223
+
224
+ def channels():
225
+ from cron.scheduler_delivery import cron_delivery_targets
226
+ native = cron_delivery_targets()
227
+ return [{"id": "friday-next", "label": "FridayNext"}, *[
228
+ {"id": row["id"], "label": row.get("label") or row["id"]}
229
+ for row in native if row.get("id") not in (None, "fridaynext", "friday-next", "local", "origin")]]
230
+
231
+ if operation == "schedule.blueprints":
232
+ entries = []
233
+ for entry in list_blueprints():
234
+ missing = missing_skills(entry)
235
+ entries.append({"id": entry.key, "name": entry.title, "description": entry.description,
236
+ "available": not missing, "unavailableReason": "缺少或已停用技能:" + ", ".join(missing) if missing else None,
237
+ "fields": [{**field, "role": "delivery" if field["name"] == "deliver" else "input"}
238
+ for field in blueprint_form_schema(entry)["fields"]]})
239
+ return {"version": 1, "timeZone": zone, "blueprints": entries}
240
+ if operation == "schedule.channels":
241
+ return {"version": 1, "channels": channels()}
242
+ if operation == "schedule.preview":
243
+ spec = blueprint(value.get("blueprintId"), value.get("values", {}))
244
+ parsed = jobs.parse_schedule(spec["schedule"])
245
+ wire = _scheduled_wire({"id": "preview", "schedule": parsed, "deliver": spec.get("deliver", "origin"),
246
+ "origin": {"platform": "fridaynext"}}, zone)
247
+ return {"version": 1, "job": {"name": spec["name"], "message": spec["prompt"],
248
+ "schedule": wire["schedule"], "delivery": wire["delivery"]}}
249
+ if operation == "schedule.list":
250
+ return {"jobs": [_scheduled_wire(job, zone) for job in jobs.list_jobs(include_disabled=True)]}
251
+ identifier = value.get("id")
252
+ existing = jobs.get_job(identifier) if isinstance(identifier, str) else None
253
+ if operation != "schedule.create" and existing is None:
254
+ raise ValueError("SCHEDULE_NOT_FOUND")
255
+ if operation == "schedule.runs":
256
+ return _scheduled_runs(root, existing, value.get("limit", 20))
257
+ patch = value.get("job" if operation == "schedule.create" else "patch", {})
258
+ if not isinstance(patch, dict):
259
+ raise ValueError("SCHEDULE_INPUT_INVALID")
260
+ allowed = {"name", "message", "schedule", "model", "nativeModel", "nativeProvider", "deviceId", "agentId",
261
+ "enabled", "deleteAfterRun", "delivery", "blueprintId", "blueprintValues", "expectedVersion"}
262
+ if set(patch) - allowed or patch.get("agentId") not in (None, "hermes"):
263
+ raise ValueError("SCHEDULE_INPUT_INVALID")
264
+ if patch.get("deviceId", device) != device:
265
+ raise ValueError("SCHEDULE_DEVICE_MISMATCH")
266
+ if "enabled" in patch and type(patch["enabled"]) is not bool:
267
+ raise ValueError("SCHEDULE_ENABLED_INVALID")
268
+ if patch.get("deleteAfterRun") not in (None, False):
269
+ raise ValueError("SCHEDULE_DELETE_AFTER_RUN_UNSUPPORTED")
270
+ if existing and patch.get("expectedVersion") not in (None, _scheduled_version(existing)):
271
+ return {"status": "conflict", "code": "SCHEDULE_VERSION_CONFLICT"}
272
+ spec = blueprint(patch["blueprintId"], patch.get("blueprintValues", {}), require_available=True) if patch.get("blueprintId") else {}
273
+ for source, target in (("name", "name"), ("message", "prompt")):
274
+ if source in patch:
275
+ if not isinstance(patch[source], str):
276
+ raise ValueError("SCHEDULE_INPUT_INVALID")
277
+ spec[target] = patch[source]
278
+ if "message" in patch and existing and (existing.get("script") or existing.get("no_agent")):
279
+ raise ValueError("SCHEDULE_PAYLOAD_READ_ONLY")
280
+ if "schedule" in patch:
281
+ spec["schedule"] = _scheduled_text(patch["schedule"], zone)
282
+ jobs.parse_schedule(spec["schedule"])
283
+ if "model" in patch:
284
+ spec["model"] = patch.get("nativeModel") or None
285
+ spec["provider"] = patch.get("nativeProvider") or None
286
+ if operation == "schedule.create":
287
+ if not (spec.get("prompt") or spec.get("skills")) or not spec.get("schedule"):
288
+ raise ValueError("SCHEDULE_PAYLOAD_REQUIRED")
289
+ spec["origin"] = {"platform": "fridaynext", "chat_id": device, "user_id": "owner", "chat_type": "dm"}
290
+ spec.setdefault("deliver", "origin")
291
+ if "delivery" in patch:
292
+ delivery = patch["delivery"]
293
+ if not isinstance(delivery, dict):
294
+ raise ValueError("SCHEDULE_DELIVERY_INVALID")
295
+ if delivery.get("mode") == "none":
296
+ spec["deliver"] = "local"
297
+ elif delivery.get("mode") == "announce":
298
+ channel = delivery.get("channel")
299
+ if channel not in {row["id"] for row in channels()}:
300
+ raise ValueError("SCHEDULE_DELIVERY_UNAVAILABLE")
301
+ target = delivery.get("to")
302
+ if channel == "friday-next":
303
+ if target not in (None, device):
304
+ raise ValueError("SCHEDULE_DEVICE_MISMATCH")
305
+ spec["deliver"] = "fridaynext:" + device
306
+ else:
307
+ spec["deliver"] = channel + (":" + target if isinstance(target, str) and target else "")
308
+ else:
309
+ raise ValueError("SCHEDULE_DELIVERY_INVALID")
310
+ if operation == "schedule.create":
311
+ if not spec.get("name"):
312
+ spec.pop("name", None)
313
+ spec["paused"] = patch.get("enabled") is False
314
+ if prepare:
315
+ prepare()
316
+ created = create_job_with_scheduler_registration(**spec)
317
+ return {"status": "applied", "value": {"job": _scheduled_wire(created, zone)}}
318
+ if operation == "schedule.update":
319
+ if prepare:
320
+ prepare()
321
+ changed = jobs.update_job(identifier, spec) if spec else existing
322
+ if "enabled" in patch:
323
+ changed = jobs.resume_job(identifier) if patch["enabled"] else jobs.pause_job(identifier)
324
+ notify()
325
+ return {"status": "applied", "value": {"job": _scheduled_wire(changed, zone)}}
326
+ if operation == "schedule.delete":
327
+ if prepare:
328
+ prepare()
329
+ removed = jobs.remove_job(identifier)
330
+ notify()
331
+ return {"status": "applied", "value": {"removed": removed}}
332
+ if operation == "schedule.run":
333
+ # 原生trigger只安排下一次tick,不在管理请求里另开Agent循环或宣称执行完成。
334
+ if existing.get("run_claim") or existing.get("fire_claim"):
335
+ return {"status": "applied", "value": {"ran": False, "reason": "already-running"}}
336
+ if prepare:
337
+ prepare()
338
+ queued = jobs.trigger_job(identifier)
339
+ notify()
340
+ return {"status": "applied", "value": {"ran": queued is not None}}
341
+ raise ValueError("SCHEDULE_OPERATION_UNSUPPORTED")
342
+ finally:
343
+ if secret_token is not None:
344
+ reset_secret_scope(secret_token)
345
+ reset_hermes_home_override(home_token)
346
+
347
+
348
+ def profile_scheduled_delivery(profile, job_id, device):
349
+ """核验原生执行或本进程正在投递的持久队列;终态记录本身不授予发送权。"""
350
+ import json
351
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
352
+ from cron import jobs, delivery_queue
353
+ from cron.executions import live_inflight_execution, get_execution
354
+ from datetime import datetime
355
+ token = set_hermes_home_override(str(profile))
356
+ try:
357
+ with _scheduled_lock, jobs.use_cron_store(profile):
358
+ queued = []
359
+ # 固定兼容:Gateway的drain认领后才进入此集合;不接受pending、旧终态或别的进程的队列。
360
+ for execution_id in tuple(delivery_queue._ACTIVE_DELIVERIES):
361
+ receipt = delivery_queue.get_status(execution_id)
362
+ execution = get_execution(execution_id)
363
+ if (not receipt or receipt.get("status") != "delivering" or receipt.get("owner_pid") != os.getpid()
364
+ or receipt.get("owner_process_id") != delivery_queue._PROCESS_ID
365
+ or not execution or execution.get("job_id") != job_id):
366
+ continue
367
+ original = json.loads(receipt["job_json"])
368
+ if original.get("id") == job_id:
369
+ if receipt.get("for_failure") and original.get("failure_deliver"):
370
+ original["deliver"] = original["failure_deliver"]
371
+ queued.append((original, execution))
372
+ if len(queued) > 1:
373
+ return None
374
+ job, execution = queued[0] if queued else (jobs.get_job(job_id), live_inflight_execution(job_id))
375
+ if not job or not execution:
376
+ return None
377
+ origin = job.get("origin") or {}
378
+ targets = (job.get("deliver") or "local").split(",")
379
+ own = ("origin" in targets and origin.get("platform") == "fridaynext" and origin.get("chat_id") == device
380
+ or "fridaynext:" + device in targets)
381
+ if not own:
382
+ return None
383
+ return {"jobId": job_id, "executionId": execution["id"], "title": job.get("name") or job_id,
384
+ "occurredAt": datetime.fromisoformat(execution.get("started_at") or execution["claimed_at"]).timestamp() * 1000}
385
+ finally:
386
+ reset_hermes_home_override(token)
387
+
388
+
389
+ def native_reply_text(context, text):
390
+ """共享CLI公开api_text没有回复字段,复用固定宿主原生上下文格式,不复制模板。"""
391
+ from gateway.platforms.event import MessageEvent
392
+ from gateway.run_inbound import GatewayInboundMixin
393
+ from .reply_context import native_fields
394
+ event = MessageEvent(text=text, **native_fields(context))
395
+ return GatewayInboundMixin._prepend_inbound_reply_context(event, None, text)
396
+
397
+
398
+ def profile_scheduled_inspection(profile, job_id, execution_id):
399
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
400
+ from cron.executions import get_execution
401
+ token = set_hermes_home_override(str(profile))
402
+ try:
403
+ row = get_execution(execution_id)
404
+ if not row or row.get("job_id") != job_id:
405
+ return {"state": "unknown", "reason": "SCHEDULE_EXECUTION_UNCONFIRMED"}
406
+ state = {"claimed": "running", "running": "running", "completed": "completed", "failed": "failed"}.get(row.get("status"), "unknown")
407
+ return {"state": state, **({"reason": "SCHEDULE_EXECUTION_FAILED", "error": row.get("error")} if state == "failed" else {})}
408
+ finally:
409
+ reset_hermes_home_override(token)
410
+
411
+
412
+ def _scheduled_runs(profile, job, limit):
413
+ """读取同一Profile的原生会话和执行记录,不从一份当前状态补造多条历史。"""
414
+ from datetime import datetime
415
+ from cron.executions import list_executions, get_execution
416
+ from hermes_state import SessionDB
417
+ count = max(1, min(int(limit), 100))
418
+ runs = []
419
+ seen = set()
420
+ state = Path(profile) / "state.db"
421
+ if state.is_file():
422
+ db = SessionDB(db_path=state, read_only=True)
423
+ try:
424
+ for row in db.list_cron_job_runs(job["id"], limit=count, offset=0):
425
+ messages = db.get_messages(row["id"])
426
+ text = "\n".join(str(item.get("content") or "") for item in messages if item.get("role") == "assistant")
427
+ execution = get_execution(row["cron_execution_id"]) if row.get("cron_execution_id") else None
428
+ if execution and execution.get("job_id") != job["id"]:
429
+ execution = None
430
+ run_id = execution["id"] if execution else row["id"]
431
+ seen.add(run_id)
432
+ runs.append({"ts": row["started_at"] * 1000, "runId": run_id, "summary": text,
433
+ "status": {"completed": "ok", "failed": "error"}.get((execution or {}).get("status")),
434
+ "error": (execution or {}).get("error")})
435
+ finally:
436
+ db.close()
437
+ for row in list_executions(job_id=job["id"], limit=count):
438
+ if row["id"] not in seen:
439
+ runs.append({"ts": datetime.fromisoformat(row["claimed_at"]).timestamp() * 1000, "runId": row["id"],
440
+ "status": {"completed": "ok", "failed": "error"}.get(row.get("status")), "error": row.get("error")})
441
+ return {"runs": sorted(runs, key=lambda row: row["ts"], reverse=True)[:count]}
442
+
443
+
444
+ def reasoning_effort_levels():
445
+ """读取固定宿主认可的请求档位;厂商wire映射仍由Hermes负责,不复制另一份梯级。"""
446
+ global _reasoning_options_warning_emitted
447
+ if not _reasoning_options_warning_emitted:
448
+ _reasoning_options_warning_emitted = True
449
+ logger.warning(
450
+ "hermes.compat.reasoning_options_v0_22_5:公开model.options不含完整档位,"
451
+ "读取固定版词表;公开接口可用后替换,读取失败不发布选项"
452
+ )
453
+ try:
454
+ from hermes_constants import VALID_REASONING_EFFORTS, parse_reasoning_effort
455
+
456
+ return [level for level in dict.fromkeys(VALID_REASONING_EFFORTS)
457
+ if isinstance(level, str)
458
+ and parse_reasoning_effort(level) == {"enabled": True, "effort": level}]
459
+ except Exception:
460
+ return []
21
461
 
22
462
 
23
463
  def _warn_message_speech_compat():
@@ -253,6 +693,17 @@ def profile_reasoning_default(profile, model):
253
693
 
254
694
 
255
695
  CRITICAL_FILES = [
696
+ "hermes_cli/commands.py", "hermes_cli/plugins.py", "agent/skill_commands.py",
697
+ "gateway/slash_commands.py", "gateway/session_commands.py", "gateway/session_policy.py", "gateway/session_context.py",
698
+ "hermes_time.py",
699
+ "cron/jobs.py",
700
+ "cron/scheduler.py",
701
+ "cron/scheduler_provider.py",
702
+ "cron/scheduler_delivery.py",
703
+ "cron/blueprint_catalog.py",
704
+ "cron/executions.py",
705
+ "cron/delivery_queue.py",
706
+ "gateway/delivery.py",
256
707
  "gateway/session_authorities.py",
257
708
  "gateway/session_identity.py",
258
709
  "gateway/session.py",
@@ -279,6 +730,8 @@ CRITICAL_FILES = [
279
730
  "gateway/session_authority.py",
280
731
  "gateway/session_pending_controls.py",
281
732
  "tools/approval.py",
733
+ "tools/approval_context.py",
734
+ "gateway/session_context.py",
282
735
  "tools/approval_gateway_wait.py",
283
736
  "tools/clarify_gateway.py",
284
737
  "gateway/session_server_requests.py",
@@ -293,6 +746,8 @@ CRITICAL_FILES = [
293
746
  "gateway/session_context.py",
294
747
  "agent/plugin_stream_hooks.py",
295
748
  "agent/stream_delivery.py",
749
+ "agent/secret_scope.py",
750
+ "tui_gateway/launch_profile_policy.py",
296
751
  ]
297
752
 
298
753
 
@@ -469,6 +924,264 @@ class BindingLocator:
469
924
  raise RuntimeError("PROFILE_NOT_SERVED")
470
925
  return value
471
926
 
927
+ def prepare_device_identity(self):
928
+ """固定版实例观察器只复制原准入事实;不改宿主执行、授权或结果。"""
929
+ authority = self.authority()
930
+ if getattr(authority, "_fridaynext_device_identity", None) is not None:
931
+ self.device_identity_authority = authority
932
+ return True
933
+ original = getattr(authority, "_execute_claimed", None)
934
+ if not callable(original):
935
+ return False
936
+ profile = self.profile_home
937
+ async def observe(ref, live, row):
938
+ stamp = (authority, profile, ref.session_id, row.get("request_id"), row.get("admission_id"),
939
+ row.get("generation"), row.get("owner_epoch"))
940
+ token = _device_execution.set(stamp)
941
+ try:
942
+ return await original(ref, live, row)
943
+ finally:
944
+ _device_execution.reset(token)
945
+ authority._fridaynext_device_identity = (original, observe)
946
+ authority._execute_claimed = observe
947
+ self.device_identity_authority = authority
948
+ logger.warning("hermes.compat.device_execution_v0_22_5:公开工具上下文缺共享本地输入身份;实例观察器冻结原准入及执行代,不改变宿主执行")
949
+ return True
950
+
951
+ def release_device_identity(self):
952
+ authority = getattr(self, "device_identity_authority", None)
953
+ pair = getattr(authority, "_fridaynext_device_identity", None)
954
+ if pair is not None and authority._execute_claimed is pair[1]:
955
+ authority._execute_claimed = pair[0]
956
+ del authority._fridaynext_device_identity
957
+ self.device_identity_authority = None
958
+
959
+ def device_tool_scope(self, session_id):
960
+ """工具原线程的任务上下文;共享CLI会话也只认本插件提交的这一条输入。"""
961
+ from hermes_constants import get_hermes_home
962
+ from gateway.session_context import _SESSION_MESSAGE_ID, _SESSION_ID
963
+ from tools.approval_context import _approval_tool_call_id, _approval_session_id
964
+ message = _SESSION_MESSAGE_ID.get(None)
965
+ native = _SESSION_ID.get(None)
966
+ tool = _approval_tool_call_id.get()
967
+ if (str(Path(get_hermes_home()).resolve()) != self.profile_home
968
+ or not all(isinstance(v, str) and v for v in (native, session_id, tool))
969
+ or native != session_id or _approval_session_id.get() != session_id):
970
+ return None
971
+ authority = self.authority()
972
+ owner = authority.logical_owner(native)
973
+ stamp = _device_execution.get()
974
+ if stamp is not None and (stamp[0] is not authority or stamp[1] != self.profile_home or stamp[2] != owner):
975
+ return None
976
+ if not message and stamp is None:
977
+ return None
978
+ with self.owner_scope(authority):
979
+ rows = [row for row in self.list_admissions(authority.db, session_id=owner, pending_only=False)
980
+ if (not message or message in (row.get("request_id"), row.get("admission_id")))
981
+ and (stamp is None or (row.get("request_id"), row.get("admission_id"),
982
+ row.get("generation"), row.get("owner_epoch")) == stamp[3:])]
983
+ if len(rows) != 1:
984
+ return None
985
+ row = rows[0]
986
+ bindings = [r for r in self.adapter.bindings.all()
987
+ if r.get("profile") == self.profile_home and r.get("service_id") == self.adapter.service_id
988
+ and r.get("input_id") == row.get("request_id") and not r.get("legacy")]
989
+ if len(bindings) != 1:
990
+ return None
991
+ record = bindings[0]
992
+ # 标准平台源继续核对持久原输入;共享operator会话只允许本插件已保存的App提交。
993
+ original = row.get("payload", {}).get("native_text_v1")
994
+ if original is not None:
995
+ source = original.get("source", {})
996
+ if (source.get("platform") != self.platform or source.get("message_id") != record["input_id"]
997
+ or original.get("event", {}).get("message_id") != record["input_id"]
998
+ or original.get("event", {}).get("allow_gateway_control") is not False):
999
+ return None
1000
+ elif record.get("shared") is not True:
1001
+ return None
1002
+ scope = {"serviceInstanceId": self.adapter.service_id, "profileRoot": self.profile_home,
1003
+ "runId": record["run_id"], "sessionKey": record["session_key"],
1004
+ "nativeId": owner, "inputId": record["input_id"], "admissionId": row.get("admission_id"),
1005
+ "generation": row.get("generation"), "authorityEpoch": row.get("owner_epoch"), "toolCallId": tool}
1006
+ if not self.device_scope_matches(scope):
1007
+ return None
1008
+ if not getattr(self, "device_warning_emitted", False):
1009
+ logger.warning("hermes.compat.device_identity_v0_22_5:工具注册为公开API;原调用ContextVar及准入执行代核验为固定版兼容接缝")
1010
+ self.device_warning_emitted = True
1011
+ return scope
1012
+
1013
+ def device_scope_matches(self, scope):
1014
+ """回包与IPC检查只复核冻结的原事实,不读取后来一次调用的当前上下文。"""
1015
+ adapter, authority = self.adapter, self.authority()
1016
+ identity = getattr(getattr(adapter.runtime, "client", None), "identity", {})
1017
+ if (scope.get("profileRoot") != self.profile_home or scope.get("serviceInstanceId") != adapter.service_id
1018
+ or scope.get("authorityEpoch") != authority.epoch or identity.get("authority_epoch") != authority.epoch
1019
+ or type(scope.get("generation")) is not int or scope["generation"] < 1
1020
+ or authority.executing.get(scope.get("nativeId")) != scope["generation"]):
1021
+ return False
1022
+ record = adapter.bindings.read(scope.get("runId", ""))
1023
+ if (record is None or record.get("legacy") or record.get("profile") != self.profile_home
1024
+ or record.get("service_id") != scope["serviceInstanceId"]
1025
+ or record.get("input_id") != scope.get("inputId") or record.get("session_key") != scope.get("sessionKey")
1026
+ or record.get("admission_id") not in (None, scope.get("admissionId"))
1027
+ or record.get("native_id") is not None and authority.logical_owner(record["native_id"]) != scope.get("nativeId")):
1028
+ return False
1029
+ with self.owner_scope(authority):
1030
+ rows = [r for r in self.list_admissions(authority.db, session_id=scope["nativeId"], pending_only=False)
1031
+ if r.get("admission_id") == scope.get("admissionId") and r.get("request_id") == scope.get("inputId")]
1032
+ return (len(rows) == 1 and rows[0].get("generation") == scope["generation"]
1033
+ and rows[0].get("owner_epoch") == scope["authorityEpoch"] and rows[0].get("status") == "started")
1034
+
1035
+ def subagent_owner(self, parent_session_id):
1036
+ """公开子任务hook缺准入身份;只从产生回调的原输入ContextVar核对原持久记录。"""
1037
+ from hermes_constants import get_hermes_home
1038
+ from gateway.session_context import _SESSION_MESSAGE_ID, _SESSION_CHAT_ID, _SESSION_KEY, _SESSION_ID, _SESSION_PLATFORM
1039
+ source = (_SESSION_MESSAGE_ID.get(None), _SESSION_CHAT_ID.get(None), _SESSION_KEY.get(None),
1040
+ _SESSION_ID.get(None), _SESSION_PLATFORM.get(None))
1041
+ if (any(not isinstance(v, str) or not v for v in source) or source[3] != parent_session_id
1042
+ or source[4] != self.platform or str(Path(get_hermes_home()).resolve()) != self.profile_home):
1043
+ return None
1044
+ authority = self.authority()
1045
+ identity = getattr(self.adapter.runtime.client, "identity", None)
1046
+ if not identity or identity.get("authority_epoch") != authority.epoch:
1047
+ return None
1048
+ native = authority.logical_owner(parent_session_id)
1049
+ live = authority.sessions.get(native)
1050
+ if (live is None or getattr(live.source, "chat_id", None) != source[1]
1051
+ or self.adapter._source_session_key(live.source) != source[2]):
1052
+ return None
1053
+ with self.owner_scope(authority):
1054
+ rows = [r for r in self.list_admissions(authority.db, session_id=native, pending_only=False)
1055
+ if r.get("request_id") == source[0]]
1056
+ if len(rows) != 1:
1057
+ return None
1058
+ row = rows[0]
1059
+ original = row.get("payload", {}).get("native_text_v1", {})
1060
+ proof = original.get("source", {})
1061
+ if (not isinstance(row.get("admission_id"), str) or not row["admission_id"]
1062
+ or row.get("owner_epoch") != authority.epoch or type(row.get("generation")) is not int
1063
+ or proof.get("platform") != self.platform or proof.get("chat_id") != source[1]
1064
+ or proof.get("message_id") != source[0] or original.get("event", {}).get("message_id") != source[0]
1065
+ or original.get("event", {}).get("allow_gateway_control") is not False):
1066
+ return None
1067
+ matches = [r for r in self.adapter.bindings.all() if r.get("input_id") == source[0]
1068
+ and r.get("profile") == self.profile_home and r.get("service_id", self.adapter.service_id) == self.adapter.service_id]
1069
+ if len(matches) != 1:
1070
+ return None
1071
+ if not getattr(self, "subagent_warning_emitted", False):
1072
+ logger.warning("hermes.compat.subagent_identity_v0_22_5:公开observer沿原输入准入/执行代绑定;不借最新运行")
1073
+ self.subagent_warning_emitted = True
1074
+ return {"profile": self.profile_home, "service": self.adapter.service_id, "root_run_id": matches[0]["run_id"],
1075
+ "input_id": source[0], "chat_id": source[1], "route": source[2], "native_id": source[3],
1076
+ "admission_id": row["admission_id"], "authority_epoch": authority.epoch, "generation": row["generation"]}
1077
+
1078
+ def subagent_context_matches(self, scope):
1079
+ from hermes_constants import get_hermes_home
1080
+ from gateway.session_context import _SESSION_MESSAGE_ID, _SESSION_CHAT_ID, _SESSION_KEY, _SESSION_PLATFORM
1081
+ authority = self.authority()
1082
+ if not (scope.get("profile") == str(Path(get_hermes_home()).resolve()) == self.profile_home
1083
+ and scope.get("service") == self.adapter.service_id
1084
+ and scope.get("authority_epoch") == authority.epoch
1085
+ and _SESSION_MESSAGE_ID.get(None) == scope.get("input_id")
1086
+ and _SESSION_CHAT_ID.get(None) == scope.get("chat_id")
1087
+ and _SESSION_KEY.get(None) == scope.get("route") and _SESSION_PLATFORM.get(None) == self.platform):
1088
+ return False
1089
+ # 后台子任务允许晚于父下一轮结束;核对原准入,不借当前正在执行的generation。
1090
+ with self.owner_scope(authority):
1091
+ rows = [row for row in self.list_admissions(authority.db,
1092
+ session_id=authority.logical_owner(scope["native_id"]), pending_only=False)
1093
+ if row.get("request_id") == scope["input_id"]]
1094
+ if len(rows) != 1:
1095
+ return False
1096
+ row = rows[0]
1097
+ if (row.get("admission_id") != scope.get("admission_id") or row.get("generation") != scope.get("generation")
1098
+ or row.get("owner_epoch") != scope["authority_epoch"]):
1099
+ return False
1100
+ bindings = [binding for binding in self.adapter.bindings.all()
1101
+ if binding.get("input_id") == scope["input_id"] and binding.get("profile") == self.profile_home
1102
+ and binding.get("service_id", self.adapter.service_id) == self.adapter.service_id]
1103
+ return len(bindings) == 1 and bindings[0].get("run_id") == scope.get("root_run_id")
1104
+
1105
+ def _continuation_admission(self, scope):
1106
+ """只认宿主已持久准入的自动回报;不按最新运行或通知正文认领。"""
1107
+ authority = self.authority()
1108
+ if (scope.get("profile") != self.profile_home or scope.get("service") != self.adapter.service_id
1109
+ or scope.get("authority_epoch") != authority.epoch):
1110
+ return None
1111
+ owner = authority.logical_owner(scope["native_id"])
1112
+ if any(authority.logical_owner(native) != owner for native in scope.get("origin_native_ids", [])):
1113
+ return None
1114
+ live = authority.sessions.get(owner)
1115
+ if (live is None or getattr(live.source, "chat_id", None) != scope.get("chat_id")
1116
+ or self.adapter._source_session_key(live.source) != scope.get("route")):
1117
+ return None
1118
+ with self.owner_scope(authority):
1119
+ rows = [row for row in self.list_admissions(authority.db, session_id=owner, pending_only=False)
1120
+ if row.get("request_id") == scope["input_id"]]
1121
+ if len(rows) != 1:
1122
+ return None
1123
+ row = rows[0]
1124
+ envelope = row.get("payload", {}).get("native_text_v1", {})
1125
+ source, event, automation = (envelope.get(key, {}) for key in ("source", "event", "automation"))
1126
+ if (row.get("principal_id") != "automation:" + scope["route"]
1127
+ or source.get("platform") != self.platform or source.get("chat_id") != scope["chat_id"]
1128
+ or source.get("message_id") is not None or envelope.get("route") != scope["route"]
1129
+ or event.get("message_id") != scope["input_id"]
1130
+ or automation.get("identity") != scope["input_id"] or automation.get("owner") != owner
1131
+ or automation.get("notification_category") == "diagnostic"
1132
+ or row.get("owner_epoch") != authority.epoch or type(row.get("generation")) is not int
1133
+ or not isinstance(row.get("admission_id"), str) or not row["admission_id"]):
1134
+ return None
1135
+ identities = automation.get("identities", [automation["identity"]])
1136
+ if not isinstance(identities, list) or not identities:
1137
+ return None
1138
+ producers = []
1139
+ for value in identities:
1140
+ try:
1141
+ identity = json.loads(value)
1142
+ except (ValueError, TypeError):
1143
+ return None
1144
+ if (not isinstance(identity, list) or len(identity) != 3 or identity[0] != "async_delegation"
1145
+ or not isinstance(identity[1], str) or not identity[1] or identity[2] != ""):
1146
+ return None
1147
+ producers.append(identity[1])
1148
+ return {**scope, "admission_id": row["admission_id"], "generation": row["generation"],
1149
+ "producer_ids": sorted(set(producers))}
1150
+
1151
+ def continuation_owner(self, frame):
1152
+ """公开会话流自带原执行戳;只读补全其自动准入及producer身份。"""
1153
+ native = frame.get("session_id")
1154
+ admission = frame.get("admission_id")
1155
+ epoch, generation = frame.get("authority_epoch"), frame.get("execution_generation")
1156
+ if (not isinstance(native, str) or not native or not isinstance(admission, str) or not admission
1157
+ or type(epoch) is not int or type(generation) is not int):
1158
+ return None
1159
+ authority = self.authority()
1160
+ identity = getattr(self.adapter.runtime.client, "identity", None)
1161
+ if not identity or identity.get("authority_epoch") != epoch or authority.epoch != epoch:
1162
+ return None
1163
+ owner = authority.logical_owner(native)
1164
+ live = authority.sessions.get(owner)
1165
+ if live is None or getattr(live.source.platform, "value", None) != self.platform:
1166
+ return None
1167
+ with self.owner_scope(authority):
1168
+ rows = [row for row in self.list_admissions(authority.db, session_id=owner, pending_only=False)
1169
+ if row.get("admission_id") == admission]
1170
+ if len(rows) != 1: return None
1171
+ scope = self._continuation_admission({"profile": self.profile_home, "service": self.adapter.service_id,
1172
+ "input_id": rows[0]["request_id"], "chat_id": live.source.chat_id,
1173
+ "route": self.adapter._source_session_key(live.source), "native_id": native, "authority_epoch": epoch})
1174
+ if scope is None or scope["generation"] != generation: return None
1175
+ if not getattr(self, "continuation_warning_emitted", False):
1176
+ logger.warning("hermes.compat.continuation_identity_v0_22_5:公开会话流沿原执行戳只读绑定自动准入;终态读取prompt.receipt")
1177
+ self.continuation_warning_emitted = True
1178
+ return scope
1179
+
1180
+ def continuation_matches(self, scope):
1181
+ current = self._continuation_admission(scope)
1182
+ return current is not None and all(current.get(key) == scope.get(key) for key in (
1183
+ "admission_id", "generation", "producer_ids"))
1184
+
472
1185
  def ingress_rejection(self, source):
473
1186
  """宿主 ingress 丢事件后,判断这是不是"明确未授权"。
474
1187
 
@@ -505,6 +1218,10 @@ class BindingLocator:
505
1218
  # 公开stage RPC未声明可读的limit字段;固定实现的额外25MiB/张合同明确收在兼容层。
506
1219
  from tui_gateway.prompt_attachments import _ATTACH_BYTES_MAX_BYTES
507
1220
  policy["maxFileBytes"] = _ATTACH_BYTES_MAX_BYTES
1221
+ else:
1222
+ # 固定版标准MessageEvent原生消费文档;operator的prompt.submit仍只接受图片。
1223
+ from .media_input import FILE_MIMES
1224
+ policy["fileMimeTypes"] = sorted(FILE_MIMES)
508
1225
  return policy
509
1226
 
510
1227
  def selected_image_root(self):
@@ -629,10 +1346,30 @@ class BindingLocator:
629
1346
  or item.get("size") != original.get("size") for item, original in zip(media, frozen))):
630
1347
  return None
631
1348
  text = payload["text"]
632
- # 固定image_routing与session_persistence的完整生成形态;只比较全值,不解析/删正文子串。
633
- rendered = (text.strip() or "What do you see in this image?") + "\n\n"
634
- rendered += "\n".join("[Image attached at: " + item["path"] + "]" for item in media)
635
- rendered += "\n[screenshot]" * len(media)
1349
+ # 只根据原准入重建固定SDK的完整注记;不按正文子串清理用户字面内容。
1350
+ from .media_input import MIMES, FILE_MIMES
1351
+ if any(mime not in MIMES and mime not in FILE_MIMES for mime in types):
1352
+ return None
1353
+ rendered = text
1354
+ if any(mime in FILE_MIMES for mime in types):
1355
+ expected_flags = [None if mime in MIMES else False for mime in types]
1356
+ if record.get("shared") or event.get("media_text_inlined") != expected_flags:
1357
+ return None
1358
+ from gateway.run import GatewayRunner
1359
+ from types import SimpleNamespace
1360
+ with self.owner_scope(self.authority()):
1361
+ rendered = GatewayRunner._prepend_inbound_document_notes(SimpleNamespace(
1362
+ media_urls=[item["path"] for item in media], media_types=types,
1363
+ media_text_inlined=expected_flags), text)
1364
+ images = [item for item, mime in zip(media, types) if mime in MIMES]
1365
+ if images:
1366
+ rendered = (rendered.strip() or "What do you see in this image?") + "\n\n"
1367
+ rendered += "\n".join("[Image attached at: " + item["path"] + "]" for item in images)
1368
+ rendered += "\n[screenshot]" * len(images)
1369
+ if record.get("reply_context"):
1370
+ if record.get("shared") and payload.get("cli_turn_v1", {}).get("api_text") != native_reply_text(record["reply_context"], text):
1371
+ return None
1372
+ rendered = native_reply_text(record["reply_context"], rendered)
636
1373
  return {"version": 1, "text": text, "rendered": rendered,
637
1374
  "sha256": [item["sha256"] for item in media]}
638
1375
 
@@ -908,3 +1645,436 @@ class BindingLocator:
908
1645
 
909
1646
  def close_observations(self):
910
1647
  self.observed_controls.clear()
1648
+
1649
+
1650
+ _AGENT_FILE_LIMIT = 128 * 1024
1651
+ _AGENT_MANAGEMENT_LOCK = threading.RLock()
1652
+ _agent_management_warning_emitted = False
1653
+
1654
+
1655
+ def _agent_digest(value):
1656
+ import hashlib
1657
+ import json
1658
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
1659
+
1660
+
1661
+ def profile_agent_management(profile, *, patch=None, expected_version=None, prepare=None):
1662
+ """固定dashboard同源配置/技能/工具集语义,只写当前物理Profile的原始配置。
1663
+
1664
+ 工具集作用于fridaynext,避免照搬dashboard的cli目标;宿主私有接缝只留在此兼容层。
1665
+ """
1666
+ import copy
1667
+ import json
1668
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
1669
+ from agent.secret_scope import set_secret_scope, reset_secret_scope
1670
+ from tui_gateway.launch_profile_policy import owner_secret_scope
1671
+ from hermes_cli import config as config_mod, tools_config
1672
+ from hermes_cli.skills_config import get_disabled_skills
1673
+ from hermes_cli.approval_mode import VALID_APPROVAL_MODES
1674
+ from tools.approval_context import _get_approval_mode
1675
+ from tools.skills_tool import find_all_skills
1676
+ from agent.skill_utils import ESSENTIAL_SKILLS
1677
+ from toolsets import resolve_toolset
1678
+ from .state import private_json
1679
+
1680
+ global _agent_management_warning_emitted
1681
+ if not _agent_management_warning_emitted:
1682
+ _agent_management_warning_emitted = True
1683
+ logger.warning("hermes.compat.agent_management_v0_22_5:复用固定dashboard配置/技能/工具集及owner凭据作用域接缝,非稳定管理SDK")
1684
+ root = Path(profile).resolve()
1685
+ presentation = root / ".fridaynext-agent-presentation.json"
1686
+ token = set_hermes_home_override(root)
1687
+ secret_token = None
1688
+ try:
1689
+ # 管理IPC不属于模型turn;多Profile模式下须显式绑定owner凭据,不能借用调用者或全局环境。
1690
+ secret_token = set_secret_scope(owner_secret_scope(root), profile_home=str(root))
1691
+ with _AGENT_MANAGEMENT_LOCK, config_mod._CONFIG_LOCK:
1692
+ path = config_mod.get_config_path()
1693
+ raw = config_mod.require_readable_config_before_write(path)
1694
+ effective = config_mod.load_config()
1695
+ if presentation.is_symlink() or presentation.exists() and presentation.stat().st_size > 4096:
1696
+ raise ValueError("AGENT_PRESENTATION_UNREADABLE")
1697
+ ui = json.loads(presentation.read_text()) if presentation.exists() else {}
1698
+ if not isinstance(ui, dict) or any(not isinstance(x, str) for x in ui.values()):
1699
+ raise ValueError("AGENT_PRESENTATION_UNREADABLE")
1700
+ installed_skills = find_all_skills(skip_disabled=True)
1701
+ resolved_ui = profile_agent_presentation(root)
1702
+ # 全量技能选择必须绑定读取时的目录,不能把刚安装的未展示技能当作用户关闭。
1703
+ inventory = sorted(row["name"] for row in installed_skills)
1704
+ version = _agent_digest([str(root), raw, effective, ui, resolved_ui, inventory])
1705
+ if patch is not None:
1706
+ if version != expected_version:
1707
+ return {"status": "conflict", "code": "AGENT_CONFIG_CHANGED"}
1708
+ if not isinstance(patch, dict) or len(patch) != 1:
1709
+ return {"status": "conflict", "code": "INVALID_AGENT_PATCH"}
1710
+ target = copy.deepcopy(raw)
1711
+ key, value = next(iter(patch.items()))
1712
+ if key == "greeting" or key == "displayName":
1713
+ limit = 60 if key == "greeting" else 80
1714
+ if not isinstance(value, str) or len(value) > limit:
1715
+ return {"status": "conflict", "code": "INVALID_AGENT_PRESENTATION"}
1716
+ updated_ui = {**ui, key: value.strip()}
1717
+ if prepare: prepare()
1718
+ private_json(presentation, updated_ui)
1719
+ else:
1720
+ if config_mod.is_managed():
1721
+ return {"status": "conflict", "code": "AGENT_CONFIG_READ_ONLY"}
1722
+ if key == "permissionMode":
1723
+ if value not in VALID_APPROVAL_MODES:
1724
+ return {"status": "conflict", "code": "INVALID_APPROVAL_MODE"}
1725
+ target.setdefault("approvals", {})["mode"] = value
1726
+ elif key == "skills":
1727
+ installed = set(inventory)
1728
+ if not isinstance(value, list) or any(not isinstance(x, str) for x in value) or set(value) - installed:
1729
+ return {"status": "conflict", "code": "INVALID_SKILL_SELECTION"}
1730
+ desired = set(value)
1731
+ if (installed & ESSENTIAL_SKILLS) - desired:
1732
+ return {"status": "conflict", "code": "ESSENTIAL_SKILL_REQUIRED"}
1733
+ skills = target.setdefault("skills", {})
1734
+ # 未展示的技能保留;启用明确清除此Profile及当前平台的停用项。
1735
+ disabled = get_disabled_skills(effective) - desired
1736
+ disabled |= installed - desired
1737
+ skills["disabled"] = sorted(disabled - ESSENTIAL_SKILLS)
1738
+ platform_disabled = skills.get("platform_disabled", {})
1739
+ if isinstance(platform_disabled, dict) and "fridaynext" in platform_disabled:
1740
+ prior = platform_disabled["fridaynext"]
1741
+ prior = [prior] if isinstance(prior, str) else prior or []
1742
+ platform_disabled["fridaynext"] = sorted(set(prior) - desired)
1743
+ elif key == "toolset":
1744
+ if not isinstance(value, dict) or set(value) != {"id", "enabled"} or type(value["enabled"]) is not bool:
1745
+ return {"status": "conflict", "code": "INVALID_TOOLSET_SELECTION"}
1746
+ allowed = tools_config._checklist_toolset_keys("fridaynext")
1747
+ name = value["id"]
1748
+ if name not in allowed:
1749
+ return {"status": "conflict", "code": "TOOLSET_NOT_AVAILABLE"}
1750
+ enabled = tools_config._get_platform_tools(effective, "fridaynext", include_default_mcp_servers=False)
1751
+ enabled.add(name) if value["enabled"] else enabled.discard(name)
1752
+ # 保留MCP/未知条目;只替换当前平台的工具集,不改cli或其他Profile。
1753
+ target.setdefault("platform_toolsets", {})["fridaynext"] = sorted(enabled)
1754
+ target.setdefault("known_builtin_toolsets", {})["fridaynext"] = sorted(tools_config._configurable_keys())
1755
+ target.setdefault("known_plugin_toolsets", {})["fridaynext"] = sorted(tools_config._get_plugin_toolset_keys())
1756
+ if value["enabled"]:
1757
+ agent = target.get("agent", {})
1758
+ if isinstance(agent.get("disabled_toolsets"), list):
1759
+ agent["disabled_toolsets"] = [x for x in agent["disabled_toolsets"] if x != name]
1760
+ else:
1761
+ return {"status": "conflict", "code": "INVALID_AGENT_PATCH"}
1762
+ if prepare: prepare()
1763
+ config_mod.atomic_config_replace(path, target)
1764
+ return {"status": "applied"}
1765
+
1766
+ disabled = get_disabled_skills(effective, "fridaynext")
1767
+ skills = [{"id": row["name"], "description": row.get("description", ""), "source": "installed",
1768
+ "editable": row["name"] not in ESSENTIAL_SKILLS} for row in installed_skills]
1769
+ enabled = tools_config._get_platform_tools(effective, "fridaynext", include_default_mcp_servers=False)
1770
+ toolsets = []
1771
+ allowed = tools_config._checklist_toolset_keys("fridaynext")
1772
+ for name, label, description in tools_config._get_effective_configurable_toolsets():
1773
+ if name not in allowed:
1774
+ continue
1775
+ toolsets.append({"id": name, "label": tools_config.gui_toolset_label(label), "description": description,
1776
+ "enabled": name in enabled, "configured": bool(tools_config._toolset_has_keys(name, effective)),
1777
+ "source": "hermes-toolset", "inProfile": False})
1778
+ defaults = profile_default_config(root)
1779
+ return {"version": version, **resolved_ui,
1780
+ "defaults": defaults, "permissionMode": _get_approval_mode(), "permissionModes": list(VALID_APPROVAL_MODES),
1781
+ "skills": sorted(row["id"] for row in skills if row["id"] not in disabled), "availableSkills": skills,
1782
+ "toolsets": toolsets, "writable": not config_mod.is_managed(),
1783
+ "builtinMemory": effective.get("memory", {}).get("provider") in (None, "", "builtin")}
1784
+ finally:
1785
+ if secret_token is not None:
1786
+ reset_secret_scope(secret_token)
1787
+ reset_hermes_home_override(token)
1788
+
1789
+
1790
+ def profile_agent_file(profile, name, *, content=None, expected_version=None, prepare=None):
1791
+ """用目录fd限定三份真实资源;父目录被并发替换也不能跟随链接越出Profile。"""
1792
+ import os
1793
+ import stat
1794
+ import uuid
1795
+ mapping = {"SOUL.md": (None, "SOUL.md"), "MEMORY.md": ("memories", "MEMORY.md"), "USER.md": ("memories", "USER.md")}
1796
+ if name not in mapping:
1797
+ raise ValueError("INVALID_AGENT_FILE")
1798
+ if content is not None and (not isinstance(content, str) or len(content.encode()) > _AGENT_FILE_LIMIT):
1799
+ raise ValueError("INVALID_AGENT_FILE")
1800
+ root = Path(profile).resolve()
1801
+ folder, leaf = mapping[name]
1802
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
1803
+ with _AGENT_MANAGEMENT_LOCK:
1804
+ root_fd = os.open(root, flags)
1805
+ parent_fd = root_fd
1806
+ try:
1807
+ if folder:
1808
+ try:
1809
+ parent_fd = os.open(folder, flags, dir_fd=root_fd)
1810
+ except FileNotFoundError:
1811
+ if content is None:
1812
+ return {"name": name, "exists": False, "content": "", "bytes": 0,
1813
+ "version": _agent_digest([str(root), name, False, ""])}
1814
+ os.mkdir(folder, mode=0o700, dir_fd=root_fd)
1815
+ parent_fd = os.open(folder, flags, dir_fd=root_fd)
1816
+ exists, data, mode = False, b"", 0o600
1817
+ try:
1818
+ fd = os.open(leaf, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent_fd)
1819
+ with os.fdopen(fd, "rb") as stream:
1820
+ info = os.fstat(stream.fileno())
1821
+ if not stat.S_ISREG(info.st_mode) or info.st_size > _AGENT_FILE_LIMIT:
1822
+ raise ValueError("INVALID_AGENT_FILE")
1823
+ data = stream.read(_AGENT_FILE_LIMIT + 1)
1824
+ mode, exists = stat.S_IMODE(info.st_mode), True
1825
+ if len(data) > _AGENT_FILE_LIMIT:
1826
+ raise ValueError("INVALID_AGENT_FILE")
1827
+ except FileNotFoundError:
1828
+ pass
1829
+ except OSError:
1830
+ raise ValueError("INVALID_AGENT_FILE") from None
1831
+ version = _agent_digest([str(root), name, exists, data.hex()])
1832
+ if content is None:
1833
+ return {"name": name, "exists": exists, "content": data.decode("utf-8"), "bytes": len(data), "version": version}
1834
+ if version != expected_version:
1835
+ return {"status": "conflict", "code": "AGENT_FILE_CHANGED"}
1836
+ if prepare: prepare()
1837
+ temporary = ".fridaynext-" + uuid.uuid4().hex
1838
+ try:
1839
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode, dir_fd=parent_fd)
1840
+ with os.fdopen(fd, "wb") as stream:
1841
+ stream.write(content.encode())
1842
+ stream.flush()
1843
+ os.fsync(stream.fileno())
1844
+ os.replace(temporary, leaf, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
1845
+ os.fsync(parent_fd)
1846
+ finally:
1847
+ try: os.unlink(temporary, dir_fd=parent_fd)
1848
+ except FileNotFoundError: pass
1849
+ return {"status": "applied", "value": {"ok": True, "name": name}}
1850
+ except OSError:
1851
+ raise ValueError("INVALID_AGENT_FILE") from None
1852
+ finally:
1853
+ if parent_fd != root_fd: os.close(parent_fd)
1854
+ os.close(root_fd)
1855
+
1856
+
1857
+ def profile_agent_file_names(profile):
1858
+ """文件目录查询不启动宿主bootstrap,避免把缺失SOUL自动种成模板。"""
1859
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
1860
+ from hermes_cli import config as config_mod
1861
+ token = set_hermes_home_override(profile)
1862
+ try:
1863
+ raw = config_mod.require_readable_config_before_write(config_mod.get_config_path())
1864
+ memory = raw.get("memory") or {}
1865
+ return ["SOUL.md"] + (["MEMORY.md", "USER.md"] if memory.get("provider") in (None, "", "builtin") else [])
1866
+ finally:
1867
+ reset_hermes_home_override(token)
1868
+
1869
+
1870
+ def profile_agent_presentation(profile):
1871
+ """App显示覆盖优先,其次使用Hermes原生Profile展示元数据;不解析人设正文猜名字。"""
1872
+ import json
1873
+ from hermes_cli.profiles import read_profile_meta
1874
+ root = Path(profile).resolve()
1875
+ path = root / ".fridaynext-agent-presentation.json"
1876
+ if path.is_symlink() or path.exists() and path.stat().st_size > 4096:
1877
+ raise ValueError("AGENT_PRESENTATION_UNREADABLE")
1878
+ ui = json.loads(path.read_text()) if path.exists() else {}
1879
+ if not isinstance(ui, dict) or any(not isinstance(x, str) for x in ui.values()):
1880
+ raise ValueError("AGENT_PRESENTATION_UNREADABLE")
1881
+ native = read_profile_meta(root)
1882
+ return {"name": ui.get("displayName") or native.get("display_name") or native.get("bot_title") or "HERMES",
1883
+ "greeting": ui.get("greeting", "")}
1884
+
1885
+
1886
+ def profile_agent_write_allowed(profile):
1887
+ """沿用宿主托管配置的只读策略,不在App内绕开它。"""
1888
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
1889
+ from hermes_cli import config as config_mod
1890
+ token = set_hermes_home_override(profile)
1891
+ try:
1892
+ return not config_mod.is_managed()
1893
+ finally:
1894
+ reset_hermes_home_override(token)
1895
+
1896
+
1897
+ # 只投影已经核对过的首批语义;注册表的其余内建项不因同名自动获得管理能力。
1898
+ _SLASH_LOCAL = frozenset({"new", "stop", "model", "reasoning"})
1899
+ _SLASH_READ = frozenset({"help", "commands", "status", "context", "usage", "version", "whoami", "profile", "insights"})
1900
+
1901
+
1902
+ @contextmanager
1903
+ def _slash_scope(adapter, source, cwd=None):
1904
+ from gateway.run import _profile_runtime_scope
1905
+ from gateway.session_commands import _session_workspace
1906
+ from gateway.session_policy import policy_for_source
1907
+ from agent.runtime_cwd import set_session_cwd, reset_session_cwd
1908
+ from gateway.session_context import _SESSION_PLATFORM
1909
+ platform_token = _SESSION_PLATFORM.set("fridaynext")
1910
+ try:
1911
+ with adapter.runtime.locator.owner_scope(adapter.runtime.locator.authority()), _profile_runtime_scope(adapter.profile):
1912
+ # 未绑定目录时只发现本Profile,不借Gateway进程目录的项目技能。
1913
+ token = set_session_cwd(cwd or str(adapter.profile)) if policy_for_source(adapter.gateway_runner, source) is None else None
1914
+ try:
1915
+ with _session_workspace(adapter.gateway_runner, source):
1916
+ yield
1917
+ finally:
1918
+ if token is not None:
1919
+ reset_session_cwd(token)
1920
+ finally:
1921
+ _SESSION_PLATFORM.reset(platform_token)
1922
+
1923
+
1924
+ def slash_command_catalog(adapter, source, cwd=None):
1925
+ """固定版registry和当前profile的原生可发现项;不运行命令或扫描别的Profile。"""
1926
+ from hermes_cli.commands import COMMAND_REGISTRY
1927
+ from hermes_cli.plugins import get_plugin_commands
1928
+ from agent.skill_commands import get_skill_commands
1929
+ from .canonical_control import NativeControlError
1930
+ runner = getattr(adapter, "gateway_runner", None)
1931
+ if (runner is None or adapter.runtime.validate_source(source) is not True
1932
+ or adapter.runtime.locator.authorize_initial_source(source) is not True):
1933
+ raise NativeControlError("COMMAND_PERMISSION_DENIED")
1934
+ verified_source()
1935
+ with _slash_scope(adapter, source, cwd=cwd):
1936
+ def allowed(name):
1937
+ return not runner._check_slash_access(source, name)
1938
+ rows = []
1939
+ for cmd in COMMAND_REGISTRY:
1940
+ if cmd.name not in _SLASH_LOCAL | _SLASH_READ | {"compress"} or not allowed(cmd.name):
1941
+ continue
1942
+ kind = "local" if cmd.name in _SLASH_LOCAL else "compaction" if cmd.name == "compress" else "result"
1943
+ args = []
1944
+ if cmd.name in {"model", "reasoning", "help", "compress"}:
1945
+ args = [{"name": "value", "required": False, "choices": []}]
1946
+ rows.append({"name": cmd.name, "textAliases": list(cmd.aliases), "description": cmd.describe(),
1947
+ "category": "options" if cmd.name in {"model", "reasoning"} else "session" if cmd.name in {"new", "stop", "compress"} else "status",
1948
+ "tier": "essential" if cmd.name in {"new", "stop", "model", "reasoning"} else "power" if cmd.name in {"insights", "profile"} else "standard",
1949
+ "kind": kind, "acceptsArgs": bool(args), "args": args})
1950
+ seen = {name for row in rows for name in (row["name"], *row["textAliases"])}
1951
+ for name, meta in (get_plugin_commands() or {}).items():
1952
+ if (not isinstance(name, str) or not name or any(c.isspace() or c == "/" for c in name)
1953
+ or name in seen or not isinstance(meta, dict) or not allowed(name)):
1954
+ continue
1955
+ rows.append({"name": name, "textAliases": [], "description": str(meta.get("description") or name),
1956
+ "category": "tools", "tier": "standard", "kind": "result", "acceptsArgs": bool(meta.get("args_hint")),
1957
+ "args": [{"name": str(meta["args_hint"]), "required": False, "choices": []}] if meta.get("args_hint") else []})
1958
+ seen.add(name)
1959
+ # 原生messaging目录不包含interactive-only插件技能;不扩大宿主平台权限。
1960
+ for native_key, info in get_skill_commands().items():
1961
+ name = native_key.removeprefix("/")
1962
+ if name in seen or not allowed(name):
1963
+ continue
1964
+ rows.append({"name": name, "textAliases": [], "description": str(info.get("description") or name),
1965
+ "category": "tools", "tier": "standard", "kind": "run", "acceptsArgs": True,
1966
+ "args": [{"name": "instruction", "required": False, "choices": []}]})
1967
+ return rows
1968
+
1969
+
1970
+ def _slash_selection(adapter, source, text, cwd=None):
1971
+ from .canonical_control import NativeControlError
1972
+ parts = text[1:].split(None, 1)
1973
+ if not parts:
1974
+ raise NativeControlError("SLASH_COMMAND_UNSUPPORTED")
1975
+ name, arg = parts[0].lower(), parts[1] if len(parts) > 1 else ""
1976
+ command = next((row for row in slash_command_catalog(adapter, source, cwd=cwd)
1977
+ if name == row["name"] or name in row["textAliases"]), None)
1978
+ if command is None:
1979
+ raise NativeControlError("SLASH_COMMAND_UNSUPPORTED")
1980
+ if arg and command["name"] not in {"model", "reasoning", "help", "compress"} and command["category"] != "tools":
1981
+ raise NativeControlError("COMMAND_ARGUMENT_UNSUPPORTED")
1982
+ return command, arg
1983
+
1984
+
1985
+ def prepare_slash_run(adapter, source, text, cwd=None):
1986
+ from agent.skill_commands import build_skill_invocation_message
1987
+ from .canonical_control import NativeControlError
1988
+ command, arg = _slash_selection(adapter, source, text, cwd=cwd)
1989
+ if command["kind"] != "run":
1990
+ raise NativeControlError("COMMAND_IS_NOT_A_RUN")
1991
+ with _slash_scope(adapter, source, cwd=cwd):
1992
+ # 只解析刚由原生messaging目录确认的名字;不将任意未知命令交给模型解释。
1993
+ message = build_skill_invocation_message("/" + command["name"], arg)
1994
+ if not message:
1995
+ raise NativeControlError("SLASH_COMMAND_UNSUPPORTED")
1996
+ return {"allowed": True, "kind": "run", "message": message, "display": text}
1997
+
1998
+
1999
+ async def execute_slash_command(adapter, source, text, *, has_session, check, cwd=None):
2000
+ """已授权原生处理器接缝;不调用Agent循环,不依赖文本回流猜测终态。"""
2001
+ from gateway.platforms.event import MessageEvent
2002
+ from hermes_cli.commands import resolve_command
2003
+ from hermes_cli.plugins import get_plugin_command_handler
2004
+ from .canonical_control import NativeControlError
2005
+ runner = adapter.gateway_runner
2006
+ check()
2007
+ command, _ = _slash_selection(adapter, source, text, cwd=cwd)
2008
+ if command["kind"] == "run":
2009
+ return {"kind": "run", "text": text}
2010
+ if command["kind"] == "local":
2011
+ return {"kind": "local", "text": text}
2012
+ if not has_session and command["name"] not in {"help", "commands", "version", "whoami", "profile"}:
2013
+ raise NativeControlError("COMMAND_SESSION_REQUIRED")
2014
+ logger.warning("hermes.compat.slash_handlers_v0_22_5:固定GatewayRunner授权与原生处理器,非公开slash.exec平台等价")
2015
+ event = MessageEvent(text=text, source=source, message_id=source.message_id, internal=False, allow_gateway_control=True)
2016
+ with _slash_scope(adapter, source, cwd=cwd):
2017
+ admitted = await runner._hm_admit_event(event)
2018
+ check()
2019
+ if (admitted is None or admitted[0].text != text or admitted[1] is not source or admitted[2] is not False):
2020
+ raise NativeControlError("COMMAND_PERMISSION_DENIED")
2021
+ event = admitted[0]
2022
+ # ingress之后重查目录/权限,撤回的插件命令不能落入普通模型分支。
2023
+ command, arg = _slash_selection(adapter, source, text, cwd=cwd)
2024
+ refused = runner._check_slash_access(source, command["name"])
2025
+ if refused:
2026
+ raise NativeControlError("COMMAND_PERMISSION_DENIED")
2027
+ definition = resolve_command(command["name"])
2028
+ rejected = False
2029
+ if definition is None:
2030
+ handler = get_plugin_command_handler(command["name"])
2031
+ if handler is None:
2032
+ raise NativeControlError("SLASH_COMMAND_UNSUPPORTED")
2033
+ route = adapter._source_session_key(source)
2034
+ entry = await asyncio.to_thread(runner.session_store.lookup_by_session_key, route)
2035
+ check()
2036
+ output = await runner._hm_run_plugin_handler(handler, event, source, entry, args=arg)
2037
+ else:
2038
+ # 宿主自己的busy分派与处理器表;不以客户端可见状态代替原会话占用事实。
2039
+ route = adapter._source_session_key(source)
2040
+ if route in adapter._active_sessions:
2041
+ rejected = runner._busy_slash_route(definition)[0] == "reject"
2042
+ output = await runner._dispatch_busy_slash_command(event, definition, route, source)
2043
+ else:
2044
+ output = await runner._command_handler_table((command["name"],))[command["name"]](event)
2045
+ check()
2046
+ return {"kind": command["kind"], "text": str(getattr(output, "text", output) or ""),
2047
+ **({"isError": True} if rejected else {})}
2048
+
2049
+
2050
+ def public_slash_command_catalog(value):
2051
+ """将公开local-session目录映射到首批合同;不复活远端未给出的名字。"""
2052
+ from hermes_cli.commands import COMMAND_REGISTRY
2053
+ from .canonical_control import NativeControlError
2054
+ if not isinstance(value, dict) or not isinstance(value.get("pairs"), list) or not isinstance(value.get("commands"), dict):
2055
+ raise NativeControlError("COMMAND_CATALOG_INVALID")
2056
+ pairs = {item[0].removeprefix("/"): str(item[1]) for item in value["pairs"]
2057
+ if isinstance(item, list) and len(item) == 2 and isinstance(item[0], str)}
2058
+ metadata = value["commands"]
2059
+ rows, seen = [], set()
2060
+ for cmd in COMMAND_REGISTRY:
2061
+ if cmd.name not in _SLASH_LOCAL | _SLASH_READ or (cmd.name not in pairs and "/" + cmd.name not in metadata):
2062
+ continue
2063
+ args = [{"name": "value", "required": False, "choices": []}] if cmd.name in {"model", "reasoning", "help"} else []
2064
+ rows.append({"name": cmd.name, "textAliases": list(cmd.aliases), "description": pairs.get(cmd.name, cmd.describe()),
2065
+ "category": "options" if cmd.name in {"model", "reasoning"} else "session" if cmd.name in {"new", "stop"} else "status",
2066
+ "tier": "essential" if cmd.name in _SLASH_LOCAL else "standard", "kind": "local" if cmd.name in _SLASH_LOCAL else "result",
2067
+ "acceptsArgs": bool(args), "args": args})
2068
+ seen.update((cmd.name, *cmd.aliases))
2069
+ plugins, skills = value.get("plugin_commands", {}), value.get("skills", {})
2070
+ if not isinstance(plugins, dict) or not isinstance(skills, dict):
2071
+ raise NativeControlError("COMMAND_CATALOG_INVALID")
2072
+ for source, kind in ((plugins, "result"), (skills, "run")):
2073
+ for key in source:
2074
+ name = key.removeprefix("/")
2075
+ if name in seen or name not in pairs:
2076
+ continue
2077
+ rows.append({"name": name, "textAliases": [], "description": pairs[name], "category": "tools", "tier": "standard",
2078
+ "kind": kind, "acceptsArgs": True, "args": [{"name": "arguments", "required": False, "choices": []}]})
2079
+ seen.add(name)
2080
+ return rows