Mode switches automatically to RTL before setting AUTO (Lua script)

Hi, I’m new to Ardupilot and have some issues with setting new waypoint for plane in LUA script.
I’m using MAV_CMD_NAV_WAYPOINT command to fill mavlink_mission_item_int_t structure
I suggest if vehicle mode is AUTO it means plane should go and reach this newly created waypoint.
But after complete takeoff command and adding waypoint to mission and change mode to auto I’m getting a message RTL and I don’t understand why is such behavior?

My goal is to have a LUA script which can update/add waypoints using some guidance law.
Script in current state is below:

takeoff_mode = 13
auto_mode = 10

local is_init = false
local is_manual = false
local is_auto = false
local waypoint_id = 0

function setup()
  if not arming:is_armed() then
    local try_arm = arming:arm()
    if not try_arm then
      return false
    end
  end
  
  local is_mode_set = vehicle:set_mode(takeoff_mode)
  if not is_mode_set then
    return false
  end
  
  mission:clear()
  return true
end

--main update function
function update()
  if not is_init then
    is_init = setup()
    if not is_init then
      return update, 2000
    end
    gcs:send_text(6, "Initial setup is done")
  end

  if not ahrs:healthy() then
    return update, 500
  end
  
  local dist = ahrs:get_relative_position_NED_home()
  local altitude = -1*dist:z()
  
  if altitude >= 40 then
    --enable auto mode
    if not is_auto then
      local is_auto_mode = vehicle:set_mode(auto_mode)
      if is_auto_mode then
        gcs:send_text(6, "Auto mode is set")
        is_auto = true
      end
    end
    
    local wp_num = mission:num_commands() - 1
    gcs:send_text(6, "num commands " .. tostring(wp_num))
    if wp_num == -1 then
      local item = mavlink_mission_item_int_t()
      local home = ahrs:get_home()
      item:command(16)
      item:x(home:lat())
      item:y(home:lng())
      item:z(home:alt())
    
      local is_item_set = mission:set_item(mission:num_commands(), item)
      gcs:send_text(6, "new waypoint is set - " .. tostring(is_item_set))
    end
    
  end

  return update, 2000
end

return update()

Thanks in advance!