@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,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
@@ -1,9 +1,10 @@
1
1
  """按会话接续回放,逐事件分发所属运行;持久ACK后才推进游标。"""
2
2
 
3
3
  import asyncio
4
+ import copy
4
5
  from .history import content_parts, terminal_error
5
6
  from .canonical_control import NativeControlError
6
- from .stream_projection import StreamProjection, opaque_identity, tool_identity, bounded, public_metadata
7
+ from .stream_projection import StreamProjection, opaque_identity, tool_identity, bounded, result_metadata
7
8
 
8
9
 
9
10
  class StreamBridge:
@@ -131,6 +132,8 @@ class StreamBridge:
131
132
  if cursor and cursor.get("epoch") == epoch
132
133
  else 0
133
134
  )
135
+ staged, pending_cursor = [], None
136
+ shadow_records = {key: copy.deepcopy(value) for key, value in records.items()}
134
137
  for frame in replay["events"]:
135
138
  seq = frame.get("seq")
136
139
  if (
@@ -157,10 +160,19 @@ class StreamBridge:
157
160
  and frame.get("execution_generation") == owner.get("generation")
158
161
  )
159
162
  if owned:
160
- await self._consume(candidate, owner, frame, epoch)
163
+ await self._consume(shadow_records[candidate["run_id"]], owner, frame, epoch, staged)
161
164
  check()
162
- bindings.save_session_cursor(service, record["native_id"], {"epoch": epoch, "sequence": seq})
165
+ pending_cursor = {"epoch": epoch, "sequence": seq}
166
+ # 只提供有界并发,不在Python复制Kit的时间/字节策略;持久ACK前不落游标。
167
+ if len(staged) >= 32:
168
+ await self._commit_staged(staged, check)
169
+ bindings.save_session_cursor(service, record["native_id"], pending_cursor)
170
+ staged, pending_cursor = [], None
171
+ await self._commit_staged(staged, check)
172
+ if pending_cursor is not None:
173
+ bindings.save_session_cursor(service, record["native_id"], pending_cursor)
163
174
  for run_id, candidate in records.items():
175
+ candidate.update(bindings.read(run_id))
164
176
  if proofs[run_id].get("status") == "terminal":
165
177
  await self._result_fallback(candidate, proofs[run_id])
166
178
  await self._enrich_result(candidate, proofs[run_id])
@@ -168,7 +180,22 @@ class StreamBridge:
168
180
  record.update(bindings.read(record["run_id"]))
169
181
  return proof
170
182
 
171
- async def _consume(self, record, proof, frame, epoch):
183
+ async def _commit_staged(self, staged, check):
184
+ # 排空所有原调用再处理失败;部分已落盘的帧重放时由原source回执去重。
185
+ async def publish(record, source, updates):
186
+ check() # 每个协程真正启动时再核对,不能让后续在途帧投到新宿主。
187
+ return await self._publish(record, source, updates)
188
+
189
+ outcomes = await asyncio.gather(*(publish(record, source, updates)
190
+ for record, source, updates, _patch in staged), return_exceptions=True)
191
+ check()
192
+ # 只保存连续收到持久ACK的前缀,缺口后的帧继续用原source重放。
193
+ for (record, _source, _updates, patch), outcome in zip(staged, outcomes, strict=True):
194
+ if isinstance(outcome, BaseException):
195
+ raise outcome
196
+ self.adapter.bindings.patch(record, patch)
197
+
198
+ async def _consume(self, record, proof, frame, epoch, staged=None):
172
199
  seq = frame["seq"]
173
200
  saved = record.get("stream_cursor") or {}
174
201
  if saved.get("epoch") == epoch and saved.get("sequence", 0) >= seq:
@@ -202,14 +229,14 @@ class StreamBridge:
202
229
  ),
203
230
  "sequence": seq,
204
231
  }
205
- await self._publish(record, source, updates)
206
- self.adapter.bindings.patch(
207
- record,
208
- {
209
- "stream_state": projection.state,
210
- "stream_cursor": {"epoch": epoch, "sequence": seq},
211
- },
212
- )
232
+ patch = {"stream_state": projection.state, "stream_cursor": {"epoch": epoch, "sequence": seq}}
233
+ if staged is not None:
234
+ # 此处只推进本次读取的内存投影;失败后sync重新读取原持久记录。
235
+ staged.append((record, source, updates, copy.deepcopy(patch)))
236
+ record.update(patch)
237
+ else:
238
+ await self._publish(record, source, updates)
239
+ self.adapter.bindings.patch(record, patch)
213
240
 
