Import ECS deployed relay source and historical patches (2026-10-27)
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
"""Hermes native tools backed by the authenticated user-token relay."""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
from .work_client import WorkClient, WorkError, AuthorizationRequired
|
||||
|
||||
INSTRUCTIONS = """海能Work平台能力已接入本机专用工具:work_authorization、work_calendar、work_contacts、work_api_request。
|
||||
涉及飞书/海能Work日历或文档时优先调用这些工具,勿使用manage_connections寻找公有云连接器,勿索要或搜索App Secret。
|
||||
用户token仅由本机安全存储和ECS换取,第一次需要本人打开授权链接。工具返回authorization_required时将链接完整提供给本人,不能声称已经创建。
|
||||
当前日期以work_authorization返回的local_time为准。创建日程必须确定带时区的起止时间和真实参会人open_id。
|
||||
姓名/工号须用work_contacts搜索核实,多个候选必须澄清,不能猜open_id。平台返回partial表示已创建但邀请未完成,勿再次创建。
|
||||
同一写操作的operation_id必须保持不变,网络异常不得换ID重试。日程创建成功、邀请提交成功、对方接受是不同状态。
|
||||
"""
|
||||
|
||||
_watching = set()
|
||||
_watch_lock = threading.Lock()
|
||||
|
||||
|
||||
def watch_authorization(directory):
|
||||
"""Claim within the server's 60-second result TTL, without keeping tokens in ECS."""
|
||||
name = str(directory)
|
||||
with _watch_lock:
|
||||
if name in _watching:
|
||||
return
|
||||
_watching.add(name)
|
||||
def poll():
|
||||
client = None
|
||||
try:
|
||||
client = WorkClient(directory, os.environ.get("HN_WORK_RELAY_URL", "https://10.77.76.13"))
|
||||
for _ in range(295):
|
||||
time.sleep(2)
|
||||
try:
|
||||
if client.pending.exists() and client.read(client.pending).get("deadline", 0) <= time.time():
|
||||
return
|
||||
if client.status().get("authorized"):
|
||||
return
|
||||
except Exception:
|
||||
# Another local consumer may hold the short token lock.
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
with _watch_lock:
|
||||
_watching.discard(name)
|
||||
threading.Thread(target=poll, daemon=True, name="work-user-auth-claim").start()
|
||||
|
||||
|
||||
def register(directory):
|
||||
from tools.registry import registry
|
||||
import toolsets
|
||||
definitions = [
|
||||
("work_authorization", "查询或发起本人海能Work用户授权,返回可点击链接和本机时间;不返回token。", {
|
||||
"type": "object", "properties": {}, "additionalProperties": False}),
|
||||
("work_calendar", "本人用户身份的日历:list/primary/list_events/get_event/create_event/invite。写操作operation_id需稳定,起止时间均带时区。", {
|
||||
"type": "object", "properties": {
|
||||
"action": {"type": "string", "enum": ["list", "primary", "list_events", "get_event", "create_event", "invite"]},
|
||||
"calendar_id": {"type": "string"}, "event_id": {"type": "string"},
|
||||
"summary": {"type": "string"}, "description": {"type": "string"},
|
||||
"start_iso": {"type": "string", "description": "ISO8601,例如2026-10-27T09:00:00+08:00"},
|
||||
"end_iso": {"type": "string"}, "attendee_open_ids": {"type": "array", "items": {"type": "string"}},
|
||||
"operation_id": {"type": "string", "description": "8-80位稳定操作ID,同一意图重试不能更换"},
|
||||
"params": {"type": "object"}}, "required": ["action"]}),
|
||||
("work_contacts", "使用本人user token搜索参会人;query可为姓名或工号,返回候选,不能未经核实猜ID。open_id可读取具体用户信息。", {
|
||||
"type": "object", "properties": {"query": {"type": "string"}, "open_id": {"type": "string"}}}),
|
||||
("work_api_request", "携本人user token代理受支持业务API(日历CRUD/邀请、通讯录查询、文档云盘知识库读取)。禁止认证接口,不支持的路径返回403。写操作必须operation_id。", {
|
||||
"type": "object", "properties": {"method": {"type": "string", "enum": ["GET", "POST", "PATCH", "DELETE"]},
|
||||
"path": {"type": "string"}, "params": {"type": "object"}, "body": {"type": "object"},
|
||||
"operation_id": {"type": "string"}}, "required": ["method", "path"]}),
|
||||
]
|
||||
|
||||
def handler_for(name):
|
||||
def handle(args, **kwargs):
|
||||
client = None
|
||||
try:
|
||||
client = WorkClient(directory, os.environ.get("HN_WORK_RELAY_URL", "https://10.77.76.13"))
|
||||
if name == "work_authorization":
|
||||
result = client.status()
|
||||
if not result.get("authorized"):
|
||||
watch_authorization(directory)
|
||||
elif name == "work_api_request":
|
||||
result = client.api(**args)
|
||||
elif name == "work_contacts":
|
||||
from urllib.parse import quote
|
||||
result = client.api("GET", "/open-apis/contact/v3/users/" + quote(args["open_id"], safe=""),
|
||||
{"user_id_type": "open_id"}) if args.get("open_id") else client.api(
|
||||
"GET", "/open-apis/search/v1/user", {"query": args.get("query", ""), "page_size": 20})
|
||||
else:
|
||||
result = calendar(client, args)
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
except AuthorizationRequired as error:
|
||||
watch_authorization(directory)
|
||||
return json.dumps({"status": "authorization_required", "authorization_url": error.url, "message": str(error)}, ensure_ascii=False)
|
||||
except (WorkError, ValueError, KeyError) as error:
|
||||
return json.dumps({"error": str(error)[:500], "status": "failed"}, ensure_ascii=False)
|
||||
except Exception as error:
|
||||
return json.dumps({"error": type(error).__name__ + ";操作状态未确认,未自动重试。"}, ensure_ascii=False)
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
return handle
|
||||
|
||||
for name, description, parameters in definitions:
|
||||
registry.register(name=name, toolset="hainuo_work", schema={"name": name, "description": description, "parameters": parameters},
|
||||
handler=handler_for(name), description=description)
|
||||
toolsets.TOOLSETS["hainuo_work"] = {"description": "海能Work本人用户授权及日历业务", "tools": [x[0] for x in definitions], "includes": []}
|
||||
# Present these four small schemas directly; otherwise Hermes defers custom
|
||||
# toolsets behind tool_search and can wrongly search a public-cloud connector.
|
||||
for name, _, _ in definitions:
|
||||
if name not in toolsets._HERMES_CORE_TOOLS:
|
||||
toolsets._HERMES_CORE_TOOLS.append(name)
|
||||
|
||||
|
||||
def calendar(client, args):
|
||||
from urllib.parse import quote
|
||||
action = args["action"]
|
||||
if action == "primary":
|
||||
return client.primary_calendar()
|
||||
if action == "list":
|
||||
return client.api("GET", "/open-apis/calendar/v4/calendars", args.get("params", {}))
|
||||
if action == "create_event":
|
||||
return client.create_event(**{k: v for k, v in args.items() if k != "action" and k != "params"})
|
||||
calendar_id = args.get("calendar_id")
|
||||
if not calendar_id:
|
||||
primary = client.primary_calendar()
|
||||
if primary.get("status") != "completed":
|
||||
return primary
|
||||
calendar_id = primary["calendar"]["calendar_id"]
|
||||
base = "/open-apis/calendar/v4/calendars/" + quote(calendar_id, safe="") + "/events"
|
||||
if action == "list_events":
|
||||
return client.api("GET", base, args.get("params", {}))
|
||||
base += "/" + quote(args["event_id"], safe="")
|
||||
if action == "get_event":
|
||||
return client.api("GET", base, {"user_id_type": "open_id"})
|
||||
if action == "invite":
|
||||
ids = args.get("attendee_open_ids", [])
|
||||
if not ids or any(not x.startswith("ou_") for x in ids):
|
||||
raise WorkError("需要已确认的参会人open_id。")
|
||||
return client.api("POST", base + "/attendees", {"user_id_type": "open_id"},
|
||||
{"attendees": [{"type": "user", "user_id": x} for x in ids], "need_notification": True}, args["operation_id"])
|
||||
raise WorkError("不支持的日历操作。")
|
||||
Reference in New Issue
Block a user