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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +2 -2
  2. package/install-config.js +67 -0
  3. package/install-runtime.js +17 -5
  4. package/install.js +6 -4
  5. package/package.json +2 -1
  6. package/plugin/README.md +2 -2
  7. package/plugin/fridaynext_plugin/__init__.py +10 -0
  8. package/plugin/fridaynext_plugin/adapter.py +221 -12
  9. package/plugin/fridaynext_plugin/agent_management.py +158 -0
  10. package/plugin/fridaynext_plugin/canonical_control.py +12 -4
  11. package/plugin/fridaynext_plugin/compat_v0225.py +1174 -4
  12. package/plugin/fridaynext_plugin/continuations.py +271 -0
  13. package/plugin/fridaynext_plugin/device-tools-v1.json +302 -0
  14. package/plugin/fridaynext_plugin/device_tools.py +144 -0
  15. package/plugin/fridaynext_plugin/history.py +25 -3
  16. package/plugin/fridaynext_plugin/host.py +7 -4
  17. package/plugin/fridaynext_plugin/media_input.py +56 -9
  18. package/plugin/fridaynext_plugin/multi_agent.py +221 -0
  19. package/plugin/fridaynext_plugin/reply_context.py +39 -0
  20. package/plugin/fridaynext_plugin/runtime_port.py +23 -1
  21. package/plugin/fridaynext_plugin/scheduled_tasks.py +229 -0
  22. package/plugin/fridaynext_plugin/settings.py +7 -3
  23. package/plugin/fridaynext_plugin/slash_commands.py +163 -0
  24. package/plugin/fridaynext_plugin/stream_bridge.py +83 -26
  25. package/plugin/fridaynext_plugin/stream_projection.py +30 -6
  26. package/plugin/fridaynext_plugin/subagents.py +228 -0
  27. package/plugin/plugin.yaml +11 -0
  28. package/plugin/runtime/dist/commands-routes.js +94 -0
  29. package/plugin/runtime/dist/device-tools-v1.json +302 -0
  30. package/plugin/runtime/dist/hosted-backend.js +250 -25
  31. package/plugin/runtime/dist/hosted-continuations.js +41 -0
  32. package/plugin/runtime/dist/hosted-device-tools.js +82 -0
  33. package/plugin/runtime/dist/hosted-media.js +54 -13
  34. package/plugin/runtime/dist/hosted-stream.js +124 -14
  35. package/plugin/runtime/dist/hosted-subagents.js +78 -0
  36. package/plugin/runtime/dist/platform-service.js +4 -0
  37. package/plugin/runtime/dist/plugin-control.js +10 -6
  38. package/plugin/runtime/dist/scheduled-routes.js +63 -0
  39. package/plugin/runtime/dist/service-host.js +27 -3
  40. package/plugin/runtime/dist/tool-presentation.js +399 -0
  41. package/plugin/runtime/node_modules/.package-lock.json +6 -6
  42. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/API.md +125 -5
  43. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/README.md +21 -1
  44. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.d.ts +1 -0
  45. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/history.js +3 -0
  46. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.d.ts +136 -0
  47. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/operations.js +105 -0
  48. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.d.ts +3 -0
  49. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/settings-schema.js +45 -0
  50. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.d.ts +10 -0
  51. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/tool-presentation.js +2 -0
  52. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.d.ts +27 -2
  53. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/types.js +1 -0
  54. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.d.ts +56 -0
  55. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/contract/work-context.js +60 -0
  56. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/device-request/pending-store.js +3 -3
  57. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.d.ts +5 -0
  58. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/index.js +5 -0
  59. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.d.ts +26 -0
  60. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/canonical-update-batcher.js +112 -0
  61. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.d.ts +4 -1
  62. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/channel-kernel.js +30 -5
  63. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.d.ts +18 -1
  64. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/durable-run-store.js +187 -51
  65. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.d.ts +1 -0
  66. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/runner.js +52 -2
  67. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.d.ts +13 -0
  68. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/runtime/work-context.js +73 -0
  69. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/service/channel-service.js +1 -1
  70. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.d.ts +47 -0
  71. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/command-lifecycle.js +184 -0
  72. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.d.ts +1 -1
  73. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/controls.js +11 -0
  74. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/messages.js +12 -6
  75. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.d.ts +13 -0
  76. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/operations.js +336 -0
  77. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.d.ts +1 -0
  78. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/runtime.js +52 -10
  79. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/session-settings.js +38 -6
  80. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/dist/transport/sessions.js +8 -8
  81. package/plugin/runtime/node_modules/@syengup/fridaynext-channel-kit/package.json +6 -7
  82. package/plugin/runtime/node_modules/tslib/README.md +3 -8
  83. package/plugin/runtime/node_modules/tslib/package.json +1 -1
  84. package/plugin/runtime/node_modules/tslib/tslib.d.ts +4 -2
  85. package/plugin/runtime/node_modules/tslib/tslib.es6.js +10 -1
  86. package/plugin/runtime/node_modules/tslib/tslib.es6.mjs +10 -1
  87. package/plugin/runtime/node_modules/tslib/tslib.js +10 -1
  88. package/plugin/runtime/package-lock.json +7 -7
  89. package/plugin/runtime/package.json +1 -1
  90. package/plugin/tools.py +3 -0
@@ -1,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()
@@ -1,9 +1,20 @@
1
1
  name: fridaynext
2
2
  version: 0.2.0-beta.1
3
3
  kind: platform
