iii-core-primitives

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Core Primitives

核心原语

iii has three top-level primitives:
  • Function: a named unit of work such as
    orders::validate
  • Trigger: an event source bound to a function
  • Worker: a process that connects to the engine and executes functions
Use
::
in function IDs, leading slashes in HTTP
api_path
, and
expression
for cron config.
iii 包含三个顶层原语:
  • Function:命名工作单元,例如
    orders::validate
  • Trigger:绑定到函数的事件源
  • Worker:连接到引擎并执行函数的进程
函数ID中使用
::
,HTTP
api_path
中使用前导斜杠,cron配置使用
expression

Function Registration

函数注册

Register local handlers when you control the implementation. Register HTTP-invoked functions when iii should call an existing external endpoint.
ShapeUse for
registerFunction(id, handler, options?)
Local worker code
registerFunction(id, HttpInvocationConfig, options?)
Existing HTTP services
registerTrigger({ type, function_id, config, metadata? })
Binding an event source
trigger({ function_id, payload, action?, timeout? })
Calling any function by ID
Functions and triggers can carry metadata for ownership, discovery, and generated skills. Do not put secrets in metadata.
当你控制实现逻辑时,注册本地处理器;当iii需要调用现有外部端点时,注册HTTP调用函数。
形式适用场景
registerFunction(id, handler, options?)
本地Worker代码
registerFunction(id, HttpInvocationConfig, options?)
现有HTTP服务
registerTrigger({ type, function_id, config, metadata? })
绑定事件源
trigger({ function_id, payload, action?, timeout? })
通过ID调用任意函数
函数和触发器可携带元数据用于归属标识、服务发现和生成技能。请勿在元数据中存储密钥。

Workers and Registry

Worker与注册表

A worker is any process that connects to the engine and registers functions or trigger types. There are two common paths:
TaskUse
Create your own workerWrite SDK code that calls
registerWorker
,
registerFunction
, and
registerTrigger
Add an existing capabilityBrowse
https://workers.iii.dev/
, then run
iii worker add <name>
Pin a worker version
iii worker add <name>@<version>
Add an OCI worker
iii worker add ghcr.io/org/worker:tag
Add a local worker during development
iii worker add ./workers/my-worker
Replay installed workersCommit
iii.lock
, then run
iii worker sync
The public worker registry at
workers.iii.dev
is for installable workers such as HTTP, state, queue, pub/sub, cron, observability, sandbox, database, shell, console, and other capability workers. Those workers may ship their own function-level skills; do not duplicate every capability as a top-level iii skill.
Worker是任何连接到引擎并注册函数或触发器类型的进程。常见使用路径有两种:
任务用法
创建自定义Worker编写调用
registerWorker
registerFunction
registerTrigger
的SDK代码
添加现有能力浏览
https://workers.iii.dev/
,然后运行
iii worker add <name>
固定Worker版本
iii worker add <name>@<version>
添加OCI Worker
iii worker add ghcr.io/org/worker:tag
开发期间添加本地Worker
iii worker add ./workers/my-worker
重放已安装Worker提交
iii.lock
,然后运行
iii worker sync
workers.iii.dev
上的公共Worker注册表用于可安装的Worker,例如HTTP、状态、队列、发布/订阅、定时任务、可观测性、沙箱、数据库、Shell、控制台及其他能力Worker。这些Worker可能自带函数级技能;无需将每个能力都复制为顶层iii技能。

Worker Manifest

Worker清单

Use
iii.worker.yaml
when iii should start a local worker project:
yaml
name: math-worker
runtime:
  kind: python
  package_manager: pip
  entry: math_worker.py
scripts:
  install: "pip install -r requirements.txt"
  start: "python math_worker.py"
The manifest describes how to start the process. Once running, the WebSocket connection and function registrations are what make the worker part of iii.
当iii需要启动本地Worker项目时,使用
iii.worker.yaml
yaml
name: math-worker
runtime:
  kind: python
  package_manager: pip
  entry: math_worker.py
scripts:
  install: "pip install -r requirements.txt"
  start: "python math_worker.py"
