Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

durable-tool.ts

382 lines13.3 KB

1import type {
2 AnyTool,
3 ApprovalSchemaConfig,
4 InferSchemaType,
5 SchemaInput,
6 ToolDefinition,
7 ToolExecutionContext,
8} from '@tanstack/ai'
9import { jsonCopy, waitUntil } from './utils'
10import type { LogRecord } from '@tanstack/ai-persistence'
11import type { AnswerOf, Question } from './commands'
12​
13/**
14 * `T` when JSON keeps it as it is, with each part that JSON changes (a
15 * `Date`, a `Map`, a class with methods, a function) as `never`. So a
16 * `step.do` value that is not JSON is a type error. `undefined` (an absent
17 * field, or no value) is allowed.
18 */
19export type AsJson<T> = T extends
20 | string
21 | number
22 | boolean
23 | null
24 | undefined
25 | void
26 ? T
27 : T extends
28 | ((...args: Array<never>) => unknown)
29 | Date
30 | Map<unknown, unknown>
31 | Set<unknown>
32 | bigint
33 | symbol
34 ? never
35 : T extends object
36 ? { [K in keyof T]: AsJson<T[K]> }
37 : never
38​
39/** `T`, checked by {@link AsJson}. `T` is inferred from the value alone. */
40type JsonOf<T> = T & AsJson<NoInfer<T>>
41​
42/** What the `fn` of one `step.do` gets. */
43export interface StepRun {
44 /**
45 * A key for the side effect of this step. Give it to a system that refuses
46 * a second call with the same key. In a harness session it is
47 * `${logId}:${toolCallId}:${name}` (`RunContext.idempotencyKey` with the
48 * tool call id as scope). It has no attempt part: a run again of the call
49 * gets the same key. Outside a session it is the step name.
50 */
51 idempotencyKey: string
52 /**
53 * The ownership epoch of the log (see `RunContext.epoch`). 0 outside a
54 * harness session.
55 */
56 epoch: number
58​
59/** The durable steps of one tool call. */
60export interface ToolStep {
61 /**
62 * Run `fn` once for `name` in this tool call, and store its value in the
63 * session log before `do` resolves. When a crash makes the harness run the
64 * call again, a stored step returns its value and `fn` does not run again.
65 * `do` returns the JSON copy of the value, the same value a replay gives.
66 * So the value must be JSON (see {@link AsJson}): a `Date`, a `Map`, or a
67 * class instance is a type error. Return `date.toISOString()`, not `date`.
68 *
69 * A step runs at least once, and is stored once: a crash after `fn` ends
70 * but before the value is stored runs `fn` again. So pass
71 * `idempotencyKey` to the system that does the side effect, and it can
72 * refuse the second call. The value must be JSON: else `do` throws, and
73 * nothing is stored. Use a name that is the same on every run (for example
74 * `charge:${orderId}`). The same name twice in one call throws. A step
75 * does not start after the host lost the session log to another host.
76 * In a harness session, a value that holds a secret of the session (a key
77 * it read, a secret answer) throws too, on the first run and on a replay:
78 * the log never keeps a secret. Read the secret outside `step.do`.
79 *
80 * @example
81 * ```ts
82 * const charge = await step.do(`charge:${orderId}`, ({ idempotencyKey }) =>
83 * payments.charge({ orderId, idempotencyKey }),
84 * )
85 * ```
86 */
87 do: <T>(
88 name: string,
89 fn: (step: StepRun) => JsonOf<T> | Promise<JsonOf<T>>,
90 ) => Promise<T>
91 /**
92 * Wait `ms` milliseconds, once for `name` in this tool call. The first
93 * run stores the wake time in the session log. A run again after a crash
94 * or a restart, on any host, waits only for the time that is left, and a
95 * sleep whose time passed returns at once. While it waits, the log keeps
96 * a wake, so a host that stops lets a worker continue the call at the
97 * wake time (see `createHarnessWorker`).
98 *
99 * The name is a step name: it must be the same on every run, and not the
100 * name of a `do` step of this call. Outside a session, it waits `ms`.
101 *
102 * @example
103 * ```ts
104 * await step.do('send-reminder', () => mail.send(reminder))
105 * await step.sleep({ name: 'wait-a-day', ms: 24 * 60 * 60 * 1000 })
106 * await step.do('send-follow-up', () => mail.send(followUp))
107 * ```
108 */
109 sleep: (options: { name: string; ms: number }) => Promise<void>
110 /**
111 * Ask the user, once for `name` in this call, and wait for the answer.
112 * The log keeps the question as a wait of this run, so a user on any
113 * machine can answer it. When the host stops while it waits, the next
114 * host runs the code again from the top: finished `do` steps return their
115 * values, and `ask` returns the logged answer, or waits again.
116 *
117 * The answer is checked against `schema`. A `secret` answer is never in
118 * the log: the credential store keeps it until the run ends, so a run
119 * again can read it. `ask` rejects when the wait is cancelled or
120 * expires, and when the run stops. Outside a harness session it throws.
121 *
122 * In an agent that the main model calls as a tool, a `secret` question
123 * throws, `expiresAt` has no effect, and the wait does not get `url`.
124 *
125 * @example
126 * ```ts
127 * const key = await step.ask({ name: 'api-key', message: 'Paste your key', secret: true })
128 * ```
129 */
130 ask: <TSchema extends SchemaInput | undefined = undefined>(
131 question: StepQuestion<TSchema>,
132 ) => Promise<AnswerOf<TSchema>>
134​
135/**
136 * A question of `step.ask`: a {@link Question}, with a `name` that is the
137 * same on every run of the code.
138 */
139export type StepQuestion<TSchema extends SchemaInput | undefined = undefined> =
140 Omit<Question<TSchema>, 'live'> & { name: string }
141​
142/** `step.ask` outside a harness session: nobody can answer. */
143export const askWithoutSession = (): never => {
144 throw new Error(
145 'step.ask needs a harness session: call it in a command, a durable tool, or an agent run of host.open().',
146 )
148​
149/** What the `execute` of a {@link durableTool} gets. */
150export type DurableToolContext<TContext = unknown> =
151 ToolExecutionContext<TContext> & {
152 step: ToolStep
153 /**
154 * Add host records to the session log with this tool call. They land in
155 * the same append as the call's result. If the call never ends (a
156 * crash), the records never happened.
157 */
158 append: (records: ReadonlyArray<LogRecord>) => void
159 }
160​
161type DurableExecute = (args: unknown, context: DurableToolContext) => unknown
162​
163/**
164 * The key that keeps the durable `execute` on a tool. An own enumerable
165 * symbol key, so `{ ...tool }` in a plugin keeps it.
166 *
167 * @internal
168 */
169export const DURABLE_EXECUTE: unique symbol = Symbol(
170 'tanstack.ai-harness.durable-execute',
172​
173/** The step name that keeps the wake time of `step.sleep({ name })`. */
174const sleepStepName = (name: string) => `sleep:${name}`
175​
176/**
177 * @internal Steps over `recorded` values, stored with `record`. `run` gives
178 * the `fn` of a step what it gets, and throws when the step must not start.
179 * `sleep` waits until the stored wake time of a `step.sleep`.
180 */
181export function createToolStep(options: {
182 recorded: (name: string) => { found: true; value: unknown } | { found: false }
183 record: (name: string, value: unknown) => Promise<void>
184 run: (name: string) => StepRun
185 sleep: (sleep: { name: string; wakeAt: number }) => Promise<void>
186 /** Ask the user, and resolve with the checked answer. */
187 ask?: (question: StepQuestion<SchemaInput | undefined>) => Promise<unknown>
188}) {
189 const used = new Set<string>()
190 const step = {
191 sleep: async ({ name, ms }: { name: string; ms: number }) => {
192 if (!Number.isFinite(ms) || ms < 0) {
193 throw new RangeError(
194 `step.sleep: ms must be 0 or more, got ${ms} for ${JSON.stringify(name)}.`,
195 )
196 }
197 // Stored once, so a run again waits for the same time.
198 const wakeAt = await step.do(sleepStepName(name), () => Date.now() + ms)
199 await options.sleep({ name, wakeAt })
200 },
201 do: async <T>(name: string, fn: (step: StepRun) => T | Promise<T>) => {
202 if (used.has(name)) {
203 throw new Error(
204 `step.do: the step name ${JSON.stringify(name)} is already used in this tool call.`,
205 )
206 }
207 used.add(name)
208 const stored = options.recorded(name)
209 // The log holds what an earlier run of this step returned. A copy, so
210 // the tool cannot change the fold.
211 if (stored.found) return structuredClone(stored.value) as T
212 const value = await fn(options.run(name))
213 // The value a replay returns. A value that is not JSON fails now, not
214 // after a crash: nothing is stored, so a run again calls `fn` again.
215 const copy = jsonCopy(value)
216 if (copy === undefined && value !== undefined) {
217 throw new TypeError(
218 `step.do: the value of step ${JSON.stringify(name)} is not JSON, so the log cannot keep it.`,
219 )
220 }
221 await options.record(name, copy)
222 // `T` is JSON (see `AsJson`), so the copy has its type, as on a replay.
223 return copy as T
224 },
225 ask: async (question) => {
226 const { ask } = options
227 if (!ask) return askWithoutSession()
228 const key = `ask:${question.name}`
229 if (used.has(key)) {
230 throw new Error(
231 `step.ask: the name ${JSON.stringify(question.name)} is already used in this call.`,
232 )
233 }
234 used.add(key)
235 // The session checked the answer against the schema of the question.
236 return (await ask(question)) as never
237 },
238 } satisfies ToolStep
239 return step
241​
242/** What a step gets outside a harness session: its name as the key. */
243export const stepRunWithoutSession = (name: string) => ({
244 idempotencyKey: name,
245 epoch: 0,
246})
247​
248const noLog = () => {
249 throw new Error(
250 'durableTool append needs a harness session: call the tool in a turn of host.open().',
251 )
253​
254const emptyContext: ToolExecutionContext = { emitCustomEvent: () => {} }
255​
256/** Options for {@link durableTool}. */
257export interface DurableToolOptions {
258 /**
259 * What the harness does with a call that a crash cut:
260 * - `'safe'` (default): run it again. Finished steps return their stored
261 * values.
262 * - `'never'`: give the model a tool error. The call does not run again.
263 */
264 replay?: 'safe' | 'never'
266​
267/**
268 * Make a server tool whose side effects survive a crash. `execute` gets
269 * `step` and `append` next to the normal tool context. Put each side effect
270 * in `step.do(name, fn)`: when a crash makes the harness run the call again,
271 * finished steps return their stored values. The tool has `replay: 'safe'`
272 * unless `options.replay` says `'never'`.
273 *
274 * Outside a harness session (plain `chat()`), `step.do` runs `fn` each
275 * time and `append` throws.
276 *
277 * @example
278 * ```ts
279 * const createInvoice = durableTool(
280 * toolDefinition({ name: 'create_invoice', description: 'Create an invoice', inputSchema }),
281 * async ({ orderId }, { step }) => {
282 * const invoice = await step.do(`create:${orderId}`, () => billing.create(orderId))
283 * return { invoiceId: invoice.id }
284 * },
285 * )
286 * ```
287 */
288export function durableTool<
289 TInput extends SchemaInput | undefined,
290 TOutput extends SchemaInput | undefined,
291 TName extends string,
292 TNeedsApproval extends boolean,
293 TApprovalSchema extends ApprovalSchemaConfig | undefined,
294>(
295 definition: ToolDefinition<
296 TInput,
297 TOutput,
298 TName,
299 TNeedsApproval,
300 TApprovalSchema
301 >,
302 execute: (
303 args: InferSchemaType<TInput>,
304 context: DurableToolContext,
305 ) => Promise<InferSchemaType<TOutput>> | InferSchemaType<TOutput>,
306 options: DurableToolOptions = {},
307) {
308 const tool = definition.server((args, context) =>
309 execute(args, {
310 ...(context ?? emptyContext),
311 step: createToolStep({
312 recorded: () => ({ found: false }),
313 record: async () => {},
314 run: stepRunWithoutSession,
315 sleep: ({ wakeAt }) => waitUntil(wakeAt, context?.abortSignal),
316 }),
317 append: noLog,
318 }),
319 )
320 Object.defineProperty(tool, DURABLE_EXECUTE, {
321 value: execute,
322 enumerable: true,
323 })
324 return Object.assign(tool, { replay: options.replay ?? 'safe' })
326​
327function isDurableTool(
328 tool: AnyTool,
329): tool is AnyTool & { [DURABLE_EXECUTE]: DurableExecute } {
330 return typeof Reflect.get(tool, DURABLE_EXECUTE) === 'function'
332​
333/**
334 * The binder that bound a durable tool. An own enumerable symbol key, so a
335 * spread copy (a middleware wrapper) stays bound.
336 */
337const DURABLE_BINDER: unique symbol = Symbol(
338 'tanstack.ai-harness.durable-binder',
340​
341/** @internal */
342export type DurableBind = (toolCallId: string) => {
343 step: ToolStep
344 append: DurableToolContext['append']
345 /** The call ended, and no run again reads what its steps keep. */
346 done?: () => Promise<void>
348​
349/**
350 * Give a {@link durableTool} the `step` and `append` of a durable session.
351 * `bind` gets the id of each call. Another tool, and a tool that `bind`
352 * already bound, comes back as it is.
353 *
354 * @internal
355 */
356export function bindDurable(tool: AnyTool, bind: DurableBind) {
357 if (!isDurableTool(tool) || Reflect.get(tool, DURABLE_BINDER) === bind) {
358 return tool
359 }
360 const execute = tool[DURABLE_EXECUTE]
361 const bound = {
362 ...tool,
363 execute: async (args: unknown, context?: ToolExecutionContext) => {
364 const base = context ?? emptyContext
365 if (!base.toolCallId) {
366 throw new Error('A durable tool call needs a tool call id.')
367 }
368 const { done, ...bound } = bind(base.toolCallId)
369 try {
370 return await execute(args, { ...base, ...bound })
371 } finally {
372 // A stopped call runs again, and reads its steps again.
373 if (!base.abortSignal?.aborted) await done?.().catch(() => {})
374 }
375 },
376 }
377 Object.defineProperty(bound, DURABLE_BINDER, {
378 value: bind,
379 enumerable: true,
380 })
381 return bound