@soiljs/agent 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/agent
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
+ 把模型推理、业务工具、审批与恢复组织成可追溯的 Agent 执行流程。它是组合 `@soiljs/spi` 与 `@soiljs/models` 的 Runtime 层,适合需要多轮工具调用、人工介入和持久进度的 TypeScript 服务;要求 Node.js ≥22.19。
4
+
5
+ ## 安装与入口
6
+
7
+ ```sh
8
+ pnpm add @soiljs/agent @soiljs/models
9
+ # 需要进程重启后恢复时,再选持久存储
10
+ pnpm add @soiljs/storage-local
11
+ ```
12
+
13
+ | 导出入口 | 用途 |
14
+ | --- | --- |
15
+ | `@soiljs/agent` | 定义函数、Runtime、Session/Turn 句柄、`memoryStorage`;重导出公共 SPI 契约与错误 |
16
+
17
+ 所有导出指向构建后的 `dist`。模型由各协议的 `bind()` 提供,Runtime 不接收一组混合的厂商请求参数。
18
+
19
+ ## 最小可运行示例
20
+
21
+ 配置 `OPENAI_API_KEY` 后,在 ESM TypeScript 中运行下列代码。天气工具返回固定业务数据,模型请求走真实供应商;完整离线版本见 [示例 01](../../examples/01-quickstart-memory.ts)。
22
+
23
+ ```ts
24
+ import { defineAgent, defineTool, openRuntime, runAgent } from "@soiljs/agent";
25
+ import { openaiResponses } from "@soiljs/models/openai";
26
+
27
+ const weather = defineTool<Record<string, unknown>, Record<string, unknown>, { city: string }>({
28
+ name: "get_weather",
29
+ version: "1",
30
+ description: "查询城市天气。",
31
+ inputSchema: {
32
+ type: "object",
33
+ properties: { city: { type: "string" } },
34
+ required: ["city"],
35
+ },
36
+ effect: "none",
37
+ async execute({ city }) {
38
+ return { city, temperatureC: 22, condition: "rain" };
39
+ },
40
+ });
41
+ const assistant = defineAgent({
42
+ id: "weather-assistant",
43
+ version: "1",
44
+ model: openaiResponses.bind({ model: "gpt-5.4", reasoningEffort: "high" }),
45
+ instructions: "使用 get_weather 查询天气,用中文简洁回答。",
46
+ tools: [weather],
47
+ });
48
+
49
+ const quick = await runAgent(assistant, "杭州天气如何?");
50
+ if (quick.status === "completed") console.log(quick.outputText);
51
+
52
+ await using runtime = await openRuntime({ agent: assistant });
53
+ const session = await runtime.openSession(assistant);
54
+ const turn = await session.send("根据杭州天气安排一日游");
55
+ await turn.steer("只安排室内活动", { fallbackToNewTurn: true });
56
+ const next = await session.followUp("列出随身物品");
57
+ for await (const event of turn.stream()) {
58
+ if (event.type === "text.delta") process.stdout.write(event.delta ?? "");
59
+ }
60
+ console.log(await turn.wait(), await next.wait());
61
+ ```
62
+
63
+ ## 核心 API 速查
64
+
65
+ | API / 配置 | 作用与使用要点 |
66
+ | --- | --- |
67
+ | `defineAgent` | 注册稳定 `id`、`version`、模型、指令与工具;模型可为 `BoundModel` 或已注册别名 |
68
+ | `defineTool` | 声明输入 Schema、版本、`execute`、副作用、审批与可选 `reconcile` |
69
+ | `openRuntime` | 管理存储、工具包与连接器生命周期;接收 `agent` / `agents`、`models`、`services`、`storage`、`authorizeCommand` 等 |
70
+ | `runAgent` / `runtime.run` | 单次任务;后者复用当前 Runtime,创建临时 Session |
71
+ | `runtime.openSession` / `getSession` / `getTurn` | 创建会话,或在无状态接口里通过持久 ID 重新取得句柄 |
72
+ | `session.send` | 默认拒绝同一 Session 的并发活跃输入,抛 `SessionBusyError` |
73
+ | `turn.steer` / `session.steer` | 纠偏输入进入持久收件箱,在安全迭代边界消费为 Step;可原子兜底新 Turn |
74
+ | `session.followUp` | 持久 FIFO;只有前序成功完成才自动出队 |
75
+ | `runtime.commands` | `approve`、`resolveUnknown`、`cancel`、`steer`、`resume`、`dispatch(CommandEnvelope)` |
76
+ | `defineContextStrategy` | 压缩提交为 `compaction` Step;通过 `ctx.callModel` 记录摘要调用用量 |
77
+ | `defineSubAgentTool` | 在独立 Session 派发子 Turn,父级等待时释放租约,按策略级联取消 |
78
+ | `runtime.subscribeRealtime` | 订阅内存实时事件,返回取消函数;监听器失败与执行隔离 |
79
+
80
+ `turn.wait()` 返回 `TurnOutcome`,应按 `status` 分支处理:
81
+
82
+ | 状态 | 含义 |
83
+ | --- | --- |
84
+ | `completed` | 成功完成,可读取 `outputText` |
85
+ | `failed` / `cancelled` | 执行失败或经授权取消 |
86
+ | `waiting_approval` | 等待工具审批 |
87
+ | `waiting_resolution` | 外部操作未决,等待对账或人工裁决 |
88
+ | `waiting_child` | 等待子 Turn |
89
+
90
+ Outcome 携带待审批、未决步骤、子步骤与 `usage: UsageTotals`。流在暂停或终止时关闭,支持保留范围内的 `fromEventId` 重订阅;实时 delta 有界且可丢弃,不写 Outbox。用量仅汇总完整 Attempt,`completeCount`、`incompleteCount` 与 `hasIncompleteUsage` 暴露缺口。
91
+
92
+ ### 工具与宿主配置
93
+
94
+ 单 Agent 可写 `openRuntime({ agent: assistant })`,等价于 `openRuntime({ agents: [assistant] })`。多个 Agent 或同一 Agent 的多个版本使用 `agents`;`agent` 与 `agents` 互斥,类型检查会拒绝同时传入,JavaScript 调用也会在打开存储前报错。两者都不传时仍可在 `runtime.openSession(agent)` 或 `runtime.run(agent, input)` 传入定义来注册;启动恢复所需定义应在启动时注册。
95
+
96
+ `ToolEffect` 只有 `"none" | "external"`;`ApprovalDecision` 只有 `"none" | "required"`,也可用函数按输入决定。输入支持 SPI 的 JSON Schema 子集与 Standard Schema v1;后者可做本地转换,但仅凭 v1 结构无法生成详细 JSON Schema,因此模型端看到通用 object,需要详细参数时应直接给 JSON Schema。
97
+
98
+ 在 `openRuntime({ models: { lead } })` 注册模型别名后,可用 `defineAgent({ model: "lead", ... })`。不可序列化客户端放 `services`,可序列化请求数据放 Session/Turn `context`。工具包每个 Runtime 打开一次并随 Runtime 关闭。本包不自动读取模型凭证环境变量,连接配置由模型协议处理。
99
+
100
+ ## 持久执行与关键边界
101
+
102
+ - 默认 `memoryStorage()` 实现九组 SPI 契约,但数据只存在进程内。注入持久 `StorageAdapter` 才能跨进程恢复;每次重启仍需注册兼容的 Agent/工具版本。默认自动恢复,也可选 `recovery: "manual"` 后显式恢复。
103
+ - 账本保存 `Session → Turn → Step → Attempt`,会话通过 `ledger.listSessionTurns()` 与已提交 Step 重建,与 Outbox 留存无关。等待态释放租约,并行兄弟 Step 独立提交,Attempt 终态历史不可改写。
104
+ - 外部操作中断后诚实保留 `unknown`。`reconcile` 可证实 `completed`、`failed` 或 `not_executed`,否则进入 `waiting_resolution`。没有 exactly-once;取消无法撤销已经发生的远端副作用。
105
+ - `toolCallId` 只配对模型消息;跨 Attempt 的操作标识是 `operationKey`,业务去重独立实现。`retryPolicy.maxAttempts` 含首次执行;无副作用失败归档后可重试,外部副作用重试需对账证据或显式裁决。
106
+ - 模型输出不是授权。应用应提供 `authorizeCommand`,云端命令必须经过该钩子,连接器开关不能替代授权。
107
+ - 模型 Step 保存 `protocolId`、`modelId` 与原始 continuation。默认超过 65,536 UTF-8 字节时先写产物再提交引用,可用 `continuationInlineThresholdBytes` 调整。活跃工具链的协议/模型或续接状态不匹配时拒绝继续;历史已完成 Turn 可投影为普通对话后更换模型。
108
+ - 压缩之间保持已提交前缀与完整工具配对;`view.messagesToCompact` 提供不含旧协议状态的对话。子 Agent 的 `mapOutput` 只投影已提交结果;`limits.maxSubTurnDepth` 默认 8。
109
+
110
+ ## 深入阅读与本地校验
111
+
112
+ [在线 API](https://ximing.github.io/agent-foundation/#/api/agent) · [生命周期](../../docs/02-lifecycle-state-machine.md) · [压缩与子 Agent 示例](../../examples/05-extensions-subagent.ts)
113
+
114
+ 从仓库根目录运行,包内类型检查前先构建依赖:
115
+
116
+ ```sh
117
+ pnpm build
118
+ pnpm --filter @soiljs/agent typecheck
119
+ pnpm --filter @soiljs/agent exec tsup
120
+ pnpm exec vitest run packages/agent/src/__tests__
121
+ pnpm exec vitest run --maxWorkers=1 packages/storage-local/src/__tests__/crash-recovery.test.ts
122
+ ```
123
+
124
+ 离线测试不代表真实供应商覆盖;子进程崩溃由单独的 SIGKILL 测试验证。
@@ -0,0 +1,253 @@
1
+ import { ToolDefinition, SchemaInput, ToolkitProvider, ToolExecutionContext, ContextStrategy, StorageAdapter, CommandPayload, CommandActor, ScopeRef, CommandEnvelope, CommandReceipt, ObservabilityHook, CommandAuthorizer, Session, Step, ApprovalRecord, UsageTotals, Turn, DurableRuntimeEvent, RealtimeEvent } from '@soiljs/spi';
2
+ export * from '@soiljs/spi';
3
+ import { BoundModel } from '@soiljs/models';
4
+
5
+ /** Definitions are registered code, never serialized executable closures. */
6
+ declare function defineTool<TServices = Record<string, unknown>, TContext = Record<string, unknown>, TInput = unknown, TOutput = unknown>(definition: ToolDefinition<TInput, TOutput, TServices, TContext>): ToolDefinition<TInput, TOutput, TServices, TContext>;
7
+ declare function defineContextStrategy<T extends ContextStrategy<string | BoundModel>>(definition: T): T;
8
+ type RegisteredTool = Omit<ToolDefinition<never, unknown, never, never>, "inputSchema"> & {
9
+ readonly inputSchema: SchemaInput;
10
+ };
11
+ type RegisteredToolkit = ToolkitProvider<never, never>;
12
+ type RegisteredSubAgentTool = Omit<SubAgentTool, "inputSchema"> & {
13
+ readonly inputSchema: SchemaInput;
14
+ };
15
+ interface AgentDefinition {
16
+ readonly id: string;
17
+ readonly version: string;
18
+ readonly model: BoundModel | string;
19
+ readonly instructions: string;
20
+ readonly tools?: readonly (RegisteredTool | RegisteredToolkit | RegisteredSubAgentTool)[];
21
+ readonly contextStrategy?: ContextStrategy<string | BoundModel>;
22
+ readonly limits?: {
23
+ readonly maxIterations?: number;
24
+ };
25
+ }
26
+ declare function defineAgent<T extends AgentDefinition>(definition: T): T;
27
+ interface ChildOutcome {
28
+ readonly status: string;
29
+ readonly output?: unknown;
30
+ readonly outputText: string;
31
+ readonly turnId: string;
32
+ }
33
+ interface SubAgentTool<TInput = never, TOutput = unknown> {
34
+ readonly kind: "sub_agent";
35
+ readonly name: string;
36
+ readonly version: string;
37
+ readonly description: string;
38
+ readonly targetAgent: string;
39
+ readonly inputSchema: SchemaInput<TInput>;
40
+ readonly mapInput: (input: TInput, parentCtx: ToolExecutionContext) => {
41
+ prompt: string;
42
+ context?: Record<string, unknown>;
43
+ };
44
+ readonly mapOutput?: (child: ChildOutcome) => TOutput;
45
+ readonly propagation?: {
46
+ cancelWithParent?: boolean;
47
+ bubbleApproval?: boolean;
48
+ };
49
+ }
50
+ declare function defineSubAgentTool<TInput, TOutput = unknown>(definition: Omit<SubAgentTool<TInput, TOutput>, "kind" | "version"> & {
51
+ version?: string;
52
+ }): SubAgentTool<TInput, TOutput>;
53
+
54
+ /** In-process, isolated storage. Transactions contain synchronous ledger work only. */
55
+ declare function memoryStorage(): StorageAdapter;
56
+
57
+ type RuntimeEvent = DurableRuntimeEvent | RealtimeEvent;
58
+ type Payload<K extends CommandPayload["kind"]> = Extract<CommandPayload, {
59
+ kind: K;
60
+ }>;
61
+ interface CommandOptions {
62
+ commandId?: string;
63
+ actor?: Omit<CommandActor, "source"> & {
64
+ source?: CommandActor["source"];
65
+ };
66
+ scope?: ScopeRef;
67
+ }
68
+ type CommandInput<K extends CommandPayload["kind"]> = Omit<Payload<K>, "kind"> & CommandOptions;
69
+ type SteerOptions = Omit<Payload<"steer">, "kind" | "turnId" | "input"> & CommandOptions;
70
+ interface SendOptions {
71
+ mode?: "reject" | "follow_up";
72
+ idempotencyKey?: string;
73
+ context?: Record<string, unknown>;
74
+ limits?: Record<string, number>;
75
+ }
76
+ interface SessionOptions {
77
+ scope?: ScopeRef;
78
+ context?: Record<string, unknown>;
79
+ }
80
+ type RuntimeConfig = {
81
+ storage?: StorageAdapter;
82
+ models?: Readonly<Record<string, BoundModel>>;
83
+ services?: Record<string, unknown>;
84
+ recovery?: "auto" | "manual";
85
+ hooks?: readonly ObservabilityHook[];
86
+ authorizeCommand?: CommandAuthorizer;
87
+ cloud?: RuntimeConnector;
88
+ limits?: {
89
+ maxSubTurnDepth?: number;
90
+ };
91
+ /** Opaque continuations larger than this spill to immutable artifacts before ledger commit. */
92
+ continuationInlineThresholdBytes?: number;
93
+ } & ({
94
+ /** Register a single Agent; mutually exclusive with agents. */
95
+ agent: AgentDefinition;
96
+ agents?: never;
97
+ } | {
98
+ agent?: never;
99
+ /** Register multiple Agents, including versions needed for recovery. */
100
+ agents?: readonly AgentDefinition[];
101
+ });
102
+ interface RuntimeConnector {
103
+ open(runtime: Runtime): Promise<void>;
104
+ close(): Promise<void>;
105
+ }
106
+ interface OutcomeBase {
107
+ turnId: string;
108
+ outputText: string;
109
+ output?: unknown;
110
+ unknownSteps: readonly Step[];
111
+ approvals: readonly ApprovalRecord[];
112
+ childSteps: readonly Step[];
113
+ usage: UsageTotals;
114
+ }
115
+ type TurnOutcome = OutcomeBase & ({
116
+ status: "completed";
117
+ } | {
118
+ status: "failed";
119
+ error?: Turn["error"];
120
+ } | {
121
+ status: "cancelled";
122
+ } | {
123
+ status: "waiting_resolution";
124
+ } | {
125
+ status: "waiting_approval";
126
+ } | {
127
+ status: "waiting_child";
128
+ });
129
+ declare class SessionHandle {
130
+ private readonly runtime;
131
+ readonly snapshot: Session;
132
+ readonly id: string;
133
+ constructor(runtime: Runtime, snapshot: Session);
134
+ send(input: string, opts?: SendOptions): Promise<TurnHandle>;
135
+ followUp(input: string, opts?: Omit<SendOptions, "mode">): Promise<TurnHandle>;
136
+ steer(input: string, opts?: SteerOptions): Promise<{
137
+ accepted: false;
138
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
139
+ mode?: never;
140
+ turnId?: never;
141
+ } | {
142
+ accepted: true;
143
+ mode: "steered" | "promoted_to_turn";
144
+ turnId: string;
145
+ reason?: never;
146
+ }>;
147
+ }
148
+ declare class TurnHandle {
149
+ private readonly runtime;
150
+ readonly id: string;
151
+ constructor(runtime: Runtime, id: string);
152
+ wait(): Promise<TurnOutcome>;
153
+ stream(opts?: {
154
+ fromEventId?: string;
155
+ }): AsyncIterable<RuntimeEvent>;
156
+ approve(approvalId: string, options: Omit<CommandInput<"approve">, "turnId" | "approvalId">): Promise<CommandReceipt>;
157
+ resolveUnknown(stepId: string, options: Omit<CommandInput<"resolve_unknown">, "turnId" | "stepId">): Promise<CommandReceipt>;
158
+ cancel(options?: Omit<CommandInput<"cancel">, "turnId">): Promise<CommandReceipt>;
159
+ steer(input: string, opts?: SteerOptions): Promise<{
160
+ accepted: false;
161
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
162
+ mode?: never;
163
+ turnId?: never;
164
+ } | {
165
+ accepted: true;
166
+ mode: "steered" | "promoted_to_turn";
167
+ turnId: string;
168
+ reason?: never;
169
+ }>;
170
+ }
171
+ /** Owns registries and runnable work; waiting Turns retain only ledger facts. */
172
+ declare class Runtime implements AsyncDisposable {
173
+ private readonly config;
174
+ readonly storage: StorageAdapter;
175
+ readonly commands: {
176
+ dispatch: (envelope: CommandEnvelope) => Promise<CommandReceipt>;
177
+ approve: (input: CommandInput<"approve">) => Promise<CommandReceipt>;
178
+ resolveUnknown: (input: CommandInput<"resolve_unknown">) => Promise<CommandReceipt>;
179
+ cancel: (input: CommandInput<"cancel">) => Promise<CommandReceipt>;
180
+ steer: (input: CommandInput<"steer">) => Promise<CommandReceipt>;
181
+ resume: (input: CommandInput<"resume">) => Promise<CommandReceipt>;
182
+ };
183
+ private readonly holderId;
184
+ private readonly agents;
185
+ private readonly tools;
186
+ private readonly jobs;
187
+ private readonly controllers;
188
+ private readonly listeners;
189
+ private readonly realtime;
190
+ private readonly history;
191
+ private readonly providers;
192
+ private readonly failures;
193
+ private hookCursor;
194
+ private closed;
195
+ private closePromise?;
196
+ private timer?;
197
+ constructor(config: RuntimeConfig);
198
+ private key;
199
+ private agent;
200
+ private model;
201
+ initialize(): Promise<void>;
202
+ private register;
203
+ openSession(agent: AgentDefinition | string, opts?: SessionOptions): Promise<SessionHandle>;
204
+ getSession(sessionId: string): Promise<SessionHandle>;
205
+ getTurn(turnId: string): Promise<TurnHandle>;
206
+ run(agent: AgentDefinition | string, input: string, opts?: SendOptions & SessionOptions): Promise<TurnOutcome>;
207
+ send(sessionId: string, input: string, opts?: SendOptions): Promise<TurnHandle>;
208
+ private assertOpen;
209
+ private snapshot;
210
+ private notify;
211
+ private flush;
212
+ /** Ephemeral events only; listeners are isolated from execution and never awaited. */
213
+ subscribeRealtime(listener: (event: RealtimeEvent) => void): () => void;
214
+ private emit;
215
+ private recover;
216
+ private schedule;
217
+ private control;
218
+ private lease;
219
+ private drive;
220
+ private sessionHistory;
221
+ private messages;
222
+ private mapSubOutputs;
223
+ private toolSpecs;
224
+ private callModel;
225
+ private compact;
226
+ private executeStep;
227
+ private span;
228
+ private finish;
229
+ steer(turnId: string, input: string, opts?: SteerOptions): Promise<{
230
+ accepted: false;
231
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
232
+ mode?: never;
233
+ turnId?: never;
234
+ } | {
235
+ accepted: true;
236
+ mode: "steered" | "promoted_to_turn";
237
+ turnId: string;
238
+ reason?: never;
239
+ }>;
240
+ private command;
241
+ private dispatch;
242
+ wait(turnId: string): Promise<TurnOutcome>;
243
+ stream(turnId: string, opts?: {
244
+ fromEventId?: string;
245
+ }): AsyncIterable<RuntimeEvent>;
246
+ close(): Promise<void>;
247
+ private shutdown;
248
+ [Symbol.asyncDispose](): Promise<void>;
249
+ }
250
+ declare function openRuntime(config?: RuntimeConfig): Promise<Runtime>;
251
+ declare function runAgent(agent: AgentDefinition, input: string, opts?: SendOptions & SessionOptions): Promise<TurnOutcome>;
252
+
253
+ export { type AgentDefinition, type ChildOutcome, type CommandInput, type CommandOptions, type RegisteredSubAgentTool, type RegisteredTool, type RegisteredToolkit, Runtime, type RuntimeConfig, type RuntimeConnector, type RuntimeEvent, type SendOptions, SessionHandle, type SessionOptions, type SteerOptions, type SubAgentTool, TurnHandle, type TurnOutcome, defineAgent, defineContextStrategy, defineSubAgentTool, defineTool, memoryStorage, openRuntime, runAgent };