@soiljs/cloud 0.0.0-stage → 0.2.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,193 @@
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`、`createTraceReporter`、配置与结构化宿主/传输类型 |
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` | 展示名与持久模式的可选初始身份;临时模式忽略 runtimeId,始终生成新身份 |
73
+ | `stateDir` | 省略时仅用内存;提供时重启保留,一目录只允许一个活连接器 |
74
+ | `ephemeral` | `true` 强制仅用内存,忽略 stateDir/runtimeId;适配 memoryStorage 每次启动重置的事件序号 |
75
+ | `observability.payloadMode` | 默认 `redacted_full`;可选 `metadata_only` |
76
+ | `observability.redactFields` | 额外字段名或点分路径,大小写不敏感 |
77
+ | `observability.streamRealtimeDeltas` | 显式开启且有 watch 才转发实时 delta |
78
+ | `observability.artifacts` | 默认 `none`;`auto_under_limit` 可配 maxBytes;`on_demand` 预留未实现 |
79
+ | `commands` | 所有远程能力默认 false |
80
+ | `configuration` | 默认 `{ mode: "code" }`,忽略远程快照 |
81
+ | `transport` | 可注入 fetch、WebSocket、时钟参数与随机数供测试 |
82
+
83
+ 本包不自动读取上述示例的环境变量,由宿主映射。结构化宿主提供 `storage`、`commands.dispatch` 与可选 `subscribeRealtime`;连接器只用公共端口,不读私有账本表。`open()` 调度初始化与网络任务,不等待 Console;`close()` 中止请求、取消订阅、关闭 socket,最多等待 100ms 收束后台任务,不等待不响应中止的宿主回调。连接器 close 后不可重新 open,请创建新实例;已经进入 Runtime 的命令不会被 close 撤销。`openRuntime({ cloud })` 自动接实时订阅,无需再放入 hooks;不支持订阅的自定义宿主可注册观测 hooks。
84
+
85
+ `flush(timeoutMs = 5000): Promise<CloudFlushResult>` 等待 Outbox 确认,返回 `{ drained, remaining }`;remaining 是最近读取的积压下界(最多 1000 条事件及一个 gap),无法读取时为 null。它不保证实时 delta、产物或命令回执全部完成,也不停止宿主产生新事件。关闭前先停止业务准入、等待执行完成,再 `await cloud.flush(3000)`,最后 `await runtime.close()`;也可 `await cloud.close({ flushTimeoutMs: 3000 })`。超时不推进未确认游标,持久模式下可在下次启动补传。
86
+
87
+ 提供 `stateDir` 时保存敏感命令意图、回执与签名快照;文件以 0600 原子替换并同步,目录以 0700 创建。损坏或身份不符只让连接器拒绝工作,不停止本地执行。不要跨进程共享目录或把目录当分布式锁;同一个 Outbox 也只能有一个 `cloud-console` 消费者。临时模式完全不访问状态目录,命令意图/回执/快照仅保留在本进程,不能提供跨重启恢复;持久 Outbox 应继续配置持久 stateDir。
88
+
89
+ ```ts
90
+ // memoryStorage host: no stateDir, fresh runtimeId for every connector instance.
91
+ const cloud = cloudConnector({
92
+ endpoint: "https://af.aimo.plus",
93
+ token: process.env.SOIL_RUNTIME_TOKEN!,
94
+ observability: { payloadMode: "redacted_full", redactFields: ["userEmail"] },
95
+ // All remote command permissions default to false.
96
+ });
97
+ ```
98
+
99
+ ## 本地优先 Outbox 与脱敏
100
+
101
+ 持久事实唯一来源是已提交 Outbox,durable hook 不再次入队。后台每批读 `consumerId: "cloud-console"`、最多 200 条;留存缺口前置 `outbox.gap`,本地清洗后 gzip POST `/v1/ingest/events`。只接受 HTTP 200 且游标处于提交区间的确认,再推进 ack;允许部分事件确认,不允许部分 gap。失败指数退避加抖动,通常 1–60 秒。留存由存储适配器管理。
102
+
103
+ 默认 `redacted_full` 清除嵌套凭证字段、Bearer、常见 token/密钥与自定义字段,复制载荷而不修改本地事实;协议关联 ID 保留。`metadata_only` 仅保留状态、时间、工具、用量、错误码、身份与产物元数据,剔除对话和工具内容。规则无法识别所有未标注自由文本秘密,业务内容需严格留在本地时用 metadata_only。
104
+
105
+ `turn.paused.reason` 的 `waiting_approval` / `waiting_child` / `waiting_resolution` 与 stopReason/status 保留在 metadata_only,供 Console 正确投影等待态。清洗覆盖握手清单、展示名与事件字符串;凭证字段里的值也从同一载荷的其他自由文本副本中移除。配置 redactFields 可使用字段名或路径后缀;认证所需的 Runtime token 仍必须出现在 HTTPS Authorization / WSS hello 中。
106
+
107
+ ## Structured Traces 与 Usage(独立采集通道)
108
+
109
+ `createTraceReporter(options: CloudTraceReporterOptions): CloudTraceReporter` 不需要 Runtime,可用于独立模型调用或多步骤 Agent。使用拥有 `traces:write` 的 `soil_ing_*` 采集密钥,POST `/api/ingest/traces`;它与 Runtime token 和 `/v1/ingest/events` 分开。Console 从 generation span 的 usage/physicalAttempts 生成 Usage 记录,无单独 `/api/ingest/usage` 请求;`/traces` 和 `/usage` 是产品读视图。旧架构文档的“通道 B”指管理命令,本文的 Structured Trace reporter 是额外的独立采集接口。
110
+
111
+ ```ts
112
+ import { createTraceReporter } from "@soiljs/cloud";
113
+
114
+ const traces = createTraceReporter({
115
+ endpoint: "https://af.aimo.plus",
116
+ token: process.env.SOIL_INGEST_TOKEN!,
117
+ producer: "vital",
118
+ payloadMode: "redacted_full", // default
119
+ redactFields: ["decryptedApiKey", "headers.x-private-key"],
120
+ maxQueueSize: 1000,
121
+ maxBatchSize: 20,
122
+ onDrop: ({ count, reason }) => console.warn("trace dropped", count, reason),
123
+ });
124
+
125
+ // Call after the business result is available; report() never waits for HTTP.
126
+ traces.report({
127
+ externalTraceId: "request-123", updateId: "request-123-v1", revision: 1,
128
+ name: "completeText", startedAt: "2026-11-28T00:00:00Z",
129
+ endedAt: "2026-11-28T00:00:01Z", status: "completed",
130
+ tags: ["vital"], metadata: { userId: "host-generated-pseudonymous-id" },
131
+ input: "Summarize this note", output: "Summary",
132
+ spans: [{
133
+ spanId: "generation-1", kind: "generation", name: "completeText",
134
+ attributes: {
135
+ callId: "model-call-123", modelId: "model-name", providerId: "provider-name",
136
+ nativeParameters: { temperature: 0.3 },
137
+ inputMessages: [{ role: "user", content: "Summarize this note" }],
138
+ outputMessage: { role: "assistant", content: "Summary" },
139
+ finishReason: "stop", requestStage: "response-received",
140
+ usage: { inputTokens: 10, outputTokens: 5, completeness: "complete" },
141
+ physicalAttempts: [{ physicalAttemptIndex: 1,
142
+ usage: { inputTokens: 10, outputTokens: 5, completeness: "complete" } }],
143
+ },
144
+ }],
145
+ });
146
+ await traces.close({ flushTimeoutMs: 3000 });
147
+ ```
148
+
149
+ 多步骤 Agent 在同一 `spans` 数组里添加 `{ kind: "agent", spanId, name, attributes: { agentId, stopReason, stepCount } }`,generation/tool 的 `parentSpanId` 指向该 agent;tool attributes 支持 `parsedArgs`、`adapterResult`、`businessData`、`modelPresentation`。Trace 顶层支持 `hostSessionId`、`hostRunId`、`sessionNamespace`、tags/metadata;trace/span 的 `input`、`output`、`error` 进入清洗后的 canonical inline contentRef(Error 的 name/message/stack/cause 也会清洗)。宿主负责把用户身份映射为伪名,reporter 不自动推测或散列用户标识。
150
+
151
+ 每次 `report(trace: CloudTraceInput): boolean` 提交完整 replace 快照;更新同一 trace 时增加 revision 并使用新的 updateId,保留 spanId/callId/physicalAttemptIndex。updateId 省略时在入队时生成一次;span revision 默认继承 trace revision,callId 缺省为 externalTraceId + spanId。不要对不同物理调用复用 callId;服务端按 producer/callId/physicalAttemptIndex 去重用量。重试不会生成新身份或重新执行模型/工具。
152
+
153
+ 队列包含在途项,默认 1000 项,每批 20(上限 100),每项序列化最多 256KiB(maxItemBytes),每请求最多 4MiB。队列满时丢弃新项;`pendingCount`、`droppedCount` 和隔离异常的 `onDrop` 回调报告结果,不携带原始内容。单个 input/output 超过 64KiB canonical envelope 时标记 unavailable,不伪造 payloadsComplete,也不自动上传 blob。队列仅在进程内保存,进程退出会丢失,不能替代持久 Outbox。
154
+
155
+ HTTP 200/202/207 必须含匹配 updateId/index 的逐项 receipt;只重试 retryable 拒绝项。网络错误、超时、408、429、5xx 指数退避(默认 1–60 秒),尊重 Retry-After;413 拆批,单项仍超限则丢弃;401 及其他永久拒绝计入 droppedCount,不无限重试无效凭证。`token` 可为函数,`fetch` 可注入代理/TLS 实现;仅允许 HTTPS 或 loopback HTTP,禁止重定向。
156
+
157
+ `flush(timeoutMs = 5000): Promise<{ drained: boolean; remaining: number }>` 有界等待并在超时中止当前请求,保留队列以便后续重试;drained 表示队列为空,需结合 droppedCount 区分成功与丢弃。`close({ flushTimeoutMs? })` 拒绝新项,可先有界 flush,再中止并丢弃剩余队列;省略 flushTimeoutMs 时快速关闭。自定义 fetch/token 即使忽略 AbortSignal 也不能阻塞 close。
158
+
159
+ 默认 redacted_full 保留清洗后的调试正文;metadata_only 丢弃 input/output/error、任意 metadata/tags、模型参数及工具内容,保留标识、状态和用量。不要把未标注的秘密放入名称或身份字段;把自定义秘密字段加入 redactFields。认证所需的 ingest token 是 Authorization 中唯一有意保留的凭证。
160
+
161
+ `auto_under_limit` 独立上传小 UTF-8 文本/JSON,脱敏后重新计算摘要与大小,排除二进制、超限与 metadata_only 内容。产物失败不阻塞事件确认;队列最多 128 引用,近期去重缓存 1024 条。内容上传跨重启为尽力而为,持久事件仍按游标补传。
162
+
163
+ 实时只转发 `watch.start` 订阅的精确 Turn;默认缓冲 256 条、单条最多 262144 序列化字节、最多 128 个 watch。拥塞丢旧 delta,stop 清队列,重连清 watch,由 Console 重新订阅;不落盘、不反压执行,也不证明提交成功。
164
+
165
+ ## 远程命令、回执与恢复
166
+
167
+ 出站 `/v1/connect` 握手后拉取未决命令,30 秒心跳,三个心跳周期缺失或握手超时重连。token 轮换会重连但不打断 Turn;生产要求 HTTPS/WSS,只有 localhost/loopback 测试可例外,拒绝重定向防止转发凭证。服务端 last-seen 决定在线状态。
168
+
169
+ | 能力开关 | 管理命令 |
170
+ | --- | --- |
171
+ | `allowRemoteApproval` | approve |
172
+ | `allowRemoteCancel` | cancel |
173
+ | `allowRemoteSteer` | steer |
174
+ | `allowRemoteResume` | resume 与 resolve_unknown |
175
+
176
+ 关掉的能力产生持久 `rejected / unauthorized` 回执,不调用 Runtime。开启后仍通过 Runtime 的授权、scope、幂等与状态检查。收到未过期命令先落意图,再发送 `received_by_runtime`;Runtime 终态回执先持久化,再发送并重传至 `command.receipt_ack`。重启用原 commandId 重放未决意图,或仅重发已保存回执;连接器状态与 Runtime 账本必须共同保留。
177
+
178
+ `accepted_by_cloud`、`received_by_runtime`、`terminal_receipt` 是三个独立持久事实。传输确认不能擦除命令历史,已接收意图可在投递 TTL 之后完成,首次收到时已过期则忽略。取消被应用也不证明外部操作已撤销,没有 exactly-once;Runtime 命令持久去重是最终依据。
179
+
180
+ 混合配置需 `mode: "hybrid"`、逐 Agent 的 `allowedFields`、宿主 `verify(snapshot)` 与 `stage(snapshot)`。仅接受更新且签名通过的白名单值,拒绝工具/凭证/权限/scope/能力字段;缓存重启后再次验证并离线 stage。宿主仅应用于未来准入,活跃/等待/恢复 Turn 保持原版本与 configHash。
181
+
182
+ ## 深入阅读与本地校验
183
+
184
+ [在线 API](https://ximing.github.io/agent-foundation/#/api/cloud) · [云连接契约](../../docs/04-cloud-connector-protocol.md) · [离线审批演示](../../examples/04-cloud-console.ts)
185
+
186
+ ```sh
187
+ pnpm build
188
+ pnpm --filter @soiljs/cloud typecheck
189
+ pnpm --filter @soiljs/cloud exec tsup
190
+ pnpm exec vitest run packages/cloud/src/__tests__
191
+ ```
192
+
193
+ 测试使用本地 HTTP 与注入 WebSocket/宿主,包含真实 Runtime 的离线裁剪和远程审批;不建立供应商、真实 WSS、代理或子进程崩溃覆盖。用量脱敏仍保留 nullable 计数与 completeness,不补零。
@@ -0,0 +1,255 @@
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
+ interface CloudFlushResult {
32
+ drained: boolean;
33
+ /** Connector: observed pending events (a lower bound); null if storage could not be read. */
34
+ remaining: number | null;
35
+ }
36
+
37
+ /** JSON-shaped attributes; values are cloned and sanitized before entering the queue. */
38
+ type TraceJson = null | boolean | number | string | TraceJson[] | {
39
+ [key: string]: TraceJson | undefined;
40
+ };
41
+ type TraceStatus = "running" | "completed" | "failed" | "cancelled" | "waiting" | "needs_attention" | "unknown";
42
+ interface GenerationAttributes {
43
+ callId?: string;
44
+ channelId?: string;
45
+ providerId?: string;
46
+ modelId?: string;
47
+ nativeParameters?: Record<string, TraceJson | undefined>;
48
+ parameterWire?: Record<string, TraceJson | undefined>;
49
+ inputMessages?: TraceJson;
50
+ outputMessage?: TraceJson;
51
+ reasoningContent?: TraceJson;
52
+ toolCalls?: TraceJson[];
53
+ usage?: Record<string, TraceJson | undefined>;
54
+ physicalAttempts?: Array<{
55
+ physicalAttemptIndex: number;
56
+ usage?: Record<string, TraceJson | undefined>;
57
+ [key: string]: TraceJson | undefined;
58
+ }>;
59
+ finishReason?: string | null;
60
+ requestStage?: string;
61
+ providerRequestId?: string;
62
+ deliveryState?: "not-sent" | "may-have-been-sent" | "response-received";
63
+ ttftMs?: number | null;
64
+ firstOutputMs?: number | null;
65
+ }
66
+ interface AgentTraceAttributes {
67
+ agentId?: string;
68
+ agentVersion?: string;
69
+ workflowVersion?: string;
70
+ stepCount?: number;
71
+ stopReason?: string;
72
+ }
73
+ interface ToolTraceAttributes {
74
+ toolRef?: string;
75
+ toolName?: string;
76
+ version?: string;
77
+ toolCallId?: string;
78
+ invocationId?: string;
79
+ parsedArgs?: TraceJson;
80
+ adapterResult?: TraceJson;
81
+ businessData?: TraceJson;
82
+ modelPresentation?: TraceJson;
83
+ toolOutcome?: string;
84
+ effectOutcome?: string;
85
+ deliveryState?: "not-sent" | "may-have-been-sent" | "response-received";
86
+ attemptIndex?: number;
87
+ }
88
+ interface TraceSpanBase {
89
+ spanId: string;
90
+ parentSpanId?: string | null;
91
+ updateId?: string;
92
+ revision?: number;
93
+ name: string;
94
+ status?: TraceStatus;
95
+ startedAt?: string | null;
96
+ endedAt?: string | null;
97
+ durationMs?: number | null;
98
+ input?: unknown;
99
+ output?: unknown;
100
+ /** Stored with output in a sanitized span-output content reference. */
101
+ error?: unknown;
102
+ }
103
+ type TraceSpanInput = TraceSpanBase & ({
104
+ kind: "generation";
105
+ attributes?: GenerationAttributes;
106
+ } | {
107
+ kind: "agent";
108
+ attributes?: AgentTraceAttributes;
109
+ } | {
110
+ kind: "tool";
111
+ attributes?: ToolTraceAttributes;
112
+ });
113
+ /** Each report is a complete replacement snapshot of a trace, including all its spans. */
114
+ interface CloudTraceInput {
115
+ externalTraceId: string;
116
+ updateId?: string;
117
+ revision?: number;
118
+ source?: "sdk" | "ingest-api" | "agent-host";
119
+ name: string;
120
+ startedAt: string;
121
+ endedAt?: string | null;
122
+ status?: TraceStatus | "budget_exhausted";
123
+ sessionNamespace?: string;
124
+ sessionId?: string;
125
+ hostSessionId?: string;
126
+ hostRunId?: string;
127
+ hostInstanceId?: string;
128
+ environment?: string;
129
+ release?: string;
130
+ tags?: string[];
131
+ /** Supply pseudonymous identifiers here; the reporter does not invent user identity. */
132
+ metadata?: Record<string, unknown>;
133
+ input?: unknown;
134
+ output?: unknown;
135
+ error?: unknown;
136
+ spans: TraceSpanInput[];
137
+ }
138
+ type TraceDropReason = "queue-full" | "invalid" | "too-large" | "rejected" | "closed";
139
+ interface CloudTraceReporterOptions {
140
+ endpoint: string;
141
+ /** Ingest key (soil_ing_*), separate from Channel A's Runtime token. */
142
+ token: string | (() => string | Promise<string>);
143
+ producer?: string;
144
+ payloadMode?: PayloadMode;
145
+ redactFields?: readonly string[];
146
+ fetch?: typeof globalThis.fetch;
147
+ maxQueueSize?: number;
148
+ maxBatchSize?: number;
149
+ /** Serialized byte limit per queued trace; bounded independently of item count. */
150
+ maxItemBytes?: number;
151
+ batchIntervalMs?: number;
152
+ requestTimeoutMs?: number;
153
+ retryBaseMs?: number;
154
+ retryMaxMs?: number;
155
+ onDrop?: (event: {
156
+ count: number;
157
+ total: number;
158
+ reason: TraceDropReason;
159
+ }) => void;
160
+ }
161
+ interface CloudTraceReporter {
162
+ /** Synchronous enqueue only; false means dropped, never throws or awaits the network. */
163
+ report(trace: CloudTraceInput): boolean;
164
+ readonly pendingCount: number;
165
+ readonly droppedCount: number;
166
+ flush(timeoutMs?: number): Promise<{
167
+ drained: boolean;
168
+ remaining: number;
169
+ }>;
170
+ close(options?: {
171
+ flushTimeoutMs?: number;
172
+ }): Promise<void>;
173
+ }
174
+
175
+ /** Bounded, process-local, best-effort telemetry; never executes models/tools. */
176
+ declare function createTraceReporter(options: CloudTraceReporterOptions): CloudTraceReporter;
177
+
178
+ /** Structural Runtime integration: no runtime dependency on @soiljs/agent. */
179
+ interface CloudRuntime {
180
+ readonly storage: StorageAdapter;
181
+ readonly commands: {
182
+ dispatch(envelope: CommandEnvelope): Promise<CommandReceipt>;
183
+ };
184
+ subscribeRealtime?(listener: (event: RealtimeEvent) => void): () => void;
185
+ }
186
+ interface CloudWebSocket {
187
+ readonly readyState: number;
188
+ readonly bufferedAmount: number;
189
+ send(data: string): void;
190
+ close(): void;
191
+ addEventListener(type: "open" | "close" | "error" | "message", listener: (event: {
192
+ data?: unknown;
193
+ }) => void): void;
194
+ }
195
+ interface CloudConnectorConfig {
196
+ endpoint: string;
197
+ token: string | (() => string | Promise<string>);
198
+ runtimeId?: string;
199
+ runtimeName?: string;
200
+ /** Keep this directory across restarts; one live connector per directory. */
201
+ stateDir?: string;
202
+ /** Fresh identity and no filesystem access, even when stateDir/runtimeId are supplied. */
203
+ ephemeral?: boolean;
204
+ agents?: readonly AgentManifest[];
205
+ commands?: Partial<RemoteCapabilities>;
206
+ observability?: {
207
+ redactFields?: readonly string[];
208
+ payloadMode?: PayloadMode;
209
+ streamRealtimeDeltas?: boolean;
210
+ realtimeBufferSize?: number;
211
+ maxRealtimeBytes?: number;
212
+ maxWatches?: number;
213
+ artifacts?: {
214
+ mode: "none";
215
+ } | {
216
+ mode: "auto_under_limit";
217
+ maxBytes: number;
218
+ };
219
+ };
220
+ configuration?: {
221
+ mode: "code";
222
+ } | {
223
+ mode: "hybrid";
224
+ allowedFields: Readonly<Record<string, readonly string[]>>;
225
+ verify(snapshot: ConfigSnapshot): boolean | Promise<boolean>;
226
+ /** Stage for FUTURE admissions only; the host must preserve Turn config pinning. */
227
+ stage(snapshot: ConfigSnapshot): void | Promise<void>;
228
+ };
229
+ transport?: {
230
+ fetch?: typeof globalThis.fetch;
231
+ webSocketFactory?: (url: string) => CloudWebSocket;
232
+ requestTimeoutMs?: number;
233
+ pollIntervalMs?: number;
234
+ retryBaseMs?: number;
235
+ retryMaxMs?: number;
236
+ heartbeatMs?: number;
237
+ receiptRetryMs?: number;
238
+ random?: () => number;
239
+ };
240
+ }
241
+ interface CloudConnector {
242
+ open(runtime: CloudRuntime): Promise<void>;
243
+ flush(timeoutMs?: number): Promise<CloudFlushResult>;
244
+ close(options?: {
245
+ flushTimeoutMs?: number;
246
+ }): Promise<void>;
247
+ onDurableEvent(event: DurableRuntimeEvent): void;
248
+ onRealtimeEvent(event: RealtimeEvent): void;
249
+ readonly runtimeId: string | undefined;
250
+ readonly connected: boolean;
251
+ }
252
+ /** Outbound control and export never await inside Runtime hooks. */
253
+ declare function cloudConnector(config: CloudConnectorConfig): CloudConnector;
254
+
255
+ export { type AgentManifest, type AgentTraceAttributes, type CloudConnector, type CloudConnectorConfig, type CloudFlushResult, type CloudRuntime, type CloudTraceInput, type CloudTraceReporter, type CloudTraceReporterOptions, type CloudWebSocket, type ConfigSnapshot, type GenerationAttributes, type PayloadMode, type RemoteCapabilities, type ToolTraceAttributes, type TraceDropReason, type TraceJson, type TraceSpanBase, type TraceSpanInput, type TraceStatus, cloudConnector, createTraceReporter, redact, redactEvent, redactText };