4
+ provides_tools:
5
+ - fridaynext_location_query
6
+ - fridaynext_health_query
7
+ - fridaynext_health_log
8
+ - fridaynext_calendar_query
9
+ - fridaynext_calendar_log
4
10
  provides_hooks:
5
11
  - api_request_error
6
12
  - on_stream_delta
13
+ - subagent_start
14
+ - subagent_stop
15
+ - on_stream_end
16
+ - post_api_request
17
+ - post_tool_call
7
18
  requires_hermes: "==0.22.5"
8
19
  description: FridayNext 原生客户端平台,复用通用 Channel Kit
9
20
  author: SyengUp
@@ -0,0 +1,94 @@
1
+ const receiptKind = "slash-command-v1";
2
+ const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
3
+ const identity = (value) => typeof value === "string" && !!value.trim() && value.length <= 1024;
4
+ // 版本化中立命令操作的所属适配器实现:复用Kit回执,不创建第二套队列或重放宿主副作用。
5
+ export function createCommandRoutes(options) {
6
+ const inFlight = new Map();
7
+ return async (req, res) => {
8
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
9
+ if (path !== "/friday-next/commands/v1/execute")
10
+ return false;
11
+ const reply = (status, body) => {
12
+ res.statusCode = status;
13
+ res.setHeader("content-type", "application/json; charset=utf-8");
14
+ res.setHeader("cache-control", "no-store");
15
+ res.end(JSON.stringify(body));
16
+ return true;
17
+ };
18
+ if (!options.authenticate(req))
19
+ return reply(401, { code: "UNAUTHORIZED" });
20
+ if (!options.available())
21
+ return reply(404, { code: "UNSUPPORTED_CAPABILITY" });
22
+ if (req.method !== "POST")
23
+ return reply(405, { code: "METHOD_NOT_ALLOWED" });
24
+ let body;
25
+ try {
26
+ const chunks = [];
27
+ let size = 0;
28
+ for await (const chunk of req) {
29
+ const bytes = Buffer.from(chunk);
30
+ size += bytes.length;
31
+ if (size > 128 * 1024)
32
+ throw Error();
33
+ chunks.push(bytes);
34
+ }
35
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
36
+ if (!object(parsed))
37
+ throw Error();
38
+ body = parsed;
39
+ }
40
+ catch {
41
+ return reply(400, { code: "INVALID_COMMAND_INPUT" });
42
+ }
43
+ const base = { version: 1, serverInstanceId: options.store.serverInstanceId, operationId: "commands.execute", commandId: body.commandId };
44
+ if (body.version !== 1)
45
+ return reply(426, { code: "UNSUPPORTED_COMMAND_VERSION" });
46
+ if (body.expectedServerInstanceId !== options.store.serverInstanceId)
47
+ return reply(409, { code: "SERVICE_IDENTITY_CHANGED" });
48
+ if (Object.keys(body).some(key => !["version", "expectedServerInstanceId", "agentId", "sessionKey", "deviceId", "commandId", "input"].includes(key))
49
+ || !identity(body.agentId) || !identity(body.commandId) || !identity(body.deviceId)
50
+ || (body.sessionKey !== undefined && !identity(body.sessionKey))
51
+ || body.deviceId !== req.headers["x-fridaynext-device-id"]
52
+ || !object(body.input) || Object.keys(body.input).length !== 1 || typeof body.input.text !== "string"
53
+ || !body.input.text.startsWith("/") || body.input.text.length > 32768)
54
+ return reply(400, { code: "INVALID_COMMAND_INPUT" });
55
+ const key = JSON.stringify([body.deviceId, body.commandId]);
56
+ const payload = body;
57
+ const send = (result) => reply(result.status === "applied" ? 200 : result.status === "conflict" ? 409 : 503, { ...base, ...result });
58
+ const status = options.store.commandReceiptStatus(receiptKind, key, payload);
59
+ if (status === "conflict")
60
+ return send({ status: "conflict", code: "COMMAND_ID_CONFLICT" });
61
+ if (status === "replayed")
62
+ return send(options.store.commandReceipt(receiptKind, key).response);
63
+ const previous = inFlight.get(key);
64
+ if (previous)
65
+ return send(await previous);
66
+ if (status === "prepared")
67
+ return send({ status: "unknown", code: "COMMAND_EXECUTION_UNCONFIRMED" });
68
+ // prepare先落盘;任何IPC/宿主响应丢失都保留原ID为unknown,重试只查此回执。
69
+ options.store.prepareCommandReceipt(receiptKind, key, payload);
70
+ const operation = (async () => {
71
+ try {
72
+ const value = await options.backend.slashCommand({ serviceInstanceId: options.store.serverInstanceId,
73
+ agentId: body.agentId, sessionKey: body.sessionKey, commandId: body.commandId }, body.input);
74
+ const valid = object(value) && ["result", "run", "compaction", "local"].includes(String(value.kind))
75
+ && (["run", "local"].includes(String(value.kind)) ? value.text === body.input.text : typeof value.text === "string");
76
+ if (!valid)
77
+ return { status: "unknown", code: "COMMAND_RESULT_INVALID" };
78
+ const result = { status: "applied", value };
79
+ options.store.completeCommandReceipt(receiptKind, key, payload, result);
80
+ return result;
81
+ }
82
+ catch {
83
+ return { status: "unknown", code: "COMMAND_EXECUTION_UNCONFIRMED" };
84
+ }
85
+ })();
86
+ inFlight.set(key, operation);
87
+ try {
88
+ return send(await operation);
89
+ }
90
+ finally {
91
+ inFlight.delete(key);
92
+ }
93
+ };
94
+ }