该清单描述了如何启动进程。进程运行后,WebSocket连接和函数注册会将Worker纳入iii体系。

Live Engine Registry

实时引擎注册表

The engine keeps a live registry of connected workers, registered functions, triggers, and trigger types. Read it through the built-in discovery functions:
FunctionReturns
engine::workers::list
Connected workers and metrics
engine::functions::list
Registered functions
engine::triggers::list
Registered triggers
engine::trigger-types::list
Advertised trigger types and schemas
For topology changes, bind triggers to
engine::workers-available
or
engine::functions-available
.
引擎维护着已连接Worker、已注册函数、触发器和触发器类型的实时注册表。可通过内置发现函数读取:
函数返回内容
engine::workers::list
已连接Worker及指标
engine::functions::list
已注册函数
engine::triggers::list
已注册触发器
engine::trigger-types::list
已声明的触发器类型及Schema
若需处理拓扑变更,可将触发器绑定到
engine::workers-available
engine::functions-available

Built-In Trigger Shapes

内置触发器形式

Trigger typeRegistration configHandler payload
http
{ api_path: "/orders/:id", http_method: "POST" }
{ query_params, path_params, headers, path, method, body }
cron
{ expression: "0 0 9 * * * *" }
{ trigger, job_id, scheduled_time, actual_time }
durable:subscriber
{ topic: "payments" }
The queued message payload
subscribe
{ topic: "orders.created" }
The published event payload
state
{ scope: "orders", key?: "order-123" }
{ event_type, scope, key, old_value, new_value }
stream
{ stream_name, group_id, item_id? }
Stream event details
log
{ level: "warn" }
OpenTelemetry-style log data
Add
condition_function_id
to built-in trigger config when the handler should only run if a boolean condition function returns
true
.
触发器类型注册配置处理器负载
http
{ api_path: "/orders/:id", http_method: "POST" }
{ query_params, path_params, headers, path, method, body }
cron
{ expression: "0 0 9 * * * *" }
{ trigger, job_id, scheduled_time, actual_time }
durable:subscriber
{ topic: "payments" }
队列消息负载
subscribe
{ topic: "orders.created" }
已发布事件负载
state
{ scope: "orders", key?: "order-123" }
{ event_type, scope, key, old_value, new_value }
stream
{ stream_name, group_id, item_id? }
流事件详情
log
{ level: "warn" }
OpenTelemetry风格日志数据
当处理器仅在布尔条件函数返回
true
时才需运行,可在内置触发器配置中添加
condition_function_id

Invocation Modes

调用模式

ModeShapeUse when
Sync
trigger({ function_id, payload })
The caller needs the result
Void
TriggerAction.Void()
Optional side effect, no result needed
Enqueue
TriggerAction.Enqueue({ queue })
Reliable async work with queue policy
Use enqueue for work that must complete with retries. Use void for analytics, notifications, and other non-critical side effects.
模式形式适用场景
同步(Sync)
trigger({ function_id, payload })
调用方需要结果
无返回(Void)
TriggerAction.Void()
可选副作用,无需结果
入队(Enqueue)
TriggerAction.Enqueue({ queue })
需重试的可靠异步任务
入队模式适用于必须完成且需重试的任务;无返回模式适用于分析、通知及其他非关键副作用。

Code Examples

代码示例

TypeScript

TypeScript

typescript
import { registerWorker, TriggerAction } from "iii-sdk";

const iii = registerWorker("ws://localhost:49134", { workerName: "orders-worker" });

iii.registerFunction("orders::validate", async (order) => {
  if (!order.id) throw new Error("missing order id");
  return { ...order, valid: true };
});

iii.registerFunction("orders::process", async (order) => {
  const validated = await iii.trigger({ function_id: "orders::validate", payload: order });
  await iii.trigger({
    function_id: "orders::charge",
    payload: validated,
    action: TriggerAction.Enqueue({ queue: "payments" }),
  });
  return { accepted: true, orderId: validated.id };
});

