@tangle-network/agent-bench 3.0.0 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,352 @@
1
+ import { execFileSync, spawn } from 'node:child_process'
2
+ import {
3
+ closeSync,
4
+ createReadStream,
5
+ existsSync,
6
+ fsyncSync,
7
+ openSync,
8
+ readFileSync,
9
+ readdirSync,
10
+ renameSync,
11
+ writeFileSync,
12
+ } from 'node:fs'
13
+ import { basename, isAbsolute, join, resolve } from 'node:path'
14
+
15
+ const identityFile = 'identity.json'
16
+ const terminalFile = 'terminal.json'
17
+ const stopFile = 'stop-requested'
18
+
19
+ function fail(message) {
20
+ throw new Error(message)
21
+ }
22
+
23
+ function readJson(path, label) {
24
+ let value
25
+ try {
26
+ value = JSON.parse(readFileSync(path, 'utf8'))
27
+ } catch (error) {
28
+ throw new Error(`${label} is not valid JSON`, { cause: error })
29
+ }
30
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
31
+ fail(`${label} must be an object`)
32
+ }
33
+ return value
34
+ }
35
+
36
+ function syncDirectory(directory) {
37
+ const fd = openSync(directory, 'r')
38
+ try {
39
+ fsyncSync(fd)
40
+ } finally {
41
+ closeSync(fd)
42
+ }
43
+ }
44
+
45
+ function writeJsonAtomic(directory, name, value) {
46
+ const target = join(directory, name)
47
+ const temporary = join(directory, `.${name}.${process.pid}.tmp`)
48
+ const fd = openSync(temporary, 'wx', 0o600)
49
+ try {
50
+ writeFileSync(fd, `${JSON.stringify(value)}\n`, 'utf8')
51
+ fsyncSync(fd)
52
+ } finally {
53
+ closeSync(fd)
54
+ }
55
+ renameSync(temporary, target)
56
+ syncDirectory(directory)
57
+ }
58
+
59
+ async function readControlInput() {
60
+ const chunks = []
61
+ for await (const chunk of createReadStream('', { fd: 3 })) {
62
+ chunks.push(Buffer.from(chunk))
63
+ }
64
+ const bytes = Buffer.concat(chunks)
65
+ if (bytes.byteLength === 0) fail('Pier supervisor received no launch request')
66
+ return JSON.parse(bytes.toString('utf8'))
67
+ }
68
+
69
+ function processIdentity(pid) {
70
+ const text = readFileSync(`/proc/${pid}/stat`, 'utf8')
71
+ const closing = text.lastIndexOf(')')
72
+ if (closing < 0) fail(`cannot parse process identity for ${pid}`)
73
+ const fields = text.slice(closing + 2).trim().split(/\s+/)
74
+ const processGroupId = Number(fields[2])
75
+ const sessionId = Number(fields[3])
76
+ const startTicks = fields[19]
77
+ if (
78
+ !Number.isSafeInteger(processGroupId) ||
79
+ !Number.isSafeInteger(sessionId) ||
80
+ !/^\d+$/.test(startTicks ?? '')
81
+ ) {
82
+ fail(`cannot parse process identity for ${pid}`)
83
+ }
84
+ return { pid, processGroupId, sessionId, startTicks }
85
+ }
86
+
87
+ function processMatches(identity) {
88
+ try {
89
+ const current = processIdentity(identity.pid)
90
+ return (
91
+ current.startTicks === identity.startTicks &&
92
+ current.processGroupId === identity.processGroupId &&
93
+ current.sessionId === identity.sessionId
94
+ )
95
+ } catch (error) {
96
+ if (error?.code === 'ENOENT' || error?.code === 'ESRCH') return false
97
+ throw error
98
+ }
99
+ }
100
+
101
+ function sessionMembers(sessionId) {
102
+ const members = []
103
+ for (const entry of readdirSync('/proc', { withFileTypes: true })) {
104
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue
105
+ try {
106
+ const identity = processIdentity(Number(entry.name))
107
+ if (identity.sessionId === sessionId) members.push(identity)
108
+ } catch (error) {
109
+ if (error?.code !== 'ENOENT') throw error
110
+ }
111
+ }
112
+ return members
113
+ }
114
+
115
+ async function signalSessionUntilEmpty(identity, signal, timeoutMs) {
116
+ const deadline = Date.now() + timeoutMs
117
+ while (true) {
118
+ const members = sessionMembers(identity.sessionId)
119
+ if (members.length === 0) return true
120
+ for (const member of members) {
121
+ try {
122
+ process.kill(member.pid, signal)
123
+ } catch (error) {
124
+ if (error?.code !== 'ESRCH') throw error
125
+ }
126
+ }
127
+ if (Date.now() >= deadline) return false
128
+ await new Promise((resolveWait) => setTimeout(resolveWait, 20))
129
+ }
130
+ }
131
+
132
+ function sanitizeProject(value) {
133
+ let project = value.toLowerCase()
134
+ if (!/^[a-z0-9]/.test(project)) project = `0${project}`
135
+ return project.replace(/[^a-z0-9_-]/g, '-')
136
+ }
137
+
138
+ function trialProjects(jobsDirectory, jobName) {
139
+ const jobRoot = join(jobsDirectory, jobName)
140
+ if (!existsSync(jobRoot)) return []
141
+ return readdirSync(jobRoot, { withFileTypes: true })
142
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
143
+ .map((entry) => sanitizeProject(entry.name))
144
+ }
145
+
146
+ function matchingContainers(dockerCommand, projects) {
147
+ if (projects.length === 0) return []
148
+ const output = execFileSync(
149
+ dockerCommand,
150
+ ['ps', '-a', '--format', '{{.ID}}\t{{.Label "com.docker.compose.project"}}'],
151
+ { encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024 },
152
+ )
153
+ const matches = []
154
+ for (const line of output.split('\n')) {
155
+ if (!line) continue
156
+ const tab = line.indexOf('\t')
157
+ if (tab < 1) continue
158
+ const id = line.slice(0, tab)
159
+ const project = line.slice(tab + 1)
160
+ if (
161
+ projects.some(
162
+ (expected) =>
163
+ project === expected || project.startsWith(`${expected}__verifier__`),
164
+ )
165
+ ) {
166
+ matches.push(id)
167
+ }
168
+ }
169
+ return matches
170
+ }
171
+
172
+ function removeTrialContainers(config) {
173
+ const projects = trialProjects(config.jobsDirectory, config.jobName)
174
+ const containers = matchingContainers(config.dockerCommand, projects)
175
+ if (containers.length > 0) {
176
+ try {
177
+ execFileSync(config.dockerCommand, ['rm', '-f', ...containers], {
178
+ encoding: 'utf8',
179
+ timeout: 30_000,
180
+ maxBuffer: 4 * 1024 * 1024,
181
+ })
182
+ } catch (error) {
183
+ if (matchingContainers(config.dockerCommand, projects).length > 0) throw error
184
+ }
185
+ }
186
+ const remaining = matchingContainers(config.dockerCommand, projects)
187
+ if (remaining.length > 0) {
188
+ fail(`Pier task containers survived removal: ${remaining.join(', ')}`)
189
+ }
190
+ return containers.length
191
+ }
192
+
193
+ async function waitForExit(exited, timeoutMs) {
194
+ return await Promise.race([
195
+ exited.then(() => true),
196
+ new Promise((resolveTimeout) => setTimeout(() => resolveTimeout(false), timeoutMs)),
197
+ ])
198
+ }
199
+
200
+ const directory = resolve(process.argv[2] ?? '')
201
+ if (!isAbsolute(directory) || basename(directory) === '') {
202
+ fail('Pier supervisor control directory must be absolute')
203
+ }
204
+
205
+ let config
206
+ let child
207
+ let childIdentity
208
+ let stopRequested = existsSync(join(directory, stopFile))
209
+ let stopping
210
+
211
+ async function stopChild() {
212
+ if (!child) return
213
+ if (!childIdentity) {
214
+ try {
215
+ child.process.kill('SIGKILL')
216
+ } catch (error) {
217
+ if (error?.code !== 'ESRCH') throw error
218
+ }
219
+ if (!(await waitForExit(child.exited, 5_000))) {
220
+ fail('Pier process with unreadable identity survived SIGKILL')
221
+ }
222
+ return
223
+ }
224
+ if (!(await signalSessionUntilEmpty(childIdentity, 'SIGTERM', 2_000))) {
225
+ if (!(await signalSessionUntilEmpty(childIdentity, 'SIGKILL', 5_000))) {
226
+ fail(`Pier process session ${childIdentity.sessionId} survived SIGKILL`)
227
+ }
228
+ }
229
+ if (!(await waitForExit(child.exited, 5_000))) {
230
+ fail(`Pier process session ${childIdentity.sessionId} retained child processes`)
231
+ }
232
+ }
233
+
234
+ function requestStop() {
235
+ stopRequested = true
236
+ stopping ??= stopChild()
237
+ }
238
+
239
+ process.on('SIGTERM', requestStop)
240
+ process.on('SIGINT', requestStop)
241
+
242
+ try {
243
+ config = await readControlInput()
244
+ if (
245
+ !config ||
246
+ typeof config !== 'object' ||
247
+ typeof config.command !== 'string' ||
248
+ !Array.isArray(config.args) ||
249
+ typeof config.cwd !== 'string' ||
250
+ !config.env ||
251
+ typeof config.env !== 'object' ||
252
+ typeof config.jobsDirectory !== 'string' ||
253
+ typeof config.jobName !== 'string' ||
254
+ typeof config.dockerCommand !== 'string'
255
+ ) {
256
+ fail('Pier supervisor launch request is malformed')
257
+ }
258
+
259
+ const identity = readJson(join(directory, identityFile), 'Pier trial identity')
260
+ if (stopRequested || existsSync(join(directory, stopFile))) {
261
+ const removedContainers = removeTrialContainers(config)
262
+ writeJsonAtomic(directory, terminalFile, {
263
+ schemaVersion: 1,
264
+ kind: 'pier-trial-terminal',
265
+ status: 'stopped',
266
+ processExited: true,
267
+ containersRemoved: true,
268
+ removedContainers,
269
+ })
270
+ process.exitCode = 0
271
+ } else {
272
+ const spawned = spawn(config.command, config.args, {
273
+ cwd: config.cwd,
274
+ env: config.env,
275
+ detached: true,
276
+ stdio: 'ignore',
277
+ })
278
+ if (spawned.pid === undefined) fail('Pier process started without a pid')
279
+ const exited = new Promise((resolveExit) => {
280
+ let settled = false
281
+ spawned.once('error', (error) => {
282
+ if (settled) return
283
+ settled = true
284
+ resolveExit({ code: null, signal: null, error })
285
+ })
286
+ spawned.once('close', (code, signal) => {
287
+ if (settled) return
288
+ settled = true
289
+ resolveExit({ code, signal })
290
+ })
291
+ })
292
+ child = { process: spawned, exited }
293
+ childIdentity = processIdentity(spawned.pid)
294
+ writeJsonAtomic(directory, identityFile, {
295
+ ...identity,
296
+ state: 'running',
297
+ pier: childIdentity,
298
+ })
299
+
300
+ if (stopRequested || existsSync(join(directory, stopFile))) {
301
+ stopRequested = true
302
+ stopping = stopChild()
303
+ }
304
+ const exit = await exited
305
+ if (stopping) await stopping
306
+ else await stopChild()
307
+ const removedContainers = removeTrialContainers(config)
308
+ const status = stopRequested ? 'stopped' : exit.code === 0 ? 'completed' : 'failed'
309
+ writeJsonAtomic(directory, terminalFile, {
310
+ schemaVersion: 1,
311
+ kind: 'pier-trial-terminal',
312
+ status,
313
+ processExited: true,
314
+ containersRemoved: true,
315
+ removedContainers,
316
+ exitCode: exit.code,
317
+ signal: exit.signal,
318
+ ...(exit.error ? { error: 'Pier process failed to start' } : {}),
319
+ ...(status === 'failed' && !exit.error
320
+ ? { error: `Pier process exited ${exit.signal ?? exit.code ?? 'without status'}` }
321
+ : {}),
322
+ })
323
+ }
324
+ } catch (error) {
325
+ const cleanupErrors = []
326
+ try {
327
+ requestStop()
328
+ if (stopping) await stopping
329
+ } catch (cleanup) {
330
+ cleanupErrors.push(cleanup)
331
+ }
332
+ if (config) {
333
+ try {
334
+ removeTrialContainers(config)
335
+ } catch (cleanup) {
336
+ cleanupErrors.push(cleanup)
337
+ }
338
+ }
339
+ writeJsonAtomic(directory, terminalFile, {
340
+ schemaVersion: 1,
341
+ kind: 'pier-trial-terminal',
342
+ status: 'failed',
343
+ processExited: !childIdentity || !processMatches(childIdentity),
344
+ containersRemoved: cleanupErrors.length === 0,
345
+ error: `${error instanceof Error ? error.message : String(error)}${
346
+ cleanupErrors.length > 0
347
+ ? `; cleanup failed: ${cleanupErrors.map((item) => item?.message ?? String(item)).join('; ')}`
348
+ : ''
349
+ }`,
350
+ })
351
+ process.exitCode = 1
352
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-bench",
3
- "version": "3.0.0",
3
+ "version": "4.0.2",
4
4
  "type": "module",
5
5
  "description": "Benchmark adapters and execution for agent-runtime across coding, tool-use, RAG, memory, browser, and terminal tasks.",
6
6
  "repository": {
@@ -28,10 +28,10 @@
28
28
  }
29
29
  },
30
30
  "dependencies": {
31
- "@tangle-network/agent-eval": "^2.0.11",
32
- "@tangle-network/agent-interface": "^5.10.28",
31
+ "@tangle-network/agent-eval": "^2.0.29",
32
+ "@tangle-network/agent-interface": "^5.10.34",
33
33
  "@tangle-network/agent-knowledge": "^23.0.0",
34
- "@tangle-network/agent-runtime": "^10.0.16",
34
+ "@tangle-network/agent-runtime": "^11.0.0",
35
35
  "@tangle-network/sandbox": "^1.0.233"
36
36
  },
37
37
  "devDependencies": {
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "scripts": {
68
68
  "prebuild": "pnpm --dir .. build",
69
- "build": "tsdown",
69
+ "build": "tsdown && cp src/pier-trial-supervisor.mjs dist/",
70
70
  "gate": "tsx src/corpus-replay.mts corpus/finsearch.jsonl --selector",
71
71
  "gate-cli": "tsx src/gate-cli.mts",
72
72
  "run-benchmarks": "tsx src/run-benchmarks-cli.mts",