taugraph 0.2.0 → 0.3.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.
@@ -0,0 +1,178 @@
1
+ import { resolveImages, textOf, } from "../nodes/index.js";
2
+ const defaultReasoningParams = (level) => ({
3
+ reasoning_effort: level === "off" ? "none" : level,
4
+ });
5
+ /** A model's own reasoning as `reasoning_content`, which DeepSeek V4 requires back in tool loops. Never another model's. */
6
+ function reasoningOf(m, modelId) {
7
+ if (modelId === undefined || m.model !== modelId || !m.reasoning?.length)
8
+ return {};
9
+ const text = m.reasoning
10
+ .filter((r) => !r.redacted)
11
+ .map((r) => r.text)
12
+ .join("\n");
13
+ return text === "" ? {} : { reasoning_content: text };
14
+ }
15
+ /** URLs OpenAI takes as they are. */
16
+ const SENDABLE = /^(https?|data):/i;
17
+ const shown = (url) => (url.length > 100 ? `${url.slice(0, 100)}…` : url);
18
+ function imageURL(image) {
19
+ if ("data" in image)
20
+ return `data:${image.mimeType};base64,${image.data}`;
21
+ if (!SENDABLE.test(image.url)) {
22
+ throw new TypeError(`Image "${shown(image.url)}" cannot be sent as a URL; make resolveImage return { data, mimeType } or an http(s) URL`);
23
+ }
24
+ return image.url;
25
+ }
26
+ const imageOf = (image) => ({ type: "image_url", image_url: { url: imageURL(image) } });
27
+ const imagesIn = (content) => typeof content === "string" ? [] : content.filter((p) => p.type === "image");
28
+ /** OpenAI's tool messages take text only, and have no error flag: errors say so in the text. */
29
+ function toolText(m) {
30
+ const text = textOf(m.content, { imagePlaceholder: "" }) || (imagesIn(m.content).length > 0 ? "(image)" : "");
31
+ return m.isError && !text.startsWith("Error") ? `Error: ${text}` : text;
32
+ }
33
+ /**
34
+ * taugraph messages in OpenAI's wire format. Images from tool results go into one user message right after the
35
+ * tool messages, since OpenAI's tool messages take text only. Image references must be read first (`resolveImage`).
36
+ * Pass the adapter's id as `modelId` to send that model's own reasoning back.
37
+ */
38
+ export function toOpenAIMessages(messages, modelId) {
39
+ const out = [];
40
+ let toolImages = [];
41
+ const flush = () => {
42
+ if (toolImages.length > 0)
43
+ out.push({ role: "user", content: toolImages });
44
+ toolImages = [];
45
+ };
46
+ for (const m of messages) {
47
+ if (m.role === "tool") {
48
+ out.push({ role: "tool", tool_call_id: m.toolCallId, content: toolText(m) });
49
+ const images = imagesIn(m.content);
50
+ if (images.length > 0) {
51
+ toolImages.push({ type: "text", text: `Images from tool call ${m.toolCallId}:` }, ...images.map(imageOf));
52
+ }
53
+ continue;
54
+ }
55
+ flush();
56
+ if (m.role === "assistant" && m.toolCalls?.length) {
57
+ out.push({
58
+ role: "assistant",
59
+ content: m.content === "" ? null : m.content,
60
+ tool_calls: m.toolCalls.map((c) => ({
61
+ id: c.id,
62
+ type: "function",
63
+ function: { name: c.name, arguments: JSON.stringify(c.arguments) },
64
+ })),
65
+ ...reasoningOf(m, modelId),
66
+ });
67
+ }
68
+ else if (m.role === "user" && typeof m.content !== "string") {
69
+ out.push({
70
+ role: "user",
71
+ content: m.content.map((p) => (p.type === "text" ? { type: "text", text: p.text } : imageOf(p))),
72
+ });
73
+ }
74
+ else {
75
+ out.push({ role: m.role, content: m.content, ...(m.role === "assistant" && reasoningOf(m, modelId)) });
76
+ }
77
+ }
78
+ flush();
79
+ return out;
80
+ }
81
+ export function toOpenAITools(tools) {
82
+ return tools.map((t) => ({
83
+ type: "function",
84
+ function: { name: t.name, ...(t.description && { description: t.description }), parameters: t.inputSchema },
85
+ }));
86
+ }
87
+ export function toOpenAIToolChoice(choice) {
88
+ return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
89
+ }
90
+ /** OpenAI's tool calls as taugraph's, arguments parsed. Unreadable arguments become `{}` with a `parseError`; missing ids become `call_<round>_<index>`. */
91
+ export function fromOpenAIToolCalls(calls, round = 1) {
92
+ return calls.flatMap((c, i) => {
93
+ const name = c.function?.name;
94
+ if (!name)
95
+ return [];
96
+ const raw = c.function?.arguments ?? "";
97
+ let parsed = {};
98
+ let parseError;
99
+ if (raw.trim() !== "") {
100
+ try {
101
+ parsed = JSON.parse(raw);
102
+ }
103
+ catch {
104
+ parseError = "arguments are not valid JSON";
105
+ }
106
+ }
107
+ const isObject = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
108
+ if (!parseError && !isObject)
109
+ parseError = "arguments are not a JSON object";
110
+ return [
111
+ {
112
+ id: c.id || `call_${round}_${i}`,
113
+ name,
114
+ arguments: isObject && !parseError ? parsed : {},
115
+ ...(parseError && { parseError }),
116
+ },
117
+ ];
118
+ });
119
+ }
120
+ export function openAICompatible(options) {
121
+ const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
122
+ const id = `openai-compatible:${options.model}`;
123
+ const readImage = (image) => {
124
+ if (/^https?:/i.test(image))
125
+ return { type: "image", url: image };
126
+ if (!options.resolveImage)
127
+ throw new TypeError(`Image "${shown(image)}" needs resolveImage to be read`);
128
+ return options.resolveImage(image);
129
+ };
130
+ return {
131
+ id,
132
+ async complete(request, { signal }) {
133
+ const messages = await resolveImages(request.messages, readImage);
134
+ const response = await (options.fetch ?? fetch)(url, {
135
+ method: "POST",
136
+ signal,
137
+ headers: {
138
+ "content-type": "application/json",
139
+ ...(options.apiKey && { authorization: `Bearer ${options.apiKey}` }),
140
+ },
141
+ body: JSON.stringify({
142
+ model: options.model,
143
+ messages: toOpenAIMessages(messages, options.sendReasoning === false ? undefined : id),
144
+ temperature: request.temperature,
145
+ max_tokens: request.maxTokens,
146
+ ...(request.responseFormat === "json" && { response_format: { type: "json_object" } }),
147
+ ...(request.tools?.length && { tools: toOpenAITools(request.tools) }),
148
+ ...(request.toolChoice && { tool_choice: toOpenAIToolChoice(request.toolChoice) }),
149
+ ...(request.reasoning && (options.reasoningParams ?? defaultReasoningParams)(request.reasoning)),
150
+ ...request.extra,
151
+ }),
152
+ });
153
+ if (!response.ok) {
154
+ throw new Error(`${url} responded ${response.status}: ${(await response.text()).slice(0, 500)}`);
155
+ }
156
+ const body = (await response.json());
157
+ const choice = body.choices?.[0];
158
+ const calls = choice?.message?.tool_calls;
159
+ const round = request.messages.filter((m) => m.role === "assistant").length + 1;
160
+ const message = choice?.message;
161
+ const thought = message?.reasoning_content || message?.reasoning;
162
+ const reasoningTokens = body.usage?.completion_tokens_details?.reasoning_tokens;
163
+ return {
164
+ content: message?.content ?? "",
165
+ ...(body.model && { model: body.model }),
166
+ ...(choice?.finish_reason && { finishReason: choice.finish_reason }),
167
+ usage: {
168
+ inputTokens: body.usage?.prompt_tokens ?? 0,
169
+ outputTokens: body.usage?.completion_tokens ?? 0,
170
+ ...(typeof reasoningTokens === "number" && { reasoningTokens }),
171
+ },
172
+ ...(thought && { reasoning: [{ text: thought }] }),
173
+ ...(calls?.length && { toolCalls: fromOpenAIToolCalls(calls, round) }),
174
+ };
175
+ },
176
+ };
177
+ }
178
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/openai/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAOL,aAAa,EAIb,MAAM,GACP,MAAM,mBAAmB,CAAC;AA+C3B,MAAM,sBAAsB,GAAG,CAAC,KAAqB,EAA2B,EAAE,CAAC,CAAC;IAClF,gBAAgB,EAAE,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK;CACnD,CAAC,CAAC;AAEH,4HAA4H;AAC5H,SAAS,WAAW,CAClB,CAA8C,EAC9C,OAA2B;IAE3B,IAAI,OAAO,KAAK,SAAS,IAAI,CAAC,CAAC,KAAK,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE,MAAM;QAAE,OAAO,EAAE,CAAC;IACpF,MAAM,IAAI,GAAG,CAAC,CAAC,SAAS;SACrB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;SAC1B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,C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I,CAAC,KAAK,EAAE,aAAa,IAAI,CAAC;oBAC3C,YAAY,EAAE,IAAI,CAAC,KAAK,EAAE,iBAAiB,IAAI,CAAC;oBAChD,GAAG,CAAC,OAAO,eAAe,KAAK,QAAQ,IAAI,EAAE,eAAe,EAAE,CAAC;iBAChE;gBACD,GAAG,CAAC,OAAO,IAAI,EAAE,SAAS,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;gBAClD,GAAG,CAAC,KAAK,EAAE,MAAM,IAAI,EAAE,SAAS,EAAE,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;aACvE,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "taugraph",
3
- "version": "0.2.0",
4
- "description": "Minimal typed agent graph harness: a graph + typed-state kernel with append-only traces and replay. Zero runtime dependencies.",
3
+ "version": "0.3.0",
4
+ "description": "Minimal typed agent graph harness: a graph + typed-state kernel with append-only traces, replay and pause/resume. Zero runtime dependencies.",
5
5
  "keywords": [
6
6
  "agent",
7
7
  "llm",
@@ -12,7 +12,9 @@
12
12
  "trace",
13
13
  "replay",
14
14
  "standard-schema",
15
- "zod"
15
+ "zod",
16
+ "human-in-the-loop",
17
+ "pause-resume"
16
18
  ],
