@soiljs/agent 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,204 @@
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
+ ## Foundation execution controls
4
+
5
+ `AgentDefinition` accepts `toolExecution?: "parallel" | "sequential"` (default
6
+ `"parallel"`), `onMaxTokens?: "complete" | "fail"` (default `"complete"`), and
7
+ `limits?: { maxIterations?: number; maxModelCalls?: number; maxToolCalls?: number }`.
8
+ `session.send(input, { limits })` overrides individual limits for that Turn. Limits
9
+ are nonnegative integers. Iterations count committed model batches; model calls
10
+ count durable request reservations, including compaction calls and retries; tool
11
+ calls count execution Attempts, including retries and child delegation, excluding
12
+ reconcile probes and validation failures. Caps apply before dispatch, including
13
+ inside multi-tool batches. Unexecuted excess calls become `skipped`.
14
+
15
+ Sequential execution persists the scheduling policy and prepares one Step at a
16
+ time in ledger order. Validation/transformation and approval run before dispatch;
17
+ their validated input is captured once and reused by approval, execution, retries,
18
+ and reconcile. Validated values must be acyclic JSON (no class instances,
19
+ undefined properties, or non-finite numbers) so every backend sees the same value.
20
+ Approval, child waits, and unknown effects block all later Steps.
21
+ Parallel remains the default and retains independently committed siblings.
22
+
23
+ Registered tools may declare `terminatesTurn?: boolean` only in sequential Agents.
24
+ A successful T4 commit persists full output, model projection, and completion
25
+ intent while atomically skipping unstarted later siblings. Recovery completes T7
26
+ with `status: "completed"`, `stopReason: "tool_terminated"`, and structured
27
+ `output`, without another model call or tool execution. Validation failure,
28
+ execution failure, approval rejection, and unknown outcomes do not terminate.
29
+ Cancellation committed before T4 wins (external effects remain unknown);
30
+ termination committed at T4 wins over later cancellation and pending Steering.
31
+ Earlier child Turns must finish before a terminating sibling can run. A child
32
+ Agent may itself terminate and return its structured output to its parent.
33
+
34
+ `TurnOutcome` and durable Turn state expose `stopReason?: StopReason`,
35
+ `providerFinishReason?: string`, and `partial?: boolean`. `StopReason` is
36
+ `"end_turn" | "tool_terminated" | "max_tokens" | "content_filter" |
37
+ "max_iterations" | "max_model_calls" | "max_tool_calls" | "cancelled" |
38
+ "error" | "unknown"`. Provider finish reasons are the normalized model adapter
39
+ reasons. Length/content-filter responses skip proposed tools; length preserves
40
+ partial text and either completes or fails according to `onMaxTokens`.
41
+
42
+ Tools also accept `modelInputSchema?: JsonSchema` independently of their execution
43
+ `inputSchema`, and `toModelResult?(output, ctx): JsonValue | Promise<JsonValue>`.
44
+ The model schema is sent verbatim to the model; the execution validator may be
45
+ Standard Schema and transform inputs. Full tool output stays in the ledger;
46
+ the captured `modelOutput` alone feeds subsequent calls, replay, session history,
47
+ and compaction views. Projection is captured before T4, including successful
48
+ reconcile and authorized manual resolution. Child tools support the same hook
49
+ after `mapOutput`, captured with child completion. Existing records without a
50
+ projection keep their original output behavior; arbitrary `output.modelOutput`
51
+ properties are never interpreted as a framework contract.
52
+
53
+ For singleton servers, static `model` and `instructions` can be replaced by:
54
+
55
+ ```ts
56
+ interface TurnResolutionContext {
57
+ readonly turnContext: Readonly<Record<string, unknown>>;
58
+ readonly scope?: ScopeRef;
59
+ readonly services: Readonly<Record<string, unknown>>;
60
+ readonly sessionId: string;
61
+ readonly turnId: string;
62
+ readonly iteration: number;
63
+ }
64
+ // AgentDefinition fields:
65
+ resolveModel?: (ctx: TurnResolutionContext) => BoundModel | Promise<BoundModel>;
66
+ resolveInstructions?: (ctx: TurnResolutionContext) => string | Promise<string>;
67
+ ```
68
+
69
+ Resolvers run per iteration (including recovery), without changing the registered
70
+ definition or retaining per-user bindings in the registry. Store only serializable
71
+ user lookup identifiers in Turn context; resolve credentials from host `services`.
72
+ Keep prompts and model/protocol identity stable within an active tool chain:
73
+ the existing committed-prefix and continuation checks still apply. Resolver
74
+ closures and BoundModel credentials are never serialized by Runtime.
75
+
76
+ `HostControlError`, `toErrorRecord`, `JsonValue`, and `StopReason` are re-exported
77
+ from SPI. Throw `new HostControlError({ code, message, requestStage, details })`
78
+ for host admission/budget/job-lease failures. Only `reason`, `nextAttemptAt`, and
79
+ `httpStatus` scalar details are retained; messages/detail strings are bounded.
80
+ `admission_rejected` is never automatically retried. This error is distinct from
81
+ `LeaseLostError`, which fences Runtime storage ownership.
82
+
83
+ 把模型推理、业务工具、审批与恢复组织成可追溯的 Agent 执行流程。它是组合 `@soiljs/spi` 与 `@soiljs/models` 的 Runtime 层,适合需要多轮工具调用、人工介入和持久进度的 TypeScript 服务;要求 Node.js ≥22.19。
84
+
85
+ ## 安装与入口
86
+
87
+ ```sh
88
+ pnpm add @soiljs/agent @soiljs/models
89
+ # 需要进程重启后恢复时,再选持久存储
90
+ pnpm add @soiljs/storage-local
91
+ ```
92
+
93
+ | 导出入口 | 用途 |
94
+ | --- | --- |
95
+ | `@soiljs/agent` | 定义函数、Runtime、Session/Turn 句柄、`memoryStorage`;重导出公共 SPI 契约与错误 |
96
+
97
+ 所有导出指向构建后的 `dist`。模型由各协议的 `bind()` 提供,Runtime 不接收一组混合的厂商请求参数。
98
+
99
+ ## 最小可运行示例
100
+
101
+ 配置 `OPENAI_API_KEY` 后,在 ESM TypeScript 中运行下列代码。天气工具返回固定业务数据,模型请求走真实供应商;完整离线版本见 [示例 01](../../examples/01-quickstart-memory.ts)。
102
+
103
+ ```ts
104
+ import { defineAgent, defineTool, openRuntime, runAgent } from "@soiljs/agent";
105
+ import { openaiResponses } from "@soiljs/models/openai";
106
+
107
+ const weather = defineTool<Record<string, unknown>, Record<string, unknown>, { city: string }>({
108
+ name: "get_weather",
109
+ version: "1",
110
+ description: "查询城市天气。",
111
+ inputSchema: {
112
+ type: "object",
113
+ properties: { city: { type: "string" } },
114
+ required: ["city"],
115
+ },
116
+ effect: "none",
117
+ async execute({ city }) {
118
+ return { city, temperatureC: 22, condition: "rain" };
119
+ },
120
+ });
121
+ const assistant = defineAgent({
122
+ id: "weather-assistant",
123
+ version: "1",
124
+ model: openaiResponses.bind({ model: "gpt-5.4", reasoningEffort: "high" }),
125
+ instructions: "使用 get_weather 查询天气,用中文简洁回答。",
126
+ tools: [weather],
127
+ });
128
+
129
+ const quick = await runAgent(assistant, "杭州天气如何?");
130
+ if (quick.status === "completed") console.log(quick.outputText);
131
+
132
+ await using runtime = await openRuntime({ agent: assistant });
133
+ const session = await runtime.openSession(assistant);
134
+ const turn = await session.send("根据杭州天气安排一日游");
135
+ await turn.steer("只安排室内活动", { fallbackToNewTurn: true });
136
+ const next = await session.followUp("列出随身物品");
137
+ for await (const event of turn.stream()) {
138
+ if (event.type === "text.delta") process.stdout.write(event.delta ?? "");
139
+ }
140
+ console.log(await turn.wait(), await next.wait());
141
+ ```
142
+
143
+ ## 核心 API 速查
144
+
145
+ | API / 配置 | 作用与使用要点 |
146
+ | --- | --- |
147
+ | `defineAgent` | 注册稳定 `id`、`version`、模型、指令与工具;模型可为 `BoundModel` 或已注册别名 |
148
+ | `defineTool` | 声明输入 Schema、版本、`execute`、副作用、审批与可选 `reconcile` |
149
+ | `openRuntime` | 管理存储、工具包与连接器生命周期;接收 `agent` / `agents`、`models`、`services`、`storage`、`authorizeCommand` 等 |
150
+ | `runAgent` / `runtime.run` | 单次任务;后者复用当前 Runtime,创建临时 Session |
151
+ | `runtime.openSession` / `getSession` / `getTurn` | 创建会话,或在无状态接口里通过持久 ID 重新取得句柄 |
152
+ | `session.send` | 默认拒绝同一 Session 的并发活跃输入,抛 `SessionBusyError` |
153
+ | `turn.steer` / `session.steer` | 纠偏输入进入持久收件箱,在安全迭代边界消费为 Step;可原子兜底新 Turn |
154
+ | `session.followUp` | 持久 FIFO;只有前序成功完成才自动出队 |
155
+ | `runtime.commands` | `approve`、`resolveUnknown`、`cancel`、`steer`、`resume`、`dispatch(CommandEnvelope)` |
156
+ | `defineContextStrategy` | 压缩提交为 `compaction` Step;通过 `ctx.callModel` 记录摘要调用用量 |
157
+ | `defineSubAgentTool` | 在独立 Session 派发子 Turn,父级等待时释放租约,按策略级联取消 |
158
+ | `runtime.subscribeRealtime` | 订阅内存实时事件,返回取消函数;监听器失败与执行隔离 |
159
+
160
+ `turn.wait()` 返回 `TurnOutcome`,应按 `status` 分支处理:
161
+
162
+ | 状态 | 含义 |
163
+ | --- | --- |
164
+ | `completed` | 成功完成,可读取 `outputText` |
165
+ | `failed` / `cancelled` | 执行失败或经授权取消 |
166
+ | `waiting_approval` | 等待工具审批 |
167
+ | `waiting_resolution` | 外部操作未决,等待对账或人工裁决 |
168
+ | `waiting_child` | 等待子 Turn |
169
+
170
+ Outcome 携带待审批、未决步骤、子步骤与 `usage: UsageTotals`。流在暂停或终止时关闭,支持保留范围内的 `fromEventId` 重订阅;实时 delta 有界且可丢弃,不写 Outbox。用量仅汇总完整 Attempt,`completeCount`、`incompleteCount` 与 `hasIncompleteUsage` 暴露缺口。
171
+
172
+ ### 工具与宿主配置
173
+
174
+ 单 Agent 可写 `openRuntime({ agent: assistant })`,等价于 `openRuntime({ agents: [assistant] })`。多个 Agent 或同一 Agent 的多个版本使用 `agents`;`agent` 与 `agents` 互斥,类型检查会拒绝同时传入,JavaScript 调用也会在打开存储前报错。两者都不传时仍可在 `runtime.openSession(agent)` 或 `runtime.run(agent, input)` 传入定义来注册;启动恢复所需定义应在启动时注册。
175
+
176
+ `ToolEffect` 只有 `"none" | "external"`;`ApprovalDecision` 只有 `"none" | "required"`,也可用函数按输入决定。输入支持 SPI 的 JSON Schema 子集与 Standard Schema v1;后者可做本地转换,但仅凭 v1 结构无法生成详细 JSON Schema,因此模型端看到通用 object,需要详细参数时应直接给 JSON Schema。
177
+
178
+ 在 `openRuntime({ models: { lead } })` 注册模型别名后,可用 `defineAgent({ model: "lead", ... })`。不可序列化客户端放 `services`,可序列化请求数据放 Session/Turn `context`。工具包每个 Runtime 打开一次并随 Runtime 关闭。本包不自动读取模型凭证环境变量,连接配置由模型协议处理。
179
+
180
+ ## 持久执行与关键边界
181
+
182
+ - 默认 `memoryStorage()` 实现九组 SPI 契约,但数据只存在进程内。注入持久 `StorageAdapter` 才能跨进程恢复;每次重启仍需注册兼容的 Agent/工具版本。默认自动恢复,也可选 `recovery: "manual"` 后显式恢复。
183
+ - 账本保存 `Session → Turn → Step → Attempt`,会话通过 `ledger.listSessionTurns()` 与已提交 Step 重建,与 Outbox 留存无关。等待态释放租约,并行兄弟 Step 独立提交,Attempt 终态历史不可改写。
184
+ - 外部操作中断后诚实保留 `unknown`。`reconcile` 可证实 `completed`、`failed` 或 `not_executed`,否则进入 `waiting_resolution`。没有 exactly-once;取消无法撤销已经发生的远端副作用。
185
+ - `toolCallId` 只配对模型消息;跨 Attempt 的操作标识是 `operationKey`,业务去重独立实现。`retryPolicy.maxAttempts` 含首次执行;无副作用失败归档后可重试,外部副作用重试需对账证据或显式裁决。
186
+ - 模型输出不是授权。应用应提供 `authorizeCommand`,云端命令必须经过该钩子,连接器开关不能替代授权。
187
+ - 模型 Step 保存 `protocolId`、`modelId` 与原始 continuation。默认超过 65,536 UTF-8 字节时先写产物再提交引用,可用 `continuationInlineThresholdBytes` 调整。活跃工具链的协议/模型或续接状态不匹配时拒绝继续;历史已完成 Turn 可投影为普通对话后更换模型。
188
+ - 压缩之间保持已提交前缀与完整工具配对;`view.messagesToCompact` 提供不含旧协议状态的对话。子 Agent 的 `mapOutput` 只投影已提交结果;`limits.maxSubTurnDepth` 默认 8。
189
+
190
+ ## 深入阅读与本地校验
191
+
192
+ [在线 API](https://ximing.github.io/agent-foundation/#/api/agent) · [生命周期](../../docs/02-lifecycle-state-machine.md) · [压缩与子 Agent 示例](../../examples/05-extensions-subagent.ts)
193
+
194
+ 从仓库根目录运行,包内类型检查前先构建依赖:
195
+
196
+ ```sh
197
+ pnpm build
198
+ pnpm --filter @soiljs/agent typecheck
199
+ pnpm --filter @soiljs/agent exec tsup
200
+ pnpm exec vitest run packages/agent/src/__tests__
201
+ pnpm exec vitest run --maxWorkers=1 packages/storage-local/src/__tests__/crash-recovery.test.ts
202
+ ```
203
+
204
+ 离线测试不代表真实供应商覆盖;子进程崩溃由单独的 SIGKILL 测试验证。
@@ -0,0 +1,275 @@
1
+ import { ScopeRef, ToolDefinition, SchemaInput, ToolkitProvider, JsonSchema, ToolExecutionContext, JsonValue, ContextStrategy, StorageAdapter, CommandPayload, CommandActor, CommandEnvelope, CommandReceipt, ObservabilityHook, CommandAuthorizer, Session, StopReason, Turn, Step, ApprovalRecord, UsageTotals, 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 resolveModel?: (ctx: TurnResolutionContext) => BoundModel | Promise<BoundModel>;
21
+ readonly resolveInstructions?: (ctx: TurnResolutionContext) => string | Promise<string>;
22
+ readonly toolExecution?: "parallel" | "sequential";
23
+ readonly onMaxTokens?: "complete" | "fail";
24
+ readonly tools?: readonly (RegisteredTool | RegisteredToolkit | RegisteredSubAgentTool)[];
25
+ readonly contextStrategy?: ContextStrategy<string | BoundModel>;
26
+ readonly limits?: {
27
+ readonly maxIterations?: number;
28
+ readonly maxModelCalls?: number;
29
+ readonly maxToolCalls?: number;
30
+ };
31
+ }
32
+ interface TurnResolutionContext {
33
+ readonly turnContext: Readonly<Record<string, unknown>>;
34
+ readonly scope?: ScopeRef;
35
+ readonly services: Readonly<Record<string, unknown>>;
36
+ readonly sessionId: string;
37
+ readonly turnId: string;
38
+ readonly iteration: number;
39
+ }
40
+ declare function defineAgent<T extends AgentDefinition>(definition: T): T;
41
+ interface ChildOutcome {
42
+ readonly status: string;
43
+ readonly output?: unknown;
44
+ readonly outputText: string;
45
+ readonly turnId: string;
46
+ }
47
+ interface SubAgentTool<TInput = never, TOutput = unknown> {
48
+ readonly modelInputSchema?: JsonSchema;
49
+ toModelResult?(output: TOutput, ctx: ToolExecutionContext): JsonValue | Promise<JsonValue>;
50
+ readonly kind: "sub_agent";
51
+ readonly name: string;
52
+ readonly version: string;
53
+ readonly description: string;
54
+ readonly targetAgent: string;
55
+ readonly inputSchema: SchemaInput<TInput>;
56
+ readonly mapInput: (input: TInput, parentCtx: ToolExecutionContext) => {
57
+ prompt: string;
58
+ context?: Record<string, unknown>;
59
+ };
60
+ readonly mapOutput?: (child: ChildOutcome) => TOutput;
61
+ readonly propagation?: {
62
+ cancelWithParent?: boolean;
63
+ bubbleApproval?: boolean;
64
+ };
65
+ }
66
+ declare function defineSubAgentTool<TInput, TOutput = unknown>(definition: Omit<SubAgentTool<TInput, TOutput>, "kind" | "version"> & {
67
+ version?: string;
68
+ }): SubAgentTool<TInput, TOutput>;
69
+
70
+ /** In-process, isolated storage. Transactions contain synchronous ledger work only. */
71
+ declare function memoryStorage(): StorageAdapter;
72
+
73
+ type RuntimeEvent = DurableRuntimeEvent | RealtimeEvent;
74
+ type Payload<K extends CommandPayload["kind"]> = Extract<CommandPayload, {
75
+ kind: K;
76
+ }>;
77
+ interface CommandOptions {
78
+ commandId?: string;
79
+ actor?: Omit<CommandActor, "source"> & {
80
+ source?: CommandActor["source"];
81
+ };
82
+ scope?: ScopeRef;
83
+ }
84
+ type CommandInput<K extends CommandPayload["kind"]> = Omit<Payload<K>, "kind"> & CommandOptions;
85
+ type SteerOptions = Omit<Payload<"steer">, "kind" | "turnId" | "input"> & CommandOptions;
86
+ interface SendOptions {
87
+ mode?: "reject" | "follow_up";
88
+ idempotencyKey?: string;
89
+ context?: Record<string, unknown>;
90
+ limits?: Record<string, number>;
91
+ }
92
+ interface SessionOptions {
93
+ scope?: ScopeRef;
94
+ context?: Record<string, unknown>;
95
+ }
96
+ type RuntimeConfig = {
97
+ storage?: StorageAdapter;
98
+ models?: Readonly<Record<string, BoundModel>>;
99
+ services?: Record<string, unknown>;
100
+ recovery?: "auto" | "manual";
101
+ hooks?: readonly ObservabilityHook[];
102
+ authorizeCommand?: CommandAuthorizer;
103
+ cloud?: RuntimeConnector;
104
+ limits?: {
105
+ maxSubTurnDepth?: number;
106
+ };
107
+ /** Opaque continuations larger than this spill to immutable artifacts before ledger commit. */
108
+ continuationInlineThresholdBytes?: number;
109
+ } & ({
110
+ /** Register a single Agent; mutually exclusive with agents. */
111
+ agent: AgentDefinition;
112
+ agents?: never;
113
+ } | {
114
+ agent?: never;
115
+ /** Register multiple Agents, including versions needed for recovery. */
116
+ agents?: readonly AgentDefinition[];
117
+ });
118
+ interface RuntimeConnector {
119
+ open(runtime: Runtime): Promise<void>;
120
+ close(): Promise<void>;
121
+ }
122
+ interface OutcomeBase {
123
+ turnId: string;
124
+ outputText: string;
125
+ output?: unknown;
126
+ stopReason?: StopReason;
127
+ providerFinishReason?: string;
128
+ partial?: boolean;
129
+ error?: Turn["error"];
130
+ unknownSteps: readonly Step[];
131
+ approvals: readonly ApprovalRecord[];
132
+ childSteps: readonly Step[];
133
+ usage: UsageTotals;
134
+ }
135
+ type TurnOutcome = OutcomeBase & ({
136
+ status: "completed";
137
+ } | {
138
+ status: "failed";
139
+ error?: Turn["error"];
140
+ } | {
141
+ status: "cancelled";
142
+ } | {
143
+ status: "waiting_resolution";
144
+ } | {
145
+ status: "waiting_approval";
146
+ } | {
147
+ status: "waiting_child";
148
+ });
149
+ declare class SessionHandle {
150
+ private readonly runtime;
151
+ readonly snapshot: Session;
152
+ readonly id: string;
153
+ constructor(runtime: Runtime, snapshot: Session);
154
+ send(input: string, opts?: SendOptions): Promise<TurnHandle>;
155
+ followUp(input: string, opts?: Omit<SendOptions, "mode">): Promise<TurnHandle>;
156
+ steer(input: string, opts?: SteerOptions): Promise<{
157
+ accepted: false;
158
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
159
+ mode?: never;
160
+ turnId?: never;
161
+ } | {
162
+ accepted: true;
163
+ mode: "steered" | "promoted_to_turn";
164
+ turnId: string;
165
+ reason?: never;
166
+ }>;
167
+ }
168
+ declare class TurnHandle {
169
+ private readonly runtime;
170
+ readonly id: string;
171
+ constructor(runtime: Runtime, id: string);
172
+ wait(): Promise<TurnOutcome>;
173
+ stream(opts?: {
174
+ fromEventId?: string;
175
+ }): AsyncIterable<RuntimeEvent>;
176
+ approve(approvalId: string, options: Omit<CommandInput<"approve">, "turnId" | "approvalId">): Promise<CommandReceipt>;
177
+ resolveUnknown(stepId: string, options: Omit<CommandInput<"resolve_unknown">, "turnId" | "stepId">): Promise<CommandReceipt>;
178
+ cancel(options?: Omit<CommandInput<"cancel">, "turnId">): Promise<CommandReceipt>;
179
+ steer(input: string, opts?: SteerOptions): Promise<{
180
+ accepted: false;
181
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
182
+ mode?: never;
183
+ turnId?: never;
184
+ } | {
185
+ accepted: true;
186
+ mode: "steered" | "promoted_to_turn";
187
+ turnId: string;
188
+ reason?: never;
189
+ }>;
190
+ }
191
+ /** Owns registries and runnable work; waiting Turns retain only ledger facts. */
192
+ declare class Runtime implements AsyncDisposable {
193
+ private readonly config;
194
+ readonly storage: StorageAdapter;
195
+ readonly commands: {
196
+ dispatch: (envelope: CommandEnvelope) => Promise<CommandReceipt>;
197
+ approve: (input: CommandInput<"approve">) => Promise<CommandReceipt>;
198
+ resolveUnknown: (input: CommandInput<"resolve_unknown">) => Promise<CommandReceipt>;
199
+ cancel: (input: CommandInput<"cancel">) => Promise<CommandReceipt>;
200
+ steer: (input: CommandInput<"steer">) => Promise<CommandReceipt>;
201
+ resume: (input: CommandInput<"resume">) => Promise<CommandReceipt>;
202
+ };
203
+ private readonly holderId;
204
+ private readonly agents;
205
+ private readonly tools;
206
+ private readonly jobs;
207
+ private readonly controllers;
208
+ private readonly listeners;
209
+ private readonly realtime;
210
+ private readonly history;
211
+ private readonly providers;
212
+ private readonly failures;
213
+ private hookCursor;
214
+ private closed;
215
+ private closePromise?;
216
+ private timer?;
217
+ constructor(config: RuntimeConfig);
218
+ private key;
219
+ private agent;
220
+ private model;
221
+ initialize(): Promise<void>;
222
+ private register;
223
+ openSession(agent: AgentDefinition | string, opts?: SessionOptions): Promise<SessionHandle>;
224
+ getSession(sessionId: string): Promise<SessionHandle>;
225
+ getTurn(turnId: string): Promise<TurnHandle>;
226
+ run(agent: AgentDefinition | string, input: string, opts?: SendOptions & SessionOptions): Promise<TurnOutcome>;
227
+ send(sessionId: string, input: string, opts?: SendOptions): Promise<TurnHandle>;
228
+ private assertOpen;
229
+ private snapshot;
230
+ private notify;
231
+ private flush;
232
+ /** Ephemeral events only; listeners are isolated from execution and never awaited. */
233
+ subscribeRealtime(listener: (event: RealtimeEvent) => void): () => void;
234
+ private emit;
235
+ private recover;
236
+ private schedule;
237
+ private control;
238
+ private lease;
239
+ private resolveAgent;
240
+ private drive;
241
+ private sessionHistory;
242
+ private messages;
243
+ private mapSubOutputs;
244
+ private toolSpecs;
245
+ private callModel;
246
+ private compact;
247
+ private reserveModel;
248
+ private executeStep;
249
+ private span;
250
+ private finish;
251
+ steer(turnId: string, input: string, opts?: SteerOptions): Promise<{
252
+ accepted: false;
253
+ reason: "turn_already_terminal" | "unauthorized" | "scope_mismatch" | "not_found" | "invalid_state";
254
+ mode?: never;
255
+ turnId?: never;
256
+ } | {
257
+ accepted: true;
258
+ mode: "steered" | "promoted_to_turn";
259
+ turnId: string;
260
+ reason?: never;
261
+ }>;
262
+ private command;
263
+ private dispatch;
264
+ wait(turnId: string): Promise<TurnOutcome>;
265
+ stream(turnId: string, opts?: {
266
+ fromEventId?: string;
267
+ }): AsyncIterable<RuntimeEvent>;
268
+ close(): Promise<void>;
269
+ private shutdown;
270
+ [Symbol.asyncDispose](): Promise<void>;
271
+ }
272
+ declare function openRuntime(config?: RuntimeConfig): Promise<Runtime>;
273
+ declare function runAgent(agent: AgentDefinition, input: string, opts?: SendOptions & SessionOptions): Promise<TurnOutcome>;
274
+
275
+ 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, type TurnResolutionContext, defineAgent, defineContextStrategy, defineSubAgentTool, defineTool, memoryStorage, openRuntime, runAgent };