iii.registerTrigger({
  type: "http",
  function_id: "orders::process",
  config: { api_path: "/orders", http_method: "POST" },
});
typescript
import { registerWorker, TriggerAction } from "iii-sdk";

const iii = registerWorker("ws://localhost:49134", { workerName: "orders-worker" });

iii.registerFunction("orders::validate", async (order) => {
  if (!order.id) throw new Error("missing order id");
  return { ...order, valid: true };
});

iii.registerFunction("orders::process", async (order) => {
  const validated = await iii.trigger({ function_id: "orders::validate", payload: order });
  await iii.trigger({
    function_id: "orders::charge",
    payload: validated,
    action: TriggerAction.Enqueue({ queue: "payments" }),
  });
  return { accepted: true, orderId: validated.id };
});

iii.registerTrigger({
  type: "http",
  function_id: "orders::process",
  config: { api_path: "/orders", http_method: "POST" },
});

Python

Python

python
from iii import register_worker

iii = register_worker("ws://localhost:49134")

def validate(order):
    if not order.get("id"):
        raise ValueError("missing order id")
    return {**order, "valid": True}

def process(order):
    validated = iii.trigger({"function_id": "orders::validate", "payload": order})
    iii.trigger({
        "function_id": "orders::charge",
        "payload": validated,
        "action": {"type": "enqueue", "queue": "payments"},
    })
    return {"accepted": True, "orderId": validated["id"]}

iii.register_function("orders::validate", validate)
iii.register_function("orders::process", process)
iii.register_trigger({
    "type": "http",
    "function_id": "orders::process",
    "config": {"api_path": "/orders", "http_method": "POST"},
})
python
from iii import register_worker

iii = register_worker("ws://localhost:49134")

def validate(order):
    if not order.get("id"):
        raise ValueError("missing order id")
    return {**order, "valid": True}

def process(order):
    validated = iii.trigger({"function_id": "orders::validate", "payload": order})
    iii.trigger({
        "function_id": "orders::charge",
        "payload": validated,
        "action": {"type": "enqueue", "queue": "payments"},
    })
    return {"accepted": True, "orderId": validated["id"]}

iii.register_function("orders::validate", validate)
iii.register_function("orders::process", process)
iii.register_trigger({
    "type": "http",
    "function_id": "orders::process",
    "config": {"api_path": "/orders", "http_method": "POST"},
})

Rust

Rust

rust
use iii_sdk::{
    register_worker, InitOptions, RegisterFunction, RegisterTriggerInput, TriggerAction,
    TriggerRequest,
};
use serde_json::json;

let iii = register_worker("ws://127.0.0.1:49134", InitOptions::default());

iii.register_function(RegisterFunction::new("orders::validate", |order: serde_json::Value| {
    if order["id"].is_null() {
        return Err("missing order id".into());
    }
    Ok(json!({ "valid": true, "order": order }))
}))?;

let process_client = iii.clone();
iii.register_function(RegisterFunction::new_async("orders::process", move |order: serde_json::Value| {
    let iii = process_client.clone();
    async move {
        let validated = iii.trigger(TriggerRequest::new("orders::validate", order)).await?;
        iii.trigger(TriggerRequest {
            function_id: "orders::charge".into(),
            payload: validated.clone(),
            action: Some(TriggerAction::Enqueue { queue: "payments".into() }),
            timeout_ms: None,
        }).await?;
        Ok(json!({ "accepted": true, "order": validated }))
    }
}))?;

iii.register_trigger(RegisterTriggerInput {
    trigger_type: "http".into(),
    function_id: "orders::process".into(),
    config: json!({ "api_path": "/orders", "http_method": "POST" }),
    metadata: None,
})?;
rust
use iii_sdk::{
    register_worker, InitOptions, RegisterFunction, RegisterTriggerInput, TriggerAction,
    TriggerRequest,
};
use serde_json::json;

let iii = register_worker("ws://127.0.0.1:49134", InitOptions::default());

iii.register_function(RegisterFunction::new("orders::validate", |order: serde_json::Value| {
    if order["id"].is_null() {
        return Err("missing order id".into());
    }
    Ok(json!({ "valid": true, "order": order }))
}))?;

