Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions .github/scripts/run-agent-task/agent-turn-limit-outcome.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* Explicit agent turn-limit outcome for the agent-task workflow result.
*
* The Agents API loop ends a synthesized max_turns budget silently and still
* reports a completed run, so a turn-capped agent used to surface as a green
* no-op (or fail later at verification). This projection makes the cap visible.
*
* Kept free of side effects so it is unit-testable without running the
* executor entrypoint.
*/

function record(value) {
return value && typeof value === "object" && !Array.isArray(value) ? value : {}
}

function positiveInteger(value) {
return Number.isSafeInteger(value) && value > 0 ? value : undefined
}

export const AGENT_TURN_LIMIT_SCHEMA = "wp-codebox/agent-turn-limit/v1"
export const AGENT_TURN_LIMIT_OUTCOME_SCHEMA = "wp-codebox/agent-turn-limit-outcome/v1"

/** Finds the content-free turn-limit record the runtime package executor stamps into result metadata. */
export function agentTurnLimitRecord(value) {
let found
const visit = (entry, depth) => {
if (found || depth > 12) return
if (Array.isArray(entry)) return entry.forEach((item) => visit(item, depth + 1))
const item = record(entry)
if (item.schema === AGENT_TURN_LIMIT_SCHEMA) {
found = item
return
}
Object.values(item).forEach((child) => visit(child, depth + 1))
}
visit(value, 0)
return found
}

/** Finds a canonical terminal result that reports a max_turns stop. */
function maxTurnsTerminalResult(runtimeResult) {
const runtime = record(runtimeResult)
const candidates = [
runtime.terminal_result,
record(runtime.agent_task_run_result).terminal_result,
record(record(runtime.agent_task_run_result).metadata).terminal_result,
].map(record)
return candidates.find((candidate) => candidate.status === "max_turns" || record(candidate.max_turns).reached === true)
}

/**
* Projects whether the agent stopped because it hit its turn cap without a
* final answer. Sources, strongest first:
* 1. a canonical `max_turns` terminal result,
* 2. the executor's `wp-codebox/agent-turn-limit/v1` metadata record,
* 3. tool observability: a tool call on the capped final turn means the model
* was still working when the loop ran out of turns.
* Returns undefined when nothing about the turn limit is known.
*/
export function agentTurnLimitOutcome({ runtimeResult, toolObservability, maxTurns }) {
const requestedMax = positiveInteger(maxTurns)
const terminal = maxTurnsTerminalResult(runtimeResult)
const limitRecord = agentTurnLimitRecord(runtimeResult)
const calls = Array.isArray(record(toolObservability).calls) ? record(toolObservability).calls.map(record) : []
const lastObservedTurn = calls.reduce((max, call) => Math.max(max, positiveInteger(call.turn) ?? 0), 0) || undefined

const max = positiveInteger(record(terminal?.max_turns).max) ?? positiveInteger(limitRecord?.max_turns) ?? requestedMax
const turnCount = positiveInteger(record(terminal?.max_turns).current) ?? positiveInteger(limitRecord?.turn_count) ?? lastObservedTurn
let source
let reached = false
if (terminal) {
source = "terminal-result"
reached = true
} else if (limitRecord) {
source = "runtime-turn-limit"
reached = limitRecord.max_turns_reached === true
} else if (requestedMax && lastObservedTurn) {
source = "tool-observability"
reached = lastObservedTurn >= requestedMax
} else {
return undefined
}

return Object.fromEntries(Object.entries({
schema: AGENT_TURN_LIMIT_OUTCOME_SCHEMA,
status: reached ? "max_turns" : "within_limit",
max_turns_reached: reached,
max_turns: max,
turn_count: turnCount,
limit_source: typeof limitRecord?.source === "string" ? limitRecord.source : undefined,
source,
message: reached
? `The agent reached its ${max ? `${max}-turn ` : "turn "}limit before producing a final answer; its work is incomplete.`
: undefined,
}).filter(([, entry]) => entry !== undefined))
}

