feat: update all alg
更新所有算法
This commit is contained in:
53
dev/demo_agent_flow.py
Normal file
53
dev/demo_agent_flow.py
Normal file
@ -0,0 +1,53 @@
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, __import__('pathlib').Path(__file__).resolve().parents[1].as_posix())
|
||||
|
||||
from larkx.agent import AgentDispatcher, get_backend
|
||||
from larkx.agent.dispatcher import build_xml_message
|
||||
|
||||
msg1 = {
|
||||
'msg_id': '7666999999999999001', 'msg_type': 4, 'msg_type_name': 'TEXT',
|
||||
'from_id': '7314999000000000001', 'chat_id': '7627124577683934408',
|
||||
'chat_type': 1, 'chat_type_name': 'P2P', 'scope': 'chat', 'anchor': '',
|
||||
'at_me': False, 'root_id': '', 'parent_id': '', 'cid': '', 'position': 1,
|
||||
'create_time': 1785000000,
|
||||
'content': '在吗?帮我确认一下现在的消息链路是不是通的,顺便说一句你好',
|
||||
'content_data': None,
|
||||
}
|
||||
|
||||
msg2 = dict(msg1, msg_id='7666999999999999002',
|
||||
content='[系统消息] type=605 群公告已更新')
|
||||
|
||||
|
||||
class SpyBackend:
|
||||
def __init__(self, inner):
|
||||
self.inner = inner
|
||||
self.prompts = []
|
||||
|
||||
async def run(self, session_key, prompt):
|
||||
self.prompts.append(prompt)
|
||||
return await self.inner.run(session_key, prompt)
|
||||
|
||||
|
||||
async def main():
|
||||
backend = SpyBackend(get_backend())
|
||||
|
||||
async def reply_fn(chat_id, text, root_id=None):
|
||||
print('>>> reply_fn 被调用(新模型下不该发生):', text)
|
||||
|
||||
disp = AgentDispatcher(backend, reply_fn)
|
||||
|
||||
print('=' * 20, '案例 1: 需要回复的消息', '=' * 20)
|
||||
print(build_xml_message(msg1))
|
||||
print('-' * 60)
|
||||
await disp.handle_message('demo:2', msg1)
|
||||
|
||||
print()
|
||||
print('=' * 20, '案例 2: 系统通知(不该回复)', '=' * 20)
|
||||
print(build_xml_message(msg2))
|
||||
print('-' * 60)
|
||||
await disp.handle_message('demo:2', msg2)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
52
dev/demo_pipe_flow.py
Normal file
52
dev/demo_pipe_flow.py
Normal file
@ -0,0 +1,52 @@
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, __import__('pathlib').Path(__file__).resolve().parents[1].as_posix())
|
||||
|
||||
from larkx.agent import AgentDispatcher, get_backend
|
||||
|
||||
msg1 = {
|
||||
'msg_id': '7666600000000000001', 'msg_type': 4, 'msg_type_name': 'TEXT',
|
||||
'from_id': '7314999000000000001', 'chat_id': '7627124577683934408',
|
||||
'chat_type': 1, 'chat_type_name': 'P2P', 'scope': 'chat', 'anchor': '',
|
||||
'at_me': False, 'root_id': '', 'parent_id': '', 'cid': '', 'position': 1,
|
||||
'create_time': 1785003200,
|
||||
'content': '在吗?帮我验证下数字人链路:收到这条后回我一句"链路正常"就行',
|
||||
'_chat_name': 'Cato的智能伙伴', '_sender_name': 'Cato的智能伙伴',
|
||||
}
|
||||
|
||||
msg2 = dict(msg1, msg_id='7666600000000000002',
|
||||
content='周末愉快呀~ 好好休息😄')
|
||||
|
||||
|
||||
class SpyBackend:
|
||||
def __init__(self, inner):
|
||||
self.inner = inner
|
||||
self.prompts = []
|
||||
|
||||
async def run(self, session_key, prompt, **kwargs):
|
||||
self.prompts.append(prompt)
|
||||
return await self.inner.run(session_key, prompt, **kwargs)
|
||||
|
||||
|
||||
async def main():
|
||||
backend = SpyBackend(get_backend())
|
||||
|
||||
async def reply_fn(chat_id, text, root_id=None):
|
||||
print('>>> reply_fn 被调用(新模型下不该发生):', text)
|
||||
|
||||
disp = AgentDispatcher(backend, reply_fn)
|
||||
|
||||
print('=' * 20, '案例 1: 明确要求回复', '=' * 20)
|
||||
await disp.handle_message('demo:final', msg1)
|
||||
|
||||
print()
|
||||
print('=' * 20, '案例 2: 纯寒暄(不该回)', '=' * 20)
|
||||
await disp.handle_message('demo:final', msg2)
|
||||
|
||||
print()
|
||||
print('=' * 20, '喂给 agent 的完整 prompt(案例 1)', '=' * 20)
|
||||
print(backend.prompts[0])
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
39
dev/proto_pipeline/README.md
Normal file
39
dev/proto_pipeline/README.md
Normal file
@ -0,0 +1,39 @@
|
||||
# Proto 再生成管线(维护者用)
|
||||
|
||||
飞书更新协议后,按以下流程重新提取全量 proto schema 和接口映射。
|
||||
|
||||
## 前提
|
||||
|
||||
先拿到 4 个基础 worklet bundle(版本会更新,文件名带 hash,需从页面 SharedWorker 创建记录里取最新 URL):
|
||||
|
||||
```
|
||||
1242.*.js (js runtime service)
|
||||
1181.*.js (shared worklet,长连接)
|
||||
9174.*.js (messenger worklet)
|
||||
9373.*.js (feed worklet)
|
||||
```
|
||||
|
||||
来源:`https://sf1-scmcdn-cn.feishucdn.com/obj/feishu-static/ee/web-client-next/p/static/js/<文件名>`,
|
||||
下载后放入 `work/`(或设 `LARK_WORK_DIR` 指向存放目录)。
|
||||
|
||||
抓取最新文件名的方法:chrome-devtools 打开 `open-dev.feishu.cn/next/messenger`,
|
||||
initScript Hook `SharedWorker` 构造器,记录传入的 blob loader 里的 `importScripts` URL。
|
||||
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
cd dev/proto_pipeline
|
||||
python extract_chunkmap.py # 从基础 bundle 解 webpack chunk 映射 → work/chunk_map.json
|
||||
python download_chunks.py # 并发下载全部懒加载 chunk(300+ 个)→ work/chunks/
|
||||
python extract_all.py # 提取 schema 注册表 + cmd 映射 → work/schemas_all.json, work/cmd_map.json
|
||||
python gen_protos.py # 生成 proto 文件(默认输出到 out/proto,含合并版 lark_all.proto)
|
||||
python gen_cmd_table.py # 生成接口映射表(默认 out/cmd_table.md)
|
||||
```
|
||||
|
||||
输出目录可用环境变量覆盖:`LARK_WORK_DIR`(输入/中间产物)、`LARK_PROTO_OUT`(proto/表输出)。
|
||||
|
||||
## 产物用途
|
||||
|
||||
- `out/proto/lark_all.proto` → 用 grpcio-tools 1.71.x 编译为 `larkx/proto/lark_all_pb2.py`
|
||||
- `work/cmd_map.json` → 按 `lark api` 的格式整理为 `larkx/proto/cmd_map.json`
|
||||
- `out/cmd_table.md` → 接口速查表(参考)
|
||||
44
dev/proto_pipeline/download_chunks.py
Normal file
44
dev/proto_pipeline/download_chunks.py
Normal file
@ -0,0 +1,44 @@
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
DIR = os.environ.get('LARK_WORK_DIR', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'work'))
|
||||
OUT = os.path.join(DIR, 'chunks')
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
BASE = 'https://sf1-scmcdn-cn.feishucdn.com/obj/feishu-static/ee/web-client-next/p/static/js'
|
||||
chunk_map = json.load(open(os.path.join(DIR, 'chunk_map.json')))
|
||||
|
||||
# also keep the 4 base bundles under their chunk ids
|
||||
BASE_BUNDLES = {
|
||||
'1242': '60b3a8cd', '1181': 'aa6c8a55', '9174': '30e252dd', '9373': 'e0426f59', '8929': '4a638fa1',
|
||||
}
|
||||
for cid, h in BASE_BUNDLES.items():
|
||||
chunk_map.setdefault(cid, h)
|
||||
|
||||
def fetch(item):
|
||||
cid, h = item
|
||||
name = '%s.%s.js' % (cid, h)
|
||||
path = os.path.join(OUT, name)
|
||||
if os.path.exists(path) and os.path.getsize(path) > 0:
|
||||
return name, 'skip', os.path.getsize(path)
|
||||
try:
|
||||
req = urllib.request.Request(BASE + '/' + name, headers={'User-Agent': 'Mozilla/5.0'})
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
data = r.read()
|
||||
open(path, 'wb').write(data)
|
||||
return name, 'ok', len(data)
|
||||
except Exception as e:
|
||||
return name, 'FAIL: %s' % e, 0
|
||||
|
||||
results = []
|
||||
with ThreadPoolExecutor(max_workers=12) as ex:
|
||||
for res in ex.map(fetch, sorted(chunk_map.items(), key=lambda x: int(x[0]))):
|
||||
results.append(res)
|
||||
|
||||
fails = [r for r in results if r[1].startswith('FAIL')]
|
||||
total = sum(r[2] for r in results)
|
||||
print('done: %d files, %d failures, total %.1f MB' % (len(results), len(fails), total / 1e6))
|
||||
for f in fails:
|
||||
print(' ', f[0], f[1])
|
||||
65
dev/proto_pipeline/extract_all.py
Normal file
65
dev/proto_pipeline/extract_all.py
Normal file
@ -0,0 +1,65 @@
|
||||
import re, os, json, glob
|
||||
|
||||
DIR = os.environ.get('LARK_WORK_DIR', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'work'))
|
||||
CHUNKS = os.path.join(DIR, 'chunks')
|
||||
|
||||
reg_pat = re.compile(r'register\("([a-zA-Z0-9_.]+)","([a-zA-Z0-9_.]+)",\{')
|
||||
cmd_pat = re.compile(r'"(-?\d+(?:\|[A-Za-z0-9_.]*)+)"')
|
||||
|
||||
def extract_regs(src):
|
||||
out = []
|
||||
for m in reg_pat.finditer(src):
|
||||
ns, name = m.group(1), m.group(2)
|
||||
i = m.end() - 1
|
||||
depth = 0
|
||||
start = i
|
||||
in_str = False
|
||||
str_ch = ''
|
||||
esc = False
|
||||
while i < len(src):
|
||||
c = src[i]
|
||||
if in_str:
|
||||
if esc:
|
||||
esc = False
|
||||
elif c == '\\':
|
||||
esc = True
|
||||
elif c == str_ch:
|
||||
in_str = False
|
||||
else:
|
||||
if c in '"\'':
|
||||
in_str = True
|
||||
str_ch = c
|
||||
elif c == '{':
|
||||
depth += 1
|
||||
elif c == '}':
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
i += 1
|
||||
out.append((ns, name, src[start:i+1]))
|
||||
return out
|
||||
|
||||
all_regs = {}
|
||||
cmd_map = {}
|
||||
files = sorted(glob.glob(os.path.join(CHUNKS, '*.js')))
|
||||
for fp in files:
|
||||
src = open(fp, encoding='utf-8', errors='replace').read()
|
||||
for ns, name, body in extract_regs(src):
|
||||
all_regs.setdefault((ns, name), body)
|
||||
for m in cmd_pat.finditer(src):
|
||||
cmd_map.setdefault(m.group(1), os.path.basename(fp))
|
||||
|
||||
print('files:', len(files))
|
||||
print('schemas:', len(all_regs))
|
||||
print('cmd mappings:', len(cmd_map))
|
||||
|
||||
json.dump({'%s.%s' % k: v for k, v in sorted(all_regs.items())},
|
||||
open(os.path.join(DIR, 'schemas_all.json'), 'w', encoding='utf-8'),
|
||||
ensure_ascii=False, indent=1)
|
||||
json.dump(cmd_map, open(os.path.join(DIR, 'cmd_map.json'), 'w', encoding='utf-8'),
|
||||
ensure_ascii=False, indent=1)
|
||||
|
||||
# namespace stats
|
||||
from collections import Counter
|
||||
ns_count = Counter(k[0] for k in all_regs)
|
||||
print('namespaces:', dict(ns_count.most_common(40)))
|
||||
16
dev/proto_pipeline/extract_chunkmap.py
Normal file
16
dev/proto_pipeline/extract_chunkmap.py
Normal file
@ -0,0 +1,16 @@
|
||||
import re, json, os
|
||||
|
||||
DIR = os.environ.get('LARK_WORK_DIR', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'work'))
|
||||
|
||||
chunk_map = {}
|
||||
for fn in ['1242.60b3a8cd.js', '1181.aa6c8a55.js', '9174.30e252dd.js', '9373.e0426f59.js']:
|
||||
src = open(os.path.join(DIR, fn), encoding='utf-8', errors='replace').read()
|
||||
for m in re.finditer(r'\.u=\w+=>"static/js/"\+\w+\+"\."\+\{([^{}]+)\}\[\w+\]\+"\.js"', src):
|
||||
body = m.group(1)
|
||||
for kv in re.finditer(r'(\d+):"([0-9a-f]+)"', body):
|
||||
chunk_map[int(kv.group(1))] = kv.group(2)
|
||||
|
||||
print('chunks found:', len(chunk_map))
|
||||
out = dict(sorted(chunk_map.items()))
|
||||
json.dump(out, open(os.path.join(DIR, 'chunk_map.json'), 'w'), indent=0)
|
||||
print(json.dumps(out))
|
||||
54
dev/proto_pipeline/gen_cmd_table.py
Normal file
54
dev/proto_pipeline/gen_cmd_table.py
Normal file
@ -0,0 +1,54 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
DIR = os.environ.get('LARK_WORK_DIR', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'work'))
|
||||
OUT = os.environ.get('LARK_PROTO_OUT', os.path.dirname(os.path.abspath(__file__)) + '/out') + '/cmd_table.md'
|
||||
|
||||
cmd_map = json.load(open(os.path.join(DIR, 'cmd_map.json'), encoding='utf-8'))
|
||||
|
||||
rows = []
|
||||
VALID = re.compile(r'^-?\d+(\|[A-Za-z0-9_.]*)+$')
|
||||
for raw in cmd_map:
|
||||
if not VALID.match(raw):
|
||||
continue
|
||||
if not re.search(r'\|[A-Za-z_.]*[A-Za-z]', raw): # must contain a proto-ish identifier
|
||||
continue
|
||||
parts = raw.split('|')
|
||||
try:
|
||||
cmd = int(parts[0])
|
||||
except ValueError:
|
||||
continue
|
||||
req = resp = name = ''
|
||||
rest = parts[1:]
|
||||
if len(rest) == 2:
|
||||
req, resp = rest
|
||||
elif len(rest) == 4:
|
||||
req, resp, _, name = rest
|
||||
elif len(rest) == 3:
|
||||
req, resp, name = rest
|
||||
else:
|
||||
resp = '|'.join(rest)
|
||||
rows.append((cmd, req, resp, name, raw))
|
||||
|
||||
rows.sort(key=lambda r: r[0])
|
||||
|
||||
lines = [
|
||||
'# 飞书网页客户端接口 (cmd) 映射表',
|
||||
'',
|
||||
'> 来源:web-client-next worklet bundles (2026-07-25, sdk 7.72.8)。',
|
||||
'> 格式 A: `cmd|请求proto|响应proto`;格式 B: `cmd||推送proto||推送名`;格式 C: `cmd|请求|响应|1|名称`。',
|
||||
'> 同名 cmd 在不同业务命名空间可能复用(推送类 cmd 与请求类 cmd 不冲突)。',
|
||||
'',
|
||||
'| cmd | 请求 | 响应/推送 | 名称 |',
|
||||
'|----:|------|-----------|------|',
|
||||
]
|
||||
for cmd, req, resp, name, raw in rows:
|
||||
lines.append('| %d | %s | %s | %s |' % (cmd, req, resp, name))
|
||||
|
||||
open(OUT, 'w', encoding='utf-8').write('\n'.join(lines))
|
||||
print('written %s, %d rows' % (OUT, len(rows)))
|
||||
|
||||
# a few stats
|
||||
push = [r for r in rows if 'Push' in r[2] or 'PUSH' in r[3]]
|
||||
print('push-type cmds:', len(push))
|
||||
413
dev/proto_pipeline/gen_protos.py
Normal file
413
dev/proto_pipeline/gen_protos.py
Normal file
@ -0,0 +1,413 @@
|
||||
"""Parse the JS schema-registry literals from schemas_all.json and generate .proto files."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
DIR = os.environ.get('LARK_WORK_DIR', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'work'))
|
||||
OUT_DIR = os.environ.get('LARK_PROTO_OUT', os.path.dirname(os.path.abspath(__file__)) + '/out/proto')
|
||||
|
||||
# ---------- JS object literal parser ----------
|
||||
|
||||
class JSParser:
|
||||
def __init__(self, s):
|
||||
self.s = s
|
||||
self.i = 0
|
||||
self.n = len(s)
|
||||
|
||||
def skip_ws(self):
|
||||
while self.i < self.n and self.s[self.i] in ' \t\r\n':
|
||||
self.i += 1
|
||||
|
||||
def peek(self):
|
||||
self.skip_ws()
|
||||
return self.s[self.i] if self.i < self.n else ''
|
||||
|
||||
def parse_value(self):
|
||||
self.skip_ws()
|
||||
c = self.s[self.i]
|
||||
if c == '{':
|
||||
return self.parse_object()
|
||||
if c == '[':
|
||||
return self.parse_array()
|
||||
if c in '"\'':
|
||||
return self.parse_string()
|
||||
if c == '!': # !0 -> true, !1 -> false
|
||||
if self.s[self.i:self.i+2] == '!0':
|
||||
self.i += 2
|
||||
return True
|
||||
if self.s[self.i:self.i+2] == '!1':
|
||||
self.i += 2
|
||||
return False
|
||||
raise ValueError('bad ! at %d' % self.i)
|
||||
# number or identifier
|
||||
m = re.match(r'-?(?:0x[0-9a-fA-F]+|\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)', self.s[self.i:])
|
||||
if m:
|
||||
tok = m.group(0)
|
||||
self.i += len(tok)
|
||||
if tok.startswith('0x') or tok.startswith('-0x'):
|
||||
return int(tok, 16)
|
||||
return float(tok) if ('.' in tok or 'e' in tok or 'E' in tok) else int(tok)
|
||||
m = re.match(r'[A-Za-z_$][A-Za-z0-9_$.]*', self.s[self.i:])
|
||||
if m:
|
||||
tok = m.group(0)
|
||||
self.i += len(tok)
|
||||
if tok == 'true':
|
||||
return True
|
||||
if tok == 'false':
|
||||
return False
|
||||
if tok in ('undefined', 'null', 'void'):
|
||||
return None
|
||||
return {'__raw__': tok}
|
||||
raise ValueError('unexpected %r at %d' % (self.s[self.i:self.i+20], self.i))
|
||||
|
||||
def parse_string(self):
|
||||
q = self.s[self.i]
|
||||
self.i += 1
|
||||
out = []
|
||||
while self.i < self.n:
|
||||
c = self.s[self.i]
|
||||
if c == '\\':
|
||||
nxt = self.s[self.i+1]
|
||||
if nxt == 'n':
|
||||
out.append('\n')
|
||||
elif nxt == 't':
|
||||
out.append('\t')
|
||||
elif nxt == 'r':
|
||||
out.append('\r')
|
||||
elif nxt == 'u':
|
||||
out.append(chr(int(self.s[self.i+2:self.i+6], 16)))
|
||||
self.i += 4
|
||||
elif nxt == 'x':
|
||||
out.append(chr(int(self.s[self.i+2:self.i+4], 16)))
|
||||
self.i += 2
|
||||
else:
|
||||
out.append(nxt)
|
||||
self.i += 2
|
||||
continue
|
||||
if c == q:
|
||||
self.i += 1
|
||||
return ''.join(out)
|
||||
out.append(c)
|
||||
self.i += 1
|
||||
raise ValueError('unterminated string')
|
||||
|
||||
def parse_key(self):
|
||||
self.skip_ws()
|
||||
c = self.s[self.i]
|
||||
if c in '"\'':
|
||||
return self.parse_string()
|
||||
m = re.match(r'[A-Za-z_$][A-Za-z0-9_$]*|\d+', self.s[self.i:])
|
||||
if not m:
|
||||
raise ValueError('bad key at %d: %r' % (self.i, self.s[self.i:self.i+20]))
|
||||
self.i += len(m.group(0))
|
||||
return m.group(0)
|
||||
|
||||
def parse_object(self):
|
||||
obj = {}
|
||||
assert self.s[self.i] == '{'
|
||||
self.i += 1
|
||||
while True:
|
||||
self.skip_ws()
|
||||
if self.s[self.i] == '}':
|
||||
self.i += 1
|
||||
return obj
|
||||
key = self.parse_key()
|
||||
self.skip_ws()
|
||||
assert self.s[self.i] == ':', 'expected : at %d' % self.i
|
||||
self.i += 1
|
||||
obj[key] = self.parse_value()
|
||||
self.skip_ws()
|
||||
if self.s[self.i] == ',':
|
||||
self.i += 1
|
||||
|
||||
def parse_array(self):
|
||||
arr = []
|
||||
assert self.s[self.i] == '['
|
||||
self.i += 1
|
||||
while True:
|
||||
self.skip_ws()
|
||||
if self.s[self.i] == ']':
|
||||
self.i += 1
|
||||
return arr
|
||||
arr.append(self.parse_value())
|
||||
self.skip_ws()
|
||||
if self.s[self.i] == ',':
|
||||
self.i += 1
|
||||
|
||||
|
||||
# ---------- proto generation ----------
|
||||
|
||||
SCALARS = {
|
||||
'string': 'string', 'bytes': 'bytes', 'bool': 'bool',
|
||||
'int32': 'int32', 'int64': 'int64', 'uint32': 'uint32', 'uint64': 'uint64',
|
||||
'sint32': 'sint32', 'sint64': 'sint64', 'fixed32': 'fixed32', 'fixed64': 'fixed64',
|
||||
'sfixed32': 'sfixed32', 'sfixed64': 'sfixed64', 'float': 'float', 'double': 'double',
|
||||
}
|
||||
|
||||
def sanitize_ident(name):
|
||||
name = re.sub(r'[^A-Za-z0-9_]', '_', str(name))
|
||||
if name and name[0].isdigit():
|
||||
name = '_' + name
|
||||
return name
|
||||
|
||||
class ProtoGen:
|
||||
def __init__(self, ns, all_namespaces, merged=False):
|
||||
self.ns = ns
|
||||
self.all_ns = all_namespaces
|
||||
self.merged = merged
|
||||
self.unresolved = set()
|
||||
self.imports = set()
|
||||
self.lines = []
|
||||
|
||||
def resolve_type(self, t, local_names):
|
||||
if t in SCALARS:
|
||||
return SCALARS[t]
|
||||
if '.' in t:
|
||||
head = t.split('.')[0]
|
||||
if head in local_names: # same-namespace nested ref, e.g. Chat.Type
|
||||
return t
|
||||
if head in self.all_ns: # cross-package
|
||||
if self.merged:
|
||||
return t # resolves via enclosing message-scope in merged file
|
||||
self.imports.add(head)
|
||||
return '.' + t
|
||||
self.unresolved.add(t)
|
||||
return t
|
||||
if t in local_names:
|
||||
return t
|
||||
# might be a nested type of current message chain - emit as-is and note
|
||||
return t
|
||||
|
||||
def gen_enum(self, name, body, indent):
|
||||
pad = ' ' * indent
|
||||
self.lines.append('%senum %s {' % (pad, sanitize_ident(name)))
|
||||
values = body.get('values', {})
|
||||
has_zero = any((int(v) if isinstance(v, float) and float(v).is_integer() else v) == 0 for v in values.values())
|
||||
if not has_zero:
|
||||
self.lines.append('%s %s_UNSPECIFIED = 0; // injected: proto3 requires a zero value' % (pad, sanitize_ident(name).upper()))
|
||||
for vn, vv in values.items():
|
||||
if isinstance(vv, float) and vv.is_integer():
|
||||
vv = int(vv)
|
||||
self.lines.append('%s %s = %s;' % (pad, sanitize_ident(vn), vv))
|
||||
self.lines.append('%s}' % pad)
|
||||
|
||||
def gen_message(self, name, body, indent):
|
||||
pad = ' ' * indent
|
||||
ident = sanitize_ident(name)
|
||||
self.lines.append('%smessage %s {' % (pad, ident))
|
||||
fields = body.get('fields', {})
|
||||
nested = body.get('nested', {})
|
||||
oneofs = body.get('oneofs', {})
|
||||
oneof_fields = set()
|
||||
for oname, odef in oneofs.items():
|
||||
for fn in (odef.get('oneof') or []):
|
||||
oneof_fields.add(fn)
|
||||
local_names = set(nested.keys())
|
||||
# plain fields first
|
||||
for fname, fdef in fields.items():
|
||||
if fname in oneof_fields:
|
||||
continue
|
||||
self.gen_field(fname, fdef, indent + 1, local_names)
|
||||
# oneofs
|
||||
for oname, odef in oneofs.items():
|
||||
self.lines.append('%s oneof %s {' % (pad, sanitize_ident(oname)))
|
||||
for fn in (odef.get('oneof') or []):
|
||||
if fn in fields:
|
||||
self.gen_field(fn, fields[fn], indent + 2, local_names, in_oneof=True)
|
||||
self.lines.append('%s }' % pad)
|
||||
# nested
|
||||
for nname, nbody in nested.items():
|
||||
if 'values' in nbody:
|
||||
self.gen_enum(nname, nbody, indent + 1)
|
||||
else:
|
||||
self.gen_message(nname, nbody, indent + 1)
|
||||
self.lines.append('%s}' % pad)
|
||||
|
||||
def gen_field(self, fname, fdef, indent, local_names, in_oneof=False):
|
||||
pad = ' ' * indent
|
||||
t = fdef.get('type', 'bytes')
|
||||
fid = fdef.get('id')
|
||||
if isinstance(fid, float) and fid.is_integer():
|
||||
fid = int(fid)
|
||||
rule = fdef.get('rule')
|
||||
key_type = fdef.get('keyType')
|
||||
opts = fdef.get('options') or {}
|
||||
tname = self.resolve_type(t, local_names)
|
||||
label = ''
|
||||
if rule == 'repeated' and not key_type:
|
||||
label = 'repeated '
|
||||
comment = ''
|
||||
opt_parts = []
|
||||
if opts.get('deprecated'):
|
||||
opt_parts.append('deprecated = true')
|
||||
if opts.get('packed') is False:
|
||||
opt_parts.append('packed = false')
|
||||
if 'default' in opts and not in_oneof:
|
||||
comment = ' // default: %s' % (opts['default'],)
|
||||
opt_str = ' [%s]' % ', '.join(opt_parts) if opt_parts else ''
|
||||
if key_type:
|
||||
kt = self.resolve_type(key_type, local_names)
|
||||
self.lines.append('%smap<%s, %s> %s = %s%s;%s' % (pad, kt, tname, sanitize_ident(fname), fid, opt_str, comment))
|
||||
else:
|
||||
if in_oneof:
|
||||
prefix = ''
|
||||
elif label:
|
||||
prefix = label
|
||||
else:
|
||||
prefix = 'optional '
|
||||
self.lines.append('%s%s%s %s = %s%s;%s' % (pad, prefix, tname, sanitize_ident(fname), fid, opt_str, comment))
|
||||
|
||||
|
||||
def main():
|
||||
schemas = json.load(open(os.path.join(DIR, 'schemas_all.json'), encoding='utf-8'))
|
||||
by_ns = defaultdict(dict)
|
||||
parse_errors = []
|
||||
for full_name, body in schemas.items():
|
||||
ns, name = full_name.split('.', 1)
|
||||
try:
|
||||
parsed = JSParser(body).parse_value()
|
||||
except Exception as e:
|
||||
parse_errors.append((full_name, str(e)))
|
||||
continue
|
||||
by_ns[ns][name] = parsed
|
||||
|
||||
print('namespaces:', len(by_ns), 'parse errors:', len(parse_errors))
|
||||
for e in parse_errors[:10]:
|
||||
print(' ERR', e)
|
||||
|
||||
all_ns = set(by_ns.keys())
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
stats = []
|
||||
all_unresolved = defaultdict(set)
|
||||
for ns in sorted(by_ns):
|
||||
gen = ProtoGen(ns, all_ns)
|
||||
for name in sorted(by_ns[ns]):
|
||||
body = by_ns[ns][name]
|
||||
if 'values' in body and 'fields' not in body:
|
||||
gen.gen_enum(name, body, 0)
|
||||
else:
|
||||
gen.gen_message(name, body, 0)
|
||||
gen.lines.append('')
|
||||
header = ['syntax = "proto3";', '', 'package %s;' % sanitize_ident(ns), '']
|
||||
header.append('// Auto-generated from Feishu web-client-next worklet schema registry (2026-07-25)')
|
||||
header.append('')
|
||||
for imp in sorted(gen.imports - {ns}):
|
||||
header.append('import "%s.proto";' % sanitize_ident(imp))
|
||||
if gen.imports - {ns}:
|
||||
header.append('')
|
||||
path = os.path.join(OUT_DIR, '%s.proto' % sanitize_ident(ns))
|
||||
open(path, 'w', encoding='utf-8').write('\n'.join(header + gen.lines))
|
||||
stats.append((ns, len(by_ns[ns])))
|
||||
if gen.unresolved:
|
||||
all_unresolved[ns] = gen.unresolved
|
||||
|
||||
print('written %d proto files to %s' % (len(stats), OUT_DIR))
|
||||
for ns, cnt in stats:
|
||||
print(' %-30s %d' % (ns, cnt))
|
||||
if all_unresolved:
|
||||
print('unresolved type refs (kept as-is):')
|
||||
for ns, s in all_unresolved.items():
|
||||
print(' %s: %s' % (ns, sorted(s)[:10]))
|
||||
|
||||
# merged single file (compilable; namespaces wrapped as messages to avoid
|
||||
# import cycles and enum-value collisions)
|
||||
merged_lines = ['syntax = "proto3";', '', 'package lark;', '',
|
||||
'// Merged view of all namespaces (each namespace wrapped as a message).',
|
||||
'// Auto-generated from Feishu web-client-next worklet schema registry (2026-07-25)', '']
|
||||
for ns in sorted(by_ns):
|
||||
gen = ProtoGen(ns, all_ns, merged=True)
|
||||
merged_lines.append('message %s {' % sanitize_ident(ns))
|
||||
for name in sorted(by_ns[ns]):
|
||||
body = by_ns[ns][name]
|
||||
if 'values' in body and 'fields' not in body:
|
||||
gen.gen_enum(name, body, 1)
|
||||
else:
|
||||
gen.gen_message(name, body, 1)
|
||||
gen.lines.append('')
|
||||
merged_lines.extend(gen.lines)
|
||||
merged_lines.append('}')
|
||||
merged_lines.append('')
|
||||
open(os.path.join(OUT_DIR, 'lark_all.proto'), 'w', encoding='utf-8').write('\n'.join(merged_lines))
|
||||
print('written merged lark_all.proto')
|
||||
|
||||
# break import cycles in per-namespace files (protoc forbids them; the
|
||||
# merged lark_all.proto remains the fully compilable version)
|
||||
graph = {}
|
||||
for ns in by_ns:
|
||||
path = os.path.join(OUT_DIR, '%s.proto' % sanitize_ident(ns))
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
lines = open(path, encoding='utf-8').read().splitlines()
|
||||
imps = [re.match(r'import "(.+)\.proto";', l).group(1) for l in lines if re.match(r'import ".+\.proto";', l)]
|
||||
graph[ns] = (path, lines, imps)
|
||||
|
||||
def find_cycle():
|
||||
visited, stack = set(), []
|
||||
def dfs(u):
|
||||
visited.add(u)
|
||||
stack.append(u)
|
||||
for v in graph.get(u, (None, None, []))[2]:
|
||||
if v not in graph:
|
||||
continue
|
||||
if v in stack:
|
||||
return stack[stack.index(v):] + [v]
|
||||
if v not in visited:
|
||||
r = dfs(v)
|
||||
if r:
|
||||
return r
|
||||
stack.pop()
|
||||
return None
|
||||
for u in graph:
|
||||
if u not in visited:
|
||||
r = dfs(u)
|
||||
if r:
|
||||
return r
|
||||
return None
|
||||
|
||||
broken = []
|
||||
while True:
|
||||
cyc = find_cycle()
|
||||
if not cyc:
|
||||
break
|
||||
# drop the import edge from the alphabetically-last file in the cycle
|
||||
a, b = cyc[-2], cyc[-1]
|
||||
frm, to = (a, b) if a > b else (b, a)
|
||||
# ensure 'to' is actually imported by 'frm'; otherwise pick any edge
|
||||
edges = [(cyc[i], cyc[i+1]) for i in range(len(cyc)-1)]
|
||||
if (frm, to) not in edges:
|
||||
frm, to = edges[-1]
|
||||
path, lines, imps = graph[frm]
|
||||
new_lines = []
|
||||
for l in lines:
|
||||
if l == 'import "%s.proto";' % to:
|
||||
new_lines.append('// import "%s.proto"; // removed to break an import cycle; use lark_all.proto to compile' % to)
|
||||
continue
|
||||
new_lines.append(l)
|
||||
open(path, 'w', encoding='utf-8').write('\n'.join(new_lines))
|
||||
graph[frm] = (path, new_lines, [i for i in imps if i != to])
|
||||
broken.append((frm, to))
|
||||
if broken:
|
||||
print('broke import cycles:', broken)
|
||||
|
||||
# fidelity-preserving fixup for the entities<->pan cycle:
|
||||
# keep pan -> entities intact; in entities.proto downgrade the two
|
||||
# .pan.VisitInfo refs to bytes (field numbers unchanged) so that
|
||||
# entities.proto (the core namespace) compiles standalone.
|
||||
ent_path = os.path.join(OUT_DIR, 'entities.proto')
|
||||
pan_path = os.path.join(OUT_DIR, 'pan.proto')
|
||||
if os.path.exists(ent_path) and os.path.exists(pan_path):
|
||||
ent = open(ent_path, encoding='utf-8').read()
|
||||
ent = ent.replace('.pan.VisitInfo', 'bytes /* orig type: .pan.VisitInfo (see pan.proto) */')
|
||||
ent = ent.replace('import "pan.proto";',
|
||||
'// import "pan.proto"; // removed to break the entities<->pan cycle')
|
||||
open(ent_path, 'w', encoding='utf-8').write(ent)
|
||||
pan = open(pan_path, encoding='utf-8').read()
|
||||
pan = pan.replace('// import "entities.proto"; // removed to break an import cycle; use lark_all.proto to compile',
|
||||
'import "entities.proto";')
|
||||
open(pan_path, 'w', encoding='utf-8').write(pan)
|
||||
print('applied entities/pan cycle fixup')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user