let process_client = iii.clone();
iii.register_function(RegisterFunction::new_async("orders::process", move |order: serde_json::Value| {
    let iii = process_client.clone();
    async move {
        let validated = iii.trigger(TriggerRequest::new("orders::validate", order)).await?;
        iii.trigger(TriggerRequest {
            function_id: "orders::charge".into(),
            payload: validated.clone(),
            action: Some(TriggerAction::Enqueue { queue: "payments".into() }),
            timeout_ms: None,
        }).await?;
        Ok(json!({ "accepted": true, "order": validated }))
    }
}))?;

iii.register_trigger(RegisterTriggerInput {
    trigger_type: "http".into(),
    function_id: "orders::process".into(),
    config: json!({ "api_path": "/orders", "http_method": "POST" }),
    metadata: None,
})?;

Advanced Primitive Patterns

高级原语模式

  • Custom triggers: use
    registerTriggerType({ id, description }, handler)
    when the event source is not built in. Keep listener setup in
    registerTrigger
    and cleanup in
    unregisterTrigger
    .
  • Channels: use
    createChannel()
    for binary or streaming data that should not be serialized into JSON payloads. Pass
    readerRef
    or
    writerRef
    through a function payload.
  • HTTP-invoked functions: use
    HttpInvocationConfig
    for legacy APIs, third-party endpoints, or immutable services. Use environment variable names for auth fields, not raw secrets.
  • Schemas: Rust can derive request/response schemas with
    schemars::JsonSchema
    ; Python can use type hints or Pydantic; Node can pass JSON Schema manually.
  • 自定义触发器:当事件源非内置时,使用
    registerTriggerType({ id, description }, handler)
    。将监听器设置放在
    registerTrigger
    中,清理逻辑放在
    unregisterTrigger
    中。
  • 通道:对于不应序列化为JSON负载的二进制或流式数据,使用
    createChannel()
    。通过函数负载传递
    readerRef
    writerRef
  • HTTP调用函数:对于遗留API、第三方端点或不可变服务,使用
    HttpInvocationConfig
    。认证字段使用环境变量名,而非原始密钥。
  • Schema:Rust可通过
    schemars::JsonSchema
    派生请求/响应Schema;Python可使用类型提示或Pydantic;Node可手动传入JSON Schema。

When to Use

使用场景

  • Use this skill for function registration, trigger binding, trigger payload shapes, invocation mode decisions, worker creation, worker registry access, trigger conditions, custom trigger types, channels, and HTTP-invoked functions.
  • Use this when a task spans TypeScript, Python, or Rust examples for the same iii primitive.
  • 当需要处理函数注册、触发器绑定、触发器负载格式、调用模式选择、Worker创建、Worker注册表访问、触发器条件、自定义触发器类型、通道及HTTP调用函数时,使用本技能。
  • 当任务涉及TypeScript、Python或Rust中相同iii原语的示例时,使用本技能。

Boundaries

边界说明

  • For engine ports, adapters, queue retry policy, worker manager, RBAC listeners, and deployment config, use
    iii-engine-config
    .
  • For SDK-specific package exports and language caveats, use
    iii-sdk-reference
    .
  • For complete backend designs such as workflows, CQRS, agentic systems, and reactive apps, use
    iii-architecture-patterns
    .
  • For failed invocations, timeouts, RBAC denials, and retryability, use
    iii-error-handling
    .
  • Worker-backed capability details live with the worker docs, not as top-level iii skills.
  • 若涉及引擎端口、适配器、队列重试策略、Worker管理器、RBAC监听器及部署配置,请使用
    iii-engine-config
  • 若涉及特定SDK的包导出及语言注意事项,请使用
    iii-sdk-reference
  • 若涉及完整后端设计(如工作流、CQRS、智能代理系统及响应式应用),请使用
    iii-architecture-patterns
  • 若涉及调用失败、超时、RBAC拒绝及重试机制,请使用
    iii-error-handling
  • Worker支持的能力详情请参考Worker文档,而非顶层iii技能。