/** The workflow failure recorded when the agent stopped at its turn cap. */
export function agentTurnLimitFailure(outcome) {
if (outcome?.status !== "max_turns") return undefined
return Object.fromEntries(Object.entries({
stage: "agent",
code: "max_turns_exceeded",
classification: "max_turns",
message: outcome.message,
max_turns: outcome.max_turns,
turn_count: outcome.turn_count,
}).filter(([, entry]) => entry !== undefined))
}
18 changes: 16 additions & 2 deletions .github/scripts/run-agent-task/execute-native-agent-task.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { assertNoRuntimeSourcePaths, sanitizeArtifactUploadText, sanitizeRuntime
import { publishRunnerWorkspace } from "./runner-workspace-publisher.mjs"
import { createRunnerWorkspaceSeedSnapshot, RUNNER_WORKSPACE_SEED_EXCLUDES } from "./runner-workspace-seed-snapshot.mjs"
import { runnerWorkspaceApplyOutcome, sandboxWorkspaceMutations } from "./runner-workspace-apply-outcome.mjs"
import { agentTurnLimitFailure, agentTurnLimitOutcome } from "./agent-turn-limit-outcome.mjs"
import { createTrustedArtifactApplyChannel, trustedArtifactApplyRefs } from "./trusted-artifact-snapshot.mjs"
import { artifactSourcePathCategory, assertNoSeedSnapshotPaths, containsRuntimeSourceContent, sanitizeSeedSnapshotJson } from "./artifact-upload-policy.mjs"
import { publishProcessMarker } from "../../../scripts/process-marker.mjs"
Expand Down Expand Up @@ -761,6 +762,9 @@ const taskInput = {
prompt: request.prompt,
provider: requestedModel.provider,
model: requestedModel.name,
// The runtime package runs its own agents/chat turn from this block;
// without an explicit limit here the package/handler default wins.
...(Number.isSafeInteger(request.limits?.max_turns) && request.limits.max_turns > 0 ? { max_turns: request.limits.max_turns } : {}),
runner_workspace: { ...record(request.runner_workspace), allowed_repos: request.access.allowed_repos },
target_repo: request.target_repo,
writable_paths: writablePaths,
Expand Down Expand Up @@ -811,7 +815,14 @@ let applyError
let workspaceEvidence
let runnerWorkspaceCore = null
let downstreamFailure = null
if (execution.code === 0 && runtimeResult.success === true && request.runner_workspace?.enabled) {
// A turn-capped agent never produced a final answer: report it at the agent
// stage and never apply or publish its partial work as if it had finished.
const agentTurnLimit = request.run_agent && !request.dry_run
? agentTurnLimitOutcome({ runtimeResult, toolObservability, maxTurns: request.limits?.max_turns })
: undefined
const agentTurnCapReached = agentTurnLimit?.status === "max_turns"
if (agentTurnCapReached) downstreamFailure = agentTurnLimitFailure(agentTurnLimit)
if (execution.code === 0 && runtimeResult.success === true && request.runner_workspace?.enabled && !agentTurnCapReached) {
try {
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)
Expand Down Expand Up @@ -926,6 +937,7 @@ const success = request.run_agent && !request.dry_run
? execution.code === 0 && runtimeRecord.success === true && verificationPassed && publicationPassed && !projectionError && !downstreamFailure
: true
const status = request.run_agent && !request.dry_run ? (success ? "succeeded" : "failed") : "skipped"
const terminalStatus = agentTurnCapReached ? "max_turns" : undefined
const workflowOutputs = {
transcript_json: await workflowOutputReference("transcript_json", serializedJson(agentResult.refs?.transcripts || []), artifactsPath),
engine_data_json: await workflowOutputReference("engine_data_json", serializedJson(redact(record(runtimeRecord.outputs))), artifactsPath),
Expand All @@ -936,6 +948,7 @@ const result = {
schema: "wp-codebox/agent-task-workflow-result/v1",
run_id: runId,
status,
...(terminalStatus ? { terminal_status: terminalStatus } : {}),
success,
request_path: requestPath,
runtime_input_path: ".codebox/native-agent-task-input.json",
Expand All @@ -948,6 +961,7 @@ const result = {
} : {}),
},
runtime_result: redact(runtimeRecord),
...(agentTurnLimit ? { agent_turn_limit: agentTurnLimit } : {}),
...(workspaceApplyOutcome ? { workspace_apply: workspaceApplyOutcome } : {}),
...(reviewerEvidence ? { reviewer_evidence: reviewerEvidence } : {}),
verification,
Expand All @@ -974,7 +988,7 @@ assertNoRuntimeSourcePaths(sanitizedResult, privateRuntimeSourceRootForSanitizat
await writeFile(resultPath, `${JSON.stringify(sanitizedResult, null, 2)}\n`)
await output("job_status", status)
await output("transcript_json", workflowOutputs.transcript_json.rendered)
await output("transcript_summary", `${request.workload?.label || "Run Agent Task"}: ${status}`)
await output("transcript_summary", `${request.workload?.label || "Run Agent Task"}: ${status}${terminalStatus ? ` (${terminalStatus})` : ""}`)
await output("engine_data_json", workflowOutputs.engine_data_json.rendered)
await output("projected_outputs_json", workflowOutputs.projected_outputs_json.rendered)
await output("credential_mode", result.access.credential_mode)
Expand Down
2 changes: 2 additions & 0 deletions .github/scripts/run-agent-task/prepare-agent-task-upload.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -176,11 +176,13 @@ function projectWorkflowResult(value) {
schema: result.schema,
run_id: result.run_id,
status: result.status,
terminal_status: result.terminal_status,
success: result.success,
request_path: result.request_path,
execution: Object.keys(execution).length ? { stdout_truncated: execution.stdout_truncated, stderr_truncated: execution.stderr_truncated } : undefined,
reviewer_evidence: reviewerEvidence.transcript === undefined ? undefined : { transcript: reviewerEvidence.transcript },
verification,
agent_turn_limit: result.agent_turn_limit,
workspace_apply: result.workspace_apply,
publication: result.publication,
transcript: result.transcript,
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/agent-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,12 @@ async function normalizeRuntimeTask(config: Record<string, unknown> | undefined,
if (!recordValue(input.task_input)) {
input.task_input = agentInput
}
const runtimePackageChatInput = ability === 'wp-codebox/run-runtime-package' ? recordValue(input.input) : null
if (runtimePackageChatInput && !positiveInteger(runtimePackageChatInput.max_turns) && positiveInteger(agentInput.max_turns)) {
// The runtime package executes its own agents/chat turn from input.input, so
// the caller's --max-turns must ride along or the package default wins.
input.input = { ...runtimePackageChatInput, max_turns: agentInput.max_turns }
}

const normalized: Record<string, unknown> = { ability, input: await runtimeTaskInputWithInlineBundle(ability, input, workspace) }
if (typeof config.wait_for_completion === "boolean") {
Expand Down Expand Up @@ -733,6 +739,10 @@ function recordValue(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined
}

function positiveInteger(value: unknown): boolean {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
}

export function agentSandboxRunCode(task: string, code: string, providerPlugins: Array<{ slug: string; pluginFile?: string; loadAs?: string }>, runtimeComponents: Array<{ slug: string; pluginFile?: string; loadAs?: string }> = []): string {
return `<?php
require_once ABSPATH . 'wp-admin/includes/plugin.php';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public function remediation_outcome( array $run, int $exit_code, string $output
$has_run_outcome = ! empty( $run_outcome );
$run_status = (string) ( $run_outcome['status'] ?? '' );
$stop_reason = (string) ( $run_outcome['stop_reason'] ?? '' );
$max_turns_reached = $has_run_outcome ? 'max_turns' === $stop_reason : $this->recursive_truthy_key( $run, 'max_turns_reached' );
// The upstream loop reports a silent max_turns cut-off as a natural stop, so
// the runtime package executor's turn-limit record is honored as well.
$max_turns_reached = ( $has_run_outcome ? 'max_turns' === $stop_reason : $this->recursive_truthy_key( $run, 'max_turns_reached' ) ) || $this->turn_limit_reached( $run );
$pending_runtime_tool = $has_run_outcome && ( 'runtime_tool_pending' === $run_status || 'runtime_tool_pending' === $stop_reason );
$provider_error = $has_run_outcome ? $this->agents_api_provider_error_details( $run_outcome ) : array();
$artifact = $this->remediation_artifact_details( $run );
Expand Down Expand Up @@ -233,6 +235,23 @@ private function decode_json_fragment( string $text ): ?array {
}

/** @param array<string,mixed> $payload */
/** @param array<string,mixed> $payload Decoded run output. */
private function turn_limit_reached( array $payload, int $depth = 0 ): bool {
if ( $depth > 16 ) {
return false;
}
if ( 'wp-codebox/agent-turn-limit/v1' === ( $payload['schema'] ?? null ) ) {
return true === ( $payload['max_turns_reached'] ?? false );
}
foreach ( $payload as $value ) {
if ( is_array( $value ) && $this->turn_limit_reached( $value, $depth + 1 ) ) {
return true;
}
}

return false;
}

private function recursive_truthy_key( array $payload, string $needle ): bool {
foreach ( $payload as $key => $value ) {
if ( $needle === (string) $key && true === (bool) $value ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ private function execute_workflow( array $task ): array|WP_Error {
}
$input['runtime_package_task'] = $task;
$input['run_id'] = $this->runtime_run_id( $input );
$turn_limit = $this->resolve_turn_limit( $input );
if ( null !== $turn_limit['max_turns'] ) {
// agents/chat resolves input.max_turns before the agent default config,
// so an explicit caller limit always overrides the package default.
$input['max_turns'] = $turn_limit['max_turns'];
}
$workspace_context = $this->sandbox_workspace_context( $input );
$ability_object = function_exists( 'wp_get_ability' ) ? wp_get_ability( $ability ) : null;
if ( ! is_object( $ability_object ) || ! method_exists( $ability_object, 'execute' ) ) {
Expand Down Expand Up @@ -176,9 +182,121 @@ private function execute_workflow( array $task ): array|WP_Error {
)
);

return $this->result_with_turn_limit( $result, $turn_limit );
}

/**
* Resolves the effective agent-loop turn limit for a runtime package run.
*
* An explicit positive caller `max_turns` wins. Otherwise the imported
* package's `meta.default_max_turns` applies. When neither is declared the
* agents/chat handler default is left in place.
*
* @param array<string,mixed> $input Workflow input.
* @return array{max_turns:int|null,source:string}
*/
private function resolve_turn_limit( array $input ): array {
$caller = $this->positive_int( $input['max_turns'] ?? null );
if ( null !== $caller ) {
return array( 'max_turns' => $caller, 'source' => 'caller' );
}
$agent = function_exists( 'wp_get_agent' ) ? wp_get_agent( (string) ( $input['agent'] ?? '' ) ) : null;
$meta = is_object( $agent ) && method_exists( $agent, 'get_meta' ) ? $agent->get_meta() : array();
$package_default = $this->positive_int( is_array( $meta ) ? ( $meta['default_max_turns'] ?? null ) : null );
if ( null !== $package_default ) {
return array( 'max_turns' => $package_default, 'source' => 'package_default' );
}

return array( 'max_turns' => null, 'source' => 'runtime_default' );
}

/**
* Records whether the agent loop stopped at its turn cap without a final answer.
*
* The Agents API loop ends a synthesized max_turns budget silently and still
* reports `completed: true`, so the cap is detected here: the loop ran every
* allowed turn and the final turn was still issuing tool calls (the model
* never got a turn to answer). An explicit `max_turns` stop reason is honored
* as well. A reached cap becomes a canonical `max_turns` terminal result.
*
* @param array<string,mixed> $result Workflow result.
* @param array{max_turns:int|null,source:string} $turn_limit Resolved turn limit.
* @return array<string,mixed>
*/
private function result_with_turn_limit( array $result, array $turn_limit ): array {
$metadata = is_array( $result['metadata'] ?? null ) ? $result['metadata'] : array();
$agents_api = is_array( $metadata['agents_api'] ?? null ) ? $metadata['agents_api'] : array();
$outcome = is_array( $agents_api['run_outcome'] ?? null ) ? $agents_api['run_outcome'] : array();
$turn_count = $this->positive_int( $agents_api['turn_count'] ?? null );
$max_turns = $turn_limit['max_turns'];
$calls = is_array( $agents_api['tool_observability']['calls'] ?? null ) ? $agents_api['tool_observability']['calls'] : array();
$final_turn_tool_calls = 0;
foreach ( $calls as $call ) {
if ( is_array( $call ) && null !== $turn_count && (int) ( $call['turn'] ?? 0 ) === $turn_count ) {
++$final_turn_tool_calls;
}
}
$explicit_stop = 'max_turns' === (string) ( $outcome['stop_reason'] ?? '' );
$cap_exhausted = null !== $max_turns && null !== $turn_count && $turn_count >= $max_turns && $final_turn_tool_calls > 0;
$reached = $explicit_stop || $cap_exhausted;

$result['metadata'] = array_merge(
$metadata,
array(
'turn_limit' => array(
'schema' => 'wp-codebox/agent-turn-limit/v1',
'max_turns' => $max_turns,
'source' => $turn_limit['source'],
'turn_count' => $turn_count,
'final_turn_tool_calls' => $final_turn_tool_calls,
'max_turns_reached' => $reached,
),
)
);
if ( ! $reached ) {
return $result;
}

$diagnostics = is_array( $result['diagnostics'] ?? null ) ? $result['diagnostics'] : array();
$diagnostics[] = array(
'schema' => 'wp-codebox/runtime-package-diagnostic/v1',
'code' => 'max_turns_exceeded',
'message' => null !== $max_turns
? sprintf( 'The agent reached its %d-turn limit before producing a final answer.', $max_turns )
: 'The agent reached its turn limit before producing a final answer.',
'severity' => 'error',
'path' => 'workflow',
);
$result['diagnostics'] = $diagnostics;
$result['success'] = false;
$result['terminal_result'] = array(
'schema' => 'wp-codebox/agent-terminal-result/v1',
'terminal' => true,
'status' => 'max_turns',
'success' => false,
'failure_classification' => 'max_turns',
'max_turns' => array_filter(
array(
'reached' => true,
'current' => $turn_count,
'max' => $max_turns,
),
static fn( mixed $value ): bool => null !== $value
),
);

return $result;
}

private function positive_int( mixed $value ): ?int {
if ( is_int( $value ) || ( is_string( $value ) && ctype_digit( trim( $value ) ) ) || ( is_float( $value ) && floor( $value ) === $value ) ) {
$int = (int) $value;
return $int > 0 ? $int : null;
}

return null;
}

/** @param array<string,mixed> $input @return array<string,mixed> */
private function sandbox_workspace_context( array $input ): array {
$policy = is_array( $input['runner_workspace_policy'] ?? null ) ? $input['runner_workspace_policy'] : array();
Expand Down
Loading
Loading