17
19
  "license": "MIT",
18
20
  "author": "wangcao-hub (https://github.com/wangcao-hub)",
@@ -35,6 +37,14 @@
35
37
  "types": "./dist/nodes/index.d.ts",
36
38
  "import": "./dist/nodes/index.js"
37
39
  },
40
+ "./agent": {
41
+ "types": "./dist/agent/index.d.ts",
42
+ "import": "./dist/agent/index.js"
43
+ },
44
+ "./openai": {
45
+ "types": "./dist/openai/index.d.ts",
46
+ "import": "./dist/openai/index.js"
47
+ },
38
48
  "./package.json": "./package.json"
39
49
  },
40
50
  "files": [
@@ -42,6 +52,7 @@
42
52
  "src",
43
53
  "README.md",
44
54
  "README.zh-CN.md",
55
+ "CHANGELOG.md",
45
56
  "LICENSE"
46
57
  ],
47
58
  "engines": {
@@ -63,6 +74,7 @@
63
74
  "example:quickstart": "tsx examples/quickstart.ts",
64
75
  "example:rag": "tsx examples/rag-retry.ts",
65
76
  "example:checkout": "tsx examples/checkout.ts",
77
+ "example:agent": "tsx examples/agent.ts",
66
78
  "prepublishOnly": "pnpm check && pnpm build"
67
79
  },
