taugraph 0.3.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.
Files changed (79) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/README.md +55 -8
  3. package/README.zh-CN.md +55 -8
  4. package/dist/agent/index.d.ts +8 -0
  5. package/dist/agent/index.d.ts.map +1 -1
  6. package/dist/agent/index.js +30 -4
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/agent/util.d.ts +10 -0
  9. package/dist/agent/util.d.ts.map +1 -1
  10. package/dist/agent/util.js +31 -0
  11. package/dist/agent/util.js.map +1 -1
  12. package/dist/core/engine.d.ts +1 -1
  13. package/dist/core/engine.d.ts.map +1 -1
  14. package/dist/core/engine.js +237 -35
  15. package/dist/core/engine.js.map +1 -1
  16. package/dist/core/errors.d.ts +2 -0
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/errors.js.map +1 -1
  19. package/dist/core/graph.d.ts.map +1 -1
  20. package/dist/core/graph.js +9 -1
  21. package/dist/core/graph.js.map +1 -1
  22. package/dist/core/node.d.ts +6 -1
  23. package/dist/core/node.d.ts.map +1 -1
  24. package/dist/core/node.js +55 -6
  25. package/dist/core/node.js.map +1 -1
  26. package/dist/core/patch.d.ts +26 -0
  27. package/dist/core/patch.d.ts.map +1 -0
  28. package/dist/core/patch.js +192 -0
  29. package/dist/core/patch.js.map +1 -0
  30. package/dist/core/retry.d.ts +20 -0
  31. package/dist/core/retry.d.ts.map +1 -0
  32. package/dist/core/retry.js +79 -0
  33. package/dist/core/retry.js.map +1 -0
  34. package/dist/core/trace.d.ts +39 -8
  35. package/dist/core/trace.d.ts.map +1 -1
  36. package/dist/core/trace.js +222 -29
  37. package/dist/core/trace.js.map +1 -1
  38. package/dist/core/types.d.ts +35 -4
  39. package/dist/core/types.d.ts.map +1 -1
  40. package/dist/core/util.d.ts +5 -1
  41. package/dist/core/util.d.ts.map +1 -1
  42. package/dist/core/util.js +41 -9
  43. package/dist/core/util.js.map +1 -1
  44. package/dist/file/index.d.ts +26 -0
  45. package/dist/file/index.d.ts.map +1 -0
  46. package/dist/file/index.js +373 -0
  47. package/dist/file/index.js.map +1 -0
  48. package/dist/index.d.ts +4 -3
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +2 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/nodes/code.d.ts +5 -0
  53. package/dist/nodes/code.d.ts.map +1 -1
  54. package/dist/nodes/code.js.map +1 -1
  55. package/dist/nodes/llm.d.ts +2 -0
  56. package/dist/nodes/llm.d.ts.map +1 -1
  57. package/dist/nodes/llm.js +5 -1
  58. package/dist/nodes/llm.js.map +1 -1
  59. package/dist/openai/index.d.ts +17 -1
  60. package/dist/openai/index.d.ts.map +1 -1
  61. package/dist/openai/index.js +32 -2
  62. package/dist/openai/index.js.map +1 -1
  63. package/package.json +6 -2
  64. package/src/agent/index.ts +47 -3
  65. package/src/agent/util.ts +39 -0
  66. package/src/core/engine.ts +241 -34
  67. package/src/core/errors.ts +2 -0
  68. package/src/core/graph.ts +7 -1
  69. package/src/core/node.ts +55 -6
  70. package/src/core/patch.ts +173 -0
  71. package/src/core/retry.ts +89 -0
  72. package/src/core/trace.ts +222 -29
  73. package/src/core/types.ts +37 -4
  74. package/src/core/util.ts +43 -10
  75. package/src/file/index.ts +408 -0
  76. package/src/index.ts +5 -1
  77. package/src/nodes/code.ts +5 -0
  78. package/src/nodes/llm.ts +7 -1
  79. package/src/openai/index.ts +43 -3
@@ -3,13 +3,18 @@
3
3
  *
4
4
  * Every operation that might be asynchronous (a node call, a schema validation) is
5
5
  * `yield`ed. `driveSync` feeds results straight back and rejects Promises;
