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.
- package/CHANGELOG.md +28 -1
- package/README.md +55 -8
- package/README.zh-CN.md +55 -8
- package/dist/agent/index.d.ts +8 -0
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +30 -4
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/util.d.ts +10 -0
- package/dist/agent/util.d.ts.map +1 -1
- package/dist/agent/util.js +31 -0
- package/dist/agent/util.js.map +1 -1
- 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/llm.d.ts +2 -0
- 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 +17 -1
- package/dist/openai/index.d.ts.map +1 -1
- package/dist/openai/index.js +32 -2
- package/dist/openai/index.js.map +1 -1
- package/package.json +6 -2
- package/src/agent/index.ts +47 -3
- package/src/agent/util.ts +39 -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/llm.ts +7 -1
- package/src/openai/index.ts +43 -3
package/src/core/util.ts
CHANGED
|
@@ -15,6 +15,9 @@ export class NotJsonError extends Error {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
/** Values made by `freezeJson`: deeply frozen and checked, so they are reused instead of copied. */
|
|
19
|
+
const checked = new WeakSet<object>();
|
|
20
|
+
|
|
18
21
|
/**
|
|
19
22
|
* Returns a deeply frozen copy of a plain-JSON value.
|
|
20
23
|
*
|
|
@@ -22,41 +25,71 @@ export class NotJsonError extends Error {
|
|
|
22
25
|
* (Date, Map, class instances, functions, bigint, NaN, cycles). This is what makes
|
|
23
26
|
* an in-memory trace and a trace loaded from JSONL replay identically.
|
|
24
27
|
* `undefined` object properties are kept (JSON drops them; `jsonEqual` ignores them).
|
|
28
|
+
*
|
|
29
|
+
* Parts that `freezeJson` made earlier are reused as they are, and so is every part of `base`
|
|
30
|
+
* (also made by `freezeJson`) that equals the part at the same position, with its keys in the same order:
|
|
31
|
+
* consecutive states share whatever did not change, which keeps traces linear in memory.
|
|
25
32
|
*/
|
|
26
|
-
export function freezeJson<T>(value: T): T {
|
|
27
|
-
return copy(value, "", new Set()) as T;
|
|
33
|
+
export function freezeJson<T>(value: T, base?: unknown): T {
|
|
34
|
+
return copy(value, "", new Set(), base) as T;
|
|
28
35
|
}
|
|
29
36
|
|
|
30
|
-
|
|
37
|
+
const isChecked = (value: unknown): value is object =>
|
|
38
|
+
typeof value === "object" && value !== null && checked.has(value);
|
|
39
|
+
|
|
40
|
+
function copy(value: unknown, path: string, ancestors: Set<object>, base: unknown): unknown {
|
|
31
41
|
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
32
42
|
if (typeof value === "number") {
|
|
33
43
|
if (!Number.isFinite(value)) throw new NotJsonError(path, `non-finite number ${value}`);
|
|
34
44
|
return value;
|
|
35
45
|
}
|
|
36
46
|
if (typeof value !== "object") throw new NotJsonError(path, `${typeof value} is not JSON`);
|
|
47
|
+
if (checked.has(value)) return value;
|
|
37
48
|
if (ancestors.has(value)) throw new NotJsonError(path, "circular reference");
|
|
38
49
|
|
|
39
50
|
ancestors.add(value);
|
|
40
|
-
|
|
51
|
+
const reuse = isChecked(base) ? base : undefined;
|
|
52
|
+
let result: object;
|
|
41
53
|
if (Array.isArray(value)) {
|
|
42
|
-
|
|
54
|
+
const old = Array.isArray(reuse) ? (reuse as readonly unknown[]) : undefined;
|
|
55
|
+
const items: unknown[] = [];
|
|
56
|
+
for (let i = 0; i < value.length; i++) {
|
|
57
|
+
if (!(i in value)) throw new NotJsonError(`${path}[${i}]`, "hole in array");
|
|
58
|
+
const item: unknown = value[i];
|
|
43
59
|
if (item === undefined) throw new NotJsonError(`${path}[${i}]`, "undefined in array");
|
|
44
|
-
|
|
45
|
-
}
|
|
60
|
+
items.push(copy(item, `${path}[${i}]`, ancestors, old?.[i]));
|
|
61
|
+
}
|
|
62
|
+
result =
|
|
63
|
+
old && old.length === items.length && items.every((item, i) => item === old[i]) ? old : Object.freeze(items);
|
|
46
64
|
} else {
|
|
47
65
|
const proto = Object.getPrototypeOf(value);
|
|
48
66
|
if (proto !== Object.prototype && proto !== null) {
|
|
49
67
|
const name = (value as { constructor?: { name?: string } }).constructor?.name ?? "object";
|
|
50
68
|
throw new NotJsonError(path, `${name} is not a plain object (use strings / numbers / arrays / objects)`);
|
|
51
69
|
}
|
|
70
|
+
const old = reuse && !Array.isArray(reuse) ? (reuse as Record<string, unknown>) : undefined;
|
|
52
71
|
const out: Record<string, unknown> = {};
|
|
53
72
|
for (const [key, item] of Object.entries(value)) {
|
|
54
|
-
|
|
73
|
+
const prev = old && Object.hasOwn(old, key) ? old[key] : undefined;
|
|
74
|
+
// defineProperty, not assignment: `out["__proto__"] = x` would set the prototype instead.
|
|
75
|
+
Object.defineProperty(out, key, {
|
|
76
|
+
value: item === undefined ? undefined : copy(item, path === "" ? key : `${path}.${key}`, ancestors, prev),
|
|
77
|
+
enumerable: true,
|
|
78
|
+
writable: true,
|
|
79
|
+
configurable: true,
|
|
80
|
+
});
|
|
55
81
|
}
|
|
56
|
-
|
|
82
|
+
const keys = Object.keys(out);
|
|
83
|
+
const oldKeys = old ? Object.keys(old) : [];
|
|
84
|
+
// Same keys in the same order: a reordered object is new state, not the old one.
|
|
85
|
+
result =
|
|
86
|
+
old && keys.length === oldKeys.length && keys.every((k, i) => k === oldKeys[i] && out[k] === old[k])
|
|
87
|
+
? old
|
|
88
|
+
: Object.freeze(out);
|
|
57
89
|
}
|
|
58
90
|
ancestors.delete(value);
|
|
59
|
-
|
|
91
|
+
checked.add(result);
|
|
92
|
+
return result;
|
|
60
93
|
}
|
|
61
94
|
|
|
62
95
|
/** Structural equality for JSON values. Object properties set to `undefined` count as absent. */
|
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// taugraph/file: one append-only JSONL file per run (format v2), written before each step goes on, with a lock per
|
|
2
|
+
// run and a repair for the half-written last line a crash leaves. Uses node:fs, so it runs on Node, Bun and Deno;
|
|
3
|
+
// the kernel itself stays platform-free.
|
|
4
|
+
import {
|
|
5
|
+
closeSync,
|
|
6
|
+
existsSync,
|
|
7
|
+
fsyncSync,
|
|
8
|
+
ftruncateSync,
|
|
9
|
+
linkSync,
|
|
10
|
+
mkdirSync,
|
|
11
|
+
openSync,
|
|
12
|
+
readdirSync,
|
|
13
|
+
readFileSync,
|
|
14
|
+
statSync,
|
|
15
|
+
unlinkSync,
|
|
16
|
+
writeFileSync,
|
|
17
|
+
writeSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { join, resolve } from "node:path";
|
|
20
|
+
import { createTraceEncoder, fromJSONL, runStatus, type Trace, type TraceEvent } from "../index.js";
|
|
21
|
+
|
|
22
|
+
/** When to fsync: around write steps, pauses and the end of a run (default), after every event, or never. */
|
|
23
|
+
export type Durability = "writes" | "every" | "none";
|
|
24
|
+
|
|
25
|
+
export interface FileStoreOptions {
|
|
26
|
+
readonly durability?: Durability | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `running`: a live process holds the run's lock. `interrupted`: no `run_end` and nobody is writing it. */
|
|
30
|
+
export type StoredRunStatus = "running" | "interrupted" | "paused" | "completed" | "failed";
|
|
31
|
+
|
|
32
|
+
export interface StoredRun {
|
|
33
|
+
readonly runId: string;
|
|
34
|
+
readonly status: StoredRunStatus;
|
|
35
|
+
readonly events: number;
|
|
36
|
+
/** Last change of the file, in ms since epoch. */
|
|
37
|
+
readonly updatedAt: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface FileStore {
|
|
41
|
+
readonly dir: string;
|
|
42
|
+
/** Pass as `onEvent`. Appends each event before the run continues. */
|
|
43
|
+
readonly sink: (event: TraceEvent) => void;
|
|
44
|
+
/** The stored trace without a half-written last line; undefined if there is no complete line. Never writes. */
|
|
45
|
+
load(runId: string): Trace | undefined;
|
|
46
|
+
/** Every run in the directory, oldest change first. Files that cannot be read are skipped. */
|
|
47
|
+
list(): StoredRun[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const RUN_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/;
|
|
51
|
+
|
|
52
|
+
function checkRunId(runId: string): void {
|
|
53
|
+
if (!RUN_ID.test(runId)) throw new TypeError(`Invalid runId "${runId.slice(0, 40)}"`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a process with this id exists. EPERM means it does, under another user. */
|
|
57
|
+
function alive(pid: number): boolean {
|
|
58
|
+
try {
|
|
59
|
+
process.kill(pid, 0);
|
|
60
|
+
return true;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return (error as { code?: string }).code === "EPERM";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function codeOf(error: unknown): string | undefined {
|
|
67
|
+
return (error as { code?: string } | undefined)?.code;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The process id a lock file holds, if its content is one. */
|
|
71
|
+
function pidIn(content: string): number | undefined {
|
|
72
|
+
const text = content.trim();
|
|
73
|
+
return /^\d+$/.test(text) && Number(text) > 0 ? Number(text) : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Lock files (absolute paths) this thread holds; released if the process exits while a run is still open. */
|
|
77
|
+
const held = new Set<string>();
|
|
78
|
+
let releaseOnExit = false;
|
|
79
|
+
|
|
80
|
+
/** When this process started, in ms since epoch. Process-wide on Node; on Bun and Deno each thread computes its own. */
|
|
81
|
+
const started = Date.now() - process.uptime() * 1000;
|
|
82
|
+
|
|
83
|
+
/** Slack for the lock's mtime: FAT stores mtimes in 2-second steps. */
|
|
84
|
+
const MTIME_STEP = 2000;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Age after which a lock without a process id is stale. A lock is empty for a moment while it is created on a file
|
|
88
|
+
* system without hard links, and for good if a power cut came before its content reached the disk.
|
|
89
|
+
*/
|
|
90
|
+
const NO_PID_STALE = 10_000;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Whether the process that wrote a lock is still writing the run. A lock with this process's id that this thread
|
|
94
|
+
* does not hold is live if it was written since this process started (another thread or store of this process),
|
|
95
|
+
* give or take one FAT mtime step; an older one was left by an earlier process that had the same id (e.g. a
|
|
96
|
+
* restarted container).
|
|
97
|
+
*/
|
|
98
|
+
function isLive(lock: string, pid: number): boolean {
|
|
99
|
+
if (pid !== process.pid) return alive(pid);
|
|
100
|
+
if (held.has(lock)) return true;
|
|
101
|
+
try {
|
|
102
|
+
return statSync(lock).mtimeMs >= started - MTIME_STEP;
|
|
103
|
+
} catch {
|
|
104
|
+
return false; // gone
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether a lock with this content keeps its run from being written: a live holder, or no process id for under 10 s. */
|
|
109
|
+
function holds(lock: string, content: string): boolean {
|
|
110
|
+
const pid = pidIn(content);
|
|
111
|
+
if (pid !== undefined) return isLive(lock, pid);
|
|
112
|
+
try {
|
|
113
|
+
return statSync(lock).mtimeMs >= Date.now() - NO_PID_STALE;
|
|
114
|
+
} catch {
|
|
115
|
+
return false; // gone
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Whether a lock keeps its run from being written. */
|
|
120
|
+
function locked(lock: string): boolean {
|
|
121
|
+
try {
|
|
122
|
+
return holds(lock, readFileSync(lock, "utf8"));
|
|
123
|
+
} catch {
|
|
124
|
+
return false; // no lock
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function hold(lock: string): void {
|
|
129
|
+
held.add(lock);
|
|
130
|
+
if (releaseOnExit) return;
|
|
131
|
+
releaseOnExit = true;
|
|
132
|
+
process.once("exit", () => {
|
|
133
|
+
for (const path of [...held]) releaseLock(path);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Removes a lock this thread holds, unless it no longer holds this process's id (another process took it over). */
|
|
138
|
+
function releaseLock(lock: string): void {
|
|
139
|
+
if (!held.delete(lock)) return;
|
|
140
|
+
try {
|
|
141
|
+
if (readFileSync(lock, "utf8") === String(process.pid)) unlinkSync(lock);
|
|
142
|
+
} catch {
|
|
143
|
+
// already gone
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function unlinkQuietly(path: string): void {
|
|
148
|
+
try {
|
|
149
|
+
unlinkSync(path);
|
|
150
|
+
} catch {
|
|
151
|
+
// already gone
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A file's text, or undefined if it does not exist. */
|
|
156
|
+
function readIfExists(path: string): string | undefined {
|
|
157
|
+
try {
|
|
158
|
+
return readFileSync(path, "utf8");
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (codeOf(error) === "ENOENT") return undefined;
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const suffix = () => `${process.pid}.${Math.random().toString(36).slice(2, 10)}`;
|
|
166
|
+
|
|
167
|
+
/** What `linkSync` throws on a file system without hard links (FAT, exFAT, some SMB and FUSE mounts). */
|
|
168
|
+
const NO_HARD_LINKS = new Set(["ENOTSUP", "EOPNOTSUPP", "EPERM", "ENOSYS"]);
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Creates the lock with this process's id in one step, so nobody can see it empty. Without hard links it is created
|
|
172
|
+
* and then written, and may be seen empty for a moment: an empty lock is refused until it is 10 s old. False if it
|
|
173
|
+
* exists.
|
|
174
|
+
*/
|
|
175
|
+
function link(lock: string): boolean {
|
|
176
|
+
const temp = `${lock}.${suffix()}`;
|
|
177
|
+
try {
|
|
178
|
+
writeFileSync(temp, String(process.pid), { flag: "wx" });
|
|
179
|
+
try {
|
|
180
|
+
linkSync(temp, lock);
|
|
181
|
+
return true;
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (codeOf(error) === "EEXIST") return false;
|
|
184
|
+
if (!NO_HARD_LINKS.has(codeOf(error) ?? "")) throw error;
|
|
185
|
+
}
|
|
186
|
+
} finally {
|
|
187
|
+
unlinkQuietly(temp);
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
writeFileSync(lock, String(process.pid), { flag: "wx" });
|
|
191
|
+
return true;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (codeOf(error) === "EEXIST") return false;
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Removes a stale lock that holds `stale`. One process at a time does this, holding `<lock>.takeover`; it removes the
|
|
200
|
+
* lock only if it still holds that content and is still stale, so a lock another process created after it was judged
|
|
201
|
+
* is kept.
|
|
202
|
+
*/
|
|
203
|
+
function takeOver(runId: string, lock: string, stale: string): void {
|
|
204
|
+
const mutex = `${lock}.takeover`;
|
|
205
|
+
try {
|
|
206
|
+
writeFileSync(mutex, String(process.pid), { flag: "wx" });
|
|
207
|
+
} catch (error) {
|
|
208
|
+
if (codeOf(error) !== "EEXIST") throw error;
|
|
209
|
+
throw new Error(`Run "${runId}" is being taken over by another process (remove ${mutex} if none is)`);
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
if (readIfExists(lock) === stale && !holds(lock, stale)) unlinkSync(lock);
|
|
213
|
+
} finally {
|
|
214
|
+
unlinkQuietly(mutex);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** The bytes up to and including the last newline. A line after it was cut short by a crash and never took effect. */
|
|
219
|
+
function completeLines(bytes: Uint8Array): Uint8Array {
|
|
220
|
+
return bytes.subarray(0, bytes.lastIndexOf(10) + 1);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The trace in a file's complete lines, or undefined if there are none. */
|
|
224
|
+
function traceOf(complete: Uint8Array): Trace | undefined {
|
|
225
|
+
return complete.length === 0 ? undefined : fromJSONL(new TextDecoder().decode(complete));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const utf8 = new TextEncoder();
|
|
229
|
+
|
|
230
|
+
/** Writes every byte: `writeSync` may write fewer than it was given. */
|
|
231
|
+
function writeAll(fd: number, text: string): void {
|
|
232
|
+
const bytes = utf8.encode(text);
|
|
233
|
+
let offset = 0;
|
|
234
|
+
while (offset < bytes.length) {
|
|
235
|
+
const written = writeSync(fd, bytes, offset);
|
|
236
|
+
if (written === 0) throw new Error("write made no progress");
|
|
237
|
+
offset += written;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Makes a new file's directory entry durable. Not every system can fsync a directory. */
|
|
242
|
+
function syncDir(dir: string): void {
|
|
243
|
+
try {
|
|
244
|
+
const fd = openSync(dir, "r");
|
|
245
|
+
try {
|
|
246
|
+
fsyncSync(fd);
|
|
247
|
+
} finally {
|
|
248
|
+
closeSync(fd);
|
|
249
|
+
}
|
|
250
|
+
} catch {
|
|
251
|
+
// not supported here
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
interface Writing {
|
|
256
|
+
readonly fd: number;
|
|
257
|
+
readonly lock: string;
|
|
258
|
+
readonly encoder: { encode(event: TraceEvent): string };
|
|
259
|
+
next: number;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function fileStore(dir: string, options: FileStoreOptions = {}): FileStore {
|
|
263
|
+
const durability = options.durability ?? "writes";
|
|
264
|
+
const writing = new Map<string, Writing>();
|
|
265
|
+
const fileOf = (runId: string) => join(dir, `${runId}.jsonl`);
|
|
266
|
+
// Absolute, so every store for this directory, however it is written, agrees on which locks this thread holds.
|
|
267
|
+
const lockOf = (runId: string) => resolve(dir, `${runId}.lock`);
|
|
268
|
+
|
|
269
|
+
function acquire(runId: string): string {
|
|
270
|
+
const lock = lockOf(runId);
|
|
271
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
272
|
+
if (link(lock)) {
|
|
273
|
+
hold(lock);
|
|
274
|
+
return lock;
|
|
275
|
+
}
|
|
276
|
+
const content = readIfExists(lock);
|
|
277
|
+
if (content === undefined) continue; // released in the meantime
|
|
278
|
+
if (holds(lock, content)) {
|
|
279
|
+
const pid = pidIn(content);
|
|
280
|
+
if (pid === undefined) {
|
|
281
|
+
throw new Error(
|
|
282
|
+
`Run "${runId}" has a lock file without a process id (${lock}); remove it if no process is writing the run`,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
throw new Error(`Run "${runId}" is being written by process ${pid} (${lock})`);
|
|
286
|
+
}
|
|
287
|
+
takeOver(runId, lock, content);
|
|
288
|
+
}
|
|
289
|
+
throw new Error(`Run "${runId}" is being written by another process`);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function release(runId: string, w: Writing): void {
|
|
293
|
+
writing.delete(runId);
|
|
294
|
+
try {
|
|
295
|
+
closeSync(w.fd);
|
|
296
|
+
} finally {
|
|
297
|
+
releaseLock(w.lock);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Opens a new run's file. One with no complete line is what a crash right after creating it leaves: start over. */
|
|
302
|
+
function create(path: string, runId: string): number {
|
|
303
|
+
try {
|
|
304
|
+
return openSync(path, "ax");
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (codeOf(error) !== "EEXIST") throw error;
|
|
307
|
+
}
|
|
308
|
+
if (completeLines(readFileSync(path)).length > 0) throw new Error(`Run "${runId}" already exists in ${dir}`);
|
|
309
|
+
unlinkSync(path);
|
|
310
|
+
return openSync(path, "ax");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function open(event: TraceEvent): Writing {
|
|
314
|
+
checkRunId(event.runId);
|
|
315
|
+
mkdirSync(dir, { recursive: true });
|
|
316
|
+
const path = fileOf(event.runId);
|
|
317
|
+
const noFile = () => new Error(`Run "${event.runId}" has no file in ${dir} to continue`);
|
|
318
|
+
const lock = acquire(event.runId);
|
|
319
|
+
let fd: number | undefined;
|
|
320
|
+
try {
|
|
321
|
+
if (event.seq === 0) {
|
|
322
|
+
fd = create(path, event.runId);
|
|
323
|
+
if (durability !== "none") syncDir(dir);
|
|
324
|
+
return { fd, lock, encoder: createTraceEncoder(), next: 0 };
|
|
325
|
+
}
|
|
326
|
+
if (!existsSync(path)) throw noFile();
|
|
327
|
+
fd = openSync(path, "a");
|
|
328
|
+
const bytes = readFileSync(path);
|
|
329
|
+
const complete = completeLines(bytes);
|
|
330
|
+
const prefix = traceOf(complete);
|
|
331
|
+
if (!prefix) throw noFile();
|
|
332
|
+
const last = (prefix[prefix.length - 1] as TraceEvent).seq;
|
|
333
|
+
if (last !== event.seq - 1) {
|
|
334
|
+
throw new Error(`Run "${event.runId}" on disk ends at seq ${last}, but the next event is seq ${event.seq}`);
|
|
335
|
+
}
|
|
336
|
+
// Cut the torn tail only after the checks, so a refused continuation leaves the file as it is.
|
|
337
|
+
if (complete.length < bytes.length) ftruncateSync(fd, complete.length);
|
|
338
|
+
return { fd, lock, encoder: createTraceEncoder(prefix), next: event.seq };
|
|
339
|
+
} catch (error) {
|
|
340
|
+
try {
|
|
341
|
+
if (fd !== undefined) closeSync(fd);
|
|
342
|
+
} catch {
|
|
343
|
+
// keep the original error
|
|
344
|
+
}
|
|
345
|
+
releaseLock(lock);
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const sink = (event: TraceEvent): void => {
|
|
351
|
+
let w = writing.get(event.runId);
|
|
352
|
+
if (!w) {
|
|
353
|
+
w = open(event);
|
|
354
|
+
writing.set(event.runId, w);
|
|
355
|
+
}
|
|
356
|
+
// Not released: the entry may belong to another run with the same id that is still going in this process.
|
|
357
|
+
if (event.seq !== w.next) throw new Error(`Run "${event.runId}" expected seq ${w.next}, got ${event.seq}`);
|
|
358
|
+
try {
|
|
359
|
+
writeAll(w.fd, `${w.encoder.encode(event)}\n`);
|
|
360
|
+
w.next++;
|
|
361
|
+
const critical =
|
|
362
|
+
event.type === "pause" ||
|
|
363
|
+
event.type === "run_end" ||
|
|
364
|
+
(event.type === "enter" && event.meta?.effect === "write");
|
|
365
|
+
if (durability === "every" || (durability === "writes" && critical)) fsyncSync(w.fd);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
// ENOSPC, EIO: the run ends here and the kernel will not send its run_end. Free the run, so a resume opens the
|
|
368
|
+
// file again and cuts what was half written.
|
|
369
|
+
try {
|
|
370
|
+
release(event.runId, w);
|
|
371
|
+
} catch {
|
|
372
|
+
// keep the original error
|
|
373
|
+
}
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
if (event.type === "run_end") release(event.runId, w);
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
dir,
|
|
381
|
+
sink,
|
|
382
|
+
load(runId) {
|
|
383
|
+
checkRunId(runId);
|
|
384
|
+
const path = fileOf(runId);
|
|
385
|
+
return existsSync(path) ? traceOf(completeLines(readFileSync(path))) : undefined;
|
|
386
|
+
},
|
|
387
|
+
list() {
|
|
388
|
+
if (!existsSync(dir)) return [];
|
|
389
|
+
return readdirSync(dir)
|
|
390
|
+
.filter((name) => name.endsWith(".jsonl") && RUN_ID.test(name.slice(0, -".jsonl".length)))
|
|
391
|
+
.flatMap((name): StoredRun[] => {
|
|
392
|
+
const runId = name.slice(0, -".jsonl".length);
|
|
393
|
+
const path = join(dir, name);
|
|
394
|
+
try {
|
|
395
|
+
const trace = traceOf(completeLines(readFileSync(path)));
|
|
396
|
+
if (!trace) return [];
|
|
397
|
+
const status = runStatus(trace);
|
|
398
|
+
const stored: StoredRunStatus =
|
|
399
|
+
status !== "running" ? status : locked(lockOf(runId)) ? "running" : "interrupted";
|
|
400
|
+
return [{ runId, status: stored, events: trace.length, updatedAt: statSync(path).mtimeMs }];
|
|
401
|
+
} catch {
|
|
402
|
+
return [];
|
|
403
|
+
}
|
|
404
|
+
})
|
|
405
|
+
.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -5,13 +5,16 @@ export type { TaugraphErrorCode, TaugraphErrorDetails } from "./core/errors.js";
|
|
|
5
5
|
export { isTaugraphError, TaugraphError } from "./core/errors.js";
|
|
6
6
|
export { createGraph } from "./core/graph.js";
|
|
7
7
|
export { defineNode } from "./core/node.js";
|
|
8
|
+
export { isRetryable } from "./core/retry.js";
|
|
8
9
|
export type { StandardSchemaV1 } from "./core/standard-schema.js";
|
|
9
|
-
export type { RecordedStep, TraceDiff } from "./core/trace.js";
|
|
10
|
+
export type { RecordedStep, RunStatus, TraceDiff } from "./core/trace.js";
|
|
10
11
|
export {
|
|
11
12
|
assertTrace,
|
|
13
|
+
createTraceEncoder,
|
|
12
14
|
diffTraces,
|
|
13
15
|
fromJSONL,
|
|
14
16
|
recordedSteps,
|
|
17
|
+
runStatus,
|
|
15
18
|
TRACE_FORMAT,
|
|
16
19
|
TRACE_VERSION,
|
|
17
20
|
toJSONL,
|
|
@@ -36,6 +39,7 @@ export type {
|
|
|
36
39
|
ReplayMode,
|
|
37
40
|
ReplayOptions,
|
|
38
41
|
ResumeOptions,
|
|
42
|
+
RetryBackoff,
|
|
39
43
|
RetryPolicy,
|
|
40
44
|
RunContext,
|
|
41
45
|
RunOptions,
|
package/src/nodes/code.ts
CHANGED
|
@@ -4,6 +4,11 @@ export interface CodeNodeOptions {
|
|
|
4
4
|
readonly retry?: RetryPolicy;
|
|
5
5
|
/** Declare `"write"` for code that changes the outside world, so replay will not repeat it. */
|
|
6
6
|
readonly effect?: Effect;
|
|
7
|
+
/**
|
|
8
|
+
* Milliseconds an async node may take; then it fails with TIMEOUT and `ctx.signal` aborts. Synchronous code cannot
|
|
9
|
+
* be interrupted.
|
|
10
|
+
*/
|
|
11
|
+
readonly timeoutMs?: number;
|
|
7
12
|
}
|
|
8
13
|
|
|
9
14
|
/**
|
package/src/nodes/llm.ts
CHANGED
|
@@ -140,6 +140,8 @@ interface LLMNodeBase<S> {
|
|
|
140
140
|
readonly prompt: (state: S) => LLMRequest | string;
|
|
141
141
|
/** Retries the whole call, including output parsing. */
|
|
142
142
|
readonly retry?: RetryPolicy;
|
|
143
|
+
/** Milliseconds each attempt may take; then the request's signal aborts and the attempt fails with TIMEOUT. */
|
|
144
|
+
readonly timeoutMs?: number;
|
|
143
145
|
}
|
|
144
146
|
|
|
145
147
|
export interface LLMTextNodeConfig<S> extends LLMNodeBase<S> {
|
|
@@ -196,7 +198,11 @@ export function LLMNode<S, T>(config: LLMTextNodeConfig<S> | LLMStructuredNodeCo
|
|
|
196
198
|
);
|
|
197
199
|
});
|
|
198
200
|
},
|
|
199
|
-
{
|
|
201
|
+
{
|
|
202
|
+
kind: "llm",
|
|
203
|
+
...(config.retry && { retry: config.retry }),
|
|
204
|
+
...(config.timeoutMs !== undefined && { timeoutMs: config.timeoutMs }),
|
|
205
|
+
},
|
|
200
206
|
);
|
|
201
207
|
}
|
|
202
208
|
|
package/src/openai/index.ts
CHANGED
|
@@ -30,7 +30,12 @@ export interface OpenAICompatibleOptions {
|
|
|
30
30
|
* without it. Set false for endpoints that refuse the field in input messages, such as Groq and Cerebras.
|
|
31
31
|
*/
|
|
32
32
|
readonly sendReasoning?: boolean | undefined;
|
|
33
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* The request field that carries `maxTokens`. Default `"max_tokens"`; OpenAI's reasoning models (o-series, GPT-5)
|
|
35
|
+
* want `"max_completion_tokens"`.
|
|
36
|
+
*/
|
|
37
|
+
readonly tokenLimit?: "max_tokens" | "max_completion_tokens" | undefined;
|
|
38
|
+
/** Used instead of the global `fetch`, e.g. for a proxy or tests. */
|
|
34
39
|
readonly fetch?: typeof fetch | undefined;
|
|
35
40
|
}
|
|
36
41
|
|
|
@@ -41,6 +46,29 @@ export interface OpenAIToolCall {
|
|
|
41
46
|
readonly function?: { readonly name?: string; readonly arguments?: string };
|
|
42
47
|
}
|
|
43
48
|
|
|
49
|
+
/** A response outside 200-299. `status` and `retryAfterMs` let `isRetryable` and the retry wait act on it. */
|
|
50
|
+
export class HTTPError extends Error {
|
|
51
|
+
override readonly name = "HTTPError";
|
|
52
|
+
constructor(
|
|
53
|
+
message: string,
|
|
54
|
+
readonly status: number,
|
|
55
|
+
readonly url: string,
|
|
56
|
+
/** From `Retry-After`, given in seconds or as an HTTP date; undefined when missing or unreadable. */
|
|
57
|
+
readonly retryAfterMs: number | undefined,
|
|
58
|
+
) {
|
|
59
|
+
super(message);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `Retry-After` in milliseconds: a number of seconds, or an HTTP date (0 once it has passed). */
|
|
64
|
+
function retryAfter(header: string | null): number | undefined {
|
|
65
|
+
if (header === null) return undefined;
|
|
66
|
+
const text = header.trim();
|
|
67
|
+
if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1000);
|
|
68
|
+
const date = Date.parse(text);
|
|
69
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
70
|
+
}
|
|
71
|
+
|
|
44
72
|
interface ChatCompletion {
|
|
45
73
|
model?: string;
|
|
46
74
|
choices?: {
|
|
@@ -191,6 +219,12 @@ export function fromOpenAIToolCalls(calls: readonly OpenAIToolCall[], round = 1)
|
|
|
191
219
|
export function openAICompatible(options: OpenAICompatibleOptions): LLMModel {
|
|
192
220
|
const url = `${options.baseURL.replace(/\/+$/, "")}/chat/completions`;
|
|
193
221
|
const id = `openai-compatible:${options.model}`;
|
|
222
|
+
const tokenLimit = options.tokenLimit ?? "max_tokens";
|
|
223
|
+
if (tokenLimit !== "max_tokens" && tokenLimit !== "max_completion_tokens") {
|
|
224
|
+
throw new TypeError(
|
|
225
|
+
`openAICompatible: tokenLimit must be "max_tokens" or "max_completion_tokens", got ${String(options.tokenLimit)}`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
194
228
|
const readImage = (image: string): MaybePromise<ImagePart> => {
|
|
195
229
|
if (/^https?:/i.test(image)) return { type: "image", url: image };
|
|
196
230
|
if (!options.resolveImage) throw new TypeError(`Image "${shown(image)}" needs resolveImage to be read`);
|
|
@@ -211,7 +245,7 @@ export function openAICompatible(options: OpenAICompatibleOptions): LLMModel {
|
|
|
211
245
|
model: options.model,
|
|
212
246
|
messages: toOpenAIMessages(messages, options.sendReasoning === false ? undefined : id),
|
|
213
247
|
temperature: request.temperature,
|
|
214
|
-
|
|
248
|
+
[tokenLimit]: request.maxTokens,
|
|
215
249
|
...(request.responseFormat === "json" && { response_format: { type: "json_object" } }),
|
|
216
250
|
...(request.tools?.length && { tools: toOpenAITools(request.tools) }),
|
|
217
251
|
...(request.toolChoice && { tool_choice: toOpenAIToolChoice(request.toolChoice) }),
|
|
@@ -220,7 +254,13 @@ export function openAICompatible(options: OpenAICompatibleOptions): LLMModel {
|
|
|
220
254
|
}),
|
|
221
255
|
});
|
|
222
256
|
if (!response.ok) {
|
|
223
|
-
|
|
257
|
+
const text = await response.text().catch(() => "");
|
|
258
|
+
throw new HTTPError(
|
|
259
|
+
`${url} responded ${response.status}: ${text.slice(0, 500)}`,
|
|
260
|
+
response.status,
|
|
261
|
+
url,
|
|
262
|
+
retryAfter(response.headers.get("retry-after")),
|
|
263
|
+
);
|
|
224
264
|
}
|
|
225
265
|
const body = (await response.json()) as ChatCompletion;
|
|
226
266
|
const choice = body.choices?.[0];
|