@syengup/fridaynext-hermes-channel 0.1.0-beta.2 → 0.1.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +2 -2
  2. package/install-config.js +67 -0
  3. package/install-runtime.js +18 -9
  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 +231 -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 +1247 -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/message_speech.py +143 -0
  19. package/plugin/fridaynext_plugin/multi_agent.py +221 -0
  20. package/plugin/fridaynext_plugin/reply_context.py +39 -0
  21. package/plugin/fridaynext_plugin/runtime_port.py +23 -1
  22. package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
  23. package/plugin/fridaynext_plugin/settings.py +7 -3
  24. package/plugin/fridaynext_plugin/slash_commands.py +163 -0
  25. package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
  26. package/plugin/fridaynext_plugin/stream_projection.py +30 -6
  27. package/plugin/fridaynext_plugin/subagents.py +228 -0
  28. package/plugin/plugin.yaml +11 -0
  29. package/plugin/runtime/dist/commands-routes.js +94 -0
  30. package/plugin/runtime/dist/device-tools-v1.json +302 -0
  31. package/plugin/runtime/dist/hosted-backend.js +293 -25
  32. package/plugin/runtime/dist/hosted-continuations.js +41 -0
  33. package/plugin/runtime/dist/hosted-device-tools.js +82 -0
  34. package/plugin/runtime/dist/hosted-media.js +54 -13
  35. package/plugin/runtime/dist/hosted-stream.js +124 -14
  36. package/plugin/runtime/dist/hosted-subagents.js +78 -0
  37. package/plugin/runtime/dist/platform-service.js +4 -0
  38. package/plugin/runtime/dist/plugin-control.js +10 -6
  39. package/plugin/runtime/dist/scheduled-routes.js +63 -0
  40. package/plugin/runtime/dist/service-host.js +40 -5
  41. package/plugin/runtime/dist/speech-routes.js +111 -0
  42. package/plugin/runtime/dist/tool-presentation.js +399 -0
  43. package/plugin/runtime/node_modules/.package-lock.json +6 -6
  44. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
  45. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
  46. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
  47. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
  48. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
  49. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
  50. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
  51. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
  52. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
  53. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
  54. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
  55. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
  56. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
  57. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
  58. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
  59. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
  60. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
  61. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
  62. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
  63. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
  64. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
  65. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
  66. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
  67. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
  68. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
  69. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
  70. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
  71. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
  72. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
  73. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
  74. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
  75. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
  76. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
  77. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
  78. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
  79. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
  80. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
  81. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
  82. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
  83. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
  84. package/plugin/runtime/node_modules/tslib/README.md +3 -8
  85. package/plugin/runtime/node_modules/tslib/package.json +1 -1
  86. package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
  87. package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
  88. package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
  89. package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
  90. package/plugin/runtime/package-lock.json +7 -7
  91. package/plugin/runtime/package.json +1 -1
  92. package/plugin/tools.py +3 -0