6
- * `driveAsync` awaits them. This keeps the kernel sync-first without tying it to
7
- * any async runtime, and both drivers share exactly the same semantics.
6
+ * `driveAsync` awaits them. The engine also yields two internal effects: `Wait`,
7
+ * to sleep before a retry (`run` sleeps, `runSync` blocks with `Atomics.wait`),
8
+ * and `SinkWait`, for an unfinished async `onEvent` (`run` awaits it, `runSync`
9
+ * refuses it). This keeps the kernel sync-first without tying it to any async
10
+ * runtime, and both drivers share exactly the same semantics.
8
11
  */
9
12
  import { formatIssues, TaugraphError } from "./errors.js";
13
+ import { FATAL, isRetryable, retryDelay } from "./retry.js";
10
14
  import type { StandardSchemaV1 } from "./standard-schema.js";
11
15
  import {
12
16
  deliveredValues,
17
+ type EventDraft,
13
18
  KERNEL_EVENT_TYPES,
14
19
  type RecordedAnswers,
15
20
  type RecordedStep,
@@ -19,7 +24,7 @@ import {
19
24
  TraceLog,
20
25
  tracePath,
21
26
  } from "./trace.js";
22
- import type { Node, PluginEvent, ReplayMode, RunContext, RunOptions, RunResult, Trace } from "./types.js";
27
+ import type { Node, PluginEvent, ReplayMode, RetryPolicy, RunContext, RunOptions, RunResult, Trace } from "./types.js";
23
28
  import { freezeJson, isThenable, jsonEqual, NotJsonError, randomId } from "./util.js";
24
29
 
25
30
  export const DEFAULT_MAX_STEPS = 100;
@@ -82,9 +87,73 @@ type StepOutcome<S> =
82
87
  | { readonly kind: "exit"; readonly state: S }
83
88
  | { readonly kind: "pause"; readonly request: unknown };
84
89
 
85
- const NON_RETRYABLE = new Set(["ABORTED", "ASYNC_IN_SYNC_RUN", "INVALID_EVENT", "SINK_FAILED"]);
86
90
  const NEVER_ABORTED = new AbortController().signal;
87
91
 
92
+ /** Yielded to wait before a retry: `run` sleeps, `runSync` blocks the thread. */
93
+ class Wait {
94
+ constructor(readonly ms: number) {}
95
+ }
96
+
97
+ /** Yielded to wait for an async `onEvent`: `run` awaits it, `runSync` refuses it and stops calling the sink. */
98
+ class SinkWait {
99
+ constructor(
100
+ readonly done: Promise<void>,
101
+ readonly detach: () => void,
102
+ ) {}
103
+ }
104
+
105
+ /** Appends a kernel event and, with an async sink, waits until the sink has stored it. */
106
+ function* record(log: TraceLog, draft: EventDraft): Effects<void> {
107
+ log.append(draft);
108
+ yield* drain(log);
109
+ }
110
+
111
+ /** Waits until an async sink has stored every event so far. Nothing to wait for with a synchronous sink. */
112
+ function* drain(log: TraceLog): Effects<void> {
113
+ const done = log.pending();
114
+ if (done) yield new SinkWait(done, () => log.detach());
115
+ }
116
+
117
+ /** A time limit for one attempt of a node. */
118
+ interface Deadline {
119
+ /** The attempt's `ctx.signal`: aborts with the run, or with the TIMEOUT error when time is up. */
120
+ readonly signal: AbortSignal;
121
+ /** Settles like `promise`, unless time is up first; then it rejects with the TIMEOUT error. */
122
+ race<T>(promise: PromiseLike<T>): Promise<T>;
123
+ /** Clears the timer when the attempt ends. */
124
+ dispose(): void;
125
+ }
126
+
127
+ /** Composed by hand: `AbortSignal.any` keeps every combination alive on a long-lived source signal. */
128
+ function startDeadline(run: AbortSignal, ms: number, error: TaugraphError): Deadline {
129
+ const timer = new AbortController();
130
+ let expire: ((reason: unknown) => void) | undefined;
131
+ const handle = setTimeout(() => {
132
+ timer.abort(error);
133
+ expire?.(error);
134
+ }, ms);
135
+ const onAbort = () => {
136
+ clearTimeout(handle);
137
+ timer.abort(run.reason);
138
+ };
139
+ if (run.aborted) onAbort();
140
+ else run.addEventListener("abort", onAbort, { once: true });
141
+ return {
142
+ signal: timer.signal,
143
+ race<T>(promise: PromiseLike<T>): Promise<T> {
144
+ return new Promise<T>((resolve, reject) => {
145
+ expire = reject;
146
+ // A late result or rejection lands here after the race is settled, so it is dropped, never unhandled.
147
+ Promise.resolve(promise).then(resolve, reject);
148
+ });
149
+ },
150
+ dispose: () => {
151
+ clearTimeout(handle);
152
+ run.removeEventListener("abort", onAbort);
153
+ },
154
+ };
155
+ }
156
+
88
157
  /** Thrown by `ctx.interrupt` to unwind the node. Detection does not rely on it propagating. */
89
158
  class PauseSignal extends Error {
90
159
  override readonly name = "TaugraphPause";
@@ -122,7 +191,7 @@ export function* execute<S>(params: ExecuteParams<S>): Effects<RunResult<S>> {
122
191
  const outcome = yield* runStep(params);
123
192
  carry = { values: undefined, recovered: false };
124
193
  if (outcome.kind === "pause") {
125
- log.append({
194
+ yield* record(log, {
126
195
  type: "run_end",
127
196
  meta: { status: "paused", steps: tracePath(log.snapshot()).length, pending: { nodeId: current, step } },
128
197
  });
@@ -136,7 +205,7 @@ export function* execute<S>(params: ExecuteParams<S>): Effects<RunResult<S>> {
136
205
  }
137
206
  }
138
207
 
139
- log.append({
208
+ yield* record(log, {
140
209
  type: "run_end",
141
210
  output: state,
142
211
  meta: { status: "completed", steps: tracePath(log.snapshot()).length },
@@ -160,6 +229,13 @@ export function* execute<S>(params: ExecuteParams<S>): Effects<RunResult<S>> {
160
229
  },
161
230
  },
162
231
  });
232
+ if (error.code !== "ABORTED") {
233
+ try {
234
+ yield* drain(log); // the sink still gets run_end, but a failure now would hide the first one
235
+ } catch {
236
+ // Already failing; the original error is the one to report.
237
+ }
238
+ }
163
239
  error.trace = log.snapshot();
164
240
  throw error;
165
241
  }
@@ -172,7 +248,7 @@ function* beginRun<S>(
172
248
  replay: ReplayPlan<S> | undefined,
173
249
  ): Effects<Start<S>> {
174
250
  const input = toJson(rawInput, "Run input is not plain JSON");
175
- log.append({
251
+ yield* record(log, {
176
252
  type: "run_start",
177
253
  input,
178
254
  meta: {
@@ -189,7 +265,7 @@ function* beginRun<S>(
189
265
  function* beginResume<S>(graph: CompiledGraph<S>, log: TraceLog, plan: ResumePlan): Effects<Start<S>> {
190
266
  const { point } = plan;
191
267
  if (point.kind === "start" || point.kind === "after") {
192
- log.append({ type: "resume", meta: { reason: "recovered" } });
268
+ yield* record(log, { type: "resume", meta: { reason: "recovered" } });
193
269
  if (point.kind === "start") {
194
270
  const input = (plan.trace[0] as Trace[number]).input;
195
271
  const state = yield* validate(graph.schema, input, "Run input failed schema validation");
@@ -209,7 +285,7 @@ function* beginResume<S>(graph: CompiledGraph<S>, log: TraceLog, plan: ResumePla
209
285
  }
210
286
 
211
287
  const delivered = point.kind === "paused";
212
- log.append({
288
+ yield* record(log, {
213
289
  type: "resume",
214
290
  nodeId: point.nodeId,
215
291
  step: point.step,
@@ -250,11 +326,11 @@ function* runStep<S>(p: StepParams<S>): Effects<StepOutcome<S>> {
250
326
 
251
327
  if (recorded && recorded.nodeId === nodeId && jsonEqual(recorded.input, state)) {
252
328
  const meta = { attempt: 1, source: "recorded", recordedFrom: { runId: replay?.sourceRunId, seq: recorded.seq } };
253
- log.append({ type: "enter", nodeId, step, input: state, meta });
329
+ yield* record(log, { type: "enter", nodeId, step, input: state, meta });
254
330
  const output = toJson(recorded.output, `Recorded output of node "${nodeId}" is not plain JSON`, nodeId, step);
255
331
  const message = `Recorded output of node "${nodeId}" (step ${step}) no longer matches the schema`;
256
- const next = yield* validate(graph.schema, output, message, nodeId, step);
257
- log.append({ type: "exit", nodeId, step, output: next, meta: { ...meta, durationMs: 0 } });
332
+ const next = yield* validate(graph.schema, output, message, nodeId, step, state);
333
+ yield* record(log, { type: "exit", nodeId, step, output: next, meta: { ...meta, durationMs: 0 } });
258
334
  return { kind: "exit", state: next };
259
335
  }
260
336
 
@@ -274,7 +350,13 @@ function* runStep<S>(p: StepParams<S>): Effects<StepOutcome<S>> {
274
350
  values = answers && answers.nodeId === nodeId && jsonEqual(answers.input, state) ? answers.values : [];
275
351
  for (const value of values) {
276
352
  const from = { runId: replay?.sourceRunId };
277
- log.append({ type: "resume", nodeId, step, input: value, meta: { reason: "replayed", recordedFrom: from } });
353
+ yield* record(log, {
354
+ type: "resume",
355
+ nodeId,
356
+ step,
357
+ input: value,
358
+ meta: { reason: "replayed", recordedFrom: from },
359
+ });
278
360
  }
279
361
  }
280
362
 
@@ -288,52 +370,124 @@ function* runStep<S>(p: StepParams<S>): Effects<StepOutcome<S>> {
288
370
  ...(node.effect !== undefined && { effect: node.effect }),
289
371
  ...(p.recovered && { recovered: true }),
290
372
  };
291
- log.append({ type: "enter", nodeId, step, input: state, meta });
373
+ yield* record(log, { type: "enter", nodeId, step, input: state, meta });
292
374
  const startedAt = Date.now();
293
- const control = createContext({ ...p, attempt, values });
375
+ const { timeoutMs } = node;
376
+ const deadline =
377
+ timeoutMs === undefined
378
+ ? undefined
379
+ : startDeadline(
380
+ p.signal,
381
+ timeoutMs,
382
+ new TaugraphError("TIMEOUT", `Node "${nodeId}" (step ${step}) timed out after ${timeoutMs}ms`, {
383
+ nodeId,
384
+ step,
385
+ }),
386
+ );
387
+ const control = createContext({ ...p, attempt, values, signal: deadline?.signal ?? p.signal });
388
+ let settled = false;
294
389
  try {
295
390
  let output: unknown;
296
391
  let failure: { readonly error: unknown } | undefined;
297
392
  try {
298
- output = yield node(state, control.ctx);
393
+ const result = node(state, control.ctx);
394
+ output = yield deadline && isThenable(result) ? deadline.race(result) : result;
395
+ settled = true;
299
396
  } catch (error) {
300
397
  failure = { error };
301
398
  } finally {
302
399
  control.close();
400
+ deadline?.dispose();
303
401
  }
402
+ yield* drain(log); // events the node appended are stored before its step ends
304
403
  // A requested pause wins, even if the node caught the signal or threw something else.
305
404
  if (control.pending) {
306
405
  const { request } = control.pending;
307
406
  const durationMs = Date.now() - startedAt;
308
- log.append({ type: "pause", nodeId, step, output: request, meta: { ...meta, durationMs } });
407
+ yield* record(log, { type: "pause", nodeId, step, output: request, meta: { ...meta, durationMs } });
309
408
  return { kind: "pause", request };
310
409
  }
311
410
  if (failure) throw failure.error;
312
411
  const message = `Node "${nodeId}" (step ${step}) returned a state that is not plain JSON`;
313
- const json = toJson(output, message, nodeId, step);
412
+ const json = toJson(output, message, nodeId, step, state);
314
413
  const next = yield* validate(
315
414
  graph.schema,
316
415
  json,
317
416
  `Node "${nodeId}" (step ${step}) returned invalid state`,
318
417
  nodeId,
319
418
  step,
419
+ state,
320
420
  );
321
- log.append({ type: "exit", nodeId, step, output: next, meta: { ...meta, durationMs: Date.now() - startedAt } });
322
- return { kind: "exit", state: next };
323
- } catch (thrown) {
324
- const error = asNodeError(thrown, nodeId, step);
325
- const willRetry = attempt < maxAttempts && !NON_RETRYABLE.has(error.code);
326
- log.append({
327
- type: "error",
421
+ yield* record(log, {
422
+ type: "exit",
328
423
  nodeId,
329
424
  step,
330
- meta: { attempt, source, code: error.code, message: error.message, willRetry },
425
+ output: next,
426
+ meta: { ...meta, durationMs: Date.now() - startedAt },
331
427
  });
428
+ return { kind: "exit", state: next };
429
+ } catch (thrown) {
430
+ const error = asNodeError(thrown, nodeId, step);
431
+ let willRetry = false;
432
+ let policyFailure: { readonly cause: unknown } | undefined;
433
+ try {
434
+ willRetry = attempt < maxAttempts && shouldRetry(node, error, thrown);
435
+ } catch (cause) {
436
+ policyFailure = { cause }; // retryOn threw: record this attempt as usual, then fail without retrying
437
+ }
438
+ const delayMs = willRetry && node.retry ? retryDelay(node.retry, attempt, thrown) : 0;
439
+ // A write that timed out or was cut off before it settled may have happened anyway.
440
+ const unknown = node.effect === "write" && !settled && (error.code === "TIMEOUT" || error.code === "ABORTED");
441
+ try {
442
+ yield* record(log, {
443
+ type: "error",
444
+ nodeId,
445
+ step,
446
+ meta: {
447
+ attempt,
448
+ source,
449
+ code: error.code,
450
+ message: error.message,
451
+ willRetry,
452
+ ...(willRetry && { delayMs }),
453
+ ...(unknown && { outcome: "unknown" }),
454
+ },
455
+ });
456
+ } catch (failure) {
457
+ // An aborted run reports ABORTED, even if a sink listening to the same signal failed
458
+ // meanwhile or the wait for the sink was cut short.
459
+ if (!p.signal.aborted) throw failure;
460
+ throw error.code === "ABORTED" ? error : asNodeError(abortError(p.signal), nodeId, step);
461
+ }
462
+ if (policyFailure) {
463
+ const { cause } = policyFailure;
464
+ const message = `Node "${nodeId}" (step ${step}): retry.retryOn threw: ${errorMessage(cause)}`;
465
+ throw new TaugraphError("NODE_FAILED", message, { nodeId, step, cause });
466
+ }
332
467
  if (!willRetry) throw error;
468
+ if (delayMs > 0) {
469
+ try {
470
+ yield new Wait(delayMs);
471
+ } catch (failure) {
472
+ // runSync cannot block here: name the node, like any other step failure.
473
+ if (failure instanceof TaugraphError && failure.code === "ASYNC_IN_SYNC_RUN") {
474
+ throw asNodeError(failure, nodeId, step);
475
+ }
476
+ throw failure;
477
+ }
478
+ }
333
479
  }
334
480
  }
335
481
  }
336
482
 
483
+ /** `retryOn` (or `isRetryable`) decides, except for a run that is stopping and for writes not declared idempotent. */
484
+ function shouldRetry<S>(node: Node<S>, error: TaugraphError, thrown: unknown): boolean {
485
+ const retry: RetryPolicy | undefined = node.retry;
486
+ if (!retry || FATAL.has(error.code)) return false;
487
+ if (node.effect === "write" && retry.idempotent !== true) return false; // createGraph refuses these too
488
+ return (retry.retryOn ?? isRetryable)(thrown);
489
+ }
490
+
337
491
  interface ContextParams {
338
492
  readonly log: TraceLog;
339
493
  readonly runId: string;
@@ -361,7 +515,14 @@ function createContext(p: ContextParams): Control {
361
515
  };
362
516
 
363
517
  const ctx: RunContext = Object.freeze({
364
- meta: Object.freeze({ runId: p.runId, nodeId, step, attempt: p.attempt, recovered: p.recovered }),
518
+ meta: Object.freeze({
519
+ runId: p.runId,
520
+ nodeId,
521
+ step,
522
+ attempt: p.attempt,
523
+ recovered: p.recovered,
524
+ idempotencyKey: `${p.runId}:${step}`,
525
+ }),
365
526
  signal: p.signal,
366
527
  trace: Object.freeze({
367
528
  append(event: PluginEvent) {
@@ -440,6 +601,7 @@ function* validate<S>(
440
601
  message: string,
441
602
  nodeId?: string,
442
603
  step?: number,
604
+ base?: unknown,
443
605
  ): Effects<S> {
444
606
  let result = schema["~standard"].validate(value);
445
607
  if (isThenable(result)) result = (yield result) as StandardSchemaV1.Result<S>;
@@ -450,12 +612,12 @@ function* validate<S>(
450
612
  issues: result.issues,
451
613
  });
452
614
  }
453
- return toJson(result.value, `${message}: validated state is not plain JSON`, nodeId, step);
615
+ return toJson(result.value, `${message}: validated state is not plain JSON`, nodeId, step, base);
454
616
  }
455
617
 
456
- export function toJson<T>(value: T, message: string, nodeId?: string, step?: number): T {
618
+ export function toJson<T>(value: T, message: string, nodeId?: string, step?: number, base?: unknown): T {
457
619
  try {
458
- return freezeJson(value);
620
+ return freezeJson(value, base);
459
621
  } catch (cause) {
460
622
  if (!(cause instanceof NotJsonError)) throw cause;
461
623
  throw new TaugraphError("INVALID_STATE", `${message} (${cause.message})`, { nodeId, step, cause });
@@ -504,24 +666,53 @@ function describe(value: unknown): string {
504
666
  export function driveSync<T>(effects: Effects<T>): T {
505
667
  let next = effects.next();
506
668
  while (!next.done) {
507
- if (isThenable(next.value)) {
508
- Promise.resolve(next.value).catch(() => {}); // the result is discarded; avoid an unhandled rejection
669
+ const effect = next.value;
670
+ if (effect instanceof Wait) {
671
+ let failure: TaugraphError | undefined;
672
+ try {
673
+ blockFor(effect.ms);
674
+ } catch (error) {
675
+ failure = error as TaugraphError;
676
+ }
677
+ next = failure ? effects.throw(failure) : effects.next(undefined);
678
+ } else if (effect instanceof SinkWait) {
679
+ effect.done.catch(() => {}); // the sink finishes on its own; avoid an unhandled rejection
680
+ effect.detach();
681
+ next = effects.throw(
682
+ new TaugraphError("ASYNC_IN_SYNC_RUN", "onEvent returned a Promise; use run() for an async sink"),
683
+ );
684
+ } else if (isThenable(effect)) {
685
+ Promise.resolve(effect).catch(() => {}); // the result is discarded; avoid an unhandled rejection
509
686
  next = effects.throw(
510
687
  new TaugraphError("ASYNC_IN_SYNC_RUN", "runSync() received a Promise. Use run() for async nodes or schemas."),
511
688
  );
512
689
  } else {
513
- next = effects.next(next.value);
690
+ next = effects.next(effect);
514
691
  }
515
692
  }
516
693
  return next.value;
517
694
  }
518
695
 
696
+ /** Blocks the thread for `ms`. Throws ASYNC_IN_SYNC_RUN where blocking is not allowed, such as a browser's main thread. */
697
+ function blockFor(ms: number): void {
698
+ try {
699
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
700
+ } catch (cause) {
701
+ throw new TaugraphError("ASYNC_IN_SYNC_RUN", `runSync() cannot wait ${ms}ms before retrying here; use run()`, {
702
+ cause,
703
+ });
704
+ }
705
+ }
706
+
519
707
  export async function driveAsync<T>(effects: Effects<T>, signal?: AbortSignal): Promise<T> {
520
708
  let next = effects.next();
521
709
  while (!next.done) {
710
+ const effect = next.value;
522
711
  let value: unknown;
523
712
  try {
524
- value = isThenable(next.value) ? await abortable(next.value, signal) : next.value;
713
+ if (effect instanceof Wait) value = await sleep(effect.ms, signal);
714
+ else if (effect instanceof SinkWait) value = await abortable(effect.done, signal);
715
+ else value = isThenable(effect) ? await abortable(effect, signal) : effect;
525
716
  } catch (error) {
526
717
  next = effects.throw(error);
527
718
  continue;
@@ -531,6 +722,22 @@ export async function driveAsync<T>(effects: Effects<T>, signal?: AbortSignal):
531
722
  return next.value;
532
723
  }
533
724
 
725
+ /** Resolves after `ms`, or rejects with ABORTED as soon as the signal fires. */
726
+ function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
727
+ if (signal?.aborted) return Promise.reject(abortError(signal));
728
+ return new Promise<void>((resolve, reject) => {
729
+ const onAbort = () => {
730
+ clearTimeout(timer);
731
+ reject(abortError(signal as AbortSignal));
732
+ };
733
+ const timer = setTimeout(() => {
734
+ signal?.removeEventListener("abort", onAbort);
735
+ resolve();
736
+ }, ms);
737
+ signal?.addEventListener("abort", onAbort, { once: true });
738
+ });
739
+ }
740
+
534
741
  /** Stops waiting as soon as the signal fires, even if the node ignores the signal. */
535
742
  function abortable<T>(promise: PromiseLike<T>, signal: AbortSignal | undefined): Promise<T> {
536
743
  if (!signal) return Promise.resolve(promise);
@@ -14,6 +14,8 @@ export type TaugraphErrorCode =
14
14
  | "MAX_STEPS"
15
15
  /** The run's AbortSignal fired. */
16
16
  | "ABORTED"
17
+ /** A node's Promise did not settle within its `timeoutMs`. */
18
+ | "TIMEOUT"
17
19
  /** `runSync` met a Promise. */
18
20
  | "ASYNC_IN_SYNC_RUN"
19
21
  /** A trace could not be parsed or is not a taugraph trace. */
package/src/core/graph.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  toJson,
9
9
  } from "./engine.js";
10
10
  import { TaugraphError } from "./errors.js";
11
+ import { nodeMetaProblem } from "./node.js";
11
12
  import type { StandardSchemaV1 } from "./standard-schema.js";
12
13
  import { assertTrace, recordedAnswers, recordedSteps, resumePoint } from "./trace.js";
13
14
  import type { Graph, GraphDefinition, Node, ReplayOptions, ResumeOptions, RunOptions, Trace } from "./types.js";
@@ -91,6 +92,8 @@ export function createGraph<S, I, K extends string>(
91
92
  if (node !== undefined && typeof node !== "function") {
92
93
  throw new TaugraphError("INVALID_GRAPH", `Override for node "${id}" is not a function`);
93
94
  }
95
+ const problem = node === undefined ? undefined : nodeMetaProblem(node);
96
+ if (problem !== undefined) throw new TaugraphError("INVALID_GRAPH", `Override for node "${id}": ${problem}`);
94
97
  }
95
98
  const mode = options.mode ?? "recorded";
96
99
  const replay = {
@@ -119,7 +122,10 @@ function compile<S>(schema: StandardSchemaV1<unknown, S>, def: GraphDefinition<S
119
122
  const ids = Object.keys(nodes);
120
123
  if (ids.length === 0) fail("Graph has no nodes");
121
124
  for (const id of ids) {
122
- if (typeof nodes[id] !== "function") fail(`Node "${id}" is not a function`);
125
+ const node = nodes[id];
126
+ if (typeof node !== "function") fail(`Node "${id}" is not a function`);
127
+ const problem = nodeMetaProblem(node as Node<S>);
128
+ if (problem !== undefined) fail(`createGraph: node "${id}": ${problem}`);
123
129
  }
124
130
  const exists = (id: unknown): id is string => typeof id === "string" && Object.hasOwn(nodes, id);
125
131
  const requireNode = (id: unknown, role: string): string => {
package/src/core/node.ts CHANGED
@@ -1,24 +1,73 @@
1
+ import { freezeRetry, MAX_DELAY_MS } from "./retry.js";
1
2
  import type { Node, NodeFn, NodeMeta } from "./types.js";
2
3
 
4
+ const atLeast = (value: unknown, min: number): boolean =>
5
+ typeof value === "number" && Number.isFinite(value) && value >= min;
6
+
7
+ /**
8
+ * What is wrong with a node's retry policy or timeout, or undefined. `defineNode` and `createGraph` both check it, so
9
+ * a node built without `defineNode` cannot slip past.
10
+ */
11
+ export function nodeMetaProblem(meta: NodeMeta): string | undefined {
12
+ const { timeoutMs } = meta;
13
+ if (timeoutMs !== undefined && !(Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_DELAY_MS)) {
14
+ return `timeoutMs must be an integer from 1 to ${MAX_DELAY_MS}, got ${String(timeoutMs)}`;
15
+ }
16
+ const retry: unknown = meta.retry;
17
+ if (retry === undefined) return undefined;
18
+ if (typeof retry !== "object" || retry === null) return `retry must be an object, got ${String(retry)}`;
19
+ const { maxAttempts, backoff, retryOn, idempotent } = retry as Record<string, unknown>;
20
+ if (!(Number.isInteger(maxAttempts) && (maxAttempts as number) >= 1)) {
21
+ return `retry.maxAttempts must be an integer >= 1, got ${String(maxAttempts)}`;
22
+ }
23
+ if (backoff !== undefined && backoff !== false) {
24
+ if (typeof backoff !== "object" || backoff === null) {
25
+ return `retry.backoff must be false or an object, got ${String(backoff)}`;
26
+ }
27
+ const { initialMs, factor, maxMs, jitter } = backoff as Record<string, unknown>;
28
+ if (initialMs !== undefined && !atLeast(initialMs, 0)) {
29
+ return `retry.backoff.initialMs must be a finite number >= 0, got ${String(initialMs)}`;
30
+ }
31
+ if (factor !== undefined && !atLeast(factor, 1)) {
32
+ return `retry.backoff.factor must be a finite number >= 1, got ${String(factor)}`;
33
+ }
34
+ if (maxMs !== undefined && !atLeast(maxMs, 0)) {
35
+ return `retry.backoff.maxMs must be a finite number >= 0, got ${String(maxMs)}`;
36
+ }
37
+ if (jitter !== undefined && !(atLeast(jitter, 0) && (jitter as number) <= 1)) {
38
+ return `retry.backoff.jitter must be a number from 0 to 1, got ${String(jitter)}`;
39
+ }
40
+ }
41
+ if (retryOn !== undefined && typeof retryOn !== "function") {
42
+ return `retry.retryOn must be a function, got ${typeof retryOn}`;
43
+ }
44
+ if (idempotent !== undefined && typeof idempotent !== "boolean") {
45
+ return `retry.idempotent must be a boolean, got ${String(idempotent)}`;
46
+ }
47
+ if (meta.effect === "write" && idempotent !== true) {
48
+ return "a write node with retry must set retry.idempotent: true (use ctx.meta.idempotencyKey to make repeats safe)";
49
+ }
50
+ return undefined;
51
+ }
52
+
3
53
  /**
4
- * Wraps a node function with metadata (kind, retry policy, effect). This is the only hook
54
+ * Wraps a node function with metadata (kind, retry policy, effect, timeout). This is the only hook
5
55
  * plugin node packages need: `CodeNode`, `LLMNode` and friends are built on it.
6
56
  */
7
57
  export function defineNode<S>(fn: NodeFn<S>, meta: NodeMeta = {}): Node<S> {
8
58
  if (typeof fn !== "function") throw new TypeError("defineNode: expected a function");
9
- const retry = meta.retry;
10
- if (retry !== undefined && !(Number.isInteger(retry.maxAttempts) && retry.maxAttempts >= 1)) {
11
- throw new TypeError(`defineNode: retry.maxAttempts must be an integer >= 1, got ${String(retry.maxAttempts)}`);
12
- }
13
59
  if (meta.effect !== undefined && meta.effect !== "read" && meta.effect !== "write") {
14
60
  throw new TypeError(`defineNode: effect must be "read" or "write", got ${String(meta.effect)}`);
15
61
  }
62
+ const problem = nodeMetaProblem(meta);
63
+ if (problem !== undefined) throw new TypeError(`defineNode: ${problem}`);
16
64
  const node: NodeFn<S> = (state, ctx) => fn(state, ctx);
17
65
  return Object.freeze(
18
66
  Object.assign(node, {
19
67
  ...(meta.kind !== undefined && { kind: meta.kind }),
20
68
  ...(meta.effect !== undefined && { effect: meta.effect }),
21
- ...(retry !== undefined && { retry: Object.freeze({ maxAttempts: retry.maxAttempts }) }),
69
+ ...(meta.retry !== undefined && { retry: freezeRetry(meta.retry) }),
70
+ ...(meta.timeoutMs !== undefined && { timeoutMs: meta.timeoutMs }),
22
71
  }),
23
72
  );
24
73
  }