214
241
  async def _enrich_result(self, record, proof):
215
242
  if record.get("stream_evidence_complete"):
@@ -269,6 +296,18 @@ class StreamBridge:
269
296
  record, {"tool_evidence": evidence, "stream_evidence_complete": True}
270
297
  )
271
298
 
299
+ async def publish_result_metadata(self, record, proof, result):
300
+ # 流检查与终态检查可能跨越完成边沿;纯meta补齐不受stream_completed限制。
301
+ metadata = result_metadata(result)
302
+ if not metadata:
303
+ return
304
+ source = {"id": opaque_identity(
305
+ record["profile"], self.adapter.service_id, record["run_id"], record["native_id"],
306
+ record["admission_id"], proof.get("authority_epoch"), proof.get("generation"),
307
+ "result-metadata-v1",
308
+ ), "sequence": 1}
309
+ await self._publish(record, source, [{"kind": "session", "data": metadata}])
310
+
272
311
  async def _snapshot_gap(self, record, proof, checkpoint):
273
312
  if record.get("stream_snapshot_checkpoint") == checkpoint:
274
313
  return
@@ -308,9 +347,17 @@ class StreamBridge:
308
347
  return
309
348
  previous = record.get("stream_state", {})
310
349
  complete = result.get("turn_trace_complete") is True
350
+ rows = set(result.get("history_rows", []))
351
+ reasoning = {message["_row_id"]: text for message in result.get("turn_messages", [])
352
+ if message.get("role") == "assistant" and message.get("_row_id") in rows
353
+ and isinstance(text := message.get("reasoning") or message.get("reasoning_content"), str) and text}
311
354
  projection = StreamProjection(record["run_id"], None if complete else previous)
312
- # 完整轨迹重建不能清掉已收到的思考;只有原持久行的真实快照才能替换它。
313
- projection.state["reasoning"] = previous.get("reasoning", "")
355
+ if not reasoning:
356
+ # 宿主未保存推理时沿用已经持久 ACK 的分段,不能以空快照删除已知内容。
357
+ received = StreamProjection(record["run_id"], previous)
358
+ for key in ("reasoning", "reasoning_segments", "reasoning_segment"):
359
+ if key in received.state:
360
+ projection.state[key] = received.state[key]
314
361
  updates = []
315
362
  if complete:
316
363
  projection.state["step_seen"] = previous.get("step_seen", False)
@@ -319,6 +366,22 @@ class StreamBridge:
319
366
  for key, value in previous.get("tools", {}).items()
320
367
  if value == "error"
321
368
  }
369
+ if reasoning:
370
+ # remove 后按原始消息次序重建;仅 replace 会让工具留在旧位置。
371
+ old_reasoning = StreamProjection(record["run_id"], previous).state["reasoning_segments"]
372
+ updates += [{"kind": "text", "id": identity, "channel": "reasoning", "operation": "remove"}
373
+ for identity in dict.fromkeys(["reasoning:" + record["run_id"],
374
+ *(row["id"] for row in old_reasoning),
375
+ *("reasoning:" + record["run_id"] + ":" + str(i)
376
+ for i in range(1, len(reasoning) + 1))])]
377
+ # 宿主可能已持久提交、但 ACK 尚未落进本地游标;原回执里的调用同样要清位。
378
+ tool_ids = dict.fromkeys([*previous.get("tools", {}),
379
+ *(tool_identity(record["run_id"], call["id"])
380
+ for message in result.get("turn_messages", [])
381
+ if message.get("_row_id") in rows and message.get("role") == "assistant"
382
+ for call in message.get("tool_calls") or [] if isinstance(call.get("id"), str))])
383
+ updates += [{"kind": "tool", "id": identity, "operation": "remove"}
384
+ for identity in tool_ids]
322
385
  for number in range(1, previous.get("commentary_count", 0) + 1):
323
386
  updates.append(
324
387
  {
@@ -336,17 +399,15 @@ class StreamBridge:
336
399
  "operation": "remove",
337
400
  }
338
401
  )
