@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
@@ -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 = ["minimal", "low", "medium", "high"]
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.insert(0, "none")
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": "Hermes Agent",
197
+ "name": ui["name"],
198
+ "greeting": ui["greeting"],
195
199
  "isDefault": True,
196
200
  "settings": [
197
201
  {
@@ -0,0 +1,163 @@
1
+ """所属适配器的命令目录、分类与作用域;原生语义集中在固定兼容封装。"""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ from pathlib import Path
6
+ from .canonical_control import NativeControlError
7
+ from . import compat_v0225
8
+
9
+
10
+ class SlashCommandsPort:
11
+ public_methods = ("commands.catalog", "slash.exec")
12
+
13
+ def __init__(self, adapter):
14
+ self.adapter = adapter
15
+ self.profile = Path(adapter.profile).resolve()
16
+ stat = self.profile.stat()
17
+ self.profile_identity = (stat.st_dev, stat.st_ino)
18
+
19
+ def check(self, params):
20
+ stat = self.profile.stat()
21
+ if (params.get("serviceInstanceId") != self.adapter.service_id
22
+ or params.get("agentId") not in (None, "hermes")
23
+ or not self.adapter.plugin_enabled or self.adapter.profile.resolve() != self.profile
24
+ or (stat.st_dev, stat.st_ino) != self.profile_identity):
25
+ raise NativeControlError("COMMAND_SCOPE_CHANGED")
26
+
27
+ async def shared_target(self, params):
28
+ key = params.get("sessionKey")
29
+ if key is None:
30
+ return None
31
+ if not isinstance(key, str) or not key or key == "__empty__":
32
+ raise NativeControlError("COMMAND_SESSION_INVALID")
33
+ catalog = self.adapter._catalog()
34
+ if catalog.directory.get(key):
35
+ selected = await catalog.resolve(key)
36
+ self.check(params)
37
+ if selected.get("shared"):
38
+ return selected["native_id"]
39
+ if selected.get("origin") != "platform":
40
+ raise NativeControlError("COMMAND_SESSION_READ_ONLY")
41
+ return None
42
+
43
+ async def source(self, params):
44
+ self.check(params)
45
+ key = params.get("sessionKey")
46
+ if key is not None and (not isinstance(key, str) or not key or key == "__empty__"):
47
+ raise NativeControlError("COMMAND_SESSION_INVALID")
48
+ source = self.adapter._source({"chat_id": "fridaynext-" + hashlib.sha256((key or "command-catalog").encode()).hexdigest(),
49
+ "input_id": "command:" + str(params.get("commandId") or "catalog")})
50
+ native = self.adapter.bindings.session_id(key) if key else None
51
+ cwd = None
52
+ if native:
53
+ client = self.adapter.runtime.client
54
+ await client.connect()
55
+ value = await client._request(client.socket, "session.info", {"session_id": native})
56
+ self.check(params)
57
+ candidate = value.get("cwd")
58
+ if isinstance(candidate, str) and Path(candidate).is_absolute() and "\x00" not in candidate:
59
+ cwd = candidate
60
+ return source, cwd, native is not None
61
+
62
+ async def call(self, method, params):
63
+ self.check(params)
64
+ runtime, host = self.adapter.runtime, self.adapter.host
65
+ connect = getattr(getattr(runtime, "client", None), "connect", None)
66
+ if callable(connect):
67
+ await connect()
68
+ self.check(params)
69
+ if self.adapter.runtime is not runtime or self.adapter.host is not host:
70
+ raise NativeControlError("COMMAND_SCOPE_CHANGED")
71
+ identity = dict(getattr(getattr(runtime, "client", None), "identity", {}) or {})
72
+ def check():
73
+ self.check(params)
74
+ current = getattr(getattr(runtime, "client", None), "identity", {}) or {}
75
+ if (self.adapter.runtime is not runtime or self.adapter.host is not host
76
+ or any(current.get(key) != identity.get(key) for key in ("instance_id", "authority_epoch"))):
77
+ raise NativeControlError("COMMAND_SCOPE_CHANGED")
78
+ try:
79
+ shared = await self.shared_target(params)
80
+ check()
81
+ if shared is not None:
82
+ return await self.call_shared(method, params, shared, check)
83
+ source, cwd, has_native_session = await self.source(params)
84
+ check()
85
+ if method == "commands.list":
86
+ value = await asyncio.to_thread(compat_v0225.slash_command_catalog, self.adapter, source, cwd=cwd)
87
+ check()
88
+ return {"commands": value}
89
+ text = params.get("text")
90
+ if not isinstance(text, str) or not text.startswith("/") or len(text) > 32768:
91
+ raise NativeControlError("COMMAND_INPUT_INVALID")
92
+ if method == "commands.prepare":
93
+ value = await asyncio.to_thread(compat_v0225.prepare_slash_run, self.adapter, source, text, cwd=cwd)
94
+ check()
95
+ return value
96
+ if method == "commands.execute":
97
+ value = await compat_v0225.execute_slash_command(self.adapter, source, text,
98
+ has_session=has_native_session, check=check, cwd=cwd)
99
+ check()
100
+ return value
101
+ raise NativeControlError("COMMAND_METHOD_UNSUPPORTED")
102
+ except NativeControlError as error:
103
+ if method == "commands.list":
104
+ raise
105
+ if method == "commands.prepare":
106
+ return {"allowed": False, "reason": error.code}
107
+ messages = {
108
+ "SLASH_COMMAND_UNSUPPORTED": "当前会话不支持此命令,或命令已被移除。",
109
+ "COMMAND_PERMISSION_DENIED": "当前会话没有执行该命令的权限。",
110
+ "permission_denied": "当前会话没有执行该命令的权限。",
111
+ "COMMAND_SESSION_REQUIRED": "请先进入已有会话,再执行此命令。",
112
+ "COMMAND_SESSION_READ_ONLY": "当前会话只支持浏览历史。",
113
+ "COMMAND_SCOPE_CHANGED": "会话连接已变化,请重新操作。",
114
+ "COMMAND_ARGUMENT_UNSUPPORTED": "当前命令不支持这些参数。",
115
+ }
116
+ return {"kind": "result", "isError": True, "code": error.code,
117
+ "text": messages.get(error.code, "命令暂时无法执行,请检查连接后重试。")}
118
+
119
+ async def call_shared(self, method, params, native_id, check):
120
+ client = self.adapter.runtime.client
121
+ await client.connect()
122
+ check()
123
+ value = await client._request(client.socket, "commands.catalog", {"session_id": native_id})
124
+ check()
125
+ commands = compat_v0225.public_slash_command_catalog(value)
126
+ if method == "commands.list":
127
+ return {"commands": commands}
128
+ text = params.get("text")
129
+ if not isinstance(text, str) or not text.startswith("/") or len(text) > 32768:
130
+ raise NativeControlError("COMMAND_INPUT_INVALID")
131
+ parts = text[1:].split(None, 1)
132
+ name = parts[0].lower() if parts else ""
133
+ command = next((row for row in commands if name == row["name"] or name in row["textAliases"]), None)
134
+ if command is None:
135
+ raise NativeControlError("SLASH_COMMAND_UNSUPPORTED")
136
+ if len(parts) > 1 and not command["acceptsArgs"]:
137
+ raise NativeControlError("COMMAND_ARGUMENT_UNSUPPORTED")
138
+ if method == "commands.execute" and command["kind"] in {"local", "run"}:
139
+ return {"kind": command["kind"], "text": text}
140
+ if method == "commands.prepare" and command["kind"] != "run":
141
+ raise NativeControlError("COMMAND_IS_NOT_A_RUN")
142
+ # 只在公开端口明确返回skill/send directive后进入原持久消息管线;此调用本身不启动模型。
143
+ result = await client._request(client.socket, "slash.exec", {"session_id": native_id, "command": text})
144
+ check()
145
+ if method == "commands.prepare":
146
+ if (result.get("type") not in {"skill", "send"} or not isinstance(result.get("message"), str)
147
+ or not result["message"].strip()):
148
+ raise NativeControlError("COMMAND_RESULT_INVALID")
149
+ return {"allowed": True, "kind": "run", "message": result["message"], "display": text}
150
+ if result.get("type") != "exec" or not isinstance(result.get("output"), str):
151
+ raise NativeControlError("COMMAND_RESULT_INVALID")
152
+ return {"kind": "result", "text": result["output"]}
153
+
154
+
155
+ def split_options(options):
156
+ settings = dict(options)
157
+ context = settings.pop("commandContext", None)
158
+ if context is not None and (not isinstance(context, dict) or set(context) != {"version", "text"}
159
+ or type(context.get("version")) is not int or context["version"] != 1
160
+ or not isinstance(context.get("text"), str) or not context["text"].startswith("/")
161
+ or len(context["text"]) > 32768):
162
+ raise ValueError("COMMAND_CONTEXT_INVALID")
163
+ return context, settings