-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent-sandbox.ts
More file actions
795 lines (708 loc) · 31 KB
/
Copy pathagent-sandbox.ts
File metadata and controls
795 lines (708 loc) · 31 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
import { existsSync } from "node:fs"
import { readFile } from "node:fs/promises"
import { dirname, resolve } from "node:path"
import { commandArgValue, commandDiagnosticsCaptureArgs, normalizeSandboxToolPolicySnapshot, normalizeStructuredArtifacts, parseCommandJson, parseCommandJsonArray, parseCommandJsonObject, type ExecutionSpec, type MountSpec, type RuntimePolicy, type SandboxToolPolicySnapshot, type SandboxWorkspaceContract, type SandboxWorkspaceMode, type StructuredArtifactPayload, type WorkspaceRecipe } from "@automattic/wp-codebox-core"
import { resolvePluginEntrypointContract, type ComponentLoadMode } from "@automattic/wp-codebox-core"
import { SANDBOX_WORKSPACE_ROOT, stripUndefined } from "@automattic/wp-codebox-core/internals"
import { agentRuntimeProbeCode, agentSandboxRunCode, resolveSandboxTaskCode } from "./agent-code.js"
import { assertResolvedInputMountPathArgs, rewriteInputMountPathArgs, rewriteInputMountPathJsonArgs, type InputMountPathMapping } from "./input-mount-paths.js"
import type { AgentBundleSpec } from "./agent-code.js"
import type { PreparedWorkspaceMount } from "./recipe-sources.js"
import { defaultPolicy } from "./recipe-validation.js"
export interface AgentRuntimeProbeOptions {
providerPluginPaths: string[]
components: AgentRuntimeComponent[]
mounts: AgentRuntimeMount[]
wpVersion?: string
artifactsDirectory?: string
secretEnvNames?: string[]
json: boolean
}
export interface AgentSandboxRunOptions extends AgentRuntimeProbeOptions {
task: string
agent?: string
mode?: string
provider?: string
model?: string
sessionId?: string
maxTurns?: string
timeoutSeconds?: string
agentBundles?: AgentBundleSpec[]
runtimeTask?: Record<string, unknown>
structuredArtifacts?: StructuredArtifactPayload[]
sandboxToolPolicy?: SandboxToolPolicySnapshot
code?: string
codeFile?: string
sandboxWorkspace?: SandboxWorkspaceContract
}
export interface AgentSandboxBatchOptions extends AgentRuntimeProbeOptions {
tasks: string[]
agent?: string
mode?: string
provider?: string
model?: string
maxTurns?: string
concurrency?: string
}
export interface AgentSandboxBatchOutput {
success: boolean
schema: "wp-codebox/agent-sandbox-batch/v1"
concurrency: number
total: number
completed: number
failed: number
runs: Array<{ success: boolean; index: number; task: string }>
}
export type AgentRuntimeMount = {
type?: MountSpec["type"]
source: string
target: string
mode: "readonly" | "readwrite"
metadata?: Record<string, unknown>
}
export type AgentRuntimeComponent = {
source: string
slug: string
pluginFile: string
loadAs: ComponentLoadMode
kind: "component" | "provider-plugin"
}
export type ResolvedRecipeExecutionSpec = ExecutionSpec & {
args: string[]
originalCommand: string
originalArgs: string[]
resolvedArgs: string[]
}
const secretEnvPolicy: RuntimePolicy = {
...defaultPolicy,
secrets: "connector-scoped",
}
export function agentRuntimeMounts(options: AgentRuntimeProbeOptions): AgentRuntimeMount[] {
const components = agentRuntimeComponents(options)
return [
...components.map((component) => ({
source: component.source,
target: pluginTarget(component.slug, component.loadAs),
mode: "readonly" as const,
metadata: {
kind: component.kind,
slug: component.slug,
pluginFile: component.pluginFile,
loadAs: component.loadAs,
},
})),
...providerPluginMounts(options).map((plugin) => ({
source: plugin.source,
target: pluginTarget(plugin.slug, plugin.loadAs),
mode: "readonly" as const,
metadata: {
kind: "provider-plugin",
slug: plugin.slug,
pluginFile: plugin.pluginFile,
loadAs: plugin.loadAs,
},
})),
...options.mounts,
]
}
export async function recipeExecutionSpec(step: WorkspaceRecipe["workflow"]["steps"][number], recipeDirectory: string, sandboxWorkspace?: SandboxWorkspaceContract, options: { inputMountPathMap?: readonly InputMountPathMapping[] } = {}): Promise<ResolvedRecipeExecutionSpec> {
const originalArgs = step.args ?? []
const resolvedStep = { ...step, args: rewriteRecipeExecutionArgs(step.command, originalArgs, recipeDirectory, options.inputMountPathMap) }
const finish = (spec: ExecutionSpec & { args?: string[] }): ResolvedRecipeExecutionSpec => {
// Commands can generate PHP and serialized payloads after their source args
// are resolved, so canonicalize the generated execution spec as well.
const resolvedArgs = rewriteInputMountPathArgs(spec.args ?? [], options.inputMountPathMap)
assertResolvedInputMountPathArgs(resolvedArgs, options.inputMountPathMap, `Recipe command ${step.command}`)
return {
...spec,
args: resolvedArgs,
originalCommand: step.command,
originalArgs: [...originalArgs],
resolvedArgs,
}
}
if (resolvedStep.command === "wordpress.run-workload") {
return finish(await wordpressRunWorkloadExecutionSpec(resolvedStep, recipeDirectory))
}
if (resolvedStep.command === "wp-codebox.agent-runtime-probe") {
return finish({
command: "wordpress.run-php",
args: [`code=${agentRuntimeProbeCode(providerPluginContracts(resolvedStep.args ?? []), runtimeComponentContracts(resolvedStep.args ?? []))}`, ...commandDiagnosticsCaptureArgs(resolvedStep.diagnostics)],
diagnostics: resolvedStep.diagnostics,
})
}
if (resolvedStep.command === "wp-codebox.agent-sandbox-run") {
const args = resolvedStep.args ?? []
const task = commandArgValue(args, "task")
if (!task) {
throw new Error("wp-codebox.agent-sandbox-run requires task=<task>")
}
const codeFile = commandArgValue(args, "code-file")
const code = commandArgValue(args, "code")
if (code && codeFile) {
throw new Error("Use either code=<php> or code-file=<path>, not both")
}
const body = codeFile ? await readFile(resolve(recipeDirectory, codeFile), "utf8") : (code ?? await resolveSandboxTaskCode({
task,
agent: commandArgValue(args, "agent"),
mode: commandArgValue(args, "mode"),
provider: commandArgValue(args, "provider"),
model: commandArgValue(args, "model"),
sessionId: commandArgValue(args, "session-id"),
maxTurns: commandArgValue(args, "max-turns"),
timeoutSeconds: commandArgValue(args, "timeout-seconds"),
agentBundles: parseAgentBundles(args),
runtimeTask: parseRuntimeTask(args),
structuredArtifacts: parseStructuredArtifacts(args),
sandboxWorkspace: parseSandboxWorkspace(args) ?? sandboxWorkspace,
sandboxToolPolicy: parseSandboxToolPolicy(args),
}))
return finish({
command: "wordpress.run-php",
args: [
`code=${agentSandboxRunCode(task, body, providerPluginContracts(args), runtimeComponentContracts(args))}`,
"wp-cli-bridge=1",
...commandDiagnosticsCaptureArgs(resolvedStep.diagnostics),
],
diagnostics: resolvedStep.diagnostics,
})
}
return finish({ command: resolvedStep.command, args: [...(resolvedStep.args ?? []), ...commandDiagnosticsCaptureArgs(resolvedStep.diagnostics)], diagnostics: resolvedStep.diagnostics })
}
function rewriteRecipeExecutionArgs(command: string, args: readonly string[], recipeDirectory: string, inputMountPathMap: readonly InputMountPathMapping[] = []): string[] {
const rewritten = rewriteRecipeBrowserPayloadArgs(command, rewriteInputMountPathArgs(args, inputMountPathMap), recipeDirectory)
if (command === "wordpress.run-workload") {
return rewriteInputMountPathJsonArgs(rewritten, ["workload-json"], inputMountPathMap)
}
if (command === "wp-codebox/run-fuzz-suite") {
return rewriteInputMountPathJsonArgs(rewritten, ["input-json", "suite-json"], inputMountPathMap)
}
return rewritten
}
function rewriteRecipeBrowserPayloadArgs(command: string, args: readonly string[], recipeDirectory: string): string[] {
const fileBackedArgs = command === "wordpress.browser-actions"
? new Set(["steps-json", "browser-environment-json"])
: command === "wordpress.browser-scenario"
? new Set(["scenario-json", "steps-json", "browser-environment-json"])
: undefined
if (!fileBackedArgs) return [...args]
return args.map((arg) => {
const separator = arg.indexOf("=")
if (separator < 0 || !fileBackedArgs.has(arg.slice(0, separator))) return arg
const value = arg.slice(separator + 1)
if (!value.startsWith("@")) return arg
return `${arg.slice(0, separator + 1)}@${resolve(recipeDirectory, value.slice(1))}`
})
}
async function wordpressRunWorkloadExecutionSpec(step: WorkspaceRecipe["workflow"]["steps"][number], recipeDirectory: string): Promise<ExecutionSpec & { args: string[] }> {
const args = step.args ?? []
const workloadJson = commandArgValue(args, "workload-json")
if (workloadJson) {
const workloadInput = await wordpressWorkloadJsonInput(workloadJson, recipeDirectory)
return {
command: "wordpress.ability",
args: [
"name=wp-codebox/run-wordpress-workload",
`input=${workloadInput}`,
"expected-result-schema=\"wp-codebox/wordpress-workload-run-result/v1\"",
],
diagnostics: step.diagnostics,
}
}
const parsedArgs = commandArgsRecord(args)
const path = parsedArgs.path ?? parsedArgs.file
const type = parsedArgs.type?.toLowerCase() ?? (path?.toLowerCase().endsWith(".php") ? "php" : undefined)
if (type !== "php") {
throw new Error(`wordpress.run-workload recipe steps require workload-json=<json-or-file> or type=php; received args=${JSON.stringify(args)}`)
}
if (!path) {
throw new Error("wordpress.run-workload recipe steps require path=<php-file> or file=<php-file>")
}
if (parsedArgs.type === undefined) {
parsedArgs.type = type
}
const encodedArgs = Buffer.from(JSON.stringify(parsedArgs), "utf8").toString("base64")
const source = await readableTextFile(path)
const encodedSource = typeof source === "string" ? Buffer.from(source, "utf8").toString("base64") : undefined
const callableLoader = encodedSource ? `$__wp_codebox_workload_file = tempnam(sys_get_temp_dir(), 'wp-codebox-workload-');\nif (false === $__wp_codebox_workload_file) { throw new RuntimeException('Unable to create temporary PHP workload file.'); }\nfile_put_contents($__wp_codebox_workload_file, base64_decode('${encodedSource}'));\n$__wp_codebox_workload_callable = require $__wp_codebox_workload_file;\nunlink($__wp_codebox_workload_file);` : `$__wp_codebox_workload_callable = require ${JSON.stringify(path)};`
const code = `$__wp_codebox_workload_args = json_decode(base64_decode('${encodedArgs}'), true);\n${callableLoader}\nif (!is_callable($__wp_codebox_workload_callable)) { throw new RuntimeException('PHP workload file must return a callable.'); }\n$__wp_codebox_workload_result = $__wp_codebox_workload_callable(array(), is_array($__wp_codebox_workload_args) ? $__wp_codebox_workload_args : array());\nif (is_array($__wp_codebox_workload_result) || is_object($__wp_codebox_workload_result)) { echo json_encode($__wp_codebox_workload_result, JSON_UNESCAPED_SLASHES) . "\\n"; } elseif (false === $__wp_codebox_workload_result) { exit(1); }`
return { command: "wordpress.run-php", args: [`code=${code}`, ...commandDiagnosticsCaptureArgs(step.diagnostics)], diagnostics: step.diagnostics }
}
async function wordpressWorkloadJsonInput(value: string, recipeDirectory: string): Promise<string> {
try {
parseCommandJsonObject(value, "workload-json")
return value
} catch (inlineError) {
const path = resolve(recipeDirectory, value)
let source: string
try {
source = await readFile(path, "utf8")
} catch {
throw inlineError
}
const workload = parseCommandJsonObject(source, `workload-json file ${value}`)
return JSON.stringify(workload)
}
}
async function readableTextFile(path: string): Promise<string | undefined> {
if (path.trim() === "") {
return undefined
}
try {
return await readFile(path, "utf8")
} catch {
return undefined
}
}
function commandArgsRecord(args: string[]): Record<string, string> {
const parsed: Record<string, string> = {}
for (const arg of args) {
const [key, value = ""] = String(arg).split(/=(.*)/s, 2)
if (key) parsed[key] = value
}
return parsed
}
export function agentRuntimeMetadata(options: AgentRuntimeProbeOptions, runtimeMetadata: (artifactsDirectory: string | undefined, wpVersion: string) => Record<string, unknown>, defaultWordPressVersion: string): Record<string, unknown> {
const base = runtimeMetadata(options.artifactsDirectory, options.wpVersion ?? defaultWordPressVersion)
return {
...base,
task: {
...(base.task as Record<string, unknown>),
kind: "agent-runtime-probe",
secretEnv: options.secretEnvNames ?? [],
},
}
}
export function agentSandboxRunMetadata(options: AgentSandboxRunOptions, runtimeMetadata: (artifactsDirectory: string | undefined, wpVersion: string) => Record<string, unknown>, defaultWordPressVersion: string): Record<string, unknown> {
return {
...runtimeMetadata(options.artifactsDirectory, options.wpVersion ?? defaultWordPressVersion),
task: stripUndefined({
kind: "agent-sandbox-run",
input: options.task,
sessionId: options.sessionId,
maxTurns: options.maxTurns,
timeoutSeconds: options.timeoutSeconds,
hasCodeOverride: Boolean(options.code || options.codeFile),
secretEnv: options.secretEnvNames ?? [],
}),
agent: stripUndefined({
agent: options.agent,
mode: options.mode,
provider: options.provider,
model: options.model,
}),
}
}
export function parseAgentRuntimeProbeOptions(args: string[], parseMount: (value: string) => AgentRuntimeMount, extraOptions: string[] = []): AgentRuntimeProbeOptions {
const options: Partial<AgentRuntimeProbeOptions> = { json: false, mounts: [], components: [] }
for (let index = 0; index < args.length; index++) {
const arg = args[index]
if (arg === "--json") {
options.json = true
continue
}
const [name, inlineValue] = arg.split("=", 2)
const value = inlineValue ?? args[++index]
if (!name.startsWith("--") || value === undefined) {
throw new Error(`Invalid argument: ${arg}`)
}
switch (name) {
case "--agents-api":
options.components = [...(options.components ?? []), componentFromPath(value, "agents-api", undefined, "mu-plugin", "component")]
break
case "--provider-plugin":
options.providerPluginPaths = [...(options.providerPluginPaths ?? []), value]
break
case "--component":
options.components = [...(options.components ?? []), parseComponentOption(value, "component")]
break
case "--mount":
options.mounts = [...(options.mounts ?? []), parseMount(value)]
break
case "--wp":
options.wpVersion = value
break
case "--artifacts":
options.artifactsDirectory = value
break
case "--secret-env":
options.secretEnvNames = [...(options.secretEnvNames ?? []), value]
break
default:
if (extraOptions.includes(name)) {
break
}
throw new Error(`Unknown option: ${name}`)
}
}
options.providerPluginPaths = options.providerPluginPaths ?? []
options.mounts = options.mounts ?? []
options.components = options.components ?? []
return options as AgentRuntimeProbeOptions
}
export function parseAgentSandboxRunOptions(args: string[], parseMount: (value: string) => AgentRuntimeMount): AgentSandboxRunOptions {
const options = parseAgentRuntimeProbeOptions(args, parseMount, ["--task", "--agent", "--mode", "--provider", "--model", "--session-id", "--max-turns", "--timeout-seconds", "--agent-bundles-json", "--runtime-task-json", "--structured-artifacts-json", "--sandbox-tool-policy-json", "--code", "--code-file", "--workspace-context-json", "--secret-env", "--mount"]) as Partial<AgentSandboxRunOptions>
for (let index = 0; index < args.length; index++) {
const arg = args[index]
const [name, inlineValue] = arg.split("=", 2)
const value = inlineValue ?? args[index + 1]
switch (name) {
case "--task":
options.task = value
break
case "--agent":
options.agent = value
break
case "--mode":
options.mode = value
break
case "--provider":
options.provider = value
break
case "--model":
options.model = value
break
case "--session-id":
options.sessionId = value
break
case "--max-turns":
options.maxTurns = value
break
case "--timeout-seconds":
options.timeoutSeconds = value
break
case "--code":
options.code = value
break
case "--code-file":
options.codeFile = value
break
case "--agent-bundles-json":
options.agentBundles = parseAgentBundleList(value)
break
case "--runtime-task-json":
options.runtimeTask = parseRuntimeTaskValue(value)
break
case "--structured-artifacts-json":
options.structuredArtifacts = parseStructuredArtifactsValue(value)
break
case "--sandbox-tool-policy-json":
options.sandboxToolPolicy = normalizeSandboxToolPolicySnapshot(parseCommandJson(value, "sandbox-tool-policy-json"))
break
case "--workspace-context-json":
options.sandboxWorkspace = parseSandboxWorkspaceValue(value)
break
}
}
if (!options.task) {
throw new Error("Missing required option: --task")
}
if (options.code && options.codeFile) {
throw new Error("Use either --code or --code-file, not both")
}
return options as AgentSandboxRunOptions
}
function parseAgentBundles(args: string[]): AgentBundleSpec[] {
return parseAgentBundleList(commandArgValue(args, "agent-bundles-json") ?? "[]")
}
function parseRuntimeTask(args: string[]): Record<string, unknown> | undefined {
const value = commandArgValue(args, "runtime-task-json")
return value ? parseRuntimeTaskValue(value) : undefined
}
function parseStructuredArtifacts(args: string[]): StructuredArtifactPayload[] {
const value = commandArgValue(args, "structured-artifacts-json")
return value ? parseStructuredArtifactsValue(value) : []
}
function parseStructuredArtifactsValue(value: string): StructuredArtifactPayload[] {
if (!value.trim()) return []
return normalizeStructuredArtifacts(parseCommandJson(value, "structured-artifacts-json"), "input")
}
function parseRuntimeTaskValue(value: string): Record<string, unknown> | undefined {
if (!value.trim()) return undefined
return parseCommandJsonObject(value, "runtime-task-json")
}
function parseSandboxWorkspace(args: string[]): SandboxWorkspaceContract | undefined {
const value = commandArgValue(args, "workspace-context-json")
return value ? parseSandboxWorkspaceValue(value) : undefined
}
function parseSandboxWorkspaceValue(value: string): SandboxWorkspaceContract | undefined {
if (!value.trim()) return undefined
const parsed = parseCommandJsonObject(value, "workspace-context-json")
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || parsed.schema !== "wp-codebox/sandbox-workspace/v1") {
throw new Error("workspace-context-json must be a wp-codebox/sandbox-workspace/v1 object")
}
return parsed as unknown as SandboxWorkspaceContract
}
function parseAgentBundleList(value: string): AgentBundleSpec[] {
if (!value.trim()) return []
const parsed = parseCommandJsonArray(value, "agent-bundles-json")
return parsed.filter((entry): entry is AgentBundleSpec => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
}
export async function parseAgentSandboxBatchOptions(args: string[], parseMount: (value: string) => AgentRuntimeMount): Promise<AgentSandboxBatchOptions> {
const options = parseAgentRuntimeProbeOptions(args, parseMount, ["--task", "--tasks-json", "--tasks-file", "--agent", "--mode", "--provider", "--model", "--max-turns", "--concurrency", "--secret-env", "--mount"]) as Partial<AgentSandboxBatchOptions>
options.tasks = []
for (let index = 0; index < args.length; index++) {
const arg = args[index]
const [name, inlineValue] = arg.split("=", 2)
const value = inlineValue ?? args[index + 1]
switch (name) {
case "--task":
if (value) {
options.tasks.push(value)
}
break
case "--tasks-json":
if (value) {
options.tasks.push(...parseTaskList(value))
}
break
case "--tasks-file":
if (value) {
options.tasks.push(...parseTaskList(await readFile(resolve(value), "utf8")))
}
break
case "--agent":
options.agent = value
break
case "--mode":
options.mode = value
break
case "--provider":
options.provider = value
break
case "--model":
options.model = value
break
case "--max-turns":
options.maxTurns = value
break
case "--concurrency":
options.concurrency = value
break
}
}
options.tasks = options.tasks.map((task) => task.trim()).filter(Boolean)
if (options.tasks.length === 0) {
throw new Error("Missing required option: --task, --tasks-json, or --tasks-file")
}
return options as AgentSandboxBatchOptions
}
export function positiveInteger(value: string | undefined, fallback: number): number {
if (!value) {
return fallback
}
const parsed = Number.parseInt(value, 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}
export function resolveSecretEnv(names: string[]): Record<string, string> {
const secretEnv: Record<string, string> = {}
for (const name of names) {
const normalized = name.trim()
if (!/^[A-Z_][A-Z0-9_]*$/.test(normalized)) {
throw new Error(`Invalid --secret-env name: ${name}`)
}
const value = process.env[normalized]
if (value) {
secretEnv[normalized] = value
}
}
return secretEnv
}
export async function runSecretEnvOptions(options: AgentRuntimeProbeOptions): Promise<Pick<{ policy?: RuntimePolicy; secretEnv?: Record<string, string> }, "policy" | "secretEnv">> {
const secretEnv = resolveSecretEnv(options.secretEnvNames ?? [])
if (Object.keys(secretEnv).length === 0) {
return {}
}
return {
policy: secretEnvPolicy,
secretEnv,
}
}
export function sandboxWorkspaceContract(workspaceMounts: PreparedWorkspaceMount[], mounts: NonNullable<WorkspaceRecipe["inputs"]>["mounts"]): SandboxWorkspaceContract {
const mountRefs = [
...workspaceMounts.map((mount) => workspaceMountRef(mount.target, mount.mode, mount.metadata)),
...(Array.isArray(mounts) ? mounts.map((mount) => workspaceMountRef(mount.target, mount.mode ?? "readwrite", mount.metadata ?? {})) : []),
]
return {
schema: "wp-codebox/sandbox-workspace/v1",
root: SANDBOX_WORKSPACE_ROOT,
defaultMode: "repo-backed",
mounts: mountRefs,
}
}
function parseSandboxToolPolicy(args: string[]): SandboxToolPolicySnapshot | undefined {
const raw = commandArgValue(args, "sandbox-tool-policy-json")
if (!raw) {
return undefined
}
return normalizeSandboxToolPolicySnapshot(parseCommandJson(raw, "sandbox-tool-policy-json"))
}
function agentRuntimeComponents(options: AgentRuntimeProbeOptions): AgentRuntimeComponent[] {
const bySlug = new Map<string, AgentRuntimeComponent>()
for (const component of defaultRuntimeComponents()) {
bySlug.set(component.slug, component)
}
for (const component of options.components) {
bySlug.set(component.slug, component)
}
return [...bySlug.values()]
}
function defaultRuntimeComponents(): AgentRuntimeComponent[] {
return defaultRuntimeComponentSources()
.map((component) => componentFromPath(component.source, component.slug, undefined, "mu-plugin", "component"))
}
function defaultRuntimeComponentSources(): Array<{ source: string; slug?: string }> {
// The runner's agent-facing file/git/GitHub tool surface is served by the
// codebox-native runner-workspace executor (target `wp-codebox/runner-workspace`),
// which the active wp-codebox plugin registers onto the live Agents API tool
// executor contract. The external coding-agent plugin is no longer mounted as a
// default runtime component for the runner: it only ever supplied that surface.
//
// Only the Agents API runtime is mounted by default (it ships the conversation
// loop + tool-execution core the runner agent runs through). A host/deploy that
// still needs additional substrate opts back in via
// CONTAINED_RUNTIME_COMPONENT_PATHS / WP_CODEBOX_AGENT_RUNTIME_COMPONENT_PATHS.
const agentsApi = defaultAgentsApiPath(process.env.WP_CODEBOX_AGENTS_API_VENDOR_ROOT?.trim() ?? "")
return uniqueComponentSources([
agentsApi ? { source: agentsApi, slug: "agents-api" } : undefined,
...configuredRuntimeComponentPaths().map((source) => ({ source })),
])
}
function configuredRuntimeComponentPaths(): string[] {
return [process.env.CONTAINED_RUNTIME_COMPONENT_PATHS ?? process.env.WP_CODEBOX_AGENT_RUNTIME_COMPONENT_PATHS ?? ""]
.filter(Boolean)
.join(",")
.split(/[,:]/)
.map((value) => value.trim())
.filter(Boolean)
.map((value) => resolve(value))
.filter((source) => existsSync(source))
}
// Resolve the Agents API runtime source. Explicit path wins; otherwise, if a
// vendoring plugin root is supplied, resolve Agents API from its conventional
// vendored subpath; otherwise fall back to a sibling agents-api checkout. No
// product-specific plugin name is referenced.
function defaultAgentsApiPath(vendorRoot = ""): string {
const explicit = process.env.WP_CODEBOX_AGENTS_API_PATH?.trim()
if (explicit) {
return explicit
}
const bundled = vendorRoot ? resolve(vendorRoot, "vendor", "wordpress", "agents-api") : ""
if (bundled && existsSync(resolve(bundled, "agents-api.php"))) {
return bundled
}
return defaultSiblingComponentPath("agents-api", "agents-api.php")
}
function defaultSiblingComponentPath(slug: string, pluginFile: string, explicit = ""): string {
if (explicit.trim()) {
return explicit.trim()
}
return [
resolve(process.cwd(), "..", slug),
resolve(dirname(process.cwd()), slug),
].find((source) => existsSync(resolve(source, pluginFile))) ?? ""
}
function uniqueComponentSources(components: Array<{ source: string; slug?: string } | undefined>): Array<{ source: string; slug?: string }> {
const seen = new Set<string>()
return components.filter((component): component is { source: string; slug?: string } => {
if (!component?.source) {
return false
}
const source = resolve(component.source)
if (seen.has(source)) {
return false
}
seen.add(source)
return true
})
}
function providerPluginSlugs(args: string[]): string[] {
const csv = commandArgValue(args, "provider-plugin-slugs") ?? ""
return csv.split(",").map((slug) => slug.trim()).filter(Boolean)
}
function providerPluginMounts(options: AgentRuntimeProbeOptions): AgentRuntimeComponent[] {
return options.providerPluginPaths.map((pluginPath) => {
return componentFromPath(pluginPath, undefined, undefined, "plugin", "provider-plugin")
})
}
function componentFromPath(sourcePath: string, slug: string | undefined, pluginFile: string | undefined, loadAs: ComponentLoadMode, kind: AgentRuntimeComponent["kind"]): AgentRuntimeComponent {
const source = resolve(sourcePath)
const entrypoint = resolvePluginEntrypointContract({ source, slug, pluginFile, loadAs })
return { source, slug: entrypoint.slug, pluginFile: entrypoint.pluginFile, loadAs: entrypoint.loadAs, kind }
}
function parseComponentOption(raw: string, kind: AgentRuntimeComponent["kind"]): AgentRuntimeComponent {
const parts = raw.split(",").map((part) => part.trim()).filter(Boolean)
const fields = new Map<string, string>()
let source = ""
for (const part of parts) {
const equals = part.indexOf("=")
if (equals === -1) {
source = source || part
continue
}
fields.set(part.slice(0, equals), part.slice(equals + 1))
}
source = fields.get("source") || fields.get("path") || source
let slug = fields.get("slug")
if (!source && fields.size === 1) {
const [entry] = fields.entries()
if (entry) {
slug = entry[0]
source = entry[1]
}
}
if (!source) {
throw new Error("--component requires a source path")
}
return componentFromPath(source, slug, fields.get("pluginFile"), fields.get("loadAs") === "plugin" ? "plugin" : "mu-plugin", kind)
}
function providerPluginContracts(args: string[]): Array<{ slug: string; pluginFile?: string; loadAs?: ComponentLoadMode }> {
const explicit = commandArgValue(args, "provider-plugin-contracts-json")
if (explicit) {
const parsed = parseCommandJsonArray(explicit, "provider-plugin-contracts-json")
return parsed
.filter((plugin) => plugin && typeof plugin === "object" && !Array.isArray(plugin))
.map((plugin) => plugin as { slug: string; pluginFile?: string; loadAs?: ComponentLoadMode })
}
return providerPluginSlugs(args).map((slug) => ({ slug }))
}
function runtimeComponentContracts(args: string[]): Array<{ slug: string; pluginFile?: string; loadAs?: ComponentLoadMode }> {
const explicit = commandArgValue(args, "runtime-component-contracts-json")
if (!explicit) {
return []
}
const parsed = parseCommandJsonArray(explicit, "runtime-component-contracts-json")
return parsed
.filter((plugin) => plugin && typeof plugin === "object" && !Array.isArray(plugin))
.map((plugin) => plugin as { slug: string; pluginFile?: string; loadAs?: ComponentLoadMode })
}
function pluginTarget(slug: string, loadAs: ComponentLoadMode): string {
return loadAs === "mu-plugin" ? `/wordpress/wp-content/mu-plugins/contained-runtime/${slug}` : `/wordpress/wp-content/plugins/${slug}`
}
function parseTaskList(raw: string): string[] {
const parsed = parseCommandJsonArray(raw, "Task list")
return parsed.map((task) => {
if (typeof task === "string") {
return task
}
if (task && typeof task === "object" && "task" in task && typeof task.task === "string") {
return task.task
}
throw new Error("Task list entries must be strings or objects with a task string")
})
}
function workspaceMountRef(target: string, mode: "readonly" | "readwrite", metadata: Record<string, unknown> = {}): SandboxWorkspaceContract["mounts"][number] {
const sourceMode: SandboxWorkspaceMode = metadata.sourceMode === "site-backed" ? "site-backed" : "repo-backed"
return stripUndefined({
target,
mode,
sourceMode,
workspaceRef: typeof metadata.workspaceRef === "string" ? metadata.workspaceRef : undefined,
mountRole: typeof metadata.mountRole === "string" ? metadata.mountRole : typeof metadata.kind === "string" ? metadata.kind : undefined,
component: typeof metadata.component === "string" ? metadata.component : typeof metadata.slug === "string" ? metadata.slug : undefined,
repo: typeof metadata.repo === "string" ? metadata.repo : undefined,
gitRef: typeof metadata.gitRef === "string" ? metadata.gitRef : typeof metadata.default_branch === "string" ? metadata.default_branch : undefined,
defaultBranch: typeof metadata.default_branch === "string" ? metadata.default_branch : undefined,
wpContentPath: typeof metadata.wpContentPath === "string" ? metadata.wpContentPath : undefined,
})
}