@@ -0,0 +1,144 @@
1
+ """标准手机工具;跨线程只交接固定来源,不接受模型选择设备。"""
2
+
3
+ import asyncio
4
+ import copy
5
+ import json
6
+ import math
7
+ import secrets
8
+ from pathlib import Path
9
+ from .canonical_control import NativeControlError
10
+
11
+ CONTRACT = json.loads(Path(__file__).with_name("device-tools-v1.json").read_text())
12
+
13
+
14
+ def _validate(value, schema):
15
+ kind = schema["type"]
16
+ valid = {"object": lambda: type(value) is dict, "array": lambda: type(value) is list,
17
+ "string": lambda: type(value) is str, "boolean": lambda: type(value) is bool,
18
+ "integer": lambda: type(value) is int,
19
+ "number": lambda: type(value) in (int, float) and math.isfinite(value)}[kind]()
20
+ if not valid or ("enum" in schema and value not in schema["enum"]):
21
+ raise ValueError("DEVICE_INVALID_ARGUMENTS")
22
+ if kind == "object":
23
+ if set(value) - set(schema["properties"]) or set(schema.get("required", [])) - set(value):
24
+ raise ValueError("DEVICE_INVALID_ARGUMENTS")
25
+ for key, item in value.items():
26
+ _validate(item, schema["properties"][key])
27
+ elif kind == "array":
28
+ if not schema.get("minItems", 0) <= len(value) <= schema.get("maxItems", 256):
29
+ raise ValueError("DEVICE_INVALID_ARGUMENTS")
30
+ for item in value:
31
+ _validate(item, schema["items"])
32
+ elif kind == "string":
33
+ if not schema.get("minLength", 0) <= len(value) <= schema.get("maxLength", 4096):
34
+ raise ValueError("DEVICE_INVALID_ARGUMENTS")
35
+ elif kind in ("integer", "number"):
36
+ if value < schema.get("minimum", -math.inf) or value > schema.get("maximum", math.inf):
37
+ raise ValueError("DEVICE_INVALID_ARGUMENTS")
38
+
39
+
40
+ def _failure(code):
41
+ return {"ok": False, "error": {"code": code, "message": {
42
+ "DEVICE_SOURCE_UNAVAILABLE": "本工具仅供FridayNext App当前输入及其绑定iPhone使用",
43
+ "DEVICE_RESULT_UNKNOWN": "设备操作结果未知,请先核实;不要自动再次写入",
44
+ "DEVICE_INVALID_ARGUMENTS": "手机工具参数无效",
45
+ }.get(code, "原手机请求当前不可用")}}
46
+
47
+
48
+ async def check_scope(adapter, scope):
49
+ if (not adapter.plugin_enabled or adapter.host is None
50
+ or scope.get("serviceInstanceId") != adapter.service_id
51
+ or scope.get("profileRoot") != str(adapter.profile)):
52
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
53
+ locator = getattr(adapter.runtime, "locator", None)
54
+ if locator is None or not locator.device_scope_matches(scope):
55
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
56
+ record = adapter.bindings.read(scope["runId"])
57
+ if record is None:
58
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
59
+ lease = adapter._recovery().lease()
60
+ receipt = await adapter.runtime.receipt(conversation_id=scope["nativeId"],
61
+ admission_id=scope["admissionId"], input_id=scope["inputId"])
62
+ adapter._recovery().check(lease)
63
+ if (receipt is None or receipt.get("status") != "started"
64
+ or receipt.get("generation") != scope["generation"]
65
+ or receipt.get("authority_epoch") != scope["authorityEpoch"]
66
+ or not locator.device_scope_matches(scope)):
67
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
68
+
69
+
70
+ async def _dispatch(adapter, scope, operation, arguments):
71
+ await check_scope(adapter, scope)
72
+ host = adapter.host
73
+ transport = getattr(host, "transport", host)
74
+ writer = transport.writer
75
+ if writer is None or writer.is_closing() or transport.stopping:
76
+ return _failure("DEVICE_SOURCE_UNAVAILABLE")
77
+ token = secrets.token_hex(32)
78
+ calls = getattr(transport, "device_calls", None)
79
+ if calls is None:
80
+ transport.device_calls = calls = {}
81
+ pending = (adapter, scope, writer)
82
+ calls[token] = pending
83
+ try:
84
+ return await transport._call_worker("device.request", {
85
+ "version": 1, "source": scope, "scopeToken": token,
86
+ "operation": operation, "arguments": arguments,
87
+ }, timeout=70)
88
+ finally:
89
+ calls.pop(token, None)
90
+
91
+
92
+ async def check_call(host, params):
93
+ token = params.get("scopeToken")
94
+ pending = getattr(host, "device_calls", {}).get(token) if isinstance(token, str) else None
95
+ if pending is None or host.stopping:
96
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
97
+ adapter, scope, writer = pending
98
+ if host.writer is not writer or writer.is_closing() or params.get("source") != scope:
99
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
100
+ await check_scope(adapter, scope)
101
+ if (getattr(host, "device_calls", {}).get(token) is not pending
102
+ or host.writer is not writer or host.stopping):
103
+ raise NativeControlError("DEVICE_SOURCE_UNAVAILABLE")
104
+ return {"allowed": True}
105
+
106
+
107
+ async def invoke(operation, arguments, *, session_id=None, **kwargs):
108
+ try:
109
+ _validate(arguments, CONTRACT["operations"][operation]["parameters"])
110
+ from hermes_constants import get_hermes_home
111
+ from .adapter import FridayNextAdapter
112
+ profile = Path(get_hermes_home()).resolve()
113
+ candidates = [a for a in tuple(FridayNextAdapter.instances)
114
+ if a.profile == profile and a.plugin_enabled and getattr(a, "runtime", None)
115
+ and getattr(a, "owner_loop", None) is not None and not a.owner_loop.is_closed()]
116
+ if len(candidates) != 1:
117
+ return _failure("DEVICE_SOURCE_UNAVAILABLE")
118
+ adapter = candidates[0]
119
+ # 固定版本兼容层在产生调用的原线程捕获准入和工具身份。
120
+ scope = adapter.runtime.locator.device_tool_scope(session_id)
121
+ if scope is None:
122
+ return _failure("DEVICE_SOURCE_UNAVAILABLE")
123
+ work = _dispatch(adapter, scope, operation, copy.deepcopy(arguments))
124
+ if asyncio.get_running_loop() is adapter.owner_loop:
125
+ return await work
126
+ return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(work, adapter.owner_loop))
127
+ except ValueError:
128
+ return _failure("DEVICE_INVALID_ARGUMENTS")
129
+ except NativeControlError:
130
+ return _failure("DEVICE_SOURCE_UNAVAILABLE")
131
+ except Exception:
132
+ return _failure("DEVICE_RESULT_UNKNOWN")
133
+
134
+
135
+ def register_tools(ctx):
136
+ for operation, definition in CONTRACT["operations"].items():
137
+ def handler_for(operation):
138
+ async def handler(args, **kwargs):
139
+ # 官方工具结果只接受文本或多模态信封;普通dict会被归一化为契约错误。
140
+ return json.dumps(await invoke(operation, args, **kwargs), ensure_ascii=False, allow_nan=False)
141
+ return handler
142
+ ctx.register_tool(name=definition["name"], toolset="fridaynext_device",
143
+ schema=definition, description=definition["description"],
144
+ handler=handler_for(operation), is_async=True)
@@ -9,6 +9,7 @@ from hermes_state import SessionDB
9
9
  from gateway.platforms.base import BasePlatformAdapter
10
10
  from .canonical_control import NativeControlError
11
11
  from . import inline_media
12
+ from . import reply_context
12
13
 
13
14
 
14
15
  def message_identity(row):
@@ -82,7 +83,8 @@ def normalize_message(row, seq, *, link=None, turn="unbound", tool_error=None):
82
83
  identity = message_identity(row)
83
84
  role = row.get("role")
84
85
  known_role = role in ("user", "assistant", "tool", "toolResult", "system")
85
- hidden = not known_role or row.get("display_kind") == "hidden"
86
+ # 后台通知仅供模型续接;展示层隐藏原行,稳定身份和分页位置仍保留。
87
+ hidden = not known_role or row.get("display_kind") in ("hidden", "internal_notification")
86
88
  content = row.get("display_content", row.get("content", row.get("text")))
87
89
  text, images = content_parts(content)
88
90
  # 宿主失败边界行不得成为助手正文;保留原文和失败事实供历史静默恢复。
@@ -191,10 +193,11 @@ def page_preview(row, budget):
191
193
 
192
194
 
193
195
  class HistoryReader:
194
- def __init__(self, runtime, profile, bindings):
196
+ def __init__(self, runtime, profile, bindings, extra_records=()):
195
197
  self.runtime = runtime
196
198
  self.profile = Path(profile)
197
199
  self.bindings = bindings
200
+ self.extra_records = extra_records
198
201
 
199
202
  def metadata(self, conversation_id):
200
203
  db = SessionDB(db_path=self.profile / "state.db", read_only=True)
@@ -218,7 +221,7 @@ class HistoryReader:
218
221
  by_uid = {}
219
222
  by_user_row = {}
220
223
  tool_evidence = {}
221
- for record in self.bindings.all():
224
+ for record in [*self.bindings.all(), *self.extra_records]:
222
225
  if (
223
226
  record.get("session_key") != key
224
227
  or record.get("native_id") != conversation_id
@@ -370,6 +373,25 @@ class HistoryReader:
370
373
  # 此字段仅跨本机RPC给Kit冻结字节再次核对,不能直接成为公共DTO。
371
374
  messages[-1]["_inputMedia"] = {**proof, "messageId": entry["id"],
372
375
  "runId": link["run_id"], "clientRequestId": link.get("client_request_id")}
376
+ if (link and row.get("role") == "user" and link.get("command_context")
377
+ and messages[-1].get("text") == link.get("text") and messages[-1].get("content") == link.get("text")):
378
+ from .slash_commands import split_options
379
+ context, _ = split_options({"commandContext": link["command_context"]})
380
+ # 原输入身份、原生用户行及完整展开正文均已匹配;只改变展示,不改宿主持久记录。
381
+ messages[-1]["text"] = context["text"]
382
+ messages[-1]["content"] = context["text"]
383
+ if link and row.get("role") == "user" and link.get("reply_context"):
384
+ from .compat_v0225 import native_reply_text
385
+ context = reply_context.checked(link["reply_context"])
386
+ expected = (link["text"] if link.get("shared") else native_reply_text(context, link["text"]))
387
+ media_proof = messages[-1].get("_inputMedia")
388
+ if media_proof:
389
+ expected = media_proof["rendered"]
390
+ if messages[-1].get("text") == expected and messages[-1].get("content") == expected:
391
+ # 仅确切原user/原正文匹配才允许展示转换,不修改原生持久记录。
392
+ messages[-1]["_replyContext"] = {"version": 1, "context": context, "text": link["text"],
393
+ "rendered": expected, "messageId": entry["id"], "runId": link["run_id"],
394
+ "clientRequestId": link.get("client_request_id")}
373
395
  if (link and row.get("role") == "assistant" and entry["id"] == link.get("answer_uid")
374
396
  and link.get("delivered_answer") and isinstance(link.get("answer"), str)
375
397
  and isinstance(link.get("answer_source_text"), str)
@@ -215,6 +215,9 @@ class KitHost:
215
215
  # 只提示重新读取原运行回执;不在本地IPC声明执行outcome。
216
216
  return await self._call_worker("run.changed", params)
217
217
 
218
+ async def scheduled_publish(self, params):
219
+ return await self._call_worker("schedule.publish", params)
220
+
218
221
  async def register_media(self, params, *, context):
219
222
  return await self._scoped_media_call("media.register", params, context)
220
223
 
@@ -243,17 +246,17 @@ class KitHost:
243
246
  context, writer = pending
244
247
  if self.writer is not writer or writer.is_closing() or params.get("source") != context.wire():
245
248
  raise RuntimeError("MEDIA_CALL_SCOPE_INVALID")
246
- await check_delivery(self.adapter, context)
249
+ await check_delivery(context.adapter, context)
247
250
  if params.get("purpose") == "delivery-observation":
248
251
  from .media_observations import has_orphan
249
- if not has_orphan(self.adapter, context):
252
+ if not has_orphan(context.adapter, context):
250
253
  raise RuntimeError("MEDIA_OBSERVATION_SOURCE_UNCONFIRMED")
251
254
  if (self.media_calls.get(token) is not pending or self.stopping
252
255
  or self.writer is not writer or writer.is_closing()):
253
256
  raise RuntimeError("MEDIA_CALL_RETIRED")
254
257
  return {"allowed": True}
255
258
 
256
- async def _call_worker(self, method, params):
259
+ async def _call_worker(self, method, params, *, timeout=10):
257
260
  writer = self.writer
258
261
  if writer is None:
259
262
  raise RuntimeError("KIT_DISCONNECTED")
@@ -273,7 +276,7 @@ class KitHost:
273
276
  ).encode()
274
277
  )
275
278
  await writer.drain()
276
- result = await asyncio.wait_for(asyncio.shield(future), 10)
279
+ result = await asyncio.wait_for(asyncio.shield(future), timeout)
277
280
  resolved = True
278
281
  return result
279
282
  finally:
@@ -1,7 +1,8 @@
1
- """标准平台入站只消费所属Kit已经冻结的图片,不解释客户端路径。"""
1
+ """标准平台入站只消费所属Kit已经冻结的附件,不解释客户端路径。"""
2
2
 
3
3
  import asyncio
4
4
  import base64
5
+ import codecs
5
6
  import hashlib
6
7
  import os
7
8
  from pathlib import Path
@@ -10,6 +11,22 @@ import stat
10
11
  from .runtime_port import InputAdmissionRefused, InputAdmissionUnconfirmed
11
12
 
12
13
  MIMES = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}
14
+ FILE_MIMES = frozenset({
15
+ "application/octet-stream", "application/pdf", "application/json", "application/xml",
16
+ "application/yaml", "application/x-yaml", "application/javascript", "application/rtf",
17
+ "application/msword", "application/vnd.ms-excel", "application/vnd.ms-powerpoint",
18
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
19
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
20
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
21
+ "application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.spreadsheet",
22
+ "application/vnd.oasis.opendocument.presentation", "application/zip", "application/gzip",
23
+ "application/x-gzip", "application/x-tar", "application/x-7z-compressed", "application/x-rar-compressed",
24
+ "application/vnd.rar", "application/x-bzip2", "application/x-sqlite3", "application/epub+zip",
25
+ "text/plain", "text/markdown", "text/x-markdown", "text/csv", "text/tab-separated-values",
26
+ "text/html", "text/css", "text/javascript", "text/xml", "text/yaml", "text/x-yaml", "text/rtf",
27
+ "text/x-python", "text/x-script.python", "text/x-swift", "text/x-c", "text/x-c++",
28
+ "text/x-shellscript", "application/x-sh", "application/x-python-code",
29
+ })
13
30
  PREFIX = "hermes-media-v1:"
14
31
 
15
32
 
@@ -30,7 +47,18 @@ def image_mime(data):
30
47
  return "image/webp"
31
48
 
32
49
 
33
- def _verify(root, references, expected, limit, file_limit=0):
50
+ def _text_mime(mime):
51
+ return mime.startswith("text/") or mime in {"application/json", "application/xml", "application/yaml", "application/x-yaml", "application/javascript"}
52
+
53
+
54
+ def _content_matches(header, mime):
55
+ image = image_mime(header)
56
+ if mime in MIMES:
57
+ return image == mime
58
+ return mime in FILE_MIMES and image is None and (mime != "application/pdf" or header.startswith(b"%PDF-"))
59
+
60
+
61
+ def _verify(root, references, expected, limit, file_limit=0, file_mimes=()):
34
62
  root = Path(root) / "media-inputs"
35
63
  if root.is_symlink() or root.resolve() != root or not root.is_dir():
36
64
  raise MediaInputRefused("MEDIA_SCOPE_INVALID")
@@ -40,14 +68,17 @@ def _verify(root, references, expected, limit, file_limit=0):
40
68
  for item, identity in zip(references, expected):
41
69
  if (type(item) is not dict or set(item) != {"id", "path", "filename", "mimeType", "sha256", "size"}
42
70
  or not isinstance(identity, str) or not re.fullmatch(PREFIX + "[a-f0-9]{64}", identity)
43
- or item.get("id") != identity or not isinstance(item.get("mimeType"), str) or item["mimeType"] not in MIMES
71
+ or item.get("id") != identity or not isinstance(item.get("mimeType"), str) or item["mimeType"] not in (*MIMES, *file_mimes)
44
72
  or not isinstance(item.get("sha256"), str) or not re.fullmatch("[a-f0-9]{64}", item["sha256"])
45
73
  or type(item.get("size")) is not int or item["size"] < 1
46
- or not isinstance(item.get("filename"), str) or not item["filename"] or Path(item["filename"]).name != item["filename"]):
74
+ or not isinstance(item.get("filename"), str) or not item["filename"] or item["filename"] in {".", ".."}
75
+ or re.search(r"[\\/\x00-\x1f\x7f]", item["filename"])
76
+ or len(item["filename"].encode()) > (1024 if item["mimeType"] in MIMES else 180)):
47
77
  raise MediaInputRefused("MEDIA_MANIFEST_INVALID")
48
78
  if file_limit and item["size"] > file_limit:
49
79
  raise MediaInputRefused("MEDIA_SIZE_EXCEEDED")
50
- target = root / (identity[len(PREFIX):] + MIMES[item["mimeType"]])
80
+ suffix = MIMES.get(item["mimeType"], "_file_" + item["filename"])
81
+ target = root / (identity[len(PREFIX):] + suffix)
51
82
  if item.get("path") != str(target) or target.is_symlink():
52
83
  raise MediaInputRefused("MEDIA_PATH_INVALID")
53
84
  descriptor = None
@@ -57,6 +88,7 @@ def _verify(root, references, expected, limit, file_limit=0):
57
88
  if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size != item["size"]:
58
89
  raise MediaInputRefused("MEDIA_INPUT_CHANGED")
59
90
  digest, size, header = hashlib.sha256(), 0, b""
91
+ decoder = codecs.getincrementaldecoder("utf-8")() if _text_mime(item["mimeType"]) else None
60
92
  with os.fdopen(descriptor, "rb") as source:
61
93
  descriptor = None
62
94
  while chunk := source.read(64 * 1024):
@@ -64,11 +96,19 @@ def _verify(root, references, expected, limit, file_limit=0):
64
96
  if limit and total + size > limit:
65
97
  raise MediaInputRefused("MEDIA_SIZE_EXCEEDED")
66
98
  digest.update(chunk)
99
+ if decoder is not None:
100
+ if b"\0" in chunk:
101
+ raise MediaInputRefused("MEDIA_INPUT_CHANGED")
102
+ decoder.decode(chunk)
67
103
  if len(header) < 12:
68
104
  header += chunk[:12 - len(header)]
69
- if size != item["size"] or digest.hexdigest() != item["sha256"] or image_mime(header) != item["mimeType"]:
105
+ if decoder is not None:
106
+ decoder.decode(b"", final=True)
107
+ if size != item["size"] or digest.hexdigest() != item["sha256"] or not _content_matches(header, item["mimeType"]):
70
108
  raise MediaInputRefused("MEDIA_INPUT_CHANGED")
71
109
  total += size
110
+ except UnicodeError as error:
111
+ raise MediaInputRefused("MEDIA_INPUT_CHANGED") from error
72
112
  except OSError as error:
73
113
  raise MediaInputRefused("MEDIA_UNAVAILABLE") from error
74
114
  finally:
@@ -85,7 +125,8 @@ async def prepare(adapter, run, references, *, shared=False):
85
125
  return []
86
126
  policy = adapter.runtime.input_media_policy(**({"shared": True} if shared else {}))
87
127
  limit = policy["maxBytes"]
88
- return await asyncio.to_thread(_verify, adapter.data, references, tuple(run["attachments"]), limit, policy.get("maxFileBytes", 0))
128
+ return await asyncio.to_thread(_verify, adapter.data, references, tuple(run["attachments"]), limit,
129
+ policy.get("maxFileBytes", 0), policy.get("fileMimeTypes", ()))
89
130
 
90
131
 
91
132
  def _read_selected(root, path, expected):
@@ -127,13 +168,19 @@ async def verify_after_ingress(adapter, event, references):
127
168
  if event.media_urls or event.media_types:
128
169
  raise InputAdmissionUnconfirmed("MEDIA_INPUT_CHANGED", "after-media-ingress")
129
170
  return
171
+ flags = event.media_text_inlined
172
+ expected_flags = [None if item["mimeType"] in MIMES else False for item in references]
173
+ exact_flags = type(flags) is list and len(flags) == len(expected_flags) and all(
174
+ actual is expected for actual, expected in zip(flags, expected_flags))
130
175
  if (type(event.media_urls) is not list or type(event.media_types) is not list
131
176
  or tuple(event.media_urls) != tuple(item["path"] for item in references)
132
177
  or tuple(event.media_types) != tuple(item["mimeType"] for item in references)
133
- or event.media_text_inlined is not None and (type(event.media_text_inlined) is not list or any(value is not None for value in event.media_text_inlined))):
178
+ or not exact_flags and not (all(value is None for value in expected_flags) and flags in (None, []))):
134
179
  raise InputAdmissionUnconfirmed("MEDIA_INPUT_CHANGED", "after-media-ingress")
135
180
  try:
136
- await asyncio.to_thread(_verify, adapter.data, references, tuple(item["id"] for item in references), adapter.runtime.input_media_policy()["maxBytes"])
181
+ policy = adapter.runtime.input_media_policy()
182
+ await asyncio.to_thread(_verify, adapter.data, references, tuple(item["id"] for item in references),
183
+ policy["maxBytes"], policy.get("maxFileBytes", 0), policy.get("fileMimeTypes", ()))
137
184
  except MediaInputRefused as error:
138
185
  # 原始授权hook已经执行,不能把之后的拒绝说成没有任何宿主副作用。
139
186
  raise InputAdmissionUnconfirmed(error.code, "after-media-ingress") from error
@@ -0,0 +1,143 @@
1
+ """消息朗读端口:经固定版Hermes TTS合成单条正文,返回受控音频字段。
2
+
3
+ 只做本地语音合成:不提交模型请求、不创建消息/运行、不写历史、不投递平台消息。
4
+ 音频写入0700私有临时目录,读取后随目录删除;不长期缓存,不记录正文或路径。
5
+ """
6
+
7
+ import asyncio
8
+ import base64
9
+ import json
10
+ import os
11
+ import re
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ from . import compat_v0225
16
+
17
+
18
+ MAX_TEXT_LENGTH = 1200
19
+ MAX_AUDIO_BYTES = 2_500_000
20
+ CONFIG_TIMEOUT_SECONDS = 15
21
+ SYNTHESIS_TIMEOUT_SECONDS = 100
22
+ TEMP_PREFIX = "fridaynext-speech-"
23
+ _MIME_TYPES = {
24
+ "mp3": "audio/mpeg",
25
+ "wav": "audio/wav",
26
+ "ogg": "audio/ogg",
27
+ "opus": "audio/ogg",
28
+ "flac": "audio/flac",
29
+ "m4a": "audio/mp4",
30
+ "aac": "audio/aac",
31
+ "amr": "audio/amr",
32
+ }
33
+
34
+
35
+ class _SpeechFailure(Exception):
36
+ def __init__(self, code):
37
+ self.code = code
38
+ super().__init__(code)
39
+
40
+
41
+ def _token(value):
42
+ return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}", value) is not None
43
+
44
+
45
+ class MessageSpeechPort:
46
+ def __init__(self, adapter):
47
+ self.adapter = adapter
48
+
49
+ def _config_sync(self):
50
+ return compat_v0225.message_speech_config(self.adapter.profile)
51
+
52
+ async def config(self):
53
+ try:
54
+ value = await asyncio.wait_for(asyncio.to_thread(self._config_sync), CONFIG_TIMEOUT_SECONDS)
55
+ except Exception:
56
+ return {"error": "TTS_UNAVAILABLE"}
57
+ if not isinstance(value, dict):
58
+ return {"error": "TTS_UNAVAILABLE"}
59
+ limit = value.get("maxTextLength")
60
+ if value.get("available") is not True or type(limit) is not int or limit <= 0:
61
+ return {"error": "TTS_UNAVAILABLE"}
62
+ return {"maxTextLength": min(limit, MAX_TEXT_LENGTH)}
63
+
64
+ def _speak_sync(self, text):
65
+ try:
66
+ value = compat_v0225.message_speech_config(self.adapter.profile)
67
+ except Exception:
68
+ raise _SpeechFailure("TTS_UNAVAILABLE") from None
69
+ if not isinstance(value, dict):
70
+ raise _SpeechFailure("TTS_UNAVAILABLE")
71
+ limit = value.get("maxTextLength")
72
+ if value.get("available") is not True:
73
+ raise _SpeechFailure("TTS_UNAVAILABLE")
74
+ if type(limit) is not int or limit <= 0:
75
+ raise _SpeechFailure("TTS_UNAVAILABLE")
76
+ if len(text) > min(limit, MAX_TEXT_LENGTH):
77
+ raise _SpeechFailure("TTS_INPUT_TOO_LONG")
78
+ with tempfile.TemporaryDirectory(prefix=TEMP_PREFIX) as directory:
79
+ root = Path(directory).resolve()
80
+ os.chmod(root, 0o700)
81
+ output = root / "speech.mp3"
82
+ try:
83
+ raw = compat_v0225.message_speech_synthesize(self.adapter.profile, text, output)
84
+ except Exception as error:
85
+ if isinstance(error, RuntimeError) and str(error) == "TTS_UNAVAILABLE":
86
+ raise _SpeechFailure("TTS_UNAVAILABLE") from None
87
+ raise _SpeechFailure("TTS_FAILED") from None
88
+ try:
89
+ envelope = json.loads(raw)
90
+ except (TypeError, ValueError):
91
+ raise _SpeechFailure("TTS_FAILED") from None
92
+ if not isinstance(envelope, dict) or envelope.get("success") is not True:
93
+ raise _SpeechFailure("TTS_FAILED")
94
+ file_path = envelope.get("file_path")
95
+ if not isinstance(file_path, str) or not file_path:
96
+ raise _SpeechFailure("TTS_FAILED")
97
+ paths = envelope.get("file_paths")
98
+ if isinstance(paths, list) and len(paths) != 1:
99
+ # 正常单条正文不应分块;缺ffmpeg时Hermes会保留多个片段,不能只返回第一段冒充完整音频。
100
+ raise _SpeechFailure("TTS_FAILED")
101
+ audio = Path(file_path)
102
+ if audio.is_symlink() or audio.resolve().parent != root:
103
+ raise _SpeechFailure("TTS_FAILED")
104
+ suffix = audio.suffix.lower().lstrip(".")
105
+ mime_type = _MIME_TYPES.get(suffix)
106
+ if not mime_type:
107
+ raise _SpeechFailure("TTS_FAILED")
108
+ try:
109
+ size = audio.stat().st_size
110
+ except OSError:
111
+ raise _SpeechFailure("TTS_FAILED") from None
112
+ if size <= 0:
113
+ raise _SpeechFailure("TTS_FAILED")
114
+ if size > MAX_AUDIO_BYTES:
115
+ raise _SpeechFailure("TTS_AUDIO_TOO_LARGE")
116
+ try:
117
+ data = audio.read_bytes()
118
+ except OSError:
119
+ raise _SpeechFailure("TTS_FAILED") from None
120
+ if len(data) != size or not data:
121
+ raise _SpeechFailure("TTS_FAILED")
122
+ provider = envelope.get("provider") or value.get("provider")
123
+ if not _token(provider):
124
+ raise _SpeechFailure("TTS_FAILED")
125
+ return {
126
+ "audioBase64": base64.b64encode(data).decode("ascii"),
127
+ "provider": provider,
128
+ "outputFormat": suffix,
129
+ "mimeType": mime_type,
130
+ }
131
+
132
+ async def speak(self, text):
133
+ if not isinstance(text, str) or not text.strip():
134
+ return {"error": "TTS_INPUT_INVALID"}
135
+ text = text.strip()
136
+ if len(text) > MAX_TEXT_LENGTH:
137
+ return {"error": "TTS_INPUT_TOO_LONG"}
138
+ try:
139
+ return await asyncio.wait_for(asyncio.to_thread(self._speak_sync, text), SYNTHESIS_TIMEOUT_SECONDS)
140
+ except _SpeechFailure as error:
141
+ return {"error": error.code}
142
+ except Exception:
143
+ return {"error": "TTS_FAILED"}