taugraph 0.2.0 → 0.4.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/CHANGELOG.md +89 -0
- package/README.md +283 -22
- package/README.zh-CN.md +283 -22
- package/dist/agent/index.d.ts +74 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +254 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/state.d.ts +30 -0
- package/dist/agent/state.d.ts.map +1 -0
- package/dist/agent/state.js +135 -0
- package/dist/agent/state.js.map +1 -0
- package/dist/agent/util.d.ts +19 -0
- package/dist/agent/util.d.ts.map +1 -0
- package/dist/agent/util.js +59 -0
- package/dist/agent/util.js.map +1 -0
- package/dist/core/engine.d.ts +1 -1
- package/dist/core/engine.d.ts.map +1 -1
- package/dist/core/engine.js +237 -35
- package/dist/core/engine.js.map +1 -1
- package/dist/core/errors.d.ts +2 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js.map +1 -1
- package/dist/core/graph.d.ts.map +1 -1
- package/dist/core/graph.js +9 -1
- package/dist/core/graph.js.map +1 -1
- package/dist/core/node.d.ts +6 -1
- package/dist/core/node.d.ts.map +1 -1
- package/dist/core/node.js +55 -6
- package/dist/core/node.js.map +1 -1
- package/dist/core/patch.d.ts +26 -0
- package/dist/core/patch.d.ts.map +1 -0
- package/dist/core/patch.js +192 -0
- package/dist/core/patch.js.map +1 -0
- package/dist/core/retry.d.ts +20 -0
- package/dist/core/retry.d.ts.map +1 -0
- package/dist/core/retry.js +79 -0
- package/dist/core/retry.js.map +1 -0
- package/dist/core/trace.d.ts +39 -8
- package/dist/core/trace.d.ts.map +1 -1
- package/dist/core/trace.js +222 -29
- package/dist/core/trace.js.map +1 -1
- package/dist/core/types.d.ts +35 -4
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/util.d.ts +5 -1
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +41 -9
- package/dist/core/util.js.map +1 -1
- package/dist/file/index.d.ts +26 -0
- package/dist/file/index.d.ts.map +1 -0
- package/dist/file/index.js +373 -0
- package/dist/file/index.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/nodes/code.d.ts +5 -0
- package/dist/nodes/code.d.ts.map +1 -1
- package/dist/nodes/code.js.map +1 -1
- package/dist/nodes/content.d.ts +18 -0
- package/dist/nodes/content.d.ts.map +1 -0
- package/dist/nodes/content.js +88 -0
- package/dist/nodes/content.js.map +1 -0
- package/dist/nodes/index.d.ts +2 -1
- package/dist/nodes/index.d.ts.map +1 -1
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/index.js.map +1 -1
- package/dist/nodes/llm.d.ts +100 -4
- package/dist/nodes/llm.d.ts.map +1 -1
- package/dist/nodes/llm.js +5 -1
- package/dist/nodes/llm.js.map +1 -1
- package/dist/openai/index.d.ts +55 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +208 -0
- package/dist/openai/index.js.map +1 -0
- package/package.json +20 -4
- package/src/agent/index.ts +359 -0
- package/src/agent/state.ts +147 -0
- package/src/agent/util.ts +74 -0
- package/src/core/engine.ts +241 -34
- package/src/core/errors.ts +2 -0
- package/src/core/graph.ts +7 -1
- package/src/core/node.ts +55 -6
- package/src/core/patch.ts +173 -0
- package/src/core/retry.ts +89 -0
- package/src/core/trace.ts +222 -29
- package/src/core/types.ts +37 -4
- package/src/core/util.ts +43 -10
- package/src/file/index.ts +408 -0
- package/src/index.ts +5 -1
- package/src/nodes/code.ts +5 -0
- package/src/nodes/content.ts +100 -0
- package/src/nodes/index.ts +10 -0
- package/src/nodes/llm.ts +109 -7
- package/src/openai/index.ts +286 -0
|
@@ -0,0 +1,359 @@
|
|
|
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
|
+
TaugraphError,
|
|
17
|
+
} from "../index.js";
|
|
18
|
+
import {
|
|
19
|
+
type ChatMessage,
|
|
20
|
+
type LLMModel,
|
|
21
|
+
LLMNode,
|
|
22
|
+
type MessageContent,
|
|
23
|
+
type ReasoningLevel,
|
|
24
|
+
type ToolCall,
|
|
25
|
+
type ToolChoice,
|
|
26
|
+
type ToolSpec,
|
|
27
|
+
} from "../nodes/index.js";
|
|
28
|
+
import { type AgentInput, type AgentState, agentStateSchema, checkContent } from "./state.js";
|
|
29
|
+
import { andThen, deadline, issuesText, isThenable, settle } from "./util.js";
|
|
30
|
+
|
|
31
|
+
export { type AgentInput, type AgentState, type AgentStop, agentStateSchema } from "./state.js";
|
|
32
|
+
|
|
33
|
+
export type ToolArgs = Readonly<Record<string, unknown>>;
|
|
34
|
+
|
|
35
|
+
export interface ToolContext {
|
|
36
|
+
readonly call: ToolCall;
|
|
37
|
+
readonly signal: AbortSignal;
|
|
38
|
+
/** The step was running when an earlier trace ended and was started again. */
|
|
39
|
+
readonly recovered: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A string, or text and images in order (`isError` tells the model the call failed). */
|
|
43
|
+
export type ToolResult = string | { readonly content: MessageContent; readonly isError?: boolean };
|
|
44
|
+
|
|
45
|
+
export interface Tool<A = ToolArgs> {
|
|
46
|
+
readonly name: string;
|
|
47
|
+
readonly description?: string;
|
|
48
|
+
/** Validates the arguments, and becomes the JSON Schema the model sees (Standard JSON Schema). */
|
|
49
|
+
readonly input?: StandardSchemaV1<unknown, A>;
|
|
50
|
+
/** JSON Schema for the model, when `input` cannot produce one or you want your own. Wins over `input`. */
|
|
51
|
+
readonly inputSchema?: Readonly<Record<string, unknown>>;
|
|
52
|
+
/** `"write"` for tools that change the outside world: they run in a write step, never repeated by replay. */
|
|
53
|
+
readonly effect?: Effect;
|
|
54
|
+
/**
|
|
55
|
+
* Milliseconds one run may take; then its `signal` aborts. A read tool that takes longer answers the model with an
|
|
56
|
+
* error and the loop goes on. A write tool fails the run with TIMEOUT, since its effect may or may not have
|
|
57
|
+
* happened. Synchronous tools cannot be interrupted.
|
|
58
|
+
*/
|
|
59
|
+
readonly timeoutMs?: number;
|
|
60
|
+
run(args: A, ctx: ToolContext): MaybePromise<ToolResult>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Defines a tool. Returns it unchanged; it only lets `args` take its type from `input`. */
|
|
64
|
+
export function tool<A = ToolArgs>(definition: Tool<A>): Tool<A> {
|
|
65
|
+
return definition;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type ApprovalDecision = "run" | "deny" | "ask";
|
|
69
|
+
|
|
70
|
+
/** Recorded by the pause when a call waits for approval. Resume with `true`, `false` or `{ approved, reason? }`. */
|
|
71
|
+
export interface ToolApprovalRequest {
|
|
72
|
+
readonly type: "tool_approval";
|
|
73
|
+
readonly call: ToolCall;
|
|
74
|
+
readonly effect: Effect;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// biome-ignore lint/suspicious/noExplicitAny: each tool has its own argument type
|
|
78
|
+
type AnyTool = Tool<any>;
|
|
79
|
+
|
|
80
|
+
export interface AgentConfig {
|
|
81
|
+
readonly model: LLMModel;
|
|
82
|
+
readonly tools?: readonly AnyTool[];
|
|
83
|
+
readonly system?: string;
|
|
84
|
+
/** Model calls allowed in one run. Default 8. */
|
|
85
|
+
readonly maxRounds?: number;
|
|
86
|
+
readonly toolChoice?: ToolChoice;
|
|
87
|
+
readonly temperature?: number;
|
|
88
|
+
readonly maxTokens?: number;
|
|
89
|
+
/** How much the model should think before each answer. Unset: the model's default. */
|
|
90
|
+
readonly reasoning?: ReasoningLevel;
|
|
91
|
+
/** Retries a failed model call. */
|
|
92
|
+
readonly retry?: RetryPolicy;
|
|
93
|
+
/** Milliseconds each model call may take; a slower call fails with TIMEOUT, which `retry` retries. */
|
|
94
|
+
readonly timeoutMs?: number;
|
|
95
|
+
/**
|
|
96
|
+
* Decides each call before it runs: run it, refuse it, or pause and ask (`ctx.interrupt`). Called again when
|
|
97
|
+
* the run resumes, so keep it pure. Without it every call runs.
|
|
98
|
+
*/
|
|
99
|
+
readonly approve?: (call: ToolCall, tool: AnyTool, state: AgentState) => ApprovalDecision;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export type AgentNodeId = "think" | "act" | "act_write" | "finish";
|
|
103
|
+
export type AgentGraph = Graph<AgentState, AgentInput, AgentNodeId>;
|
|
104
|
+
|
|
105
|
+
export const AGENT_DEFAULTS = Object.freeze({ maxRounds: 8, maxCallsPerReply: 32, maxSteps: 1000 });
|
|
106
|
+
|
|
107
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
108
|
+
const DENIED = "The user did not allow this call";
|
|
109
|
+
const TOO_MANY = `Too many tool calls in one reply; at most ${AGENT_DEFAULTS.maxCallsPerReply} run`;
|
|
110
|
+
const MAX_TIMEOUT = 2_147_483_647;
|
|
111
|
+
const badTimeout = (ms: unknown): boolean =>
|
|
112
|
+
ms !== undefined && !(Number.isInteger(ms) && (ms as number) >= 1 && (ms as number) <= MAX_TIMEOUT);
|
|
113
|
+
|
|
114
|
+
interface JSONSchemaProps {
|
|
115
|
+
readonly jsonSchema?: { readonly input: (options: { readonly target: string }) => Record<string, unknown> };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function inputSchemaOf(t: AnyTool): Readonly<Record<string, unknown>> {
|
|
119
|
+
if (t.inputSchema) return t.inputSchema;
|
|
120
|
+
const converter = (t.input?.["~standard"] as JSONSchemaProps | undefined)?.jsonSchema;
|
|
121
|
+
if (!converter) return { type: "object" };
|
|
122
|
+
try {
|
|
123
|
+
const json = converter.input({ target: "draft-2020-12" });
|
|
124
|
+
return Object.fromEntries(Object.entries(json).filter(([key]) => key !== "$schema"));
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
throw new TypeError(`createAgent: the input schema of tool "${t.name}" has no JSON Schema form; pass inputSchema`, {
|
|
127
|
+
cause,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const toolMessage = (id: string, content: MessageContent, isError: boolean): ChatMessage => ({
|
|
133
|
+
role: "tool",
|
|
134
|
+
toolCallId: id,
|
|
135
|
+
content,
|
|
136
|
+
...(isError && { isError: true }),
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
function lastAnswer(messages: readonly ChatMessage[]): string {
|
|
140
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
141
|
+
const m = messages[i];
|
|
142
|
+
if (m?.role === "assistant") return m.content;
|
|
143
|
+
}
|
|
144
|
+
return "";
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Error answers for the calls of the last assistant message that have none: the ones beyond the per-reply limit. */
|
|
148
|
+
function unanswered(messages: readonly ChatMessage[]): ChatMessage[] {
|
|
149
|
+
let i = messages.length - 1;
|
|
150
|
+
while (i >= 0 && messages[i]?.role !== "assistant") i--;
|
|
151
|
+
const last = messages[i];
|
|
152
|
+
if (last?.role !== "assistant" || !last.toolCalls) return [];
|
|
153
|
+
const done = new Set(messages.slice(i + 1).flatMap((m) => (m.role === "tool" ? [m.toolCallId] : [])));
|
|
154
|
+
return last.toolCalls.filter((c) => !done.has(c.id)).map((c) => toolMessage(c.id, TOO_MANY, true));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function readApproval(answer: unknown): { approved: boolean; reason?: string } {
|
|
158
|
+
if (answer === true) return { approved: true };
|
|
159
|
+
if (typeof answer !== "object" || answer === null) return { approved: false };
|
|
160
|
+
const { approved, reason } = answer as { approved?: unknown; reason?: unknown };
|
|
161
|
+
return { approved: approved === true, ...(typeof reason === "string" && reason !== "" && { reason }) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function resultOf(t: AnyTool, value: unknown): { content: MessageContent; isError: boolean } {
|
|
165
|
+
if (typeof value === "string") return { content: value, isError: false };
|
|
166
|
+
const content = typeof value === "object" && value !== null ? (value as { content?: unknown }).content : undefined;
|
|
167
|
+
if (typeof content !== "string" && !Array.isArray(content)) {
|
|
168
|
+
throw new TypeError(`Tool "${t.name}" returned neither a string nor { content: string | ContentPart[] }`);
|
|
169
|
+
}
|
|
170
|
+
const issues: StandardSchemaV1.Issue[] = [];
|
|
171
|
+
checkContent(content, ["content"], issues, true);
|
|
172
|
+
if (issues.length > 0) throw new TypeError(`Tool "${t.name}" returned bad content: ${issuesText(issues)}`);
|
|
173
|
+
return { content: content as MessageContent, isError: (value as { isError?: unknown }).isError === true };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The model <-> tools loop as a graph. Every model call and every tool call is a step of its own. */
|
|
177
|
+
export function createAgent(config: AgentConfig): AgentGraph {
|
|
178
|
+
const tools = new Map<string, AnyTool>();
|
|
179
|
+
for (const t of config.tools ?? []) {
|
|
180
|
+
if (!TOOL_NAME.test(t.name)) throw new TypeError(`createAgent: tool name "${t.name}" must match ${TOOL_NAME}`);
|
|
181
|
+
if (tools.has(t.name)) throw new TypeError(`createAgent: two tools are named "${t.name}"`);
|
|
182
|
+
if (t.effect !== undefined && t.effect !== "read" && t.effect !== "write") {
|
|
183
|
+
throw new TypeError(`createAgent: tool "${t.name}" has effect ${String(t.effect)}; use "read" or "write"`);
|
|
184
|
+
}
|
|
185
|
+
if (badTimeout(t.timeoutMs)) {
|
|
186
|
+
throw new TypeError(
|
|
187
|
+
`createAgent: tool "${t.name}" has timeoutMs ${String(t.timeoutMs)}; use an integer from 1 to ${MAX_TIMEOUT}`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
tools.set(t.name, t);
|
|
191
|
+
}
|
|
192
|
+
const maxRounds = config.maxRounds ?? AGENT_DEFAULTS.maxRounds;
|
|
193
|
+
if (!Number.isInteger(maxRounds) || maxRounds < 1)
|
|
194
|
+
throw new TypeError("createAgent: maxRounds must be an integer >= 1");
|
|
195
|
+
if (badTimeout(config.timeoutMs)) {
|
|
196
|
+
throw new TypeError(
|
|
197
|
+
`createAgent: timeoutMs must be an integer from 1 to ${MAX_TIMEOUT}, got ${String(config.timeoutMs)}`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const specs: ToolSpec[] = [...tools.values()].map((t) => ({
|
|
201
|
+
name: t.name,
|
|
202
|
+
...(t.description && { description: t.description }),
|
|
203
|
+
inputSchema: inputSchemaOf(t),
|
|
204
|
+
}));
|
|
205
|
+
|
|
206
|
+
const callModel = LLMNode<AgentState>({
|
|
207
|
+
model: config.model,
|
|
208
|
+
...(config.retry && { retry: config.retry }),
|
|
209
|
+
prompt: (s) => ({
|
|
210
|
+
messages: [...(config.system ? [{ role: "system" as const, content: config.system }] : []), ...s.messages],
|
|
211
|
+
...(specs.length > 0 && { tools: specs }),
|
|
212
|
+
...(config.toolChoice && { toolChoice: config.toolChoice }),
|
|
213
|
+
...(config.temperature !== undefined && { temperature: config.temperature }),
|
|
214
|
+
...(config.maxTokens !== undefined && { maxTokens: config.maxTokens }),
|
|
215
|
+
...(config.reasoning && { reasoning: config.reasoning }),
|
|
216
|
+
}),
|
|
217
|
+
update: (s, text, response) => {
|
|
218
|
+
const round = s.rounds + 1;
|
|
219
|
+
const calls = (response.toolCalls ?? []).map((c, i) => ({ ...c, id: c.id || `call_${round}_${i}` }));
|
|
220
|
+
const run = calls.slice(0, AGENT_DEFAULTS.maxCallsPerReply);
|
|
221
|
+
const assistant: ChatMessage = {
|
|
222
|
+
role: "assistant",
|
|
223
|
+
content: text,
|
|
224
|
+
...(calls.length > 0 && { toolCalls: calls }),
|
|
225
|
+
...(response.reasoning?.length && { reasoning: response.reasoning }),
|
|
226
|
+
model: config.model.id, // signatures are only valid for the model that wrote them
|
|
227
|
+
};
|
|
228
|
+
return {
|
|
229
|
+
...s,
|
|
230
|
+
messages: [...s.messages, assistant],
|
|
231
|
+
pending: run,
|
|
232
|
+
rounds: round,
|
|
233
|
+
final: run.length === 0 ? text : null,
|
|
234
|
+
stop: run.length === 0 ? "done" : null,
|
|
235
|
+
};
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
const think = defineNode<AgentState>(
|
|
240
|
+
(s, ctx) => {
|
|
241
|
+
if (s.pending.length > 0) return s; // calls left from where an earlier run stopped: run them first
|
|
242
|
+
if (s.rounds >= maxRounds) return { ...s, stop: "max_rounds", final: lastAnswer(s.messages) };
|
|
243
|
+
return callModel(s, ctx);
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
kind: "llm",
|
|
247
|
+
...(config.retry && { retry: config.retry }),
|
|
248
|
+
...(config.timeoutMs !== undefined && { timeoutMs: config.timeoutMs }),
|
|
249
|
+
},
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
/** Runs `pending[0]`. Everything before the tool runs is pure, so re-running the step on resume is safe. */
|
|
253
|
+
const act = (effect: Effect) =>
|
|
254
|
+
defineNode<AgentState>(
|
|
255
|
+
(s, ctx: RunContext): MaybePromise<AgentState> => {
|
|
256
|
+
const call = s.pending[0];
|
|
257
|
+
if (!call) return s;
|
|
258
|
+
const answered = (content: MessageContent, isError: boolean): AgentState => {
|
|
259
|
+
const messages = [...s.messages, toolMessage(call.id, content, isError)];
|
|
260
|
+
// after the last call that runs, answer the ones beyond the per-reply limit, so they come last
|
|
261
|
+
return {
|
|
262
|
+
...s,
|
|
263
|
+
messages: s.pending.length === 1 ? [...messages, ...unanswered(messages)] : messages,
|
|
264
|
+
pending: s.pending.slice(1),
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
const t = tools.get(call.name);
|
|
268
|
+
if (!t) return answered(`No tool named "${call.name}"`, true);
|
|
269
|
+
if (call.parseError) return answered(`Invalid arguments: ${call.parseError}`, true);
|
|
270
|
+
const checked = t.input ? t.input["~standard"].validate(call.arguments) : { value: call.arguments };
|
|
271
|
+
return andThen(checked, (result): MaybePromise<AgentState> => {
|
|
272
|
+
if (result.issues) return answered(`Invalid arguments: ${issuesText(result.issues)}`, true);
|
|
273
|
+
const decision = config.approve?.(call, t, s) ?? "run";
|
|
274
|
+
if (decision === "deny") return answered(DENIED, true);
|
|
275
|
+
if (decision === "ask") {
|
|
276
|
+
const request: ToolApprovalRequest = { type: "tool_approval", call, effect };
|
|
277
|
+
const { approved, reason } = readApproval(ctx.interrupt<unknown>(request));
|
|
278
|
+
if (!approved) return answered(reason ? `${DENIED}: ${reason}` : DENIED, true);
|
|
279
|
+
}
|
|
280
|
+
const startedAt = Date.now();
|
|
281
|
+
const record = (content: MessageContent, isError: boolean, failed: boolean): AgentState => {
|
|
282
|
+
ctx.trace.append({
|
|
283
|
+
type: "tool_call",
|
|
284
|
+
input: { id: call.id, name: call.name, arguments: call.arguments },
|
|
285
|
+
output: { content, isError },
|
|
286
|
+
meta: { effect, durationMs: Date.now() - startedAt, ...(failed && { error: true }) },
|
|
287
|
+
});
|
|
288
|
+
return answered(content, isError);
|
|
289
|
+
};
|
|
290
|
+
const limit =
|
|
291
|
+
t.timeoutMs === undefined
|
|
292
|
+
? undefined
|
|
293
|
+
: deadline(
|
|
294
|
+
ctx.signal,
|
|
295
|
+
t.timeoutMs,
|
|
296
|
+
new TaugraphError("TIMEOUT", `Tool "${call.name}" timed out after ${t.timeoutMs}ms`),
|
|
297
|
+
);
|
|
298
|
+
return settle(
|
|
299
|
+
() => {
|
|
300
|
+
const signal = limit?.signal ?? ctx.signal;
|
|
301
|
+
const value = t.run(result.value, { call, signal, recovered: ctx.meta.recovered });
|
|
302
|
+
return limit && isThenable(value) ? limit.race(value) : value;
|
|
303
|
+
},
|
|
304
|
+
(value) => {
|
|
305
|
+
limit?.dispose();
|
|
306
|
+
const { content, isError } = resultOf(t, value);
|
|
307
|
+
return record(content, isError, false);
|
|
308
|
+
},
|
|
309
|
+
(error) => {
|
|
310
|
+
limit?.dispose();
|
|
311
|
+
if (ctx.signal.aborted) throw error; // a cancelled run stops; it is not the tool's answer
|
|
312
|
+
if (limit && error === limit.error) {
|
|
313
|
+
if (effect === "write") throw error; // the write may or may not have happened: fail, do not guess
|
|
314
|
+
return record(limit.error.message, true, true);
|
|
315
|
+
}
|
|
316
|
+
return record(String(error instanceof Error ? `Error: ${error.message}` : error), true, true);
|
|
317
|
+
},
|
|
318
|
+
);
|
|
319
|
+
});
|
|
320
|
+
},
|
|
321
|
+
{ kind: "tool", ...(effect === "write" && { effect }) },
|
|
322
|
+
);
|
|
323
|
+
|
|
324
|
+
const next = (s: AgentState): AgentNodeId => {
|
|
325
|
+
const call = s.pending[0];
|
|
326
|
+
if (call) return tools.get(call.name)?.effect === "write" ? "act_write" : "act";
|
|
327
|
+
return s.stop ? "finish" : "think";
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const graph = createGraph(agentStateSchema, {
|
|
331
|
+
start: "think",
|
|
332
|
+
nodes: {
|
|
333
|
+
think,
|
|
334
|
+
act: act("read"),
|
|
335
|
+
act_write: act("write"),
|
|
336
|
+
finish: defineNode<AgentState>((s) => s, { kind: "code" }),
|
|
337
|
+
},
|
|
338
|
+
conditionalEdges: [
|
|
339
|
+
{ from: "think", route: next, targets: ["act", "act_write", "finish"] },
|
|
340
|
+
{ from: "act", route: next, targets: ["act", "act_write", "think"] },
|
|
341
|
+
{ from: "act_write", route: next, targets: ["act", "act_write", "think"] },
|
|
342
|
+
],
|
|
343
|
+
endNodes: ["finish"],
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
// maxRounds is the real bound; the kernel's step guard only has to leave room for every call of every round.
|
|
347
|
+
const steps = <O extends { readonly maxSteps?: number }>(options?: O): O =>
|
|
348
|
+
({ ...options, maxSteps: options?.maxSteps ?? AGENT_DEFAULTS.maxSteps }) as O;
|
|
349
|
+
return Object.freeze({
|
|
350
|
+
start: graph.start,
|
|
351
|
+
nodeIds: graph.nodeIds,
|
|
352
|
+
endNodes: graph.endNodes,
|
|
353
|
+
run: (input, options) => graph.run(input, steps(options)),
|
|
354
|
+
runSync: (input, options) => graph.runSync(input, steps(options)),
|
|
355
|
+
resume: (trace, value, options) => graph.resume(trace, value, steps(options)),
|
|
356
|
+
resumeSync: (trace, value, options) => graph.resumeSync(trace, value, steps(options)),
|
|
357
|
+
replay: (trace, options) => graph.replay(trace, steps(options)),
|
|
358
|
+
} satisfies AgentGraph);
|
|
359
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// The agent's state and its schema, written against Standard Schema by hand so the agent needs no validator.
|
|
2
|
+
import type { StandardSchemaV1 } from "../index.js";
|
|
3
|
+
import type { ChatMessage, ToolCall } from "../nodes/index.js";
|
|
4
|
+
|
|
5
|
+
export type AgentStop = "done" | "max_rounds";
|
|
6
|
+
|
|
7
|
+
export interface AgentState {
|
|
8
|
+
/** The conversation without the system prompt, which comes from the config on every call. */
|
|
9
|
+
readonly messages: readonly ChatMessage[];
|
|
10
|
+
/** Calls from the last assistant message that have not run yet, in order. */
|
|
11
|
+
readonly pending: readonly ToolCall[];
|
|
12
|
+
/** Model calls made in this run. */
|
|
13
|
+
readonly rounds: number;
|
|
14
|
+
/** The last answer, once the model stops calling tools. */
|
|
15
|
+
readonly final: string | null;
|
|
16
|
+
readonly stop: AgentStop | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** What a run starts from: a conversation, and optionally where an earlier run left off. */
|
|
20
|
+
export interface AgentInput {
|
|
21
|
+
readonly messages: readonly ChatMessage[];
|
|
22
|
+
readonly pending?: readonly ToolCall[];
|
|
23
|
+
readonly rounds?: number;
|
|
24
|
+
readonly final?: string | null;
|
|
25
|
+
readonly stop?: AgentStop | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type Issue = StandardSchemaV1.Issue;
|
|
29
|
+
type Path = (string | number)[];
|
|
30
|
+
|
|
31
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
32
|
+
|
|
33
|
+
function checkCall(value: unknown, path: Path, issues: Issue[]): void {
|
|
34
|
+
if (!isObject(value)) {
|
|
35
|
+
issues.push({ message: "expected a tool call object", path });
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (typeof value.id !== "string") issues.push({ message: "expected a string", path: [...path, "id"] });
|
|
39
|
+
if (typeof value.name !== "string") issues.push({ message: "expected a string", path: [...path, "name"] });
|
|
40
|
+
if (!isObject(value.arguments)) issues.push({ message: "expected an object", path: [...path, "arguments"] });
|
|
41
|
+
if (value.parseError !== undefined && typeof value.parseError !== "string")
|
|
42
|
+
issues.push({ message: "expected a string", path: [...path, "parseError"] });
|
|
43
|
+
if (value.signature !== undefined && typeof value.signature !== "string")
|
|
44
|
+
issues.push({ message: "expected a string", path: [...path, "signature"] });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function checkPart(value: unknown, path: Path, issues: Issue[]): void {
|
|
48
|
+
if (!isObject(value)) {
|
|
49
|
+
issues.push({ message: "expected a content part object", path });
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (value.type === "text") {
|
|
53
|
+
if (typeof value.text !== "string") issues.push({ message: "expected a string", path: [...path, "text"] });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (value.type !== "image") {
|
|
57
|
+
issues.push({ message: 'expected "text" or "image"', path: [...path, "type"] });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (value.data !== undefined) {
|
|
61
|
+
if (typeof value.data !== "string") issues.push({ message: "expected a string", path: [...path, "data"] });
|
|
62
|
+
if (typeof value.mimeType !== "string") issues.push({ message: "expected a string", path: [...path, "mimeType"] });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (typeof value.url !== "string")
|
|
66
|
+
issues.push({ message: "expected a string (or data and mimeType)", path: [...path, "url"] });
|
|
67
|
+
if (value.mimeType !== undefined && typeof value.mimeType !== "string")
|
|
68
|
+
issues.push({ message: "expected a string", path: [...path, "mimeType"] });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Checks a message's `content`: a string, or, where `parts` is true, also an array of text and image parts. */
|
|
72
|
+
export function checkContent(value: unknown, path: Path, issues: Issue[], parts: boolean): void {
|
|
73
|
+
if (typeof value === "string") return;
|
|
74
|
+
if (!parts || !Array.isArray(value)) {
|
|
75
|
+
issues.push({ message: parts ? "expected a string or an array of content parts" : "expected a string", path });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
for (const [i, part] of value.entries()) checkPart(part, [...path, i], issues);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function checkReasoning(value: unknown, path: Path, issues: Issue[]): void {
|
|
82
|
+
if (!isObject(value)) {
|
|
83
|
+
issues.push({ message: "expected a reasoning part object", path });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (typeof value.text !== "string") issues.push({ message: "expected a string", path: [...path, "text"] });
|
|
87
|
+
if (value.signature !== undefined && typeof value.signature !== "string")
|
|
88
|
+
issues.push({ message: "expected a string", path: [...path, "signature"] });
|
|
89
|
+
if (value.redacted !== undefined && typeof value.redacted !== "boolean")
|
|
90
|
+
issues.push({ message: "expected a boolean", path: [...path, "redacted"] });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function checkMessage(value: unknown, path: Path, issues: Issue[]): void {
|
|
94
|
+
if (!isObject(value)) {
|
|
95
|
+
issues.push({ message: "expected a message object", path });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const { role } = value;
|
|
99
|
+
if (role !== "system" && role !== "user" && role !== "assistant" && role !== "tool") {
|
|
100
|
+
issues.push({ message: 'expected "system", "user", "assistant" or "tool"', path: [...path, "role"] });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
checkContent(value.content, [...path, "content"], issues, role === "user" || role === "tool");
|
|
104
|
+
if (role === "assistant" && value.toolCalls !== undefined) {
|
|
105
|
+
if (!Array.isArray(value.toolCalls)) issues.push({ message: "expected an array", path: [...path, "toolCalls"] });
|
|
106
|
+
else for (const [i, c] of value.toolCalls.entries()) checkCall(c, [...path, "toolCalls", i], issues);
|
|
107
|
+
}
|
|
108
|
+
if (role === "assistant") {
|
|
109
|
+
if (value.model !== undefined && typeof value.model !== "string")
|
|
110
|
+
issues.push({ message: "expected a string", path: [...path, "model"] });
|
|
111
|
+
if (value.reasoning !== undefined) {
|
|
112
|
+
if (!Array.isArray(value.reasoning)) issues.push({ message: "expected an array", path: [...path, "reasoning"] });
|
|
113
|
+
else for (const [i, r] of value.reasoning.entries()) checkReasoning(r, [...path, "reasoning", i], issues);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (role === "tool") {
|
|
117
|
+
if (typeof value.toolCallId !== "string")
|
|
118
|
+
issues.push({ message: "expected a string", path: [...path, "toolCallId"] });
|
|
119
|
+
if (value.isError !== undefined && typeof value.isError !== "boolean")
|
|
120
|
+
issues.push({ message: "expected a boolean", path: [...path, "isError"] });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Validates an agent state, filling in `pending: []`, `rounds: 0`, `final: null` and `stop: null`. */
|
|
125
|
+
export const agentStateSchema: StandardSchemaV1<AgentInput, AgentState> = {
|
|
126
|
+
"~standard": {
|
|
127
|
+
version: 1,
|
|
128
|
+
vendor: "taugraph",
|
|
129
|
+
validate(value) {
|
|
130
|
+
if (!isObject(value)) return { issues: [{ message: "expected an object" }] };
|
|
131
|
+
const issues: Issue[] = [];
|
|
132
|
+
const { messages, pending = [], rounds = 0, final = null, stop = null } = value;
|
|
133
|
+
if (!Array.isArray(messages)) issues.push({ message: "expected an array", path: ["messages"] });
|
|
134
|
+
else for (const [i, m] of messages.entries()) checkMessage(m, ["messages", i], issues);
|
|
135
|
+
if (!Array.isArray(pending)) issues.push({ message: "expected an array", path: ["pending"] });
|
|
136
|
+
else for (const [i, c] of pending.entries()) checkCall(c, ["pending", i], issues);
|
|
137
|
+
if (!Number.isInteger(rounds) || (rounds as number) < 0)
|
|
138
|
+
issues.push({ message: "expected a non-negative integer", path: ["rounds"] });
|
|
139
|
+
if (final !== null && typeof final !== "string")
|
|
140
|
+
issues.push({ message: "expected a string or null", path: ["final"] });
|
|
141
|
+
if (stop !== null && stop !== "done" && stop !== "max_rounds")
|
|
142
|
+
issues.push({ message: 'expected "done", "max_rounds" or null', path: ["stop"] });
|
|
143
|
+
if (issues.length > 0) return { issues };
|
|
144
|
+
return { value: { messages, pending, rounds, final, stop } as AgentState };
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { MaybePromise, StandardSchemaV1 } from "../index.js";
|
|
2
|
+
|
|
3
|
+
export function isThenable<T>(value: MaybePromise<T>): value is PromiseLike<T> {
|
|
4
|
+
return value !== null && typeof value === "object" && typeof (value as PromiseLike<T>).then === "function";
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** Chains without introducing a Promise when the value is synchronous, so the agent stays `runSync`-friendly. */
|
|
8
|
+
export function andThen<A, B>(value: MaybePromise<A>, fn: (value: A) => MaybePromise<B>): MaybePromise<B> {
|
|
9
|
+
return isThenable(value) ? Promise.resolve(value).then(fn) : fn(value);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Runs `run` and hands its value to `ok`, or its error (thrown or rejected) to `fail`. Sync in, sync out. */
|
|
13
|
+
export function settle<T, R>(
|
|
14
|
+
run: () => MaybePromise<T>,
|
|
15
|
+
ok: (value: T) => MaybePromise<R>,
|
|
16
|
+
fail: (error: unknown) => MaybePromise<R>,
|
|
17
|
+
): MaybePromise<R> {
|
|
18
|
+
let value: MaybePromise<T>;
|
|
19
|
+
try {
|
|
20
|
+
value = run();
|
|
21
|
+
} catch (error) {
|
|
22
|
+
return fail(error);
|
|
23
|
+
}
|
|
24
|
+
return isThenable(value) ? Promise.resolve(value).then(ok, fail) : ok(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Schema issues as one line the model can act on: "city: expected string; days: too small". */
|
|
28
|
+
export function issuesText(issues: readonly StandardSchemaV1.Issue[]): string {
|
|
29
|
+
return issues
|
|
30
|
+
.map((issue) => {
|
|
31
|
+
const path = (issue.path ?? []).map((p) => String(typeof p === "object" ? p.key : p)).join(".");
|
|
32
|
+
return path ? `${path}: ${issue.message}` : issue.message;
|
|
33
|
+
})
|
|
34
|
+
.join("; ");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A time limit for one call: `signal` aborts with `error` once `ms` pass, and `race` rejects with it. */
|
|
38
|
+
export interface Deadline {
|
|
39
|
+
readonly signal: AbortSignal;
|
|
40
|
+
readonly error: Error;
|
|
41
|
+
race<T>(value: PromiseLike<T>): Promise<T>;
|
|
42
|
+
/** Clears the timer when the call ends. */
|
|
43
|
+
dispose(): void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Composed by hand: `AbortSignal.any` keeps every combination alive on a long-lived parent signal. */
|
|
47
|
+
export function deadline(parent: AbortSignal, ms: number, error: Error): Deadline {
|
|
48
|
+
const timer = new AbortController();
|
|
49
|
+
let expire: ((reason: unknown) => void) | undefined;
|
|
50
|
+
const handle = setTimeout(() => {
|
|
51
|
+
timer.abort(error);
|
|
52
|
+
expire?.(error);
|
|
53
|
+
}, ms);
|
|
54
|
+
const onAbort = () => {
|
|
55
|
+
clearTimeout(handle);
|
|
56
|
+
timer.abort(parent.reason);
|
|
57
|
+
};
|
|
58
|
+
if (parent.aborted) onAbort();
|
|
59
|
+
else parent.addEventListener("abort", onAbort, { once: true });
|
|
60
|
+
return {
|
|
61
|
+
signal: timer.signal,
|
|
62
|
+
error,
|
|
63
|
+
race<T>(value: PromiseLike<T>): Promise<T> {
|
|
64
|
+
return new Promise<T>((resolve, reject) => {
|
|
65
|
+
expire = reject;
|
|
66
|
+
Promise.resolve(value).then(resolve, reject); // a late rejection is dropped, never unhandled
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
dispose: () => {
|
|
70
|
+
clearTimeout(handle);
|
|
71
|
+
parent.removeEventListener("abort", onAbort);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|