@soiljs/agent 0.1.0 → 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/README.md CHANGED
@@ -1,5 +1,85 @@
1
1
  # @soiljs/agent
2
2
 
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
+
3
83
  把模型推理、业务工具、审批与恢复组织成可追溯的 Agent 执行流程。它是组合 `@soiljs/spi` 与 `@soiljs/models` 的 Runtime 层,适合需要多轮工具调用、人工介入和持久进度的 TypeScript 服务;要求 Node.js ≥22.19。
4
84
 
5
85
  ## 安装与入口
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
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';
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
2
  export * from '@soiljs/spi';
3
3
  import { BoundModel } from '@soiljs/models';
4
4
 
@@ -15,14 +15,28 @@ type RegisteredSubAgentTool = Omit<SubAgentTool, "inputSchema"> & {
15
15
  interface AgentDefinition {
16
16
  readonly id: string;
17
17
  readonly version: string;
18
- readonly model: BoundModel | string;
19
- readonly instructions: 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";
20
24
  readonly tools?: readonly (RegisteredTool | RegisteredToolkit | RegisteredSubAgentTool)[];
21
25
  readonly contextStrategy?: ContextStrategy<string | BoundModel>;
22
26
  readonly limits?: {
23
27
  readonly maxIterations?: number;
28
+ readonly maxModelCalls?: number;
29
+ readonly maxToolCalls?: number;
24
30
  };
25
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
+ }
26
40
  declare function defineAgent<T extends AgentDefinition>(definition: T): T;
27
41
  interface ChildOutcome {
28
42
  readonly status: string;
@@ -31,6 +45,8 @@ interface ChildOutcome {
31
45
  readonly turnId: string;
32
46
  }
33
47
  interface SubAgentTool<TInput = never, TOutput = unknown> {
48
+ readonly modelInputSchema?: JsonSchema;
49
+ toModelResult?(output: TOutput, ctx: ToolExecutionContext): JsonValue | Promise<JsonValue>;
34
50
  readonly kind: "sub_agent";
35
51
  readonly name: string;
36
52
  readonly version: string;
@@ -107,6 +123,10 @@ interface OutcomeBase {
107
123
  turnId: string;
108
124
  outputText: string;
109
125
  output?: unknown;
126
+ stopReason?: StopReason;
127
+ providerFinishReason?: string;
128
+ partial?: boolean;
129
+ error?: Turn["error"];
110
130
  unknownSteps: readonly Step[];
111
131
  approvals: readonly ApprovalRecord[];
112
132
  childSteps: readonly Step[];
@@ -216,6 +236,7 @@ declare class Runtime implements AsyncDisposable {
216
236
  private schedule;
217
237
  private control;
218
238
  private lease;
239
+ private resolveAgent;
219
240
  private drive;
220
241
  private sessionHistory;
221
242
  private messages;
@@ -223,6 +244,7 @@ declare class Runtime implements AsyncDisposable {
223
244
  private toolSpecs;
224
245
  private callModel;
225
246
  private compact;
247
+ private reserveModel;
226
248
  private executeStep;
227
249
  private span;
228
250
  private finish;
@@ -250,4 +272,4 @@ declare class Runtime implements AsyncDisposable {
250
272
  declare function openRuntime(config?: RuntimeConfig): Promise<Runtime>;
251
273
  declare function runAgent(agent: AgentDefinition, input: string, opts?: SendOptions & SessionOptions): Promise<TurnOutcome>;
252
274
 
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 };
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 };