-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexecute-native-agent-task.mjs
More file actions
505 lines (469 loc) · 28 KB
/
Copy pathexecute-native-agent-task.mjs
File metadata and controls
505 lines (469 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import { rmSync } from "node:fs"
import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises"
import { join, relative, resolve } from "node:path"
import { pathToFileURL } from "node:url"
import { spawn } from "node:child_process"
import { materializeExternalNativePackage, materializeRuntimeSources, normalizeExternalPackageSource, normalizeRuntimeSources, parseExternalPackageSourcePolicy, validateRuntimeSourceModel } from "./materialize-external-native-package.mjs"
import { readNativeResult } from "./native-result-file.mjs"
import { assertNoRuntimeSourcePaths, sanitizeRuntimeSourceJson, sanitizeRuntimeSourceText, sanitizeRuntimeSourceValue } from "./runtime-source-sanitizer.mjs"
import { publishRunnerWorkspace } from "./runner-workspace-publisher.mjs"
const requestPath = process.env.AGENT_TASK_REQUEST_PATH || ".codebox/agent-task-request.json"
const workspace = resolve(process.env.AGENT_TASK_WORKSPACE || process.cwd())
const codeboxRoot = resolve(process.env.WP_CODEBOX_WORKFLOW_ROOT || ".")
const codeboxCliPath = process.env.WP_CODEBOX_CLI_PATH || join(codeboxRoot, "packages/cli/dist/index.js")
const outputPath = process.env.GITHUB_OUTPUT
const MAX_CAPTURE_BYTES = 32768
const MAX_OUTPUT_CHARS = 8192
const secretValues = ["OPENAI_API_KEY", "MODEL_PROVIDER_SECRET_1", "MODEL_PROVIDER_SECRET_2", "MODEL_PROVIDER_SECRET_3", "MODEL_PROVIDER_SECRET_4", "MODEL_PROVIDER_SECRET_5", "GITHUB_TOKEN", "GH_TOKEN", "ACCESS_TOKEN", "EXTERNAL_PACKAGE_SOURCE_POLICY"].map((name) => process.env[name]).filter(Boolean)
let privateRuntimeSourceRoot = ""
let privateRuntimeSourceRootForSanitization = ""
function redact(value) {
if (typeof value === "string") return secretValues.reduce((output, secret) => output.split(secret).join("[REDACTED]"), value)
if (Array.isArray(value)) return value.map(redact)
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redact(entry)]))
return value
}
function bounded(value, limit = MAX_CAPTURE_BYTES) {
const safe = sanitizeRuntimeSourceText(redact(value), privateRuntimeSourceRoot)
if (typeof safe !== "string") return safe
return safe.length > limit ? `${safe.slice(0, limit)}\n[TRUNCATED ${safe.length - limit} characters]` : safe
}
function capturedStream(limit = MAX_CAPTURE_BYTES) {
const chunks = []
let retainedBytes = 0
let totalBytes = 0
return {
append(chunk) {
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
totalBytes += value.length
const remaining = limit - retainedBytes
if (remaining > 0) {
const retained = value.subarray(0, remaining)
chunks.push(retained)
retainedBytes += retained.length
}
},
result() {
return {
output: bounded(Buffer.concat(chunks, retainedBytes).toString("utf8"), limit),
truncated: totalBytes > retainedBytes,
}
},
}
}
function output(name, value) {
if (!outputPath) return Promise.resolve()
const rendered = typeof value === "string" ? value : JSON.stringify(value)
return appendFile(outputPath, `${name}<<__WP_CODEBOX_OUTPUT__\n${bounded(rendered, MAX_OUTPUT_CHARS)}\n__WP_CODEBOX_OUTPUT__\n`)
}
function safeEnvironment(extra = {}) {
return { PATH: process.env.PATH || "", HOME: process.env.HOME || "", CI: process.env.CI || "true", ...extra }
}
function agentEnvironment() {
return safeEnvironment(Object.fromEntries(["OPENAI_API_KEY", "MODEL_PROVIDER_SECRET_1", "MODEL_PROVIDER_SECRET_2", "MODEL_PROVIDER_SECRET_3", "MODEL_PROVIDER_SECRET_4", "MODEL_PROVIDER_SECRET_5", "GITHUB_TOKEN"].map((name) => [name, process.env[name]]).filter(([, value]) => value)))
}
function command(command, args, cwd, env = safeEnvironment()) {
return new Promise((resolveCommand) => {
const child = spawn(command, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] })
const stdout = capturedStream()
const stderr = capturedStream()
let settled = false
const complete = (code, error) => {
if (settled) return
settled = true
if (error) stderr.append(`${error.message}\n`)
const capturedStdout = stdout.result()
const capturedStderr = stderr.result()
resolveCommand({
code: code ?? 1,
stdout: capturedStdout.output,
stderr: capturedStderr.output,
stdout_truncated: capturedStdout.truncated,
stderr_truncated: capturedStderr.truncated,
})
}
child.stdout.on("data", (chunk) => { stdout.append(chunk) })
child.stderr.on("data", (chunk) => { stderr.append(chunk) })
child.on("close", (code) => complete(code))
child.on("error", (error) => complete(1, error))
})
}
function record(value) {
return value && typeof value === "object" && !Array.isArray(value) ? value : {}
}
function string(value) {
return typeof value === "string" ? value.trim() : ""
}
function commandEntries(value, name) {
if (!Array.isArray(value)) throw new Error(`${name} must be an array.`)
return value.map((entry, index) => {
const check = record(entry)
const command = string(check.command)
if (!command) throw new Error(`${name}[${index}].command must be a non-empty string.`)
const description = check.description === undefined ? command : string(check.description)
if (!description) throw new Error(`${name}[${index}].description must be a non-empty string when provided.`)
return { command, description }
})
}
function resultValue(result, path) {
return path.split(".").reduce((value, key) => value && typeof value === "object" && !Array.isArray(value) ? value[key] : undefined, result)
}
function accessFailure(request) {
const access = record(request.access)
const allowed = Array.isArray(access.allowed_repos) ? access.allowed_repos : []
const tokenRepos = Array.isArray(access.access_token_repos) ? access.access_token_repos : []
const target = string(request.target_repo)
const caller = string(access.caller_repo)
if (!allowed.includes(target) || !tokenRepos.includes(target)) return "Target repository is not explicitly authorized by allowed_repos and access_token_repos."
if (!caller) return "Caller repository is required for publication authorization."
if (target !== caller && process.env.EXPLICIT_ACCESS_TOKEN_CONFIGURED !== "true") return "An explicit ACCESS_TOKEN is required for cross-repository publication."
if (!string(process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN)) return "No effective GitHub token is available for runner workspace tools."
return ""
}
function validPublication(value, targetRepo) {
const publication = record(value)
const pullRequest = record(publication.pull_request)
const url = string(pullRequest.url)
return publication.schema === "wp-codebox/runner-workspace-publication-result/v1"
&& publication.success === true
&& publication.status === "published"
&& /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+\/?$/.test(url)
&& url.startsWith(`https://github.com/${targetRepo}/pull/`)
}
async function verifyPublishedPullRequest(publication, targetRepo, cwd) {
if (!validPublication(publication, targetRepo)) return { valid: false, error: "Publication did not return a valid canonical pull-request result." }
const match = string(record(publication).pull_request && record(publication).pull_request.url).match(/\/pull\/(\d+)\/?$/)
const pullNumber = match?.[1]
if (!pullNumber) return { valid: false, error: "Publication pull-request URL did not contain a pull number." }
const response = await command("gh", ["api", `repos/${targetRepo}/pulls/${pullNumber}`], cwd, agentEnvironment())
if (response.code !== 0) return { valid: false, error: "Published pull request could not be resolved through GitHub.", stderr: response.stderr, stderr_truncated: response.stderr_truncated }
try {
const pullRequest = JSON.parse(response.stdout)
return {
valid: pullRequest?.html_url === record(publication).pull_request?.url
&& pullRequest?.base?.repo?.full_name === targetRepo,
error: "Published pull request did not resolve to the target repository.",
}
} catch {
return { valid: false, error: "GitHub pull-request validation did not return JSON." }
}
}
function projections(value, runtimeResult) {
const entries = Object.entries(record(value))
const output = {}
for (const [name, declaration] of entries) {
const descriptor = typeof declaration === "string" ? { path: declaration, required: true } : record(declaration)
if (!/^[A-Za-z0-9_.-]+$/.test(name)) {
throw new Error(`output_projections.${name} must have a non-empty output name.`)
}
if (Object.keys(descriptor).some((key) => key !== "path" && key !== "required")) {
throw new Error(`output_projections.${name} descriptor supports only path and required.`)
}
const path = string(descriptor.path)
if (!path || !/^[A-Za-z0-9_.-]+(?:\.[A-Za-z0-9_.-]+)*$/.test(path)) {
throw new Error(`output_projections.${name}.path must be a dot-delimited result path.`)
}
if (typeof descriptor.required !== "boolean") {
throw new Error(`output_projections.${name}.required must be a boolean.`)
}
const projected = resultValue(runtimeResult, path)
if (projected === undefined && descriptor.required) throw new Error(`output_projections.${name} did not resolve from ${path}.`)
if (projected === undefined) continue
output[name] = projected
}
return output
}
function requiredArtifacts(declarations) {
return Array.from(new Set((Array.isArray(declarations) ? declarations : []).flatMap((declaration) => {
const artifact = record(declaration)
const name = string(artifact.name)
return artifact.required === true && artifact.direction !== "input" && name ? [name] : []
})))
}
function workflowPath(path) {
const relativePath = relative(workspace, resolve(path))
return relativePath && !relativePath.startsWith("..") ? relativePath.replaceAll("\\", "/") : ".codebox/agent-task-workflow-result.json"
}
function failureClassification(error) {
const message = error instanceof Error ? error.message : String(error)
const code = typeof error?.code === "string" && error.code ? error.code : ""
if (code.includes(".policy")) return { code, classification: "policy" }
if (code && !/materializ|fetch|download|archive|entrypoint|git failed|spawn git/i.test(message)) return { code, classification: "native-agent-task" }
if (/policy|authorized|allowlisted|allowed_repos|ACCESS_TOKEN/i.test(message)) return { code: "wp-codebox.agent-task.policy", classification: "policy" }
if (/materializ|fetch|download|archive|entrypoint|git failed|spawn git/i.test(message)) return { code: "wp-codebox.agent-task.materialization", classification: "materialization" }
if (/approval|publication|pull request/i.test(message)) return { code: "wp-codebox.agent-task.approval", classification: "approval" }
if (/projection/i.test(message)) return { code: "wp-codebox.agent-task.output-projection", classification: "output-projection" }
return { code: "wp-codebox.agent-task.execution", classification: "execution" }
}
async function writeNormalizedFailure(error, request = {}) {
const resultPath = join(workspace, ".codebox", "agent-task-workflow-result.json")
const failure = failureClassification(error)
const message = bounded(error instanceof Error ? error.message : String(error), MAX_OUTPUT_CHARS)
const accessError = failure.classification === "policy" && /allowed_repos|ACCESS_TOKEN|GitHub token|Caller repository|authorized/i.test(message)
const result = {
schema: "wp-codebox/agent-task-workflow-result/v1",
run_id: `${record(request).workload?.id || "agent-task"}-${process.env.GITHUB_RUN_ID || "local"}`.replace(/[^A-Za-z0-9._-]+/g, "-"),
status: "failed",
success: false,
request_path: workflowPath(requestPath),
failure: { ...failure, message },
...(accessError ? { access: { authorized: false, error: message } } : {}),
}
await mkdir(join(workspace, ".codebox"), { recursive: true })
const sanitized = sanitizeRuntimeSourceValue(redact(result), privateRuntimeSourceRootForSanitization)
assertNoRuntimeSourcePaths(sanitized, privateRuntimeSourceRootForSanitization)
await writeFile(resultPath, `${JSON.stringify(sanitized, null, 2)}\n`)
await output("job_status", "failed")
await output("result_path", ".codebox/agent-task-workflow-result.json")
}
async function redactArtifactFiles(directory) {
const { readdir, stat } = await import("node:fs/promises")
for (const entry of await readdir(directory, { withFileTypes: true })) {
const path = join(directory, entry.name)
if (entry.isDirectory()) await redactArtifactFiles(path)
if (entry.isFile() && path.endsWith(".json") && (await stat(path)).size <= 4 * 1024 * 1024) {
const contents = await readFile(path, "utf8").catch(() => null)
if (contents !== null) {
const sanitized = sanitizeRuntimeSourceJson(bounded(contents, 4 * 1024 * 1024), privateRuntimeSourceRootForSanitization)
assertNoRuntimeSourcePaths(sanitized, privateRuntimeSourceRootForSanitization)
await writeFile(path, sanitized)
}
}
}
}
async function executeNativeAgentTask() {
const request = JSON.parse(await readFile(requestPath, "utf8"))
const verificationCommands = commandEntries(request.verification_commands, "verification_commands")
const driftChecks = commandEntries(request.drift_checks, "drift_checks")
const runId = `${request.workload?.id || "agent-task"}-${process.env.GITHUB_RUN_ID || "local"}`.replace(/[^A-Za-z0-9._-]+/g, "-")
const externalPackagePolicy = parseExternalPackageSourcePolicy(string(process.env.EXTERNAL_PACKAGE_SOURCE_POLICY))
const externalPackageSource = normalizeExternalPackageSource(request.external_package_source, externalPackagePolicy)
const runtimeSources = normalizeRuntimeSources(request.runtime_sources ?? [], externalPackagePolicy)
const requestedModel = validateRuntimeSourceModel(request.model, runtimeSources)
const artifactsPath = join(workspace, ".codebox", "agent-task-artifacts")
const runtimeInputPath = join(workspace, ".codebox", "native-agent-task-input.json")
const resultPath = join(workspace, ".codebox", "agent-task-workflow-result.json")
const controlledCodeboxPath = resolve(requestPath, "..")
const nativeResultPath = join(controlledCodeboxPath, "native-agent-task-result.json")
let cleaningPrivateRuntimeSources = false
async function cleanupPrivateRuntimeSources() {
if (cleaningPrivateRuntimeSources || !privateRuntimeSourceRoot) return
cleaningPrivateRuntimeSources = true
const root = privateRuntimeSourceRoot
privateRuntimeSourceRoot = ""
await rm(root, { recursive: true, force: true })
}
process.once("exit", () => { if (privateRuntimeSourceRoot) rmSync(privateRuntimeSourceRoot, { recursive: true, force: true }) })
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
process.once(signal, () => { cleanupPrivateRuntimeSources().finally(() => process.exit(128)) })
}
const runnerWorkspaceTools = [
"workspace_read", "workspace_ls", "workspace_grep", "workspace_write", "workspace_edit", "workspace_apply_patch",
"workspace_show", "workspace_git_status", "workspace_git_diff",
]
function runtimeMetadataForExecutionLocation(executionLocation) {
if (executionLocation === "sandbox") return { environment: "runtime_local", capability_scope: "runtime_local" }
if (executionLocation === "parent") return { environment: "control_plane", capability_scope: "control_plane" }
throw new Error(`Unsupported tool execution location: ${executionLocation}`)
}
await mkdir(artifactsPath, { recursive: true })
const accessError = accessFailure(request)
if (accessError) {
const error = new Error(accessError)
error.code = "wp-codebox.agent-task.policy"
throw error
}
const skipMaterialization = process.env.NODE_ENV === "test" && process.env.WP_CODEBOX_TEST_SKIP_MATERIALIZATION === "true"
const materializedPackage = request.run_agent && !request.dry_run && !skipMaterialization
? await materializeExternalNativePackage(externalPackageSource, { policy: externalPackagePolicy })
: undefined
const materializedRuntimeSources = request.run_agent && !request.dry_run && !skipMaterialization
? await materializeRuntimeSources(runtimeSources, { policy: externalPackagePolicy, forbiddenRoots: [workspace, artifactsPath] })
: undefined
privateRuntimeSourceRoot = materializedRuntimeSources?.root ?? ""
privateRuntimeSourceRootForSanitization = privateRuntimeSourceRoot
await output("runtime_source_root", privateRuntimeSourceRoot)
const runtimeSourceInputs = (materializedRuntimeSources?.lowered ?? []).reduce((input, lowered) => {
for (const [key, entries] of Object.entries(lowered)) input[key] = [...(input[key] ?? []), ...entries]
return input
}, {})
// Runtime source preparation must remain beside the private checkout, never in
// the target artifact directory that is collected after the run.
const privatePreparationRoot = privateRuntimeSourceRoot ? join(privateRuntimeSourceRoot, "prepared-runtime-sources") : ""
const sourcePackageRoot = privatePreparationRoot || artifactsPath
const executionInputPath = privateRuntimeSourceRoot ? join(privateRuntimeSourceRoot, "native-agent-task-input.json") : runtimeInputPath
const taskInput = {
schema: "wp-codebox/agent-task-run-request/v1",
task_id: runId,
artifacts_path: artifactsPath,
source_package_root: sourcePackageRoot,
callback_data: record(request.callback_data),
task_input: {
schema: "wp-codebox/task-input/v1",
goal: request.prompt,
target: { kind: "repo", materialization: { root: workspace } },
expected_artifacts: request.artifacts?.expected || [],
structured_artifacts: request.artifacts?.declarations || [],
secret_env: ["OPENAI_API_KEY", "MODEL_PROVIDER_SECRET_1", "MODEL_PROVIDER_SECRET_2", "MODEL_PROVIDER_SECRET_3", "MODEL_PROVIDER_SECRET_4", "MODEL_PROVIDER_SECRET_5"].filter((name) => process.env[name]),
...runtimeSourceInputs,
allowed_tools: runnerWorkspaceTools,
sandbox_tool_policy: {
schema: "wp-codebox/sandbox-tool-policy/v1",
version: 1,
tools: runnerWorkspaceTools.map((id) => ({ id, runtime_tool_id: id, execution_location: "sandbox", transport_visibility: "sandbox", allowed: true, runtime: runtimeMetadataForExecutionLocation("sandbox") })),
},
max_turns: request.limits?.max_turns,
task_timeout_seconds: Math.ceil(Number(request.limits?.time_budget_ms || 0) / 1000),
runtime_task: {
kind: "bundle",
ability: "wp-codebox/run-runtime-package",
input: {
schema: "wp-codebox/runtime-package-task/v1",
package: {
slug: materializedPackage?.identity.slug || "external-agent-pending-materialization",
source: "public-external-package",
external_source: externalPackageSource,
bootstrap: materializedPackage ? { encoding: "base64", bytes: materializedPackage.bytes.toString("base64"), digest: externalPackageSource.digest } : undefined,
},
workflow: { id: "agents/chat" },
input: {
prompt: request.prompt,
provider: requestedModel.provider,
model: requestedModel.name,
runner_workspace: { ...record(request.runner_workspace), allowed_repos: request.access.allowed_repos },
target_repo: request.target_repo,
writable_paths: request.writable_paths,
runner_workspace_policy: { allowed_repos: request.access.allowed_repos, writable_paths: request.writable_paths },
},
artifact_declarations: request.artifacts?.declarations || [],
required_artifacts: requiredArtifacts(request.artifacts?.declarations),
output_projections: [],
metadata: { workload: request.workload, ...(materializedPackage ? { imported_agent: materializedPackage.identity } : {}), runtime_sources: materializedRuntimeSources?.descriptors ?? [] },
},
},
},
workspaces: request.runner_workspace?.enabled ? [{ target: "/workspace", mode: "readwrite", sourceMode: "repo-backed", seed: { type: "directory", source: workspace, excludePaths: [".git/**", ".codebox/**", "node_modules/**", "vendor/**", "dist/**", "build/**", "coverage/**", ".cache/**"] } }] : [],
}
await writeFile(executionInputPath, `${JSON.stringify(taskInput, null, 2)}\n`)
let execution = { code: 0, stdout: "", stderr: "", stdout_truncated: false, stderr_truncated: false }
if (request.run_agent && !request.dry_run) {
execution = await command("node", [codeboxCliPath, "agent-task-run", "--input-file", executionInputPath, "--result-file", nativeResultPath], workspace, agentEnvironment())
}
// Public package bytes are embedded in the runtime recipe and consumed only by
// the Playground bootstrap before the agent's tools are resolved.
const nativeRuntimeResult = request.run_agent && !request.dry_run
? await readNativeResult(nativeResultPath, controlledCodeboxPath, secretValues, redact)
: {}
await rm(nativeResultPath, { force: true })
const runtimeResult = sanitizeRuntimeSourceValue(nativeRuntimeResult, privateRuntimeSourceRootForSanitization)
assertNoRuntimeSourcePaths(runtimeResult, privateRuntimeSourceRootForSanitization)
let workspaceApply = { status: "no-op", changedFiles: [] }
let runnerWorkspaceCore = null
if (execution.code === 0 && runtimeResult.success === true && request.runner_workspace?.enabled) {
runnerWorkspaceCore = await import(pathToFileURL(join(codeboxRoot, "packages/runtime-core/dist/runner-workspace-apply.js")).href)
const publicCore = await import(pathToFileURL(join(codeboxRoot, "packages/runtime-core/dist/public.js")).href)
const refs = publicCore.normalizePublicArtifactRefDTOs(runtimeResult)
.filter((ref) => ref.kind === "codebox-patch" || ref.kind === "codebox-changed-files")
workspaceApply = await runnerWorkspaceCore.applyRunnerWorkspacePatch({ artifactRoot: artifactsPath, artifactRefs: refs, workspaceRoot: workspace, writablePaths: String(request.writable_paths || "").split(",").map((value) => value.trim()).filter(Boolean) })
}
await cleanupPrivateRuntimeSources()
assertNoRuntimeSourcePaths(runtimeResult, privateRuntimeSourceRootForSanitization)
await redactArtifactFiles(artifactsPath)
const verification = []
if (execution.code === 0 && request.run_agent && !request.dry_run) {
const validationDependencies = string(request.validation_dependencies)
if (validationDependencies) {
const checkResult = await command("bash", ["-lc", validationDependencies], workspace)
verification.push({ kind: "validation_dependencies", command: validationDependencies, description: "Install validation dependencies", success: checkResult.code === 0, exit_code: checkResult.code, stdout: checkResult.stdout, stderr: checkResult.stderr, stdout_truncated: checkResult.stdout_truncated, stderr_truncated: checkResult.stderr_truncated })
}
for (const check of verificationCommands) {
const checkResult = await command("bash", ["-lc", check.command], workspace)
verification.push({ kind: "verification", ...check, success: checkResult.code === 0, exit_code: checkResult.code, stdout: checkResult.stdout, stderr: checkResult.stderr, stdout_truncated: checkResult.stdout_truncated, stderr_truncated: checkResult.stderr_truncated })
}
for (const check of driftChecks) {
const checkResult = await command("bash", ["-lc", check.command], workspace)
verification.push({ kind: "drift", ...check, success: checkResult.code === 0, exit_code: checkResult.code, stdout: checkResult.stdout, stderr: checkResult.stderr, stdout_truncated: checkResult.stdout_truncated, stderr_truncated: checkResult.stderr_truncated })
}
}
const verificationPassed = verification.every((check) => check.success)
const runtimeRecord = record(runtimeResult)
const agentResult = record(runtimeRecord.agent_task_run_result)
let publication = resultValue(runtimeRecord, "metadata.runner_workspace_publication")
if (execution.code === 0 && runtimeRecord.success === true && verificationPassed && workspaceApply.status === "applied") {
await runnerWorkspaceCore.verifyRunnerWorkspaceIntegrity(workspaceApply.integrity)
const testPublisher = string(process.env.WP_CODEBOX_TEST_PUBLISHER_MODULE)
const publisher = testPublisher ? (await import(pathToFileURL(resolve(testPublisher)).href)).publishRunnerWorkspace : publishRunnerWorkspace
const testHook = testPublisher && process.env.WP_CODEBOX_TEST_PUBLISHER_HOOK
? JSON.parse(process.env.WP_CODEBOX_TEST_PUBLISHER_HOOK)
: undefined
publication = await publisher({ request, changedFiles: workspaceApply.changedFiles, publicationFiles: workspaceApply.publicationFiles, token: process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN, ...(testHook ? { testHook } : {}) })
runtimeRecord.metadata = { ...record(runtimeRecord.metadata), runner_workspace_publication: publication }
runtimeRecord.outputs = { ...record(runtimeRecord.outputs), runner_workspace_publication: publication }
}
if (request.success?.requires_pr === true && workspaceApply.status === "no-op" && !publication) throw new Error("success_requires_pr cannot succeed for a no-op runner workspace task.")
let evaluatedProjections = {}
let projectionError = ""
try {
evaluatedProjections = projections(request.outputs?.projections, runtimeRecord)
} catch (error) {
projectionError = error instanceof Error ? error.message : String(error)
}
const publicationRequired = request.success?.requires_pr === true
const publicationVerification = publicationRequired && execution.code === 0 && runtimeRecord.success === true
? await verifyPublishedPullRequest(publication, request.target_repo, workspace)
: { valid: !publicationRequired, error: "" }
const publicationPassed = publicationVerification.valid
const success = request.run_agent && !request.dry_run
? execution.code === 0 && runtimeRecord.success === true && verificationPassed && publicationPassed && !projectionError
: true
const status = request.run_agent && !request.dry_run ? (success ? "succeeded" : "failed") : "skipped"
const result = {
schema: "wp-codebox/agent-task-workflow-result/v1",
run_id: runId,
status,
success,
request_path: requestPath,
runtime_input_path: ".codebox/native-agent-task-input.json",
execution: { stdout_truncated: execution.stdout_truncated, stderr_truncated: execution.stderr_truncated },
runtime_result: redact(runtimeRecord),
verification,
publication,
transcript: { artifact_name: request.artifacts?.transcript_name || "agent-task-transcript" },
artifacts: { declarations: request.artifacts?.declarations || [], expected: request.artifacts?.expected || [], replay_bundle_name: request.artifacts?.replay_bundle_name || "" },
outputs: {
engine_data: record(runtimeRecord.outputs),
projections: evaluatedProjections,
},
access: { authorized: true, credential_mode: process.env.GITHUB_TOKEN ? "runner-access-token" : (process.env.OPENAI_API_KEY ? "runner-provider-credentials" : "runner-default-credentials"), policy: { allowed_repos: request.access.allowed_repos } },
...(publicationRequired ? { publication_verification: publicationVerification } : {}),
...(publicationRequired && !publicationPassed ? { publication_error: "success_requires_pr requires a valid published runner-workspace pull request for target_repo." } : {}),
...(projectionError ? { projection_error: projectionError } : {}),
}
const sanitizedResult = sanitizeRuntimeSourceValue(redact(result), privateRuntimeSourceRootForSanitization)
assertNoRuntimeSourcePaths(sanitizedResult, privateRuntimeSourceRootForSanitization)
await writeFile(resultPath, `${JSON.stringify(sanitizedResult, null, 2)}\n`)
await output("job_status", status)
await output("transcript_json", JSON.stringify(agentResult.refs?.transcripts || []))
await output("transcript_summary", `${request.workload?.label || "Run Agent Task"}: ${status}`)
await output("engine_data_json", result.outputs.engine_data)
await output("projected_outputs_json", result.outputs.projections)
await output("credential_mode", result.access.credential_mode)
await output("declared_artifacts_json", result.artifacts.declarations)
await output("result_path", ".codebox/agent-task-workflow-result.json")
if (!success) process.exitCode = 1
}
try {
await executeNativeAgentTask()
} catch (error) {
try {
await writeNormalizedFailure(error)
} finally {
if (privateRuntimeSourceRoot) {
const root = privateRuntimeSourceRoot
privateRuntimeSourceRoot = ""
await rm(root, { recursive: true, force: true })
}
}
console.error(bounded(error instanceof Error ? error.message : String(error), MAX_OUTPUT_CHARS))
process.exitCode = 1
}