astra 模块参考
v2 插件从 'astra' 导入的全部接口:生命周期、存储、密钥、设置、网络、命令、事件、任务、通知、权限、数据查询、界面与网关钩子
插件只能通过 import … from 'astra' 使用宿主能力。每个接口都需要对应的权限;没有权限时调用抛出 AstraError,code 为 permission_denied。SDK 里有这些接口的完整类型(@astragate/plugin-sdk)。
错误
所有失败都是 AstraError:code 是 permission_denied、not_supported、invalid_argument、not_found、rate_limited、timeout、quota_exceeded、unavailable 之一,message 是说明。
环境
生命周期
清单的 activation 决定何时激活:onStartup,或第一次打开视图、执行命令、收到事件、运行任务时(onView:<id> 等)。
存储与密钥
网关钩子不能直接读存储;清单的 reads 列出的键会作为 ctx.shared 的快照交给钩子。
设置
config.get() 返回用户在设置表单里填的值(按清单 configuration 的默认值补全);config.onChange(fn) 在设置改变时调用。secret: true 的设置项不在这里,用 secrets.get 读取。
网络
http.fetch(url, { method, headers, body, timeoutMs }) 返回 { status, ok, url, headers, text(), json(), bytes() }。
- 只能访问
net:权限列出的 https 源(或net:{config.<设置>}指向的地址); - 不允许私有地址和本机地址;重定向每一跳都重新检查;
- 回复不超过 10 MB,默认 15 秒超时(
timeoutMs可设 0.1 – 120 秒)。
stream: true 时在收到响应头后就返回,响应体留在宿主按需读取:res.lines()(整行文本,适合 SSE 和 NDJSON)、res.stream()(字节块)、res.cancel();text() / json() / bytes() 读完整个流。每个插件同时最多 8 个流,每个流至多 100 MiB,60 秒无人读取即关闭。
开发插件例外:可以用 http 访问本机地址,但仍要在 net: 里声明它,并且服务端启动时设置了 ASTRA_PLUGIN_DEV_LOOPBACK=1。
命令、事件、任务、通知
加密与计时
crypto.sha256(data)、crypto.hmac(key, data, algorithm)、crypto.randomUUID()、crypto.randomBytes(n);timers.sleep(ms)、timers.setTimeout/clearTimeout/setInterval/clearInterval。沙箱里没有 Node 或浏览器的全局对象(fetch、process、window 等)。
数据查询
只读,需要对应权限,结果里从不含密钥:
界面
视图的 ctx:params、query、client(界面、语言、主题、宽度、位置、时区)、local(输入的值)、t、toast、navigate、back、openExternal、copy、download、focus、scrollTo、close、fail(表单字段错误)、setQuery、flush、refresh、confirm、prompt、pickFile、openSheet、openDialog、collection(name)(replace / append / prepend / update / remove / clear / setChildren)。
服务商(providers)
客户端(clients)
clients.register(id, { connect(input) }):input 是 { gateway: { url, v1, key }, model, models, agent },返回要写在模型旁边的键值(按键路径)。时限 5 秒。
网关钩子
gateway.defineHooks({ <id>: { onRequest, onUpstream, onEvent, onText, onResponse, onComplete } }),见网关钩子。钩子的 ctx:protocol、model、stream、path、client、token、requestId、options、shared、state、status、upstream、reject(status, message)、setHeader / removeHeader、emit、count、holdBack(n)、sha256。