68
80
  "devDependencies": {
@@ -0,0 +1,315 @@
1
+ // The model <-> tools loop as a taugraph graph: one step per model call and one step per tool call, so the trace,
2
+ // replay, write protection, crash recovery and approvals all apply to every single call.
3
+ //
4
+ // think --a call, read--> act --------+-- more calls --> act / act_write
5
+ // | --a call, write--> act_write --+-- none left ---> think
6
+ // +--no calls, or maxRounds reached--> finish
7
+ import {
8
+ createGraph,
9
+ defineNode,
10
+ type Effect,
11
+ type Graph,
12
+ type MaybePromise,
13
+ type RetryPolicy,
14
+ type RunContext,
15
+ type StandardSchemaV1,
16
+ } from "../index.js";
17
+ import {
18
+ type ChatMessage,
19
+ type LLMModel,
20
+ LLMNode,
21
+ type MessageContent,
22
+ type ReasoningLevel,
23
+ type ToolCall,
24
+ type ToolChoice,
25
+ type ToolSpec,
26
+ } from "../nodes/index.js";
27
+ import { type AgentInput, type AgentState, agentStateSchema, checkContent } from "./state.js";
28
+ import { andThen, issuesText, settle } from "./util.js";
29
+
30
+ export { type AgentInput, type AgentState, type AgentStop, agentStateSchema } from "./state.js";
31
+
32
+ export type ToolArgs = Readonly<Record<string, unknown>>;
33
+
34
+ export interface ToolContext {
35
+ readonly call: ToolCall;
36
+ readonly signal: AbortSignal;
37
+ /** The step was running when an earlier trace ended and was started again. */
38
+ readonly recovered: boolean;
39
+ }
40
+
41
+ /** A string, or text and images in order (`isError` tells the model the call failed). */
42
+ export type ToolResult = string | { readonly content: MessageContent; readonly isError?: boolean };
43
+
44
+ export interface Tool<A = ToolArgs> {
45
+ readonly name: string;
46
+ readonly description?: string;
47
+ /** Validates the arguments, and becomes the JSON Schema the model sees (Standard JSON Schema). */
48
+ readonly input?: StandardSchemaV1<unknown, A>;
49
+ /** JSON Schema for the model, when `input` cannot produce one or you want your own. Wins over `input`. */
50
+ readonly inputSchema?: Readonly<Record<string, unknown>>;
51
+ /** `"write"` for tools that change the outside world: they run in a write step, never repeated by replay. */
52
+ readonly effect?: Effect;
53
+ run(args: A, ctx: ToolContext): MaybePromise<ToolResult>;
54
+ }
55
+
56
+ /** Defines a tool. Returns it unchanged; it only lets `args` take its type from `input`. */
57
+ export function tool<A = ToolArgs>(definition: Tool<A>): Tool<A> {
58
+ return definition;
59
+ }
60
+
61
+ export type ApprovalDecision = "run" | "deny" | "ask";
62
+
63
+ /** Recorded by the pause when a call waits for approval. Resume with `true`, `false` or `{ approved, reason? }`. */
64
+ export interface ToolApprovalRequest {
65
+ readonly type: "tool_approval";
66
+ readonly call: ToolCall;
67
+ readonly effect: Effect;
68
+ }
69
+
70
+ // biome-ignore lint/suspicious/noExplicitAny: each tool has its own argument type
71
+ type AnyTool = Tool<any>;
72
+
73
+ export interface AgentConfig {
74
+ readonly model: LLMModel;
75
+ readonly tools?: readonly AnyTool[];
76
+ readonly system?: string;
77
+ /** Model calls allowed in one run. Default 8. */
78
+ readonly maxRounds?: number;
79
+ readonly toolChoice?: ToolChoice;
80
+ readonly temperature?: number;
81
+ readonly maxTokens?: number;
82
+ /** How much the model should think before each answer. Unset: the model's default. */
83
+ readonly reasoning?: ReasoningLevel;
84
+ /** Retries a failed model call. */
85
+ readonly retry?: RetryPolicy;
86
+ /**
87
+ * Decides each call before it runs: run it, refuse it, or pause and ask (`ctx.interrupt`). Called again when
88
+ * the run resumes, so keep it pure. Without it every call runs.
89
+ */
90
+ readonly approve?: (call: ToolCall, tool: AnyTool, state: AgentState) => ApprovalDecision;
91
+ }
92
+
93
+ export type AgentNodeId = "think" | "act" | "act_write" | "finish";
94
+ export type AgentGraph = Graph<AgentState, AgentInput, AgentNodeId>;
95
+
96
+ export const AGENT_DEFAULTS = Object.freeze({ maxRounds: 8, maxCallsPerReply: 32, maxSteps: 1000 });
97
+
98
+ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
99
+ const DENIED = "The user did not allow this call";
100
+ const TOO_MANY = `Too many tool calls in one reply; at most ${AGENT_DEFAULTS.maxCallsPerReply} run`;
101
+
102
+ interface JSONSchemaProps {
103
+ readonly jsonSchema?: { readonly input: (options: { readonly target: string }) => Record<string, unknown> };
104
+ }
105
+
106
+ function inputSchemaOf(t: AnyTool): Readonly<Record<string, unknown>> {
107
+ if (t.inputSchema) return t.inputSchema;
108
+ const converter = (t.input?.["~standard"] as JSONSchemaProps | undefined)?.jsonSchema;
109
+ if (!converter) return { type: "object" };
110
+ try {
111
+ const json = converter.input({ target: "draft-2020-12" });
112
+ return Object.fromEntries(Object.entries(json).filter(([key]) => key !== "$schema"));
113
+ } catch (cause) {
114
+ throw new TypeError(`createAgent: the input schema of tool "${t.name}" has no JSON Schema form; pass inputSchema`, {
115
+ cause,
116
+ });
117
+ }
118
+ }
119
+
120
+ const toolMessage = (id: string, content: MessageContent, isError: boolean): ChatMessage => ({
121
+ role: "tool",
122
+ toolCallId: id,
123
+ content,
124
+ ...(isError && { isError: true }),
125
+ });
126
+
127
+ function lastAnswer(messages: readonly ChatMessage[]): string {
128
+ for (let i = messages.length - 1; i >= 0; i--) {
129
+ const m = messages[i];
130
+ if (m?.role === "assistant") return m.content;
131
+ }
132
+ return "";
133
+ }
134
+
135
+ /** Error answers for the calls of the last assistant message that have none: the ones beyond the per-reply limit. */
136
+ function unanswered(messages: readonly ChatMessage[]): ChatMessage[] {
137
+ let i = messages.length - 1;
138
+ while (i >= 0 && messages[i]?.role !== "assistant") i--;
139
+ const last = messages[i];
140
+ if (last?.role !== "assistant" || !last.toolCalls) return [];
141
+ const done = new Set(messages.slice(i + 1).flatMap((m) => (m.role === "tool" ? [m.toolCallId] : [])));
142
+ return last.toolCalls.filter((c) => !done.has(c.id)).map((c) => toolMessage(c.id, TOO_MANY, true));
143
+ }
144
+
145
+ function readApproval(answer: unknown): { approved: boolean; reason?: string } {
146
+ if (answer === true) return { approved: true };
147
+ if (typeof answer !== "object" || answer === null) return { approved: false };
148
+ const { approved, reason } = answer as { approved?: unknown; reason?: unknown };
149
+ return { approved: approved === true, ...(typeof reason === "string" && reason !== "" && { reason }) };
150
+ }
151
+
152
+ function resultOf(t: AnyTool, value: unknown): { content: MessageContent; isError: boolean } {
153
+ if (typeof value === "string") return { content: value, isError: false };
154
+ const content = typeof value === "object" && value !== null ? (value as { content?: unknown }).content : undefined;
155
+ if (typeof content !== "string" && !Array.isArray(content)) {
156
+ throw new TypeError(`Tool "${t.name}" returned neither a string nor { content: string | ContentPart[] }`);
157
+ }
158
+ const issues: StandardSchemaV1.Issue[] = [];
159
+ checkContent(content, ["content"], issues, true);
160
+ if (issues.length > 0) throw new TypeError(`Tool "${t.name}" returned bad content: ${issuesText(issues)}`);
161
+ return { content: content as MessageContent, isError: (value as { isError?: unknown }).isError === true };
162
+ }
163
+
164
+ /** The model <-> tools loop as a graph. Every model call and every tool call is a step of its own. */
165
+ export function createAgent(config: AgentConfig): AgentGraph {
166
+ const tools = new Map<string, AnyTool>();
167
+ for (const t of config.tools ?? []) {
168
+ if (!TOOL_NAME.test(t.name)) throw new TypeError(`createAgent: tool name "${t.name}" must match ${TOOL_NAME}`);
169
+ if (tools.has(t.name)) throw new TypeError(`createAgent: two tools are named "${t.name}"`);
170
+ if (t.effect !== undefined && t.effect !== "read" && t.effect !== "write") {
171
+ throw new TypeError(`createAgent: tool "${t.name}" has effect ${String(t.effect)}; use "read" or "write"`);
172
+ }
173
+ tools.set(t.name, t);
174
+ }
175
+ const maxRounds = config.maxRounds ?? AGENT_DEFAULTS.maxRounds;
176
+ if (!Number.isInteger(maxRounds) || maxRounds < 1)
177
+ throw new TypeError("createAgent: maxRounds must be an integer >= 1");
178
+ const specs: ToolSpec[] = [...tools.values()].map((t) => ({
179
+ name: t.name,
180
+ ...(t.description && { description: t.description }),
181
+ inputSchema: inputSchemaOf(t),
182
+ }));
183
+
184
+ const callModel = LLMNode<AgentState>({
185
+ model: config.model,
186
+ ...(config.retry && { retry: config.retry }),
187
+ prompt: (s) => ({
188
+ messages: [...(config.system ? [{ role: "system" as const, content: config.system }] : []), ...s.messages],
189
+ ...(specs.length > 0 && { tools: specs }),
190
+ ...(config.toolChoice && { toolChoice: config.toolChoice }),
191
+ ...(config.temperature !== undefined && { temperature: config.temperature }),
192
+ ...(config.maxTokens !== undefined && { maxTokens: config.maxTokens }),
193
+ ...(config.reasoning && { reasoning: config.reasoning }),
194
+ }),
195
+ update: (s, text, response) => {
196
+ const round = s.rounds + 1;
197
+ const calls = (response.toolCalls ?? []).map((c, i) => ({ ...c, id: c.id || `call_${round}_${i}` }));
198
+ const run = calls.slice(0, AGENT_DEFAULTS.maxCallsPerReply);
199
+ const assistant: ChatMessage = {
200
+ role: "assistant",
201
+ content: text,
202
+ ...(calls.length > 0 && { toolCalls: calls }),
203
+ ...(response.reasoning?.length && { reasoning: response.reasoning }),
204
+ model: config.model.id, // signatures are only valid for the model that wrote them
205
+ };
206
+ return {
207
+ ...s,
208
+ messages: [...s.messages, assistant],
209
+ pending: run,
210
+ rounds: round,
211
+ final: run.length === 0 ? text : null,
212
+ stop: run.length === 0 ? "done" : null,
213
+ };
214
+ },
215
+ });
216
+
217
+ const think = defineNode<AgentState>(
218
+ (s, ctx) => {
219
+ if (s.pending.length > 0) return s; // calls left from where an earlier run stopped: run them first
220
+ if (s.rounds >= maxRounds) return { ...s, stop: "max_rounds", final: lastAnswer(s.messages) };
221
+ return callModel(s, ctx);
222
+ },
223
+ { kind: "llm", ...(config.retry && { retry: config.retry }) },
224
+ );
225
+
226
+ /** Runs `pending[0]`. Everything before the tool runs is pure, so re-running the step on resume is safe. */
227
+ const act = (effect: Effect) =>
228
+ defineNode<AgentState>(
229
+ (s, ctx: RunContext): MaybePromise<AgentState> => {
230
+ const call = s.pending[0];
231
+ if (!call) return s;
232
+ const answered = (content: MessageContent, isError: boolean): AgentState => {
233
+ const messages = [...s.messages, toolMessage(call.id, content, isError)];
234
+ // after the last call that runs, answer the ones beyond the per-reply limit, so they come last
235
+ return {
236
+ ...s,
237
+ messages: s.pending.length === 1 ? [...messages, ...unanswered(messages)] : messages,
238
+ pending: s.pending.slice(1),
239
+ };
240
+ };
241
+ const t = tools.get(call.name);
242
+ if (!t) return answered(`No tool named "${call.name}"`, true);
243
+ if (call.parseError) return answered(`Invalid arguments: ${call.parseError}`, true);
244
+ const checked = t.input ? t.input["~standard"].validate(call.arguments) : { value: call.arguments };
245
+ return andThen(checked, (result): MaybePromise<AgentState> => {
246
+ if (result.issues) return answered(`Invalid arguments: ${issuesText(result.issues)}`, true);
247
+ const decision = config.approve?.(call, t, s) ?? "run";
248
+ if (decision === "deny") return answered(DENIED, true);
249
+ if (decision === "ask") {
250
+ const request: ToolApprovalRequest = { type: "tool_approval", call, effect };
251
+ const { approved, reason } = readApproval(ctx.interrupt<unknown>(request));
252
+ if (!approved) return answered(reason ? `${DENIED}: ${reason}` : DENIED, true);
253
+ }
254
+ const startedAt = Date.now();
255
+ const record = (content: MessageContent, isError: boolean, failed: boolean): AgentState => {
256
+ ctx.trace.append({
257
+ type: "tool_call",
258
+ input: { id: call.id, name: call.name, arguments: call.arguments },
259
+ output: { content, isError },
260
+ meta: { effect, durationMs: Date.now() - startedAt, ...(failed && { error: true }) },
261
+ });
262
+ return answered(content, isError);
263
+ };
264
+ return settle(
265
+ () => t.run(result.value, { call, signal: ctx.signal, recovered: ctx.meta.recovered }),
266
+ (value) => {
267
+ const { content, isError } = resultOf(t, value);
268
+ return record(content, isError, false);
269
+ },
270
+ (error) => {
271
+ if (ctx.signal.aborted) throw error; // a cancelled run stops; it is not the tool's answer
272
+ return record(String(error instanceof Error ? `Error: ${error.message}` : error), true, true);
273
+ },
274
+ );
275
+ });
276
+ },
277
+ { kind: "tool", ...(effect === "write" && { effect }) },
278
+ );
279
+
280
+ const next = (s: AgentState): AgentNodeId => {
281
+ const call = s.pending[0];
282
+ if (call) return tools.get(call.name)?.effect === "write" ? "act_write" : "act";
283
+ return s.stop ? "finish" : "think";
284
+ };
285
+
286
+ const graph = createGraph(agentStateSchema, {
287
+ start: "think",
288
+ nodes: {
289
+ think,
290
+ act: act("read"),
291
+ act_write: act("write"),
292
+ finish: defineNode<AgentState>((s) => s, { kind: "code" }),
293
+ },
294
+ conditionalEdges: [
295
+ { from: "think", route: next, targets: ["act", "act_write", "finish"] },
296
+ { from: "act", route: next, targets: ["act", "act_write", "think"] },
297
+ { from: "act_write", route: next, targets: ["act", "act_write", "think"] },
298
+ ],
299
+ endNodes: ["finish"],
300
+ });
301
+
302
+ // maxRounds is the real bound; the kernel's step guard only has to leave room for every call of every round.
303
+ const steps = <O extends { readonly maxSteps?: number }>(options?: O): O =>
304
+ ({ ...options, maxSteps: options?.maxSteps ?? AGENT_DEFAULTS.maxSteps }) as O;
305
+ return Object.freeze({
306
+ start: graph.start,
307
+ nodeIds: graph.nodeIds,
308
+ endNodes: graph.endNodes,
309
+ run: (input, options) => graph.run(input, steps(options)),
310
+ runSync: (input, options) => graph.runSync(input, steps(options)),
311
+ resume: (trace, value, options) => graph.resume(trace, value, steps(options)),
312
+ resumeSync: (trace, value, options) => graph.resumeSync(trace, value, steps(options)),
313
+ replay: (trace, options) => graph.replay(trace, steps(options)),
314
+ } satisfies AgentGraph);
315
+ }