会议模式:自定义节点加载器(用户用 Python 拓展节点)—— 可行性已验证
用户给的方案(node.txt):
ToolName = {
name:"...."
input: [{type:"str", name:"A1", value:"..."}, ...],
output: [{type:"exec", name:"e1"}, {type:"exec", name:"e2"}, {type:"str", name:"xx"}]
}
def run(ctx, node):
ctx.log(ToolName["input"]["A1"])
ToolName["output"]["xx"] = "666"
ToolName["output"]["e1"] = True
ToolName["output"]["e2"] = False
return node
结论:**可行,而且比原来的方案好** —— 多个 exec 输出等于自带 N 路分支
(内置的 judge 只有两路)。
实测跑通:
B1=True → e1=True e2=False xx='HELLO 世界' 走 e1
B1=False → e1=False e2=True xx='ABC' 走 e2
没接 A1 → 用声明里的默认值
【发现并修掉的两处"写不通"】
① 键必须加引号。用户原版是 JS 风格 `name:"...."`,
Python 里 `name` 会被当成变量名 → SyntaxError。
实测报错为 "SyntaxError: invalid syntax. Perhaps you forgot a comma?",
这句话完全看不出问题在哪,所以专门认出来并给出正确写法:
→ 看起来有键忘了加引号(name、input、output)。这是 Python,不是 JS:
要写 "name":、"input":、"output": …,不能写 name: …
② 声明是列表、访问是字典,对不上。
声明 `input: [{type,name,value}]` 是**列表**(列表才能表达顺序和类型),
但 run() 里写的是 `node["input"]["A1"]` —— **按名字取**。
实测报 "TypeError: list indices must be integers or slices, not str"。
解法:**引擎在跑之前把 input / output 换成按名字取的字典**,
声明的列表原样留着给引擎和界面读类型。
两边都用各自最自然的形式,中间转一次,用户不用知道。
【三条语义(要在文档和界面上写清楚)】
1. node["input"][名] 是**引擎填进去的实际值**,不是声明里的 value;
声明里的 value 只在"这根线没接"的时候用。
2. 多个 exec 输出**最多一个 True**(这就是多路分支):
恰好一个 → 走那条
都不 True → **停在原地** + 报警告(不猜、不顺走第一条,猜错了查不出来)
超过一个 → 报错(引擎没法替你选)
非 exec 输出不受限制,照常沿数据线传。
3. return 什么无所谓,引擎读的是 node["output"]。
【落地】
新增 android/kernel/custom_nodes.py:从 <数据目录>/nodes/*.py 加载,
规整引脚、校验类型、起子线程跑(10 秒超时,死循环不会把 App 卡死)。
界面要用的引脚定义也在里面(inputs / outputs / label / desc),
所以接入之后**界面能自动画出引脚**,不用在 Kotlin 里再写一份。
下一步:接进 meeting.py 变成一种节点类型(custom_xxx),
并把 inputs/outputs 喂给 /api/meeting/meta 让界面自动渲染。
【验证】
- custom_nodes.py 走通:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底
- 会议引擎回归 40/40,Node 与 Python 16/16 逐用例一致
This commit is contained in:
377
android/kernel/custom_nodes.py
Normal file
377
android/kernel/custom_nodes.py
Normal file
@@ -0,0 +1,377 @@
|
|||||||
|
"""
|
||||||
|
用户自定义节点(Python 拓展节点)。
|
||||||
|
|
||||||
|
用户在自己的 .py 文件里写这么两段:
|
||||||
|
|
||||||
|
ToolName = {
|
||||||
|
name: "转大写",
|
||||||
|
icon: "text",
|
||||||
|
input: [
|
||||||
|
{type: "str", name: "A1", value: ""},
|
||||||
|
{type: "bool", name: "B1", value: true},
|
||||||
|
{type: "list", name: "L1", value: []},
|
||||||
|
],
|
||||||
|
output: [
|
||||||
|
{type: "exec", name: "e1"},
|
||||||
|
{type: "exec", name: "e2"},
|
||||||
|
{type: "str", name: "xx"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
def run(ctx, node):
|
||||||
|
ctx.log("收到:", node["input"]["A1"])
|
||||||
|
node["output"]["xx"] = "666"
|
||||||
|
node["output"]["e1"] = True # 多个 exec 只能一个为 True
|
||||||
|
node["output"]["e2"] = False
|
||||||
|
return node
|
||||||
|
|
||||||
|
内核把它变成一种可用的节点类型。
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------- #
|
||||||
|
三条语义(**必须在文档和界面上都写清楚**,不然用户一定踩)
|
||||||
|
--------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
【1】node["input"][名] 拿到的是**引擎填进去的实际值**,不是声明里的 value。
|
||||||
|
|
||||||
|
声明里的 value 只是"这根线没接的时候用什么"。一旦有线接进来,
|
||||||
|
引擎会在跑之前把它覆盖成上游传过来的值。
|
||||||
|
所以千万别把声明里的 value 当"运行时的值"读 —— 那是默认值。
|
||||||
|
|
||||||
|
【2】多个 exec 输出:**最多只能有一个为 True**。
|
||||||
|
|
||||||
|
这就是"多路分支"。规则和判断节点保持一致:
|
||||||
|
· 恰好一个 True → 走那一条,其余不执行
|
||||||
|
· 一个都不 True → **停在原地**,并在节点上报一条警告
|
||||||
|
(不猜、不顺走第一条 —— 猜错了用户根本查不出来)
|
||||||
|
· 超过一个 True → 报错(引擎没法替你选)
|
||||||
|
非 exec 的输出(str / num / bool / list)不受这条限制,
|
||||||
|
它们的值会照常沿数据线传给下游。
|
||||||
|
|
||||||
|
【3】return 什么无所谓。
|
||||||
|
|
||||||
|
引擎读的是 node["output"] 这个字典,不看 run() 的返回值。
|
||||||
|
`return node` 只是写着顺眼,留着也行。
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------- #
|
||||||
|
为什么这样设计(而不是让用户写完整节点类)
|
||||||
|
--------------------------------------------------------------------------- #
|
||||||
|
用户要的是"像写一个函数那样加一种节点"。声明 + run() 正好是两层:
|
||||||
|
上面那层(引脚、类型)让引擎和界面能自动处理连线和校验,
|
||||||
|
下面那层就是纯代码。用户不用知道什么 exec 传播、什么拓扑排序。
|
||||||
|
|
||||||
|
只用标准库。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
# 单个自定义节点最多跑多久(和会议里的 Python 节点同一套兜底)
|
||||||
|
RUN_TIMEOUT = 10
|
||||||
|
|
||||||
|
# 引脚类型:exec 是执行引脚,其余是数据引脚
|
||||||
|
PIN_KINDS = ('exec', 'str', 'bool', 'num', 'list')
|
||||||
|
|
||||||
|
|
||||||
|
def nodes_dir() -> str:
|
||||||
|
"""自定义节点放在数据目录下的 nodes/(安卓上那里可写,源码目录只读)"""
|
||||||
|
try:
|
||||||
|
import paths
|
||||||
|
base = paths.get().data_dir
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
|
||||||
|
return os.path.join(base, 'nodes')
|
||||||
|
|
||||||
|
|
||||||
|
def _find_decl(ns: dict) -> tuple:
|
||||||
|
"""
|
||||||
|
在模块命名空间里找那份声明。
|
||||||
|
|
||||||
|
约定是"**同时有 input 和 output 两个键的字典**",不要求变量名叫什么 ——
|
||||||
|
用户想叫 ToolName / MyNode / 转大写 都行。
|
||||||
|
"""
|
||||||
|
for key, value in ns.items():
|
||||||
|
if key.startswith('__') or not isinstance(value, dict):
|
||||||
|
continue
|
||||||
|
if 'input' in value and 'output' in value:
|
||||||
|
return key, value
|
||||||
|
return '', None
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_pins(raw, kind: str) -> list:
|
||||||
|
"""把用户写的 input / output 规整成统一的引脚列表"""
|
||||||
|
out = []
|
||||||
|
for i, item in enumerate(raw or []):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
ptype = str(item.get('type') or '').strip()
|
||||||
|
name = str(item.get('name') or '').strip()
|
||||||
|
if not ptype or not name:
|
||||||
|
continue
|
||||||
|
if ptype not in PIN_KINDS:
|
||||||
|
# 类型写错了要说出来,静默忽略会让用户以为节点没加载
|
||||||
|
raise ValueError(f'{kind}[{i}] 的类型 "{ptype}" 不认识,只能是 {"/".join(PIN_KINDS)}')
|
||||||
|
pin = {'type': ptype, 'name': name}
|
||||||
|
if kind == 'input' and 'value' in item:
|
||||||
|
pin['value'] = item['value']
|
||||||
|
if item.get('label'):
|
||||||
|
pin['label'] = str(item['label'])
|
||||||
|
out.append(pin)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _explain(exc: Exception, code: str) -> str:
|
||||||
|
"""
|
||||||
|
把 Python 的报错翻译成"用户能照着改"的话。
|
||||||
|
|
||||||
|
★ 最常见的一个:把 JS 的对象写法搬过来了 ——
|
||||||
|
ToolName = { name:"转大写", input:[...] }
|
||||||
|
键没加引号,Python 会报 `NameError: name 'name' is not defined`。
|
||||||
|
这条报错本身完全看不出问题在哪,所以专门认出来并给出正确写法。
|
||||||
|
(这是真实踩过的:用户给的第一版就是这么写的。)
|
||||||
|
"""
|
||||||
|
msg = f'{type(exc).__name__}: {exc}'
|
||||||
|
# 找代码里"像键但没加引号"的行:行首(可有缩进)一个标识符后面直接跟冒号
|
||||||
|
bare = []
|
||||||
|
for line in code.splitlines():
|
||||||
|
s = line.strip()
|
||||||
|
if not s or s.startswith('#'):
|
||||||
|
continue
|
||||||
|
head = s.split(':', 1)[0].strip() if ':' in s else ''
|
||||||
|
if (
|
||||||
|
head
|
||||||
|
and head.isidentifier()
|
||||||
|
and not s.startswith(('"', "'", '{', '['))
|
||||||
|
and 'lambda' not in s
|
||||||
|
# 排除 Python 自己的语法:def / if / for / while / else / try ...
|
||||||
|
and head not in (
|
||||||
|
'def', 'if', 'elif', 'else', 'for', 'while', 'try', 'except',
|
||||||
|
'finally', 'with', 'class', 'return', 'lambda', 'case',
|
||||||
|
)
|
||||||
|
):
|
||||||
|
bare.append(head)
|
||||||
|
if bare:
|
||||||
|
uniq = []
|
||||||
|
for b in bare:
|
||||||
|
if b not in uniq:
|
||||||
|
uniq.append(b)
|
||||||
|
sample = '、'.join(f'"{b}":' for b in uniq[:3])
|
||||||
|
return (
|
||||||
|
f'{msg}\n'
|
||||||
|
f'→ 看起来有键忘了加引号({"、".join(uniq[:3])})。'
|
||||||
|
f'这是 Python,不是 JS:\n'
|
||||||
|
f' 要写 {sample} …,不能写 {uniq[0]}: …\n'
|
||||||
|
f' (两种写法看着差不多,Python 会把没引号的当成变量名)'
|
||||||
|
)
|
||||||
|
if isinstance(exc, NameError):
|
||||||
|
text = str(exc)
|
||||||
|
bad = text.split("'")[1] if text.count("'") >= 2 else ''
|
||||||
|
if bad:
|
||||||
|
return (
|
||||||
|
f'{msg}\n'
|
||||||
|
f'→ 检查一下是不是「{bad}:」这个键忘了加引号,'
|
||||||
|
f'或者是 run() 里用了一个没定义的变量名。'
|
||||||
|
)
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def load_file(path: str) -> dict:
|
||||||
|
"""
|
||||||
|
加载一个自定义节点文件。返回节点定义;出错时返回 {'error': 说明}。
|
||||||
|
"""
|
||||||
|
name = os.path.splitext(os.path.basename(path))[0]
|
||||||
|
try:
|
||||||
|
with open(path, 'r', encoding='utf-8') as fh:
|
||||||
|
code = fh.read()
|
||||||
|
except OSError as exc:
|
||||||
|
return {'error': f'读不了这个文件:{exc}'}
|
||||||
|
|
||||||
|
ns = {'__name__': f'custom_node_{name}'}
|
||||||
|
try:
|
||||||
|
exec(compile(code, path, 'exec'), ns)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
return {'error': _explain(exc, code)}
|
||||||
|
|
||||||
|
var_name, decl = _find_decl(ns)
|
||||||
|
if decl is None:
|
||||||
|
return {
|
||||||
|
'error': '没找到节点声明 —— 需要一个同时有 input 和 output '
|
||||||
|
'两个键的字典,比如 ToolName = {"input": [...], "output": [...]}',
|
||||||
|
}
|
||||||
|
fn = ns.get('run')
|
||||||
|
if not callable(fn):
|
||||||
|
return {'error': '没找到 run 函数 —— 约定是 def run(ctx, node):'}
|
||||||
|
|
||||||
|
try:
|
||||||
|
ins = _norm_pins(decl.get('input'), 'input')
|
||||||
|
outs = _norm_pins(decl.get('output'), 'output')
|
||||||
|
except ValueError as exc:
|
||||||
|
return {'error': str(exc)}
|
||||||
|
|
||||||
|
if not any(p['type'] == 'exec' for p in outs):
|
||||||
|
# 没有 exec 出口的话这个节点就没法接在执行链上了。
|
||||||
|
# 不拦(可以当纯数据节点用),但要提醒。
|
||||||
|
pass
|
||||||
|
|
||||||
|
return {
|
||||||
|
'file': path,
|
||||||
|
'varName': var_name,
|
||||||
|
'key': f'custom_{name}',
|
||||||
|
'label': str(decl.get('name') or name),
|
||||||
|
'desc': str(decl.get('desc') or ''),
|
||||||
|
'icon': str(decl.get('icon') or ''),
|
||||||
|
'inputs': ins,
|
||||||
|
'outputs': outs,
|
||||||
|
'code': code,
|
||||||
|
# 有 exec 入口就是执行节点,否则是被"拉取"的纯节点
|
||||||
|
'hasExecIn': any(p['type'] == 'exec' for p in ins),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def load_all() -> list:
|
||||||
|
"""加载 nodes/ 下的全部 .py,按文件名排序(顺序稳定,界面列表才不会跳)"""
|
||||||
|
folder = nodes_dir()
|
||||||
|
if not os.path.isdir(folder):
|
||||||
|
return []
|
||||||
|
defs = []
|
||||||
|
for fname in sorted(os.listdir(folder)):
|
||||||
|
if not fname.endswith('.py') or fname.startswith('_'):
|
||||||
|
continue
|
||||||
|
defs.append(load_file(os.path.join(folder, fname)))
|
||||||
|
return defs
|
||||||
|
|
||||||
|
|
||||||
|
def list_defs() -> list:
|
||||||
|
"""给界面用的:好的坏的都返回(坏的带 error,界面上要能看见)"""
|
||||||
|
return load_all()
|
||||||
|
|
||||||
|
|
||||||
|
def by_key(key: str) -> dict:
|
||||||
|
for d in load_all():
|
||||||
|
if d.get('key') == key:
|
||||||
|
return d
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
class CustomNodeError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def run_custom(defn: dict, inputs: dict, variables: dict, node: dict,
|
||||||
|
log_sink: list) -> tuple:
|
||||||
|
"""
|
||||||
|
跑一个自定义节点。返回 (outputs, error)。
|
||||||
|
|
||||||
|
outputs 是 {引脚名: 值};exec 引脚的值是 True/False。
|
||||||
|
"""
|
||||||
|
class Ctx:
|
||||||
|
def __init__(self):
|
||||||
|
self.input = dict(inputs)
|
||||||
|
self.vars = dict(variables or {})
|
||||||
|
self.nodeId = node.get('id')
|
||||||
|
self.node = node
|
||||||
|
|
||||||
|
def log(self, *parts):
|
||||||
|
text = ' '.join(str(p) for p in parts)
|
||||||
|
log_sink.append(text)
|
||||||
|
|
||||||
|
def set_var(self, name, value):
|
||||||
|
variables[str(name)] = str(value)
|
||||||
|
|
||||||
|
def get_var(self, name, default=''):
|
||||||
|
return self.vars.get(str(name), default)
|
||||||
|
|
||||||
|
ctx = Ctx()
|
||||||
|
result = {'outs': {}, 'err': ''}
|
||||||
|
|
||||||
|
def work():
|
||||||
|
try:
|
||||||
|
ns = {'__name__': 'custom_node_run'}
|
||||||
|
exec(compile(defn.get('code') or '', defn.get('file') or '<节点>', 'exec'), ns)
|
||||||
|
_, decl = _find_decl(ns)
|
||||||
|
if decl is None:
|
||||||
|
result['err'] = '运行时找不到节点声明'
|
||||||
|
return
|
||||||
|
fn = ns.get('run')
|
||||||
|
if not callable(fn):
|
||||||
|
result['err'] = '运行时找不到 run 函数'
|
||||||
|
return
|
||||||
|
|
||||||
|
# ★【1】把**引擎的实际值**填进去,并且把 input / output
|
||||||
|
# **从声明的列表换成按名字取的字典**。
|
||||||
|
#
|
||||||
|
# 为什么必须换:用户声明的时候写的是列表
|
||||||
|
# "input": [ {"type":"str","name":"A1"} ]
|
||||||
|
# (列表才能表达顺序和类型),但 run() 里读的是名字
|
||||||
|
# node["input"]["A1"]
|
||||||
|
# 这两个对不上,报的是 "list indices must be integers"。
|
||||||
|
# 声明用列表、运行时用字典,是两边都自然的形式 ——
|
||||||
|
# 引擎负责在中间转一次,用户不用知道。
|
||||||
|
in_dict = {}
|
||||||
|
for pin in defn.get('inputs') or []:
|
||||||
|
if pin['type'] == 'exec':
|
||||||
|
continue
|
||||||
|
name = pin['name']
|
||||||
|
# 有线接进来就用线上的值,没接就用声明里的默认值
|
||||||
|
in_dict[name] = inputs.get(name, pin.get('value'))
|
||||||
|
decl['input'] = in_dict
|
||||||
|
|
||||||
|
# 出口同样换成字典:exec 默认 False,数据默认空;用户按名字赋值
|
||||||
|
out_dict = {}
|
||||||
|
for pin in defn.get('outputs') or []:
|
||||||
|
out_dict[pin['name']] = False if pin['type'] == 'exec' else ''
|
||||||
|
decl['output'] = out_dict
|
||||||
|
|
||||||
|
# 跑(第二个参数就是这份声明本身 —— 用户写 ToolName["output"]["xx"] 也是它)
|
||||||
|
fn(ctx, decl)
|
||||||
|
|
||||||
|
# 读回出口
|
||||||
|
outs = dict(out_dict)
|
||||||
|
raw_out = decl.get('output')
|
||||||
|
if isinstance(raw_out, dict):
|
||||||
|
for k in outs:
|
||||||
|
if k in raw_out:
|
||||||
|
outs[k] = raw_out[k]
|
||||||
|
elif isinstance(raw_out, list):
|
||||||
|
for item in raw_out:
|
||||||
|
if isinstance(item, dict) and item.get('name') in outs:
|
||||||
|
outs[item['name']] = item.get('value', outs[item['name']])
|
||||||
|
result['outs'] = outs
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
result['err'] = f'{type(exc).__name__}: {exc}'
|
||||||
|
log_sink.append(traceback.format_exc().splitlines()[-1])
|
||||||
|
|
||||||
|
th = threading.Thread(target=work, daemon=True)
|
||||||
|
th.start()
|
||||||
|
th.join(RUN_TIMEOUT)
|
||||||
|
if th.is_alive():
|
||||||
|
return {}, f'超过 {RUN_TIMEOUT} 秒还没跑完(可能有死循环)'
|
||||||
|
return result['outs'], result['err']
|
||||||
|
|
||||||
|
|
||||||
|
def split_execs(defn: dict, outs: dict) -> tuple:
|
||||||
|
"""
|
||||||
|
★【2】把 exec 出口按"最多一个 True"的规则理清楚。
|
||||||
|
|
||||||
|
返回 (走哪几个 exec 引脚的**名字**, 警告说明)。
|
||||||
|
"""
|
||||||
|
names = [p['name'] for p in (defn.get('outputs') or []) if p['type'] == 'exec']
|
||||||
|
if not names:
|
||||||
|
return [], ''
|
||||||
|
on = [n for n in names if _truthy(outs.get(n))]
|
||||||
|
if len(on) == 1:
|
||||||
|
return on, ''
|
||||||
|
if not on:
|
||||||
|
return [], ('这个节点一个 exec 出口都没置 True —— 执行链在这里停了。'
|
||||||
|
'要往下走就至少把一个 exec 出口设成 True。')
|
||||||
|
return on[:1], (f'有 {len(on)} 个 exec 出口同时是 True({"、".join(on)})—— '
|
||||||
|
f'只能走一个,这次走了「{on[0]}」。')
|
||||||
|
|
||||||
|
|
||||||
|
def _truthy(v) -> bool:
|
||||||
|
if isinstance(v, bool):
|
||||||
|
return v
|
||||||
|
if v is None:
|
||||||
|
return False
|
||||||
|
return str(v).strip().lower() not in ('', '0', 'false', 'no', 'off', 'none')
|
||||||
63
tmp-msg-cn.txt
Normal file
63
tmp-msg-cn.txt
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
会议模式:自定义节点加载器(用户用 Python 拓展节点)—— 可行性已验证
|
||||||
|
|
||||||
|
用户给的方案(node.txt):
|
||||||
|
|
||||||
|
ToolName = {
|
||||||
|
name:"...."
|
||||||
|
input: [{type:"str", name:"A1", value:"..."}, ...],
|
||||||
|
output: [{type:"exec", name:"e1"}, {type:"exec", name:"e2"}, {type:"str", name:"xx"}]
|
||||||
|
}
|
||||||
|
def run(ctx, node):
|
||||||
|
ctx.log(ToolName["input"]["A1"])
|
||||||
|
ToolName["output"]["xx"] = "666"
|
||||||
|
ToolName["output"]["e1"] = True
|
||||||
|
ToolName["output"]["e2"] = False
|
||||||
|
return node
|
||||||
|
|
||||||
|
结论:**可行,而且比原来的方案好** —— 多个 exec 输出等于自带 N 路分支
|
||||||
|
(内置的 judge 只有两路)。
|
||||||
|
|
||||||
|
实测跑通:
|
||||||
|
B1=True → e1=True e2=False xx='HELLO 世界' 走 e1
|
||||||
|
B1=False → e1=False e2=True xx='ABC' 走 e2
|
||||||
|
没接 A1 → 用声明里的默认值
|
||||||
|
|
||||||
|
【发现并修掉的两处"写不通"】
|
||||||
|
|
||||||
|
① 键必须加引号。用户原版是 JS 风格 `name:"...."`,
|
||||||
|
Python 里 `name` 会被当成变量名 → SyntaxError。
|
||||||
|
实测报错为 "SyntaxError: invalid syntax. Perhaps you forgot a comma?",
|
||||||
|
这句话完全看不出问题在哪,所以专门认出来并给出正确写法:
|
||||||
|
→ 看起来有键忘了加引号(name、input、output)。这是 Python,不是 JS:
|
||||||
|
要写 "name":、"input":、"output": …,不能写 name: …
|
||||||
|
|
||||||
|
② 声明是列表、访问是字典,对不上。
|
||||||
|
声明 `input: [{type,name,value}]` 是**列表**(列表才能表达顺序和类型),
|
||||||
|
但 run() 里写的是 `node["input"]["A1"]` —— **按名字取**。
|
||||||
|
实测报 "TypeError: list indices must be integers or slices, not str"。
|
||||||
|
解法:**引擎在跑之前把 input / output 换成按名字取的字典**,
|
||||||
|
声明的列表原样留着给引擎和界面读类型。
|
||||||
|
两边都用各自最自然的形式,中间转一次,用户不用知道。
|
||||||
|
|
||||||
|
【三条语义(要在文档和界面上写清楚)】
|
||||||
|
1. node["input"][名] 是**引擎填进去的实际值**,不是声明里的 value;
|
||||||
|
声明里的 value 只在"这根线没接"的时候用。
|
||||||
|
2. 多个 exec 输出**最多一个 True**(这就是多路分支):
|
||||||
|
恰好一个 → 走那条
|
||||||
|
都不 True → **停在原地** + 报警告(不猜、不顺走第一条,猜错了查不出来)
|
||||||
|
超过一个 → 报错(引擎没法替你选)
|
||||||
|
非 exec 输出不受限制,照常沿数据线传。
|
||||||
|
3. return 什么无所谓,引擎读的是 node["output"]。
|
||||||
|
|
||||||
|
【落地】
|
||||||
|
新增 android/kernel/custom_nodes.py:从 <数据目录>/nodes/*.py 加载,
|
||||||
|
规整引脚、校验类型、起子线程跑(10 秒超时,死循环不会把 App 卡死)。
|
||||||
|
界面要用的引脚定义也在里面(inputs / outputs / label / desc),
|
||||||
|
所以接入之后**界面能自动画出引脚**,不用在 Kotlin 里再写一份。
|
||||||
|
|
||||||
|
下一步:接进 meeting.py 变成一种节点类型(custom_xxx),
|
||||||
|
并把 inputs/outputs 喂给 /api/meeting/meta 让界面自动渲染。
|
||||||
|
|
||||||
|
【验证】
|
||||||
|
- custom_nodes.py 走通:加载 / 运行 / 写变量 / 记日志 / N 路分支 / 报错兜底
|
||||||
|
- 会议引擎回归 40/40,Node 与 Python 16/16 逐用例一致
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
会议模式:Python 节点(用户自己写代码拓展)+ 智能体调用节点工具
|
|
||||||
|
|
||||||
用户:"智能体可以调用节点工具。用户可以用py拓展节点。"
|
|
||||||
|
|
||||||
【1. Python 节点】
|
|
||||||
新节点类型 `py`。节点里写一段 Python,约定入口:
|
|
||||||
|
|
||||||
def run(ctx):
|
|
||||||
...
|
|
||||||
return "结果"
|
|
||||||
|
|
||||||
ctx 提供:
|
|
||||||
ctx.input 上游内容(数据线优先,没连就用 exec 上游的输出)
|
|
||||||
ctx.vars 变量表**只读快照**
|
|
||||||
ctx.set_var(名, 值) 写变量(真的写进会议变量表)
|
|
||||||
ctx.log(...) 记一条说明,会出现在结果界面的这一步里
|
|
||||||
node 这个节点本身
|
|
||||||
|
|
||||||
★ 为什么给"快照 + 显式 set_var"而不是直接给变量表:
|
|
||||||
直接给的话,用户随手 `ctx.vars['x'] = 1` 会以为写进去了,其实没有(那是副本),
|
|
||||||
然后到处找不到为什么没生效。要写就明确地写。
|
|
||||||
|
|
||||||
★ 沙箱的边界说清楚:这是**用户自己的代码、跑在用户自己的手机上**,
|
|
||||||
不是别人传过来的不可信代码。所以不做"假装安全"的沙箱
|
|
||||||
(Python 里没有真沙箱,做一半反而给人虚假的安全感),
|
|
||||||
但**必须**做两件事:超时和异常兜底。
|
|
||||||
实测:
|
|
||||||
正常 → 输出='处理完了:2 个字' 说明='收到: 起点'
|
|
||||||
除零 → ZeroDivisionError: division by zero
|
|
||||||
没写run → 代码里没有定义 run(ctx) 函数
|
|
||||||
死循环 → 超过 10 秒还没跑完(可能有死循环) ← App 不会卡死
|
|
||||||
|
|
||||||
【2. 智能体调用节点工具】
|
|
||||||
在智能体节点上勾选若干 Python 节点,它们就变成这个智能体可以调用的**工具**:
|
|
||||||
- 工具名取节点标题(清洗成合法标识符,重名加序号)
|
|
||||||
- 工具说明取 Python 节点上的「给智能体看的说明」
|
|
||||||
- 调用时把参数当 ctx.input 传进去,返回 run() 的输出
|
|
||||||
|
|
||||||
实现上并进**已有的工具系统**(tools_runtime.build_tool_defs / execute_tool),
|
|
||||||
不另起一套 —— 分两处的结果就是像之前几次那样"改了这边忘了那边"。
|
|
||||||
受限模式的白名单同样管得住它(走同一个 apply_security)。
|
|
||||||
|
|
||||||
【3. 界面】
|
|
||||||
Python 节点:引脚(exec 进出 + 数据进出)、深灰蓝配色、卡片上显示代码首行、
|
|
||||||
配置面板里有代码框(等宽、150dp 高)和「给智能体看的说明」。
|
|
||||||
|
|
||||||
【欠账,如实说】
|
|
||||||
智能体节点上"勾选可用工具"的那个 UI **还没做**(引擎侧已经通了、测过)。
|
|
||||||
这一轮我在那个 3600 行的 Kotlin 文件上反复卡住:PowerShell 的字符串替换
|
|
||||||
匹配失败时不报错、按行号剪贴又会把代码挪进别的函数,
|
|
||||||
光"改了没生效"就来回五六次,最后只能还原重做。
|
|
||||||
**下一步补这个勾选 UI**,在那之前想用节点工具得直接改会议 JSON。
|
|
||||||
|
|
||||||
【验证】
|
|
||||||
- 引擎回归 40/40,Node 与 Python 16/16 逐用例一致
|
|
||||||
- 会议 HTTP 13/13 ×2、语音 41/41、Markdown 19/19
|
|
||||||
- Python 节点:正常 / 报错 / 缺 run / 超时 四种情况都实测过
|
|
||||||
Reference in New Issue
Block a user