WASM API v0.1(draft)
供 Netbook /
ain trace view/ 浏览器 sandbox 使用。目标:小、稳定、可测试。 实现:Rust +wasm-bindgen;单线程(v1);所有输入输出用 JSON 字符串/字节数组,避免复杂 ABI。
1. 类型
type Json = string;
interface StepResult {
step: number;
redex: [string, string];
rule: string;
hash: string;
metrics: Metrics;
}
interface RunResult {
steps: number;
hash: string;
normalForm: boolean;
metrics: Metrics;
}
interface Metrics {
interactions: number;
cells: number;
wires: number;
free: number;
maxParallelism?: number;
elapsedMs?: number;
}
interface Diagnostic {
severity: "error" | "warning";
code: string; // "E-LINEAR-01" ...
message: string;
span?: { start: number; end: number };
cell?: string;
port?: number;
help?: string;
}
2. 核心 API
class Net {
/** 从 JSON(specs/net-ir.md)创建;未知 agent 会报错。 */
static fromJSON(json: Json): Net;
/** 导出当前网(确定性排序)。 */
toJSON(): Json;
/** 单步;无活跃对返回 null。 */
step(): StepResult | null;
/** 跑最多 maxSteps;返回是否到达范式。 */
run(maxSteps: number): RunResult;
/** 跑到指定 step(用于时间旅行);超出燃料返回错误。 */
runUntil(step: number): RunResult;
/** 快照(二进制;含版本/校验)。 */
snapshot(): Uint8Array;
/** 恢复;版本不匹配抛错。 */
restore(bytes: Uint8Array): void;
/** 当前网 hash(sha256 hex)。 */
hash(): string;
/** 指标。 */
metrics(): Metrics;
/** 当前 trace(JSONL 字符串;可选,调试用)。 */
trace(): Json;
/** 释放 WASM 内存;之后对象不可用。 */
free(): void;
}
class Compiler {
/** 解析无类型 λ 项,编码为网。 */
static lambdaToNet(source: string, strategy?: "cbv" | "cbn" | "need" | "optimal"): Net;
/** 解析 Ainet Core/Flow(子集),编译为网。 */
static ainetToNet(source: string): Net;
/** 类型检查;返回诊断(不抛错)。 */
static check(source: string): Diagnostic[];
/** 从 Ainet 源生成 IR JSON(不运行)。 */
static compileToJSON(source: string): Json;
}
class Validator {
/** 校验网:端口唯一、类型、线性、规则覆盖。 */
static validate(net: Json): Diagnostic[];
/** 建议布局(分层/力导向)。 */
static layout(net: Json, width: number, height: number): { id: string; x: number; y: number }[];
}
3. 错误
- 构造函数/方法在不可恢复错误时抛
Error,message为 JSON:
{ "code": "E-IR-01", "message": "duplicate cell id: c3", "span": null }
- 可恢复的编译/校验错误通过
Diagnostic[]返回,不抛。 - 错误码表在
specs/errors.md(待补);前缀:E-IR,E-LINEAR,E-SESSION,E-EFFECT,E-BUDGET,E-DEADLOCK,E-FUEL,E-REPLAY。
4. 线程与内存
- v1:单线程;
step/run同步执行。 - 大网:调用方用
run(maxSteps)分片,避免长时间阻塞 UI;或放到 Web Worker。 - 内存:WASM 线性内存;
free()释放;不要在多线程共享同一Net。 - 快照:
snapshot()产生独立字节数组;可存 IndexedDB/URL(压缩后)。
5. JS 使用示例
import init, { Net, Compiler, Validator } from "@ainet/wasm";
await init();
const net = Net.fromJSON(irJson);
let r;
while ((r = net.step())) {
console.log(r.step, r.rule, r.hash);
}
console.log("normal form:", net.hash(), net.metrics());
const diagnostics = Validator.validate(net.toJSON());
if (diagnostics.some(d => d.severity === "error")) {
throw new Error(JSON.stringify(diagnostics));
}
const lambdaNet = Compiler.lambdaToNet("(λx.x x) (λy.y)", "optimal");
lambdaNet.run(10_000);
6. 稳定性
- 语义版本:新增方法/字段 → minor;改变行为/删除 → major。
Net.toJSON()的输出必须与specs/net-ir.md的 canonical 形式一致;Netbook 的 permalink 依赖它。- 任何 API 变更需更新
apps/netbook与ain trace view的适配层。