@soiljs/cloud 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ximing
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,124 @@
1
- # Temporary Holding Version
1
+ # @soiljs/cloud
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 让本地或私网中的 Runtime 通过出站连接接入 Console,集中看进度、补传历史并按授权接收远程命令。它是 Layer 1 本地优先连接器,发布后的运行依赖只有 `@soiljs/spi`。协议校验助手在构建时从私有 `@soiljs/cloud-protocol` 打进 `dist`,安装方不安装该私有包。Console 或网络故障不阻塞本地执行,也不需要开放入站端口。
4
+
5
+ ## 安装与入口
6
+
7
+ ```sh
8
+ pnpm add @soiljs/cloud
9
+ # 宿主 Runtime 与持久存储按需安装
10
+ pnpm add @soiljs/agent @soiljs/models @soiljs/storage-local
11
+ ```
12
+
13
+ | 导出入口 | 用途 |
14
+ | --- | --- |
15
+ | `@soiljs/cloud` | `cloudConnector`、配置与结构化宿主/传输类型 |
16
+
17
+ 生产使用 Node.js ≥22.19 的原生 fetch/WebSocket,公开导出指向 `dist`。不在运行时依赖 Agent 或 models。
18
+
19
+ ## 最小可运行示例
20
+
21
+ 已部署 Console 后,由宿主设置 `SOIL_CONSOLE_URL` 与 `SOIL_RUNTIME_TOKEN`。下例以离线模型执行业务任务,网络不可用也能在本地完成;完整补传和审批演示见 [示例 04](../../examples/04-cloud-console.ts)。
22
+
23
+ ```ts
24
+ import { defineAgent, openRuntime } from "@soiljs/agent";
25
+ import { createFixtureModel } from "@soiljs/models/recording";
26
+ import { localStorage } from "@soiljs/storage-local";
27
+ import { cloudConnector } from "@soiljs/cloud";
28
+
29
+ const endpoint = process.env.SOIL_CONSOLE_URL;
30
+ const token = process.env.SOIL_RUNTIME_TOKEN;
31
+ if (!endpoint || !token) throw new Error("请配置 Console 地址与 Runtime Token");
32
+ const assistant = defineAgent({
33
+ id: "support",
34
+ version: "1",
35
+ model: createFixtureModel({
36
+ protocolId: "openai/chat",
37
+ model: "offline",
38
+ responses: ["本地任务完成"],
39
+ }),
40
+ instructions: "简洁回答。",
41
+ });
42
+ const cloud = cloudConnector({
43
+ endpoint,
44
+ token: () => token,
45
+ runtimeName: "orders-worker",
46
+ stateDir: "./.soil/cloud",
47
+ observability: {
48
+ payloadMode: "metadata_only",
49
+ redactFields: ["creditCard"],
50
+ artifacts: { mode: "none" },
51
+ },
52
+ commands: { allowRemoteApproval: true },
53
+ });
54
+ await using runtime = await openRuntime({
55
+ agents: [assistant],
56
+ storage: localStorage({ dir: "./.soil/runtime" }),
57
+ cloud,
58
+ // 示例仅允许同一 project 的命令;生产还需结合应用角色/主体策略。
59
+ authorizeCommand: async (envelope, turn) => ({
60
+ allowed: envelope.scope?.projectId === "orders" && turn.scope?.projectId === "orders",
61
+ }),
62
+ });
63
+ const session = await runtime.openSession(assistant, { scope: { projectId: "orders" } });
64
+ console.log(await (await session.send("处理本地任务")).wait());
65
+ ```
66
+
67
+ ## 配置速查与生命周期
68
+
69
+ | 配置 | 默认与约束 |
70
+ | --- | --- |
71
+ | `endpoint` / `token` | 显式配置;token 可为函数,每次 HTTP 与心跳重新读取 |
72
+ | `runtimeName` / `runtimeId` | 展示名与可选初始身份;身份生成后保存在 stateDir |
73
+ | `stateDir` | 默认 `./.soil-cloud`,重启保留;一目录只允许一个活连接器 |
74
+ | `observability.payloadMode` | 默认 `redacted_full`;可选 `metadata_only` |
75
+ | `observability.redactFields` | 额外字段名或点分路径,大小写不敏感 |
76
+ | `observability.streamRealtimeDeltas` | 显式开启且有 watch 才转发实时 delta |
77
+ | `observability.artifacts` | 默认 `none`;`auto_under_limit` 可配 maxBytes;`on_demand` 预留未实现 |
78
+ | `commands` | 所有远程能力默认 false |
79
+ | `configuration` | 默认 `{ mode: "code" }`,忽略远程快照 |
80
+ | `transport` | 可注入 fetch、WebSocket、时钟参数与随机数供测试 |
81
+
82
+ 本包不自动读取上述示例的环境变量,由宿主映射。结构化宿主提供 `storage`、`commands.dispatch` 与可选 `subscribeRealtime`;连接器只用公共端口,不读私有账本表。`open()` 调度初始化与网络任务,不等待 Console;`close()` 中止请求、取消订阅、关闭 socket 并收束后台任务。`openRuntime({ cloud })` 自动接实时订阅,无需再放入 hooks;不支持订阅的自定义宿主可注册观测 hooks。
83
+
84
+ `stateDir` 保存敏感命令意图、回执与签名快照;文件以 0600 原子替换并同步,目录以 0700 创建。损坏或身份不符只让连接器拒绝工作,不停止本地执行。不要跨进程共享目录或把目录当分布式锁;同一个 Outbox 也只能有一个 `cloud-console` 消费者。
85
+
86
+ ## 本地优先 Outbox 与脱敏
87
+
88
+ 持久事实唯一来源是已提交 Outbox,durable hook 不再次入队。后台每批读 `consumerId: "cloud-console"`、最多 200 条;留存缺口前置 `outbox.gap`,本地清洗后 gzip POST `/v1/ingest/events`。只接受 HTTP 200 且游标处于提交区间的确认,再推进 ack;允许部分事件确认,不允许部分 gap。失败指数退避加抖动,通常 1–60 秒。留存由存储适配器管理。
89
+
90
+ 默认 `redacted_full` 清除嵌套凭证字段、Bearer、常见 token/密钥与自定义字段,复制载荷而不修改本地事实;协议关联 ID 保留。`metadata_only` 仅保留状态、时间、工具、用量、错误码、身份与产物元数据,剔除对话和工具内容。规则无法识别所有未标注自由文本秘密,业务内容需严格留在本地时用 metadata_only。
91
+
92
+ `auto_under_limit` 独立上传小 UTF-8 文本/JSON,脱敏后重新计算摘要与大小,排除二进制、超限与 metadata_only 内容。产物失败不阻塞事件确认;队列最多 128 引用,近期去重缓存 1024 条。内容上传跨重启为尽力而为,持久事件仍按游标补传。
93
+
94
+ 实时只转发 `watch.start` 订阅的精确 Turn;默认缓冲 256 条、单条最多 262144 序列化字节、最多 128 个 watch。拥塞丢旧 delta,stop 清队列,重连清 watch,由 Console 重新订阅;不落盘、不反压执行,也不证明提交成功。
95
+
96
+ ## 远程命令、回执与恢复
97
+
98
+ 出站 `/v1/connect` 握手后拉取未决命令,30 秒心跳,三个心跳周期缺失或握手超时重连。token 轮换会重连但不打断 Turn;生产要求 HTTPS/WSS,只有 localhost/loopback 测试可例外,拒绝重定向防止转发凭证。服务端 last-seen 决定在线状态。
99
+
100
+ | 能力开关 | 管理命令 |
101
+ | --- | --- |
102
+ | `allowRemoteApproval` | approve |
103
+ | `allowRemoteCancel` | cancel |
104
+ | `allowRemoteSteer` | steer |
105
+ | `allowRemoteResume` | resume 与 resolve_unknown |
106
+
107
+ 关掉的能力产生持久 `rejected / unauthorized` 回执,不调用 Runtime。开启后仍通过 Runtime 的授权、scope、幂等与状态检查。收到未过期命令先落意图,再发送 `received_by_runtime`;Runtime 终态回执先持久化,再发送并重传至 `command.receipt_ack`。重启用原 commandId 重放未决意图,或仅重发已保存回执;连接器状态与 Runtime 账本必须共同保留。
108
+
109
+ `accepted_by_cloud`、`received_by_runtime`、`terminal_receipt` 是三个独立持久事实。传输确认不能擦除命令历史,已接收意图可在投递 TTL 之后完成,首次收到时已过期则忽略。取消被应用也不证明外部操作已撤销,没有 exactly-once;Runtime 命令持久去重是最终依据。
110
+
111
+ 混合配置需 `mode: "hybrid"`、逐 Agent 的 `allowedFields`、宿主 `verify(snapshot)` 与 `stage(snapshot)`。仅接受更新且签名通过的白名单值,拒绝工具/凭证/权限/scope/能力字段;缓存重启后再次验证并离线 stage。宿主仅应用于未来准入,活跃/等待/恢复 Turn 保持原版本与 configHash。
112
+
113
+ ## 深入阅读与本地校验
114
+
115
+ [在线 API](https://ximing.github.io/agent-foundation/#/api/cloud) · [云连接契约](../../docs/04-cloud-connector-protocol.md) · [离线审批演示](../../examples/04-cloud-console.ts)
116
+
117
+ ```sh
118
+ pnpm build
119
+ pnpm --filter @soiljs/cloud typecheck
120
+ pnpm --filter @soiljs/cloud exec tsup
121
+ pnpm exec vitest run packages/cloud/src/__tests__
122
+ ```
123
+
124
+ 测试使用本地 HTTP 与注入 WebSocket/宿主,包含真实 Runtime 的离线裁剪和远程审批;不建立供应商、真实 WSS、代理或子进程崩溃覆盖。用量脱敏仍保留 nullable 计数与 completeness,不补零。
@@ -0,0 +1,103 @@
1
+ import { DurableRuntimeEvent, RealtimeEvent, StorageAdapter, CommandEnvelope, CommandReceipt } from '@soiljs/spi';
2
+
3
+ /** Structural wire shapes. Published declarations must not import the private protocol package. */
4
+ interface RemoteCapabilities {
5
+ allowRemoteApproval: boolean;
6
+ allowRemoteCancel: boolean;
7
+ allowRemoteSteer: boolean;
8
+ allowRemoteResume: boolean;
9
+ }
10
+ interface AgentManifest {
11
+ agentId: string;
12
+ version: string;
13
+ configHash: string;
14
+ tools: readonly string[];
15
+ }
16
+ interface ConfigSnapshot {
17
+ agentId: string;
18
+ version: string;
19
+ configHash: string;
20
+ issuedAt: string;
21
+ signature: string;
22
+ values: Readonly<Record<string, unknown>>;
23
+ }
24
+
25
+ type PayloadMode = "metadata_only" | "redacted_full";
26
+ declare function redactText(value: string, fields?: readonly string[]): string;
27
+ /** Fresh JSON-compatible data; never mutates a ledger event. Cycles fail closed. */
28
+ declare function redact(value: unknown, fields?: readonly string[]): unknown;
29
+ declare function redactEvent<T extends DurableRuntimeEvent | RealtimeEvent>(event: T, mode: PayloadMode, fields: readonly string[]): T;
30
+
31
+ /** Structural Runtime integration: no runtime dependency on @soiljs/agent. */
32
+ interface CloudRuntime {
33
+ readonly storage: StorageAdapter;
34
+ readonly commands: {
35
+ dispatch(envelope: CommandEnvelope): Promise<CommandReceipt>;
36
+ };
37
+ subscribeRealtime?(listener: (event: RealtimeEvent) => void): () => void;
38
+ }
39
+ interface CloudWebSocket {
40
+ readonly readyState: number;
41
+ readonly bufferedAmount: number;
42
+ send(data: string): void;
43
+ close(): void;
44
+ addEventListener(type: "open" | "close" | "error" | "message", listener: (event: {
45
+ data?: unknown;
46
+ }) => void): void;
47
+ }
48
+ interface CloudConnectorConfig {
49
+ endpoint: string;
50
+ token: string | (() => string | Promise<string>);
51
+ runtimeId?: string;
52
+ runtimeName?: string;
53
+ /** Keep this directory across restarts; one live connector per directory. */
54
+ stateDir?: string;
55
+ agents?: readonly AgentManifest[];
56
+ commands?: Partial<RemoteCapabilities>;
57
+ observability?: {
58
+ redactFields?: readonly string[];
59
+ payloadMode?: PayloadMode;
60
+ streamRealtimeDeltas?: boolean;
61
+ realtimeBufferSize?: number;
62
+ maxRealtimeBytes?: number;
63
+ maxWatches?: number;
64
+ artifacts?: {
65
+ mode: "none";
66
+ } | {
67
+ mode: "auto_under_limit";
68
+ maxBytes: number;
69
+ };
70
+ };
71
+ configuration?: {
72
+ mode: "code";
73
+ } | {
74
+ mode: "hybrid";
75
+ allowedFields: Readonly<Record<string, readonly string[]>>;
76
+ verify(snapshot: ConfigSnapshot): boolean | Promise<boolean>;
77
+ /** Stage for FUTURE admissions only; the host must preserve Turn config pinning. */
78
+ stage(snapshot: ConfigSnapshot): void | Promise<void>;
79
+ };
80
+ transport?: {
81
+ fetch?: typeof globalThis.fetch;
82
+ webSocketFactory?: (url: string) => CloudWebSocket;
83
+ requestTimeoutMs?: number;
84
+ pollIntervalMs?: number;
85
+ retryBaseMs?: number;
86
+ retryMaxMs?: number;
87
+ heartbeatMs?: number;
88
+ receiptRetryMs?: number;
89
+ random?: () => number;
90
+ };
91
+ }
92
+ interface CloudConnector {
93
+ open(runtime: CloudRuntime): Promise<void>;
94
+ close(): Promise<void>;
95
+ onDurableEvent(event: DurableRuntimeEvent): void;
96
+ onRealtimeEvent(event: RealtimeEvent): void;
97
+ readonly runtimeId: string | undefined;
98
+ readonly connected: boolean;
99
+ }
100
+ /** Outbound control and export never await inside Runtime hooks. */
101
+ declare function cloudConnector(config: CloudConnectorConfig): CloudConnector;
102
+
103
+ export { type AgentManifest, type CloudConnector, type CloudConnectorConfig, type CloudRuntime, type CloudWebSocket, type ConfigSnapshot, type PayloadMode, type RemoteCapabilities, cloudConnector, redact, redactEvent, redactText };