#!/usr/bin/env python3
"""Drive real T3 delegation through its CLI; run a dev server on --home first.
Provider configuration: codex-held uses hold.cjs as binaryPath; give the server
PROOF_GATE=<an empty directory>. Link a second server for --peer runs.
"""
import argparse,json,pathlib,subprocess
p=argparse.ArgumentParser()
p.add_argument('--checkout',required=True);p.add_argument('--home',required=True)
p.add_argument('--project',required=True);p.add_argument('--peer');p.add_argument('--peer-project')
p.add_argument('--thread');p.add_argument('--release-gate')
a=p.parse_args()
linked=bool(a.peer)
name='linked' if linked else 'local'
if a.thread:
 script='release-linked-provider.sh' if linked else 'release-provider.sh'
 gate=pathlib.Path(a.release_gate).resolve()
 pathlib.Path(a.project,script).write_text('#!/bin/sh\ntouch '+__import__('shlex').quote(str(gate/'release'))+'\necho "'+('Linked provider' if linked else 'Provider')+' startup hold released"\n')
 prompt=f'Release the held {"linked " if linked else ""}provider now by running bash ./{script}. Then run sleep 5 to let provider startup finish. Then call task_status exactly once for your existing child. End your turn after this call. Do not wait for completion or summarize the result.'
 cmd=['thread','send',a.thread,prompt]
else:
 scope=f' with environmentId {a.peer}' if linked else ''
 target=f'environmentId {a.peer}, projectId {a.peer_project}, ' if linked else ''
 prompt=f'Call orchestrator_capabilities once{scope}. Then call delegate_task with target {target}providerInstanceId codex-held, model gpt-6-luna, mode async, title Held {name} child, task: Run sleep 60 in the shell, then reply done. After delegate_task returns call task_status exactly once for that task, as explicitly requested for this diagnostic, then end your turn. Do not wait for the child. Do not read files or run commands yourself.'
 cmd=['thread','start',a.project,prompt,'--title',f'{"Linked" if linked else "Local"} startup status','--provider','codex','--model','gpt-6-luna']
subprocess.run(['node','apps/server/src/bin.ts',*cmd,'--base-dir',a.home,'--json'],cwd=a.checkout,check=True)