339
- rows = set(result.get("history_rows", []))
340
- reasoning = [text for message in result.get("turn_messages", [])
341
- if message.get("role") == "assistant" and message.get("_row_id") in rows
342
- and isinstance(text := message.get("reasoning") or message.get("reasoning_content"), str) and text]
343
- if complete and reasoning:
344
- updates += projection.apply("reasoning.complete", {"text": "\n\n".join(reasoning)})
345
402
  arguments = {}
346
403
  for message in result.get("turn_messages", []):
347
404
  if message.get("_row_id") not in rows:
348
405
  continue
349
406
  if message.get("role") == "assistant":
407
+ if complete and message.get("_row_id") in reasoning:
408
+ updates += projection.apply("reasoning.complete", {
409
+ "text": reasoning[message["_row_id"]], "message_id": message["_row_id"],
410
+ })
350
411
  if complete and message.get("_row_id") != result.get("final_row_id"):
351
412
  text, _ = content_parts(message.get("content", message.get("text")))
352
413
  if text:
@@ -393,11 +454,7 @@ class StreamBridge:
393
454
  "response_reused": result.get("response_reused"),
394
455
  },
395
456
  )
396
- metadata = public_metadata({"usage": {
397
- "model": result.get("model"), "total": result.get("total_tokens"),
398
- "context_used": result.get("last_prompt_tokens"), "context_max": result.get("context_length"),
399
- "context_source": result.get("context_source"), "context_estimated": result.get("context_estimated"),
400
- }})
457
+ metadata = result_metadata(result)
401
458
  if metadata:
402
459
  updates.append({"kind": "session", "data": metadata})
403
460
  updates.append({"kind": "activity", "id": "replay-gap:" + record["run_id"], "operation": "remove"})
@@ -409,7 +466,7 @@ class StreamBridge:
409
466
  record["admission_id"],
410
467
  proof.get("authority_epoch"),
411
468
  proof.get("generation"),
412
- "result-v2",
469
+ "result-v3",
413
470
  ),
414
471
  "sequence": 1,
415
472
  }
@@ -48,6 +48,15 @@ def public_metadata(payload):
48
48
  return result
49
49
 
50
50
 
51
+ def result_metadata(result):
52
+ """只转换同一已校验回执的测量值,与流式完成共用缺测及数值规则。"""
53
+ return public_metadata({"usage": {
54
+ "model": result.get("model"), "total": result.get("total_tokens"),
55
+ "context_used": result.get("last_prompt_tokens"), "context_max": result.get("context_length"),
56
+ "context_source": result.get("context_source"), "context_estimated": result.get("context_estimated"),
57
+ }})
58
+
59
+
51
60
  class StreamProjection:
52
61
  def __init__(self, run_id, state=None):
53
62
  self.run_id = run_id
@@ -56,6 +65,13 @@ class StreamProjection:
56
65
  self.state.setdefault("commentary_count", 0)
57
66
  self.state.setdefault("tools", {})
58
67
  self.state.setdefault("reasoning", "")
68
+ if "reasoning_segments" not in self.state:
69
+ # 老游标只有整轮合并文本,先保留原 ID;完整原始回执到达后才重建顺序。
70
+ self.state["reasoning_segments"] = ([{
71
+ "id": "reasoning:" + run_id,
72
+ "source": self.state.get("reasoning_segment", [None, None]),
73
+ "text": self.state["reasoning"],
74
+ }] if self.state["reasoning"] else [])
59
75
  # 旧游标仅存answer时继续同一segment;不把重开后的首个delta当新正文。
60
76
  self.media_display = MediaStreamDisplay(self.state.setdefault("media_display", {"raw": self.state["answer"]} if self.state["answer"] else {}))
61
77
 
@@ -146,17 +162,25 @@ class StreamProjection:
146
162
  text = payload.get("text")
147
163
  if isinstance(text, str):
148
164
  # thinking.delta是等待文案,reasoning.available仅为截短预览,均不作推理正文。
149
- segment = [payload.get("turn_id"), payload.get("iteration")]
150
- boundary = "\n\n" if self.state["reasoning"] and self.state.get("reasoning_segment") not in (None, segment) else ""
151
- self.state["reasoning"] = text if kind == "reasoning.complete" else self.state["reasoning"] + boundary + text
152
- self.state["reasoning_segment"] = segment
165
+ source = (["message", payload["message_id"]] if "message_id" in payload
166
+ else [payload.get("turn_id"), payload.get("iteration")])
167
+ segments = self.state["reasoning_segments"]
168
+ segment = next((row for row in segments if row["source"] == source), None)
169
+ if segment is None:
170
+ segment = {"id": "reasoning:" + self.run_id + ":" + str(len(segments) + 1),
171
+ "source": source, "text": ""}
172
+ segments.append(segment)
173
+ segment["text"] = text if kind == "reasoning.complete" else segment["text"] + text
174
+ # 汇总只用于旧缓存兼容;canonical 每段使用独立 ID,同段增量原位更新。
175
+ self.state["reasoning"] = "\n\n".join(row["text"] for row in segments)
176
+ self.state["reasoning_segment"] = source
153
177
  updates = [
154
178
  {
155
179
  "kind": "text",
156
- "id": "reasoning:" + self.run_id,
180
+ "id": segment["id"],
157
181
  "channel": "reasoning",
158
182
  "operation": "replace",
159
- "text": self.state["reasoning"],
183
+ "text": segment["text"],
160
184
  }
161
185
  ]
162
186
  elif kind in ("tool.start", "tool.complete"):
@@ -0,0 +1,228 @@
1
+ """公开子任务观察的私有持久回执;只记录宿主事实,不启动/恢复任何Agent执行。"""
2
+ import asyncio
3
+ import copy
4
+ import json
5
+ import logging
6
+ import threading
7
+ from .state import private_json
8
+ from .stream_projection import StreamProjection, opaque_identity
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ def outcome(status):
14
+ if status in ("completed", "success", "succeeded"):
15
+ return "completed", "ok"
16
+ if status in ("interrupted", "cancelled", "canceled"):
17
+ return "cancelled", "aborted"
18
+ if status in ("timeout", "timed_out"):
19
+ return "failed", "timeout"
20
+ if status in ("failed", "error"):
21
+ return "failed", "error"
22
+ return "reconciling", "unknown"
23
+
24
+
25
+ class SubagentObserver:
26
+ def __init__(self, adapter):
27
+ self.adapter = adapter
28
+ self.folder = adapter.data / "subagent-observations"
29
+ self.folder.mkdir(parents=True, exist_ok=True, mode=0o700)
30
+ self.lock = threading.RLock()
31
+ self.records = {}
32
+ self.tasks = {}
33
+ self.closed = False
34
+ for file in self.folder.glob("*.json"):
35
+ record = json.loads(file.read_text())
36
+ if record.get("version") == 1 and record.get("scope", {}).get("profile") == str(adapter.profile):
37
+ entries = self._events(record)
38
+ record["sequence"] = max(record.get("sequence", 0), entries[-1]["sequence"] if entries else 0)
39
+ for entry in entries:
40
+ if entry["kind"] in ("stop", "unknown"):
41
+ record["phase"], record["outcome"] = outcome(entry["payload"].get("child_status"))
42
+ self.records[record["native_id"]] = record
43
+
44
+ def _file(self, record, suffix=".json"):
45
+ return self.folder / (opaque_identity(record["scope"], record["native_id"]) + suffix)
46
+
47
+ def _append(self, record, kind, payload):
48
+ sequence = record.get("sequence", 0) + 1
49
+ entry = {"sequence": sequence, "kind": kind, "payload": payload}
50
+ # 观察先落盘再投递;丢ACK后沿原source/sequence重放,不换号或重跑输入。
51
+ folder = self._file(record, ".events")
52
+ folder.mkdir(parents=True, exist_ok=True, mode=0o700)
53
+ private_json(folder / (str(sequence).zfill(16) + ".json"), entry)
54
+ record["sequence"] = sequence
55
+ if kind in ("stop", "unknown"):
56
+ record["phase"], record["outcome"] = outcome(payload.get("child_status"))
57
+ private_json(self._file(record), record)
58
+
59
+ def _events(self, record):
60
+ entries = [json.loads(file.read_text()) for file in sorted(self._file(record, ".events").glob("*.json"))]
61
+ entries = [row for row in entries if row.get("sequence", 0) > record.get("ack", 0)]
62
+ if any(row.get("sequence") != record.get("ack", 0) + index for index, row in enumerate(entries, 1)):
63
+ raise ValueError("SUBAGENT_OBSERVATION_GAP")
64
+ return entries
65
+
66
+ def observe(self, kind, event):
67
+ adapter = self.adapter
68
+ locator = getattr(adapter.runtime, "locator", None)
69
+ if self.closed or locator is None or adapter.host is None or not adapter.service_id:
70
+ return False
71
+ with self.lock:
72
+ if kind == "start":
73
+ native, child_id = event.get("child_session_id"), event.get("child_subagent_id")
74
+ parent_id = event.get("parent_session_id")
75
+ if not all(isinstance(v, str) and v for v in (native, child_id, parent_id)):
76
+ return False
77
+ existing = self.records.get(native)
78
+ if existing is not None:
79
+ # 原child身份已绑定;重复开始不会改绑或复活。
80
+ return False
81
+ parent = self.records.get(parent_id)
82
+ scope = copy.deepcopy(parent["scope"]) if parent else locator.subagent_owner(parent_id)
83
+ if not scope or not locator.subagent_context_matches(scope):
84
+ return False
85
+ if parent and parent.get("child_id") != event.get("parent_subagent_id"):
86
+ return False
87
+ identity = opaque_identity(scope, native, child_id)
88
+ record = {"version": 1, "scope": scope, "native_id": native, "child_id": child_id,
89
+ "parent_native_id": parent_id, "run_id": "subagent:" + identity,
90
+ "session_key": "subagent:" + opaque_identity(scope["profile"], native),
91
+ "parent_run_id": parent["run_id"] if parent else scope["root_run_id"],
92
+ "depth": parent["depth"] + 1 if parent else 1,
93
+ "label": str(event.get("child_goal") or "")[:16000], "phase": "running", "ack": 0}
94
+ self.records[native] = record
95
+ self._append(record, "start", {})
96
+ else:
97
+ native = event.get("child_session_id") if kind == "stop" else event.get("session_id")
98
+ record = self.records.get(native)
99
+ if (not record or record.get("phase") != "running" or not locator.subagent_context_matches(record["scope"])):
100
+ return False
101
+ if kind == "stop" and event.get("parent_session_id") != record["parent_native_id"]:
102
+ return False
103
+ payload = self._payload(kind, event)
104
+ if payload is None:
105
+ return False
106
+ self._append(record, kind, payload)
107
+ loop = adapter.owner_loop
108
+ if loop is not None and not loop.is_closed():
109
+ loop.call_soon_threadsafe(self._schedule, native)
110
+ return True
111
+
112
+ @staticmethod
113
+ def _payload(kind, event):
114
+ if kind == "stream.delta":
115
+ if event.get("kind") not in ("text", "reasoning") or not isinstance(event.get("delta"), str):
116
+ return None
117
+ return {k: event[k] for k in ("kind", "delta", "turn_id", "iteration") if k in event}
118
+ if kind == "stream.end":
119
+ return {"text": event["final_text"]} if event.get("finished") is True and isinstance(event.get("final_text"), str) else None
120
+ if kind in ("tool.start", "tool.complete"):
121
+ if not isinstance(event.get("tool_call_id"), str) or not event["tool_call_id"]:
122
+ return None
123
+ return {"tool_call_id": event["tool_call_id"], "name": event.get("tool_name"), "args": event.get("args", {}),
124
+ **({"result": event.get("result"), "is_error": event.get("status") not in ("ok", None)} if kind == "tool.complete" else {})}
125
+ if kind == "stop":
126
+ return {"child_status": event.get("child_status"), "text": event.get("child_summary")}
127
+ return None
128
+
129
+ def _schedule(self, native):
130
+ current = self.tasks.get(native)
131
+ if self.closed or (current is not None and not current.done()):
132
+ return
133
+ task = self.tasks[native] = asyncio.create_task(self._pump(native))
134
+ task.add_done_callback(lambda done: self.tasks.pop(native, None) if self.tasks.get(native) is done else None)
135
+
136
+ async def _pump(self, native):
137
+ adapter = self.adapter
138
+ host, service = adapter.host, adapter.service_id
139
+ while not self.closed and adapter.host is host and adapter.service_id == service:
140
+ try:
141
+ with self.lock:
142
+ record = copy.deepcopy(self.records[native])
143
+ if record["scope"]["service"] != service:
144
+ return
145
+ entries = self._events(record)
146
+ projection = StreamProjection(record["run_id"], record.get("projection_state"))
147
+ phase, result = record.get("acked_phase", "running"), record.get("acked_outcome")
148
+ for entry in entries:
149
+ kind, payload = entry["kind"], entry["payload"]
150
+ updates = []
151
+ if kind == "stream.delta":
152
+ updates = projection.apply("reasoning.delta" if payload["kind"] == "reasoning" else "message.delta",
153
+ {**payload, "text": payload["delta"]})
154
+ elif kind == "stream.end":
155
+ updates = projection.apply("message.complete", payload)
156
+ elif kind.startswith("tool."):
157
+ updates = projection.apply(kind, payload)
158
+ elif kind == "stop":
159
+ if isinstance(payload.get("text"), str):
160
+ updates = projection.apply("message.complete", {"text": payload["text"]})
161
+ phase, result = outcome(payload.get("child_status"))
162
+ elif kind == "unknown":
163
+ phase, result = "reconciling", "unknown"
164
+ if entry["sequence"] <= record.get("ack", 0):
165
+ continue
166
+ child = {"runId": record["run_id"], "sessionKey": record["session_key"],
167
+ "parentRunId": record["parent_run_id"], "depth": record["depth"],
168
+ "label": record["label"], "phase": phase, **({"outcome": result} if result else {})}
169
+ reply = await host.publish({"serviceInstanceId": service, "runId": record["scope"]["root_run_id"],
170
+ "child": child, "source": {"id": opaque_identity(record["scope"], native), "sequence": entry["sequence"]}, "updates": updates})
171
+ if self.closed or adapter.host is not host or adapter.service_id != service or reply.get("durable") is not True:
172
+ raise RuntimeError("SUBAGENT_ACK_NOT_DURABLE")
173
+ with self.lock:
174
+ current = self.records[native]
175
+ current["ack"] = entry["sequence"]
176
+ current["projection_state"] = projection.state
177
+ current["acked_phase"], current["acked_outcome"] = phase, result
178
+ private_json(self._file(current), current)
179
+ # Kit已拥有完整规范事实;本地只保留后续增量所需状态及未确认观察。
180
+ (self._file(current, ".events") / (str(entry["sequence"]).zfill(16) + ".json")).unlink(missing_ok=True)
181
+ with self.lock:
182
+ if self.records[native].get("ack", 0) >= self.records[native].get("sequence", 0):
183
+ return
184
+ except asyncio.CancelledError:
185
+ raise
186
+ except Exception as error:
187
+ # 保留源事实等待同身份重试;通信失败不等于子任务执行失败。
188
+ logger.debug("hermes.subagent.delivery_pending type=%s", type(error).__name__)
189
+ await asyncio.sleep(0.25)
190
+
191
+ def restore(self):
192
+ locator = getattr(self.adapter.runtime, "locator", None)
193
+ if locator is None:
194
+ return
195
+ epoch = locator.authority().epoch
196
+ with self.lock:
197
+ for native, record in self.records.items():
198
+ if record["scope"]["service"] != self.adapter.service_id:
199
+ continue
200
+ if record["scope"]["authority_epoch"] != epoch and record["phase"] == "running":
201
+ self._append(record, "unknown", {})
202
+ self._schedule(native)
203
+
204
+ def rebind(self):
205
+ # 共享worker换代不重建宿主Profile;取消旧投递等待,再以原source接续。
206
+ for task in self.tasks.values():
207
+ task.cancel()
208
+ self.tasks.clear()
209
+ self.restore()
210
+
211
+ def inspect(self, run_id):
212
+ with self.lock:
213
+ found = [r for r in self.records.values() if r["run_id"] == run_id and r["scope"]["service"] == self.adapter.service_id]
214
+ if len(found) != 1:
215
+ return {"state": "unknown", "reason": "SUBAGENT_OBSERVATION_UNAVAILABLE"}
216
+ record = found[0]
217
+ # 终态正文尚未取得Kit持久ACK时,不让公共恢复器抢先封口并拒绝原结果。
218
+ phase = record["phase"] if record.get("ack", 0) >= record.get("sequence", 0) else "running"
219
+ return {"state": "unknown" if phase == "reconciling" else phase,
220
+ **({"reason": "HOST_EXECUTION_UNKNOWN"} if phase == "reconciling" else {})}
221
+
222
+ async def close(self):
223
+ self.closed = True
224
+ tasks = list(self.tasks.values())
225
+ for task in tasks:
226
+ task.cancel()
227
+ await asyncio.gather(*tasks, return_exceptions=True)
228
+ self.tasks.clear()