aiskillstore/marketplace / pending/cagdasyurekli/agy-worker
agy-worker
UnverifiedUse when Codex or Claude Code should delegate repository exploration or implementation to Google Antigravity CLI (agy), then review, verify, repair, and deliver the result.
runtime/agy-worker.sh
View on GitHub#!/usr/bin/env bash
# agy-worker.sh — dispatch a bounded job to agy and return a schema-valid result envelope.
#
# Forked from octo's agy-exec.sh (the prompt-delivery, force-inline and silent-empty
# handling below are its hard-won lessons, not speculation) and extended with the
# structured-output contract Codex needs to act as QA.
#
# VERIFIED ON THIS BOX 2026-08-01 (agy 1.1.9):
# * The prompt is --print's ARGUMENT VALUE. agy ignores stdin in print mode, and
# with --print placed before other flags it reads the NEXT FLAG as the message.
# So --print is built LAST, always.
# * Auth can be intermittent and is not sandbox-dependent. The dispatcher never
# retries it automatically: a caller may explicitly resume or restart instead.
# * Under --sandbox, SHELL commands need an `unsandboxed(<target>)` allow-rule; a
# `command(<name>)` rule alone is NOT enough. But a worker editing files via its
# FILE tools needs neither — a full accept-edits job was verified working with no
# unsandboxed grant. Keep workers off the shell; the driver owns verification.
# * Therefore: exit code 0 proves nothing. Empty stdout is a FAILURE. See classify().
set -euo pipefail
if [[ -n "${AGY_WORKER_TIER:-}" ]]; then
echo "agy-worker.sh: AGY_WORKER_TIER is retired; use --model / AGY_WORKER_MODEL" >&2
exit 64
fi
# Prompts, streams, stderr, and envelopes can contain private repository content.
# Create dispatcher-owned artifacts under a private mask regardless of the caller's
# umask. The local supervisor restores this exact mask only in the agy child, so
# target-file behavior remains caller-controlled without exposing controller state.
CALLER_UMASK="$(umask)"
umask 077
SCRIPT_SOURCE_DIR="${BASH_SOURCE[0]%/*}"
[[ "$SCRIPT_SOURCE_DIR" != "${BASH_SOURCE[0]}" ]] || SCRIPT_SOURCE_DIR=.
SCRIPT_DIR="$(CDPATH= cd -- "$SCRIPT_SOURCE_DIR" && pwd -P)"
if [[ "${1:-}" == transmission-preview || "${1:-}" == preview ]]; then
shift
exec /usr/bin/python3 -I -S -B "$SCRIPT_DIR/scripts/agy_dispatch_worktree.py" transmission-preview "$@"
fi
# agy receives the ergonomic provider schema. The controller restores its only
# optional report arrays before independently validating the canonical schema.
SCHEMA="${AGY_WORKER_SCHEMA:-$SCRIPT_DIR/schemas/worker-result.provider.schema.json}"
LOG_DIR="${AGY_WORKER_LOG_DIR:-$SCRIPT_DIR/logs}"
# Selector values are presence-sensitive. An explicitly empty environment variable
# is not the same as an unset one, and CLI never silently overrides environment.
model_env_seen=0; model_env_value=""
effort_env_seen=0; effort_env_value=""
if [[ -n "${AGY_WORKER_MODEL+x}" ]]; then model_env_seen=1; model_env_value="$AGY_WORKER_MODEL"; fi
if [[ -n "${AGY_WORKER_EFFORT+x}" ]]; then effort_env_seen=1; effort_env_value="$AGY_WORKER_EFFORT"; fi
mode_env_seen=0; mode_env_value=""
if [[ -n "${AGY_WORKER_MODE+x}" ]]; then mode_env_seen=1; mode_env_value="$AGY_WORKER_MODE"; fi
mode="${AGY_WORKER_MODE:-plan}" # plan | accept-edits (rec: plan is the safe default)
idle_timeout="${AGY_WORKER_IDLE_TIMEOUT:-10m}"
hard_timeout="${AGY_WORKER_HARD_TIMEOUT:-2h}"
max_runtime="${AGY_WORKER_MAX_RUNTIME:-12h}"
notice_interval="${AGY_WORKER_NOTICE_INTERVAL:-30m}"
legacy_timeout_seen=0
if [[ -n "${AGY_WORKER_TIMEOUT+x}" ]]; then
legacy_timeout_seen=1
hard_timeout="$AGY_WORKER_TIMEOUT"
fi
job_env_seen=0; job_id=""
if [[ -n "${AGY_WORKER_JOB_ID+x}" ]]; then job_env_seen=1; job_id="$AGY_WORKER_JOB_ID"; fi
dispatch_action="run"
case "${1:-}" in
run|start|status|wait|result|verification-copy|self-verify|extend|cancel|resume|restart|continue|finalize)
dispatch_action="$1"; shift ;;
esac
validate_log_root() {
python3 -B - "$1" <<'PY'
import os
import stat
import sys
try:
metadata = os.lstat(sys.argv[1])
except OSError:
raise SystemExit(1)
mode = stat.S_IMODE(metadata.st_mode)
valid = (
not stat.S_ISLNK(metadata.st_mode)
and stat.S_ISDIR(metadata.st_mode)
and metadata.st_uid == os.geteuid()
and (mode & 0o022) == 0
)
raise SystemExit(0 if valid else 1)
PY
}
project_log_root_is_external() {
python3 -I -S -B - "$1" "$2" <<'PY'
import os
import sys
log_dir, workdir = sys.argv[1:3]
try:
if not log_dir or not workdir or "\0" in log_dir or "\0" in workdir:
raise ValueError
resolved_log = os.path.realpath(log_dir)
resolved_workdir = os.path.realpath(workdir)
if not os.path.isabs(resolved_log) or not os.path.isabs(resolved_workdir):
raise ValueError
if resolved_log == resolved_workdir:
raise ValueError
if os.path.commonpath([resolved_workdir, resolved_log]) == resolved_workdir:
raise ValueError
except (TypeError, UnicodeError, ValueError, OSError):
raise SystemExit(64)
PY
}
usage() {
local usage_exit="${1:-64}"
cat >&2 <<'EOF'
usage: agy-worker.sh [--workdir DIR] [--mode plan|accept-edits]
[--workflow explore|task|project] [--max-cycles N]
[--model MODEL [--effort EFFORT]]
[--idle-timeout 10m] [--hard-timeout 2h]
[--max-runtime 12h] [--notice-interval 30m]
--provider-isolation session|native
[--base-commit IMMUTABLE_GIT_HEAD]
[--provider-env NAME]...
[--provider-scope FILE --approve-transmission-sha SHA256]
[--allow-scoped-repair]
[--self-verification-manifest ABSOLUTE_PRIVATE_FILE]
[--approve-whole-worktree LAUNCH_APPROVAL_SHA256]
--approval-record ABSOLUTE_PRIVATE_PREVIEW_FILE
[--add-dir DIR]... [--allow-slash-commands]
... task prompt on stdin ...
agy-worker.sh start [run options] ... task prompt on stdin ...
agy-worker.sh transmission-preview --workdir ABSOLUTE_DISPOSABLE_WORKTREE --provider-isolation session|native
agy-worker.sh native-keychain-login (one-time agy sign-in into the dedicated native keychain)
agy-worker.sh status|result --job-id JOB [--state WORKFLOW_STATE] [--format json|text]
agy-worker.sh verification-copy --job-id JOB --destination NEW_DIRECTORY_IN_0700_PARENT [--format json|text]
agy-worker.sh self-verify --job-id JOB --approve-state-sha SHA [--format json|text]
agy-worker.sh resume --job-id JOB --approve-state-sha SHA [--format json|text]
agy-worker.sh restart --job-id JOB --approve-state-sha SHA [--format json|text]
agy-worker.sh continue --job-id JOB --approve-state-sha SHA [--format json|text] < driver-verification-input
agy-worker.sh continue --job-id JOB --approve-state-sha SHA --use-self-verification [--format json|text]
agy-worker.sh finalize --job-id JOB --approve-state-sha SHA \
--assurance verified|partially_verified|rejected|blocked [--format json|text] < driver-verification-input
agy-worker.sh wait --job-id JOB --after-state-sha SHA [--timeout 60s] [--format json|text]
agy-worker.sh cancel --job-id JOB --approve-state-sha SHA
agy-worker.sh extend --job-id JOB --approve-state-sha SHA --by 2h
Workflow cycle limits: explore/task 1..2 (default 2); project 1..5 (default 5).
--max-cycles requires an explicit workflow; legacy raw mode remains one attempt.
Every selection runs capability preflight; model and effort are literal caller values.
Stdout contracts: run emits a worker result envelope; start and lifecycle controls emit
control JSON, with status/wait/resume/restart/continue/finalize accepting --format text;
result emits its bound worker envelope unless --format text. A non-zero run exit means
stdout is NOT a valid envelope. Artifacts land in $AGY_WORKER_LOG_DIR.
Exit codes: 0 ok · 2 no prompt · 3 empty output · 4 schema invalid · 5 unclassified agy failure
6 permission gate · 8 capability evidence unavailable
9 idle timeout · 16 hard deadline · 17 provider timeout · 20 status, binding, or verification-copy runtime unavailable · 21 resume failed
22 cancelled · 23 output oversized · 25 provider terminal error
26 model selection failed · 27 native host sandbox or dedicated keychain unavailable
28 source checkout changed · 29 source checkout guard unavailable
64 invalid usage
Advanced controls accept --state WORKFLOW_STATE to resolve the bound dispatch log root.
Resume and restart use the current state approval before any provider call:
agy-worker.sh resume --job-id JOB --approve-state-sha STATE_SHA
agy-worker.sh restart --job-id JOB --approve-state-sha STATE_SHA
EOF
exit "$usage_exit"
}
login_tmp=""
native_keychain_login() {
# Fresh private HOME whose only content is a DefaultKeychain preference naming the
# dedicated keychain, so agy's browser sign-in stores its credential there.
local py="$SCRIPT_DIR/scripts/agy_dispatch_containment.py" rc=0
command -v agy >/dev/null 2>&1 || { echo "agy-worker.sh: agy is not on PATH" >&2; exit 127; }
login_tmp="$(mktemp -d "${TMPDIR:-/tmp}/agy-worker-keychain-login.XXXXXX")" || exit 1
trap 'rm -rf -- "$login_tmp"' EXIT
trap 'exit 130' HUP INT TERM
mkdir "$login_tmp/home" "$login_tmp/cwd"
python3 -I -S -B "$py" keychain-login-home "$login_tmp/home" || exit $?
(cd "$login_tmp/cwd" && exec env HOME="$login_tmp/home" agy -p "Reply with OK") || rc=$?
exit "$rc"
}
if [[ "${1:-}" == native-keychain-login ]]; then
shift
[[ $# -eq 0 ]] || usage
native_keychain_login
fi
if [[ "$dispatch_action" != "run" && "$dispatch_action" != "start" ]]; then
control_job="$job_id"
control_job_seen=0
control_state_sha=""
control_after_sha=""
control_timeout="60s"
control_format="json"
control_by=""
control_assurance=""
control_destination=""
control_state=""
control_use_self_verification_seen=0
while [[ $# -gt 0 ]]; do
case "$1" in
--approve-migration-sha|--approve-migration-sha=*)
echo "agy-worker.sh: --approve-migration-sha was removed after v0.22.0; finish or discard the old job with the release that created it." >&2
exit 64 ;;
--job-id)
[[ $# -ge 2 && $control_job_seen -eq 0 ]] || usage
control_job="$2"; control_job_seen=1; shift 2 ;;
--state)
[[ $# -ge 2 && -z "$control_state" && -n "$2" ]] || usage
control_state="$2"; shift 2 ;;
--approve-state-sha)
[[ $# -ge 2 && -z "$control_state_sha" ]] || usage
control_state_sha="$2"; shift 2 ;;
--after-state-sha)
[[ $# -ge 2 && -z "$control_after_sha" ]] || usage
control_after_sha="$2"; shift 2 ;;
--timeout)
[[ $# -ge 2 && "$control_timeout" == "60s" ]] || usage
control_timeout="$2"; shift 2 ;;
--format)
[[ $# -ge 2 && "$control_format" == "json" ]] || usage
control_format="$2"; shift 2 ;;
--by)
[[ $# -ge 2 && -z "$control_by" ]] || usage
control_by="$2"; shift 2 ;;
--assurance)
[[ $# -ge 2 && -z "$control_assurance" ]] || usage
control_assurance="$2"; shift 2 ;;
--destination)
[[ $# -ge 2 && -z "$control_destination" ]] || usage
control_destination="$2"; shift 2 ;;
--use-self-verification)
(( control_use_self_verification_seen == 0 )) || usage
control_use_self_verification_seen=1; shift ;;
-h|--help) usage 0 ;;
*) echo "agy-worker.sh: invalid usage; run --help for usage" >&2; usage ;;
esac
done
case "$control_job" in
''|.|..|*[!A-Za-z0-9._-]*) echo "agy-worker.sh: invalid job ID" >&2; exit 64 ;;
esac
case "$control_format" in json|text) ;; *) usage ;; esac
if (( control_use_self_verification_seen )) && [[ "$dispatch_action" != "continue" ]]; then
echo "agy-worker.sh: --use-self-verification is valid only with continue" >&2
exit 64
fi
if [[ -n "$control_state" ]]; then
LOG_DIR="$(python3 -I -S -B - "$SCRIPT_DIR/scripts" "$control_state" "$control_job" <<'PY'
import sys
from pathlib import Path
sys.path.insert(0, sys.argv[1])
from workflow import WorkflowError, dispatch_log_root_from_workflow_state
try:
print(dispatch_log_root_from_workflow_state(Path(sys.argv[2]), sys.argv[3]))
except WorkflowError as exc:
print(f"agy-worker.sh: {exc}", file=sys.stderr)
raise SystemExit(64)
PY
)" || exit 64
fi
[[ -d "$LOG_DIR" ]] || { echo "agy-worker.sh: log root is unavailable" >&2; exit 64; }
validate_log_root "$LOG_DIR" || {
echo "agy-worker.sh: log root must be an owner-owned, non-writable real directory" >&2
exit 64
}
LOG_DIR="$(CDPATH= cd -- "$LOG_DIR" 2>/dev/null && pwd -P)" || exit 64
job_dir="$LOG_DIR/$control_job"
supervisor=(python3 -I -S -B "$SCRIPT_DIR/scripts/agy_dispatch.py" "$dispatch_action" --job-dir "$job_dir")
case "$dispatch_action" in status|wait|result|verification-copy|self-verify|resume|restart|continue|finalize) supervisor+=(--format "$control_format") ;; esac
case "$dispatch_action" in
wait)
[[ -n "$control_after_sha" ]] || usage
supervisor+=(--after-state-sha "$control_after_sha" --timeout "$control_timeout") ;;
cancel)
[[ -n "$control_state_sha" ]] || usage
supervisor+=(--approve-state-sha "$control_state_sha") ;;
extend)
[[ -n "$control_state_sha" && -n "$control_by" ]] || usage
supervisor+=(--approve-state-sha "$control_state_sha" --by "$control_by") ;;
restart|continue)
[[ -n "$control_state_sha" ]] || usage
supervisor+=(--approve-state-sha "$control_state_sha")
(( control_use_self_verification_seen == 0 )) || supervisor+=(--use-self-verification) ;;
resume)
# Let the controller read the current safe snapshot so an omitted
# approval can return its exact actionable replacement, not usage.
[[ -z "$control_state_sha" ]] || supervisor+=(--approve-state-sha "$control_state_sha")
;;
finalize)
[[ -n "$control_state_sha" && -n "$control_assurance" ]] || usage
supervisor+=(--approve-state-sha "$control_state_sha" --assurance "$control_assurance")
;;
verification-copy)
[[ -n "$control_destination" ]] || usage
supervisor+=(--destination "$control_destination") ;;
self-verify)
[[ -n "$control_state_sha" ]] || usage
supervisor+=(--approve-state-sha "$control_state_sha") ;;
esac
exec "${supervisor[@]}"
fi
workdir="$PWD"
workflow=""
max_cycles=""
workflow_cli_seen=0; max_cycles_cli_seen=0; mode_cli_seen=0
extra_dirs=()
model_cli_seen=0; model_cli_value=""
effort_cli_seen=0; effort_cli_value=""
idle_cli_seen=0; hard_cli_seen=0; max_cli_seen=0; notice_cli_seen=0
job_cli_seen=0
provider_scope_seen=0; provider_scope=""
approve_transmission_sha_seen=0; approve_transmission_sha=""
approve_whole_worktree_seen=0; approve_whole_worktree=""
allow_scoped_repair_seen=0
self_verification_manifest_seen=0; self_verification_manifest=""
provider_isolation_seen=0; provider_isolation=""
base_commit_seen=0; base_commit=""
provider_env=()
approval_record=""
# Injection control (rec #8): worker prompts routinely embed repo content, and a
# "/skill ..." string inside that content would otherwise expand as a real command.
# Default OFF; only a caller who controls the whole prompt should re-enable it.
disable_slash=1
while [[ $# -gt 0 ]]; do
case "$1" in
--approve-migration-sha|--approve-migration-sha=*)
echo "agy-worker.sh: --approve-migration-sha was removed after v0.22.0; finish or discard the old job with the release that created it." >&2
exit 64 ;;
--workdir) [[ $# -ge 2 ]] || usage; workdir="$2"; shift 2 ;;
--boost|--boost=*|--approve-boost-risk-sha|--approve-boost-risk-sha=*|--persona|--persona=*)
echo "agy-worker.sh: ${1%%=*} was removed after v0.22.0; use the ordinary task workflow." >&2
exit 64 ;;
--mode) [[ $# -ge 2 && $mode_cli_seen -eq 0 ]] || usage; mode_cli_seen=1; mode="$2"; shift 2 ;;
--workflow)
[[ $# -ge 2 && $workflow_cli_seen -eq 0 ]] || usage
workflow_cli_seen=1; workflow="$2"; shift 2 ;;
--max-cycles)
[[ $# -ge 2 && $max_cycles_cli_seen -eq 0 ]] || usage
max_cycles_cli_seen=1; max_cycles="$2"; shift 2 ;;
--model)
[[ $# -ge 2 ]] || usage
(( model_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --model" >&2; exit 64; }
model_cli_seen=1; model_cli_value="$2"; shift 2 ;;
--literal-model|--literal-model=*)
echo "agy-worker.sh: --literal-model is retired; use --model" >&2
exit 64 ;;
--idle-timeout)
[[ $# -ge 2 ]] || usage
(( idle_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --idle-timeout" >&2; exit 64; }
idle_cli_seen=1; idle_timeout="$2"; shift 2 ;;
--hard-timeout)
[[ $# -ge 2 ]] || usage
(( hard_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --hard-timeout" >&2; exit 64; }
hard_cli_seen=1; hard_timeout="$2"; shift 2 ;;
--max-runtime)
[[ $# -ge 2 ]] || usage
(( max_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --max-runtime" >&2; exit 64; }
max_cli_seen=1; max_runtime="$2"; shift 2 ;;
--job-id)
[[ $# -ge 2 ]] || usage
(( job_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --job-id" >&2; exit 64; }
job_cli_seen=1; job_id="$2"; shift 2 ;;
--notice-interval)
[[ $# -ge 2 ]] || usage
(( notice_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --notice-interval" >&2; exit 64; }
notice_cli_seen=1; notice_interval="$2"; shift 2 ;;
--provider-env)
[[ $# -ge 2 ]] || usage
provider_env+=("$2"); shift 2 ;;
--approval-record)
[[ $# -ge 2 && -z "$approval_record" ]] || usage
approval_record="$2"; shift 2 ;;
--provider-isolation)
[[ $# -ge 2 && $provider_isolation_seen -eq 0 ]] || usage
provider_isolation_seen=1; provider_isolation="$2"; shift 2 ;;
--base-commit)
[[ $# -ge 2 && $base_commit_seen -eq 0 ]] || usage
base_commit_seen=1; base_commit="$2"; shift 2 ;;
--effort)
[[ $# -ge 2 ]] || usage
(( effort_cli_seen == 0 )) || { echo "agy-worker.sh: repeated --effort" >&2; exit 64; }
effort_cli_seen=1; effort_cli_value="$2"; shift 2 ;;
--compatibility-disposition|--approve-help-sha)
echo "agy-worker.sh: version-attestation flags are retired; remove them and use capability preflight" >&2
exit 64 ;;
--provider-scope)
[[ $# -ge 2 ]] || usage
(( provider_scope_seen == 0 )) || { echo "agy-worker.sh: repeated --provider-scope" >&2; exit 64; }
provider_scope_seen=1; provider_scope="$2"; shift 2 ;;
--approve-transmission-sha)
[[ $# -ge 2 ]] || usage
(( approve_transmission_sha_seen == 0 )) || { echo "agy-worker.sh: repeated --approve-transmission-sha" >&2; exit 64; }
approve_transmission_sha_seen=1; approve_transmission_sha="$2"; shift 2 ;;
--allow-scoped-repair)
(( allow_scoped_repair_seen == 0 )) || { echo "agy-worker.sh: repeated --allow-scoped-repair" >&2; exit 64; }
allow_scoped_repair_seen=1; shift ;;
--self-verification-manifest)
[[ $# -ge 2 ]] || usage
(( self_verification_manifest_seen == 0 )) || { echo "agy-worker.sh: repeated --self-verification-manifest" >&2; exit 64; }
self_verification_manifest_seen=1; self_verification_manifest="$2"; shift 2 ;;
--approve-whole-worktree)
[[ $# -ge 2 ]] || usage
(( approve_whole_worktree_seen == 0 )) || { echo "agy-worker.sh: repeated --approve-whole-worktree" >&2; exit 64; }
approve_whole_worktree_seen=1; approve_whole_worktree="$2"; shift 2 ;;
--add-dir) [[ $# -ge 2 ]] || usage; extra_dirs+=("$2"); shift 2 ;;
--allow-slash-commands) disable_slash=0; shift ;;
-h|--help) usage 0 ;;
*) echo "agy-worker.sh: invalid usage; run --help for usage" >&2; usage ;;
esac
done
if (( provider_scope_seen && ${#extra_dirs[@]} > 0 )); then
echo "agy-worker.sh: --provider-scope conflicts with --add-dir" >&2
exit 64
fi
if (( provider_isolation_seen == 0 )); then
echo "agy-worker.sh: --provider-isolation session|native is required; session keeps ambient HOME, enabled user plugins, hooks and MCP servers active" >&2
exit 64
fi
case "$provider_isolation" in
session|native) ;;
*) echo "agy-worker.sh: invalid provider isolation: $provider_isolation" >&2; exit 64 ;;
esac
if [[ "$provider_isolation" == "native" && $provider_scope_seen -eq 0 ]]; then
echo "agy-worker.sh: native provider isolation requires --provider-scope" >&2
exit 64
fi
if (( provider_scope_seen && approve_whole_worktree_seen )); then
echo "agy-worker.sh: --provider-scope conflicts with --approve-whole-worktree" >&2
exit 64
fi
if (( provider_scope_seen && approve_transmission_sha_seen == 0 )); then
if [[ "$provider_isolation" == "session" ]]; then
echo "agy-worker.sh: session provider authority is normal same-user filesystem and network access; selected scope is staging and reconciliation, not host confinement" >&2
fi
echo "agy-worker.sh: --provider-scope requires --approve-transmission-sha" >&2
exit 64
fi
if (( provider_scope_seen == 0 && approve_transmission_sha_seen )); then
echo "agy-worker.sh: --approve-transmission-sha requires --provider-scope" >&2
exit 64
fi
if (( approve_transmission_sha_seen )); then
if [[ ! "$approve_transmission_sha" =~ ^[0-9a-f]{64}$ ]]; then
echo "agy-worker.sh: --approve-transmission-sha must be 64 lowercase hex characters" >&2
exit 64
fi
fi
if (( approve_whole_worktree_seen )); then
if [[ ! "$approve_whole_worktree" =~ ^[0-9a-f]{64}$ ]]; then
echo "agy-worker.sh: --approve-whole-worktree must be 64 lowercase hex characters" >&2
exit 64
fi
fi
if (( allow_scoped_repair_seen && provider_scope_seen == 0 )); then
echo "agy-worker.sh: --allow-scoped-repair requires --provider-scope" >&2
exit 64
fi
if (( self_verification_manifest_seen )) && [[ "$self_verification_manifest" != /* ]]; then
echo "agy-worker.sh: --self-verification-manifest requires a canonical absolute path" >&2
exit 64
fi
if (( ${#provider_env[@]} > 64 )); then
echo "agy-worker.sh: at most 64 --provider-env names are supported" >&2
exit 64
fi
if (( ${#provider_env[@]} )); then
for provider_env_name in "${provider_env[@]}"; do
case "$provider_env_name" in
''|*[!A-Za-z0-9_]*|[0-9]*|BASH_ENV|ENV|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE|BASH_LOADABLES_PATH|BASH_XTRACEFD|BASH_COMPAT|NODE_OPTIONS|RUBYOPT|RUBYLIB|PERL5OPT|PERL5LIB|JAVA_TOOL_OPTIONS|JDK_JAVA_OPTIONS|CLASSPATH|BASH_FUNC_*|PYTHON*|LD_*|DYLD_*|AGY_WORKER_INTERNAL_*|AGY_WORKER_SCHEMA|GIT_*)
echo "agy-worker.sh: unsafe --provider-env name" >&2; exit 64 ;;
esac
[[ ${#provider_env_name} -le 128 ]] || {
echo "agy-worker.sh: invalid --provider-env name" >&2; exit 64;
}
provider_env_occurrences=0
for compared_provider_env_name in "${provider_env[@]}"; do
[[ "$provider_env_name" != "$compared_provider_env_name" ]] || \
provider_env_occurrences=$((provider_env_occurrences + 1))
done
(( provider_env_occurrences == 1 )) || {
echo "agy-worker.sh: repeated --provider-env name" >&2; exit 64;
}
done
fi
if (( job_cli_seen == 0 && job_env_seen == 0 )); then
job_id="job-$(python3 -I -S -B - <<'PY'
import secrets
print(secrets.token_hex(16))
PY
)" || { echo "agy-worker.sh: could not generate an opaque job ID" >&2; exit 64; }
fi
if (( legacy_timeout_seen && hard_cli_seen )); then
echo "agy-worker.sh: --hard-timeout conflicts with deprecated AGY_WORKER_TIMEOUT" >&2
exit 64
fi
if (( legacy_timeout_seen )); then
echo "agy-worker.sh: warning: AGY_WORKER_TIMEOUT is deprecated; use --hard-timeout" >&2
fi
(( model_cli_seen == 0 || model_env_seen == 0 )) || {
echo "agy-worker.sh: --model conflicts with AGY_WORKER_MODEL" >&2; exit 64;
}
(( effort_cli_seen == 0 || effort_env_seen == 0 )) || {
echo "agy-worker.sh: --effort conflicts with AGY_WORKER_EFFORT" >&2; exit 64;
}
model_seen=$((model_cli_seen + model_env_seen))
effort_seen=$((effort_cli_seen + effort_env_seen))
if (( effort_seen > 0 && model_seen == 0 )); then
echo "agy-worker.sh: effort requires an explicit base model" >&2
exit 64
fi
if (( model_seen > 0 )); then
if (( model_cli_seen )); then user_model="$model_cli_value"; model_source="cli"
else user_model="$model_env_value"; model_source="environment"; fi
[[ -n "$user_model" ]] || { echo "agy-worker.sh: explicit model must not be empty" >&2; exit 64; }
user_effort=""; effort_source=""
if (( effort_seen > 0 )); then
if (( effort_cli_seen )); then user_effort="$effort_cli_value"; effort_source="cli"
else user_effort="$effort_env_value"; effort_source="environment"; fi
[[ -n "$user_effort" ]] || { echo "agy-worker.sh: explicit effort must not be empty" >&2; exit 64; }
fi
selection_kind="model"
else
selection_kind="agy-default"
fi
case "$workflow" in
''|explore|task|project) ;;
*) echo "agy-worker.sh: invalid workflow: $workflow" >&2; exit 64 ;;
esac
case "$workflow" in
explore)
if (( mode_cli_seen )) && [[ "$mode" != "plan" ]]; then
echo "agy-worker.sh: --workflow explore conflicts with --mode $mode" >&2; exit 64
fi
if (( ! mode_cli_seen && mode_env_seen )) && [[ "$mode_env_value" != "plan" ]]; then
echo "agy-worker.sh: --workflow explore conflicts with AGY_WORKER_MODE" >&2; exit 64
fi
mode="plan" ;;
project)
if (( mode_cli_seen )) && [[ "$mode" != "accept-edits" ]]; then
echo "agy-worker.sh: --workflow project conflicts with --mode $mode" >&2; exit 64
fi
if (( ! mode_cli_seen && mode_env_seen )) && [[ "$mode_env_value" != "accept-edits" ]]; then
echo "agy-worker.sh: --workflow project conflicts with AGY_WORKER_MODE" >&2; exit 64
fi
mode="accept-edits" ;;
task)
if (( ! mode_cli_seen && ! mode_env_seen )); then mode="accept-edits"; fi ;;
esac
case "$workflow" in
explore|task)
if (( max_cycles_cli_seen )); then
[[ "$max_cycles" =~ ^[1-2]$ ]] || { echo "agy-worker.sh: --max-cycles for $workflow must be 1 or 2" >&2; exit 64; }
else max_cycles=2; fi ;;
project)
if (( max_cycles_cli_seen )); then
[[ "$max_cycles" =~ ^[1-5]$ ]] || { echo "agy-worker.sh: --max-cycles for project must be 1 through 5" >&2; exit 64; }
else max_cycles=5; fi ;;
'')
(( ! max_cycles_cli_seen )) || { echo "agy-worker.sh: --max-cycles requires an explicit workflow" >&2; exit 64; }
max_cycles=1 ;;
esac
case "$mode" in
plan|accept-edits) ;;
*) echo "agy-worker.sh: invalid mode: $mode" >&2; exit 64 ;;
esac
if [[ -n "${AGY_WORKER_MAX_ATTEMPTS+x}" && "$AGY_WORKER_MAX_ATTEMPTS" != "1" ]]; then
echo "agy-worker.sh: automatic retries were removed; AGY_WORKER_MAX_ATTEMPTS must be 1" >&2
exit 64
fi
case "$job_id" in
''|.|..|*[!A-Za-z0-9._-]*) echo "agy-worker.sh: invalid AGY_WORKER_JOB_ID: $job_id" >&2; exit 64 ;;
esac
if (( allow_scoped_repair_seen )); then
if [[ "$workflow" != "task" && "$workflow" != "project" ]]; then
echo "agy-worker.sh: --allow-scoped-repair requires task or project workflow" >&2
exit 64
fi
if (( max_cycles < 2 )); then
echo "agy-worker.sh: --allow-scoped-repair requires at least two cycles" >&2
exit 64
fi
fi
if (( self_verification_manifest_seen )); then
if [[ "$workflow" != "task" && "$workflow" != "project" ]]; then
echo "agy-worker.sh: --self-verification-manifest requires task or project workflow" >&2
exit 64
fi
fi
if (( provider_scope_seen && base_commit_seen )); then
echo "agy-worker.sh: --base-commit applies only to whole-worktree dispatch" >&2
exit 64
fi
duration_seconds() {
python3 -I -S -B - "$1" <<'PY'
import re
import sys
match = re.fullmatch(r"([1-9][0-9]*)(s|m|h)", sys.argv[1])
if match is None:
raise SystemExit(64)
factor = {"s": 1, "m": 60, "h": 3600}[match.group(2)]
value = int(match.group(1)) * factor
if value > 7 * 24 * 3600:
raise SystemExit(64)
print(value)
PY
}
idle_seconds="$(duration_seconds "$idle_timeout")" || { echo "agy-worker.sh: invalid idle timeout" >&2; exit 64; }
hard_seconds="$(duration_seconds "$hard_timeout")" || { echo "agy-worker.sh: invalid hard timeout" >&2; exit 64; }
max_seconds="$(duration_seconds "$max_runtime")" || { echo "agy-worker.sh: invalid max runtime" >&2; exit 64; }
notice_seconds="$(duration_seconds "$notice_interval")" || { echo "agy-worker.sh: invalid notice interval" >&2; exit 64; }
if (( idle_seconds > hard_seconds || hard_seconds > max_seconds )); then
echo "agy-worker.sh: require idle-timeout <= hard-timeout <= max-runtime" >&2
exit 64
fi
if [[ "$workflow" == "project" ]]; then
# Resolve the existing worktree and the prospective physical log path before
# mkdir. realpath intentionally follows existing symlink ancestors and
# resolves relative spellings while allowing a missing final log path.
[[ -d "$workdir" ]] || { echo "agy-worker.sh: --workdir not a directory: $workdir" >&2; exit 64; }
prospective_workdir="$(CDPATH= cd -- "$workdir" 2>/dev/null && pwd -P)" || {
echo "agy-worker.sh: --workdir cannot be resolved safely" >&2
exit 64
}
if ! project_log_root_is_external "$LOG_DIR" "$prospective_workdir"; then
echo "agy-worker.sh: project log root cannot be inside the target workdir" >&2
exit 64
fi
fi
mkdir -p "$LOG_DIR" 2>/dev/null || {
echo "agy-worker.sh: log root cannot be created safely" >&2
exit 64
}
if ! validate_log_root "$LOG_DIR"; then
echo "agy-worker.sh: log root must be an owner-owned, non-writable real directory" >&2
exit 64
fi
# agy operates on its CWD as the workspace, so the dispatcher must actually move
# there. LOG_DIR is resolved to an absolute path first: it defaults to a path under
# SCRIPT_DIR, but a caller-supplied relative AGY_WORKER_LOG_DIR would otherwise
# silently follow us into the worktree and scatter artifacts.
if ! LOG_DIR="$(CDPATH= cd -- "$LOG_DIR" 2>/dev/null && pwd -P)"; then
echo "agy-worker.sh: log root cannot be resolved safely" >&2
exit 64
fi
[[ -f "$SCHEMA" ]] || { echo "agy-worker.sh: schema not found: $SCHEMA" >&2; exit 64; }
SCHEMA="$(cd "$(dirname "$SCHEMA")" && pwd)/$(basename "$SCHEMA")"
[[ -d "$workdir" ]] || { echo "agy-worker.sh: --workdir not a directory: $workdir" >&2; exit 64; }
workdir="$(cd "$workdir" && pwd -P)"
normalized_dirs=()
for d in ${extra_dirs+"${extra_dirs[@]}"}; do
[[ -d "$d" ]] || { echo "agy-worker.sh: --add-dir not a directory: $d" >&2; exit 64; }
resolved_dir="$(cd "$d" && pwd -P)"
case "$resolved_dir/" in
"$workdir/"*) normalized_dirs+=("$resolved_dir") ;;
*)
echo "agy-worker.sh: --add-dir must resolve inside the audited --workdir: $d" >&2
exit 64 ;;
esac
done
extra_dirs=()
if (( ${#normalized_dirs[@]} > 0 )); then
extra_dirs=("${normalized_dirs[@]}")
fi
cd "$workdir"
if (( self_verification_manifest_seen )) && ! project_log_root_is_external "$LOG_DIR" "$workdir"; then
echo "agy-worker.sh: self-verification job artifacts must be outside the target workdir" >&2
exit 64
fi
# The record is comparison data; only its human-approved digest grants authority.
if (( provider_scope_seen == 0 && approve_whole_worktree_seen == 0 )); then
echo "agy-worker.sh: choose provider scope, or explicitly approve whole-worktree transmission" >&2
echo "agy-worker.sh: obtain a full transmission-preview with the exact task and launch options" >&2
exit 64
fi
[[ -n "$approval_record" ]] || {
echo "agy-worker.sh: --approval-record is required for full launch authority" >&2
exit 64
}
approved_launch_sha="$approve_whole_worktree"
(( provider_scope_seen == 0 )) || approved_launch_sha="$approve_transmission_sha"
/usr/bin/python3 -I -S -B "$SCRIPT_DIR/scripts/launch_authority.py" \
check-record "$approval_record" "$approved_launch_sha" || exit 64
if [[ "$workflow" == "project" ]]; then
# Repeat the physical containment decision after creation and canonical
# resolution so an observed path race cannot authorize provider execution.
if ! project_log_root_is_external "$LOG_DIR" "$workdir"; then
echo "agy-worker.sh: project log root cannot be inside the target workdir" >&2
exit 64
fi
python3 -I -S -B - "$workdir" <<'PY'
import os
import stat
import sys
root = os.path.realpath(sys.argv[1])
def binding(info):
return (
info.st_dev, info.st_ino, info.st_mode, info.st_nlink,
info.st_uid, info.st_gid, info.st_size, info.st_mtime_ns, info.st_ctime_ns,
)
def marker_only_preflight(root_fd):
nofollow = getattr(os, "O_NOFOLLOW", 0)
directory = getattr(os, "O_DIRECTORY", 0)
seen = 0
def walk(parent_fd, is_root=False):
nonlocal seen
try:
before = os.fstat(parent_fd)
if not stat.S_ISDIR(before.st_mode):
return False
except OSError:
return False
scan_fd = -1
try:
scan_fd = os.dup(parent_fd)
with os.scandir(scan_fd) as entries:
for entry in entries:
raw_name = os.fsencode(entry.name)
if not raw_name or b"\0" in raw_name:
return False
# Directory-entry bytes—not a case-folding pathname
# lookup—decide whether this is a Git authority marker.
if raw_name.lower() == b".git":
if is_root and raw_name == b".git":
continue
return False
seen += 1
if seen > 100000:
return False
try:
info = os.stat(entry.name, dir_fd=parent_fd, follow_symlinks=False)
except OSError:
return False
if not stat.S_ISDIR(info.st_mode):
continue
try:
child_fd = os.open(
entry.name, os.O_RDONLY | directory | nofollow, dir_fd=parent_fd,
)
except OSError:
return False
try:
if binding(os.fstat(child_fd)) != binding(info) or not walk(child_fd):
return False
if binding(os.fstat(child_fd)) != binding(info):
return False
except OSError:
return False
finally:
os.close(child_fd)
except OSError:
return False
finally:
if scan_fd >= 0:
os.close(scan_fd)
try:
return binding(os.fstat(parent_fd)) == binding(before)
except OSError:
return False
return walk(root_fd, is_root=True)
try:
root_fd = os.open(
root, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0),
)
try:
root_info = os.fstat(root_fd)
if (
not stat.S_ISDIR(root_info.st_mode)
or binding(os.lstat(root)) != binding(root_info)
or not marker_only_preflight(root_fd)
):
raise SystemExit(64)
finally:
os.close(root_fd)
except OSError:
raise SystemExit(64)
marker = os.path.join(root, ".git")
try:
marker_info = os.lstat(marker)
except OSError:
raise SystemExit(64)
if (os.path.islink(marker) or not stat.S_ISREG(marker_info.st_mode)
or marker_info.st_uid != os.geteuid() or marker_info.st_size > 4096):
raise SystemExit(64)
pending = [root]
count = 0
while pending:
current = pending.pop()
with os.scandir(current) as entries:
for entry in entries:
raw_name = os.fsencode(entry.name)
if raw_name.lower() == b".git":
# The root marker is the sole authority validated above. A
# nested marker must fail before it can be resolved or read.
if current == root and raw_name == b".git":
continue
raise SystemExit(64)
count += 1
if count > 100000:
raise SystemExit(64)
if entry.is_symlink():
resolved = os.path.realpath(entry.path)
try:
contained = os.path.commonpath([root, resolved]) == root
except ValueError:
contained = False
if not contained:
raise SystemExit(64)
relative = os.path.relpath(resolved, root)
if any(part.lower() == ".git" for part in relative.split(os.sep)):
raise SystemExit(64)
elif entry.is_dir(follow_symlinks=False):
pending.append(entry.path)
PY
boundary_rc=$?
if (( boundary_rc != 0 )); then
echo "agy-worker.sh: project workflow requires a local Git marker and bounded contained paths" >&2
exit 64
fi
fi
# Native isolation uses only the dedicated agy keychain; fail closed before any job
# artifact exists when it is missing or locked (a locked lookup would pop a GUI dialog).
if [[ "$provider_isolation" == "native" ]]; then
keychain_rc=0
python3 -I -S -B "$SCRIPT_DIR/scripts/agy_dispatch_containment.py" keychain-preflight || keychain_rc=$?
(( keychain_rc == 0 )) || exit "$keychain_rc"
fi
job_dir="$LOG_DIR/$job_id"
if ! mkdir "$job_dir" 2>/dev/null; then
echo "agy-worker.sh: job artifact path already exists or cannot be created: $job_id" >&2
exit 64
fi
job_dir_identity="$(python3 -I -S -B - "$job_dir" <<'PY'
import os
import stat
import sys
try:
info = os.lstat(sys.argv[1])
except OSError:
raise SystemExit(1)
if (not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode)
or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700):
raise SystemExit(1)
print(f"{info.st_dev}:{info.st_ino}:{info.st_uid}:{stat.S_IMODE(info.st_mode):o}")
PY
)" || {
echo "agy-worker.sh: job artifact path identity is invalid: $job_id" >&2
exit 64
}
# Capability preflight is pre-task. Remove only the exact empty owner-private
# directory after rejection; preserve replacements and unexpected content.
cleanup_empty_preflight_job() {
python3 -I -S -B - "$job_dir" "$job_dir_identity" <<'PY'
import os
import stat
import sys
path, expected = sys.argv[1:]
try:
info = os.lstat(path)
except OSError:
raise SystemExit(1)
actual = f"{info.st_dev}:{info.st_ino}:{info.st_uid}:{stat.S_IMODE(info.st_mode):o}"
if (actual != expected or not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode)
or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700):
raise SystemExit(1)
try:
os.rmdir(path)
except OSError:
raise SystemExit(1)
PY
}
stdout_file="$job_dir/stream.ndjson"
stderr_file="$job_dir/stderr.txt"
prompt_file="$job_dir/task.txt"
full_prompt_file="$job_dir/full-prompt.txt"
envelope_file="$job_dir/envelope.json"
staged_dir="$job_dir/staged"
staged_prompt_file="$staged_dir/full-prompt.txt"
selection_file="$job_dir/selection.json"
# Resolve once before consuming the task; every selection shares capability checks.
selection_args=(--output "$selection_file" --provider-isolation "$provider_isolation")
child_env_args=()
for provider_env_name in ${provider_env+"${provider_env[@]}"}; do
child_env_args+=(--child-env "$provider_env_name")
done
if (( ${#child_env_args[@]} )); then
selection_args+=("${child_env_args[@]}")
fi
if [[ "$selection_kind" == "model" ]]; then
selection_args+=(--model "$user_model" --model-source "$model_source")
if [[ -n "$user_effort" ]]; then
selection_args+=(--effort "$user_effort" --effort-source "$effort_source")
fi
fi
set +e
model="$(python3 -B "$SCRIPT_DIR/scripts/model_selection.py" "${selection_args[@]}")"
selection_rc=$?
set -e
if (( selection_rc != 0 )); then
cleanup_empty_preflight_job || true
exit "$selection_rc"
fi
# Selection publication has completed the shared capability preflight.
agy_version="$(python3 -I -S -B - "$selection_file" <<'PYCODE'
import json, sys
with open(sys.argv[1], encoding="utf-8") as handle:
print(json.load(handle)["installed_agy_version"])
PYCODE
)"
agy_version_observed=true
self_verification_manifest_file=""
self_verification_prompt_block=""
if (( self_verification_manifest_seen )); then
self_verification_manifest_file="$job_dir/self-verification-manifest.json"
if ! self_verification_prompt_block="$(
python3 -I -S -B - "$SCRIPT_DIR/scripts/agy_dispatch.py" \
"$self_verification_manifest" "$self_verification_manifest_file" \
"$job_dir" "$workdir" <<'PY'
import os
from pathlib import Path
import runpy
import stat
import sys
dispatch_source, source_text, target_text, job_text, worktree_text = sys.argv[1:]
source = Path(source_text)
target = Path(target_text)
job = Path(job_text)
descriptor = -1
created_inode = None
def stable_identity(info):
return (
info.st_dev, info.st_ino, info.st_uid, info.st_gid, info.st_mode,
info.st_nlink, info.st_size, info.st_mtime_ns, info.st_ctime_ns,
)
try:
if not source.is_absolute() or Path(os.path.realpath(source)) != source:
raise ValueError
worktree = Path(os.path.realpath(worktree_text))
if os.path.commonpath((str(worktree), str(source))) == str(worktree):
raise ValueError
job_info = job.lstat()
if (
Path(os.path.realpath(job)) != job
or target.parent != job
or not stat.S_ISDIR(job_info.st_mode)
or stat.S_ISLNK(job_info.st_mode)
or job_info.st_uid != os.getuid()
or stat.S_IMODE(job_info.st_mode) != 0o700
):
raise ValueError
descriptor = os.open(source, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
before = os.fstat(descriptor)
if (
not stat.S_ISREG(before.st_mode)
or before.st_uid != os.getuid()
or stat.S_IMODE(before.st_mode) != 0o600
or before.st_nlink != 1
):
raise ValueError
dispatch = runpy.run_path(dispatch_source, run_name="agy_dispatch_manifest_reader")
verification = dispatch["SELF_VERIFICATION"]
limit = verification.MAX_MANIFEST_BYTES
chunks = []
total = 0
while True:
chunk = os.read(descriptor, min(65536, limit + 1 - total))
if not chunk:
break
chunks.append(chunk)
total += len(chunk)
if total > limit:
raise ValueError
after = os.fstat(descriptor)
os.close(descriptor)
descriptor = -1
named = source.lstat()
if stable_identity(before) != stable_identity(after) or stable_identity(after) != stable_identity(named):
raise ValueError
raw = b"".join(chunks)
manifest = verification.parse_manifest(raw)
verification.validate_runtime(manifest, Path(worktree_text))
descriptor = os.open(
target,
os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
0o600,
)
created = os.fstat(descriptor)
created_inode = (created.st_dev, created.st_ino, created.st_uid)
if not stat.S_ISREG(created.st_mode) or created.st_uid != os.getuid() or created.st_nlink != 1:
raise ValueError
os.fchmod(descriptor, 0o600)
view = memoryview(raw)
while view:
written = os.write(descriptor, view)
if written <= 0:
raise OSError
view = view[written:]
os.fsync(descriptor)
os.close(descriptor)
descriptor = -1
descriptor = os.open(target, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
copied = b""
while len(copied) <= limit:
chunk = os.read(descriptor, min(65536, limit + 1 - len(copied)))
if not chunk:
break
copied += chunk
bound = os.fstat(descriptor)
os.close(descriptor)
descriptor = -1
named_target = target.lstat()
if (
copied != raw
or len(copied) > limit
or stable_identity(bound) != stable_identity(named_target)
or not stat.S_ISREG(bound.st_mode)
or bound.st_uid != os.getuid()
or stat.S_IMODE(bound.st_mode) != 0o600
or bound.st_nlink != 1
):
raise ValueError
parent_descriptor = os.open(job, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
try:
os.fsync(parent_descriptor)
finally:
os.close(parent_descriptor)
required = ", ".join(check.identifier for check in manifest.checks if check.required) or "(none)"
optional = ", ".join(check.identifier for check in manifest.checks if not check.required) or "(none)"
sys.stdout.write(
"DRIVER-OWNED SELF-VERIFICATION CHECK REQUESTS:\n"
f"- Required check IDs, run automatically: {required}\n"
f"- Optional check IDs, request only when useful: {optional}\n"
"- requested_check_ids may contain each optional ID at most once. "
"Check IDs are requests, not commands or execution authority."
)
except Exception:
if descriptor >= 0:
try:
os.close(descriptor)
except OSError:
pass
if created_inode is not None:
try:
info = target.lstat()
if (
stat.S_ISREG(info.st_mode)
and (info.st_dev, info.st_ino, info.st_uid) == created_inode
and info.st_nlink == 1
):
target.unlink()
except OSError:
pass
raise SystemExit(64)
PY
)"; then
echo "agy-worker.sh: self-verification manifest is invalid or unavailable" >&2
exit 64
fi
fi
restore_staged_permissions() {
if [[ -d "$staged_dir" ]]; then
chmod 0700 "$staged_dir" 2>/dev/null || true
[[ ! -f "$staged_prompt_file" ]] || chmod 0600 "$staged_prompt_file" 2>/dev/null || true
fi
}
handle_signal() {
local signal="$1" status="$2"
restore_staged_permissions
trap - "$signal"
kill -s "$signal" "$$"
exit "$status"
}
trap 'restore_staged_permissions' EXIT
trap 'handle_signal HUP 129' HUP
trap 'handle_signal INT 130' INT
trap 'handle_signal TERM 143' TERM
# --- read the task -----------------------------------------------------------
# stdin is consumed once; cache it so a retry can replay it verbatim.
if [[ -t 0 ]]; then
echo "agy-worker.sh: no task on stdin" >&2
exit 2
fi
cat > "$prompt_file"
task="$(<"$prompt_file")"
# $(<file) strips trailing LF bytes; reject whitespace-only tasks before rendering.
if [[ -z "${task//[[:space:]]/}" ]]; then
echo "agy-worker.sh: empty task; refusing to dispatch a promptless worker" >&2
exit 2
fi
# Build the exact reviewed prompt with the same code used by local previews.
if ! /usr/bin/python3 -I -S -B "$SCRIPT_DIR/scripts/launch_authority.py" \
render "$mode" "$provider_isolation" "$self_verification_prompt_block" \
< "$prompt_file" > "$full_prompt_file"; then
echo "agy-worker.sh: task cannot be bound to launch authority" >&2
exit 64
fi
full_prompt="$(<"$full_prompt_file")"
launch_preview_file="$job_dir/launch-preview.json"
launch_preview_args=(transmission-preview --workdir "$workdir"
--provider-isolation "$provider_isolation" --workflow "${workflow:-legacy}"
--mode "$mode" --max-cycles "$max_cycles"
--idle-timeout "${idle_seconds}s" --hard-timeout "${hard_seconds}s"
--max-runtime "${max_seconds}s" --notice-interval "${notice_seconds}s"
--provider-schema "$SCHEMA")
(( provider_scope_seen == 0 )) || launch_preview_args+=(--provider-scope "$provider_scope")
(( allow_scoped_repair_seen == 0 )) || launch_preview_args+=(--allow-scoped-repair)
[[ -z "$self_verification_manifest_file" ]] || \
launch_preview_args+=(--self-verification-manifest "$self_verification_manifest_file")
(( disable_slash )) || launch_preview_args+=(--allow-slash-commands)
(( model_cli_seen == 0 )) || launch_preview_args+=(--model "$model_cli_value")
(( effort_cli_seen == 0 )) || launch_preview_args+=(--effort "$effort_cli_value")
for provider_env_name in ${provider_env+"${provider_env[@]}"}; do
launch_preview_args+=(--provider-env "$provider_env_name")
done
for extra_dir in ${extra_dirs+"${extra_dirs[@]}"}; do
launch_preview_args+=(--add-dir "$extra_dir")
done
/usr/bin/python3 -I -S -B "$SCRIPT_DIR/scripts/agy_dispatch_worktree.py" \
"${launch_preview_args[@]}" < "$prompt_file" > "$launch_preview_file" || exit 64
/usr/bin/python3 -I -S -B "$SCRIPT_DIR/scripts/launch_authority.py" \
match-record "$approval_record" "$approved_launch_sha" "$launch_preview_file" || exit 64
# --- build the command -------------------------------------------------------
build_cmd() {
cmd=(agy)
[[ "$provider_isolation" != "native" ]] || cmd+=(--sandbox)
cmd+=(--mode "$mode" --print-timeout "${max_seconds}s")
cmd+=(--output-format stream-json --json-schema "$SCHEMA")
[[ -n "$model" ]] && cmd+=(--model "$model")
[[ -z "${user_effort:-}" ]] || cmd+=(--effort "$user_effort")
if (( disable_slash )) && [[ "$mode" != "plan" ]]; then
cmd+=(--disable-slash-commands)
fi
for d in ${extra_dirs+"${extra_dirs[@]}"}; do cmd+=(--add-dir "$d"); done
# argv ceiling: MAX_ARG_STRLEN is ~128KiB of BYTES. Oversized prompts get staged
# to the cached file and agy is pointed at it instead of failing the job.
local LC_ALL=C
stage_used=0
if (( provider_scope_seen )) && (( ${#full_prompt} > 100000 )); then
echo "agy-worker.sh: narrow provider scope prompt exceeds the inline bound" >&2
exit 64
fi
if (( provider_scope_seen == 0 )) && { [[ "$mode" == "plan" ]] || (( ${#full_prompt} > 100000 )); }; then
# The automatic out-of-repo root contains only one read-only staged prompt.
# Logs and envelopes remain outside agy's granted roots.
restore_staged_permissions
mkdir -p "$staged_dir"
printf '%s' "$full_prompt" > "$staged_prompt_file"
chmod 0444 "$staged_prompt_file"
chmod 0555 "$staged_dir"
stage_used=1
cmd+=(--add-dir "$staged_dir")
stage_instruction="$(/usr/bin/python3 -I -S -B \
"$SCRIPT_DIR/scripts/launch_authority.py" stage-instruction "$staged_prompt_file")"
cmd+=(--print "$stage_instruction")
else
cmd+=(--print "$full_prompt") # ALWAYS last, prompt as the value
fi
}
# --- hand one frozen command to the common foreground/background supervisor ---
build_cmd
command_file="$job_dir/dispatch-command.json"
stage_dir_arg=""; stage_file_arg=""
if (( stage_used )); then
stage_dir_arg="$staged_dir"; stage_file_arg="$staged_prompt_file"
fi
command_workflow="${workflow:-legacy}"
python3 -I -S -B - "$SCRIPT_DIR/scripts/agy_dispatch.py" "$command_file" "$job_id" "$workdir" "$agy_version" "$agy_version_observed" \
"$idle_seconds" "$hard_seconds" "$max_seconds" "$notice_seconds" \
"$stage_dir_arg" "$stage_file_arg" "$CALLER_UMASK" "$command_workflow" "$max_cycles" \
"${#provider_env[@]}" ${provider_env+"${provider_env[@]}"} "$selection_file" \
"$provider_scope" "$approve_transmission_sha" "$approve_whole_worktree" "$allow_scoped_repair_seen" "$self_verification_manifest_file" "$provider_isolation" "$base_commit" "${cmd[@]}" <<'PY'
import json
import os
from pathlib import Path
import runpy
import sys
(
dispatch_source, output, job_id, workdir, agy_version, agy_version_observed, idle, hard, maximum, notice,
stage_dir, stage_file, child_umask, workflow, max_cycles, provider_env_count, *remainder
) = sys.argv[1:]
dispatch = runpy.run_path(dispatch_source, run_name="agy_dispatch_scope_reader")
provider_env_count = int(provider_env_count)
provider_env = sorted(remainder[:provider_env_count])
selection_path, provider_scope_arg, approved_transmission_sha_arg, approved_whole_worktree_sha_arg, allow_scoped_repair_arg, self_verification_manifest_arg, provider_isolation_arg, base_commit_arg, *argv = remainder[provider_env_count:]
if not isinstance(child_umask, str) or len(child_umask) not in (3, 4) or any(ch not in "01234567" for ch in child_umask):
raise SystemExit(64)
value = {
"schema_version": dispatch["CURRENT_COMMAND_SCHEMA"],
"kind": "agy-worker-dispatch-command",
"job_id": job_id,
"workdir": workdir,
"argv": argv,
"agy_version": agy_version,
"agy_version_observed": agy_version_observed == "true",
"selection_path": selection_path,
"provider_env": provider_env,
"idle_seconds": int(idle),
"hard_seconds": int(hard),
"max_seconds": int(maximum),
"notice_seconds": int(notice),
"stage_dir": stage_dir or None,
"stage_file": stage_file or None,
"child_umask": child_umask,
"workflow": workflow,
"max_cycles": int(max_cycles),
"resume_prompt": (
"Continue the existing bounded task from its retained conversation. "
"Do not repeat completed work. Return only the final schema-valid envelope."
),
"continue_prompt": (
"Read the driver-owned verification feedback from the supplied read-only file. "
"Address the reported issues using file tools, do not run shell commands, and "
"return only the final schema-valid envelope."
),
"provider_scope_path": None,
"provider_scope_sha256": None,
"provider_scope_identity": None,
"approved_transmission_sha256": None,
"approved_whole_worktree_sha256": approved_whole_worktree_sha_arg or None,
"allow_scoped_repair": allow_scoped_repair_arg == "1",
"repair_authority_sha256": None,
"allow_self_verification": bool(self_verification_manifest_arg),
"self_verification_manifest_path": self_verification_manifest_arg or None,
"self_verification_manifest_sha256": None,
"self_verification_manifest_identity": None,
"provider_isolation": provider_isolation_arg,
"base_commit": None,
"whole_worktree_content_sha256": None,
"native_grant_profile": (
"baseline" if provider_isolation_arg == "session"
else dispatch["CONTAINMENT"].NEW_NATIVE_GRANT_PROFILE
),
}
with open(Path(output).parent / "launch-preview.json", "rb") as handle:
launch_preview = json.load(handle)
value["launch_authority"] = launch_preview["launch_authority"]
value["launch_approval_sha256"] = launch_preview["launch_approval_sha256"]
descriptor = os.open(selection_path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
try:
before = os.fstat(descriptor)
if (not __import__("stat").S_ISREG(before.st_mode) or before.st_uid != os.geteuid()
or __import__("stat").S_IMODE(before.st_mode) != 0o600 or before.st_nlink != 1):
raise SystemExit(64)
selection = b""
while len(selection) <= 512 * 1024:
part = os.read(descriptor, 65536)
if not part:
break
selection += part
after = os.fstat(descriptor)
finally:
os.close(descriptor)
named = os.lstat(selection_path)
identity = lambda info: (info.st_dev, info.st_ino, info.st_uid, info.st_gid, __import__("stat").S_IMODE(info.st_mode))
if len(selection) > 512 * 1024 or identity(before) != identity(after) or identity(after) != identity(named):
raise SystemExit(64)
value["selection_sha256"] = __import__("hashlib").sha256(selection).hexdigest()
value["selection_identity"] = list(identity(after))
if provider_scope_arg:
try:
scope_path, sc_data, scope_info = dispatch["_read_provider_scope_file"](
provider_scope_arg, 512 * 1024,
)
except Exception:
raise SystemExit(64)
value["provider_scope_path"] = scope_path
value["provider_scope_sha256"] = __import__("hashlib").sha256(sc_data).hexdigest()
value["provider_scope_identity"] = list(identity(scope_info))
value["approved_transmission_sha256"] = approved_transmission_sha_arg
else:
try:
value["base_commit"] = dispatch["_bound_whole_worktree_base"](
workdir, base_commit_arg or None, workflow,
)
except dispatch["DispatchError"] as exc:
sys.stderr.write(f"agy-worker.sh: whole-worktree Git base binding failed: {exc}\n")
raise SystemExit(64)
try:
content = dispatch["whole_worktree_content_manifest"](workdir)
except Exception:
sys.stderr.write(
"agy-worker.sh: whole-worktree content binding failed its bounded local scan; "
"use --provider-scope for selected content\n"
)
raise SystemExit(20)
value["whole_worktree_content_sha256"] = content["manifest_sha256"]
if self_verification_manifest_arg:
manifest_path = Path(self_verification_manifest_arg)
try:
if (
Path(os.path.realpath(manifest_path)) != manifest_path
or manifest_path.parent != Path(output).parent
):
raise ValueError
manifest_data, manifest_info = dispatch["read_regular"](
manifest_path,
dispatch["SELF_VERIFICATION"].MAX_MANIFEST_BYTES,
"self-verification manifest",
)
manifest = dispatch["SELF_VERIFICATION"].parse_manifest(manifest_data)
dispatch["SELF_VERIFICATION"].validate_runtime(manifest, Path(workdir))
except Exception:
raise SystemExit(64)
value["self_verification_manifest_sha256"] = __import__("hashlib").sha256(manifest_data).hexdigest()
value["self_verification_manifest_identity"] = list(identity(manifest_info))
if value["allow_scoped_repair"]:
value["repair_authority_sha256"] = dispatch["_repair_authority_for_command"](value)
raw = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("ascii") + b"\n"
descriptor = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
try:
os.fchmod(descriptor, 0o600)
os.write(descriptor, raw)
os.fsync(descriptor)
finally:
os.close(descriptor)
PY
# From this point the controller owns staged-file modes and child cleanup.
restore_staged_permissions
trap - EXIT HUP INT TERM
exec python3 -I -S -B "$SCRIPT_DIR/scripts/agy_dispatch.py" \
"$dispatch_action" --job-dir "$job_dir"
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Unverified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |