基因开发指南
本指南引导你完成 Rotifier 基因的完整生命周期——从创意构思到云端发布。
什么是基因?
Section titled “什么是基因?”基因是 Rotifer 协议中能力的原子单元。与传统的”技能”或”工具”不同,基因是活的实体:
- 具有 Phenotype(表型)——描述接口、域和适应度契约的类型化元数据
- 在 Arena 中竞争——同域基因按适应度分数正面较量
- 可以组合——通过形式代数(Seq、Par、Cond、Try)组合基因
- 在沙箱中运行——WASM 隔离确保内存安全、资源受限的执行
第 1 步:初始化项目
Section titled “第 1 步:初始化项目”npx @rotifer/playground init my-projectcd my-project项目会预装 5 个创世基因,作为 Arena 中的基线。
第 2 步:创建基因
Section titled “第 2 步:创建基因”创建基因目录和必要文件:
mkdir -p genes/my-translator2.1 编写 Express 函数
Section titled “2.1 编写 Express 函数”每个基因必须导出一个 express() 函数——基因调用的唯一入口。
export async function express(input: { text: string; targetLang: string;}): Promise<{ translated: string; confidence: number }> { const translated = await translateText(input.text, input.targetLang); return { translated, confidence: 0.95, };}
async function translateText(text: string, lang: string): Promise<string> { return `[${lang}] ${text}`;}express() 的关键规则:
- 必须是命名导出(非默认导出)
- 接受单个输入对象
- 返回非空的结果对象
- 应优雅地处理错误
2.2 定义 Phenotype
Section titled “2.2 定义 Phenotype”Phenotype 描述基因的接口契约。
{ "domain": "text.translate", "inputSchema": { "type": "object", "properties": { "text": { "type": "string", "description": "要翻译的文本" }, "targetLang": { "type": "string", "description": "目标语言代码" } }, "required": ["text", "targetLang"] }, "outputSchema": { "type": "object", "properties": { "translated": { "type": "string" }, "confidence": { "type": "number", "minimum": 0, "maximum": 1 } }, "required": ["translated", "confidence"] }, "version": "0.1.0", "fidelity": "Wrapped", "transparency": "Open"}Phenotype 字段说明:
| 字段 | 说明 |
|---|---|
domain | 功能域——同域基因在 Arena 中竞争 |
inputSchema | 输入验证的 JSON Schema |
outputSchema | 输出验证的 JSON Schema |
version | 语义版本号 |
fidelity | Wrapped(API 调用)、Hybrid(混合)或 Native(纯 WASM) |
transparency | Open(源码可审计)或 Opaque |
或使用 rotifer wrap 自动生成:
rotifer wrap my-translator --domain text.translate第 3 步:测试基因
Section titled “第 3 步:测试基因”rotifer test my-translator测试套件自动执行:
- 验证 Phenotype 是否符合基因标准
- 使用生成的测试输入调用
express() - 检查输出是否匹配
outputSchema - 验证错误处理
- 计算初步适应度分数
第 4 步:编译为 WASM
Section titled “第 4 步:编译为 WASM”rotifer compile my-translator编译管线:TypeScript → esbuild → WASI shim → Javy → IR 注入器
编译后,基因的保真度从 Wrapped 升级为 Native。
第 5 步:提交到 Arena
Section titled “第 5 步:提交到 Arena”rotifer arena submit my-translator第 6 步:发布到云端
Section titled “第 6 步:发布到云端”rotifer loginrotifer publish my-translator第 7 步:参与 Cloud Arena 竞争
Section titled “第 7 步:参与 Cloud Arena 竞争”rotifer arena submit my-translator --cloudrotifer arena list --cloud -d text.translate基因开发最佳实践
Section titled “基因开发最佳实践”使用点分隔的层级名称:search.web、file.read、code.format、text.translate
Schema 设计
Section titled “Schema 设计”- 使用 JSON Schema draft 2020-12
- 始终指定
required字段 - 为每个属性添加
description - 对数值约束使用
minimum/maximum
从 express() 抛出类型化错误:
export async function express(input: { query: string }) { if (!input.query?.trim()) { throw new Error("INVALID_INPUT: query 必须为非空字符串"); } // ...}- 最小化冷启动时间
- 缓存昂贵的资源
- 在验证失败时提前返回